Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

fix(pam): address Claude bot review comments — resilience, correctness, and logging

bernie-g9ca0dfdc8e3d
diff --git a/backend/src/ee/services/pam-resource/pam-resource-fns.ts b/backend/src/ee/services/pam-resource/pam-resource-fns.ts
index 057d7db61e..0d4d8a57af 100644
--- a/backend/src/ee/services/pam-resource/pam-resource-fns.ts
+++ b/backend/src/ee/services/pam-resource/pam-resource-fns.ts
@@ -126,15 +126,19 @@ export const decryptResource = async (
const { encryptedSessionSummaryConfig } = resource;
if (encryptedSessionSummaryConfig) {
- const { decryptor } = await kmsService.createCipherPairWithDataKey({
- type: KmsDataKey.SecretManager,
- projectId
- });
- sessionSummaryConfig = JSON.parse(decryptor({ cipherTextBlob: encryptedSessionSummaryConfig }).toString()) as {
- aiInsightsEnabled: boolean;
- connectionId: string;
- model: string;
- };
+ try {
+ const { decryptor } = await kmsService.createCipherPairWithDataKey({
+ type: KmsDataKey.SecretManager,
+ projectId
+ });
+ sessionSummaryConfig = JSON.parse(decryptor({ cipherTextBlob: encryptedSessionSummaryConfig }).toString()) as {
+ aiInsightsEnabled: boolean;
+ connectionId: string;
+ model: string;
+ };
+ } catch {
+ // Session summary config is non-essential — fall back to null on KMS failure or corrupted blob
+ }
}
return {
diff --git a/backend/src/ee/services/pam-resource/pam-resource-schemas.ts b/backend/src/ee/services/pam-resource/pam-resource-schemas.ts
index bb1bf713b8..648dd57933 100644
--- a/backend/src/ee/services/pam-resource/pam-resource-schemas.ts
+++ b/backend/src/ee/services/pam-resource/pam-resource-schemas.ts
@@ -20,7 +20,7 @@ export const GatewayAccessResponseSchema = z.object({
export const SessionSummaryConfigSchema = z
.object({
aiInsightsEnabled: z.boolean(),
- connectionId: z.string(),
+ connectionId: z.string().uuid(),
model: z.string()
})
.nullable()
diff --git a/backend/src/ee/services/pam-resource/pam-resource-service.ts b/backend/src/ee/services/pam-resource/pam-resource-service.ts
index 485990a04a..893027a614 100644
--- a/backend/src/ee/services/pam-resource/pam-resource-service.ts
+++ b/backend/src/ee/services/pam-resource/pam-resource-service.ts
@@ -47,6 +47,9 @@ import { TWindowsResource } from "./windows-server/windows-server-resource-types
// Extend this set as more LLM providers are added (e.g. AppConnection.OpenAI)
const LLM_APP_CONNECTIONS = new Set<AppConnection>([AppConnection.Anthropic]);
+// Resource types that have AI session summary prompts defined in pam-session-summary-fns.ts
+const AI_SUMMARY_SUPPORTED_RESOURCE_TYPES = new Set<PamResource>([PamResource.Postgres, PamResource.SSH]);
+
type TPamResourceServiceFactoryDep = {
pamResourceDAL: TPamResourceDALFactory;
pamResourceFavoriteDAL: TPamResourceFavoriteDALFactory;
@@ -406,6 +409,12 @@ export const pamResourceServiceFactory = ({
if (sessionSummaryConfig === null) {
updateDoc.encryptedSessionSummaryConfig = null;
} else {
+ if (!AI_SUMMARY_SUPPORTED_RESOURCE_TYPES.has(resource.resourceType as PamResource)) {
+ throw new BadRequestError({
+ message: `AI session summaries are not supported for resource type '${resource.resourceType}'`
+ });
+ }
+
const appConnection = await appConnectionDAL.findById(sessionSummaryConfig.connectionId);
if (!appConnection) {
throw new NotFoundError({ message: `App connection with ID '${sessionSummaryConfig.connectionId}' not found` });
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.ts
index 3acfff389b..327544d83d 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
@@ -83,12 +83,12 @@ export const pamSessionAiSummaryServiceFactory = ({
queueService.start(QueueName.PamSessionAiSummary, async (job) => {
const { sessionId, projectId } = job.data;
- logger.info({ sessionId }, `${QueueName.PamSessionAiSummary}: starting AI summary`);
+ 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`);
+ logger.warn({ sessionId }, `${QueueName.PamSessionAiSummary}: session not found, skipping [sessionId=${sessionId}]`);
return;
}
@@ -97,7 +97,7 @@ export const pamSessionAiSummaryServiceFactory = ({
if (!resourceId) {
logger.info(
{ sessionId },
- `${QueueName.PamSessionAiSummary}: no resourceId on session (resource deleted?), skipping`
+ `${QueueName.PamSessionAiSummary}: no resourceId on session (resource deleted?), skipping [sessionId=${sessionId}]`
);
await pamSessionDAL.updateById(sessionId, { aiInsightsStatus: null });
return;
@@ -106,7 +106,7 @@ export const pamSessionAiSummaryServiceFactory = ({
// 3. Fetch resource and decrypt sessionSummaryConfig
const resource = await pamResourceDAL.findById(resourceId);
if (!resource) {
- logger.info({ sessionId, resourceId }, `${QueueName.PamSessionAiSummary}: resource not found, skipping`);
+ logger.info({ sessionId, resourceId }, `${QueueName.PamSessionAiSummary}: resource not found, skipping [sessionId=${sessionId}] [resourceId=${resourceId}]`);
await pamSessionDAL.updateById(sessionId, { aiInsightsStatus: null });
return;
}
@@ -116,7 +116,7 @@ export const pamSessionAiSummaryServiceFactory = ({
if (!encryptedConfig) {
logger.info(
{ sessionId, resourceId },
- `${QueueName.PamSessionAiSummary}: no sessionSummaryConfig on resource, skipping`
+ `${QueueName.PamSessionAiSummary}: no sessionSummaryConfig on resource, skipping [sessionId=${sessionId}] [resourceId=${resourceId}]`
);
await pamSessionDAL.updateById(sessionId, { aiInsightsStatus: null });
return;
@@ -130,13 +130,13 @@ export const pamSessionAiSummaryServiceFactory = ({
});
summaryConfig = JSON.parse(decryptor({ cipherTextBlob: encryptedConfig }).toString()) as TSessionSummaryConfig;
} catch (err) {
- logger.error({ sessionId, err }, `${QueueName.PamSessionAiSummary}: failed to decrypt sessionSummaryConfig`);
+ 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`);
+ logger.info({ sessionId }, `${QueueName.PamSessionAiSummary}: AI insights disabled for resource, skipping [sessionId=${sessionId}]`);
await pamSessionDAL.updateById(sessionId, { aiInsightsStatus: null });
return;
}
@@ -161,7 +161,7 @@ export const pamSessionAiSummaryServiceFactory = ({
});
apiKey = (credentials as { apiKey: string }).apiKey;
} catch (err) {
- logger.error({ sessionId, err }, `${QueueName.PamSessionAiSummary}: failed to decrypt connection credentials`);
+ 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"
@@ -174,44 +174,53 @@ export const pamSessionAiSummaryServiceFactory = ({
// loading more data than formatLogsForSummary will use, and this bounds memory usage
// to the content budget rather than an arbitrary batch count.
let logs;
- const PAGE_SIZE = 20;
- let offset = 0;
- let contentChars = 0;
- const accumulatedLogs: (TPamSessionCommandLog | TTerminalEvent)[] = [];
- let hasMoreBatches = true;
+ 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
- });
+ 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 });
- contentChars += plain.length;
- const batchEvents = JSON.parse(plain.toString()) as (TPamSessionCommandLog | TTerminalEvent)[];
- accumulatedLogs.push(...batchEvents);
- if (contentChars >= MAX_LOG_CHARS) break;
+ 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 });
+ contentChars += plain.length;
+ const batchEvents = JSON.parse(plain.toString()) as (TPamSessionCommandLog | TTerminalEvent)[];
+ accumulatedLogs.push(...batchEvents);
+ if (contentChars >= MAX_LOG_CHARS) break;
+ }
+ if (page.length < PAGE_SIZE) hasMoreBatches = false;
+ offset += PAGE_SIZE;
}
- 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`);
- await pamSessionDAL.updateById(sessionId, { aiInsightsStatus: null });
- return;
- }
+ 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 });
+ if (logs.length === 0) {
+ await pamSessionDAL.updateById(sessionId, { aiInsightsStatus: null });
+ return;
+ }
+ } 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;
}
@@ -249,14 +258,14 @@ export const pamSessionAiSummaryServiceFactory = ({
aiInsightsError: null
});
- logger.info({ sessionId }, `${QueueName.PamSessionAiSummary}: AI summary completed successfully`);
+ 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`);
+ logger.error({ sessionId, err }, `${QueueName.PamSessionAiSummary}: AI summarization failed [sessionId=${sessionId}]`);
await pamSessionDAL.updateById(sessionId, {
aiInsightsStatus: "failed",
diff --git a/backend/src/ee/services/pam-session/pam-session-fns.ts b/backend/src/ee/services/pam-session/pam-session-fns.ts
index a636d481bc..f66f84bd3a 100644
--- a/backend/src/ee/services/pam-session/pam-session-fns.ts
+++ b/backend/src/ee/services/pam-session/pam-session-fns.ts
@@ -53,14 +53,18 @@ export const decryptSession = async (
let aiInsights: { summary: string; warnings: { text: string; logIndex?: number }[] } | null = null;
if (encryptedAiInsights) {
- const { decryptor } = await kmsService.createCipherPairWithDataKey({
- type: KmsDataKey.SecretManager,
- projectId
- });
- aiInsights = JSON.parse(decryptor({ cipherTextBlob: encryptedAiInsights }).toString()) as {
- summary: string;
- warnings: { text: string; logIndex?: number }[];
- };
+ try {
+ const { decryptor } = await kmsService.createCipherPairWithDataKey({
+ type: KmsDataKey.SecretManager,
+ projectId
+ });
+ aiInsights = JSON.parse(decryptor({ cipherTextBlob: encryptedAiInsights }).toString()) as {
+ summary: string;
+ warnings: { text: string; logIndex?: number }[];
+ };
+ } catch {
+ // AI insights are non-essential — fall back to null on KMS failure or corrupted blob
+ }
}
return {
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 3791d3c42b..aed8fb7da7 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -2838,9 +2838,19 @@ export const registerRoutes = async (
totpService
});
+ const pamSessionAiSummaryService = pamSessionAiSummaryServiceFactory({
+ queueService,
+ pamSessionDAL,
+ pamSessionEventBatchDAL,
+ pamResourceDAL,
+ appConnectionDAL,
+ kmsService
+ });
+
const pamSessionExpirationService = pamSessionExpirationServiceFactory({
queueService,
- pamSessionDAL
+ pamSessionDAL,
+ pamSessionAiSummaryService
});
const pamAccountService = pamAccountServiceFactory({
@@ -2870,15 +2880,6 @@ export const registerRoutes = async (
pamAccountService
});
- const pamSessionAiSummaryService = pamSessionAiSummaryServiceFactory({
- queueService,
- pamSessionDAL,
- pamSessionEventBatchDAL,
- pamResourceDAL,
- appConnectionDAL,
- kmsService
- });
-
const pamSessionService = pamSessionServiceFactory({
pamSessionDAL,
pamSessionEventBatchDAL,
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.ts
index ab6192e50a..215387e68c 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
@@ -1,18 +1,21 @@
import { TPamSessionDALFactory } from "@app/ee/services/pam-session/pam-session-dal";
+import { TPamSessionAiSummaryServiceFactory } from "@app/ee/services/pam-session/pam-session-ai-summary-queue";
import { getConfig } from "@app/lib/config/env";
import { logger } from "@app/lib/logger";
import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
type TPamSessionExpirationServiceFactoryDep = {
queueService: TQueueServiceFactory;
- pamSessionDAL: Pick<TPamSessionDALFactory, "expireSessionById">;
+ pamSessionDAL: Pick<TPamSessionDALFactory, "expireSessionById" | "findById">;
+ pamSessionAiSummaryService: Pick<TPamSessionAiSummaryServiceFactory, "queueAiSummary">;
};
export type TPamSessionExpirationServiceFactory = ReturnType<typeof pamSessionExpirationServiceFactory>;
export const pamSessionExpirationServiceFactory = ({
queueService,
- pamSessionDAL
+ pamSessionDAL,
+ pamSessionAiSummaryService
}: TPamSessionExpirationServiceFactoryDep) => {
const appCfg = getConfig();
@@ -24,18 +27,22 @@ export const pamSessionExpirationServiceFactory = ({
queueService.start(QueueName.PamSessionExpiration, async (job) => {
const { sessionId } = job.data;
try {
- logger.info({ sessionId }, `${QueueName.PamSessionExpiration}: expiring session`);
+ logger.info({ sessionId }, `${QueueName.PamSessionExpiration}: expiring session [sessionId=${sessionId}]`);
+ const session = await pamSessionDAL.findById(sessionId);
const updated = await pamSessionDAL.expireSessionById(sessionId);
if (updated > 0) {
- logger.info({ sessionId }, `${QueueName.PamSessionExpiration}: session expired successfully`);
+ logger.info({ sessionId }, `${QueueName.PamSessionExpiration}: session expired successfully [sessionId=${sessionId}]`);
+ if (session?.projectId) {
+ await pamSessionAiSummaryService.queueAiSummary(sessionId, session.projectId);
+ }
} else {
logger.info(
{ sessionId },
- `${QueueName.PamSessionExpiration}: session not expired (already ended or not found)`
+ `${QueueName.PamSessionExpiration}: session not expired (already ended or not found) [sessionId=${sessionId}]`
);
}
} catch (error) {
- logger.error(error, `${QueueName.PamSessionExpiration}: failed to expire session ${sessionId}`);
+ logger.error(error, `${QueueName.PamSessionExpiration}: failed to expire session [sessionId=${sessionId}]`);
throw error;
}
});