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
feat(pam): rotation on discovery import
Andrey96080587b9a5
diff --git a/backend/src/ee/routes/v1/pam-routers/pam-discovery-router.ts b/backend/src/ee/routes/v1/pam-routers/pam-discovery-router.tsindex fadf52045d..21deafca4a 100644--- a/backend/src/ee/routes/v1/pam-routers/pam-discovery-router.ts+++ b/backend/src/ee/routes/v1/pam-routers/pam-discovery-router.ts@@ -460,7 +460,14 @@ export const registerPamDiscoveryRouter = async (server: FastifyZodProvider) =>.object({discoveredAccountId: z.string().uuid(),templateId: z.string().uuid(),- name: slugSchema({ field: "Name" }).optional()+ name: slugSchema({ field: "Name" }).optional(),+ rotationAccountId: z+ .string()+ .uuid()+ .optional()+ .describe(+ "Account that rotates this account's password. When set, it becomes the account's rotation account and the password is rotated right after import"+ )}).array().min(1)@@ -474,7 +481,16 @@ export const registerPamDiscoveryRouter = async (server: FastifyZodProvider) =>status: z.nativeEnum(PamDiscoveryImportStatus),accountId: z.string().optional(),name: z.string().optional(),- message: z.string().optional()+ message: z.string().optional(),+ rotationAccountId: z+ .string()+ .optional()+ .describe("Rotation account set on the imported account. Omitted when it could not be set"),+ rotationStatus: z+ .string()+ .optional()+ .describe("Outcome of the rotation requested on import: success or failed"),+ rotationMessage: z.string().optional().describe("Why the rotation requested on import failed")}).array()})@@ -487,6 +503,7 @@ export const registerPamDiscoveryRouter = async (server: FastifyZodProvider) =>sourceId: req.params.sourceId,folderId: req.body.folderId,accounts: req.body.accounts,+ auditLogInfo: req.auditLogInfo,projectId: req.internalPamProjectId,actorId: req.permission.id,actor: req.permission.type,diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-source-service.ts b/backend/src/ee/services/pam-discovery/pam-discovery-source-service.tsindex 913ce58a26..35350e3418 100644--- a/backend/src/ee/services/pam-discovery/pam-discovery-source-service.ts+++ b/backend/src/ee/services/pam-discovery/pam-discovery-source-service.ts@@ -18,6 +18,10 @@ import { TKmsServiceFactory } from "@app/services/kms/kms-service";import { KmsDataKey } from "@app/services/kms/kms-types";import { TOrgDALFactory } from "@app/services/org/org-dal";+import {+ ROTATION_STATUS,+ TPamAccountRotationServiceFactory+} from "../pam-account-rotation/pam-account-rotation-service";import { TPamAccountDALFactory } from "../pam-account/pam-account-dal";import { TPamAccountServiceFactory } from "../pam-account/pam-account-service";import { PamAccountType, PamPostgresAuthMethod, PamProductRole, PamSshAuthMethod } from "../pam/pam-enums";@@ -60,6 +64,7 @@ type TPamDiscoverySourceServiceFactoryDep = {pamAccountDependencyDAL: TPamAccountDependencyDALFactory;pamAccountDAL: Pick<TPamAccountDALFactory, "findById" | "findByIdWithDetails">;pamAccountService: Pick<TPamAccountServiceFactory, "create">;+ pamAccountRotationService: Pick<TPamAccountRotationServiceFactory, "setRotationAccount" | "rotateNow">;permissionService: Pick<TPermissionServiceFactory,"getProjectPermission" | "getResourcePermission" | "getOrgPermission"@@ -83,6 +88,8 @@ const MAX_SCAN_DURATION_MS = 45 * 60 * 1000;// bound concurrent discovered-account upserts so a large result set can't exhaust the DB connection poolconst DISCOVERED_UPSERT_CONCURRENCY = 8;+const IMPORT_ROTATION_CONCURRENCY = 5;+const withScanTimeout = async <T>(scan: Promise<T>, controller: AbortController, timeoutMs: number): Promise<T> => {let timer: ReturnType<typeof setTimeout> | undefined;const timeout = new Promise<never>((_, reject) => {@@ -114,6 +121,7 @@ export const pamDiscoverySourceServiceFactory = (deps: TPamDiscoverySourceServicpamAccountDependencyDAL,pamAccountDAL,pamAccountService,+ pamAccountRotationService,permissionService,kmsService,gatewayV2Service,@@ -735,7 +743,14 @@ export const pamDiscoverySourceServiceFactory = (deps: TPamDiscoverySourceServic}));};- const importAccounts = async ({ projectId, sourceId, folderId, accounts, ...ctx }: TImportDiscoveredDTO) => {+ const importAccounts = async ({+ projectId,+ sourceId,+ folderId,+ accounts,+ auditLogInfo,+ ...ctx+ }: TImportDiscoveredDTO) => {await verifyAdmin(projectId, ctx);const source = await pamDiscoverySourceDAL.findById(sourceId);if (!source || source.projectId !== projectId) {@@ -743,6 +758,48 @@ export const pamDiscoverySourceServiceFactory = (deps: TPamDiscoverySourceServic}const { decryptor } = await getProjectCipher(projectId);+ const rotationLimit = pLimit(IMPORT_ROTATION_CONCURRENCY);++ const rotateImported = async (accountId: string, accountType: string, rotationAccountId: string) => {+ try {+ await pamAccountRotationService.setRotationAccount({ accountId, rotationAccountId, projectId, ...ctx });+ } catch (err) {+ return {+ rotationStatus: ROTATION_STATUS.Failed,+ rotationMessage: err instanceof Error ? err.message : "Failed to set the rotation account"+ };+ }+ await auditLogService.createAuditLog({+ ...auditLogInfo,+ orgId: ctx.actorOrgId,+ projectId,+ event: { type: EventType.PAM_ACCOUNT_SET_ROTATION_ACCOUNT, metadata: { accountId, rotationAccountId } }+ });++ const { rotationStatus, message } = await pamAccountRotationService+ .rotateNow({ accountId, projectId, ...ctx })+ .catch((err: unknown) => ({+ rotationStatus: ROTATION_STATUS.Failed,+ message: err instanceof Error ? err.message : "Rotation failed"+ }));+ await auditLogService.createAuditLog({+ ...auditLogInfo,+ orgId: ctx.actorOrgId,+ projectId,+ event: {+ type: EventType.PAM_ACCOUNT_ROTATE_CREDENTIALS,+ metadata: {+ accountId,+ accountType,+ rotationStatus,+ manual: true,+ rotationAccountId,+ ...(message ? { message } : {})+ }+ }+ });+ return { rotationAccountId, rotationStatus, rotationMessage: message };+ };const results = await Promise.all(accounts.map(async (item) => {@@ -785,11 +842,18 @@ export const pamDiscoverySourceServiceFactory = (deps: TPamDiscoverySourceServic// Flip this account's staged dependencies onto the managed account so they're rotation-eligible// immediately, without waiting for the next scan.await pamAccountDependencyDAL.backfillImported(discovered.id, account.id);++ // runs after the backfill so the rotation's dependency sync pushes the new password to them+ const { rotationAccountId } = item;+ const rotation = rotationAccountId+ ? await rotationLimit(() => rotateImported(account.id, discovered.accountType, rotationAccountId))+ : {};return {discoveredAccountId: item.discoveredAccountId,status: PamDiscoveryImportStatus.Imported,accountId: account.id,- name: item.name ?? discovered.name+ name: item.name ?? discovered.name,+ ...rotation};} catch (err) {return {diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-types.ts b/backend/src/ee/services/pam-discovery/pam-discovery-types.tsindex d661c7ba35..8a63c2bb0d 100644--- a/backend/src/ee/services/pam-discovery/pam-discovery-types.ts+++ b/backend/src/ee/services/pam-discovery/pam-discovery-types.ts@@ -1,3 +1,4 @@+import { AuditLogInfo } from "@app/ee/services/audit-log/audit-log-types";import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";import { PamAccountType } from "../pam/pam-enums";@@ -103,7 +104,8 @@ export type TImportDiscoveredDTO = {projectId: string;sourceId: string;folderId: string;- accounts: { discoveredAccountId: string; templateId: string; name?: string }[];+ accounts: { discoveredAccountId: string; templateId: string; name?: string; rotationAccountId?: string }[];+ auditLogInfo: AuditLogInfo;} & TActorContext;export type TListAccountDependenciesDTO = {diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex a13ab6b9c7..0f0c0b1063 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -4255,6 +4255,20 @@ export const registerRoutes = async (const pamDiscoveredAccountDAL = pamDiscoveredAccountDALFactory(db);const pamAccountDependencyDAL = pamAccountDependencyDALFactory(db);+ const pamAccountRotationService = pamAccountRotationServiceFactory({+ pamAccountDAL,+ permissionService,+ membershipDAL,+ membershipRoleDAL,+ kmsService,+ keyStore,+ gatewayV2Service,+ gatewayPoolService,+ pamAccountDependencyDAL,+ pamDiscoverySourceDAL,+ projectDAL+ });+const pamDiscoveryService = pamDiscoverySourceServiceFactory({orgDAL,pamDiscoverySourceDAL,@@ -4263,6 +4277,7 @@ export const registerRoutes = async (pamAccountDependencyDAL,pamAccountDAL,pamAccountService,+ pamAccountRotationService,permissionService,kmsService,gatewayV2DAL,@@ -4273,20 +4288,6 @@ export const registerRoutes = async (auditLogService});- const pamAccountRotationService = pamAccountRotationServiceFactory({- pamAccountDAL,- permissionService,- membershipDAL,- membershipRoleDAL,- kmsService,- keyStore,- gatewayV2Service,- gatewayPoolService,- pamAccountDependencyDAL,- pamDiscoverySourceDAL,- projectDAL- });-const pamAccountHeartbeatService = pamAccountHeartbeatServiceFactory({pamAccountDAL,gatewayV2Service,diff --git a/frontend/src/hooks/api/pam/types/index.ts b/frontend/src/hooks/api/pam/types/index.tsindex 8eeb4d67cd..8576d6a536 100644--- a/frontend/src/hooks/api/pam/types/index.ts+++ b/frontend/src/hooks/api/pam/types/index.ts@@ -128,7 +128,12 @@ export type TTriggerPamDiscoveryScanDTO = { sourceId: string; discoveryType: Pamexport type TImportPamDiscoveredAccountsDTO = {sourceId: string;folderId: string;- accounts: { discoveredAccountId: string; templateId: string; name?: string }[];+ accounts: {+ discoveredAccountId: string;+ templateId: string;+ name?: string;+ rotationAccountId?: string;+ }[];};export type TImportPamDiscoveredAccountResult = {@@ -136,6 +141,9 @@ export type TImportPamDiscoveredAccountResult = {status: string;accountId?: string;message?: string;+ rotationAccountId?: string;+ rotationStatus?: PamRotationStatus;+ rotationMessage?: string;};export type PamFolderPermissionSet = [diff --git a/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoverySourceDetailSheet.tsx b/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoverySourceDetailSheet.tsxindex 456e663fce..96d2c76d8e 100644--- a/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoverySourceDetailSheet.tsx+++ b/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoverySourceDetailSheet.tsx@@ -913,6 +913,7 @@ export const DiscoverySourceDetailSheet = ({ isOpen, sourceId, onOpenChange }: PisOpen={isImportOpen}onOpenChange={setIsImportOpen}sourceId={sourceId}+ credentialAccountId={source?.credentialAccountId}accounts={selectedAccounts}onImported={() => setSelected({})}/>diff --git a/frontend/src/pages/pam/PamDiscoveryPage/components/ImportDiscoveredModal.tsx b/frontend/src/pages/pam/PamDiscoveryPage/components/ImportDiscoveredModal.tsxindex 0e6febf9d3..8c9645030e 100644--- a/frontend/src/pages/pam/PamDiscoveryPage/components/ImportDiscoveredModal.tsx+++ b/frontend/src/pages/pam/PamDiscoveryPage/components/ImportDiscoveredModal.tsx@@ -3,6 +3,7 @@ import { useMemo, useState } from "react";import { createNotification } from "@app/components/notifications";import {Button,+ Combobox,Dialog,DialogContent,DialogFooter,@@ -15,12 +16,17 @@ import {SelectContent,SelectItem,SelectTrigger,- SelectValue+ SelectValue,+ Toggle} from "@app/components/v3";import {+ isRotatablePamAccountType,+ PamAccountAccessibilityIssue,PamAccountType,+ PamRotationStatus,TPamDiscoveredAccount,useImportPamDiscoveredAccounts,+ useListPamAccounts,useListPamAccountTemplates,useListPamFolders,usePamAccountTypeMap@@ -30,6 +36,7 @@ type Props = {isOpen: boolean;onOpenChange: (open: boolean) => void;sourceId: string;+ credentialAccountId?: string;accounts: TPamDiscoveredAccount[];onImported: () => void;};@@ -38,26 +45,53 @@ export const ImportDiscoveredModal = ({isOpen,onOpenChange,sourceId,+ credentialAccountId,accounts,onImported}: Props) => {const [folderId, setFolderId] = useState("");const [templateByType, setTemplateByType] = useState<Record<string, string>>({});+ const [rotateOnImport, setRotateOnImport] = useState(false);+ // null is a cleared selection; a type with no entry falls back to the source's credential account+ const [rotationAccountByType, setRotationAccountByType] = useState<Record<string, string | null>>(+ {}+ );const importAccounts = useImportPamDiscoveredAccounts();const { data: folders = [] } = useListPamFolders();const { data: templates = [] } = useListPamAccountTemplates();+ const { data: pamAccounts = [] } = useListPamAccounts();const { map: accountTypeMap } = usePamAccountTypeMap();const accountTypes = useMemo(() => Array.from(new Set(accounts.map((a) => a.accountType))),[accounts]);+ const rotatableTypes = accountTypes.filter(isRotatablePamAccountType);+ const isRotating = rotateOnImport && rotatableTypes.length > 0;++ // a rotation account authenticates with its own stored password, so one without it can't rotate+ const rotationCandidates = (type: string) =>+ pamAccounts.filter(+ (a) =>+ a.accountType === type &&+ !a.accessibilityIssues.includes(PamAccountAccessibilityIssue.NoCredential)+ );++ const rotationAccountIdFor = (type: string) => {+ const selected = rotationAccountByType[type];+ if (selected !== undefined) return selected;+ return rotationCandidates(type).some((a) => a.id === credentialAccountId)+ ? (credentialAccountId ?? null)+ : null;+ };const reset = () => {setFolderId("");setTemplateByType({});+ setRotateOnImport(false);+ setRotationAccountByType({});};const handleImport = () => {@@ -65,18 +99,32 @@ export const ImportDiscoveredModal = ({{sourceId,folderId,- accounts: accounts.map((a) => ({- discoveredAccountId: a.id,- templateId: templateByType[a.accountType]- }))+ accounts: accounts.map((a) => {+ const rotationAccountId =+ isRotating && isRotatablePamAccountType(a.accountType)+ ? rotationAccountIdFor(a.accountType)+ : null;+ return {+ discoveredAccountId: a.id,+ templateId: templateByType[a.accountType],+ ...(rotationAccountId ? { rotationAccountId } : {})+ };+ })},{onSuccess: (results) => {const imported = results.filter((r) => r.status === "imported").length;const failed = results.length - imported;+ const rotationFailures = results.filter(+ (r) => r.rotationStatus === PamRotationStatus.Failed+ );+ const rotationNote =+ rotationFailures.length > 0+ ? `. ${rotationFailures.length} could not be rotated: ${rotationFailures[0].rotationMessage}`+ : "";createNotification({- type: failed > 0 ? "info" : "success",- text: `Imported ${imported} account${imported === 1 ? "" : "s"}${failed > 0 ? `, ${failed} failed` : ""}`+ type: failed > 0 || rotationFailures.length > 0 ? "info" : "success",+ text: `Imported ${imported} account${imported === 1 ? "" : "s"}${failed > 0 ? `, ${failed} failed` : ""}${rotationNote}`});reset();onImported();@@ -144,8 +192,55 @@ export const ImportDiscoveredModal = ({);})}+ {rotatableTypes.length > 0 && (+ <Field>+ <div className="flex items-center justify-between gap-4">+ <FieldLabel htmlFor="rotate-on-import" className="mb-0">+ Rotate account passwords on import+ </FieldLabel>+ <Toggle+ id="rotate-on-import"+ variant="pam"+ checked={rotateOnImport}+ onCheckedChange={setRotateOnImport}+ />+ </div>+ </Field>+ )}++ {isRotating &&+ rotatableTypes.map((type) => {+ const typeName = accountTypeMap[type as PamAccountType]?.name ?? type;+ const candidates = rotationCandidates(type);+ const selectedId = rotationAccountIdFor(type);+ return (+ <Field key={`rotation-${type}`}>+ <FieldLabel htmlFor={`rotation-account-${type}`}>+ {typeName} Rotation Account+ </FieldLabel>+ <FieldContent>+ <Combobox+ id={`rotation-account-${type}`}+ value={candidates.find((a) => a.id === selectedId) ?? null}+ onValueChange={(val) =>+ setRotationAccountByType((prev) => ({ ...prev, [type]: val?.id ?? null }))+ }+ options={candidates}+ getOptionValue={(a) => a.id}+ getOptionLabel={(a) =>+ a.folderName ? `${a.folderName} / ${a.name}` : a.name+ }+ placeholder={`Select a ${typeName} account`}+ />+ </FieldContent>+ </Field>+ );+ })}+<p className="text-xs text-muted">- Imported accounts come in without a credential and stay unusable until one is added.+ {isRotating+ ? "A rotation account can only rotate accounts on its own host or domain. Accounts with no rotation account come in without a credential."+ : `Imported accounts come in without a credential and stay unusable until one is added${rotatableTypes.length > 0 ? " or their password is rotated" : ""}.`}</p></div>