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
escalate lock to avoid instance stall
Thiago Araujo da Silva70a8429e8624
diff --git a/backend/AGENTS.md b/backend/AGENTS.mdindex 42b806e96e..7065fcb5e7 100644--- a/backend/AGENTS.md+++ b/backend/AGENTS.md@@ -936,9 +936,13 @@ itself whether the actor still reaches the org.group-derived PAM admin's personal folder row), and the consumer reaps both.- **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`** (advisory xact locks, one statement over the sorted ids so callers- can't deadlock) serializes everything that grants against the consumer, so access granted between its- check and its deletes doesn't get reaped or outlive it. Two kinds of caller take it:+- **`orgDAL.lockActorsForOrgAccess({ orgId, actorIds }, tx)`** serializes everything that grants against the+ consumer, so access granted between its check and its deletes doesn't get reaped or outlive it. Advisory+ xact locks at two levels: the root org (resolved from `orgId`) shared plus one key per actor in one sorted+ statement, or, past `ORG_ACCESS_LOCK_ESCALATION_THRESHOLD` actors, the root org exclusive and no actor+ keys. The escalation keeps a bulk SCIM sync from filling Postgres's shared lock table, which would fail+ unrelated transactions instance-wide; the price is that such a sync stalls other grants in its own tenant+ until it commits. Root org first, then sorted actors, so callers can't deadlock. Two kinds of caller take it:- The add-to-group helpers in `group-fns.ts` (the SSO and SCIM services only pass it through) and GitHub orgsync, which adds team members itself. Take it in any new path that grants an org path outside them.- Every path that writes a project or resource membership for a user or identity, throughdiff --git a/backend/src/ee/services/github-org-sync/github-org-sync-reconcile.test.ts b/backend/src/ee/services/github-org-sync/github-org-sync-reconcile.test.tsindex e06b0915bc..399a35274e 100644--- a/backend/src/ee/services/github-org-sync/github-org-sync-reconcile.test.ts+++ b/backend/src/ee/services/github-org-sync/github-org-sync-reconcile.test.ts@@ -171,8 +171,8 @@ describe("GitHub org sync and org access reconcile", () => {// One add for the new group, one for the existing group, each behind the lock.expect(insertMany).toHaveBeenCalledTimes(2);expect(lockActorsForOrgAccess).toHaveBeenCalledTimes(2);- lockActorsForOrgAccess.mock.calls.forEach(([actorIds, tx]) => {- expect(actorIds).toEqual(["user-1"]);+ lockActorsForOrgAccess.mock.calls.forEach(([scope, tx]) => {+ expect(scope).toEqual({ orgId: ORG_ID, actorIds: ["user-1"] });expect(tx).toBe(TX);});lockActorsForOrgAccess.mock.invocationCallOrder.forEach((lockOrder, index) => {@@ -234,7 +234,7 @@ describe("GitHub org sync and org access reconcile", () => {);expect(lockActorsForOrgAccess).toHaveBeenCalledTimes(1);- expect(lockActorsForOrgAccess).toHaveBeenCalledWith(["user-3"], TX);+ expect(lockActorsForOrgAccess).toHaveBeenCalledWith({ orgId: ORG_ID, actorIds: ["user-3"] }, TX);expect(lockActorsForOrgAccess.mock.invocationCallOrder[0]).toBeLessThan(insertMany.mock.invocationCallOrder[0]);});});diff --git a/backend/src/ee/services/github-org-sync/github-org-sync-service.ts b/backend/src/ee/services/github-org-sync/github-org-sync-service.tsindex f07398232e..32ae2fd1c8 100644--- a/backend/src/ee/services/github-org-sync/github-org-sync-service.ts+++ b/backend/src/ee/services/github-org-sync/github-org-sync-service.ts@@ -704,7 +704,7 @@ export const githubOrgSyncServiceFactory = ({tx);- await orgDAL.lockActorsForOrgAccess([userId], tx);+ await orgDAL.lockActorsForOrgAccess({ orgId, actorIds: [userId] }, tx);await userGroupMembershipDAL.insertMany(insertedGroups.map((el) => ({groupId: el.id,@@ -735,7 +735,7 @@ export const githubOrgSyncServiceFactory = ({if (updateTeams.length) {const groupsToUpdate = updateTeams.map((teamName) => githubUserTeamOnInfisicalGroupByName[teamName][0]);await groupDAL.transaction(async (tx) => {- await orgDAL.lockActorsForOrgAccess([userId], tx);+ await orgDAL.lockActorsForOrgAccess({ orgId, actorIds: [userId] }, tx);await userGroupMembershipDAL.insertMany(groupsToUpdate.map((group) => ({groupId: group.id,@@ -1141,7 +1141,7 @@ export const githubOrgSyncServiceFactory = ({const { usersToAdd, membershipsToRemove } = resolveMembershipChanges(latestMemberships);if (usersToAdd.length > 0) {- await orgDAL.lockActorsForOrgAccess(usersToAdd, tx);+ await orgDAL.lockActorsForOrgAccess({ orgId: orgPermission.orgId, actorIds: usersToAdd }, tx);await userGroupMembershipDAL.insertMany(usersToAdd.map((userId) => ({userId,diff --git a/backend/src/ee/services/group/group-fns.ts b/backend/src/ee/services/group/group-fns.tsindex cdd2de940d..0a5e3d0b2a 100644--- a/backend/src/ee/services/group/group-fns.ts+++ b/backend/src/ee/services/group/group-fns.ts@@ -271,10 +271,7 @@ export const addUsersToGroupByUserIds = async ({});});- await orgDAL.lockActorsForOrgAccess(- foundMembers.map((member) => member.id),- tx- );+ await orgDAL.lockActorsForOrgAccess({ orgId: group.orgId, actorIds: foundMembers.map((member) => member.id) }, tx);const membersToAddToGroupNonPending: TUsers[] = [];const membersToAddToGroupPending: TUsers[] = [];@@ -383,7 +380,7 @@ export const addIdentitiesToGroup = async ({}return identityDAL.transaction(async (tx) => {- await orgDAL.lockActorsForOrgAccess(identityIdsArray, tx);+ await orgDAL.lockActorsForOrgAccess({ orgId: group.orgId, actorIds: identityIdsArray }, tx);await identityGroupMembershipDAL.insertMany(foundIdentitiesMemberships.map((membership) => ({diff --git a/backend/src/ee/services/pam-session/pam-session-access-fns.test.ts b/backend/src/ee/services/pam-session/pam-session-access-fns.test.tsindex d50517d3cf..a04d5a3c4e 100644--- a/backend/src/ee/services/pam-session/pam-session-access-fns.test.ts+++ b/backend/src/ee/services/pam-session/pam-session-access-fns.test.ts@@ -54,7 +54,7 @@ describe("assertUserStillActiveInOrg", () => {test("passes a user who reaches the sub-org only through a group, under the actor lock", async () => {const { run, orgDAL } = build({ rows: { "root-org": { isActive: true } }, groupAccessOrgIds: ["sub-org"] });await expect(run()).resolves.toBeUndefined();- expect(orgDAL.lockActorsForOrgAccess).toHaveBeenCalledWith(["user-1"], tx);+ expect(orgDAL.lockActorsForOrgAccess).toHaveBeenCalledWith({ orgId: "sub-org", actorIds: ["user-1"] }, tx);expect(orgDAL.lockActorsForOrgAccess.mock.invocationCallOrder[0]).toBeLessThan(orgDAL.findActorsWithActiveOrgAccess.mock.invocationCallOrder[0]);diff --git a/backend/src/ee/services/pam-session/pam-session-access-fns.ts b/backend/src/ee/services/pam-session/pam-session-access-fns.tsindex ad3c125288..69ce6761d3 100644--- a/backend/src/ee/services/pam-session/pam-session-access-fns.ts+++ b/backend/src/ee/services/pam-session/pam-session-access-fns.ts@@ -226,7 +226,7 @@ export const assertUserStillActiveInOrg = async ({const membership = await membershipDAL.lockOrgMembershipForUser(id, userId, tx);let isActive = Boolean(membership?.isActive);if (!membership) {- await orgDAL.lockActorsForOrgAccess([userId], tx);+ await orgDAL.lockActorsForOrgAccess({ orgId: id, actorIds: [userId] }, tx);const withAccess = await orgDAL.findActorsWithActiveOrgAccess({ orgId: id, userIds: [userId], identityIds: [] },txdiff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.tsindex d2a56a64aa..fbe25ecb29 100644--- a/backend/src/keystore/keystore.ts+++ b/backend/src/keystore/keystore.ts@@ -43,6 +43,7 @@ export const PgSqlLock = {KmsProjectDataKeyCreation: (projectId: string) => pgAdvisoryLockHashText(`kms-project-data-key:${projectId}`),ScimGroupUpdate: (groupId: string) => pgAdvisoryLockHashText(`scim-group-update:${groupId}`),OrgAccessReconcile: (actorId: string) => pgAdvisoryLockHashText(`org-access-reconcile:${actorId}`),+ OrgAccessReconcileScope: (rootOrgId: string) => pgAdvisoryLockHashText(`org-access-reconcile-scope:${rootOrgId}`),LastAdminGuard: (scope: "org" | "project", scopeId: string) =>pgAdvisoryLockHashText(`last-admin-guard:${scope}:${scopeId}`),AuditReportRequest: (projectId: string) => pgAdvisoryLockHashText(`audit-report-request:${projectId}`),diff --git a/backend/src/services/org/org-access-fns.test.ts b/backend/src/services/org/org-access-fns.test.tsindex fbd88900fb..58a2a90f1e 100644--- a/backend/src/services/org/org-access-fns.test.ts+++ b/backend/src/services/org/org-access-fns.test.ts@@ -23,7 +23,7 @@ describe("lockAndAssertActiveOrgAccess", () => {await lockAndAssertActiveOrgAccess({ orgDAL, orgId: "org", userIds: ["u1"], identityIds: ["i1"] }, tx);expect(calls).toEqual(["lock", "check"]);- expect(orgDAL.lockActorsForOrgAccess).toHaveBeenCalledWith(["u1", "i1"], tx);+ expect(orgDAL.lockActorsForOrgAccess).toHaveBeenCalledWith({ orgId: "org", actorIds: ["u1", "i1"] }, tx);expect(orgDAL.findActorsWithActiveOrgAccess).toHaveBeenCalledWith({ orgId: "org", userIds: ["u1"], identityIds: ["i1"] },txdiff --git a/backend/src/services/org/org-access-fns.ts b/backend/src/services/org/org-access-fns.tsindex 3369bea654..3508bc1845 100644--- a/backend/src/services/org/org-access-fns.ts+++ b/backend/src/services/org/org-access-fns.ts@@ -49,7 +49,7 @@ export const lockAndAssertActiveOrgAccess = async () => {if (!userIds.length && !identityIds.length) return;- await orgDAL.lockActorsForOrgAccess([...userIds, ...identityIds], tx);+ await orgDAL.lockActorsForOrgAccess({ orgId, actorIds: [...userIds, ...identityIds] }, tx);const withAccess = await orgDAL.findActorsWithActiveOrgAccess({ orgId, userIds, identityIds }, tx);const lost = [...userIds.filter((id) => !withAccess.userIds.has(id)),diff --git a/backend/src/services/org/org-access-reconcile-consumer.test.ts b/backend/src/services/org/org-access-reconcile-consumer.test.tsindex df3103e36f..56037c5867 100644--- a/backend/src/services/org/org-access-reconcile-consumer.test.ts+++ b/backend/src/services/org/org-access-reconcile-consumer.test.ts@@ -207,7 +207,7 @@ describe("org access reconcile consumer", () => {const [orgResult] = await consumer.handle([userRemovedFromOrg()]);expect(orgResult.status).toBe(EventResultStatus.Delivered);- expect(deps.orgDAL.lockActorsForOrgAccess).toHaveBeenCalledWith([USER_ID], tx);+ expect(deps.orgDAL.lockActorsForOrgAccess).toHaveBeenCalledWith({ orgId: ORG_ID, actorIds: [USER_ID] }, tx);expect(deps.projectAccessRevokeService.revokeActorsInOrgs).toHaveBeenCalledWith({ orgIds: [ORG_ID], userIds: [USER_ID], identityIds: [] },tx@@ -352,10 +352,14 @@ describe("org access reconcile consumer", () => {expect(tx.raw).toHaveBeenCalledWith(expect.stringContaining("SET LOCAL statement_timeout"));expect(deps.orgDAL.lockActorsForOrgAccess).toHaveBeenNthCalledWith(1,- userIds.slice(0, ACTORS_PER_RECONCILE_TX),+ { orgId: ORG_ID, actorIds: userIds.slice(0, ACTORS_PER_RECONCILE_TX) },+ tx+ );+ expect(deps.orgDAL.lockActorsForOrgAccess).toHaveBeenNthCalledWith(+ 2,+ { orgId: ORG_ID, actorIds: userIds.slice(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 d9559a6f6a..b90df5b5ab 100644--- a/backend/src/services/org/org-access-reconcile-consumer.ts+++ b/backend/src/services/org/org-access-reconcile-consumer.ts@@ -104,7 +104,7 @@ export const orgAccessReconcileConsumerFactory = ({const $revokeActors = async (orgId: string, candidates: { userIds: string[]; identityIds: string[] }) =>orgDAL.transaction(async (tx) => {await tx.raw(`SET LOCAL statement_timeout = ${RECONCILE_STATEMENT_TIMEOUT_MS}`);- await orgDAL.lockActorsForOrgAccess([...candidates.userIds, ...candidates.identityIds], tx);+ await orgDAL.lockActorsForOrgAccess({ orgId, actorIds: [...candidates.userIds, ...candidates.identityIds] }, tx);const withAccess = await orgDAL.findActorsWithOrgAccess({ orgId, ...candidates }, tx);const userIds = candidates.userIds.filter((id) => !withAccess.userIds.has(id));diff --git a/backend/src/services/org/org-dal.test.ts b/backend/src/services/org/org-dal.test.tsnew file mode 100644index 0000000000..123e2b1890--- /dev/null+++ b/backend/src/services/org/org-dal.test.ts@@ -0,0 +1,92 @@+import { Knex } from "knex";++import { TableName } from "@app/db/schemas";+import { PgSqlLock } from "@app/keystore/keystore";++import { ORG_ACCESS_LOCK_ESCALATION_THRESHOLD, orgDALFactory } from "./org-dal";++const ROOT_ORG_ID = "root-org";+const SUB_ORG_ID = "sub-org";++const buildTx = (orgs: Record<string, { rootOrgId: string | null }>) => {+ const raws: [string, unknown[] | undefined][] = [];+ const tables: string[] = [];+ const queryBuilder = (table: string) => {+ tables.push(table);+ let id: string | undefined;+ const chain = {+ where: (filter: { id: string }) => {+ id = filter.id;+ return chain;+ },+ select: () => chain,+ first: async () => (id ? orgs[id] : undefined)+ };+ return chain;+ };+ const tx = Object.assign(queryBuilder, {+ raw: vi.fn(async (sql: string, bindings?: unknown[]) => {+ raws.push([sql, bindings]);+ })+ }) as unknown as Knex;+ return { tx, raws, tables };+};++const dal = orgDALFactory({} as never);++describe("lockActorsForOrgAccess", () => {+ test("takes the tenant shared, then every actor exclusive in one sorted statement", async () => {+ const { tx, raws, tables } = buildTx({ [ROOT_ORG_ID]: { rootOrgId: null } });++ await dal.lockActorsForOrgAccess({ orgId: ROOT_ORG_ID, actorIds: ["b", "a", "b"] }, tx);++ expect(tables).toEqual([TableName.Organization]);+ expect(raws).toEqual([+ ["SELECT pg_advisory_xact_lock_shared(?)", [PgSqlLock.OrgAccessReconcileScope(ROOT_ORG_ID)]],+ [+ "SELECT pg_advisory_xact_lock(k) FROM unnest(?::int[]) AS k",+ [[PgSqlLock.OrgAccessReconcile("a"), PgSqlLock.OrgAccessReconcile("b")]]+ ]+ ]);+ });++ test("scopes a sub-org to its root org, since a root-org group reaches the sub-org", async () => {+ const { tx, raws } = buildTx({ [SUB_ORG_ID]: { rootOrgId: ROOT_ORG_ID } });++ await dal.lockActorsForOrgAccess({ orgId: SUB_ORG_ID, actorIds: ["a"] }, tx);++ expect(raws[0]).toEqual([+ "SELECT pg_advisory_xact_lock_shared(?)",+ [PgSqlLock.OrgAccessReconcileScope(ROOT_ORG_ID)]+ ]);+ });++ test("escalates a bulk set to one exclusive tenant lock and no actor locks", async () => {+ const { tx, raws } = buildTx({ [SUB_ORG_ID]: { rootOrgId: ROOT_ORG_ID } });+ const actorIds = Array.from({ length: ORG_ACCESS_LOCK_ESCALATION_THRESHOLD + 1 }, (_, i) => `actor-${i}`);++ await dal.lockActorsForOrgAccess({ orgId: SUB_ORG_ID, actorIds }, tx);++ expect(raws).toEqual([["SELECT pg_advisory_xact_lock(?)", [PgSqlLock.OrgAccessReconcileScope(ROOT_ORG_ID)]]]);+ });++ test("stays per actor exactly at the threshold", async () => {+ const { tx, raws } = buildTx({ [ROOT_ORG_ID]: { rootOrgId: null } });+ const actorIds = Array.from({ length: ORG_ACCESS_LOCK_ESCALATION_THRESHOLD }, (_, i) => `actor-${i}`);++ await dal.lockActorsForOrgAccess({ orgId: ROOT_ORG_ID, actorIds }, tx);++ expect(raws).toHaveLength(2);+ expect(raws[0][0]).toBe("SELECT pg_advisory_xact_lock_shared(?)");+ expect((raws[1][1] as number[][])[0]).toHaveLength(ORG_ACCESS_LOCK_ESCALATION_THRESHOLD);+ });++ test("locks nothing for an empty set", async () => {+ const { tx, raws, tables } = buildTx({});++ await dal.lockActorsForOrgAccess({ orgId: ROOT_ORG_ID, actorIds: [] }, tx);++ expect(tables).toEqual([]);+ expect(raws).toEqual([]);+ });+});diff --git a/backend/src/services/org/org-dal.ts b/backend/src/services/org/org-dal.tsindex ec85c475de..1a05190f76 100644--- a/backend/src/services/org/org-dal.ts+++ b/backend/src/services/org/org-dal.ts@@ -54,6 +54,8 @@ type TOrphanedProjectActor = {scopeOrgId: string;};+export const ORG_ACCESS_LOCK_ESCALATION_THRESHOLD = 500;+export const orgDALFactory = (db: TDbClient) => {const orgOrm = ormify(db, TableName.Organization);@@ -1428,14 +1430,25 @@ export const orgDALFactory = (db: TDbClient) => {}};- // 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;+ // Serializes grants with the reconcile consumer. Two levels, like an engine escalating row locks to a table+ // lock: a small set takes the tenant shared plus one exclusive key per actor, a set past the threshold takes+ // the tenant exclusive and nothing per actor. Every key is a slot in Postgres's shared lock table (about+ // 6,400 on default settings), so a SCIM sync adding thousands would otherwise fill it and fail unrelated+ // transactions instance-wide; escalated, it only stalls grants in its own tenant. The tenant is the root org+ // because access never crosses one: a root-org group reaches its sub-orgs, nothing reaches another tenant.+ // Tenant first, then sorted actors in one statement, so two callers can't deadlock.+ const lockActorsForOrgAccess = async ({ orgId, actorIds }: { orgId: string; actorIds: string[] }, tx: Knex) => {+ const actorKeys = [...new Set(actorIds)].sort().map((actorId) => PgSqlLock.OrgAccessReconcile(actorId));+ if (!actorKeys.length) return;try {- await tx.raw("SELECT pg_advisory_xact_lock(k) FROM unnest(?::int[]) AS k", [keys]);+ const org = await tx(TableName.Organization).where({ id: orgId }).select("rootOrgId").first();+ const scopeKey = PgSqlLock.OrgAccessReconcileScope(org?.rootOrgId ?? orgId);+ if (actorKeys.length > ORG_ACCESS_LOCK_ESCALATION_THRESHOLD) {+ await tx.raw("SELECT pg_advisory_xact_lock(?)", [scopeKey]);+ return;+ }+ await tx.raw("SELECT pg_advisory_xact_lock_shared(?)", [scopeKey]);+ await tx.raw("SELECT pg_advisory_xact_lock(k) FROM unnest(?::int[]) AS k", [actorKeys]);} catch (error) {throw new DatabaseError({ error, name: "LockActorsForOrgAccess" });}