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 delegation writes in removal order and keep updatedAt honest
Scott Wilsoneaadaa090daf
diff --git a/backend/e2e-test/routes/v1/agent-vault.spec.ts b/backend/e2e-test/routes/v1/agent-vault.spec.tsindex 445a03404d..a10c0d3f3f 100644--- a/backend/e2e-test/routes/v1/agent-vault.spec.ts+++ b/backend/e2e-test/routes/v1/agent-vault.spec.ts@@ -4546,6 +4546,7 @@ describe("Agent Vault V1 Router", async () => {type TMissing = { missingAccessBundles: { id: string; name: string }[] };type TDelegationDetail = TMissing & {scope: string;+ updatedAt: string;users: (TMissing & { id: string; addedAt: string })[];groups: (TMissing & { id: string; addedAt: string })[];};@@ -5203,6 +5204,17 @@ describe("Agent Vault V1 Router", async () => {expect(await available()).toEqual([carol.userId]);expect(await available("&actorType=group")).toEqual([]);+ // An identity that isn't in Agent Vault has no candidates to offer, the same 404 as its other subject routes.+ const unknown = await inject("GET", `${delegationUrl(crypto.randomUUID())}/subjects/available`);+ expect(unknown.statusCode).toBe(404);+ expect(unknown.json().message).toContain("is not a member of Agent Vault");++ // updatedAt moves only when someone is added or taken out, so a client can cache the delegation off it.+ const savedAt = (now.json().delegation as TDelegationDetail).updatedAt;+ const again = await inject("POST", subjectsUrl, { userIds: [alice.userId] });+ expect(again.statusCode).toBe(200);+ expect((again.json().delegation as TDelegationDetail).updatedAt).toBe(savedAt);+const stranger = await inject("POST", subjectsUrl, { userIds: [outsider.userId] });expect(stranger.statusCode).toBe(400);expect(stranger.json().message).toContain("are not members of Agent Vault");@@ -5212,6 +5224,9 @@ describe("Agent Vault V1 Router", async () => {const lessAlice = await inject("DELETE", subjectsUrl, { userIds: [alice.userId, carol.userId] });expect(lessAlice.statusCode).toBe(200);expect(named(lessAlice)).toEqual({ users: [bob.userId], groups: [group.id] });+ expect(new Date((lessAlice.json().delegation as TDelegationDetail).updatedAt).getTime()).toBeGreaterThan(+ new Date(savedAt).getTime()+ );const emptied = await inject("DELETE", subjectsUrl, { userIds: [bob.userId], groupIds: [group.id] });expect(emptied.statusCode).toBe(200);expect(emptied.json().delegation).toBeNull();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 c30e79d8b9..3c36caaf83 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@@ -69,21 +69,28 @@ export const agentVaultDelegationDALFactory = (db: TDbClient) => {}};- // Creates a selected delegation, or locks the one already there and returns it with its scope unchanged. The conflict- // waits for a save still writing the row, so the returned scope is the committed one.- const createSelectedOrLock = async (+ // Creates a selected delegation if the identity has none. One a concurrent save is still writing is waited for and+ // left as it is, so the caller locks and reads the row afterwards to see its committed scope.+ const insertSelectedIfMissing = async ({ projectId, identityId, membershipId }: { projectId: string; identityId: string; membershipId: string },tx: Knex- ): Promise<TAgentVaultDelegations> => {+ ) => {try {- const [row] = (await tx(TableName.AgentVaultDelegation)+ await tx(TableName.AgentVaultDelegation).insert({ projectId, identityId, membershipId, scope: AgentVaultDelegationScope.Selected }).onConflict(["identityId", "projectId"])- .merge({ membershipId })- .returning("*")) as TAgentVaultDelegations[];- return row;+ .ignore();+ } catch (error) {+ throw new DatabaseError({ error, name: "Create Agent Vault delegation" });+ }+ };++ // Adding or removing subjects writes only the subject rows, so this is what moves the delegation's updatedAt.+ const markChanged = async (delegationId: string, tx: Knex) => {+ try {+ await tx.raw(`UPDATE ?? SET "updatedAt" = now() WHERE id = ?`, [TableName.AgentVaultDelegation, delegationId]);} catch (error) {- throw new DatabaseError({ error, name: "Create or lock Agent Vault delegation" });+ throw new DatabaseError({ error, name: "Mark Agent Vault delegation changed" });}};@@ -360,7 +367,8 @@ export const agentVaultDelegationDALFactory = (db: TDbClient) => {return {...orm,upsertScope,- createSelectedOrLock,+ insertSelectedIfMissing,+ markChanged,insertSubjectsSkippingNamed,deleteIfNamesNoOne,lockForIdentity,diff --git a/backend/src/ee/services/agent-vault-delegation/agent-vault-delegation-service.ts b/backend/src/ee/services/agent-vault-delegation/agent-vault-delegation-service.tsindex 62555cf317..522e6804d7 100644--- a/backend/src/ee/services/agent-vault-delegation/agent-vault-delegation-service.ts+++ b/backend/src/ee/services/agent-vault-delegation/agent-vault-delegation-service.ts@@ -34,7 +34,8 @@ type TAgentVaultDelegationServiceFactoryDep = {agentVaultDelegationDAL: Pick<TAgentVaultDelegationDALFactory,| "upsertScope"- | "createSelectedOrLock"+ | "insertSelectedIfMissing"+ | "markChanged"| "insertSubjectsSkippingNamed"| "deleteIfNamesNoOne"| "lockForIdentity"@@ -108,16 +109,27 @@ export const agentVaultDelegationServiceFactory = ({};// Project-scoped, so an identity from another org is a 404 like one that doesn't exist.+ const notInAgentVault = (machineIdentityId: string) =>+ new NotFoundError({+ message: `Machine identity with ID '${machineIdentityId}' is not a member of Agent Vault. Add it under Access Control first.`+ });const requireIdentityMembership = (memberships: TLockedMembership[], machineIdentityId: string) => {const identityMembership = memberships.find((row) => row.actorIdentityId === machineIdentityId);- if (!identityMembership) {- throw new NotFoundError({- message: `Machine identity with ID '${machineIdentityId}' is not a member of Agent Vault. Add it under Access Control first.`- });- }+ if (!identityMembership) throw notInAgentVault(machineIdentityId);return identityMembership;};+ // Removing the identity from Agent Vault deletes its membership, then cascades to the delegation and its subjects.+ // A write that changes only the delegation still takes the membership first, so the two lock in the same order.+ const lockIdentityMembership = async (projectId: string, machineIdentityId: string, tx: Knex) =>+ requireIdentityMembership(+ await agentVaultDelegationDAL.lockMemberships(+ { projectId, identityId: machineIdentityId, userIds: [], groupIds: [] },+ tx+ ),+ machineIdentityId+ );+const notFound = (machineIdentityId: string) =>new NotFoundError({message: `Machine identity with ID '${machineIdentityId}' has no delegation, so it can't act on behalf of users`@@ -354,6 +366,8 @@ export const agentVaultDelegationServiceFactory = ({tx);+ // Locked first, so a remove of the last subject still in flight is waited for and its emptied row replaced.+ await agentVaultDelegationDAL.lockForIdentity({ projectId, identityId: machineIdentityId }, tx);await agentVaultDelegationDAL.deleteIfNamesNoOne({ projectId, identityId: machineIdentityId }, tx);const row = await agentVaultDelegationDAL.upsertScope({ projectId, identityId: machineIdentityId, membershipId: identityMembership.id, scope },@@ -417,17 +431,20 @@ export const agentVaultDelegationServiceFactory = ({refuseAllMembers(current?.scope);await agentVaultDelegationDAL.deleteIfNamesNoOne({ projectId, identityId: machineIdentityId }, tx);- // With no row there was nothing to lock above, so a save can have created one since: checked again here.- const row = await agentVaultDelegationDAL.createSelectedOrLock(+ await agentVaultDelegationDAL.insertSelectedIfMissing({ projectId, identityId: machineIdentityId, membershipId: identityMembership.id },tx);+ // With no row there was nothing to lock above, so a save can have created one since: locked and checked again.+ const row = await agentVaultDelegationDAL.lockForIdentity({ projectId, identityId: machineIdentityId }, tx);+ if (!row) throw notFound(machineIdentityId);refuseAllMembers(row.scope);const added = await agentVaultDelegationDAL.insertSubjectsSkippingNamed({ delegationId: row.id, membershipIds: membershipIdsNaming(memberships, userIds, groupIds) },tx);+ if (added) await agentVaultDelegationDAL.markChanged(row.id, tx);// Read in the transaction because the replica may not have the write yet.const {delegations: [written]@@ -451,6 +468,7 @@ export const agentVaultDelegationServiceFactory = ({await checkIdentityPermission({ projectId, ctx, machineIdentityId }, ProjectPermissionIdentityActions.Edit);const changed = await agentVaultDelegationDAL.transaction(async (tx) => {+ await lockIdentityMembership(projectId, machineIdentityId, tx);const current = await agentVaultDelegationDAL.lockForIdentity({ projectId, identityId: machineIdentityId }, tx);const viewNow = async () =>(await agentVaultDelegationDAL.findViews({ projectId, identityIds: [machineIdentityId] }, tx)).delegations[0];@@ -466,6 +484,7 @@ export const agentVaultDelegationServiceFactory = ({{ delegationId: current.id, userIds, groupIds },tx);+ if (removed) await agentVaultDelegationDAL.markChanged(current.id, tx);return { before, after: (await viewNow()) ?? null, isChanged: removed > 0 };});if (!changed) throw notFound(machineIdentityId);@@ -484,6 +503,13 @@ export const agentVaultDelegationServiceFactory = ({}: TListAvailableDelegationSubjectsDTO) => {await checkIdentityPermission({ projectId, ctx, machineIdentityId }, ProjectPermissionIdentityActions.Read);+ const [identityMembership] = await membershipDAL.find({+ scope: AccessScope.Project,+ scopeProjectId: projectId,+ actorIdentityId: machineIdentityId+ });+ if (!identityMembership) throw notInAgentVault(machineIdentityId);+const delegation = await agentVaultDelegationDAL.findForIdentity({ projectId, identityId: machineIdentityId });return agentVaultMemberDAL.findProductMembers({projectId,@@ -500,6 +526,9 @@ export const agentVaultDelegationServiceFactory = ({await checkIdentityPermission({ projectId, ctx, machineIdentityId }, ProjectPermissionIdentityActions.Edit);const deleted = await agentVaultDelegationDAL.transaction(async (tx) => {+ await lockIdentityMembership(projectId, machineIdentityId, tx);+ // Locked before the read, so the audit entry lists exactly who the delete removed.+ await agentVaultDelegationDAL.lockForIdentity({ projectId, identityId: machineIdentityId }, tx);const {delegations: [delegation]} = await agentVaultDelegationDAL.findViews({ projectId, identityIds: [machineIdentityId] }, tx);diff --git a/backend/src/ee/services/agent-vault/AGENTS.md b/backend/src/ee/services/agent-vault/AGENTS.mdindex 87535fb907..1e0f316fb4 100644--- a/backend/src/ee/services/agent-vault/AGENTS.md+++ b/backend/src/ee/services/agent-vault/AGENTS.md@@ -183,7 +183,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.+ brings back deadlocks with identity deletion and with removal from Agent Vault. A remove or delete, which names no+ new subjects, still takes the identity's membership before the delegation row for the same reason. Every write locks+ the 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 scopesdon't narrow, and a delegation lets an identity act as other users.diff --git a/frontend/src/components/agent-vault/ManageDelegationSheet.tsx b/frontend/src/components/agent-vault/ManageDelegationSheet.tsxindex 3b94188d3e..12a601f7b3 100644--- a/frontend/src/components/agent-vault/ManageDelegationSheet.tsx+++ b/frontend/src/components/agent-vault/ManageDelegationSheet.tsx@@ -1,7 +1,6 @@import { useEffect, useRef, useState } from "react";import { format } from "date-fns";import {- BotIcon,ChevronDownIcon,FilterIcon,SearchIcon,@@ -505,10 +504,6 @@ const ManageDelegationContent = ({Manage Delegation<DocumentationLinkBadge href={AgentVaultDocsUrls.sessionsOnBehalfOfUsers} /></SheetTitle>- <div className="flex min-w-0 items-center gap-2 rounded-md border border-border bg-neutral/5 px-3 py-2 text-xs">- <BotIcon className="size-3.5 shrink-0 text-muted" />- <span className="truncate text-foreground">{identity.name}</span>- </div></SheetHeader><div className="thin-scrollbar flex-1 space-y-4 overflow-y-auto p-4">diff --git a/frontend/src/components/agent-vault/MissingAccessBundlesHint.tsx b/frontend/src/components/agent-vault/MissingAccessBundlesHint.tsxindex 289bf674fe..d8bb1bd4ed 100644--- a/frontend/src/components/agent-vault/MissingAccessBundlesHint.tsx+++ b/frontend/src/components/agent-vault/MissingAccessBundlesHint.tsx@@ -1,7 +1,13 @@import { Link } from "@tanstack/react-router";import { PackageIcon } from "lucide-react";-import { Badge, HoverCard, HoverCardContent, HoverCardTrigger } from "@app/components/v3";+import {+ Badge,+ HoverCard,+ HoverCardContent,+ HoverCardTrigger,+ ScrollableContent+} from "@app/components/v3";import { useOrganization } from "@app/context";import { TAgentVaultMissingAccessBundle } from "@app/hooks/api/agentVault/types";@@ -35,7 +41,17 @@ export const MissingAccessBundlesHint = ({ bundles, machineIdentityName, onBehal<p className="text-xs text-muted">{`Sessions on behalf of ${onBehalfOf} can't use these access bundles, because "${machineIdentityName}" isn't granted them.`}</p>- <div className="flex flex-wrap gap-1.5">+ {/* An all-members delegation can miss every bundle in a large org; scrolling keeps each one a link. The card+ portals outside the sheet, whose scroll lock would otherwise swallow the wheel. */}+ <ScrollableContent+ aria-label="Excluded access bundles"+ edgeBehavior="fade"+ outline={false}+ maxHeight="12rem"+ className="overscroll-contain"+ contentClassName="flex flex-wrap gap-1.5"+ onWheel={(event) => event.stopPropagation()}+ >{bundles.map((bundle) => (<Badge key={bundle.id} variant="neutral" iconPosition="left" asChild><Link@@ -47,7 +63,7 @@ export const MissingAccessBundlesHint = ({ bundles, machineIdentityName, onBehal</Link></Badge>))}- </div>+ </ScrollableContent><p className="text-xs text-muted">{`To include one, grant it to "${machineIdentityName}" from the bundle's Manage Access.`}</p>