Skip to content

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

feat(pam): staleness check for Windows discovery

x1fb7c33a2915
diff --git a/backend/src/db/migrations/20260730120000_pam-discovered-account-staleness.ts b/backend/src/db/migrations/20260730120000_pam-discovered-account-staleness.ts
new file mode 100644
index 0000000000..c2dd6af3f0
--- /dev/null
+++ b/backend/src/db/migrations/20260730120000_pam-discovered-account-staleness.ts
@@ -0,0 +1,31 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+
+export async function up(knex: Knex): Promise<void> {
+ const hasIsStale = await knex.schema.hasColumn(TableName.PamDiscoveredAccount, "isStale");
+ const hasLastDiscoveredAt = await knex.schema.hasColumn(TableName.PamDiscoveredAccount, "lastDiscoveredAt");
+
+ if (!hasIsStale || !hasLastDiscoveredAt) {
+ await knex.schema.alterTable(TableName.PamDiscoveredAccount, (t) => {
+ if (!hasIsStale) t.boolean("isStale").notNullable().defaultTo(false);
+ if (!hasLastDiscoveredAt) t.timestamp("lastDiscoveredAt");
+ });
+
+ if (!hasLastDiscoveredAt) {
+ await knex(TableName.PamDiscoveredAccount).update("lastDiscoveredAt", knex.ref("updatedAt"));
+ }
+ }
+}
+
+export async function down(knex: Knex): Promise<void> {
+ const hasIsStale = await knex.schema.hasColumn(TableName.PamDiscoveredAccount, "isStale");
+ const hasLastDiscoveredAt = await knex.schema.hasColumn(TableName.PamDiscoveredAccount, "lastDiscoveredAt");
+
+ if (hasIsStale || hasLastDiscoveredAt) {
+ await knex.schema.alterTable(TableName.PamDiscoveredAccount, (t) => {
+ if (hasIsStale) t.dropColumn("isStale");
+ if (hasLastDiscoveredAt) t.dropColumn("lastDiscoveredAt");
+ });
+ }
+}
diff --git a/backend/src/db/schemas/pam-discovered-accounts.ts b/backend/src/db/schemas/pam-discovered-accounts.ts
index 983d4b6e37..5e32ea62c3 100644
--- a/backend/src/db/schemas/pam-discovered-accounts.ts
+++ b/backend/src/db/schemas/pam-discovered-accounts.ts
@@ -18,7 +18,9 @@ export const PamDiscoveredAccountsSchema = z.object({
encryptedDetails: zodBuffer,
importedAccountId: z.string().uuid().nullable().optional(),
createdAt: z.date(),
- updatedAt: z.date()
+ updatedAt: z.date(),
+ isStale: z.boolean().default(false),
+ lastDiscoveredAt: z.date().nullable().optional()
});
export type TPamDiscoveredAccounts = z.infer<typeof PamDiscoveredAccountsSchema>;
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.ts
index 676ccdfac2..a79c496912 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
@@ -398,6 +398,54 @@ export const registerPamDiscoveryRouter = async (server: FastifyZodProvider) =>
}
});
+ server.route({
+ method: "GET",
+ url: "/:sourceId/unavailable-accounts",
+ schema: {
+ operationId: "listPamUnavailableAccounts",
+ description: "List imported accounts a PAM discovery source no longer finds in the environment",
+ tags: [ApiDocsTags.PamDiscovery],
+ params: z.object({ sourceId: z.string().uuid() }),
+ querystring: z.object({
+ search: z.string().optional(),
+ offset: z.coerce.number().min(0).default(0).optional(),
+ limit: z.coerce.number().min(1).max(100).default(20).optional()
+ }),
+ response: {
+ 200: z.object({
+ accounts: z.array(
+ z.object({
+ id: z.string(),
+ accountId: z.string(),
+ name: z.string(),
+ folderId: z.string().nullable(),
+ folderName: z.string().nullable(),
+ accountType: z.nativeEnum(PamAccountType),
+ lastDiscoveredAt: z.date().nullable()
+ })
+ ),
+ totalCount: z.number()
+ })
+ }
+ },
+ config: { rateLimit: readLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const { accounts, totalCount } = await server.services.pamDiscovery.listStale({
+ sourceId: req.params.sourceId,
+ projectId: req.internalPamProjectId,
+ search: req.query.search,
+ offset: req.query.offset,
+ limit: req.query.limit,
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod
+ });
+ return { accounts, totalCount };
+ }
+ });
+
server.route({
method: "POST",
url: "/:sourceId/discovered-accounts/import",
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.ts
index 62ee28ac28..be129bcb6c 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
@@ -931,6 +931,9 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServic
ResourcePermissionPamResourceActions.ManageRotation,
ctx
);
+ if (account.isStale) {
+ throw new BadRequestError({ message: "This account is no longer available in the environment" });
+ }
const readiness = getRotationReadiness({
accountId: account.id,
accountType: account.accountType,
@@ -1015,6 +1018,7 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServic
} | null> => {
const account = await pamAccountDAL.findByIdWithDetails(accountId);
if (!account) return null;
+ if (account.isStale) return null;
const rotation = getRotationConfig(account.templateSettings);
if (!rotation?.enabled) return null;
const result = await runRotation(account);
diff --git a/backend/src/ee/services/pam-account/pam-account-dal.ts b/backend/src/ee/services/pam-account/pam-account-dal.ts
index a23671d7f0..e78d223136 100644
--- a/backend/src/ee/services/pam-account/pam-account-dal.ts
+++ b/backend/src/ee/services/pam-account/pam-account-dal.ts
@@ -38,6 +38,13 @@ const gatewayExemptAccountTypes = (Object.entries(ACCOUNT_TYPE_CONFIGS) as [stri
.map(([type]) => `'${type}'`)
.join(", ");
+export const staleAccountExistsSql = (accountTable: string): string =>
+ `exists (
+ select 1 from "${TableName.PamDiscoveredAccount}"
+ where "${TableName.PamDiscoveredAccount}"."importedAccountId" = "${accountTable}"."id"
+ and "${TableName.PamDiscoveredAccount}"."isStale" = true
+ )`;
+
export const accountAccessibilitySql = (accountTable: string, templateTable: string): string =>
`(
("${templateTable}"."type" in (${gatewayExemptAccountTypes})
@@ -54,6 +61,7 @@ export const accountAccessibilitySql = (accountTable: string, templateTable: str
"${templateTable}"."settings"->'recordingS3Config'
) is not null
))
+ and not ${staleAccountExistsSql(accountTable)}
)`;
type TPamAccountTemplateInheritedFields = {
@@ -84,6 +92,7 @@ export type TPamAccountListItem = Pick<
accountType: string;
templateName: string;
folderName: string | null;
+ isStale: boolean;
};
export type TPamAccountDetail = TPamAccounts &
@@ -93,6 +102,7 @@ export type TPamAccountDetail = TPamAccounts &
templatePolicies: unknown;
templateSettings: unknown;
folderName: string | null;
+ isStale: boolean;
};
export type TPamAccountDALFactory = ReturnType<typeof pamAccountDALFactory>;
@@ -174,7 +184,8 @@ export const pamAccountDALFactory = (db: TDbClient) => {
`${TableName.PamAccountTemplate}.gatewayId as templateGatewayId`,
`${TableName.PamAccountTemplate}.gatewayPoolId as templateGatewayPoolId`,
`${TableName.PamAccountTemplate}.recordingConnectionId as templateRecordingConnectionId`,
- `${TableName.PamFolder}.name as folderName`
+ `${TableName.PamFolder}.name as folderName`,
+ db.raw(`${staleAccountExistsSql(TableName.PamAccount)} as "isStale"`)
)
.orderBy(`${TableName.PamFolder}.name`, "asc")
.orderBy(`${TableName.PamAccount}.name`, "asc");
@@ -199,7 +210,8 @@ export const pamAccountDALFactory = (db: TDbClient) => {
`${TableName.PamAccountTemplate}.gatewayId as templateGatewayId`,
`${TableName.PamAccountTemplate}.gatewayPoolId as templateGatewayPoolId`,
`${TableName.PamAccountTemplate}.recordingConnectionId as templateRecordingConnectionId`,
- `${TableName.PamFolder}.name as folderName`
+ `${TableName.PamFolder}.name as folderName`,
+ db.raw(`${staleAccountExistsSql(TableName.PamAccount)} as "isStale"`)
];
const findByIdWithDetails = async (accountId: string, tx?: Knex): Promise<TPamAccountDetail | null> => {
@@ -235,7 +247,9 @@ export const pamAccountDALFactory = (db: TDbClient) => {
.whereNotNull(`${TableName.PamAccount}.nextRotationAt`)
.where(`${TableName.PamAccount}.nextRotationAt`, "<=", now)
.whereIn(`${TableName.PamAccountTemplate}.type`, ROTATABLE_TYPE_VALUES)
- .whereRaw(`"${TableName.PamAccountTemplate}"."settings"->'rotation'->>'enabled' = 'true'`);
+ .whereRaw(`"${TableName.PamAccountTemplate}"."settings"->'rotation'->>'enabled' = 'true'`)
+ // a stale account (deleted/disabled in the environment) must not keep getting rotated
+ .whereRaw(`not ${staleAccountExistsSql(TableName.PamAccount)}`);
// Only ready accounts get a nextRotationAt, so every due row here is already rotation-ready.
const findAccountsToRotate = async (now: Date, limit: number, tx?: Knex): Promise<TPamAccountDetail[]> => {
diff --git a/backend/src/ee/services/pam-account/pam-account-schemas.ts b/backend/src/ee/services/pam-account/pam-account-schemas.ts
index 9bd6c6f338..13f18bfd27 100644
--- a/backend/src/ee/services/pam-account/pam-account-schemas.ts
+++ b/backend/src/ee/services/pam-account/pam-account-schemas.ts
@@ -839,7 +839,8 @@ export enum PamAccountAccessibilityIssue {
NoGateway = "no-gateway",
NoRecordingConfig = "no-recording-config",
NoCredential = "no-credential",
- NoApprovalConfig = "no-approval-config"
+ NoApprovalConfig = "no-approval-config",
+ Stale = "stale"
}
export const accountTypeRequiresRecording = (accountType: PamAccountType): boolean =>
@@ -863,9 +864,12 @@ export const getAccountAccessibilityIssues = (account: {
settingsOverrides?: unknown;
templateSettings: unknown;
credentialConfigured: boolean;
+ isStale?: boolean;
}): PamAccountAccessibilityIssue[] => {
const issues: PamAccountAccessibilityIssue[] = [];
+ if (account.isStale) issues.push(PamAccountAccessibilityIssue.Stale);
+
if (
accountTypeRequiresGateway(account.accountType as PamAccountType) &&
!account.gatewayId &&
diff --git a/backend/src/ee/services/pam-account/pam-account-service.ts b/backend/src/ee/services/pam-account/pam-account-service.ts
index 48cd2c9867..1220280e84 100644
--- a/backend/src/ee/services/pam-account/pam-account-service.ts
+++ b/backend/src/ee/services/pam-account/pam-account-service.ts
@@ -172,6 +172,7 @@ export const pamAccountServiceFactory = (deps: TPamAccountServiceFactoryDep) =>
settingsOverrides?: unknown;
templateSettings: unknown;
credentialConfigured: boolean;
+ isStale?: boolean;
}) => {
const accessibilityIssues = getAccountAccessibilityIssues(a);
return { isAccessible: accessibilityIssues.length === 0, accessibilityIssues };
diff --git a/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-factory.ts b/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-factory.ts
index de6a4594bd..50ad5ad1ae 100644
--- a/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-factory.ts
+++ b/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-factory.ts
@@ -322,6 +322,7 @@ export const activeDirectoryDiscoveryFactory: TPamDiscoveryFactory = ({
const machineErrors: TDiscoveryMachineError[] = [];
const dependencies: TDiscoveredDependency[] = [];
const scannedDependencyMachines: string[] = [];
+ const scannedAccountMachines: string[] = [];
// Both local-account and dependency sweeps need the machine list from LDAP.
const enumerateComputers = Boolean(config.scanLocalAccounts || config.discoverDependencies);
@@ -444,6 +445,7 @@ export const activeDirectoryDiscoveryFactory: TPamDiscoveryFactory = ({
}
});
}
+ scannedAccountMachines.push(`${domain}:${computer.objectGUID}`);
} catch (err) {
const message = err instanceof Error ? err.message : "WinRM enumeration failed";
logger.warn(err, `PAM AD discovery failed to enumerate local accounts [host=${host}]`);
@@ -492,7 +494,7 @@ export const activeDirectoryDiscoveryFactory: TPamDiscoveryFactory = ({
}
}
- return { accounts: discovered, machineErrors, dependencies, scannedDependencyMachines };
+ return { accounts: discovered, machineErrors, dependencies, scannedDependencyMachines, scannedAccountMachines };
};
return { validateConnection, scan };
diff --git a/backend/src/ee/services/pam-discovery/pam-discovered-account-dal.ts b/backend/src/ee/services/pam-discovery/pam-discovered-account-dal.ts
index f9fe4703ad..610dd5fd7a 100644
--- a/backend/src/ee/services/pam-discovery/pam-discovered-account-dal.ts
+++ b/backend/src/ee/services/pam-discovery/pam-discovered-account-dal.ts
@@ -16,13 +16,14 @@ export const pamDiscoveredAccountDALFactory = (db: TDbClient) => {
data: { accountType: string; name: string; encryptedDetails: Buffer },
tx?: Knex
): Promise<{ isNew: boolean }> => {
+ const seen = { lastDiscoveredAt: new Date(), isStale: false };
const existing = await (tx || db)(TableName.PamDiscoveredAccount).where({ discoverySourceId, fingerprint }).first();
if (existing) {
- if (existing.importedAccountId) return { isNew: false };
- await (tx || db)(TableName.PamDiscoveredAccount).where({ id: existing.id }).update(data);
+ const update = existing.importedAccountId ? seen : { ...data, ...seen };
+ await (tx || db)(TableName.PamDiscoveredAccount).where({ id: existing.id }).update(update);
return { isNew: false };
}
- await (tx || db)(TableName.PamDiscoveredAccount).insert({ discoverySourceId, fingerprint, ...data });
+ await (tx || db)(TableName.PamDiscoveredAccount).insert({ discoverySourceId, fingerprint, ...data, ...seen });
return { isNew: true };
};
@@ -47,12 +48,64 @@ export const pamDiscoveredAccountDALFactory = (db: TDbClient) => {
return { accounts, totalCount: Number(countResult?.count ?? 0) };
};
- // Just the columns needed to map a run-as fingerprint to its account, without pulling every row's
- // encryptedDetails buffer into memory (a large domain can have tens of thousands of discovered accounts).
+ // Imported accounts this source no longer finds in the environment, joined to the managed account for its
+ // current name/folder (the review surface for blocked accounts). Staged rows are never stale (they're deleted).
+ const listStale = async (
+ discoverySourceId: string,
+ { search, offset, limit }: { search?: string; offset?: number; limit?: number } = {}
+ ) => {
+ const baseQuery = db
+ .replicaNode()(TableName.PamDiscoveredAccount)
+ .where(`${TableName.PamDiscoveredAccount}.discoverySourceId`, discoverySourceId)
+ .where(`${TableName.PamDiscoveredAccount}.isStale`, true)
+ .whereNotNull(`${TableName.PamDiscoveredAccount}.importedAccountId`)
+ .join(TableName.PamAccount, `${TableName.PamDiscoveredAccount}.importedAccountId`, `${TableName.PamAccount}.id`)
+ .leftJoin(TableName.PamFolder, `${TableName.PamAccount}.folderId`, `${TableName.PamFolder}.id`);
+ if (search) void baseQuery.andWhere(`${TableName.PamAccount}.name`, "ilike", `%${sanitizeSqlLikeString(search)}%`);
+
+ const countQuery = baseQuery
+ .clone()
+ .clearSelect()
+ .count(`${TableName.PamDiscoveredAccount}.id as count`)
+ .first<{ count: string }>();
+
+ const dataQuery = baseQuery
+ .clone()
+ .select(
+ `${TableName.PamDiscoveredAccount}.id`,
+ `${TableName.PamDiscoveredAccount}.accountType`,
+ `${TableName.PamDiscoveredAccount}.lastDiscoveredAt`,
+ `${TableName.PamDiscoveredAccount}.importedAccountId`,
+ `${TableName.PamAccount}.name as accountName`,
+ `${TableName.PamAccount}.folderId`,
+ `${TableName.PamFolder}.name as folderName`
+ )
+ .orderBy(`${TableName.PamAccount}.name`, "asc");
+ if (limit) void dataQuery.limit(limit);
+ if (offset) void dataQuery.offset(offset);
+
+ const [countResult, accounts] = await Promise.all([countQuery, dataQuery]);
+ return { accounts, totalCount: Number(countResult?.count ?? 0) };
+ };
+
+ // Just the columns needed to map a run-as fingerprint to its account (and to reconcile staleness), without
+ // pulling every row's encryptedDetails buffer into memory (a large domain can have tens of thousands of rows).
const findFingerprintLinks = async (discoverySourceId: string, tx?: Knex) =>
(tx || db.replicaNode())(TableName.PamDiscoveredAccount)
.where({ discoverySourceId })
- .select("id", "fingerprint", "importedAccountId");
+ .select("id", "fingerprint", "importedAccountId", "accountType");
+
+ // Flag imported accounts a scan no longer found (staged ones are deleted instead, see deleteByIds). The
+ // caller scopes which ids; `= ANY(?)` binds the list as one param.
+ const markStale = async (ids: string[], tx?: Knex): Promise<void> => {
+ if (!ids.length) return;
+ await (tx || db)(TableName.PamDiscoveredAccount).whereRaw(`"id" = ANY(?::uuid[])`, [ids]).update({ isStale: true });
+ };
+
+ const deleteByIds = async (ids: string[], tx?: Knex): Promise<void> => {
+ if (!ids.length) return;
+ await (tx || db)(TableName.PamDiscoveredAccount).whereRaw(`"id" = ANY(?::uuid[])`, [ids]).delete();
+ };
- return { ...orm, upsertByFingerprint, listStaged, findFingerprintLinks };
+ return { ...orm, upsertByFingerprint, listStaged, listStale, findFingerprintLinks, markStale, deleteByIds };
};
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.ts
index 454946aed7..bda55b20c8 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
@@ -451,11 +451,8 @@ export const pamDiscoverySourceServiceFactory = (deps: TPamDiscoverySourceServic
});
const controller = new AbortController();
- const { accounts, machineErrors, dependencies, scannedDependencyMachines } = await withScanTimeout(
- provider.scan(controller.signal),
- controller,
- MAX_SCAN_DURATION_MS
- );
+ const { accounts, machineErrors, dependencies, scannedDependencyMachines, scannedAccountMachines } =
+ await withScanTimeout(provider.scan(controller.signal), controller, MAX_SCAN_DURATION_MS);
const upsertLimit = pLimit(DISCOVERED_UPSERT_CONCURRENCY);
const results = await Promise.all(
accounts.map((d) =>
@@ -469,6 +466,24 @@ export const pamDiscoverySourceServiceFactory = (deps: TPamDiscoverySourceServic
)
);
+ // reconcile accounts a re-checked scope no longer returned
+ const seenFingerprints = new Set(accounts.map((a) => a.fingerprint));
+ const scannedMachines = new Set(scannedAccountMachines);
+ const storedAccounts = await pamDiscoveredAccountDAL.findFingerprintLinks(sourceId);
+ const goneAccounts = storedAccounts.filter((a) => {
+ if (seenFingerprints.has(a.fingerprint)) return false;
+ if (a.accountType === PamAccountType.WindowsAd) return true;
+ if (a.accountType === PamAccountType.Windows) {
+ // local-account fingerprint is `${domain}:${computerObjectGUID}:${username}`; the machine key is the
+ // first two segments, matching what the provider reports as re-checked
+ const machineKey = a.fingerprint.split(":").slice(0, 2).join(":");
+ return scannedMachines.has(machineKey);
+ }
+ return false;
+ });
+ await pamDiscoveredAccountDAL.markStale(goneAccounts.filter((a) => a.importedAccountId).map((a) => a.id));
+ await pamDiscoveredAccountDAL.deleteByIds(goneAccounts.filter((a) => !a.importedAccountId).map((a) => a.id));
+
// Persist dependencies from the sweep, anchoring each to its run-as account by fingerprint. null =
// dependency discovery did not run this scan, so the summary omits the dependencies clause.
let dependencyCount: number | null = null;
@@ -639,6 +654,27 @@ export const pamDiscoverySourceServiceFactory = (deps: TPamDiscoverySourceServic
};
};
+ const listStale = async ({ projectId, sourceId, search, offset, limit, ...ctx }: TListDiscoveredDTO) => {
+ await verifyAdmin(projectId, ctx);
+ const source = await pamDiscoverySourceDAL.findById(sourceId);
+ if (!source || source.projectId !== projectId) {
+ throw new NotFoundError({ message: `Discovery source with ID '${sourceId}' not found` });
+ }
+ const { accounts, totalCount } = await pamDiscoveredAccountDAL.listStale(sourceId, { search, offset, limit });
+ return {
+ accounts: accounts.map((a) => ({
+ id: a.id,
+ accountId: a.importedAccountId as string,
+ name: a.accountName as string,
+ folderId: (a.folderId as string | null) ?? null,
+ folderName: (a.folderName as string | null) ?? null,
+ accountType: a.accountType as PamAccountType,
+ lastDiscoveredAt: (a.lastDiscoveredAt as Date | null) ?? null
+ })),
+ totalCount
+ };
+ };
+
const listAccountDependencies = async ({ accountId, projectId, ...ctx }: TListAccountDependenciesDTO) => {
const account = await pamAccountDAL.findByIdWithDetails(accountId);
if (!account || account.projectId !== projectId) {
@@ -778,6 +814,7 @@ export const pamDiscoverySourceServiceFactory = (deps: TPamDiscoverySourceServic
runScan,
listRuns,
listDiscovered,
+ listStale,
importAccounts,
listAccountDependencies
};
diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-types.ts b/backend/src/ee/services/pam-discovery/pam-discovery-types.ts
index 9e69e0683f..d661c7ba35 100644
--- a/backend/src/ee/services/pam-discovery/pam-discovery-types.ts
+++ b/backend/src/ee/services/pam-discovery/pam-discovery-types.ts
@@ -27,6 +27,7 @@ export type TDiscoveryScanResult = {
dependencies: TDiscoveredDependency[];
// Machines whose dependency sweep completed, so reconciliation only prunes what it actually re-checked.
scannedDependencyMachines: string[];
+ scannedAccountMachines: string[];
};
export type TPamDiscoveryProvider = {
diff --git a/backend/src/ee/services/pam-discovery/unix/unix-discovery-factory.ts b/backend/src/ee/services/pam-discovery/unix/unix-discovery-factory.ts
index f8807accd9..83705b5b81 100644
--- a/backend/src/ee/services/pam-discovery/unix/unix-discovery-factory.ts
+++ b/backend/src/ee/services/pam-discovery/unix/unix-discovery-factory.ts
@@ -189,7 +189,8 @@ export const unixDiscoveryFactory: TPamDiscoveryFactory = ({
accounts: discovered.slice(0, MAX_ACCOUNTS_PER_SCAN),
machineErrors: results.flatMap((r) => (r.error ? [r.error] : [])),
dependencies: [],
- scannedDependencyMachines: []
+ scannedDependencyMachines: [],
+ scannedAccountMachines: []
};
};
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 482d614bbd..3ef07a8487 100644
--- a/backend/src/ee/services/pam-session/pam-session-service.ts
+++ b/backend/src/ee/services/pam-session/pam-session-service.ts
@@ -425,6 +425,10 @@ export const pamSessionServiceFactory = ({
}) => {
const account = await resolveAccountByPath(projectId, path);
+ if (account.isStale) {
+ throw new ForbiddenRequestError({ message: "This account is no longer available in the environment" });
+ }
+
const policy = resolveAccessControls(account.templatePolicies);
const { requiresApproval } = policy;
diff --git a/backend/src/ee/services/pam-web-access/pam-web-access-service.ts b/backend/src/ee/services/pam-web-access/pam-web-access-service.ts
index 677d03492b..7065dcd626 100644
--- a/backend/src/ee/services/pam-web-access/pam-web-access-service.ts
+++ b/backend/src/ee/services/pam-web-access/pam-web-access-service.ts
@@ -167,6 +167,10 @@ export const pamWebAccessServiceFactory = ({
throw new NotFoundError({ message: `Account with ID '${accountId}' not found` });
}
+ if (account.isStale) {
+ throw new ForbiddenRequestError({ message: "This account is no longer available in the environment" });
+ }
+
if (!SESSION_HANDLERS[account.accountType as PamAccountType]) {
throw new BadRequestError({ message: "Web access is not supported for this account type" });
}
diff --git a/backend/src/ee/services/pam/CLAUDE.md b/backend/src/ee/services/pam/CLAUDE.md
index 17a8884e36..56c753769b 100644
--- a/backend/src/ee/services/pam/CLAUDE.md
+++ b/backend/src/ee/services/pam/CLAUDE.md
@@ -95,6 +95,12 @@ fingerprint dedupe. Discovery runs everything **through the gateway** (SSH-exec
so `ssh2` is never used on the backend and scans produce no session rows, recordings, or session audits.
Current types: Active Directory and Unix.
+**Staleness (Windows).** After a completed scan, discovered accounts it no longer finds are reconciled:
+never-imported ones are deleted, imported ones are flagged stale (reappearing self-heals). Only accounts in a
+re-checked scope are touched, so an unreachable host can't mass-flag (same guardrail as dependency pruning). A
+managed account's staleness is derived from its discovered row (not stored on the account); a stale one becomes
+an accessibility issue — blocked from rotation and session launch — and is listed on the source's Unavailable tab.
+
## Credential Rotation
`pam-account-rotation/`: scheduled + on-demand SQL password rotation (Postgres/MySQL/MSSQL). Rotation
diff --git a/frontend/src/hooks/api/pam/queries.tsx b/frontend/src/hooks/api/pam/queries.tsx
index 4b29b1bb45..997e7f725f 100644
--- a/frontend/src/hooks/api/pam/queries.tsx
+++ b/frontend/src/hooks/api/pam/queries.tsx
@@ -39,7 +39,8 @@ import {
TPamMembersData,
TPamResourceRole,
TPamRotationCandidateGroup,
- TPamSession
+ TPamSession,
+ TPamUnavailableAccount
} from "./types";
// Resolves the org's PAM project, creating it on first access (lazy bootstrap on the backend).
@@ -95,6 +96,10 @@ export const pamKeys = {
sourceId: string,
params?: { search?: string; offset?: number; limit?: number }
) => [...pamKeys.discovery(), "discovered", sourceId, params] as const,
+ listUnavailableAccounts: (
+ sourceId: string,
+ params?: { search?: string; offset?: number; limit?: number }
+ ) => [...pamKeys.discovery(), "unavailable", sourceId, params] as const,
accountRotation: (accountId: string) => [...pamKeys.account(), "rotation", accountId] as const,
accountDependencies: (accountId: string) =>
[...pamKeys.account(), "dependencies", accountId] as const,
@@ -562,6 +567,24 @@ export const useListPamDiscoveredAccounts = (
});
};
+export const useListPamUnavailableAccounts = (
+ sourceId: string,
+ params?: { search?: string; offset?: number; limit?: number }
+) => {
+ return useQuery({
+ queryKey: pamKeys.listUnavailableAccounts(sourceId, params),
+ queryFn: async () => {
+ const { data } = await apiRequest.get<{
+ accounts: TPamUnavailableAccount[];
+ totalCount: number;
+ }>(`/api/v1/pam/discovery-sources/${sourceId}/unavailable-accounts`, { params });
+ return data;
+ },
+ enabled: Boolean(sourceId),
+ placeholderData: (prev) => prev
+ });
+};
+
export const useListPamAccountDependencies = (accountId: string) => {
return useQuery({
queryKey: pamKeys.accountDependencies(accountId),
diff --git a/frontend/src/hooks/api/pam/types/index.ts b/frontend/src/hooks/api/pam/types/index.ts
index b575d3fab7..81cd347066 100644
--- a/frontend/src/hooks/api/pam/types/index.ts
+++ b/frontend/src/hooks/api/pam/types/index.ts
@@ -74,6 +74,17 @@ export type TPamDiscoveredAccount = {
dependencies: TPamDependency[];
};
+// an imported account a source no longer finds in the environment (rotation + access blocked)
+export type TPamUnavailableAccount = {
+ id: string;
+ accountId: string;
+ name: string;
+ folderId: string | null;
+ folderName: string | null;
+ accountType: PamAccountType;
+ lastDiscoveredAt: string | null;
+};
+
export type TPamAccountDependency = TPamDependency & {
data: Record<string, unknown> | null;
rotationStatus: PamRotationStatus | null;
@@ -173,7 +184,8 @@ export enum PamAccountAccessibilityIssue {
NoGateway = "no-gateway",
NoRecordingConfig = "no-recording-config",
NoCredential = "no-credential",
- NoApprovalConfig = "no-approval-config"
+ NoApprovalConfig = "no-approval-config",
+ Stale = "stale"
}
export const accountTypeRequiresRecording = (type: PamAccountType): boolean =>
diff --git a/frontend/src/hooks/usePamSheetState.ts b/frontend/src/hooks/usePamSheetState.ts
index f65c87ad8a..50afd2104d 100644
--- a/frontend/src/hooks/usePamSheetState.ts
+++ b/frontend/src/hooks/usePamSheetState.ts
@@ -10,7 +10,8 @@ export enum PamSheetTab {
General = "general",
Rotation = "rotation",
Dependencies = "dependencies",
- Approvals = "approvals"
+ Approvals = "approvals",
+ Unavailable = "unavailable"
}
export const pamSheetSearchParams = z.object({
diff --git a/frontend/src/pages/pam/PamAccountsPage/components/AccountDetailSheet.tsx b/frontend/src/pages/pam/PamAccountsPage/components/AccountDetailSheet.tsx
index 2fcd1fa95c..bb97d7b485 100644
--- a/frontend/src/pages/pam/PamAccountsPage/components/AccountDetailSheet.tsx
+++ b/frontend/src/pages/pam/PamAccountsPage/components/AccountDetailSheet.tsx
@@ -108,7 +108,7 @@ type ResolvedMember = {
};
// Maps each accessibility issue to the tab where it can be resolved
-const ISSUE_TO_TAB: Record<PamAccountAccessibilityIssue, PamSheetTab> = {
+const ISSUE_TO_TAB: Partial<Record<PamAccountAccessibilityIssue, PamSheetTab>> = {
[PamAccountAccessibilityIssue.NoCredential]: PamSheetTab.Configuration,
[PamAccountAccessibilityIssue.NoGateway]: PamSheetTab.Advanced,
[PamAccountAccessibilityIssue.NoRecordingConfig]: PamSheetTab.Advanced,
@@ -862,7 +862,9 @@ export const AccountDetailSheet = ({ isOpen, accountId, onOpenChange }: Props) =
);
const tabsWithIssues = new Set(
- (account?.accessibilityIssues ?? []).map((issue) => ISSUE_TO_TAB[issue])
+ (account?.accessibilityIssues ?? [])
+ .map((issue) => ISSUE_TO_TAB[issue])
+ .filter((t): t is PamSheetTab => Boolean(t))
);
const conn = (account?.connectionDetails ?? {}) as Record<string, unknown>;
diff --git a/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoverySourceDetailSheet.tsx b/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoverySourceDetailSheet.tsx
index bc050b87e6..235ad8b4aa 100644
--- a/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoverySourceDetailSheet.tsx
+++ b/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoverySourceDetailSheet.tsx
@@ -56,6 +56,7 @@ import {
useListPamDiscoveryRuns,
useListPamDiscoverySources,
useListPamDiscoveryTypes,
+ useListPamUnavailableAccounts,
usePamAccountTypeMap,
useTriggerPamDiscoveryScan,
useUpdatePamDiscoverySource
@@ -375,10 +376,28 @@ export const DiscoverySourceDetailSheet = ({ isOpen, sourceId, onOpenChange }: P
});
const triggerScan = useTriggerPamDiscoveryScan();
+ const [staleSearch, setStaleSearch] = useState("");
+ const [debouncedStaleSearch] = useDebounce(staleSearch);
+ const [stalePage, setStalePage] = useState(1);
+ const [stalePerPage, setStalePerPage] = useState(() =>
+ getUserTablePreference("pamUnavailableAccountsTable", PreferenceKey.PerPage, 20)
+ );
+ const staleOffset = (stalePage - 1) * stalePerPage;
+ const { data: { accounts: unavailable = [], totalCount: unavailableTotal = 0 } = {} } =
+ useListPamUnavailableAccounts(sourceId ?? "", {
+ search: debouncedStaleSearch,
+ offset: staleOffset,
+ limit: stalePerPage
+ });
+
useEffect(() => {
setPage(1);
}, [debouncedSearch]);
+ useEffect(() => {
+ setStalePage(1);
+ }, [debouncedStaleSearch]);
+
const queryClient = useQueryClient();
const latestRunStatus = runs[0]?.status;
const prevRunStatus = useRef(latestRunStatus);
@@ -562,6 +581,120 @@ export const DiscoverySourceDetailSheet = ({ isOpen, sourceId, onOpenChange }: P
</div>
);
+ const sq = staleSearch.trim().toLowerCase();
+ const visibleUnavailable = sq
+ ? unavailable.filter((a) => a.name.toLowerCase().includes(sq))
+ : unavailable;
+
+ const unavailableTab: ReactNode = (
+ <div className="flex flex-1 flex-col gap-4 p-4">
+ <Card>
+ <CardHeader className="border-b">
+ <CardTitle className="text-base">Unavailable Accounts</CardTitle>
+ <CardDescription>
+ Imported accounts the latest scan no longer finds in the environment. Rotation and
+ access are blocked until they are rediscovered.
+ </CardDescription>
+ </CardHeader>
+ <CardContent className="flex flex-col gap-4">
+ <InputGroup>
+ <InputGroupAddon align="inline-start">
+ <Search />
+ </InputGroupAddon>
+ <InputGroupInput
+ placeholder="Search accounts..."
+ value={staleSearch}
+ onChange={(e) => setStaleSearch(e.target.value)}
+ />
+ </InputGroup>
+
+ {unavailableTotal === 0 ? (
+ <Empty className="border">
+ <EmptyHeader>
+ <EmptyTitle>
+ {debouncedStaleSearch
+ ? "No accounts match your search."
+ : "No unavailable accounts. Everything imported is still present in the environment."}
+ </EmptyTitle>
+ </EmptyHeader>
+ </Empty>
+ ) : (
+ <>
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>Name</TableHead>
+ <TableHead className="w-40">Folder</TableHead>
+ <TableHead className="w-40">Type</TableHead>
+ <TableHead className="w-48">Last seen</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {visibleUnavailable.map((account) => {
+ const typeDetails = accountTypeMap[account.accountType as PamAccountType];
+ return (
+ <TableRow key={account.id}>
+ <TableCell className="font-medium text-foreground">
+ <Link
+ to="/organizations/$orgId/pam/accounts"
+ params={{ orgId: currentOrg.id }}
+ search={{
+ accountId: account.accountId,
+ folderId: account.folderId ?? undefined
+ }}
+ className="hover:underline"
+ >
+ <HighlightText text={account.name} highlight={staleSearch} />
+ </Link>
+ </TableCell>
+ <TableCell className="text-muted">{account.folderName ?? "-"}</TableCell>
+ <TableCell>
+ <div className="flex items-center gap-2">
+ {typeDetails && (
+ <img
+ src={`/images/integrations/${typeDetails.icon}`}
+ alt={typeDetails.name}
+ className="size-5 shrink-0 rounded-sm"
+ />
+ )}
+ <span className="text-sm">
+ {typeDetails?.name ?? account.accountType}
+ </span>
+ </div>
+ </TableCell>
+ <TableCell className="text-muted">
+ {account.lastDiscoveredAt
+ ? format(new Date(account.lastDiscoveredAt), "MMM d, yyyy h:mm a")
+ : "-"}
+ </TableCell>
+ </TableRow>
+ );
+ })}
+ </TableBody>
+ </Table>
+
+ <Pagination
+ count={unavailableTotal}
+ page={stalePage}
+ perPage={stalePerPage}
+ onChangePage={setStalePage}
+ onChangePerPage={(newPerPage) => {
+ setStalePerPage(newPerPage);
+ setStalePage(1);
+ setUserTablePreference(
+ "pamUnavailableAccountsTable",
+ PreferenceKey.PerPage,
+ newPerPage
+ );
+ }}
+ />
+ </>
+ )}
+ </CardContent>
+ </Card>
+ </div>
+ );
+
const runsTab: ReactNode = (
<div className="flex flex-1 flex-col gap-4 p-4">
<Card>
@@ -661,6 +794,7 @@ export const DiscoverySourceDetailSheet = ({ isOpen, sourceId, onOpenChange }: P
const tabContent: Partial<Record<PamSheetTab, ReactNode>> = {
[PamSheetTab.General]: stagedTab,
+ [PamSheetTab.Unavailable]: unavailableTab,
[PamSheetTab.Runs]: runsTab,
[PamSheetTab.Configuration]: source ? (
<ConfigurationTab source={source} onDirtyChange={setIsFormDirty} />
@@ -683,6 +817,8 @@ export const DiscoverySourceDetailSheet = ({ isOpen, sourceId, onOpenChange }: P
setSelected({});
setSearch("");
setPage(1);
+ setStaleSearch("");
+ setStalePage(1);
}
onOpenChange(open);
}}
diff --git a/frontend/src/pages/pam/components/AccountAccessibilityBadge.tsx b/frontend/src/pages/pam/components/AccountAccessibilityBadge.tsx
index f67387bd5b..7dd8177151 100644
--- a/frontend/src/pages/pam/components/AccountAccessibilityBadge.tsx
+++ b/frontend/src/pages/pam/components/AccountAccessibilityBadge.tsx
@@ -8,7 +8,9 @@ const ISSUE_LABELS: Record<PamAccountAccessibilityIssue, string> = {
[PamAccountAccessibilityIssue.NoRecordingConfig]: "No recording bucket is configured",
[PamAccountAccessibilityIssue.NoCredential]: "No password is set",
[PamAccountAccessibilityIssue.NoApprovalConfig]:
- "No approvers are configured for its folder. Ask a folder admin to add approvers under the folder's Approvals tab."
+ "No approvers are configured for its folder. Ask a folder admin to add approvers under the folder's Approvals tab.",
+ [PamAccountAccessibilityIssue.Stale]:
+ "It is no longer present in the environment. Rotation and access are blocked until it is rediscovered."
};
type Props = {
@@ -34,10 +36,10 @@ export const AccountAccessibilityBadge = ({ issues }: Props) => {
</TooltipTrigger>
<TooltipContent className="max-w-xs">
{issues.length === 1 ? (
- <p>This account can&apos;t be used yet: {formatSingleIssue(ISSUE_LABELS[issues[0]])}</p>
+ <p>This account can&apos;t be used: {formatSingleIssue(ISSUE_LABELS[issues[0]])}</p>
) : (
<>
- <p className="mb-1 font-medium">This account can&apos;t be used yet</p>
+ <p className="mb-1 font-medium">This account can&apos;t be used</p>
<ul className="list-inside list-disc">
{issues.map((issue) => (
<li key={issue}>{ISSUE_LABELS[issue]}</li>
diff --git a/frontend/src/pages/pam/components/pamResourceTabs.ts b/frontend/src/pages/pam/components/pamResourceTabs.ts
index 634fe4bfe1..b626212ba9 100644
--- a/frontend/src/pages/pam/components/pamResourceTabs.ts
+++ b/frontend/src/pages/pam/components/pamResourceTabs.ts
@@ -6,6 +6,7 @@ import {
Settings,
Settings2,
ShieldCheck,
+ TriangleAlert,
Users
} from "lucide-react";
@@ -74,6 +75,7 @@ export const PAM_TEMPLATE_TABS: PamResourceTab[] = [
export const PAM_DISCOVERY_TABS: PamResourceTab[] = [
{ value: PamSheetTab.General, label: "Staged Accounts", icon: FolderOpen },
+ { value: PamSheetTab.Unavailable, label: "Unavailable", icon: TriangleAlert },
{ value: PamSheetTab.Runs, label: "Runs", icon: History },
{ value: PamSheetTab.Configuration, label: "Configuration", icon: Settings }
];