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
Address PR comments
Carlos Monastyrskibbd5eea90631
diff --git a/backend/src/ee/services/pam-account-rotation/pam-account-rotation-service.test.ts b/backend/src/ee/services/pam-account-rotation/pam-account-rotation-service.test.tsnew file mode 100644index 0000000000..5e5679e674--- /dev/null+++ b/backend/src/ee/services/pam-account-rotation/pam-account-rotation-service.test.ts@@ -0,0 +1,187 @@+import { beforeAll, describe, expect, test, vi } from "vitest";++import { crypto } from "@app/lib/crypto/cryptography";++import { PamAccountType } from "../pam/pam-enums";+import { pamAccountRotationServiceFactory, ROTATION_STATUS } from "./pam-account-rotation-service";+import { PAM_ROTATION_FACTORY_MAP, TPamRotationHandler } from "./pam-rotation-handlers";++vi.mock("@app/lib/logger", () => ({+ logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn(), debug: vi.fn() }+}));++// The KMS cipher is faked as identity, so a "blob" is just the JSON buffer and encrypt/decrypt round-trip in-memory.+const blobOf = (data: Record<string, unknown>) => Buffer.from(JSON.stringify(data));++const connectionDetails = {+ host: "db.internal",+ port: 5432,+ database: "app",+ sslEnabled: false,+ sslRejectUnauthorized: false+};++const CURRENT_PASSWORD = "current-pw";+const PENDING_PASSWORD = "pending-pw";++// A self-rotating Postgres account with a staged pending credential, so every run enters the recovery-probe branch.+const buildAccount = () => ({+ id: "acc-1",+ projectId: "proj-1",+ accountType: PamAccountType.Postgres,+ rotationAccountId: "acc-1",+ credentialConfigured: true,+ name: "target",+ encryptedCredentials: blobOf({ username: "app", password: CURRENT_PASSWORD }),+ encryptedConnectionDetails: blobOf(connectionDetails),+ encryptedPendingCredentials: blobOf({ username: "app", password: PENDING_PASSWORD }),+ templateSettings: { rotation: { enabled: true, intervalSeconds: 3600 } },+ templateGatewayId: null,+ templateGatewayPoolId: null,+ gatewayId: null,+ gatewayPoolId: null+});++// Builds the service with a fake handler whose testCredential verdict is driven per-password by `passwordWorks`.+// A `rotator` override enables the delegated path: findById(WithDetails) resolves it by id, everything else the target.+const buildService = (+ passwordWorks: (password: string) => boolean,+ opts: { account?: ReturnType<typeof buildAccount>; rotator?: Record<string, unknown> } = {}+) => {+ const updateById = vi.fn(async () => undefined);+ const account = opts.account ?? buildAccount();+ const { rotator } = opts;+ const resolve = async (id: string) => (rotator && id === rotator.id ? rotator : account);++ const applyPasswordChange = vi.fn<(input: unknown) => Promise<void>>(async () => undefined);+ const testCredential = vi.fn(async ({ auth }: { auth: { password: string } }) => passwordWorks(auth.password));+ const handler: TPamRotationHandler = { validateTarget: vi.fn(), applyPasswordChange, testCredential };+ const rotationHandlers: typeof PAM_ROTATION_FACTORY_MAP = {+ [PamAccountType.Postgres]: handler,+ [PamAccountType.MySQL]: handler,+ [PamAccountType.MsSQL]: handler+ };++ const identityCipher = {+ encryptor: ({ plainText }: { plainText: Buffer }) => ({ cipherTextBlob: plainText }),+ decryptor: ({ cipherTextBlob }: { cipherTextBlob: Buffer }) => cipherTextBlob+ };++ const deps = {+ pamAccountDAL: {+ findById: vi.fn(resolve),+ findByIdWithDetails: vi.fn(resolve),+ updateById,+ findRotationCandidates: vi.fn(),+ reconcileRotationScheduleForAccount: vi.fn(),+ transaction: vi.fn()+ },+ permissionService: { getProjectPermission: vi.fn(), getResourcePermission: vi.fn() },+ membershipDAL: { findResourceMembershipsForActor: vi.fn() },+ membershipRoleDAL: { find: vi.fn() },+ kmsService: { createCipherPairWithDataKey: vi.fn(async () => identityCipher) },+ keyStore: { acquireLock: vi.fn(async () => ({ release: vi.fn(async () => undefined) })) },+ gatewayService: { fnGetGatewayClientTlsByGatewayId: vi.fn() },+ gatewayV2Service: { getPlatformConnectionDetailsByGatewayId: vi.fn() },+ gatewayPoolService: { resolveEffectiveGatewayId: vi.fn() },+ rotationHandlers+ };++ const service = pamAccountRotationServiceFactory(+ deps as unknown as Parameters<typeof pamAccountRotationServiceFactory>[0]+ );+ return { service, updateById, applyPasswordChange, testCredential };+};++describe("rotateScheduledAccount recovery probe", () => {+ beforeAll(async () => {+ await crypto.initialize({} as never, {} as never, {} as never);+ });++ test("promotes the pending credential when it authenticates, without re-applying", async () => {+ const { service, updateById, applyPasswordChange } = buildService((password) => password === PENDING_PASSWORD);++ const result = await service.rotateScheduledAccount("acc-1");++ expect(result?.rotationStatus).toBe(ROTATION_STATUS.Success);+ expect(applyPasswordChange).not.toHaveBeenCalled();+ // markRotated writes the pending blob as the live credential and clears the staged one.+ expect(updateById).toHaveBeenCalledWith(+ "acc-1",+ expect.objectContaining({+ encryptedCredentials: blobOf({ username: "app", password: PENDING_PASSWORD }),+ encryptedPendingCredentials: null,+ rotationStatus: ROTATION_STATUS.Success+ })+ );+ });++ test("defers when neither the pending nor the current credential authenticates", async () => {+ const { service, applyPasswordChange } = buildService(() => false);++ const result = await service.rotateScheduledAccount("acc-1");++ expect(result?.rotationStatus).toBe(ROTATION_STATUS.Failed);+ expect(result?.message).toContain("deferred");+ expect(applyPasswordChange).not.toHaveBeenCalled();+ });++ test("clears the stale pending credential and proceeds to rotate when the current one still works", async () => {+ // Pending fails, current (and the freshly-generated password) succeed.+ const { service, applyPasswordChange } = buildService((password) => password !== PENDING_PASSWORD);++ const result = await service.rotateScheduledAccount("acc-1");++ expect(result?.rotationStatus).toBe(ROTATION_STATUS.Success);+ expect(applyPasswordChange).toHaveBeenCalledTimes(1);+ });++ test("delegated target with no stored current password falls through instead of deferring, and applies over the rotator's own connection", async () => {+ // Delegated target: no stored current password, so the "neither works" defer is skipped (the rotator re-sets).+ const account = {+ ...buildAccount(),+ rotationAccountId: "rot-1",+ credentialConfigured: false,+ encryptedCredentials: blobOf({ username: "app" })+ };+ const rotator = {+ id: "rot-1",+ projectId: "proj-1",+ accountType: PamAccountType.Postgres,+ encryptedCredentials: blobOf({ username: "rotuser", password: "rot-pw" }),+ encryptedConnectionDetails: blobOf({+ host: "db.internal",+ port: 5432,+ database: "rotdb",+ sslEnabled: false,+ sslRejectUnauthorized: false+ }),+ gatewayId: "gw-rot",+ gatewayPoolId: null,+ templateGatewayId: null,+ templateGatewayPoolId: null+ };+ // Pending fails; the freshly-generated password verifies.+ const { service, applyPasswordChange } = buildService((password) => password !== PENDING_PASSWORD, {+ account,+ rotator+ });++ const result = await service.rotateScheduledAccount("acc-1");++ expect(result?.rotationStatus).toBe(ROTATION_STATUS.Success);+ // The apply must run over the ROTATOR's own database and gateway, authenticating as the rotator.+ expect(applyPasswordChange).toHaveBeenCalledTimes(1);+ const applyArgs = applyPasswordChange.mock.calls[0]?.[0] as {+ connectionDetails: { database: string };+ gatewayId?: string | null;+ auth: { username: string };+ targetUsername: string;+ };+ expect(applyArgs.connectionDetails.database).toBe("rotdb");+ expect(applyArgs.gatewayId).toBe("gw-rot");+ expect(applyArgs.auth.username).toBe("rotuser");+ // ...but the target's own username is what gets altered.+ expect(applyArgs.targetUsername).toBe("app");+ });+});diff --git a/backend/src/ee/services/pam-account-rotation/pam-account-rotation-service.ts b/backend/src/ee/services/pam-account-rotation/pam-account-rotation-service.tsindex da8c2fc40d..4dcbe2b6ff 100644--- a/backend/src/ee/services/pam-account-rotation/pam-account-rotation-service.ts+++ b/backend/src/ee/services/pam-account-rotation/pam-account-rotation-service.ts@@ -63,6 +63,7 @@ type TPamAccountRotationServiceFactoryDep = {gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">;gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;+ rotationHandlers?: typeof PAM_ROTATION_FACTORY_MAP;};export type TPamAccountRotationServiceFactory = ReturnType<typeof pamAccountRotationServiceFactory>;@@ -77,7 +78,8 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServickeyStore,gatewayService,gatewayV2Service,- gatewayPoolService+ gatewayPoolService,+ rotationHandlers = PAM_ROTATION_FACTORY_MAP} = deps;const gatewayDeps = { gatewayService, gatewayV2Service, gatewayPoolService };@@ -140,20 +142,31 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServicraw: Record<string, unknown>): TPamSqlConnectionDetails => validateConnectionDetails(accountType, raw) as TPamSqlConnectionDetails;- const resolveAuthCredential = async (+ const resolveRotator = async (account: TPamAccountDetail,- targetCredentials: TSqlAccountCredentials- ): Promise<{ username: string; password: string }> => {+ targetCredentials: TSqlAccountCredentials,+ targetConnectionDetails: TPamSqlConnectionDetails,+ targetGateway: { gatewayId?: string | null; gatewayPoolId?: string | null }+ ): Promise<{+ auth: { username: string; password: string };+ connectionDetails: TPamSqlConnectionDetails;+ gatewayId?: string | null;+ gatewayPoolId?: string | null;+ }> => {const projectId = account.projectId as string;if (account.rotationAccountId === account.id) {if (!targetCredentials.password) {throw new BadRequestError({ message: "Account has no stored password to self-rotate" });}- return { username: targetCredentials.username, password: targetCredentials.password };+ return {+ auth: { username: targetCredentials.username, password: targetCredentials.password },+ connectionDetails: targetConnectionDetails,+ ...targetGateway+ };}- const rotator = await pamAccountDAL.findById(account.rotationAccountId as string);+ const rotator = await pamAccountDAL.findByIdWithDetails(account.rotationAccountId as string);if (!rotator || rotator.projectId !== projectId) {throw new BadRequestError({ message: "Rotation account no longer exists" });}@@ -166,7 +179,16 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServicif (!rotatorCredentials.password) {throw new BadRequestError({ message: "Rotation account has no stored password" });}- return { username: rotatorCredentials.username, password: rotatorCredentials.password };+ const rotatorConnectionDetails = toSqlConnectionDetails(+ account.accountType as PamAccountType,+ await decrypt(projectId, rotator.encryptedConnectionDetails)+ );+ return {+ auth: { username: rotatorCredentials.username, password: rotatorCredentials.password },+ connectionDetails: rotatorConnectionDetails,+ gatewayId: rotator.gatewayId ?? rotator.templateGatewayId,+ gatewayPoolId: rotator.gatewayPoolId ?? rotator.templateGatewayPoolId+ };};const rotateWithinLock = async (account: TPamAccountDetail) => {@@ -182,7 +204,7 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServicconst targetCredentials = await decryptSqlCredentials(projectId, accountType, account.encryptedCredentials);const targetUsername = targetCredentials.username;- const handler = PAM_ROTATION_FACTORY_MAP[accountType];+ const handler = rotationHandlers[accountType];handler.validateTarget({ accountType, authMethod: targetCredentials.authMethod });@@ -224,7 +246,12 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServicawait pamAccountDAL.updateById(account.id, { encryptedPendingCredentials: null });}- const auth = await resolveAuthCredential(account, targetCredentials);+ const {+ auth,+ connectionDetails: rotatorConnectionDetails,+ gatewayId: rotatorGatewayId,+ gatewayPoolId: rotatorGatewayPoolId+ } = await resolveRotator(account, targetCredentials, connectionDetails, { gatewayId, gatewayPoolId });const requirements = getPasswordRequirements(account.templateSettings);const newPassword = generatePassword(requirements);const encryptedPending = await encrypt(projectId, { ...targetCredentials, password: newPassword });@@ -234,7 +261,15 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServictry {await handler.applyPasswordChange(- { accountType, connectionDetails, auth, targetUsername, newPassword, gatewayId, gatewayPoolId },+ {+ accountType,+ connectionDetails: rotatorConnectionDetails,+ auth,+ targetUsername,+ newPassword,+ gatewayId: rotatorGatewayId,+ gatewayPoolId: rotatorGatewayPoolId+ },gatewayDeps);} catch (err) {@@ -389,17 +424,15 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServic}if (rotationAccountId) {- if (account.credentialConfigured) {- const targetCredentials = await decryptSqlCredentials(- projectId,- account.accountType,- account.encryptedCredentials- );- PAM_ROTATION_FACTORY_MAP[account.accountType].validateTarget({- accountType: account.accountType,- authMethod: targetCredentials.authMethod- });- }+ const targetCredentials = await decryptSqlCredentials(+ projectId,+ account.accountType,+ account.encryptedCredentials+ );+ rotationHandlers[account.accountType].validateTarget({+ accountType: account.accountType,+ authMethod: targetCredentials.authMethod+ });if (rotationAccountId !== accountId) {const rotator = await pamAccountDAL.findByIdWithDetails(rotationAccountId);@@ -507,7 +540,7 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServicmembershipDAL,membershipRoleDAL,projectId,- { allOf: [ResourcePermissionPamResourceActions.ReadAccounts] },+ { allOf: [ResourcePermissionPamResourceActions.ViewCredentials] },ctx);diff --git a/frontend/src/pages/pam/PamAccountsPage/components/RotationTab.tsx b/frontend/src/pages/pam/PamAccountsPage/components/RotationTab.tsxindex b76f49cf35..7ce57331b6 100644--- a/frontend/src/pages/pam/PamAccountsPage/components/RotationTab.tsx+++ b/frontend/src/pages/pam/PamAccountsPage/components/RotationTab.tsx@@ -100,8 +100,8 @@ const RotationAccountPicker = ({)}<CommandGroup><CommandItem value="none" onSelect={() => onSelect(null)}>- <Check className={`mr-2 size-4 ${selectedId ? "opacity-0" : "opacity-100"}`} />None (not configured)+ <Check className={`ml-auto size-4 ${selectedId ? "opacity-0" : "opacity-100"}`} /></CommandItem></CommandGroup>{candidates.map((group) => (@@ -115,9 +115,6 @@ const RotationAccountPicker = ({value={candidate.id}onSelect={() => onSelect(candidate.id)}>- <Check- className={`mr-2 size-4 ${selectedId === candidate.id ? "opacity-100" : "opacity-0"}`}- /><div className="flex min-w-0 flex-col"><span className="truncate font-medium">{candidate.name}@@ -125,6 +122,9 @@ const RotationAccountPicker = ({</span><span className="truncate text-xs text-muted">{candidate.host}</span></div>+ <Check+ className={`ml-auto size-4 ${selectedId === candidate.id ? "opacity-100" : "opacity-0"}`}+ /></CommandItem>))}</CommandGroup>@@ -198,23 +198,20 @@ export const RotationTab = ({ accountId }: Props) => {<span className="text-sm text-muted">Default</span>)}</DetailRow>- <div className="flex items-center justify-between gap-3 py-3">- <span className="text-sm text-foreground">Last rotated</span>- <div className="flex items-center gap-3">- <span className="text-sm text-muted">- {rotation.lastRotatedAt ? formatDetailDate(rotation.lastRotatedAt) : "Never"}- </span>- <Button- variant="outline"- size="sm"- isDisabled={!canManage || !rotation.isReady}- isPending={rotateNow.isPending}- onClick={onRotateNow}- >- Rotate now- </Button>- </div>- </div>+ <DetailRow label="Last rotated">+ <span className="text-sm text-muted">+ {rotation.lastRotatedAt ? formatDetailDate(rotation.lastRotatedAt) : "Never"}+ </span>+ </DetailRow>+ <Button+ variant="pam"+ className="mt-4 w-full"+ isDisabled={!canManage || !rotation.isReady}+ isPending={rotateNow.isPending}+ onClick={onRotateNow}+ >+ Rotate now+ </Button></div><div className="rounded-lg border border-border bg-container p-4">diff --git a/frontend/src/pages/pam/PamTemplatesPage/components/TemplateDetailSheet.tsx b/frontend/src/pages/pam/PamTemplatesPage/components/TemplateDetailSheet.tsxindex 1bab14b78a..6680182c5e 100644--- a/frontend/src/pages/pam/PamTemplatesPage/components/TemplateDetailSheet.tsx+++ b/frontend/src/pages/pam/PamTemplatesPage/components/TemplateDetailSheet.tsx@@ -81,20 +81,62 @@ const settingsSchema = z})}).superRefine((data, ctx) => {- if (data.recordingStorageBackend !== "aws-s3") return;- if (!data.recordingConnectionId) {- ctx.addIssue({- code: z.ZodIssueCode.custom,- path: ["recordingConnectionId"],- message: "Select an AWS connection"- });+ if (data.recordingStorageBackend === "aws-s3") {+ if (!data.recordingConnectionId) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["recordingConnectionId"],+ message: "Select an AWS connection"+ });+ }+ if (!data.s3Bucket?.trim()) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["s3Bucket"],+ message: "Bucket is required"+ });+ }}- if (!data.s3Bucket?.trim()) {- ctx.addIssue({- code: z.ZodIssueCode.custom,- path: ["s3Bucket"],- message: "Bucket is required"++ if (data.settings.rotationEnabled) {+ const length = data.settings.pwLength ?? 32;+ const mins = {+ uppercase: data.settings.pwUppercase ?? 0,+ lowercase: data.settings.pwLowercase ?? 0,+ digits: data.settings.pwDigits ?? 0,+ symbols: data.settings.pwSymbols ?? 0+ };+ if (length < 1 || length > 250) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["settings", "pwLength"],+ message: "Length must be between 1 and 250"+ });+ }+ (["pwUppercase", "pwLowercase", "pwDigits", "pwSymbols"] as const).forEach((key) => {+ const value = data.settings[key];+ if (value !== undefined && value < 0) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["settings", key],+ message: "Cannot be negative"+ });+ }});+ const totalRequired = mins.uppercase + mins.lowercase + mins.digits + mins.symbols;+ if (totalRequired === 0) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["settings", "pwLength"],+ message: "Require at least one character type"+ });+ } else if (totalRequired > length) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["settings", "pwLength"],+ message: "Length must be at least the sum of the minimums"+ });+ }}});@@ -412,6 +454,12 @@ const SettingsTab = ({});return;}+ // Surface the specific validation issue rather than the opaque generic toast.+ createNotification({+ type: "error",+ text: responseData.message[0]?.message ?? "Failed to update template"+ });+ return;}const msg = (error.response?.data as { message?: string })?.message;createNotification({@@ -506,8 +554,8 @@ const SettingsTab = ({Automatically rotate credentials</p><p className="text-xs text-muted">- Infisical rotates credentials on a fixed schedule. When off, they rotate only- when triggered manually.+ Infisical rotates credentials on a fixed schedule. When off, accounts using+ this template won't rotate, on a schedule or manually.</p></div><Switch@@ -602,7 +650,7 @@ const SettingsTab = ({key={name}control={control}name={name}- render={({ field }) => (+ render={({ field, fieldState }) => (<Field><FieldLabel>{label}</FieldLabel><Input@@ -611,6 +659,7 @@ const SettingsTab = ({onChange={(e) => field.onChange(Number(e.target.value))}onWheel={(e) => e.currentTarget.blur()}/>+ {fieldState.error && <FieldError>{fieldState.error.message}</FieldError>}</Field>)}/>