Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion actions/check-product-changes/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ const { StateManager } = require('../lib/state');
const { ObservabilityClient } = require('../lib/observability');
const { getRuntimeConfig } = require('../lib/runtimeConfig');
const { handleActionError } = require('../lib/errorHandler');
const { checkAndAlertTokenExpiration } = require('../lib/tokenExpirationMonitor');

/**
* Entry point for the "Product changes check" action.
Expand Down Expand Up @@ -63,6 +64,9 @@ async function main(params) {
// Mark job as running with TTL to avoid permanent lock on unexpected failures
await stateMgr.put('running', 'true', { ttl: 3600 });

// Check API key expiration once per day
Copy link
Collaborator

@jkf276 jkf276 Sep 25, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

does it make sense to have the token expiration as a separate action instead of tacking it on to the check-product-change action? this also eliminate the need to use the state mgr to keep track of when the last time the expiration check was performed.

await checkAndAlertTokenExpiration(cfg.adminAuthToken, stateMgr, observabilityClient, logger);

// Core logic
activationResult = await poll(cfg, { stateLib: stateMgr, filesLib }, logger);
} finally {
Expand Down Expand Up @@ -96,4 +100,4 @@ async function main(params) {
}
}

exports.main = main
exports.main = main;
122 changes: 69 additions & 53 deletions actions/lib/observability.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
class ObservabilityClient {
constructor(nativeLogger, options = {}) {
this.activationId = process.env.__OW_ACTIVATION_ID;
this.namespace = process.env.__OW_NAMESPACE;
this.instanceStartTime = Date.now();
this.options = options;
this.org = options.org;
this.site = options.site;
this.endpoint = options.endpoint;
this.nativeLogger = nativeLogger;
this.activationId = process.env.__OW_ACTIVATION_ID;
this.namespace = process.env.__OW_NAMESPACE;
this.instanceStartTime = Date.now();
this.options = options;
this.org = options.org;
this.site = options.site;
this.endpoint = options.endpoint;
this.nativeLogger = nativeLogger;
}

getEndpoints(type) {
Expand All @@ -19,68 +19,84 @@ class ObservabilityClient {
}

async #sendRequestToObservability(type, payload) {
try {
const logEndpoint = this.getEndpoints(type);
if (logEndpoint) {
await fetch(logEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.options.token}`,
try {
const logEndpoint = this.getEndpoints(type);

if (logEndpoint) {
await fetch(logEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.options.token}`,
},
body: JSON.stringify(payload),
});
}
} catch (error) {
this.nativeLogger.debug(`[ObservabilityClient] Failed to send to observability endpoint '${type}': ${error.message}`, { error });
body: JSON.stringify(payload),
});
}
} catch (error) {
this.nativeLogger.debug(`[ObservabilityClient] Failed to send to observability endpoint '${type}': ${error.message}`, { error });
}
}

severityMap = {
'DEBUG': 1,
'VERBOSE': 2,
'INFO': 3,
'WARNING': 4,
'ERROR': 5,
'CRITICAL': 6,
}
severityMap = {
'DEBUG': 1,
'VERBOSE': 2,
'INFO': 3,
'WARNING': 4,
'ERROR': 5,
'CRITICAL': 6,
}

stateToSeverity(state) {
const stateToSeverityMap = {
skipped: 'DEBUG',
completed: 'INFO',
failure: 'ERROR',
};
stateToSeverity(state) {
const stateToSeverityMap = {
skipped: 'DEBUG',
completed: 'INFO',
failure: 'ERROR',
};

return this.severityMap[stateToSeverityMap[state]] || this.severityMap['DEBUG'];
}
return this.severityMap[stateToSeverityMap[state]] || this.severityMap['DEBUG'];
}

/**
* Sends a single activation log entry to the observability endpoint.
* @param {object} result The JSON object representing the activation log.
* @returns {Promise<void>} A promise that resolves when the log is sent, or rejects on error.
*/
async sendActivationResult(result) {
if (!result || typeof result !== 'object') {
return;
}
if (!result || typeof result !== 'object') {
return;
}

let severity = this.stateToSeverity(result.state);
let severity = this.stateToSeverity(result.state);

if (result?.status?.failed > 0) {
severity = this.severityMap['WARNING'];
}
if (result?.status?.failed > 0) {
severity = this.severityMap['WARNING'];
}

const payload = {
environment: `${this.namespace}`,
timestamp: this.instanceStartTime,
result,
severity,
activationId: this.activationId,
};

await this.#sendRequestToObservability('activationResults', payload);
}

const payload = {
environment: `${this.namespace}`,
timestamp: this.instanceStartTime,
result,
severity,
activationId: this.activationId,
};
async sendApiKeyAlert(alertData) {
const payload = {
environment: this.namespace || 'local-test',
timestamp: Date.now(),
result: {
type: 'api_key_expiration_alert',
daysUntilExpiration: alertData.daysUntilExpiration,
message: alertData.message,
recommendedAction: alertData.recommendedAction
},
activationId: this.activationId || `token-alert-${Date.now()}`
};

await this.#sendRequestToObservability('activationResults', payload);
await this.#sendRequestToObservability('activationResults', payload);
}
}

Expand Down
56 changes: 56 additions & 0 deletions actions/lib/tokenExpirationMonitor.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/*
Copyright 2025 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under
the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/

const { checkTokenExpiration } = require('./tokenValidator');

/**
* Check API key expiration and send alerts if needed
* @param {string} token - The API token to check
* @param {Object} stateMgr - State manager for tracking last check
* @param {Object} observabilityClient - Client for sending alerts
* @param {Object} logger - Logger instance
*/
async function checkAndAlertTokenExpiration(token, stateMgr, observabilityClient, logger) {
const alertThresholdDays = 30; // Alert when token expires in 30 days or less
const checkIntervalMs = 24 * 60 * 60 * 1000; // 24 hours

const lastTokenCheck = await stateMgr.get('lastTokenCheck');
const now = new Date();
const intervalAgo = new Date(now.getTime() - checkIntervalMs);

if (!lastTokenCheck || new Date(lastTokenCheck.value) < intervalAgo) {
const tokenInfo = checkTokenExpiration(token);
if (tokenInfo.isValid) {
const { daysUntilExpiration } = tokenInfo;

if (daysUntilExpiration < alertThresholdDays) {

const message = `AEM Admin API key expires in ${daysUntilExpiration} days`;

try {
await observabilityClient.sendApiKeyAlert({
daysUntilExpiration,
message,
recommendedAction: 'Contact AEM project lead to generate new API key'
});
} catch (alertErr) {
logger.warn('Failed to send API key expiration alert.', alertErr);
}
}
}
await stateMgr.put('lastTokenCheck', now.toISOString());
}
}

module.exports = {
checkAndAlertTokenExpiration
};
Loading
Loading