Skip to content

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

pam: tenant-scope dependencies, permission-filter shared identity, idempotent import

bernie-g2fe430a8ec66
diff --git a/backend/src/db/migrations/20260720183403_pam-account-dependencies-rework.ts b/backend/src/db/migrations/20260720183403_pam-account-dependencies-rework.ts
index fa58be78b2..4275a25f60 100644
--- a/backend/src/db/migrations/20260720183403_pam-account-dependencies-rework.ts
+++ b/backend/src/db/migrations/20260720183403_pam-account-dependencies-rework.ts
@@ -13,6 +13,12 @@ export async function up(knex: Knex): Promise<void> {
await knex.schema.createTable(TableName.PamAccountDependency, (t) => {
t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
+ // Tenant scope (the per-org internal PAM project, same as every other PAM table). Part of the upsert key so
+ // two orgs scanning the same host/directory can't collide on one global row.
+ t.string("projectId").notNullable();
+ t.foreign("projectId").references("id").inTable(TableName.Project).onDelete("CASCADE");
+ t.index("projectId");
+
// Run-as stable identity (domain:objectGUID / SID); the upsert key, stable across the
// staged -> imported flip.
t.string("fingerprint").notNullable();
@@ -36,7 +42,7 @@ export async function up(knex: Knex): Promise<void> {
t.timestamps(true, true, true);
- t.unique(["fingerprint", "machine", "type", "name"]);
+ t.unique(["projectId", "fingerprint", "machine", "type", "name"]);
});
// Exactly one of accountId / discoveredAccountId is set: staged -> discoveredAccountId, imported -> accountId.
diff --git a/backend/src/db/schemas/pam-account-dependencies.ts b/backend/src/db/schemas/pam-account-dependencies.ts
index ef48547621..57e599e037 100644
--- a/backend/src/db/schemas/pam-account-dependencies.ts
+++ b/backend/src/db/schemas/pam-account-dependencies.ts
@@ -11,6 +11,7 @@ import { TImmutableDBKeys } from "./models";
export const PamAccountDependenciesSchema = z.object({
id: z.string().uuid(),
+ projectId: z.string(),
fingerprint: z.string(),
accountId: z.string().uuid().nullable().optional(),
discoveredAccountId: z.string().uuid().nullable().optional(),
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 3d3cba34d2..676ccdfac2 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
@@ -365,7 +365,7 @@ export const registerPamDiscoveryRouter = async (server: FastifyZodProvider) =>
server.route({
method: "GET",
- url: "/:sourceId/discovered",
+ url: "/:sourceId/discovered-accounts",
schema: {
operationId: "listPamDiscoveredAccounts",
description: "List staged accounts discovered by a PAM discovery source",
@@ -400,7 +400,7 @@ export const registerPamDiscoveryRouter = async (server: FastifyZodProvider) =>
server.route({
method: "POST",
- url: "/:sourceId/discovered/import",
+ url: "/:sourceId/discovered-accounts/import",
schema: {
operationId: "importPamDiscoveredAccounts",
description: "Import staged accounts into a folder",
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 32829b44dd..24db9b3ee2 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
@@ -15,8 +15,13 @@ import { KmsDataKey } from "@app/services/kms/kms-types";
import { TMembershipDALFactory } from "@app/services/membership/membership-dal";
import { TMembershipRoleDALFactory } from "@app/services/membership/membership-role-dal";
-import { PamAccountType } from "../pam/pam-enums";
-import { checkAccountAccess, getResourceIdsWithActions, TActorContext } from "../pam/pam-permission";
+import { PamAccountType, PamProductRole } from "../pam/pam-enums";
+import {
+ checkAccountAccess,
+ getResourceIdsWithActions,
+ TActorContext,
+ verifyProductMembership
+} from "../pam/pam-permission";
import { TPamAccountDALFactory, TPamAccountDetail } from "../pam-account/pam-account-dal";
import { validateConnectionDetails, validateCredentials } from "../pam-account/pam-account-schemas";
import { PamTemplateSettingsSchema } from "../pam-account-template/pam-account-template-schemas";
@@ -333,7 +338,8 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServic
// credential — the two collisions seen in practice.
const getSharedIdentityReferences = async (
account: TPamAccountDetail,
- projectId: string
+ projectId: string,
+ ctx: TActorContext
): Promise<{ id: string; name: string; discoverySources: string[] }[]> => {
if (!isRotatableAccountType(account.accountType)) return [];
@@ -349,7 +355,7 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServic
const siblings = account.discoveryFingerprint
? (await pamAccountDAL.find({ projectId, discoveryFingerprint: account.discoveryFingerprint }))
.filter((sibling) => sibling.id !== account.id)
- .map((sibling) => ({ id: sibling.id, name: sibling.name }))
+ .map((sibling) => ({ id: sibling.id, name: sibling.name, folderId: sibling.folderId }))
: [];
// A source whose credential is the account itself is fine (it updates in place); only a *different*
@@ -368,23 +374,53 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServic
await decrypt(projectId, cred.encryptedConnectionDetails)
);
if (identityKey(cred.accountType, credConn, credCreds.username) !== key) return null;
- return { accountId: cred.id, accountName: cred.name, sourceName: source.name };
+ return { accountId: cred.id, accountName: cred.name, folderId: cred.folderId, sourceName: source.name };
} catch {
return null;
}
})
)
- ).filter((m): m is { accountId: string; accountName: string; sourceName: string } => m !== null);
+ ).filter((m): m is { accountId: string; accountName: string; folderId: string; sourceName: string } => m !== null);
// Merge into one list keyed by account, collecting the discovery sources each is a credential for.
- const byAccount = new Map<string, { id: string; name: string; discoverySources: string[] }>();
- siblings.forEach((s) => byAccount.set(s.id, { id: s.id, name: s.name, discoverySources: [] }));
+ const byAccount = new Map<
+ string,
+ { id: string; name: string; folderId?: string | null; discoverySources: string[] }
+ >();
+ siblings.forEach((s) => byAccount.set(s.id, { id: s.id, name: s.name, folderId: s.folderId, discoverySources: [] }));
sourceMatches.forEach((m) => {
const existing = byAccount.get(m.accountId);
if (existing) existing.discoverySources.push(m.sourceName);
- else byAccount.set(m.accountId, { id: m.accountId, name: m.accountName, discoverySources: [m.sourceName] });
+ else
+ byAccount.set(m.accountId, {
+ id: m.accountId,
+ name: m.accountName,
+ folderId: m.folderId,
+ discoverySources: [m.sourceName]
+ });
});
- return [...byAccount.values()];
+
+ // Only surface what the caller may already see: an account they can read, and discovery-source names only if
+ // they can view sources (PAM Admin) — otherwise this warning would leak names of resources behind folder or
+ // product authorization the caller doesn't hold.
+ const { hasRole } = await verifyProductMembership(permissionService, projectId, ctx);
+ const canViewSources = hasRole(PamProductRole.Admin);
+ const visible = await Promise.all(
+ [...byAccount.values()].map(async (ref) => {
+ const canRead = await checkAccount(
+ ref.id,
+ ref.folderId,
+ projectId,
+ ResourcePermissionPamResourceActions.ReadAccounts,
+ ctx
+ )
+ .then(() => true)
+ .catch(() => false);
+ if (!canRead) return null;
+ return { id: ref.id, name: ref.name, discoverySources: canViewSources ? ref.discoverySources : [] };
+ })
+ );
+ return visible.filter((v): v is { id: string; name: string; discoverySources: string[] } => v !== null);
};
const resolveRotator = async (
@@ -750,7 +786,7 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServic
lastRotationError = (decrypted as { message?: string }).message ?? null;
}
- const sharedIdentity = await getSharedIdentityReferences(account, projectId);
+ const sharedIdentity = await getSharedIdentityReferences(account, projectId, ctx);
return {
enabled: settings?.rotation?.enabled ?? false,
diff --git a/backend/src/ee/services/pam-discovery/pam-account-dependency-dal.ts b/backend/src/ee/services/pam-discovery/pam-account-dependency-dal.ts
index fe366d73d7..3e0e65e169 100644
--- a/backend/src/ee/services/pam-discovery/pam-account-dependency-dal.ts
+++ b/backend/src/ee/services/pam-discovery/pam-account-dependency-dal.ts
@@ -7,6 +7,7 @@ import { ormify } from "@app/lib/knex";
export type TPamAccountDependencyDALFactory = ReturnType<typeof pamAccountDependencyDALFactory>;
type TUpsertDependency = {
+ projectId: string;
fingerprint: string;
machine: string;
type: string;
@@ -31,10 +32,10 @@ export const pamAccountDependencyDALFactory = (db: TDbClient) => {
// so it distinguishes a newly-discovered dependency from one the scan merely re-saw (drives the run's new count).
const upsertByIdentity = async (dep: TUpsertDependency, tx?: Knex): Promise<{ id: string; isNew: boolean }> => {
const conn = tx || db;
- const { fingerprint, machine, type, name, data, accountId, discoveredAccountId } = dep;
+ const { projectId, fingerprint, machine, type, name, data, accountId, discoveredAccountId } = dep;
const [row] = await conn(TableName.PamAccountDependency)
- .insert({ fingerprint, machine, type, name, data, accountId, discoveredAccountId })
- .onConflict(["fingerprint", "machine", "type", "name"])
+ .insert({ projectId, fingerprint, machine, type, name, data, accountId, discoveredAccountId })
+ .onConflict(["projectId", "fingerprint", "machine", "type", "name"])
.merge({
data,
accountId: conn.raw(`COALESCE(??."accountId", EXCLUDED."accountId")`, [TableName.PamAccountDependency]),
@@ -53,18 +54,27 @@ export const pamAccountDependencyDALFactory = (db: TDbClient) => {
// narrower source never drops another scan's dependencies.
const deleteStaleForSource = async (
{
+ projectId,
accountIds,
discoveredAccountIds,
scannedMachines,
keepIds
- }: { accountIds: string[]; discoveredAccountIds: string[]; scannedMachines: string[]; keepIds: string[] },
+ }: {
+ projectId: string;
+ accountIds: string[];
+ discoveredAccountIds: string[];
+ scannedMachines: string[];
+ keepIds: string[];
+ },
tx?: Knex
): Promise<void> => {
if (!scannedMachines.length || (!accountIds.length && !discoveredAccountIds.length)) return;
// Bind each list as a single array parameter (`= ANY(?)`) rather than one bind per element, so a large
// domain can't blow past Postgres's 65,535 bind-parameter cap and fail the reconcile after upserts wrote.
+ // Scoped to this tenant's project so a scan never touches another org's rows sharing the same machine name.
await (tx || db)(TableName.PamAccountDependency)
+ .where("projectId", projectId)
.whereRaw(`"machine" = ANY(?::text[])`, [scannedMachines])
.where((qb) => {
if (accountIds.length) void qb.whereRaw(`"accountId" = ANY(?::uuid[])`, [accountIds]);
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 bb9af56f66..ed9fe35cad 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
@@ -492,6 +492,7 @@ export const pamDiscoverySourceServiceFactory = (deps: TPamDiscoverySourceServic
const accountId = match.importedAccountId;
return depLimit(() =>
pamAccountDependencyDAL.upsertByIdentity({
+ projectId: source.projectId,
fingerprint: dep.fingerprint,
machine: dep.machine,
type: dep.type,
@@ -511,6 +512,7 @@ export const pamDiscoverySourceServiceFactory = (deps: TPamDiscoverySourceServic
newDependencyCount = depResults.filter((r) => r.isNew).length;
await pamAccountDependencyDAL.deleteStaleForSource({
+ projectId: source.projectId,
accountIds: sourceAccounts.map((a) => a.importedAccountId).filter((v): v is string => Boolean(v)),
discoveredAccountIds: sourceAccounts.map((a) => a.id),
scannedMachines: scannedDependencyMachines,
@@ -687,7 +689,19 @@ export const pamDiscoverySourceServiceFactory = (deps: TPamDiscoverySourceServic
if (!discovered || discovered.discoverySourceId !== sourceId) {
throw new NotFoundError({ message: "Discovered account not found" });
}
- if (discovered.importedAccountId) throw new BadRequestError({ message: "Already imported" });
+ if (discovered.importedAccountId) {
+ // Already imported. The account is created, marked, and its deps backfilled in three separate writes
+ // (create runs its own transaction, so they can't share one). Re-run the idempotent backfill here so
+ // a retry heals a prior import whose backfill didn't complete, flipping any still-staged deps onto
+ // the account instead of leaving them stranded behind this early return.
+ await pamAccountDependencyDAL.backfillImported(discovered.id, discovered.importedAccountId);
+ return {
+ discoveredAccountId: item.discoveredAccountId,
+ status: PamDiscoveryImportStatus.Imported,
+ accountId: discovered.importedAccountId,
+ name: item.name ?? discovered.name
+ };
+ }
const details = decryptToObject(discovered.encryptedDetails, decryptor) as {
connectionDetails: Record<string, unknown>;
diff --git a/frontend/src/hooks/api/pam/mutations.tsx b/frontend/src/hooks/api/pam/mutations.tsx
index 9182d216cb..822fc44dd1 100644
--- a/frontend/src/hooks/api/pam/mutations.tsx
+++ b/frontend/src/hooks/api/pam/mutations.tsx
@@ -735,7 +735,7 @@ export const useImportPamDiscoveredAccounts = () => {
return useMutation({
mutationFn: async ({ sourceId, ...body }: TImportPamDiscoveredAccountsDTO) => {
const { data } = await apiRequest.post<{ results: TImportPamDiscoveredAccountResult[] }>(
- `/api/v1/pam/discovery-sources/${sourceId}/discovered/import`,
+ `/api/v1/pam/discovery-sources/${sourceId}/discovered-accounts/import`,
body
);
return data.results;
diff --git a/frontend/src/hooks/api/pam/queries.tsx b/frontend/src/hooks/api/pam/queries.tsx
index 90023c1916..4a3340d5b1 100644
--- a/frontend/src/hooks/api/pam/queries.tsx
+++ b/frontend/src/hooks/api/pam/queries.tsx
@@ -577,7 +577,7 @@ export const useListPamDiscoveredAccounts = (
const { data } = await apiRequest.get<{
discoveredAccounts: TPamDiscoveredAccount[];
totalCount: number;
- }>(`/api/v1/pam/discovery-sources/${sourceId}/discovered`, { params });
+ }>(`/api/v1/pam/discovery-sources/${sourceId}/discovered-accounts`, { params });
return data;
},
enabled: Boolean(sourceId),