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 Monastyrski5ff920a6c2a9
diff --git a/backend/src/ee/routes/v1/pam-routers/pam-account-router.ts b/backend/src/ee/routes/v1/pam-routers/pam-account-router.tsindex 3d77eddb4d..94e2df8737 100644--- a/backend/src/ee/routes/v1/pam-routers/pam-account-router.ts+++ b/backend/src/ee/routes/v1/pam-routers/pam-account-router.ts@@ -472,6 +472,8 @@ export const registerPamAccountRouter = async (server: FastifyZodProvider) => {rotationAccountId: z.string().nullable(),rotationAccountName: z.string().nullable(),lastRotatedAt: z.date().nullable(),+ rotationStatus: z.string().nullable(),+ lastRotationError: z.string().nullable(),isReady: z.boolean()});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.tsindex 1b4cd3c216..6a1e628788 100644--- 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.ts@@ -35,7 +35,7 @@ const buildAccount = () => ({encryptedCredentials: blobOf({ username: "app", password: CURRENT_PASSWORD }),encryptedConnectionDetails: blobOf(connectionDetails),encryptedPendingCredentials: blobOf({ username: "app", password: PENDING_PASSWORD }),- templateSettings: { rotation: { enabled: true, intervalSeconds: 3600 } },+ templateSettings: { rotation: { enabled: true, intervalSeconds: 3600 as number | null } },templateGatewayId: null,templateGatewayPoolId: null,gatewayId: null,@@ -116,6 +116,23 @@ describe("rotateScheduledAccount recovery probe", () => {);});+ test("manual mode (null interval) rotates but does not schedule a next run", async () => {+ const account = {+ ...buildAccount(),+ templateSettings: { rotation: { enabled: true, intervalSeconds: null } }+ };+ const { service, updateById } = buildService((password) => password === PENDING_PASSWORD, { account });++ const result = await service.rotateScheduledAccount("acc-1");++ expect(result?.rotationStatus).toBe(ROTATION_STATUS.Success);+ // markRotated must clear nextRotationAt for a manual account so the cron never re-selects it.+ expect(updateById).toHaveBeenCalledWith(+ "acc-1",+ expect.objectContaining({ rotationStatus: ROTATION_STATUS.Success, nextRotationAt: null })+ );+ });+test("defers when neither the pending nor the current credential authenticates", async () => {const { service, applyPasswordChange } = buildService(() => false);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 a8a37f3dfc..bbdf96dc8e 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@@ -38,7 +38,6 @@ export const ROTATION_STATUS = { Success: "success", Failed: "failed" } as constconst ROTATION_IN_PROGRESS_MESSAGE = "A rotation is already in progress for this account";const ROTATION_NOT_READY_MESSAGE: Record<PamRotationReadinessIssue, string> = {- [PamRotationReadinessIssue.RotationDisabled]: "Rotation is not enabled for this account's template",[PamRotationReadinessIssue.UnsupportedType]: "Rotation is not supported for this account type",[PamRotationReadinessIssue.NotConfigured]: "No rotation account is configured for this account",[PamRotationReadinessIssue.SelfRotationNoCredential]:@@ -122,7 +121,7 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServicconst nextRotationAfter = (templateSettings: unknown, now: Date): Date | null => {const rotation = getRotationConfig(templateSettings);- if (!rotation?.enabled) return null;+ if (!rotation?.enabled || rotation.intervalSeconds == null) return null;return computeNextRotationAt({ anchor: now, intervalSeconds: rotation.intervalSeconds, now });};@@ -322,11 +321,10 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServicaccountId: account.id,accountType: account.accountType,rotationAccountId: account.rotationAccountId,- credentialConfigured: account.credentialConfigured,- templateSettings: account.templateSettings+ credentialConfigured: account.credentialConfigured});const nextRotationAt =- ready && rotation?.enabled+ ready && rotation?.enabled && rotation.intervalSeconds != null? computeNextRotationAt({anchor: now,intervalSeconds: Math.min(rotation.intervalSeconds, ROTATION_FAILURE_RETRY_CAP_SECONDS),@@ -380,8 +378,7 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServicaccountId: account.id,accountType: account.accountType,rotationAccountId: account.rotationAccountId,- credentialConfigured: account.credentialConfigured,- templateSettings: account.templateSettings+ credentialConfigured: account.credentialConfigured});let rotationAccountName: string | null = null;@@ -409,6 +406,12 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServic}}+ let lastRotationError: string | null = null;+ if (account.rotationStatus === ROTATION_STATUS.Failed && account.encryptedLastRotationMessage) {+ const decrypted = await decrypt(projectId, account.encryptedLastRotationMessage);+ lastRotationError = (decrypted as { message?: string }).message ?? null;+ }+return {enabled: settings?.rotation?.enabled ?? false,intervalSeconds: settings?.rotation?.intervalSeconds ?? null,@@ -416,6 +419,8 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServicrotationAccountId,rotationAccountName,lastRotatedAt: account.lastRotatedAt ?? null,+ rotationStatus: account.rotationStatus ?? null,+ lastRotationError,isReady: readiness.ready};};@@ -531,8 +536,7 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServicaccountId: account.id,accountType: account.accountType,rotationAccountId: account.rotationAccountId,- credentialConfigured: account.credentialConfigured,- templateSettings: account.templateSettings+ credentialConfigured: account.credentialConfigured});if (!readiness.ready && readiness.issue) {throw new BadRequestError({ message: ROTATION_NOT_READY_MESSAGE[readiness.issue] });diff --git a/backend/src/ee/services/pam-account-rotation/pam-account-rotation-types.ts b/backend/src/ee/services/pam-account-rotation/pam-account-rotation-types.tsindex c2e1b97686..93760a802a 100644--- a/backend/src/ee/services/pam-account-rotation/pam-account-rotation-types.ts+++ b/backend/src/ee/services/pam-account-rotation/pam-account-rotation-types.ts@@ -30,5 +30,7 @@ export type TPamAccountRotationView = {rotationAccountId: string | null;rotationAccountName: string | null;lastRotatedAt: Date | null;+ rotationStatus: string | null;+ lastRotationError: string | null;isReady: boolean;};diff --git a/backend/src/ee/services/pam-account-rotation/pam-rotation-fns.test.ts b/backend/src/ee/services/pam-account-rotation/pam-rotation-fns.test.tsindex 78a9c6359d..90454984bc 100644--- a/backend/src/ee/services/pam-account-rotation/pam-rotation-fns.test.ts+++ b/backend/src/ee/services/pam-account-rotation/pam-rotation-fns.test.ts@@ -8,12 +8,6 @@ import {PamRotationReadinessIssue} from "./pam-rotation-fns";-const templateSettings = (enabled: boolean, intervalSeconds = 86400) => ({- recordingEnabled: true,- recordingStorageBackend: "postgres",- rotation: { enabled, intervalSeconds }-});-describe("isRotatableAccountType", () => {test("accepts the three SQL types", () => {expect(isRotatableAccountType(PamAccountType.Postgres)).toBe(true);@@ -32,13 +26,12 @@ describe("getRotationReadiness", () => {const base = {accountId: "acc-1",accountType: PamAccountType.Postgres,- credentialConfigured: true,- templateSettings: templateSettings(true)+ credentialConfigured: true};- test("not ready when template rotation is disabled", () => {- const r = getRotationReadiness({ ...base, rotationAccountId: "acc-1", templateSettings: templateSettings(false) });- expect(r).toEqual({ ready: false, issue: PamRotationReadinessIssue.RotationDisabled });+ test("ready regardless of the automatic-rotation toggle (manual is always available once configured)", () => {+ const r = getRotationReadiness({ ...base, rotationAccountId: "acc-1" });+ expect(r).toEqual({ ready: true });});test("not ready for an unsupported account type", () => {diff --git a/backend/src/ee/services/pam-account-rotation/pam-rotation-fns.ts b/backend/src/ee/services/pam-account-rotation/pam-rotation-fns.tsindex 3f18581573..236fb63010 100644--- a/backend/src/ee/services/pam-account-rotation/pam-rotation-fns.ts+++ b/backend/src/ee/services/pam-account-rotation/pam-rotation-fns.ts@@ -1,7 +1,6 @@import { AppConnection } from "@app/services/app-connection/app-connection-enums";import { PamAccountType } from "../pam/pam-enums";-import { PamTemplateSettingsSchema } from "../pam-account-template/pam-account-template-schemas";export const ROTATABLE_ACCOUNT_TYPES = [PamAccountType.Postgres, PamAccountType.MySQL, PamAccountType.MsSQL] as const;@@ -21,7 +20,6 @@ export const PAM_ROTATION_APP_MAP: Record<};export enum PamRotationReadinessIssue {- RotationDisabled = "rotation-disabled",UnsupportedType = "unsupported-type",NotConfigured = "not-configured",SelfRotationNoCredential = "self-rotation-no-credential"@@ -32,7 +30,6 @@ type TRotationReadinessInput = {accountType: PamAccountType | string;rotationAccountId?: string | null;credentialConfigured: boolean;- templateSettings: unknown;};// Account-level readiness as raw SQL, shared by the reconcile and impact count so they can't drift from each other@@ -43,10 +40,6 @@ export const ACCOUNT_NEEDS_ROTATION_ACCOUNT_SQL = `"rotationAccountId" IS NULL Oexport type TRotationReadiness = { ready: boolean; issue?: PamRotationReadinessIssue };export const getRotationReadiness = (account: TRotationReadinessInput): TRotationReadiness => {- const parsed = PamTemplateSettingsSchema.safeParse(account.templateSettings);- const rotationEnabled = parsed.success && parsed.data.rotation?.enabled === true;-- if (!rotationEnabled) return { ready: false, issue: PamRotationReadinessIssue.RotationDisabled };if (!isRotatableAccountType(account.accountType)) {return { ready: false, issue: PamRotationReadinessIssue.UnsupportedType };}diff --git a/backend/src/ee/services/pam-account-template/pam-account-template-schemas.ts b/backend/src/ee/services/pam-account-template/pam-account-template-schemas.tsindex 6e127b9a40..82fd9646e9 100644--- a/backend/src/ee/services/pam-account-template/pam-account-template-schemas.ts+++ b/backend/src/ee/services/pam-account-template/pam-account-template-schemas.ts@@ -8,7 +8,7 @@ import { PamRecordingStorageBackend } from "../pam-session-recording/pam-recordiexport const PamRotationConfigSchema = z.object({enabled: z.boolean(),- intervalSeconds: z.number().int().min(3600).max(31_536_000) // 1 hour .. 1 year+ intervalSeconds: z.number().int().min(3600).max(31_536_000).nullable() // 1 hour .. 1 year, or null for manual});export const PamRecordingS3ConfigSchema = z.object({diff --git a/backend/src/ee/services/pam-account/pam-account-dal.ts b/backend/src/ee/services/pam-account/pam-account-dal.tsindex 36ee50d9db..441447a2fa 100644--- a/backend/src/ee/services/pam-account/pam-account-dal.ts+++ b/backend/src/ee/services/pam-account/pam-account-dal.ts@@ -289,7 +289,7 @@ export const pamAccountDALFactory = (db: TDbClient) => {const rotation = parsed.success ? parsed.data.rotation : undefined;const enabled = rotation?.enabled === true && ROTATABLE_TYPE_VALUES.includes(template.type);- if (!enabled || !rotation) {+ if (!enabled || !rotation || rotation.intervalSeconds == null) {await dbClient(TableName.PamAccount).where({ templateId }).whereNotNull("nextRotationAt")@@ -326,16 +326,15 @@ export const pamAccountDALFactory = (db: TDbClient) => {accountId: account.id,accountType: account.accountType,rotationAccountId: account.rotationAccountId,- credentialConfigured: account.credentialConfigured,- templateSettings: account.templateSettings+ credentialConfigured: account.credentialConfigured});const rotation = PamTemplateSettingsSchema.safeParse(account.templateSettings).data?.rotation;const current = account.nextRotationAt ?? null;let nextRotationAt: Date | null = current;- if (!readiness.ready) {+ if (!readiness.ready || !rotation?.enabled || rotation.intervalSeconds == null) {nextRotationAt = null;- } else if (!current && rotation?.enabled) {+ } else if (!current) {nextRotationAt = computeNextRotationAt({anchor: account.lastRotatedAt ?? null,intervalSeconds: rotation.intervalSeconds,diff --git a/backend/src/ee/services/pam-account/pam-account-service.ts b/backend/src/ee/services/pam-account/pam-account-service.tsindex ee2a0879ed..71dd5fe859 100644--- a/backend/src/ee/services/pam-account/pam-account-service.ts+++ b/backend/src/ee/services/pam-account/pam-account-service.ts@@ -36,6 +36,7 @@ import {validateRecordingConnection} from "../pam/pam-validators";import { TPamAccountTemplateDALFactory } from "../pam-account-template/pam-account-template-dal";+import { PamTemplateSettingsSchema } from "../pam-account-template/pam-account-template-schemas";import { TPamFolderDALFactory } from "../pam-folder/pam-folder-dal";import { TPamAccountDALFactory } from "./pam-account-dal";import {@@ -72,6 +73,46 @@ type TPamAccountServiceFactoryDep = {appConnectionDAL: Pick<TAppConnectionDALFactory, "findOne" | "findById">;};+const assertPasswordMeetsRequirements = (credentials: unknown, templateSettings: unknown) => {+ const requirements = PamTemplateSettingsSchema.safeParse(templateSettings).data?.passwordRequirements;+ const { password } = credentials as { password?: string };+ if (!requirements || !password) return;++ let upper = 0;+ let lower = 0;+ let digit = 0;+ let symbol = 0;+ const allowed = requirements.allowedSymbols ? new Set(requirements.allowedSymbols.split("")) : null;+ const disallowed = new Set<string>();+ for (const ch of password) {+ if (ch >= "A" && ch <= "Z") upper += 1;+ else if (ch >= "a" && ch <= "z") lower += 1;+ else if (ch >= "0" && ch <= "9") digit += 1;+ else {+ symbol += 1;+ if (allowed && !allowed.has(ch)) disallowed.add(ch);+ }+ }++ const violations: string[] = [];+ if (password.length < requirements.length) violations.push(`be at least ${requirements.length} characters long`);+ if (upper < requirements.required.uppercase)+ violations.push(`include at least ${requirements.required.uppercase} uppercase letter(s)`);+ if (lower < requirements.required.lowercase)+ violations.push(`include at least ${requirements.required.lowercase} lowercase letter(s)`);+ if (digit < requirements.required.digits)+ violations.push(`include at least ${requirements.required.digits} number(s)`);+ if (symbol < requirements.required.symbols)+ violations.push(`include at least ${requirements.required.symbols} symbol(s)`);+ if (allowed && disallowed.size > 0) violations.push(`only use these symbols: ${requirements.allowedSymbols}`);++ if (violations.length > 0) {+ throw new BadRequestError({+ message: `Password does not meet this template's requirements: it must ${violations.join(", ")}.`+ });+ }+};+export type TPamAccountServiceFactory = ReturnType<typeof pamAccountServiceFactory>;export const pamAccountServiceFactory = (deps: TPamAccountServiceFactoryDep) => {@@ -251,6 +292,7 @@ export const pamAccountServiceFactory = (deps: TPamAccountServiceFactoryDep) =>const validatedConnectionDetails = validateConnectionDetails(accountType, connectionDetails);const validatedCredentials = validateCredentials(accountType, credentials);+ assertPasswordMeetsRequirements(validatedCredentials, template.settings);const encryptedConnectionDetails = await encrypt(projectId, validatedConnectionDetails);const encryptedCredentials = await encrypt(projectId, validatedCredentials);@@ -385,11 +427,25 @@ export const pamAccountServiceFactory = (deps: TPamAccountServiceFactoryDep) =>if (credentials) {const existingCredentials = await decrypt(projectId, existing.encryptedCredentials);const validated = validateCredentials(accountType, { ...existingCredentials, ...credentials });+ const templateSettings = templateId+ ? (await pamAccountTemplateDAL.findById(templateId))?.settings+ : existing.templateSettings;+ assertPasswordMeetsRequirements(validated, templateSettings);updateData.encryptedCredentials = await encrypt(projectId, validated);updateData.credentialConfigured = isCredentialConfigured(accountType, validated);}- const routingChanged = connectionDetails !== undefined || gatewayId !== undefined || gatewayPoolId !== undefined;+ let routingChanged =+ (gatewayId !== undefined && gatewayId !== existing.gatewayId) ||+ (gatewayPoolId !== undefined && gatewayPoolId !== existing.gatewayPoolId);+ if (connectionDetails) {+ const oldConn = validateConnectionDetails(+ accountType,+ await decrypt(projectId, existing.encryptedConnectionDetails)+ ) as { host?: string; port?: number };+ const newConn = validateConnectionDetails(accountType, connectionDetails) as { host?: string; port?: number };+ if (oldConn.host !== newConn.host || oldConn.port !== newConn.port) routingChanged = true;+ }if (routingChanged && existing.rotationAccountId) {updateData.rotationAccountId = null;}diff --git a/frontend/src/hooks/api/pam/enums.ts b/frontend/src/hooks/api/pam/enums.tsindex e23acf24d6..93caca5dd1 100644--- a/frontend/src/hooks/api/pam/enums.ts+++ b/frontend/src/hooks/api/pam/enums.ts@@ -30,7 +30,7 @@ export const PAM_ROTATION_INTERVAL_OPTIONS: { seconds: number; label: string }[]];export const formatRotationInterval = (seconds: number | null | undefined): string => {- if (!seconds) return "Not set";+ if (seconds == null) return "Manual only";const preset = PAM_ROTATION_INTERVAL_OPTIONS.find((option) => option.seconds === seconds);if (preset) return preset.label;const hours = Math.round(seconds / 3600);diff --git a/frontend/src/hooks/api/pam/types/index.ts b/frontend/src/hooks/api/pam/types/index.tsindex 5caf4a8513..c786e6820f 100644--- a/frontend/src/hooks/api/pam/types/index.ts+++ b/frontend/src/hooks/api/pam/types/index.ts@@ -475,6 +475,8 @@ export type TPamAccountRotation = {rotationAccountId: string | null;rotationAccountName: string | null;lastRotatedAt: string | null;+ rotationStatus: string | null;+ lastRotationError: string | null;isReady: boolean;};diff --git a/frontend/src/pages/pam/PamAccountsPage/components/AccountDetailSheet.tsx b/frontend/src/pages/pam/PamAccountsPage/components/AccountDetailSheet.tsxindex dd0f9f51e3..5c297675bd 100644--- a/frontend/src/pages/pam/PamAccountsPage/components/AccountDetailSheet.tsx+++ b/frontend/src/pages/pam/PamAccountsPage/components/AccountDetailSheet.tsx@@ -914,7 +914,9 @@ export const AccountDetailSheet = ({ isOpen, accountId, onOpenChange }: Props) =[PamSheetTab.Configuration]: accountId ? (<EditAccountForm accountId={accountId} onDirtyChange={setIsFormDirty} />) : null,- [PamSheetTab.Rotation]: accountId ? <RotationTab accountId={accountId} /> : null,+ [PamSheetTab.Rotation]: accountId ? (+ <RotationTab accountId={accountId} onDirtyChange={setIsFormDirty} />+ ) : null,[PamSheetTab.Advanced]: accountId ? (<SettingsTab accountId={accountId} onDirtyChange={setIsFormDirty} />) : nulldiff --git a/frontend/src/pages/pam/PamAccountsPage/components/RotationTab.tsx b/frontend/src/pages/pam/PamAccountsPage/components/RotationTab.tsxindex 7ce57331b6..41bfa2f111 100644--- a/frontend/src/pages/pam/PamAccountsPage/components/RotationTab.tsx+++ b/frontend/src/pages/pam/PamAccountsPage/components/RotationTab.tsx@@ -1,8 +1,12 @@-import { useState } from "react";+import { useEffect, useState } from "react";+import { Controller, useForm } from "react-hook-form";import { Check, ChevronsUpDown } from "lucide-react";import { createNotification } from "@app/components/notifications";import {+ Alert,+ AlertDescription,+ AlertTitle,Badge,Button,Command,@@ -26,8 +30,11 @@ import {import { TPamAccountRotation } from "@app/hooks/api/pam/types";import { formatDetailDate } from "../../components/PamDetailSheet";+import { SheetSaveBar } from "../../components/SheetSaveBar";-type Props = { accountId: string };+type Props = { accountId: string; onDirtyChange?: (isDirty: boolean) => void };++type RotationForm = { rotationAccountId: string | null };const passwordFormatBadges = (reqs: TPamAccountRotation["passwordRequirements"]) => {if (!reqs) return [];@@ -48,12 +55,14 @@ const DetailRow = ({ label, children }: { label: string; children: React.ReactNoconst RotationAccountPicker = ({accountId,- selectedId,+ value,+ onChange,selectedName,disabled}: {accountId: string;- selectedId: string | null;+ value: string | null;+ onChange: (rotationAccountId: string | null) => void;selectedName: string | null;disabled: boolean;}) => {@@ -61,22 +70,16 @@ const RotationAccountPicker = ({const { data: candidates = [], isPending } = useGetPamRotationCandidates(accountId, {enabled: open});- const updateRotation = useUpdatePamAccountRotation();const allAccounts = candidates.flatMap((group) => group.accounts);- const selected = allAccounts.find((a) => a.id === selectedId);- const selectedLabel = selectedId- ? `${selected?.name ?? selectedName ?? selectedId}${selectedId === accountId ? " (this account)" : ""}`+ const selected = allAccounts.find((a) => a.id === value);+ const selectedLabel = value+ ? `${selected?.name ?? selectedName ?? value}${value === accountId ? " (this account)" : ""}`: "None";- const onSelect = async (rotationAccountId: string | null) => {+ const handleSelect = (rotationAccountId: string | null) => {setOpen(false);- try {- await updateRotation.mutateAsync({ accountId, rotationAccountId });- createNotification({ type: "success", text: "Rotation account updated" });- } catch {- createNotification({ type: "error", text: "Failed to update rotation account" });- }+ onChange(rotationAccountId);};return (@@ -99,9 +102,9 @@ const RotationAccountPicker = ({<CommandEmpty>No eligible accounts</CommandEmpty>)}<CommandGroup>- <CommandItem value="none" onSelect={() => onSelect(null)}>+ <CommandItem value="none" onSelect={() => handleSelect(null)}>None (not configured)- <Check className={`ml-auto size-4 ${selectedId ? "opacity-0" : "opacity-100"}`} />+ <Check className={`ml-auto size-4 ${value ? "opacity-0" : "opacity-100"}`} /></CommandItem></CommandGroup>{candidates.map((group) => (@@ -113,7 +116,7 @@ const RotationAccountPicker = ({<CommandItemkey={candidate.id}value={candidate.id}- onSelect={() => onSelect(candidate.id)}+ onSelect={() => handleSelect(candidate.id)}><div className="flex min-w-0 flex-col"><span className="truncate font-medium">@@ -123,7 +126,7 @@ const RotationAccountPicker = ({<span className="truncate text-xs text-muted">{candidate.host}</span></div><Check- className={`ml-auto size-4 ${selectedId === candidate.id ? "opacity-100" : "opacity-0"}`}+ className={`ml-auto size-4 ${value === candidate.id ? "opacity-100" : "opacity-0"}`}/></CommandItem>))}@@ -136,21 +139,45 @@ const RotationAccountPicker = ({);};-export const RotationTab = ({ accountId }: Props) => {+export const RotationTab = ({ accountId, onDirtyChange }: Props) => {const { data: rotation, isPending } = useGetPamAccountRotation(accountId);const { can } = usePamAccountActions(accountId);const canManage = can(PamResourcePermissionActions.ManageRotation);const rotateNow = useRotatePamAccount();+ const updateRotation = useUpdatePamAccountRotation();++ const {+ control,+ handleSubmit,+ reset,+ formState: { isDirty }+ } = useForm<RotationForm>({ defaultValues: { rotationAccountId: null } });++ useEffect(() => {+ onDirtyChange?.(isDirty);+ return () => onDirtyChange?.(false);+ }, [isDirty, onDirtyChange]);++ useEffect(() => {+ if (rotation) reset({ rotationAccountId: rotation.rotationAccountId });+ }, [rotation, reset]);++ const onSubmit = async (data: RotationForm) => {+ try {+ await updateRotation.mutateAsync({ accountId, rotationAccountId: data.rotationAccountId });+ createNotification({ type: "success", text: "Rotation account updated" });+ reset(data);+ } catch {+ createNotification({ type: "error", text: "Failed to update rotation account" });+ }+ };const onRotateNow = async () => {try {await rotateNow.mutateAsync({ accountId });createNotification({ type: "success", text: "Credential rotated" });} catch {- createNotification({- type: "error",- text: "Rotation failed. Check the account's rotation status."- });+ createNotification({ type: "error", text: "Rotation failed. See the error below." });}};@@ -163,12 +190,14 @@ export const RotationTab = ({ accountId }: Props) => {);}+ const hasFailure = rotation.rotationStatus === "failed" && Boolean(rotation.lastRotationError);+return (- <div className="flex flex-col gap-4 p-4">+ <form onSubmit={handleSubmit(onSubmit)} className="flex flex-1 flex-col gap-4 p-4"><div className="rounded-lg border border-border bg-container p-4"><div className="mb-2 flex items-center justify-between"><div>- <h3 className="text-sm font-semibold text-foreground">Automatic rotation</h3>+ <h3 className="text-sm font-semibold text-foreground">Rotation</h3><p className="text-xs text-muted">How and when this account's password is rotated.</p>@@ -176,13 +205,13 @@ export const RotationTab = ({ accountId }: Props) => {<spanclassName={`text-xs font-medium ${rotation.enabled ? "text-success" : "text-muted"}`}>- {rotation.enabled ? "● Enabled" : "○ Disabled"}+ {rotation.enabled ? "● Automatic" : "○ On demand"}</span></div>- <DetailRow label="Frequency">+ <DetailRow label="Schedule"><span className="text-sm text-muted">- {formatRotationInterval(rotation.intervalSeconds)}+ {rotation.enabled ? formatRotationInterval(rotation.intervalSeconds) : "On demand only"}</span></DetailRow><DetailRow label="Password format">@@ -204,6 +233,7 @@ export const RotationTab = ({ accountId }: Props) => {</span></DetailRow><Button+ type="button"variant="pam"className="mt-4 w-full"isDisabled={!canManage || !rotation.isReady}@@ -214,16 +244,30 @@ export const RotationTab = ({ accountId }: Props) => {</Button></div>+ {hasFailure && (+ <Alert variant="danger">+ <AlertTitle>Last rotation failed</AlertTitle>+ <AlertDescription>{rotation.lastRotationError}</AlertDescription>+ </Alert>+ )}+<div className="rounded-lg border border-border bg-container p-4"><h3 className="text-sm font-semibold text-foreground">Rotation account</h3><p className="mb-3 text-xs text-muted">The privileged account used to rotate this password.</p>- <RotationAccountPicker- accountId={accountId}- selectedId={rotation.rotationAccountId}- selectedName={rotation.rotationAccountName}- disabled={!canManage}+ <Controller+ control={control}+ name="rotationAccountId"+ render={({ field }) => (+ <RotationAccountPicker+ accountId={accountId}+ value={field.value}+ onChange={field.onChange}+ selectedName={rotation.rotationAccountName}+ disabled={!canManage}+ />+ )}/><p className="mt-2 text-xs text-muted">Select this account to have it rotate its own password. If set to None, the account will@@ -231,13 +275,17 @@ export const RotationTab = ({ accountId }: Props) => {</p></div>- {!rotation.isReady && rotation.enabled && (- <div className="rounded-lg border border-warning/40 bg-warning/10 p-3 text-xs text-warning">- Rotation is enabled, but this account won't rotate until a rotation account is set.- Choose one above, or select this account to rotate its own password (which requires stored- credentials).- </div>+ {!rotation.isReady && (+ <Alert variant="warning">+ <AlertTitle>Not rotating yet</AlertTitle>+ <AlertDescription>+ This account won't rotate until a rotation account is set. Choose one above, or+ select this account to rotate its own password.+ </AlertDescription>+ </Alert>)}- </div>++ {isDirty && <SheetSaveBar isPending={updateRotation.isPending} onDiscard={() => reset()} />}+ </form>);};diff --git a/frontend/src/pages/pam/PamTemplatesPage/components/TemplateDetailSheet.tsx b/frontend/src/pages/pam/PamTemplatesPage/components/TemplateDetailSheet.tsxindex 6680182c5e..0b06a0f34d 100644--- a/frontend/src/pages/pam/PamTemplatesPage/components/TemplateDetailSheet.tsx+++ b/frontend/src/pages/pam/PamTemplatesPage/components/TemplateDetailSheet.tsx@@ -71,7 +71,7 @@ const settingsSchema = zsettings: z.object({sessionLogMaskingPatterns: z.string().optional(),rotationEnabled: z.boolean().optional(),- rotationIntervalSeconds: z.coerce.number().optional(),+ rotationIntervalSeconds: z.number().nullable().optional(),pwLength: z.coerce.number().optional(),pwUppercase: z.coerce.number().optional(),pwLowercase: z.coerce.number().optional(),@@ -98,45 +98,43 @@ const settingsSchema = z}}- 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 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"});- 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) {+ }+ (["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", "pwLength"],- message: "Length must be at least the sum of the minimums"+ 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"+ });}});@@ -326,7 +324,7 @@ const SettingsTab = ({...(() => {const rotation = (settings.rotation ?? {}) as {enabled?: boolean;- intervalSeconds?: number;+ intervalSeconds?: number | null;};const pw = (settings.passwordRequirements ?? {}) as {length?: number;@@ -340,7 +338,8 @@ const SettingsTab = ({};return {rotationEnabled: rotation.enabled ?? false,- rotationIntervalSeconds: rotation.intervalSeconds ?? 86400,+ rotationIntervalSeconds:+ rotation.intervalSeconds !== undefined ? rotation.intervalSeconds : 86400,pwLength: pw.length ?? 32,pwUppercase: pw.required?.uppercase ?? 1,pwLowercase: pw.required?.lowercase ?? 1,@@ -406,24 +405,20 @@ const SettingsTab = ({const isRotationOn = Boolean(data.settings.rotationEnabled);settings.rotation = {enabled: isRotationOn,- intervalSeconds: data.settings.rotationIntervalSeconds ?? 86400+ intervalSeconds: isRotationOn ? (data.settings.rotationIntervalSeconds ?? 86400) : null+ };+ settings.passwordRequirements = {+ length: data.settings.pwLength ?? 32,+ required: {+ uppercase: data.settings.pwUppercase ?? 0,+ lowercase: data.settings.pwLowercase ?? 0,+ digits: data.settings.pwDigits ?? 0,+ symbols: data.settings.pwSymbols ?? 0+ },+ ...(data.settings.pwAllowedSymbols+ ? { allowedSymbols: data.settings.pwAllowedSymbols }+ : {})};- if (isRotationOn) {- settings.passwordRequirements = {- length: data.settings.pwLength ?? 32,- required: {- uppercase: data.settings.pwUppercase ?? 0,- lowercase: data.settings.pwLowercase ?? 0,- digits: data.settings.pwDigits ?? 0,- symbols: data.settings.pwSymbols ?? 0- },- ...(data.settings.pwAllowedSymbols- ? { allowedSymbols: data.settings.pwAllowedSymbols }- : {})- };- } else {- delete settings.passwordRequirements;- }} else {delete settings.rotation;delete settings.passwordRequirements;@@ -554,8 +549,8 @@ const SettingsTab = ({Automatically rotate credentials</p><p className="text-xs text-muted">- Infisical rotates credentials on a fixed schedule. When off, accounts using- this template won't rotate, on a schedule or manually.+ Infisical rotates credentials on a fixed schedule. When off, credentials+ rotate only when triggered manually.</p></div><Switch@@ -578,13 +573,12 @@ const SettingsTab = ({</AlertTitle><AlertDescription>Set a rotation account on{" "}- {template.rotationImpact.needsRotationAccount === 1 ? "it" : "them"} to include{" "}- {template.rotationImpact.needsRotationAccount === 1 ? "it" : "them"} in the- schedule.+ {template.rotationImpact.needsRotationAccount === 1 ? "it" : "them"} to enable+ rotation.{template.rotationImpact.willRotate > 0 &&` ${template.rotationImpact.willRotate} ${- template.rotationImpact.willRotate === 1 ? "account" : "accounts"- } will rotate as configured.`}+ template.rotationImpact.willRotate === 1 ? "account is" : "accounts are"+ } ready to rotate.`}</AlertDescription></Alert>) : (@@ -601,8 +595,8 @@ const SettingsTab = ({</AlertTitle><AlertDescription>{template.rotationImpact.willRotate === 0- ? "Accounts using this template will rotate on schedule once they have a rotation account."- : "Every account using this template is set to rotate on schedule."}+ ? "Accounts using this template will rotate once they have a rotation account."+ : "Every account using this template has a rotation account."}</AlertDescription></Alert>)@@ -630,16 +624,26 @@ const SettingsTab = ({</SelectContent></Select><FieldDescription>- How often credentials are rotated for accounts using this template.+ How often credentials are rotated automatically for accounts using this+ template.</FieldDescription></Field>)}/>)}+ {/* Requirements are a policy independent of rotation: they apply to onboarded credentials and to the+ passwords generated during rotation, so they show whether or not automatic rotation is on. */}+ <div className="border-t border-border pt-4">+ <p className="text-sm font-medium text-foreground">Requirements</p>+ <p className="text-xs text-muted">+ Every credential must meet these rules, both when an account is onboarded and when a+ password is generated during rotation.+ </p>+ </div><div className="grid grid-cols-2 gap-3">{([- { name: "settings.pwLength", label: "Length" },+ { name: "settings.pwLength", label: "Min length" },{ name: "settings.pwUppercase", label: "Min uppercase" },{ name: "settings.pwLowercase", label: "Min lowercase" },{ name: "settings.pwDigits", label: "Min numbers" },@@ -673,8 +677,8 @@ const SettingsTab = ({<FieldLabel>Allowed symbols</FieldLabel><Input value={field.value ?? ""} onChange={field.onChange} placeholder="-_.~!*" /><FieldDescription>- Symbols that generated passwords may use. Quotes, backticks, backslashes,- semicolons, and question marks are not allowed.+ Symbols a credential may use. Quotes, backticks, backslashes, semicolons, and+ question marks are not allowed.</FieldDescription></Field>)}