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-gc69710325672
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 893027a614..ed040baf2c 100644
--- a/backend/src/ee/services/pam-resource/pam-resource-service.ts
+++ b/backend/src/ee/services/pam-resource/pam-resource-service.ts
@@ -1,11 +1,8 @@
import { ForbiddenError, subject } from "@casl/ability";
import { ActionProjectType, OrganizationActionScope, TPamResources } from "@app/db/schemas";
+import { OrgPermissionAppConnectionActions, OrgPermissionSubjects } from "@app/ee/services/permission/org-permission";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
-import {
- OrgPermissionAppConnectionActions,
- OrgPermissionSubjects
-} from "@app/ee/services/permission/org-permission";
import {
ProjectPermissionActions,
ProjectPermissionAppConnectionActions,
@@ -18,10 +15,10 @@ import { PgSqlLock } from "@app/keystore/keystore";
import { DatabaseErrorCode } from "@app/lib/error-codes";
import { BadRequestError, DatabaseError, NotFoundError } from "@app/lib/errors";
import { OrgServiceActor, TProjectPermission } from "@app/lib/types";
-import { TKmsServiceFactory } from "@app/services/kms/kms-service";
-import { KmsDataKey } from "@app/services/kms/kms-types";
import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
+import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+import { KmsDataKey } from "@app/services/kms/kms-types";
import { TResourceMetadataDALFactory } from "@app/services/resource-metadata/resource-metadata-dal";
import { TGatewayV2ServiceFactory } from "../gateway-v2/gateway-v2-service";
@@ -417,18 +414,24 @@ export const pamResourceServiceFactory = ({
const appConnection = await appConnectionDAL.findById(sessionSummaryConfig.connectionId);
if (!appConnection) {
- throw new NotFoundError({ message: `App connection with ID '${sessionSummaryConfig.connectionId}' not found` });
+ throw new NotFoundError({
+ message: `App connection with ID '${sessionSummaryConfig.connectionId}' not found`
+ });
}
if (appConnection.orgId !== actor.orgId) {
- throw new BadRequestError({ message: "App connection does not belong to the same organization as the resource" });
+ throw new BadRequestError({
+ message: "App connection does not belong to the same organization as the resource"
+ });
}
if (!LLM_APP_CONNECTIONS.has(appConnection.app as AppConnection)) {
- throw new BadRequestError({ message: `App connection must be an AI provider connection, got '${appConnection.app}'` });
+ throw new BadRequestError({
+ message: `App connection must be an AI provider connection, got '${appConnection.app}'`
+ });
}
// Check actor has Connect permission on the app connection
if (appConnection.projectId) {
- const { permission } = await permissionService.getProjectPermission({
+ const { permission: appConnectionPermission } = await permissionService.getProjectPermission({
actor: actor.type,
actorId: actor.id,
projectId: appConnection.projectId,
@@ -436,12 +439,12 @@ export const pamResourceServiceFactory = ({
actorOrgId: actor.orgId,
actionProjectType: ActionProjectType.Any
});
- ForbiddenError.from(permission).throwUnlessCan(
+ ForbiddenError.from(appConnectionPermission).throwUnlessCan(
ProjectPermissionAppConnectionActions.Connect,
subject(ProjectPermissionSub.AppConnections, { connectionId: sessionSummaryConfig.connectionId })
);
} else {
- const { permission } = await permissionService.getOrgPermission({
+ const { permission: appConnectionPermission } = await permissionService.getOrgPermission({
actorId: actor.id,
actor: actor.type,
orgId: appConnection.orgId,
@@ -449,7 +452,7 @@ export const pamResourceServiceFactory = ({
actorAuthMethod: actor.authMethod,
scope: OrganizationActionScope.Any
});
- ForbiddenError.from(permission).throwUnlessCan(
+ ForbiddenError.from(appConnectionPermission).throwUnlessCan(
OrgPermissionAppConnectionActions.Connect,
subject(OrgPermissionSubjects.AppConnections, { connectionId: sessionSummaryConfig.connectionId })
);
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 327544d83d..5ca7b5d71b 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
@@ -10,7 +10,12 @@ import { KmsDataKey } from "@app/services/kms/kms-types";
import { TPamSessionDALFactory } from "./pam-session-dal";
import { TPamSessionEventBatchDALFactory } from "./pam-session-event-batch-dal";
import { decryptSessionCommandLogs } from "./pam-session-fns";
-import { MAX_LOG_CHARS, buildSummaryPrompt, formatLogsForSummary, generateSessionSummary } from "./pam-session-summary-fns";
+import {
+ buildSummaryPrompt,
+ formatLogsForSummary,
+ generateSessionSummary,
+ MAX_LOG_CHARS
+} from "./pam-session-summary-fns";
import { TPamSessionCommandLog, TTerminalEvent } from "./pam-session-types";
type TSessionSummaryConfig = {
@@ -59,7 +64,11 @@ export const pamSessionAiSummaryServiceFactory = ({
projectId
});
summaryConfig = JSON.parse(decryptor({ cipherTextBlob: encryptedConfig }).toString()) as TSessionSummaryConfig;
- } catch {
+ } catch (err) {
+ logger.warn(
+ { sessionId, err },
+ `queueAiSummary: failed to decrypt sessionSummaryConfig, skipping [sessionId=${sessionId}]`
+ );
return;
}
@@ -88,7 +97,10 @@ export const pamSessionAiSummaryServiceFactory = ({
// 1. Fetch session
const session = await pamSessionDAL.findById(sessionId);
if (!session) {
- logger.warn({ sessionId }, `${QueueName.PamSessionAiSummary}: session not found, skipping [sessionId=${sessionId}]`);
+ logger.warn(
+ { sessionId },
+ `${QueueName.PamSessionAiSummary}: session not found, skipping [sessionId=${sessionId}]`
+ );
return;
}
@@ -106,7 +118,10 @@ 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 [sessionId=${sessionId}] [resourceId=${resourceId}]`);
+ logger.info(
+ { sessionId, resourceId },
+ `${QueueName.PamSessionAiSummary}: resource not found, skipping [sessionId=${sessionId}] [resourceId=${resourceId}]`
+ );
await pamSessionDAL.updateById(sessionId, { aiInsightsStatus: null });
return;
}
@@ -130,13 +145,19 @@ export const pamSessionAiSummaryServiceFactory = ({
});
summaryConfig = JSON.parse(decryptor({ cipherTextBlob: encryptedConfig }).toString()) as TSessionSummaryConfig;
} catch (err) {
- logger.error({ sessionId, err }, `${QueueName.PamSessionAiSummary}: failed to decrypt sessionSummaryConfig [sessionId=${sessionId}]`);
+ 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}]`);
+ logger.info(
+ { sessionId },
+ `${QueueName.PamSessionAiSummary}: AI insights disabled for resource, skipping [sessionId=${sessionId}]`
+ );
await pamSessionDAL.updateById(sessionId, { aiInsightsStatus: null });
return;
}
@@ -161,7 +182,10 @@ export const pamSessionAiSummaryServiceFactory = ({
});
apiKey = (credentials as { apiKey: string }).apiKey;
} catch (err) {
- logger.error({ sessionId, err }, `${QueueName.PamSessionAiSummary}: failed to decrypt connection credentials [sessionId=${sessionId}]`);
+ 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"
@@ -192,8 +216,20 @@ export const pamSessionAiSummaryServiceFactory = ({
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)[];
+ // 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;
}
@@ -206,7 +242,10 @@ export const pamSessionAiSummaryServiceFactory = ({
} else if (session.encryptedLogsBlob) {
logs = await decryptSessionCommandLogs({ projectId, encryptedLogs: session.encryptedLogsBlob, kmsService });
} else {
- logger.info({ sessionId }, `${QueueName.PamSessionAiSummary}: no session logs, skipping [sessionId=${sessionId}]`);
+ logger.info(
+ { sessionId },
+ `${QueueName.PamSessionAiSummary}: no session logs, skipping [sessionId=${sessionId}]`
+ );
await pamSessionDAL.updateById(sessionId, { aiInsightsStatus: null });
return;
}
@@ -216,7 +255,10 @@ export const pamSessionAiSummaryServiceFactory = ({
return;
}
} catch (err) {
- logger.error({ sessionId, err }, `${QueueName.PamSessionAiSummary}: failed to decrypt session logs [sessionId=${sessionId}]`);
+ 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"
@@ -258,14 +300,20 @@ export const pamSessionAiSummaryServiceFactory = ({
aiInsightsError: null
});
- logger.info({ sessionId }, `${QueueName.PamSessionAiSummary}: AI summary completed successfully [sessionId=${sessionId}]`);
+ 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}]`);
+ 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-service.ts b/backend/src/ee/services/pam-session/pam-session-service.ts
index 91c48cd2b3..d4ada358e6 100644
--- a/backend/src/ee/services/pam-session/pam-session-service.ts
+++ b/backend/src/ee/services/pam-session/pam-session-service.ts
@@ -52,7 +52,13 @@ export const pamSessionServiceFactory = ({
// Only applies to non-gateway sessions (e.g., AWS IAM) - gateway sessions are managed by the gateway
// This is intentionally only called in getById (session details view), not in list
const checkAndExpireSessionIfNeeded = async <
- T extends { id: string; status: string; expiresAt: Date | null; gatewayIdentityId?: string | null }
+ T extends {
+ id: string;
+ status: string;
+ expiresAt: Date | null;
+ gatewayIdentityId?: string | null;
+ projectId?: string | null;
+ }
>(
session: T
): Promise<T> => {
@@ -70,6 +76,13 @@ export const pamSessionServiceFactory = ({
status: PamSessionStatus.Ended,
endedAt: new Date()
});
+ if (session.projectId) {
+ 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")
+ );
+ }
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
return { ...session, ...updatedSession };
}
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 215387e68c..648a3a650a 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,5 +1,5 @@
-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 { TPamSessionDALFactory } from "@app/ee/services/pam-session/pam-session-dal";
import { getConfig } from "@app/lib/config/env";
import { logger } from "@app/lib/logger";
import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
@@ -31,7 +31,10 @@ export const pamSessionExpirationServiceFactory = ({
const session = await pamSessionDAL.findById(sessionId);
const updated = await pamSessionDAL.expireSessionById(sessionId);
if (updated > 0) {
- logger.info({ sessionId }, `${QueueName.PamSessionExpiration}: session expired successfully [sessionId=${sessionId}]`);
+ logger.info(
+ { sessionId },
+ `${QueueName.PamSessionExpiration}: session expired successfully [sessionId=${sessionId}]`
+ );
if (session?.projectId) {
await pamSessionAiSummaryService.queueAiSummary(sessionId, session.projectId);
}
diff --git a/frontend/src/pages/pam/PamResourceByIDPage/components/PamSessionRecordingModal.tsx b/frontend/src/pages/pam/PamResourceByIDPage/components/PamSessionRecordingModal.tsx
index 012bd60e15..23f11296c0 100644
--- a/frontend/src/pages/pam/PamResourceByIDPage/components/PamSessionRecordingModal.tsx
+++ b/frontend/src/pages/pam/PamResourceByIDPage/components/PamSessionRecordingModal.tsx
@@ -73,7 +73,7 @@ export const PamSessionRecordingModal = ({ isOpen, onOpenChange, config, onSave
handleSubmit,
reset,
setValue,
- formState: { isSubmitting }
+ formState: { isSubmitting, dirtyFields }
} = useForm<FormData>({
resolver: zodResolver(formSchema),
defaultValues: {
@@ -99,11 +99,13 @@ export const PamSessionRecordingModal = ({ isOpen, onOpenChange, config, onSave
const selectedProvider = selectedConnection?.app as LlmAppConnection | undefined;
const availableModels = selectedProvider ? LLM_MODELS[selectedProvider] : [];
+ // Only reset the model when the user explicitly changes the connection (field is dirty),
+ // not when connections load async and selectedProvider goes undefined → defined on open.
useEffect(() => {
- if (selectedProvider) {
+ if (selectedProvider && dirtyFields.connectionId) {
setValue("model", DEFAULT_MODEL[selectedProvider], { shouldDirty: true });
}
- }, [selectedProvider, setValue]);
+ }, [selectedProvider, dirtyFields.connectionId, setValue]);
const onSubmit = async (data: FormData) => {
if (!data.aiInsightsEnabled) {