Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
notifyExpiredTokens fixes
carlosmonastyrski965084cc0c28
diff --git a/backend/src/services/resource-cleanup/resource-cleanup-queue.ts b/backend/src/services/resource-cleanup/resource-cleanup-queue.tsindex edd6847830..32f180636c 100644--- a/backend/src/services/resource-cleanup/resource-cleanup-queue.ts+++ b/backend/src/services/resource-cleanup/resource-cleanup-queue.ts@@ -22,7 +22,7 @@ type TDailyResourceCleanUpQueueServiceFactoryDep = {secretFolderVersionDAL: Pick<TSecretFolderVersionDALFactory, "pruneExcessVersions">;snapshotDAL: Pick<TSnapshotDALFactory, "pruneExcessSnapshots">;secretSharingDAL: Pick<TSecretSharingDALFactory, "pruneExpiredSharedSecrets" | "pruneExpiredSecretRequests">;- serviceTokenService: Pick<TServiceTokenServiceFactory, "notifyExpiredTokens">;+ serviceTokenService: Pick<TServiceTokenServiceFactory, "notifyExpiringTokens">;queueService: TQueueServiceFactory;};@@ -53,7 +53,7 @@ export const dailyResourceCleanUpQueueServiceFactory = ({await secretVersionDAL.pruneExcessVersions();await secretVersionV2DAL.pruneExcessVersions();await secretFolderVersionDAL.pruneExcessVersions();- await serviceTokenService.notifyExpiredTokens();+ await serviceTokenService.notifyExpiringTokens();logger.info(`${QueueName.DailyResourceCleanUp}: queue task completed`);});diff --git a/backend/src/services/service-token/service-token-dal.ts b/backend/src/services/service-token/service-token-dal.tsindex 660d64a41d..adb2f325a3 100644--- a/backend/src/services/service-token/service-token-dal.ts+++ b/backend/src/services/service-token/service-token-dal.ts@@ -28,51 +28,36 @@ export const serviceTokenDALFactory = (db: TDbClient) => {}};- const findExpiredTokens = async (tx?: Knex, batchSize = 1000) => {+ const findExpiringTokens = async (tx?: Knex, batchSize = 500, offset = 0) => {try {- const allDocs: { name: string; projectName: string; createdByEmail: string; id: string; projectId: string }[] =- [];- let offset = 0;- let hasMoreRecords = true;-- while (hasMoreRecords) {- // eslint-disable-next-line- const batch: { name: string; projectName: string; createdByEmail: string; id: string; projectId: string }[] =- // eslint-disable-next-line no-await-in-loop- await (tx || db.replicaNode())(TableName.ServiceToken)- .leftJoin<TUsers>(- TableName.Users,- `${TableName.Users}.id`,- db.raw(`${TableName.ServiceToken}."createdBy"::uuid`)- )- .join(TableName.Project, `${TableName.Project}.id`, `${TableName.ServiceToken}.projectId`)- .whereRaw(- `${TableName.ServiceToken}."expiresAt" < NOW() + INTERVAL '1 day' AND ${TableName.ServiceToken}."expiryNotificationSent" = false`- )- .whereNotNull(`${TableName.Users}.email`)- .select(- db.ref("id").withSchema(TableName.ServiceToken),- db.ref("name").withSchema(TableName.ServiceToken),- db.ref("projectId").withSchema(TableName.ServiceToken),- db.ref("createdBy").withSchema(TableName.ServiceToken),- db.ref("email").withSchema(TableName.Users).as("createdByEmail"),- db.ref("name").withSchema(TableName.Project).as("projectName")- )- .limit(batchSize)- .offset(offset);-- if (batch.length === 0) {- hasMoreRecords = false;- } else {- allDocs.push(...batch);- offset += batchSize;- }- }-- return allDocs;+ const batch: { name: string; projectName: string; createdByEmail: string; id: string; projectId: string }[] =+ await (tx || db.replicaNode())(TableName.ServiceToken)+ .leftJoin<TUsers>(+ TableName.Users,+ `${TableName.Users}.id`,+ db.raw(`${TableName.ServiceToken}."createdBy"::uuid`)+ )+ .join(TableName.Project, `${TableName.Project}.id`, `${TableName.ServiceToken}.projectId`)+ .whereRaw(+ `${TableName.ServiceToken}."expiresAt" < NOW() + INTERVAL '1 day' AND ${TableName.ServiceToken}."expiryNotificationSent" = false`+ )+ .whereNotNull(`${TableName.Users}.email`)+ .select(+ db.ref("id").withSchema(TableName.ServiceToken),+ db.ref("name").withSchema(TableName.ServiceToken),+ db.ref("projectId").withSchema(TableName.ServiceToken),+ db.ref("createdBy").withSchema(TableName.ServiceToken),+ db.ref("email").withSchema(TableName.Users).as("createdByEmail"),+ db.ref("name").withSchema(TableName.Project).as("projectName")+ )+ .limit(batchSize)+ .offset(offset);++ return batch;} catch (err) {throw new DatabaseError({ error: err, name: "FindExpiredTokens" });}};- return { ...stOrm, findById, findExpiredTokens };++ return { ...stOrm, findById, findExpiringTokens };};diff --git a/backend/src/services/service-token/service-token-service.ts b/backend/src/services/service-token/service-token-service.tsindex 760ad4b79f..bbd306bb52 100644--- a/backend/src/services/service-token/service-token-service.ts+++ b/backend/src/services/service-token/service-token-service.ts@@ -189,31 +189,48 @@ export const serviceTokenServiceFactory = ({return { ...serviceToken, lastUsed: new Date(), orgId: project.orgId };};- const notifyExpiredTokens = async () => {+ const notifyExpiringTokens = async () => {const appCfg = getConfig();+ let processedCount = 0;+ let hasMoreRecords = true;+ let offset = 0;+ const batchSize = 500;++ while (hasMoreRecords) {+ // eslint-disable-next-line no-await-in-loop+ const expiringTokens = await serviceTokenDAL.findExpiringTokens(undefined, batchSize, offset);++ if (expiringTokens.length === 0) {+ hasMoreRecords = false;+ break;+ }++ // eslint-disable-next-line no-await-in-loop+ await Promise.all(+ expiringTokens.map(async (token) => {+ try {+ await smtpService.sendMail({+ recipients: [token.createdByEmail],+ subjectLine: "Service Token Expiry Notice",+ template: SmtpTemplates.ServiceTokenExpired,+ substitutions: {+ tokenName: token.name,+ projectName: token.projectName,+ url: `${appCfg.SITE_URL}/secret-manager/${token.projectId}/access-management?selectedTab=service-tokens`+ }+ });+ await serviceTokenDAL.update({ id: token.id }, { expiryNotificationSent: true });+ } catch (error) {+ logger.error(error, `Failed to send expiration notification for token ${token.id}:`);+ }+ })+ );++ processedCount += expiringTokens.length;+ offset += batchSize;+ }- const expiredTokens = await serviceTokenDAL.findExpiredTokens();- if (expiredTokens.length === 0) return;-- await Promise.all(- expiredTokens.map(async (token) => {- try {- await smtpService.sendMail({- recipients: [token.createdByEmail],- subjectLine: "Your Service Token is about to expire",- template: SmtpTemplates.ServiceTokenExpired,- substitutions: {- tokenName: token.name,- projectName: token.projectName,- url: `${appCfg.SITE_URL}/secret-manager/${token.projectId}/access-management?selectedTab=service-tokens`- }- });- await serviceTokenDAL.update({ id: token.id }, { expiryNotificationSent: true });- } catch (error) {- logger.error(error, `Failed to send expiration notification for token ${token.id}:`);- }- })- );+ return processedCount;};return {@@ -222,6 +239,6 @@ export const serviceTokenServiceFactory = ({getServiceToken,getProjectServiceTokens,fnValidateServiceToken,- notifyExpiredTokens+ notifyExpiringTokens};};diff --git a/backend/src/services/smtp/templates/serviceTokenExpired.handlebars b/backend/src/services/smtp/templates/serviceTokenExpired.handlebarsindex 0b3c63dfb3..199150c051 100644--- a/backend/src/services/smtp/templates/serviceTokenExpired.handlebars+++ b/backend/src/services/smtp/templates/serviceTokenExpired.handlebars@@ -7,10 +7,10 @@</head><body>- <h2>Your Service Token is about to expire</h2>+ <h2>Service Token Expiry Notice</h2><p>Your service token <strong>"{{tokenName}}"</strong> will expire within 24 hours.</p>- <p>This token is currently being on project "{{projectName}}". If this token is still needed for your workflow, please create a new one before it expires.</p>+ <p>This token is currently being used on project "{{projectName}}". If this token is still needed for your workflow, please create a new one before it expires.</p><a href="{{url}}">Create New Token</a>