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
clean resources as well
Thiago Araujo da Silva180fe148f84e
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdindex ce774ede08..2399c1adb6 100644--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@ -904,10 +904,13 @@ membership can't tell on its own whether the actor still reaches the org.`org-access-reconcile-sweep` cron is a backstop, not a substitute.- **The consumer (`org-access-reconcile`) subscribes to all four, works out the orgs and actors to recheck**(from the payload for the three group events, the org plus its sub-orgs for an org membership removal) **and recomputes from current state**,- one short transaction per org. Actors with no path left lose their project rows in that org, plus privileges, project keys and- application approver slots across every project of the org, since those are keyed on actor + project- and may exist for group-only projects. PAM cancellations, the `revoke-org-project-access` audit event- and the usage meters fire after commit, only when rows were removed, so a replay logs nothing.+ one short transaction per org. Actors with no path left lose their project rows in that org, plus privileges, project keys,+ application approver slots and resource-scope memberships (PAM folders and accounts, Agent Vault, PKI+ applications, signers) across every project of the org, since those are keyed on actor + project and may+ exist for group-only projects: a group-derived PAM admin who creates a folder gets a personal+ folder-admin row with no project row behind it. PAM cancellations, the `revoke-org-project-access` audit event+ (`projectIds` for project memberships, `resources` for resource grants) and the usage meters fire after+ commit, only when rows were removed, so a replay logs nothing.- **It's not on the enforcement path.** Token validation already rejects an actor with no effective orgmembership (`assertActiveOrgMembership` and its Go port). The lag only shows in member lists, seatcounts and SCIM reads.diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex 994b7df419..4f0d08d75c 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -2941,7 +2941,11 @@ interface RevokeOrgProjectAccessEvent {metadata: {userId?: string;identityId?: string;+ // projects whose membership was removedprojectIds: string[];+ // resource-level grants removed (PAM folders and accounts, Agent Vault, PKI applications, signers),+ // including ones in projects the actor only reached through a group+ resources: { projectId: string; resourceType: string; resourceId: string }[];reason: string;groupId?: string;};diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex df3943de5e..a7b6da4b3d 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -3197,7 +3197,6 @@ export const registerRoutes = async (additionalPrivilegeDAL,projectKeyDAL,approvalPolicyDAL,- applicationMembershipCleanupService,alertChannelRecipientDAL,pamSessionDAL,gatewayV2Service,diff --git a/backend/src/services/org/org-access-reconcile-consumer.test.ts b/backend/src/services/org/org-access-reconcile-consumer.test.tsindex e60dc2c378..fadd24412c 100644--- a/backend/src/services/org/org-access-reconcile-consumer.test.ts+++ b/backend/src/services/org/org-access-reconcile-consumer.test.ts@@ -1,8 +1,7 @@-import { AccessScope } from "@app/db/schemas";+import { AccessScope, RESOURCE_SCOPE } from "@app/db/schemas";import { EventType } from "@app/ee/services/audit-log/audit-log-types";import { ActorType } from "@app/services/auth/auth-type";import { EventResultStatus, TEvent } from "@app/services/event-outbox/event-outbox-types";-import { ApplicationMemberKind } from "@app/services/pki-application/pki-application-types";import { orgAccessReconcileConsumerFactory } from "./org-access-reconcile-consumer";import {@@ -37,11 +36,19 @@ const makeEvent = (eventType: string, payload: Record<string, unknown>, id = 1):const userRemovedFromOrg = (orgId = ORG_ID) =>makeEvent(ORG_MEMBERSHIP_REMOVED_EVENT, { orgId, actorType: ActorType.USER, actorId: USER_ID });-type TRow = { id: string; actorUserId?: string; actorIdentityId?: string; scopeProjectId: string };+type TRow = {+ id: string;+ actorUserId?: string;+ actorIdentityId?: string;+ scopeProjectId: string;+ scopeResourceType?: string;+ scopeResourceId?: string;+};const build = (opts?: {withAccess?: { userIds?: string[]; identityIds?: string[] };projectRows?: TRow[];+ resourceRows?: TRow[];orgs?: Record<string, unknown>;childOrgs?: string[];}) => {@@ -63,10 +70,10 @@ const build = (opts?: {},projectDAL: { find: vi.fn().mockResolvedValue([{ id: PROJECT_A }, { id: PROJECT_B }, { id: PROJECT_C }]) },membershipDAL: {- find: vi.fn((filter: { $in?: { actorUserId?: string[]; actorIdentityId?: string[] } }) => {- const rows = opts?.projectRows ?? [];- if (filter.$in?.actorUserId) return Promise.resolve(rows.filter((row) => Boolean(row.actorUserId)));- return Promise.resolve(rows.filter((row) => Boolean(row.actorIdentityId)));+ find: vi.fn((filter: { scope: string; $in?: { actorUserId?: string[]; actorIdentityId?: string[] } }) => {+ const rows = (filter.scope === RESOURCE_SCOPE ? opts?.resourceRows : opts?.projectRows) ?? [];+ const ofKind = rows.filter((row) => Boolean(filter.$in?.actorUserId ? row.actorUserId : row.actorIdentityId));+ return Promise.resolve(ofKind.map((row) => ({ ...row, scope: filter.scope })));}),delete: vi.fn().mockResolvedValue([]),transaction: vi.fn(async (cb: (trx: unknown) => Promise<unknown>) => cb(tx))@@ -75,10 +82,6 @@ const build = (opts?: {additionalPrivilegeDAL: { delete: vi.fn().mockResolvedValue([]) },projectKeyDAL: { delete: vi.fn().mockResolvedValue([]) },approvalPolicyDAL: { deleteUserStepApproversInProjects: vi.fn().mockResolvedValue(undefined) },- applicationMembershipCleanupService: {- cleanupActorApplicationMemberships: vi.fn().mockResolvedValue(undefined),- cleanupUsersApplicationMemberships: vi.fn().mockResolvedValue(undefined)- },alertChannelRecipientDAL: { pruneOutOfScopeRecipients: vi.fn().mockResolvedValue(0) },pamSessionDAL: { findLiveByOrgAndUserIds: vi.fn(), update: vi.fn() },gatewayV2Service: { getPAMConnectionDetails: vi.fn() },@@ -230,7 +233,6 @@ describe("org access reconcile consumer", () => {expect.objectContaining({ projectIds: allProjects, userIds: [USER_ID] }),tx);- expect(deps.applicationMembershipCleanupService.cleanupUsersApplicationMemberships).toHaveBeenCalledTimes(2);expect(deps.alertChannelRecipientDAL.pruneOutOfScopeRecipients).toHaveBeenCalledWith({ userIds: [USER_ID] }, tx);expect(terminatePamSessionsForUsers).toHaveBeenCalledWith(expect.objectContaining({ orgIds: [ORG_ID], userIds: [USER_ID], tx })@@ -246,6 +248,7 @@ describe("org access reconcile consumer", () => {metadata: {userId: USER_ID,projectIds: [PROJECT_A, PROJECT_B],+ resources: [],reason: ORG_MEMBERSHIP_REMOVED_EVENT,groupId: undefined}@@ -255,9 +258,18 @@ describe("org access reconcile consumer", () => {expect(deps.usageMeteringService.emit).toHaveBeenCalledTimes(3);});- test("revokes an identity's rows and application memberships and logs it under the identity with the group", async () => {+ test("revokes an identity's rows and resource grants and logs it under the identity with the group", async () => {const { consumer, deps, tx } = build({- projectRows: [{ id: uuid(102), actorIdentityId: IDENTITY_ID, scopeProjectId: PROJECT_A }]+ projectRows: [{ id: uuid(102), actorIdentityId: IDENTITY_ID, scopeProjectId: PROJECT_A }],+ resourceRows: [+ {+ id: uuid(202),+ actorIdentityId: IDENTITY_ID,+ scopeProjectId: PROJECT_A,+ scopeResourceType: "pam-account",+ scopeResourceId: uuid(302)+ }+ ]});const [result] = await consumer.handle([@@ -269,15 +281,18 @@ describe("org access reconcile consumer", () => {]);expect(result.status).toBe(EventResultStatus.Delivered);- expect(deps.membershipDAL.delete).toHaveBeenCalledWith({ $in: { id: [uuid(102)] } }, tx);+ expect(deps.membershipDAL.find).toHaveBeenCalledWith(+ {+ scope: RESOURCE_SCOPE,+ $in: { scopeProjectId: [PROJECT_A, PROJECT_B, PROJECT_C], actorIdentityId: [IDENTITY_ID] }+ },+ { tx }+ );+ expect(deps.membershipDAL.delete).toHaveBeenCalledWith({ $in: { id: [uuid(102), uuid(202)] } }, tx);expect(deps.additionalPrivilegeDAL.delete).toHaveBeenCalledWith({ $in: { actorIdentityId: [IDENTITY_ID], projectId: [PROJECT_A, PROJECT_B, PROJECT_C] } },tx);- expect(deps.applicationMembershipCleanupService.cleanupActorApplicationMemberships).toHaveBeenCalledWith(- { projectId: PROJECT_A, actorKind: ApplicationMemberKind.Identity, actorId: IDENTITY_ID },- tx- );expect(deps.projectKeyDAL.delete).not.toHaveBeenCalled();const [auditCall] = deps.auditLogService.createAuditLog.mock.calls[0] as [{ event: { metadata: Record<string, unknown> } }@@ -285,11 +300,42 @@ describe("org access reconcile consumer", () => {expect(auditCall.event.metadata).toMatchObject({identityId: IDENTITY_ID,projectIds: [PROJECT_A],+ resources: [{ projectId: PROJECT_A, resourceType: "pam-account", resourceId: uuid(302) }],reason: GROUP_REMOVED_EVENT,groupId: GROUP_ID});});+ test("reaps a resource grant in a project the user only reached through a group, and logs it", async () => {+ // a group-derived PAM admin who created a folder holds a personal folder-admin row but no project row+ const { consumer, deps, tx } = build({+ resourceRows: [+ {+ id: uuid(203),+ actorUserId: USER_ID,+ scopeProjectId: PROJECT_C,+ scopeResourceType: "pam-folder",+ scopeResourceId: uuid(303)+ }+ ]+ });++ const [result] = await consumer.handle([userRemovedFromOrg()]);++ expect(result.status).toBe(EventResultStatus.Delivered);+ expect(deps.membershipRoleDAL.delete).toHaveBeenCalledWith({ $in: { membershipId: [uuid(203)] } }, tx);+ expect(deps.membershipDAL.delete).toHaveBeenCalledWith({ $in: { id: [uuid(203)] } }, tx);+ const [auditCall] = deps.auditLogService.createAuditLog.mock.calls[0] as [+ { event: { metadata: Record<string, unknown> } }+ ];+ expect(auditCall.event.metadata).toMatchObject({+ userId: USER_ID,+ projectIds: [],+ resources: [{ projectId: PROJECT_C, resourceType: "pam-folder", resourceId: uuid(303) }]+ });+ expect(deps.usageMeteringService.emit).toHaveBeenCalledTimes(3);+ });+test("a replay that finds no project rows left writes no audit entry and emits no meters", async () => {const { consumer, deps } = build({ projectRows: [] });diff --git a/backend/src/services/org/org-access-reconcile-consumer.ts b/backend/src/services/org/org-access-reconcile-consumer.tsindex 27a5058b3f..038a2105af 100644--- a/backend/src/services/org/org-access-reconcile-consumer.ts+++ b/backend/src/services/org/org-access-reconcile-consumer.ts@@ -1,4 +1,4 @@-import { AccessScope } from "@app/db/schemas";+import { AccessScope, RESOURCE_SCOPE } from "@app/db/schemas";import { EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";import { terminatePamSessionsForUsers } from "@app/ee/services/pam-session/pam-session-access-fns";@@ -17,13 +17,9 @@ import {} from "@app/services/event-outbox/event-outbox-types";import { AgentVaultIdentities, PamIdentities, SecretIdentities } from "@app/services/license-client";import { TUsageMeteringServiceFactory } from "@app/services/license-client/usage";-import {- APPLICATION_APPROVAL_SCOPES,- TApplicationMembershipCleanupServiceFactory-} from "@app/services/membership/application-membership-cleanup-service";+import { APPLICATION_APPROVAL_SCOPES } from "@app/services/membership/application-membership-cleanup-service";import { TMembershipDALFactory } from "@app/services/membership/membership-dal";import { TMembershipRoleDALFactory } from "@app/services/membership/membership-role-dal";-import { ApplicationMemberKind } from "@app/services/pki-application/pki-application-types";import { TProjectDALFactory } from "@app/services/project/project-dal";import { TProjectKeyDALFactory } from "@app/services/project-key/project-key-dal";@@ -53,10 +49,6 @@ export type TOrgAccessReconcileConsumerDep = {additionalPrivilegeDAL: Pick<TAdditionalPrivilegeDALFactory, "delete">;projectKeyDAL: Pick<TProjectKeyDALFactory, "delete">;approvalPolicyDAL: Pick<TApprovalPolicyDALFactory, "deleteUserStepApproversInProjects">;- applicationMembershipCleanupService: Pick<- TApplicationMembershipCleanupServiceFactory,- "cleanupActorApplicationMemberships" | "cleanupUsersApplicationMemberships"- >;alertChannelRecipientDAL: Pick<TAlertChannelRecipientDALFactory, "pruneOutOfScopeRecipients">;pamSessionDAL: Pick<TPamSessionDALFactory, "findLiveByOrgAndUserIds" | "update">;gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPAMConnectionDetails">;@@ -64,7 +56,13 @@ export type TOrgAccessReconcileConsumerDep = {usageMeteringService: Pick<TUsageMeteringServiceFactory, "emit">;};-type TRevokedActor = { userId?: string; identityId?: string; projectIds: string[] };+type TRevokedResource = { projectId: string; resourceType: string; resourceId: string };+type TRevokedActor = {+ userId?: string;+ identityId?: string;+ projectIds: string[];+ resources: TRevokedResource[];+};type TReconcileScope = { orgIds: string[]; actors: TOrgMembershipActor[]; groupId?: string };const splitActors = (actors: TOrgMembershipActor[]) => ({@@ -88,7 +86,6 @@ export const orgAccessReconcileConsumerFactory = ({additionalPrivilegeDAL,projectKeyDAL,approvalPolicyDAL,- applicationMembershipCleanupService,alertChannelRecipientDAL,pamSessionDAL,gatewayV2Service,@@ -149,15 +146,34 @@ export const orgAccessReconcileConsumerFactory = ({? await membershipDAL.find({ ...projectScope, $in: { actorIdentityId: identityIds } }, { tx }): [];- const membershipIds = [...userRows, ...identityRows].map((row) => row.id);+ // Everything below is keyed on actor + project rather than on a project membership, and may exist for+ // projects reached only through a group (a group-derived PAM admin creating a folder gets a personal+ // folder-admin row with no project row), so reap across the whole org or it reactivates on re-add.+ const orgProjectIds = (await projectDAL.find({ orgId }, { tx })).map((project) => project.id);+ const resourceScope = { scope: RESOURCE_SCOPE };+ const userResourceRows =+ orgProjectIds.length && userIds.length+ ? await membershipDAL.find(+ { ...resourceScope, $in: { scopeProjectId: orgProjectIds, actorUserId: userIds } },+ { tx }+ )+ : [];+ const identityResourceRows =+ orgProjectIds.length && identityIds.length+ ? await membershipDAL.find(+ { ...resourceScope, $in: { scopeProjectId: orgProjectIds, actorIdentityId: identityIds } },+ { tx }+ )+ : [];++ const membershipIds = [...userRows, ...identityRows, ...userResourceRows, ...identityResourceRows].map(+ (row) => row.id+ );if (membershipIds.length) {await membershipRoleDAL.delete({ $in: { membershipId: membershipIds } }, tx);await membershipDAL.delete({ $in: { id: membershipIds } }, tx);}- // keyed on actor + project, not on a membership, and may exist for projects reached only through a- // group; reap across the whole org so nothing reactivates on re-add- const orgProjectIds = (await projectDAL.find({ orgId }, { tx })).map((project) => project.id);if (orgProjectIds.length && userIds.length) {await additionalPrivilegeDAL.delete({ $in: { actorUserId: userIds, projectId: orgProjectIds } }, tx);await projectKeyDAL.delete({ $in: { receiverId: userIds, projectId: orgProjectIds } }, tx);@@ -170,24 +186,6 @@ export const orgAccessReconcileConsumerFactory = ({await additionalPrivilegeDAL.delete({ $in: { actorIdentityId: identityIds, projectId: orgProjectIds } }, tx);}- const userRowsByProject = groupBy(userRows, (row) => row.scopeProjectId as string);- for await (const [projectId, rows] of Object.entries(userRowsByProject)) {- await applicationMembershipCleanupService.cleanupUsersApplicationMemberships(- { projectId, userIds: rows.map((row) => row.actorUserId as string) },- tx- );- }- for await (const row of identityRows) {- await applicationMembershipCleanupService.cleanupActorApplicationMemberships(- {- projectId: row.scopeProjectId as string,- actorKind: ApplicationMemberKind.Identity,- actorId: row.actorIdentityId as string- },- tx- );- }-if (userIds.length) {await alertChannelRecipientDAL.pruneOutOfScopeRecipients({ userIds }, tx);}@@ -200,16 +198,23 @@ export const orgAccessReconcileConsumerFactory = ({tx});- const projectIdsOf = (rows: typeof userRows) => rows.map((row) => row.scopeProjectId as string);+ const toRevoked = (rows: typeof userRows) => ({+ projectIds: rows.filter((row) => row.scope === AccessScope.Project).map((row) => row.scopeProjectId as string),+ resources: rows+ .filter((row) => row.scope === RESOURCE_SCOPE)+ .map((row) => ({+ projectId: row.scopeProjectId as string,+ resourceType: row.scopeResourceType as string,+ resourceId: row.scopeResourceId as string+ }))+ });const revoked: TRevokedActor[] = [- ...Object.entries(groupBy(userRows, (row) => row.actorUserId as string)).map(([userId, rows]) => ({- userId,- projectIds: projectIdsOf(rows)- })),- ...Object.entries(groupBy(identityRows, (row) => row.actorIdentityId as string)).map(([identityId, rows]) => ({- identityId,- projectIds: projectIdsOf(rows)- }))+ ...Object.entries(groupBy([...userRows, ...userResourceRows], (row) => row.actorUserId as string)).map(+ ([userId, rows]) => ({ userId, ...toRevoked(rows) })+ ),+ ...Object.entries(+ groupBy([...identityRows, ...identityResourceRows], (row) => row.actorIdentityId as string)+ ).map(([identityId, rows]) => ({ identityId, ...toRevoked(rows) }))];return { revoked, sendPamCancellations };});@@ -220,13 +225,13 @@ export const orgAccessReconcileConsumerFactory = ({// at-least-once delivery: a replay finds no rows and returns above, so these fire onceif (!outcome.revoked.length) return;- for await (const { projectIds, ...actor } of outcome.revoked) {+ for await (const { projectIds, resources, ...actor } of outcome.revoked) {await auditLogService.createAuditLog({orgId,actor: { type: ActorType.PLATFORM, metadata: {} },event: {type: EventType.REVOKE_ORG_PROJECT_ACCESS,- metadata: { ...actor, projectIds, reason, groupId: scope.groupId }+ metadata: { ...actor, projectIds, resources, reason, groupId: scope.groupId }}});}