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
handle in small batches
Thiago Araujo da Silva95970d507844
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdindex 24f83b6ba3..8ceb0abf30 100644--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@ -899,12 +899,13 @@ itself whether the actor still reaches the org.the consumer runs. Both lists are paged at 100 (one event per org page x member page) because the outboxrejects payloads over 16 KiB, which rolls back the removal. Any new path removing one of these must emitthe 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+- **The consumer (`org-access-reconcile`) rechecks against current state**, in batches of 10 actors per org,+ each in its own short tx with a `statement_timeout`, since the rows an actor holds aren't bounded. Orgs andactors come from the payload for group events, and from the org plus its sub-orgs for a membershipremoval. 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 theorg, 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.+ audit log and usage meters fire after each batch commits, 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, sodiff --git a/backend/src/services/org/org-access-reconcile-consumer.test.ts b/backend/src/services/org/org-access-reconcile-consumer.test.tsindex b14def9153..f3f92acdc2 100644--- a/backend/src/services/org/org-access-reconcile-consumer.test.ts+++ b/backend/src/services/org/org-access-reconcile-consumer.test.ts@@ -3,7 +3,7 @@ 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 { orgAccessReconcileConsumerFactory } from "./org-access-reconcile-consumer";+import { ACTORS_PER_RECONCILE_TX, orgAccessReconcileConsumerFactory } from "./org-access-reconcile-consumer";import {GROUP_LINK_REMOVED_EVENT,GROUP_MEMBERSHIP_REMOVED_EVENT,@@ -52,7 +52,7 @@ const build = (opts?: {orgs?: Record<string, unknown>;childOrgs?: string[];}) => {- const tx = { sentinel: true };+ const tx = { raw: vi.fn().mockResolvedValue(undefined) };const deps = {orgDAL: {findById: vi.fn((id: string) => {@@ -424,6 +424,45 @@ describe("org access reconcile consumer", () => {{ scope: AccessScope.Project, scopeOrgId: ORG_ID, $in: { actorUserId: [USER_ID] } },{ tx });- expect(deps.projectDAL.find).toHaveBeenCalledWith({ orgId: ORG_ID }, { tx });+ expect(deps.projectDAL.find).toHaveBeenCalledWith({ orgId: ORG_ID });+ });++ test("splits the actors into short, time-boxed transactions and logs each batch after it commits", async () => {+ const userIds = Array.from({ length: ACTORS_PER_RECONCILE_TX + 1 }, (_, i) => uuid(200 + i));+ const { consumer, deps, tx } = build({+ projectRows: userIds.map((actorUserId, i) => ({ id: uuid(300 + i), actorUserId, scopeProjectId: PROJECT_A }))+ });+ deps.membershipDAL.find.mockImplementation((filter: { scope: string; $in?: { actorUserId?: string[] } }) =>+ Promise.resolve(+ filter.scope === AccessScope.Project+ ? (filter.$in?.actorUserId ?? []).map((actorUserId) => ({+ id: actorUserId,+ actorUserId,+ scope: filter.scope,+ scopeProjectId: PROJECT_A+ }))+ : []+ )+ );++ const [result] = await consumer.handle([+ makeEvent(GROUP_LINK_REMOVED_EVENT, {+ orgId: ORG_ID,+ groupId: GROUP_ID,+ members: userIds.map((actorId) => ({ actorType: ActorType.USER, actorId }))+ })+ ]);++ expect(result.status).toBe(EventResultStatus.Delivered);+ expect(deps.membershipDAL.transaction).toHaveBeenCalledTimes(2);+ expect(tx.raw).toHaveBeenCalledTimes(2);+ expect(tx.raw).toHaveBeenCalledWith(expect.stringContaining("SET LOCAL statement_timeout"));+ expect(deps.orgDAL.lockActorsForOrgAccess).toHaveBeenNthCalledWith(+ 1,+ userIds.slice(0, ACTORS_PER_RECONCILE_TX),+ tx+ );+ expect(deps.orgDAL.lockActorsForOrgAccess).toHaveBeenNthCalledWith(2, userIds.slice(ACTORS_PER_RECONCILE_TX), tx);+ expect(deps.auditLogService.createAuditLog).toHaveBeenCalledTimes(userIds.length);});});diff --git a/backend/src/services/org/org-access-reconcile-consumer.ts b/backend/src/services/org/org-access-reconcile-consumer.tsindex a013b8552c..3397f4ffd6 100644--- a/backend/src/services/org/org-access-reconcile-consumer.ts+++ b/backend/src/services/org/org-access-reconcile-consumer.ts@@ -3,7 +3,7 @@ import { EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/aimport { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";import { terminatePamSessionsForUsers } from "@app/ee/services/pam-session/pam-session-access-fns";import { TPamSessionDALFactory } from "@app/ee/services/pam-session/pam-session-dal";-import { groupBy } from "@app/lib/fn";+import { chunkArray, groupBy } from "@app/lib/fn";import { logger } from "@app/lib/logger";import { TAdditionalPrivilegeDALFactory } from "@app/services/additional-privilege/additional-privilege-dal";import { TAlertChannelRecipientDALFactory } from "@app/services/alert/alert-channel-recipient-dal";@@ -40,6 +40,8 @@ import {} from "./org-membership-events";export const ORG_ACCESS_RECONCILE_CONSUMER = "org-access-reconcile";+export const ACTORS_PER_RECONCILE_TX = 10;+const RECONCILE_STATEMENT_TIMEOUT_MS = 30_000;export type TOrgAccessReconcileConsumerDep = {orgDAL: Pick<TOrgDALFactory, "findById" | "find" | "findActorsWithOrgAccess" | "lockActorsForOrgAccess">;@@ -72,8 +74,8 @@ const splitActors = (actors: TOrgMembershipActor[]) => ({// 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.+// against current state 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,projectDAL,@@ -122,13 +124,14 @@ 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;- const candidates = splitActors(scope.actors);-- const outcome = await membershipDAL.transaction(async (tx) => {+ // or they come back on re-add.+ const $revokeActors = async (+ orgId: string,+ orgProjectIds: string[],+ candidates: { userIds: string[]; identityIds: string[] }+ ) =>+ membershipDAL.transaction(async (tx) => {+ await tx.raw(`SET LOCAL statement_timeout = ${RECONCILE_STATEMENT_TIMEOUT_MS}`);await orgDAL.lockActorsForOrgAccess([...candidates.userIds, ...candidates.identityIds], tx);const withAccess = await orgDAL.findActorsWithOrgAccess({ orgId, ...candidates }, tx);@@ -144,7 +147,6 @@ export const orgAccessReconcileConsumerFactory = ({? await membershipDAL.find({ ...projectScope, $in: { actorIdentityId: identityIds } }, { tx }): [];- const orgProjectIds = (await projectDAL.find({ orgId }, { tx })).map((project) => project.id);const resourceScope = { scope: RESOURCE_SCOPE };const userResourceRows =orgProjectIds.length && userIds.length@@ -214,25 +216,33 @@ export const orgAccessReconcileConsumerFactory = ({return { revoked, sendPamCancellations };});- if (!outcome) return;- outcome.sendPamCancellations();-- if (!outcome.revoked.length) return;+ // 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.+ const $reconcileOrg = async (orgId: string, scope: TReconcileScope, reason: string) => {+ const org = await orgDAL.findById(orgId);+ if (!org) return;+ const orgProjectIds = (await projectDAL.find({ orgId })).map((project) => project.id);- 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, resources, reason, groupId: scope.groupId }+ for await (const actors of chunkArray(scope.actors, ACTORS_PER_RECONCILE_TX)) {+ const outcome = await $revokeActors(orgId, orgProjectIds, splitActors(actors));+ if (outcome) outcome.sendPamCancellations();+ if (outcome?.revoked.length) {+ 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, resources, reason, groupId: scope.groupId }+ }+ });}- });- }- usageMeteringService.emit(orgId, SecretIdentities.key);- usageMeteringService.emit(orgId, PamIdentities.key);- usageMeteringService.emit(orgId, AgentVaultIdentities.key);+ usageMeteringService.emit(orgId, SecretIdentities.key);+ usageMeteringService.emit(orgId, PamIdentities.key);+ usageMeteringService.emit(orgId, AgentVaultIdentities.key);+ }+ }};const $handleEvent = async (event: TEvent): Promise<TEventConsumerResult> => {