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
fix comments
Thiago Araujo da Silva2b5ac80158f3
diff --git a/backend/e2e-test/routes/v1/org-access-reconcile.spec.ts b/backend/e2e-test/routes/v1/org-access-reconcile.spec.tsindex 513b5d2fd2..8b91e74f15 100644--- a/backend/e2e-test/routes/v1/org-access-reconcile.spec.ts+++ b/backend/e2e-test/routes/v1/org-access-reconcile.spec.ts@@ -33,9 +33,8 @@ import {} from "../../testUtils/project-members";import { addUserMembership, createUser, deleteUsers } from "../../testUtils/users";-// A user reaches a sub-org only through a root group linked into it. Removing the group path has to-// reap the direct project rows they hold there, and nothing else: the consumer rechecks current-// state, so a second path keeps the rows, and the root org is untouched throughout.+// A user reaches the sub-org only through a linked root group. Losing that path reaps their sub-org+// project rows and nothing else: a second path keeps them and the root org is never touched.describe("Org access reconcile", () => {let rootOrgId: string;let rootProjectId: string;@@ -66,8 +65,7 @@ describe("Org access reconcile", () => {});};- // Drains what is pending now, then waits for whatever the relay may have claimed first, so an- // assertion that rows survived is made after the consumer has actually run.+ // Drain, then wait out anything the relay claimed first, so "rows survived" checks run after the consumer.const reconcile = async () => {await eventOutbox.drain(ORG_ACCESS_RECONCILE_CONSUMER);await pollUntil({@@ -89,7 +87,6 @@ describe("Org access reconcile", () => {return groupId;};- // A root member with a direct project row in the root project and in the sub-org project.const createRootUserWithProjects = async (label: string, groupIds: string[]) => {const { userId, username } = await createUser(label);createdUserIds.push(userId);@@ -200,8 +197,8 @@ describe("Org access reconcile", () => {expect(await projectRows(rootProjectId, { actorIdentityId: identityId })).toHaveLength(1);});- // An indirect member (in the sub-org only through a linked root group) can be assigned to a sub-org- // project directly, without becoming a direct sub-org member, and loses it again once the path goes.+ // Indirect members can be added to a sub-org project without becoming direct sub-org members, and lose it+ // once the group path goes.test("a user who reaches the sub-org only through a group can be added to its project", async () => {const groupId = await createLinkedGroup("assign-grp");const { userId, username } = await createUser("assign-user");@@ -270,7 +267,7 @@ describe("Org access reconcile", () => {);});- // PAM and Agent Vault run over one implicit project per org, and add members through their own routes.+ // PAM and Agent Vault have one implicit project per org and their own member routes.const asSubOrg = (method: "GET" | "POST", url: string, body?: Record<string, unknown>) =>testServer.inject({ method, url, headers: { authorization: `Bearer ${subOrgToken}` }, ...(body ? { body } : {}) });@@ -313,6 +310,7 @@ describe("Org access reconcile", () => {});});+ // A lazily created Agent Vault project starts empty, so an org admin has to join it first.test("Agent Vault offers and takes a user who reaches the sub-org only through a group", async () => {const groupId = await createLinkedGroup("av-grp");const { userId } = await createUser("av-user");@@ -320,7 +318,6 @@ describe("Org access reconcile", () => {await addUserMembership({ userId, orgId: rootOrgId, role: OrgMembershipRole.Member });await testDb(TableName.UserGroupMembership).insert({ userId, groupId });const agentVaultProjectId = await implicitProjectId("agent-vault");- // A lazily created Agent Vault project starts empty; an org admin joins it before managing members.const join = await asSubOrg("POST",`/api/v1/organization-admin/projects/${agentVaultProjectId}/grant-admin-access`@@ -336,8 +333,8 @@ describe("Org access reconcile", () => {expect(await projectRows(agentVaultProjectId, { actorUserId: userId })).toHaveLength(1);});- // The sweep's query is what backs the daily backstop, so it is checked against real rows: an actor- // with a project row and no path into that org is an orphan, and every kind of path clears them.+ // The sweep query, against real rows: a project or resource row with no path into the org is an orphan,+ // any path clears it. Resource-only rows (like a group-derived PAM admin's folder row) count too.test("the sweep query finds an actor with a project or resource row and no path into the org, and nothing else", async () => {const orgDAL = orgDALFactory(testDb);const groupId = await createLinkedGroup("reconcile-sweep-grp");@@ -363,7 +360,6 @@ describe("Org access reconcile", () => {const { userId: viaGroupUserId } = await createRootUserWithProjects("reconcile-via-group", [groupId]);- // Resource rows with no project row behind them, like a group-derived PAM admin's personal folder row.const resourceRow = (actor: { actorUserId?: string; actorIdentityId?: string }, resourceType: ResourceType) => ({scope: RESOURCE_SCOPE,scopeOrgId: subOrgId,diff --git a/backend/e2e-test/testUtils/fixtures.ts b/backend/e2e-test/testUtils/fixtures.tsindex b05650112b..638bbcdd24 100644--- a/backend/e2e-test/testUtils/fixtures.ts+++ b/backend/e2e-test/testUtils/fixtures.ts@@ -61,10 +61,8 @@ export const createIsolatedOrgAndProject = async (namePrefix: string) => {return { orgId, projectId, authToken, cleanup };};-// A sub-org under `rootOrgId` with a project in it. There is no API for creating a sub-org in the-// test plan, so the org row is written directly; the seed user is made its admin so a token can be-// scoped to it and the project created the normal way. Deleting the root org cascades to the sub-org-// (organizations.parentOrgId is ON DELETE CASCADE), so this needs no cleanup of its own.+// Nothing in the test plan creates sub-orgs, so the row is written directly and the seed user made its+// admin to get a scoped token. Deleting the root org cascades to it (parentOrgId), so no cleanup needed.export const createSubOrgAndProject = async (dto: { rootOrgId: string; namePrefix: string }) => {const slug = `${dto.namePrefix}-${randomUUID().slice(0, 8)}`;const [subOrg] = await testDb(TableName.Organization)diff --git a/backend/e2e-test/testUtils/groups.ts b/backend/e2e-test/testUtils/groups.tsindex 788018e55e..48bf9d56f8 100644--- a/backend/e2e-test/testUtils/groups.ts+++ b/backend/e2e-test/testUtils/groups.ts@@ -2,8 +2,8 @@ import { randomUUID } from "node:crypto";import { AccessScope, OrgMembershipRole, TableName } from "@app/db/schemas";-// Group creation over the API is gated on the groups plan flag, which the license fake turns off, so-// the rows are written directly: the group plus the org row that lets the group routes resolve it.+// Group creation sits behind a plan flag the license fake turns off, so the group and its org row are+// written directly.export const createOrgGroup = async (dto: { orgId: string; label: string; role?: OrgMembershipRole }) => {const slug = `${dto.label}-${randomUUID().slice(0, 8)}`;const [group] = await testDb(TableName.Groups).insert({ orgId: dto.orgId, name: slug, slug }).returning("*");@@ -27,7 +27,7 @@ export const deleteGroups = async (groupIds: string[]) => {await testDb(TableName.Groups).whereIn("id", groupIds).delete();};-// `authToken` must be scoped to the sub-org being linked into; the route reads the org from it.+// `authToken` has to be scoped to the sub-org, the route reads the org from it.export const linkGroupToOrg = async (dto: { groupId: string; authToken: string; role?: OrgMembershipRole }) => {const res = await testServer.inject({method: "POST",diff --git a/backend/src/ee/services/agent-vault-member/agent-vault-member-dal.ts b/backend/src/ee/services/agent-vault-member/agent-vault-member-dal.tsindex fb8b3511b9..dad38d8366 100644--- a/backend/src/ee/services/agent-vault-member/agent-vault-member-dal.ts+++ b/backend/src/ee/services/agent-vault-member/agent-vault-member-dal.ts@@ -231,7 +231,8 @@ export const agentVaultMemberDALFactory = (db: TDbClient) => {};// Every rule here mirrors one in assertActorsAreAddable, so the picker cannot offer an actor the add- // path would then refuse.+ // path would then refuse. Group-only users and identities get a synthetic row shaped and aliased like+ // the memberships table, so the same filters cover them.const findAvailableActors = async ({ projectId, orgId, actorTypes, search, limit, offset }: TFindAvailableActorsDTO,tx?: Knex@@ -248,8 +249,6 @@ export const agentVaultMemberDALFactory = (db: TDbClient) => {.whereNotNull(`${TableName.Membership}.${column}`).select(column);- // The org's own rows plus a synthetic active row for every user or identity reaching it only through an- // active group, shaped like and aliased as the memberships table so the filters below read both alike.const m = TableName.Membership;const orgActors = () => {const direct = conn(m)diff --git a/backend/src/ee/services/agent-vault-member/agent-vault-membership-service.test.ts b/backend/src/ee/services/agent-vault-member/agent-vault-membership-service.test.tsindex 7ef2486491..a941f7cdb5 100644--- a/backend/src/ee/services/agent-vault-member/agent-vault-membership-service.test.ts+++ b/backend/src/ee/services/agent-vault-member/agent-vault-membership-service.test.ts@@ -45,7 +45,8 @@ const buildTx = (adminCount: number) => {};// Only the collaborators these three guards touch; everything else is left undefined so a guard that-// fails to short-circuit shows up as a crash rather than a silent pass.+// fails to short-circuit shows up as a crash rather than a silent pass. findActorsWithActiveOrgAccess+// follows the org read, and groupReachableIds fakes actors that reach the org only through a group.const buildService = ({identityProjectId = null as string | null,productMemberships = [] as ({ id: string } & Record<string, string | null>)[],@@ -71,8 +72,6 @@ const buildService = ({userAliasDAL: { findBySsoExternalIds: vi.fn().mockResolvedValue([]) },orgDAL: {findById: vi.fn().mockResolvedValue({ id: ORG_ID, rootOrgId: null }),- // Derived from the organization read below, so a test that changes what the org holds changes this- // too; groupReachableIds stands in for actors the org reaches only through an active group.lockActorsForOrgAccess: vi.fn().mockResolvedValue(undefined),findActorsWithActiveOrgAccess: vi.fn(async ({ userIds, identityIds }: { userIds: string[]; identityIds: string[] }) => {diff --git a/backend/src/ee/services/agent-vault-member/agent-vault-membership-service.ts b/backend/src/ee/services/agent-vault-member/agent-vault-membership-service.tsindex cb58e20f93..e0858c18f9 100644--- a/backend/src/ee/services/agent-vault-member/agent-vault-membership-service.ts+++ b/backend/src/ee/services/agent-vault-member/agent-vault-membership-service.ts@@ -306,8 +306,8 @@ export const agentVaultMembershipServiceFactory = ({resolveAgentVaultActorNames({ userDAL, groupDAL, identityDAL }, actors);// resolveSession refuses an actor with no active org membership, so one added without it could never mint.- // Users and identities count when they have an active row of their own or an active group reaching the org;- // the reconcile consumer revokes the membership if that group path goes away.+ // Users and identities need an active row of their own or an active group into the org. Reconcile revokes+ // the membership if that group path goes.const assertActorsAreAddable = async (actors: TAgentVaultNamedActor[], orgId: string, projectId: string) => {const groupIds = named(actors, AgentVaultMemberType.Group);const machineIdentityIds = named(actors, AgentVaultMemberType.MachineIdentity);diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex 3db152d721..c2a69ac2c9 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -2935,10 +2935,9 @@ interface UnlinkGroupFromSubOrgEvent {};}-// Logged by the reconcile consumer after the fact, so the actor is the platform and the cause is in-// `reason`, with the group that carried the lost path when there was one. Names are resolved at log-// time and omitted when the row is already gone (a deleted group). `resources` are resource-level-// grants (PAM, Agent Vault, PKI apps, signers), including ones in projects only reached through a group.+// Written by the reconcile consumer, so the actor is the platform and `reason` / `groupId` say why. Names+// are looked up at log time and missing if the row's already gone. `resources` are resource-level grants+// (PAM, Agent Vault, PKI apps, signers), including ones in projects only reached through a group.interface RevokeOrgProjectAccessEvent {type: EventType.REVOKE_ORG_PROJECT_ACCESS;metadata: {diff --git a/backend/src/ee/services/group/group-dal.ts b/backend/src/ee/services/group/group-dal.tsindex e7c838c650..e596887b47 100644--- a/backend/src/ee/services/group/group-dal.ts+++ b/backend/src/ee/services/group/group-dal.ts@@ -653,8 +653,8 @@ export const groupDALFactory = (db: TDbClient) => {}};- // Every org a member reaches through the group: the one that owns it plus every org it is linked into.- // The one source for the org list on org membership events, so the emit sites cannot disagree.+ // Orgs the group reaches: its owner plus every org it's linked into. The only source for event org lists,+ // so emit sites can't disagree.const findGroupOrgIds = async (groupId: string, tx?: Knex) => {try {const conn = tx || db.replicaNode();diff --git a/backend/src/ee/services/group/group-service.ts b/backend/src/ee/services/group/group-service.tsindex 0ee22aec35..1b57f15f7d 100644--- a/backend/src/ee/services/group/group-service.ts+++ b/backend/src/ee/services/group/group-service.ts@@ -380,8 +380,7 @@ export const groupServiceFactory = ({/*** Delete a group owned by the current organization.* Ensures the group is not linked by any sub-organizations before deleting.- * Folder grant cleanup and the actor/org read have to run before the delete, since the cascade wipes- * the memberships they read.+ * Folder grant cleanup and the actor/org read run before the delete, the cascade wipes what they read.*/const deleteOwnedGroup = async ({ groupId, actorOrgId }: { groupId: string; actorOrgId: string }) => {const referencingSubOrgs = await groupDAL.getGroupsReferencingGroup(groupId);diff --git a/backend/src/ee/services/group/group-types.ts b/backend/src/ee/services/group/group-types.tsindex 54bb7bda8c..1ca60932de 100644--- a/backend/src/ee/services/group/group-types.ts+++ b/backend/src/ee/services/group/group-types.ts@@ -172,8 +172,7 @@ export type TRemoveIdentitiesFromGroup = {eventEmitter: TEventEmitter;};-// Structural rather than Pick<TGroupDALFactory, ...>: group-dal.ts imports this file, so naming its type-// here would make the two files import each other.+// Structural instead of Pick<TGroupDALFactory>, since group-dal.ts imports this file.export type TGroupOrgIdsDAL = { findGroupOrgIds: (groupId: string, tx?: Knex) => Promise<string[]> };export type TConvertPendingGroupAdditionsToGroupMemberships = {diff --git a/backend/src/services/membership-group/membership-group-service.ts b/backend/src/services/membership-group/membership-group-service.tsindex d951856159..32eba1e9ad 100644--- a/backend/src/services/membership-group/membership-group-service.ts+++ b/backend/src/services/membership-group/membership-group-service.ts@@ -378,9 +378,8 @@ export const membershipGroupServiceFactory = ({return { membership: membershipDoc, group };};- // Unlinks a group from an org, plus its project rows there (otherwise they'd keep granting access through- // a group the org no longer holds) and folder grants members only had through it. Whether members keep- // their own project rows is up to the reconcile consumer.+ // Unlinks a group from an org plus its project rows there (or they'd keep granting access) and folder grants+ // members only had through it. Members' own project rows are left to the reconcile consumer.const detachGroupFromOrg = async ({ groupId, orgId, orgMembershipId }: { groupId: string; orgId: string; orgMembershipId?: string },tx: Knexdiff --git a/backend/src/services/membership-identity/membership-identity-dal.ts b/backend/src/services/membership-identity/membership-identity-dal.tsindex 0ecdb6706c..51f424504e 100644--- a/backend/src/services/membership-identity/membership-identity-dal.ts+++ b/backend/src/services/membership-identity/membership-identity-dal.ts@@ -450,6 +450,7 @@ export const membershipIdentityDALFactory = (db: TDbClient) => {}};+ // Project scope: anyone grantable in the project's org (findActorsWithActiveOrgAccess rule) not already in it.const listAvailableIdentities = async (scopeData: AccessScopeData, rootOrgId: string) => {// TODO (akhil/scott): need to implement filters@@ -472,8 +473,6 @@ export const membershipIdentityDALFactory = (db: TDbClient) => {db.ref("hasDeleteProtection").withSchema(TableName.Identity)];- // A project can take anyone who can be granted access in its org, the same rule as- // findActorsWithActiveOrgAccess.if (scopeData.scope === AccessScope.Project) {const directOrgIdentities = (activeOnly: boolean) =>dbdiff --git a/backend/src/services/membership-identity/membership-identity-service.ts b/backend/src/services/membership-identity/membership-identity-service.tsindex a4219f54ac..adf6ef21c5 100644--- a/backend/src/services/membership-identity/membership-identity-service.ts+++ b/backend/src/services/membership-identity/membership-identity-service.ts@@ -415,6 +415,7 @@ export const membershipIdentityServiceFactory = ({return { membership: membershipDoc };};+ // On org removal the identity's project rows in the org and its sub-orgs are left to the reconcile consumer.const deleteMembership = async (dto: TDeleteMembershipIdentityDTO, externalTx?: Knex) => {const { scopeData } = dto;const factory = scopeFactory[scopeData.scope];@@ -471,8 +472,7 @@ export const membershipIdentityServiceFactory = ({}}- // Durable deny atomic with the org-membership removal. The identity's project rows in this org- // and its sub-orgs are left to the reconcile consumer, which the event triggers.+ // Durable deny atomic with the org-membership removal.if (scopeData.scope === AccessScope.Organization) {await identityAccessTokenService.insertOrgMembershipRevocationMarker({identityId: dto.selector.identityId,@@ -581,8 +581,8 @@ export const membershipIdentityServiceFactory = ({return membership;};- // The list is made of org identities, so at project scope it's gated on org identity read alone, plus a- // check that the project belongs to the org.+ // It's a list of org identities, so at project scope only org identity read gates it, plus a check that+ // the project is in the org.const listAvailableIdentities = async (dto: TListMembershipIdentityDTO) => {const { scopeData } = dto;diff --git a/backend/src/services/membership-identity/project/project-membership-identity-factory.ts b/backend/src/services/membership-identity/project/project-membership-identity-factory.tsindex a2df496217..1ebfef112d 100644--- a/backend/src/services/membership-identity/project/project-membership-identity-factory.ts+++ b/backend/src/services/membership-identity/project/project-membership-identity-factory.ts@@ -58,8 +58,8 @@ export const newProjectMembershipIdentityFactory = ({const isCustomRole: TMembershipIdentityScopeFactory["isCustomRole"] = (role) => isCustomProjectRole(role);- // Same rule as every other add path (findActorsWithActiveOrgAccess): an active row of its own or an active- // group reaching the org. The reconcile consumer revokes the project row if that group path goes away.+ // Same add rule as everywhere else (findActorsWithActiveOrgAccess). Reconcile revokes the row if the group+ // path goes.const assertOrgAccess = async (identityId: string, orgId: string) => {const withOrgAccess = await orgDAL.findActorsWithActiveOrgAccess({ orgId, userIds: [], identityIds: [identityId] });if (!withOrgAccess.identityIds.has(identityId)) {diff --git a/backend/src/services/membership-user/membership-user-dal.ts b/backend/src/services/membership-user/membership-user-dal.tsindex 7ac300cf30..3bb0803c29 100644--- a/backend/src/services/membership-user/membership-user-dal.ts+++ b/backend/src/services/membership-user/membership-user-dal.ts@@ -283,8 +283,8 @@ export const membershipUserDALFactory = (db: TDbClient) => {}};- // Sub-org: root org users not yet in it. Project: anyone who can be granted access in the project's org- // (same rule as findActorsWithActiveOrgAccess) without a direct project row.+ // Sub-org: root org users not in it yet. Project: anyone grantable in the project's org+ // (findActorsWithActiveOrgAccess rule) without a direct project row.const listAvailableUsers = async (scopeData: AccessScopeData, rootOrgId?: string | null) => {try {const userColumns = [diff --git a/backend/src/services/membership-user/membership-user-service.ts b/backend/src/services/membership-user/membership-user-service.tsindex 42a2a0bed2..062950fe60 100644--- a/backend/src/services/membership-user/membership-user-service.ts+++ b/backend/src/services/membership-user/membership-user-service.ts@@ -709,8 +709,8 @@ export const membershipUserServiceFactory = ({return membership;};- // The list is made of org members, so at project scope it's gated on org member read alone, plus a check- // that the project belongs to the org.+ // It's a list of org members, so at project scope only org member read gates it, plus a check that the+ // project is in the org.const listAvailableUsers = async (dto: TListMembershipUserDTO) => {const { scopeData } = dto;diff --git a/backend/src/services/membership-user/membership-user-types.ts b/backend/src/services/membership-user/membership-user-types.tsindex a834457a9f..d9c05d5813 100644--- a/backend/src/services/membership-user/membership-user-types.ts+++ b/backend/src/services/membership-user/membership-user-types.ts@@ -36,8 +36,8 @@ export type TCreateMembershipUserDTO = {temporaryRange?: string;temporaryAccessStartTime?: string;}[];- // Org scope only: users who can already be granted access in the org (findActorsWithActiveOrgAccess)- // count as members, so a project invite doesn't turn a group-only user into a direct org member.+ // Org scope only: users already grantable in the org count as members, so a project invite doesn't turn+ // a group-only user into a direct org member.skipUsersWithOrgAccess?: boolean;};};diff --git a/backend/src/services/membership-user/project/project-membership-user-factory.ts b/backend/src/services/membership-user/project/project-membership-user-factory.tsindex b3d1318152..b855a5e180 100644--- a/backend/src/services/membership-user/project/project-membership-user-factory.ts+++ b/backend/src/services/membership-user/project/project-membership-user-factory.ts@@ -70,8 +70,7 @@ export const newProjectMembershipUserFactory = ({const isCustomRole: TMembershipUserScopeFactory["isCustomRole"] = (role) => isCustomProjectRole(role);- // Users with an active org row of their own or an active group reaching the org can get a project- // membership, the same rule every other add path uses (findActorsWithActiveOrgAccess).+ // Same add rule as everywhere else (findActorsWithActiveOrgAccess).const onCreateMembershipUserGuard: TMembershipUserScopeFactory["onCreateMembershipUserGuard"] = async (dto,newUsers@@ -156,8 +155,7 @@ export const newProjectMembershipUserFactory = ({}};- // Only users who can already sign in get the email: accepted direct members, plus group-only members- // (no direct row, so no status to check).+ // Only email users who can already sign in: accepted direct members and group-only members.const onCreateMembershipComplete: TMembershipUserScopeFactory["onCreateMembershipComplete"] = async (dto,newMembersdiff --git a/backend/src/services/membership/application-membership-cleanup-service.ts b/backend/src/services/membership/application-membership-cleanup-service.tsindex e85b255a72..fff3371550 100644--- a/backend/src/services/membership/application-membership-cleanup-service.ts+++ b/backend/src/services/membership/application-membership-cleanup-service.ts@@ -80,7 +80,7 @@ export const applicationMembershipCleanupServiceFactory = ({);};- // Returns the resource rows it removed, so a caller can say which grants went.+ // Returns the removed resource rows so callers can report them.const cleanupActorsApplicationMembershipsInProjects = async ({ projectIds, userIds, identityIds }: { projectIds: string[]; userIds: string[]; identityIds: string[] },tx: Knexdiff --git a/backend/src/services/membership/project-access-revoke-service.ts b/backend/src/services/membership/project-access-revoke-service.tsindex 72b6439045..c70d2a55d5 100644--- a/backend/src/services/membership/project-access-revoke-service.ts+++ b/backend/src/services/membership/project-access-revoke-service.ts@@ -48,11 +48,9 @@ const toRevoked = (rows: TMemberships[]) => ({}))});-// The one definition of what an actor loses when they leave the projects of an org: project rows,-// resource rows (PAM, Agent Vault, PKI applications, signers), project keys, privileges, approver-// slots, alert recipient slots and live PAM sessions. Everything keyed on actor + project is reaped-// across every project in the orgs, not only the ones the actor held a row in, since those can exist-// in projects reached through a group. Membership roles cascade from the membership row.+// The one list of what leaving an org's projects takes away: project and resource rows, keys, privileges,+// approver and alert recipient slots, live PAM sessions. Actor + project stuff is reaped across every+// project in the orgs, since it can exist in group-only projects. Roles cascade from the membership row.export const projectAccessRevokeServiceFactory = ({membershipDAL,projectDAL,@@ -63,8 +61,7 @@ export const projectAccessRevokeServiceFactory = ({pamSessionDAL,gatewayV2Service}: TProjectAccessRevokeServiceFactoryDep) => {- // Runs inside the caller's transaction and returns the PAM cancellation sender to call after it- // commits, as `terminatePamSessionsForUsers` does.+ // Runs in the caller's tx; call the returned PAM cancellation sender after commit.const revokeActorsInOrgs = async ({ orgIds, userIds = [], identityIds = [] }: { orgIds: string[]; userIds?: string[]; identityIds?: string[] },tx: Knexdiff --git a/backend/src/services/org/org-access-fns.ts b/backend/src/services/org/org-access-fns.tsindex b308bb3f9a..533daf2c8b 100644--- a/backend/src/services/org/org-access-fns.ts+++ b/backend/src/services/org/org-access-fns.ts@@ -4,9 +4,8 @@ import { BadRequestError } from "@app/lib/errors";import { TOrgDALFactory } from "./org-dal";-// Call inside the transaction that writes the grant, before the write. It takes the reconcile consumer's-// per-actor lock and rechecks access under it, so a path removed concurrently is either seen here or seen-// by the consumer once this commits. Without it the grant can land after the consumer ran and outlive it.+// Call in the grant's tx before writing. Takes the consumer's per-actor lock and rechecks, so a path removed+// at the same time is caught either here or by the consumer after commit, never neither.export const lockAndAssertActiveOrgAccess = async ({orgDAL,diff --git a/backend/src/services/org/org-access-reconcile-consumer.test.ts b/backend/src/services/org/org-access-reconcile-consumer.test.tsindex 543beac195..fb19f33ed0 100644--- a/backend/src/services/org/org-access-reconcile-consumer.test.ts+++ b/backend/src/services/org/org-access-reconcile-consumer.test.ts@@ -31,7 +31,7 @@ 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 });-// The revoke service reports one entry per actor it found rows for; actors without rows are absent.+// The revoke service only reports actors it found rows for.const build = (opts?: {withAccess?: { userIds?: string[]; identityIds?: string[] };revoked?: TRevokedProjectAccess[];diff --git a/backend/src/services/org/org-access-reconcile-consumer.ts b/backend/src/services/org/org-access-reconcile-consumer.tsindex 6b10e163e2..74d38e507f 100644--- a/backend/src/services/org/org-access-reconcile-consumer.ts+++ b/backend/src/services/org/org-access-reconcile-consumer.ts@@ -65,10 +65,9 @@ const splitActors = (actors: TOrgMembershipActor[]) => ({identityIds: actors.filter((a) => a.actorType === ActorType.IDENTITY).map((a) => a.actorId)});-// Keeps project memberships in an org only for actors that still reach it (direct org row or a group-// holding one). Events say what got removed; we figure out who might've lost their last path, recheck-// against current state and delete what's orphaned. Not on the enforcement path (token validation-// already rejects these actors) and safe to re-run.+// Keeps project memberships in an org only for actors that still reach it. Events say what got removed; we+// recheck who might've lost their last path and delete what's orphaned. Not on the enforcement path (token+// validation already rejects these actors) and safe to re-run.export const orgAccessReconcileConsumerFactory = ({orgDAL,userDAL,@@ -81,9 +80,8 @@ export const orgAccessReconcileConsumerFactory = ({const eventTypes = new Set<string>(ORG_MEMBERSHIP_EVENTS);const subscribesTo = (eventType: string) => eventTypes.has(eventType);- // Group events carry the orgs and actors captured at removal time, since later removals can wipe the- // rows that would tell us. Parsing is eager and reads are deferred: a bad payload never recovers, a- // failed read is worth a retry.+ // Group events carry orgs and actors captured at removal time, since later removals can wipe those rows.+ // Parse eagerly and read lazily: a bad payload never recovers, a failed read is worth a retry.const $parseScope = (event: TEvent): (() => Promise<TReconcileScope>) => {switch (event.eventType) {case GROUP_MEMBERSHIP_REMOVED_EVENT: {@@ -127,7 +125,6 @@ export const orgAccessReconcileConsumerFactory = ({return projectAccessRevokeService.revokeActorsInOrgs({ orgIds: [orgId], userIds, identityIds }, tx);});- // Names are read at log time, so a deleted group (or an actor since removed) simply has none.const $describeActor = async ({ userId, identityId }: Pick<TRevokedProjectAccess, "userId" | "identityId">) => {if (userId) {const user = await userDAL.findById(userId);@@ -137,8 +134,8 @@ export const orgAccessReconcileConsumerFactory = ({return { identityId, identityName: identity?.name };};- // Actors are handled in small batches, each in its own short tx, since the rows they hold aren't bounded.- // Side effects fire per batch after commit and only when rows were removed, so replays are no-ops.+ // Small actor batches, each in its own short tx, since what they hold isn't bounded. Side effects fire per+ // batch after commit and only when rows went, so replays are no-ops.const $reconcileOrg = async (orgId: string, scope: TReconcileScope, groupName?: string) => {const org = await orgDAL.findById(orgId);if (!org) return;diff --git a/backend/src/services/org/org-access-sweep-queue.ts b/backend/src/services/org/org-access-sweep-queue.tsindex 75b03d4a75..2ff523051c 100644--- a/backend/src/services/org/org-access-sweep-queue.ts+++ b/backend/src/services/org/org-access-sweep-queue.ts@@ -17,8 +17,8 @@ type TOrgAccessSweepQueueDep = {export type TOrgAccessSweepQueueFactory = ReturnType<typeof orgAccessSweepQueueFactory>;-// Backstop for the reconcile consumer: finds project and resource rows whose actor no longer reaches the org-// and emits an org membership removal for each. Also cleans up data from before the events existed.+// Backstop for the reconcile consumer: emits an org membership removal for every project or resource row+// whose actor no longer reaches the org. Also catches data from before the events existed.export const orgAccessSweepQueueFactory = ({ cronJob, orgDAL, eventEmitter }: TOrgAccessSweepQueueDep) => {const runSweep = async () => {const orphans = await orgDAL.findOrphanedProjectActors({diff --git a/backend/src/services/org/org-dal.ts b/backend/src/services/org/org-dal.tsindex 3861f0c3c0..d12a4a3ce3 100644--- a/backend/src/services/org/org-dal.ts+++ b/backend/src/services/org/org-dal.ts@@ -1196,8 +1196,8 @@ export const orgDALFactory = (db: TDbClient) => {}};- // Actors that still reach the org: a direct org row (any status) or a group holding one. Same as- // findEffectiveOrgMembership minus isActive, which the token layer handles.+ // Actors that still reach the org: a direct org row (any status) or a group holding one. Ignores isActive+ // on purpose, it's for the reconcile consumer, and deactivating someone mustn't reap their projects.const findActorsWithOrgAccess = async ({ orgId, userIds, identityIds }: { orgId: string; userIds: string[]; identityIds: string[] },tx?: Knex@@ -1235,9 +1235,9 @@ export const orgDALFactory = (db: TDbClient) => {}};- // Actors that can be granted access in the org right now: an active direct org row, or no direct row and- // an active group that holds one. A deactivated direct member stays out even if a group reaches the org,- // matching findEffectiveOrgMembership, which resolves the direct row first.+ // Actors that can be granted access right now, used by every add path: an active direct org row, or no+ // direct row and an active group holding one. A deactivated direct member stays out even with a group+ // path, matching findEffectiveOrgMembership, which resolves the direct row first.const findActorsWithActiveOrgAccess = async ({ orgId, userIds, identityIds }: { orgId: string; userIds: string[]; identityIds: string[] },tx?: Knex@@ -1284,13 +1284,11 @@ export const orgDALFactory = (db: TDbClient) => {}};- // (actor, org) pairs with a project or resource row (PAM, Agent Vault, PKI apps, signers) in an org the- // actor no longer reaches. Resource rows count on their own: a group-derived PAM admin's personal folder- // row can exist with no project row behind it. Skips ghost users (project bots), they never have an org- // row. One streaming pass over those rows against a hash of the org rows; collapsing to distinct pairs- // first was measured and only moved the cost into an aggregate.- // Without a caller's tx it runs in its own replica transaction so `statementTimeoutMs` bounds it: a- // backstop that overruns should fail and log, not keep the replica busy after the cron has given up on it.+ // (actor, org) pairs with a project or resource row in an org they no longer reach. Resource rows count on+ // their own (a group-derived PAM admin's folder row has no project row). Skips ghost users, they never+ // have an org row. One streaming pass against a hash of org rows; collapsing to pairs first was measured+ // and just moved the cost into an aggregate. Without a tx it runs in its own replica tx so+ // `statementTimeoutMs` can bound it: an overrunning backstop should fail, not keep the replica busy.const findOrphanedProjectActors = async ({ limit, statementTimeoutMs }: { limit: number; statementTimeoutMs?: number },tx?: Knex@@ -1357,11 +1355,9 @@ export const orgDALFactory = (db: TDbClient) => {}};- // Serializes group additions with the reconcile consumer per actor, so access granted between its check- // and its deletes doesn't get reaped. One statement for the whole set: a SCIM sync can add thousands of- // members in one request and everything else on that path is batched. The function scan emits the array- // in order and the lock call runs per row, so a sorted array is taken in sorted order, which is what- // keeps two callers from deadlocking on each other.+ // Serializes grants with the reconcile consumer per actor. One statement for the whole set, since a SCIM+ // sync can add thousands at once. unnest keeps array order, so sorted ids lock in sorted order and two+ // callers can't deadlock.const lockActorsForOrgAccess = async (actorIds: string[], tx: Knex) => {const keys = [...new Set(actorIds)].sort().map((actorId) => PgSqlLock.OrgAccessReconcile(actorId));if (!keys.length) return;diff --git a/backend/src/services/org/org-fns.ts b/backend/src/services/org/org-fns.tsindex c1e3bb01e0..7ec0fa6300 100644--- a/backend/src/services/org/org-fns.ts+++ b/backend/src/services/org/org-fns.ts@@ -24,9 +24,8 @@ type TDeleteOrgMemberships = {eventEmitter: TEventEmitter;};-// Removes the users from the org and its sub-orgs outright: their org rows, their groups there and-// everything they held in those projects. The event is still emitted so the reconcile consumer can-// confirm nothing is left.+// Removes the users from the org and its sub-orgs outright, org rows, groups and project access included.+// Still emits the event so the reconcile consumer can confirm nothing's left.export const deleteOrgMembershipsFn = async ({orgMembershipIds,orgId,diff --git a/backend/src/services/org/org-membership-events.ts b/backend/src/services/org/org-membership-events.tsindex d9925c8ba7..77e1467d9d 100644--- a/backend/src/services/org/org-membership-events.ts+++ b/backend/src/services/org/org-membership-events.ts@@ -43,8 +43,8 @@ const ActorSchema = z.object({});export type TOrgMembershipActor = z.infer<typeof ActorSchema>;-// Group events snapshot the orgs and members at removal time, since by the time the consumer runs a later-// removal or the delete cascade may have wiped those rows. orgIds includes the group's own org.+// Group events snapshot orgs and members at removal time, since a later removal or the delete cascade can+// wipe those rows before the consumer runs. orgIds includes the group's own org.const GroupScopePayloadSchema = z.object({groupId: z.string().uuid(),orgIds: z.array(z.string().uuid()).max(ORGS_PER_EVENT),diff --git a/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/InviteMembersDialog.tsx b/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/InviteMembersDialog.tsxindex b16e1f2e92..3bb0a15897 100644--- a/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/InviteMembersDialog.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/InviteMembersDialog.tsx@@ -37,6 +37,8 @@ type Props = {onOpenChange: (isOpen: boolean) => void;};+// The ?requesterEmail= link resolves against the candidate list (group-only members included); existing+// members are caught by requesterMatch. Both fetch a page since the search is a substring match.export const InviteMembersDialog = ({ isOpen, onOpenChange }: Props) => {const { currentOrg } = useOrganization();const addMembers = useAddAgentVaultMembers();@@ -63,9 +65,6 @@ export const InviteMembersDialog = ({ isOpen, onOpenChange }: Props) => {{ actorType: AgentVaultMemberType.User, search: debouncedSearch.trim() || undefined },isOpen);- // The ?requesterEmail= deep link resolves against the candidate list, which holds everyone who can be- // added, group-only sub-org members included. A requester who is already a member is caught by- // requesterMatch instead. A page for the same reason as there: the search is a substring match.const { data: requesterCandidates } = useListAvailableAgentVaultMembers({ actorType: AgentVaultMemberType.User, search: requesterEmail, limit: 20 },Boolean(requesterEmail)