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
refactor comments
Thiago Araujo da Silva80291438ae18
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdindex 2399c1adb6..24f83b6ba3 100644--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@ -880,46 +880,39 @@ query shape.### Org Access Reconcile (second outbox consumer)-`src/services/org/org-membership-events.ts` (the event contract), `org-access-reconcile-consumer.ts` and-`org-access-sweep-queue.ts` (queries live on `org-dal.ts`) keep one invariant: **an actor holds project-memberships in an org only while they have a direct org row there or belong to a group that does.** A-user can reach a sub-org purely through a root group linked into it, so the code that removes a group-membership can't tell on its own whether the actor still reaches the org.--- **Every removal of an org path is a fact event, emitted inside the transaction that removed it.** Four- events, all `com.infisical.organization.<entity>.removed.v1` per the event naming ADR, each saying what- went away and nothing about who lost access: `group-membership` (`groupId`, the group's `orgIds` and the- `members` who left, from the two group-removal helpers in `group-fns.ts`, which covers the manual route- plus SCIM, LDAP, OIDC and SAML sync), `group-link` (`orgId`, `groupId` and the group's `members`, from- `membershipGroupService.detachGroupFromOrg`, used by `group-service.ts` and the org-scope group- membership `DELETE`), `group` (`groupId`, `orgIds` and all `members`, from the owned and SCIM group- deletes, read through `groupDAL.findGroupActorsAndOrgs` before the cascade removes it) and `membership`- (`orgId` + actor, from `deleteOrgMembershipsFn` and the sweep). Actors are- `{ actorType: user | identity, actorId }`. The group events carry the orgs and members as they were at- removal time, never left for the consumer to read: removing a member and then unlinking the group before- the consumer runs would otherwise leave neither event able to name that member in that org. Both lists- are paged (100 each, one event per org page x member page), because a group can be linked into any- number of sub-orgs and the outbox rejects a payload over 16 KiB, which rolls back the removal. A new path- that removes a group membership, link, group or org membership must emit the matching event. The daily- `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,- 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 org- membership (`assertActiveOrgMembership` and its Go port). The lag only shows in member lists, seat- counts and SCIM reads.-- **`orgDAL.lockActorsForOrgAccess`** is taken by the add-to-group helpers and the consumer, in sorted- order, so a membership granted between the consumer's access check and its deletes can't be reaped.- Take it in any new path that grants an actor an org path outside `group-fns.ts`.-- **Adding a user to a project checks effective org membership** (`orgDAL.findActorsWithOrgAccess` in- `project-membership-user-factory.ts`), so a user who only reaches the org through a linked group can- get a direct project membership. That row is what the consumer revokes when the group path goes.+Lives in `src/services/org/`: `org-membership-events.ts` (event contract), `org-access-reconcile-consumer.ts`+and `org-access-sweep-queue.ts`, with queries on `org-dal.ts`. The rule: **an actor keeps project+memberships in an org only while they have a direct org row there or are in a group that has one.** A user+can reach a sub-org only through a linked root group, so code removing a group membership can't tell by+itself whether the actor still reaches the org.++- **Every removal of an org path emits a fact event in the same tx.** Four of them,+ `com.infisical.organization.<entity>.removed.v1`:+ - `group-membership`: `groupId`, `orgIds`, the `members` who left. From the removal helpers in+ `group-fns.ts` (manual route plus SCIM, LDAP, OIDC and SAML sync).+ - `group-link`: `orgId`, `groupId`, the group's `members`. From `membershipGroupService.detachGroupFromOrg`.+ - `group`: `groupId`, `orgIds`, all `members`. From owned and SCIM group deletes, read with+ `groupDAL.findGroupActorsAndOrgs` before the cascade.+ - `membership`: `orgId` + actor. From `deleteOrgMembershipsFn` and the sweep.++ Group events snapshot orgs and members at removal time, since a later removal can wipe those rows before+ the consumer runs. Both lists are paged at 100 (one event per org page x member page) because the outbox+ rejects payloads over 16 KiB, which rolls back the removal. Any new path removing one of these must emit+ the matching event. The daily `org-access-reconcile-sweep` cron is a backstop, not a substitute.+- **The consumer (`org-access-reconcile`) rechecks against current state**, one short tx per org. Orgs and+ actors come from the payload for group events, and from the org plus its sub-orgs for a membership+ removal. Actors with no path left lose their project rows in that org, plus privileges, project keys,+ approver slots and resource memberships (PAM, Agent Vault, PKI apps, signers) across every project in the+ org, since those can exist in group-only projects. PAM cancellations, the `revoke-org-project-access`+ audit log and usage meters fire after commit and only when something was removed, so replays are silent.+- **Not on the enforcement path.** Token validation already rejects actors with no effective org membership+ (`assertActiveOrgMembership` and its Go port). The lag only shows in member lists, seat counts and SCIM.+- **`orgDAL.lockActorsForOrgAccess`** is taken (sorted) by the add-to-group helpers and the consumer, so+ access granted between the consumer's check and its deletes doesn't get reaped. Take it in any new path+ that grants an org path outside `group-fns.ts`.+- **Adding a user to a project checks effective org membership** (`orgDAL.findActorsWithOrgAccess`), so+ group-only users can get a direct project membership. That's the row the consumer revokes once the group+ path goes away.### Soft-Delete + Async Cleanupdiff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex 4f0d08d75c..3b02cb983f 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -2934,17 +2934,15 @@ interface UnlinkGroupFromSubOrgEvent {};}-// Logged by the org access reconcile consumer after the fact, so the actor is the platform and the-// cause lives in reason and groupId.+// Logged by the reconcile consumer after the fact, so the actor is the platform and the cause is in+// reason/groupId. `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: {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 groupresources: { projectId: string; resourceType: string; resourceId: string }[];reason: string;groupId?: string;diff --git a/backend/src/ee/services/group/group-dal.ts b/backend/src/ee/services/group/group-dal.tsindex f7068cf7d7..804f35a2d8 100644--- a/backend/src/ee/services/group/group-dal.ts+++ b/backend/src/ee/services/group/group-dal.ts@@ -653,7 +653,7 @@ export const groupDALFactory = (db: TDbClient) => {}};- // read before deleting the group: the cascade removes all three+ // Call before deleting the group, the cascade wipes all three.const findGroupActorsAndOrgs = async (groupId: string, tx?: Knex) => {try {const conn = tx || db.replicaNode();diff --git a/backend/src/ee/services/group/group-fns.ts b/backend/src/ee/services/group/group-fns.tsindex 3e22cd16e7..a090016948 100644--- a/backend/src/ee/services/group/group-fns.ts+++ b/backend/src/ee/services/group/group-fns.ts@@ -403,6 +403,7 @@ export const addIdentitiesToGroup = async ({* this function will handle both cases.* @param {group} group - group to remove user(s) from* @param {string[]} userIds - id(s) of user(s) to remove from group+ * Cleans up projects in every org the group reaches, not just its home org.*/export const removeUsersFromGroupByUserIds = async ({group,@@ -487,7 +488,6 @@ export const removeUsersFromGroupByUserIds = async ({}});- // every org the group reaches, not just its home orgconst projectIds = Array.from(new Set((diff --git a/backend/src/ee/services/group/group-service.ts b/backend/src/ee/services/group/group-service.tsindex 8a0c8f9cd1..bb3fe70403 100644--- a/backend/src/ee/services/group/group-service.ts+++ b/backend/src/ee/services/group/group-service.ts@@ -400,6 +400,8 @@ 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.*/const deleteOwnedGroup = async ({ groupId, actorOrgId }: { groupId: string; actorOrgId: string }) => {const referencingSubOrgs = await groupDAL.getGroupsReferencingGroup(groupId);@@ -417,7 +419,6 @@ export const groupServiceFactory = ({tx);- // both must run before the delete: the cascade removes the memberships they readawait reapDeletedGroupFolderGrants({ userGroupMembershipDAL, identityGroupMembershipDAL, membershipGroupDAL, additionalPrivilegeDAL },groupId,diff --git a/backend/src/ee/services/scim/scim-service.ts b/backend/src/ee/services/scim/scim-service.tsindex 0cb5d15b27..c33490adb0 100644--- a/backend/src/ee/services/scim/scim-service.ts+++ b/backend/src/ee/services/scim/scim-service.ts@@ -1783,6 +1783,8 @@ export const scimServiceFactory = ({};};+ // SCIM can delete a group that's still linked into sub-orgs, so read its orgs and members before the+ // cascade drops the links.const deleteScimGroup: TScimServiceFactory["deleteScimGroup"] = async ({ groupId, orgId }) => {const org = await requestMemoize(requestMemoKeys.orgFindById(orgId), () => orgDAL.findById(orgId));if (!org) {@@ -1812,7 +1814,6 @@ export const scimServiceFactory = ({groupId,tx);- // SCIM can delete a group that is still linked into sub-orgs; read before the cascade drops the linksconst { orgIds, userIds, identityIds } = await groupDAL.findGroupActorsAndOrgs(groupId, tx);await emitGroupRemoved(eventEmitter,diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex a7b6da4b3d..b15e697aae 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -856,7 +856,6 @@ export const registerRoutes = async (const folderPermissionDAL = folderPermissionDALFactory(db);const membershipRoleDAL = membershipRoleDALFactory(db);const approvalPolicyDAL = approvalPolicyDALFactory(db);- // built early: the membership services below emit through it, consumers register laterconst eventOutboxDAL = eventOutboxDALFactory(db);const eventOutboxRegistry = eventOutboxRegistryFactory();const eventOutboxService = eventOutboxServiceFactory({ eventOutboxDAL, eventOutboxRegistry });diff --git a/backend/src/services/membership-group/membership-group-service.ts b/backend/src/services/membership-group/membership-group-service.tsindex adb7c385cf..d951856159 100644--- a/backend/src/services/membership-group/membership-group-service.ts+++ b/backend/src/services/membership-group/membership-group-service.ts@@ -378,8 +378,9 @@ export const membershipGroupServiceFactory = ({return { membership: membershipDoc, group };};- // Removes a linked group from an org: its link, its project rows there and the folder grants members- // held only through it. Whether members keep their own project rows is the reconcile consumer's call.+ // 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.const detachGroupFromOrg = async ({ groupId, orgId, orgMembershipId }: { groupId: string; orgId: string; orgMembershipId?: string },tx: Knex@@ -582,7 +583,6 @@ export const membershipGroupServiceFactory = ({}if (scopeData.scope === AccessScope.Organization) {- // the group's project rows go too, or they keep granting access through a group the org no longer holdsawait detachGroupFromOrg({groupId: dto.selector.groupId,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 5dfe1154b2..e4f417a6de 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,6 +70,7 @@ export const newProjectMembershipUserFactory = ({const isCustomRole: TMembershipUserScopeFactory["isCustomRole"] = (role) => isCustomProjectRole(role);+ // Users reaching the org through a direct row or a group can both get a project membership.const onCreateMembershipUserGuard: TMembershipUserScopeFactory["onCreateMembershipUserGuard"] = async (dto,newUsers@@ -85,7 +86,6 @@ export const newProjectMembershipUserFactory = ({});ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionMemberActions.Create, ProjectPermissionSub.Member);- // a direct org row or a group holding one; either is enough to hold a project membershipconst withOrgAccess = await orgDAL.findActorsWithOrgAccess({orgId: dto.permission.orgId,userIds: newUsers.map((el) => el.id),@@ -155,6 +155,8 @@ 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).const onCreateMembershipComplete: TMembershipUserScopeFactory["onCreateMembershipComplete"] = async (dto,newMembers@@ -168,8 +170,6 @@ export const newProjectMembershipUserFactory = ({});}- // only users who can already sign in get the email: accepted direct members, plus group-only- // members, who have no direct row to carry a statusconst newMemberIds = newMembers.map((el) => el.id);const directOrgMemberships = await membershipUserDAL.find({scope: AccessScope.Organization,diff --git a/backend/src/services/org/org-access-reconcile-consumer.test.ts b/backend/src/services/org/org-access-reconcile-consumer.test.tsindex fadd24412c..b14def9153 100644--- a/backend/src/services/org/org-access-reconcile-consumer.test.ts+++ b/backend/src/services/org/org-access-reconcile-consumer.test.ts@@ -194,6 +194,7 @@ describe("org access reconcile consumer", () => {expect(deps.usageMeteringService.emit).not.toHaveBeenCalled();});+ // A group with no org rows names no orgs, so the actual reconcile is driven by an org membership event.test("revokes every project row, key, privilege and approver slot in the org when no path remains", async () => {const { consumer, deps, tx } = build({projectRows: [@@ -209,7 +210,6 @@ describe("org access reconcile consumer", () => {members: [{ actorType: ActorType.USER, actorId: USER_ID }]})]);- // a group that held no org rows names no orgs; drive the reconcile with an org membership eventexpect(result.status).toBe(EventResultStatus.Delivered);expect(deps.membershipDAL.transaction).not.toHaveBeenCalled();@@ -219,7 +219,6 @@ describe("org access reconcile consumer", () => {expect(deps.orgDAL.lockActorsForOrgAccess).toHaveBeenCalledWith([USER_ID], tx);expect(deps.membershipRoleDAL.delete).toHaveBeenCalledWith({ $in: { membershipId: [uuid(100), uuid(101)] } }, tx);expect(deps.membershipDAL.delete).toHaveBeenCalledWith({ $in: { id: [uuid(100), uuid(101)] } }, tx);- // reaped across the whole org, not only the projects that had a rowconst allProjects = [PROJECT_A, PROJECT_B, PROJECT_C];expect(deps.additionalPrivilegeDAL.delete).toHaveBeenCalledWith({ $in: { actorUserId: [USER_ID], projectId: allProjects } },@@ -307,7 +306,6 @@ describe("org access reconcile consumer", () => {});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 rowconst { consumer, deps, tx } = build({resourceRows: [{@@ -382,8 +380,8 @@ describe("org access reconcile consumer", () => {expect(deps.membershipDAL.transaction).not.toHaveBeenCalled();});+ // Nothing in the DB says who to recheck anymore, only the payloads do.test("still reaps when the group lost its link and its member before the events were handled", async () => {- // the group no longer holds a row in the sub-org nor lists the user, so only the payloads say who to recheckconst { consumer, deps } = build({projectRows: [{ id: uuid(105), actorUserId: USER_ID, scopeProjectId: PROJECT_A }]});diff --git a/backend/src/services/org/org-access-reconcile-consumer.ts b/backend/src/services/org/org-access-reconcile-consumer.tsindex 038a2105af..a013b8552c 100644--- a/backend/src/services/org/org-access-reconcile-consumer.ts+++ b/backend/src/services/org/org-access-reconcile-consumer.ts@@ -70,14 +70,10 @@ const splitActors = (actors: TOrgMembershipActor[]) => ({identityIds: actors.filter((a) => a.actorType === ActorType.IDENTITY).map((a) => a.actorId)});-// One invariant: an actor keeps project memberships in an org only while they have a direct org row-// there or a group that holds one. The org membership events say what was removed; this works out who-// may have lost their last path, recomputes from current state and deletes what is orphaned, one short-// transaction per org.-//-// Not on the enforcement path: token validation already rejects actors with no effective org-// membership, so these rows are inert until it runs. Safe to re-run, and an actor re-added in the-// meantime keeps everything.+// 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, one short tx per org. Not on the enforcement path+// (token validation already rejects these actors) and safe to re-run.export const orgAccessReconcileConsumerFactory = ({orgDAL,projectDAL,@@ -95,10 +91,9 @@ export const orgAccessReconcileConsumerFactory = ({const eventTypes = new Set<string>(ORG_MEMBERSHIP_EVENTS);const subscribesTo = (eventType: string) => eventTypes.has(eventType);- // The group events carry the orgs and actors to recheck, captured when the removal happened, because- // later removals can delete the rows that would say. Only the access check reads current state.- // Parsing happens here and any read in the returned function, because a payload that fails to parse- // never will, while a read that fails is worth retrying.+ // 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.const $parseScope = (event: TEvent): (() => Promise<TReconcileScope>) => {switch (event.eventType) {case GROUP_MEMBERSHIP_REMOVED_EVENT: {@@ -125,6 +120,9 @@ export const orgAccessReconcileConsumerFactory = ({}};+ // Privileges, keys and resource rows are keyed on actor + project and can exist in group-only projects+ // (e.g. a group-derived PAM admin's personal folder-admin row), so they're reaped across the whole org+ // or they come back on re-add. Side effects fire only when rows were removed, so replays are no-ops.const $reconcileOrg = async (orgId: string, scope: TReconcileScope, reason: string) => {const org = await orgDAL.findById(orgId);if (!org) return;@@ -146,9 +144,6 @@ export const orgAccessReconcileConsumerFactory = ({? await membershipDAL.find({ ...projectScope, $in: { actorIdentityId: identityIds } }, { tx }): [];- // 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 =@@ -222,7 +217,6 @@ export const orgAccessReconcileConsumerFactory = ({if (!outcome) return;outcome.sendPamCancellations();- // at-least-once delivery: a replay finds no rows and returns above, so these fire onceif (!outcome.revoked.length) return;for await (const { projectIds, resources, ...actor } of outcome.revoked) {diff --git a/backend/src/services/org/org-access-sweep-queue.ts b/backend/src/services/org/org-access-sweep-queue.tsindex 31c9f8c06a..4b4d1469b5 100644--- a/backend/src/services/org/org-access-sweep-queue.ts+++ b/backend/src/services/org/org-access-sweep-queue.ts@@ -6,7 +6,6 @@ import { TEventEmitter } from "@app/services/event-outbox/event-outbox-types";import { TOrgDALFactory } from "./org-dal";import { emitOrgMembershipRemoved, toOrgMembershipActors } from "./org-membership-events";-// per run; a run that hits it logs and the next run picks up the restexport const ORG_ACCESS_SWEEP_LIMIT = 5000;type TOrgAccessSweepQueueDep = {@@ -17,8 +16,8 @@ type TOrgAccessSweepQueueDep = {export type TOrgAccessSweepQueueFactory = ReturnType<typeof orgAccessSweepQueueFactory>;-// Backstop for the reconcile consumer: finds project rows whose actor no longer reaches the org and-// reports each as an org membership that is gone. Also repairs data from before the events existed.+// Backstop for the reconcile consumer: finds project 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.export const orgAccessSweepQueueFactory = ({ cronJob, orgDAL, eventEmitter }: TOrgAccessSweepQueueDep) => {const runSweep = async () => {const orphans = await orgDAL.findOrphanedProjectActors({ limit: ORG_ACCESS_SWEEP_LIMIT });diff --git a/backend/src/services/org/org-dal.ts b/backend/src/services/org/org-dal.tsindex c40add25b9..13a0a87fa2 100644--- a/backend/src/services/org/org-dal.ts+++ b/backend/src/services/org/org-dal.ts@@ -1195,8 +1195,8 @@ export const orgDALFactory = (db: TDbClient) => {}};- // Which of the given actors still reach the org: a direct org row of any status, or a group that holds- // one. Same rule as findEffectiveOrgMembership minus isActive, which the token layer enforces.+ // 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.const findActorsWithOrgAccess = async ({ orgId, userIds, identityIds }: { orgId: string; userIds: string[]; identityIds: string[] },tx?: Knex@@ -1234,8 +1234,8 @@ export const orgDALFactory = (db: TDbClient) => {}};- // (actor, org) pairs with a project row in an org the actor no longer reaches. Ghost users are the- // project bots and never hold an org row, so they are skipped.+ // (actor, org) pairs with a project row in an org the actor no longer reaches. Skips ghost users (project+ // bots), they never have an org row.const findOrphanedProjectActors = async ({ limit }: { limit: number }, tx?: Knex) => {try {const conn = tx || db.replicaNode();@@ -1292,8 +1292,8 @@ export const orgDALFactory = (db: TDbClient) => {}};- // Serializes group additions with the reconcile consumer on the same actor, so a path granted between- // its access check and its deletes cannot be reaped. Sorted to avoid deadlocks.+ // Serializes group additions with the reconcile consumer per actor, so access granted between its check+ // and its deletes doesn't get reaped. Sorted to avoid deadlocks.const lockActorsForOrgAccess = async (actorIds: string[], tx: Knex) => {try {for await (const actorId of [...new Set(actorIds)].sort()) {diff --git a/backend/src/services/org/org-fns.ts b/backend/src/services/org/org-fns.tsindex 2567be8de3..621432d711 100644--- a/backend/src/services/org/org-fns.ts+++ b/backend/src/services/org/org-fns.ts@@ -38,6 +38,8 @@ type TDeleteOrgMemberships = {eventEmitter: TEventEmitter;};+// Only reaps projects held directly. The reconcile consumer handles what was reached through groups, here+// and in sub-orgs.export const deleteOrgMembershipsFn = async ({orgMembershipIds,orgId,@@ -170,8 +172,6 @@ export const deleteOrgMembershipsFn = async ({await alertChannelRecipientDAL.pruneOutOfScopeRecipients({ userIds: membershipUserIds }, tx);- // the deletes above only cover projects held directly; the consumer reaps what was reached through- // groups, here and in the sub-orgsawait emitOrgMembershipRemoved(eventEmitter,{ orgId, actors: toOrgMembershipActors({ userIds: membershipUserIds }) },diff --git a/backend/src/services/org/org-membership-events.test.ts b/backend/src/services/org/org-membership-events.test.tsindex 8086d3c50b..7abd5ba652 100644--- a/backend/src/services/org/org-membership-events.test.ts+++ b/backend/src/services/org/org-membership-events.test.ts@@ -123,8 +123,7 @@ describe("org membership events", () => {await emitGroupMembershipRemoved(eventEmitter, { groupId: GROUP, orgIds, actors: members }, TX);}- // 5 org pages x 3 member pages- expect(emitted).toHaveLength(15);+ expect(emitted).toHaveLength(5 * 3);const covered = new Set<string>();for (const { event, tx } of emitted) {expect(tx).toBe(TX);diff --git a/backend/src/services/org/org-membership-events.ts b/backend/src/services/org/org-membership-events.tsindex 79072091b1..36ce82aba5 100644--- a/backend/src/services/org/org-membership-events.ts+++ b/backend/src/services/org/org-membership-events.ts@@ -17,8 +17,8 @@ export const ORG_MEMBERSHIP_EVENTS = [ORG_MEMBERSHIP_REMOVED_EVENT] as const;-// Together these keep one event well under MAX_OUTBOX_PAYLOAD_BYTES (about 4 KB of org ids, 6 KB of members);-// a group can be linked into any number of sub-orgs, so neither list may go unbounded.+// Keeps each event well under MAX_OUTBOX_PAYLOAD_BYTES (~4 KB of org ids, ~6 KB of members). A group can be+// linked into any number of sub-orgs, so both lists need a cap.const ORGS_PER_EVENT = 100;const MEMBERS_PER_EVENT = 100;@@ -28,10 +28,8 @@ const ActorSchema = z.object({});export type TOrgMembershipActor = z.infer<typeof ActorSchema>;-// Each group event carries the orgs and actors it affects, read when the removal happened: by the time the-// consumer runs, a later removal (or the group delete cascade) may have taken away the rows that would say.-// A group membership removal names the members who left; a group removal names all of them. Both list every-// org the group held a row in, the group's own org included.+// 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.const GroupScopePayloadSchema = z.object({groupId: z.string().uuid(),orgIds: z.array(z.string().uuid()).max(ORGS_PER_EVENT),@@ -70,10 +68,10 @@ const emitAll = async (eventEmitter: TEventEmitter, events: TEventInput[], tx?:}};-// Big lists are paged across events so each fits the outbox; an empty one is still one page.+// An empty list is still one page, so the event still goes out.const page = <T>(items: T[], size: number): T[][] => (items.length ? chunkArray(items, size) : [[]]);-// One event per (org page, member page), so every member is rechecked in every org.+// One event per (org page, member page) so every member gets rechecked in every org.const pageGroupScope = (orgIds: string[], members: TOrgMembershipActor[]) =>page([...new Set(orgIds)], ORGS_PER_EVENT).flatMap((orgPage) =>page(members, MEMBERS_PER_EVENT).map((memberPage) => ({ orgIds: orgPage, members: memberPage }))