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
fix(pam): address Claude bot review comments — resilience and logging
bernie-gfb4ba781ef18
diff --git a/backend/src/ee/services/pam-session/pam-session-ai-summary-queue.ts b/backend/src/ee/services/pam-session/pam-session-ai-summary-queue.tsindex 5ca7b5d71b..f2e7dfb599 100644--- a/backend/src/ee/services/pam-session/pam-session-ai-summary-queue.ts+++ b/backend/src/ee/services/pam-session/pam-session-ai-summary-queue.ts@@ -94,231 +94,246 @@ export const pamSessionAiSummaryServiceFactory = ({logger.info({ sessionId }, `${QueueName.PamSessionAiSummary}: starting AI summary [sessionId=${sessionId}]`);- // 1. Fetch session- const session = await pamSessionDAL.findById(sessionId);- if (!session) {- logger.warn(- { sessionId },- `${QueueName.PamSessionAiSummary}: session not found, skipping [sessionId=${sessionId}]`- );- return;- }+ try {+ // 1. Fetch session+ const session = await pamSessionDAL.findById(sessionId);+ if (!session) {+ logger.warn(+ { sessionId },+ `${QueueName.PamSessionAiSummary}: session not found, skipping [sessionId=${sessionId}]`+ );+ return;+ }- // 2. Skip if no resourceId (resource was deleted)- const { resourceId } = session;- if (!resourceId) {- logger.info(- { sessionId },- `${QueueName.PamSessionAiSummary}: no resourceId on session (resource deleted?), skipping [sessionId=${sessionId}]`- );- await pamSessionDAL.updateById(sessionId, { aiInsightsStatus: null });- return;- }+ // 2. Skip if no resourceId (resource was deleted)+ const { resourceId } = session;+ if (!resourceId) {+ logger.info(+ { sessionId },+ `${QueueName.PamSessionAiSummary}: no resourceId on session (resource deleted?), skipping [sessionId=${sessionId}]`+ );+ await pamSessionDAL.updateById(sessionId, { aiInsightsStatus: null });+ return;+ }- // 3. Fetch resource and decrypt sessionSummaryConfig- const resource = await pamResourceDAL.findById(resourceId);- if (!resource) {- logger.info(- { sessionId, resourceId },- `${QueueName.PamSessionAiSummary}: resource not found, skipping [sessionId=${sessionId}] [resourceId=${resourceId}]`- );- await pamSessionDAL.updateById(sessionId, { aiInsightsStatus: null });- return;- }+ // 3. Fetch resource and decrypt sessionSummaryConfig+ const resource = await pamResourceDAL.findById(resourceId);+ if (!resource) {+ logger.info(+ { sessionId, resourceId },+ `${QueueName.PamSessionAiSummary}: resource not found, skipping [sessionId=${sessionId}] [resourceId=${resourceId}]`+ );+ await pamSessionDAL.updateById(sessionId, { aiInsightsStatus: null });+ return;+ }- const { encryptedSessionSummaryConfig: encryptedConfig } = resource;+ const { encryptedSessionSummaryConfig: encryptedConfig } = resource;- if (!encryptedConfig) {- logger.info(- { sessionId, resourceId },- `${QueueName.PamSessionAiSummary}: no sessionSummaryConfig on resource, skipping [sessionId=${sessionId}] [resourceId=${resourceId}]`- );- await pamSessionDAL.updateById(sessionId, { aiInsightsStatus: null });- return;- }+ if (!encryptedConfig) {+ logger.info(+ { sessionId, resourceId },+ `${QueueName.PamSessionAiSummary}: no sessionSummaryConfig on resource, skipping [sessionId=${sessionId}] [resourceId=${resourceId}]`+ );+ await pamSessionDAL.updateById(sessionId, { aiInsightsStatus: null });+ return;+ }- let summaryConfig: TSessionSummaryConfig;- try {- const { decryptor } = await kmsService.createCipherPairWithDataKey({- type: KmsDataKey.SecretManager,- projectId- });- summaryConfig = JSON.parse(decryptor({ cipherTextBlob: encryptedConfig }).toString()) as TSessionSummaryConfig;- } catch (err) {- logger.error(- { sessionId, err },- `${QueueName.PamSessionAiSummary}: failed to decrypt sessionSummaryConfig [sessionId=${sessionId}]`- );- await pamSessionDAL.updateById(sessionId, { aiInsightsStatus: null });- return;- }+ let summaryConfig: TSessionSummaryConfig;+ try {+ const { decryptor } = await kmsService.createCipherPairWithDataKey({+ type: KmsDataKey.SecretManager,+ projectId+ });+ summaryConfig = JSON.parse(decryptor({ cipherTextBlob: encryptedConfig }).toString()) as TSessionSummaryConfig;+ } catch (err) {+ logger.error(+ { sessionId, err },+ `${QueueName.PamSessionAiSummary}: failed to decrypt sessionSummaryConfig [sessionId=${sessionId}]`+ );+ await pamSessionDAL.updateById(sessionId, { aiInsightsStatus: null });+ return;+ }- if (!summaryConfig.aiInsightsEnabled) {- logger.info(- { sessionId },- `${QueueName.PamSessionAiSummary}: AI insights disabled for resource, skipping [sessionId=${sessionId}]`- );- await pamSessionDAL.updateById(sessionId, { aiInsightsStatus: null });- return;- }+ if (!summaryConfig.aiInsightsEnabled) {+ logger.info(+ { sessionId },+ `${QueueName.PamSessionAiSummary}: AI insights disabled for resource, skipping [sessionId=${sessionId}]`+ );+ await pamSessionDAL.updateById(sessionId, { aiInsightsStatus: null });+ return;+ }- // 4. Fetch app connection and decrypt credentials- const appConnection = await appConnectionDAL.findById(summaryConfig.connectionId);- if (!appConnection) {- await pamSessionDAL.updateById(sessionId, {- aiInsightsStatus: "failed",- aiInsightsError: "Configured AI app connection not found"- });- return;- }+ // 4. Fetch app connection and decrypt credentials+ const appConnection = await appConnectionDAL.findById(summaryConfig.connectionId);+ if (!appConnection) {+ await pamSessionDAL.updateById(sessionId, {+ aiInsightsStatus: "failed",+ aiInsightsError: "Configured AI app connection not found"+ });+ return;+ }- let apiKey: string;- try {- const credentials = await decryptAppConnectionCredentials({- orgId: appConnection.orgId,- encryptedCredentials: appConnection.encryptedCredentials,- kmsService,- projectId: appConnection.projectId- });- apiKey = (credentials as { apiKey: string }).apiKey;- } catch (err) {- logger.error(- { sessionId, err },- `${QueueName.PamSessionAiSummary}: failed to decrypt connection credentials [sessionId=${sessionId}]`- );- await pamSessionDAL.updateById(sessionId, {- aiInsightsStatus: "failed",- aiInsightsError: "Failed to decrypt AI connection credentials"- });- return;- }+ let apiKey: string;+ try {+ const credentials = await decryptAppConnectionCredentials({+ orgId: appConnection.orgId,+ encryptedCredentials: appConnection.encryptedCredentials,+ kmsService,+ projectId: appConnection.projectId+ });+ apiKey = (credentials as { apiKey: string }).apiKey;+ } catch (err) {+ logger.error(+ { sessionId, err },+ `${QueueName.PamSessionAiSummary}: failed to decrypt connection credentials [sessionId=${sessionId}]`+ );+ await pamSessionDAL.updateById(sessionId, {+ aiInsightsStatus: "failed",+ aiInsightsError: "Failed to decrypt AI connection credentials"+ });+ return;+ }- // 5. Decrypt session logs — batch table first (new), fall back to legacy blob.- // Stop decrypting once accumulated content exceeds MAX_LOG_CHARS — there is no point- // loading more data than formatLogsForSummary will use, and this bounds memory usage- // to the content budget rather than an arbitrary batch count.- let logs;- try {- const PAGE_SIZE = 20;- let offset = 0;- let contentChars = 0;- const accumulatedLogs: (TPamSessionCommandLog | TTerminalEvent)[] = [];- let hasMoreBatches = true;-- const { decryptor } = await kmsService.createCipherPairWithDataKey({- type: KmsDataKey.SecretManager,- projectId- });-- while (hasMoreBatches && contentChars < MAX_LOG_CHARS) {- // eslint-disable-next-line no-await-in-loop- const page = await pamSessionEventBatchDAL.findBySessionIdPaginated(sessionId, { offset, limit: PAGE_SIZE });- if (page.length === 0) break;- for (const batch of page) {- const plain = decryptor({ cipherTextBlob: batch.encryptedEventsBlob });- const batchEvents = JSON.parse(plain.toString()) as (TPamSessionCommandLog | TTerminalEvent)[];- // For SSH, only input events are used by formatLogsForSummary — count only those bytes- // to avoid premature truncation from output/resize/error events that are discarded.- // For Postgres, every event is a command log so count all of them.- const isSsh = resource.resourceType === PamResource.SSH;- for (const event of batchEvents) {- if (isSsh) {- const termEvent = event as TTerminalEvent;- if (termEvent.eventType === "input") contentChars += termEvent.data?.length ?? 0;- } else {- const cmdLog = event as TPamSessionCommandLog;- contentChars += (cmdLog.input?.length ?? 0) + (cmdLog.output?.length ?? 0);+ // 5. Decrypt session logs — batch table first (new), fall back to legacy blob.+ // Stop decrypting once accumulated content exceeds MAX_LOG_CHARS — there is no point+ // loading more data than formatLogsForSummary will use, and this bounds memory usage+ // to the content budget rather than an arbitrary batch count.+ let logs;+ try {+ const PAGE_SIZE = 20;+ let offset = 0;+ let contentChars = 0;+ const accumulatedLogs: (TPamSessionCommandLog | TTerminalEvent)[] = [];+ let hasMoreBatches = true;++ const { decryptor } = await kmsService.createCipherPairWithDataKey({+ type: KmsDataKey.SecretManager,+ projectId+ });++ while (hasMoreBatches && contentChars < MAX_LOG_CHARS) {+ // eslint-disable-next-line no-await-in-loop+ const page = await pamSessionEventBatchDAL.findBySessionIdPaginated(sessionId, { offset, limit: PAGE_SIZE });+ if (page.length === 0) break;+ for (const batch of page) {+ const plain = decryptor({ cipherTextBlob: batch.encryptedEventsBlob });+ const batchEvents = JSON.parse(plain.toString()) as (TPamSessionCommandLog | TTerminalEvent)[];+ // For SSH, only input events are used by formatLogsForSummary — count only those bytes+ // to avoid premature truncation from output/resize/error events that are discarded.+ // For Postgres, every event is a command log so count all of them.+ const isSsh = resource.resourceType === PamResource.SSH;+ for (const event of batchEvents) {+ if (isSsh) {+ const termEvent = event as TTerminalEvent;+ if (termEvent.eventType === "input") contentChars += termEvent.data?.length ?? 0;+ } else {+ const cmdLog = event as TPamSessionCommandLog;+ contentChars += (cmdLog.input?.length ?? 0) + (cmdLog.output?.length ?? 0);+ }}+ accumulatedLogs.push(...batchEvents);+ if (contentChars >= MAX_LOG_CHARS) break;}- accumulatedLogs.push(...batchEvents);- if (contentChars >= MAX_LOG_CHARS) break;+ if (page.length < PAGE_SIZE) hasMoreBatches = false;+ offset += PAGE_SIZE;+ }++ if (accumulatedLogs.length > 0) {+ logs = accumulatedLogs;+ } else if (session.encryptedLogsBlob) {+ logs = await decryptSessionCommandLogs({ projectId, encryptedLogs: session.encryptedLogsBlob, kmsService });+ } else {+ logger.info(+ { sessionId },+ `${QueueName.PamSessionAiSummary}: no session logs, skipping [sessionId=${sessionId}]`+ );+ await pamSessionDAL.updateById(sessionId, { aiInsightsStatus: null });+ return;+ }++ if (logs.length === 0) {+ await pamSessionDAL.updateById(sessionId, { aiInsightsStatus: null });+ return;}- if (page.length < PAGE_SIZE) hasMoreBatches = false;- offset += PAGE_SIZE;+ } catch (err) {+ logger.error(+ { sessionId, err },+ `${QueueName.PamSessionAiSummary}: failed to decrypt session logs [sessionId=${sessionId}]`+ );+ await pamSessionDAL.updateById(sessionId, {+ aiInsightsStatus: "failed",+ aiInsightsError: "Failed to decrypt session logs"+ });+ return;}- if (accumulatedLogs.length > 0) {- logs = accumulatedLogs;- } else if (session.encryptedLogsBlob) {- logs = await decryptSessionCommandLogs({ projectId, encryptedLogs: session.encryptedLogsBlob, kmsService });- } else {+ // 6. Format logs, build prompt, and generate summary+ try {+ const resourceType = resource.resourceType as PamResource;+ const durationSeconds = session.endedAt+ ? (new Date(session.endedAt).getTime() - new Date(session.createdAt).getTime()) / 1000+ : 0;++ const formattedLogs = formatLogsForSummary(logs, resourceType);+ const { system, user } = buildSummaryPrompt({+ resourceType,+ resourceName: resource.name,+ actorName: session.actorName,+ actorEmail: session.actorEmail,+ durationSeconds,+ formattedLogs+ });++ const { summary, warnings } = await generateSessionSummary(apiKey, summaryConfig.model, system, user);++ const { encryptor } = await kmsService.createCipherPairWithDataKey({+ type: KmsDataKey.SecretManager,+ projectId+ });++ const { cipherTextBlob: encryptedAiInsights } = encryptor({+ plainText: Buffer.from(JSON.stringify({ summary, warnings }))+ });++ await pamSessionDAL.updateById(sessionId, {+ encryptedAiInsights,+ aiInsightsStatus: "completed",+ aiInsightsError: null+ });+logger.info({ sessionId },- `${QueueName.PamSessionAiSummary}: no session logs, skipping [sessionId=${sessionId}]`+ `${QueueName.PamSessionAiSummary}: AI summary completed successfully [sessionId=${sessionId}]`+ );+ } catch (err) {+ const message =+ err instanceof Error && err.message.length < 500+ ? err.message+ : "AI summarization failed. The session logs may be too large for the selected model.";++ logger.error(+ { sessionId, err },+ `${QueueName.PamSessionAiSummary}: AI summarization failed [sessionId=${sessionId}]`);- await pamSessionDAL.updateById(sessionId, { aiInsightsStatus: null });- return;- }- if (logs.length === 0) {- await pamSessionDAL.updateById(sessionId, { aiInsightsStatus: null });- return;+ await pamSessionDAL.updateById(sessionId, {+ aiInsightsStatus: "failed",+ aiInsightsError: message+ });}} catch (err) {logger.error({ sessionId, err },- `${QueueName.PamSessionAiSummary}: failed to decrypt session logs [sessionId=${sessionId}]`+ `${QueueName.PamSessionAiSummary}: unexpected worker error [sessionId=${sessionId}]`);- await pamSessionDAL.updateById(sessionId, {- aiInsightsStatus: "failed",- aiInsightsError: "Failed to decrypt session logs"- });- return;- }-- // 6. Format logs, build prompt, and generate summary- try {- const resourceType = resource.resourceType as PamResource;- const durationSeconds = session.endedAt- ? (new Date(session.endedAt).getTime() - new Date(session.createdAt).getTime()) / 1000- : 0;-- const formattedLogs = formatLogsForSummary(logs, resourceType);- const { system, user } = buildSummaryPrompt({- resourceType,- resourceName: resource.name,- actorName: session.actorName,- actorEmail: session.actorEmail,- durationSeconds,- formattedLogs- });-- const { summary, warnings } = await generateSessionSummary(apiKey, summaryConfig.model, system, user);-- const { encryptor } = await kmsService.createCipherPairWithDataKey({- type: KmsDataKey.SecretManager,- projectId- });-- const { cipherTextBlob: encryptedAiInsights } = encryptor({- plainText: Buffer.from(JSON.stringify({ summary, warnings }))- });-- await pamSessionDAL.updateById(sessionId, {- encryptedAiInsights,- aiInsightsStatus: "completed",- aiInsightsError: null- });-- logger.info(- { sessionId },- `${QueueName.PamSessionAiSummary}: AI summary completed successfully [sessionId=${sessionId}]`- );- } catch (err) {- const message =- err instanceof Error && err.message.length < 500- ? err.message- : "AI summarization failed. The session logs may be too large for the selected model.";-- logger.error(- { sessionId, err },- `${QueueName.PamSessionAiSummary}: AI summarization failed [sessionId=${sessionId}]`- );-- await pamSessionDAL.updateById(sessionId, {- aiInsightsStatus: "failed",- aiInsightsError: message- });+ try {+ await pamSessionDAL.updateById(sessionId, {+ aiInsightsStatus: "failed",+ aiInsightsError: "Unexpected error during AI summarization"+ });+ } catch {+ // best-effort status reset+ }}});};diff --git a/backend/src/ee/services/pam-session/pam-session-service.ts b/backend/src/ee/services/pam-session/pam-session-service.tsindex d4ada358e6..158ff6df18 100644--- a/backend/src/ee/services/pam-session/pam-session-service.ts+++ b/backend/src/ee/services/pam-session/pam-session-service.ts@@ -80,7 +80,10 @@ export const pamSessionServiceFactory = ({void pamSessionAiSummaryService.queueAiSummary(session.id, session.projectId).catch((err: unknown) =>- logger.error({ sessionId: session.id, err }, "Failed to queue AI summary for inline-expired session")+ logger.error(+ { sessionId: session.id, err },+ `Failed to queue AI summary for inline-expired session [sessionId=${session.id}]`+ ));}// eslint-disable-next-line @typescript-eslint/no-unsafe-argument@@ -233,7 +236,7 @@ export const pamSessionServiceFactory = ({try {await pamSessionAiSummaryService.queueAiSummary(sessionId, project.id);} catch (err) {- logger.error({ sessionId, err }, "Failed to queue AI summary for ended session");+ logger.error({ sessionId, err }, `Failed to queue AI summary for ended session [sessionId=${sessionId}]`);}})();@@ -272,7 +275,7 @@ export const pamSessionServiceFactory = ({try {await pamSessionAiSummaryService.queueAiSummary(sessionId, project.id);} catch (err) {- logger.error({ sessionId, err }, "Failed to queue AI summary for terminated session");+ logger.error({ sessionId, err }, `Failed to queue AI summary for terminated session [sessionId=${sessionId}]`);}})();diff --git a/backend/src/services/pam-session-expiration/pam-session-expiration-queue.ts b/backend/src/services/pam-session-expiration/pam-session-expiration-queue.tsindex 648a3a650a..5db32b1f57 100644--- a/backend/src/services/pam-session-expiration/pam-session-expiration-queue.ts+++ b/backend/src/services/pam-session-expiration/pam-session-expiration-queue.ts@@ -36,7 +36,14 @@ export const pamSessionExpirationServiceFactory = ({`${QueueName.PamSessionExpiration}: session expired successfully [sessionId=${sessionId}]`);if (session?.projectId) {- await pamSessionAiSummaryService.queueAiSummary(sessionId, session.projectId);+ void pamSessionAiSummaryService+ .queueAiSummary(sessionId, session.projectId)+ .catch((err: unknown) =>+ logger.error(+ { sessionId, err },+ `${QueueName.PamSessionExpiration}: failed to queue AI summary [sessionId=${sessionId}]`+ )+ );}} else {logger.info(