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(agent-vault): lock memberships in id order before removing them from Agent Vault
Scott Wilsone4bb7af1ce02
diff --git a/backend/src/ee/services/agent-vault-delegation/agent-vault-delegation-dal.ts b/backend/src/ee/services/agent-vault-delegation/agent-vault-delegation-dal.tsindex 3c36caaf83..7e13619d91 100644--- a/backend/src/ee/services/agent-vault-delegation/agent-vault-delegation-dal.ts+++ b/backend/src/ee/services/agent-vault-delegation/agent-vault-delegation-dal.ts@@ -350,7 +350,8 @@ export const agentVaultDelegationDALFactory = (db: TDbClient) => {if (userIds.length) void actor.orWhereIn(`${TableName.Membership}.actorUserId`, userIds);if (groupIds.length) void actor.orWhereIn(`${TableName.Membership}.actorGroupId`, groupIds);})- // In id order, the order a removal's multi-row delete takes them, so the two can't each wait on the other.+ // In id order, the order a removal of several memberships locks them in (lockMembershipsById) before it+ // deletes, so the two can't each wait on the other..orderBy(`${TableName.Membership}.id`).forShare().select(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 83d69e7e90..16da2491fa 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@@ -3,9 +3,16 @@ import { describe, expect, test, vi } from "vitest";import { AccessScope, ProjectMembershipRole } from "@app/db/schemas";import { AgentVaultMemberType } from "@app/ee/services/agent-vault/agent-vault-enums";import { ActorType } from "@app/services/auth/auth-type";+import { lockMembershipsById } from "@app/services/membership/membership-dal";import { agentVaultMembershipServiceFactory } from "./agent-vault-membership-service";+// The real lock queries the database. Here only when the removal takes it matters.+vi.mock("@app/services/membership/membership-dal", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@app/services/membership/membership-dal")>()),+ lockMembershipsById: vi.fn(async () => [])+}));+const ORG_ID = "org-1";const PROJECT_ID = "project-1";const OTHER_PROJECT_ID = "project-2";@@ -212,9 +219,15 @@ describe("agentVaultMembership guards", () => {adminMembershipIds: ["mem-other"]});+ vi.mocked(lockMembershipsById).mockClear();await service.revokeProductMembers({ projectId: PROJECT_ID, ...addIds, ctx });expect(deps.membershipDAL.delete).toHaveBeenCalledWith({ $in: { id: ["mem-1"] } }, expect.anything());+ // Locked in id order before anything is deleted, the order a delegation save takes them in.+ expect(lockMembershipsById).toHaveBeenCalledWith(["mem-1"], expect.anything());+ expect(vi.mocked(lockMembershipsById).mock.invocationCallOrder[0]).toBeLessThan(+ vi.mocked(deps.membershipDAL.delete).mock.invocationCallOrder[0]+ );// Leaving Agent Vault loses every bundle, so the cleanup covers the whole project for this identity.expect(deps.agentVaultPersonalValueDAL.deleteForActorsWithoutGrant).toHaveBeenCalledWith({ projectId: PROJECT_ID, accessBundleId: undefined, userIds: [], identityIds: [IDENTITY_ID] },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 473d0b4dd4..384f14b1b4 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@@ -24,7 +24,7 @@ import { ActorType } from "@app/services/auth/auth-type";import { TIdentityDALFactory } from "@app/services/identity/identity-dal";import { AgentVaultIdentities } from "@app/services/license-client";import { TUsageMeteringServiceFactory } from "@app/services/license-client/usage";-import { TMembershipDALFactory } from "@app/services/membership/membership-dal";+import { lockMembershipsById, TMembershipDALFactory } from "@app/services/membership/membership-dal";import { assertWillRetainProjectAdmin } from "@app/services/membership/membership-fns";import { TMembershipRoleDALFactory } from "@app/services/membership/membership-role-dal";import { lockAndAssertActiveOrgAccess } from "@app/services/org/org-access-fns";@@ -669,6 +669,10 @@ export const agentVaultMembershipServiceFactory = ({tx});+ // In id order before anything is deleted, the order a delegation save takes them in. A multi-row delete takes+ // its rows in whatever order its plan reads them, so without this the two could each hold a row the other wants.+ await lockMembershipsById(membershipIds, tx);+await Promise.all(ALL_ACTOR_TYPES.map(async (type) => {const typeIds = named(held, type);diff --git a/backend/src/ee/services/agent-vault/AGENTS.md b/backend/src/ee/services/agent-vault/AGENTS.mdindex f5259f802a..3553392567 100644--- a/backend/src/ee/services/agent-vault/AGENTS.md+++ b/backend/src/ee/services/agent-vault/AGENTS.md@@ -190,7 +190,9 @@ is one `agent_vault_delegations` row per identity, with a scope of `all-members`the next save replaces the row instead of reviving it.- **A save locks parent rows, then memberships, then the delegation**, in the order deleting or removing them does:`FOR KEY SHARE` on the identity, users and groups, then the memberships `FOR SHARE` in id order. Changing the order- brings back deadlocks with identity deletion and with removal from Agent Vault. A remove or delete, which names no+ brings back deadlocks with identity deletion and with removal from Agent Vault. A removal that deletes several+ memberships locks them in id order first (`lockMembershipsById`), since a multi-row delete takes its rows in plan+ order. A remove or delete, which names nonew subjects, still takes the identity's membership before the delegation row for the same reason. Every write locksthe delegation row before reading or replacing it, and `updatedAt` moves only on a save or a real add or remove.- **Delegation routes take no `AuthMode.OAUTH`.** The admin check reads the role, which a delegated token's scopes