Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

fix(agent-vault): keep a concurrent all-members save when adding subjects

Scott Wilsonef277150fef2
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.ts
index 8d3ca34a04..c30e79d8b9 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,6 +69,42 @@ 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 (
+ { projectId, identityId, membershipId }: { projectId: string; identityId: string; membershipId: string },
+ tx: Knex
+ ): Promise<TAgentVaultDelegations> => {
+ try {
+ const [row] = (await tx(TableName.AgentVaultDelegation)
+ .insert({ projectId, identityId, membershipId, scope: AgentVaultDelegationScope.Selected })
+ .onConflict(["identityId", "projectId"])
+ .merge({ membershipId })
+ .returning("*")) as TAgentVaultDelegations[];
+ return row;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Create or lock Agent Vault delegation" });
+ }
+ };
+
+ // Returns how many were new: memberships the delegation already names are skipped.
+ const insertSubjectsSkippingNamed = async (
+ { delegationId, membershipIds }: { delegationId: string; membershipIds: string[] },
+ tx: Knex
+ ) => {
+ if (!membershipIds.length) return 0;
+ try {
+ const rows = await tx(SUBJECTS)
+ .insert(membershipIds.map((membershipId) => ({ delegationId, membershipId })))
+ .onConflict(["membershipId", "delegationId"])
+ .ignore()
+ .returning("id");
+ return rows.length;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Add Agent Vault delegation subjects" });
+ }
+ };
+
// A selected delegation whose subjects all left reads as none, so a save replaces it rather than reviving it with its
// old createdAt.
const deleteIfNamesNoOne = async ({ projectId, identityId }: { projectId: string; identityId: string }, tx: Knex) => {
@@ -324,6 +360,8 @@ export const agentVaultDelegationDALFactory = (db: TDbClient) => {
return {
...orm,
upsertScope,
+ createSelectedOrLock,
+ insertSubjectsSkippingNamed,
deleteIfNamesNoOne,
lockForIdentity,
removeSubjectsByActors,
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.ts
index e8aeba9c27..62555cf317 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,6 +34,8 @@ type TAgentVaultDelegationServiceFactoryDep = {
agentVaultDelegationDAL: Pick<
TAgentVaultDelegationDALFactory,
| "upsertScope"
+ | "createSelectedOrLock"
+ | "insertSubjectsSkippingNamed"
| "deleteIfNamesNoOne"
| "lockForIdentity"
| "removeSubjectsByActors"
@@ -394,7 +396,15 @@ export const agentVaultDelegationServiceFactory = ({
}: TChangeDelegationSubjectsDTO) => {
await checkIdentityPermission({ projectId, ctx, machineIdentityId }, ProjectPermissionIdentityActions.Edit);
- const delegation = await agentVaultDelegationDAL.transaction(async (tx) => {
+ const refuseAllMembers = (scope?: string) => {
+ if (scope === AgentVaultDelegationScope.AllMembers) {
+ throw new BadRequestError({
+ message: `Machine identity with ID '${machineIdentityId}' already acts on behalf of every Agent Vault member. To name users and groups instead, set its scope to selected.`
+ });
+ }
+ };
+
+ const { delegation, isChanged } = await agentVaultDelegationDAL.transaction(async (tx) => {
// The same order a save takes them in: memberships, then the delegation row.
const memberships = await agentVaultDelegationDAL.lockMemberships(
{ projectId, identityId: machineIdentityId, userIds, groupIds },
@@ -404,38 +414,29 @@ export const agentVaultDelegationServiceFactory = ({
await assertSubjectsInAgentVault({ projectId, userIds, groupIds, memberships }, tx);
const current = await agentVaultDelegationDAL.lockForIdentity({ projectId, identityId: machineIdentityId }, tx);
- if (current?.scope === AgentVaultDelegationScope.AllMembers) {
- throw new BadRequestError({
- message: `Machine identity with ID '${machineIdentityId}' already acts on behalf of every Agent Vault member. To name users and groups instead, set its scope to selected.`
- });
- }
+ refuseAllMembers(current?.scope);
await agentVaultDelegationDAL.deleteIfNamesNoOne({ projectId, identityId: machineIdentityId }, tx);
- const row = await agentVaultDelegationDAL.upsertScope(
- {
- projectId,
- identityId: machineIdentityId,
- membershipId: identityMembership.id,
- scope: AgentVaultDelegationScope.Selected
- },
+ // 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(
+ { projectId, identityId: machineIdentityId, membershipId: identityMembership.id },
tx
);
- const existing = new Set(
- (await agentVaultDelegationSubjectDAL.find({ delegationId: row.id }, { tx })).map((named) => named.membershipId)
- );
- const added = membershipIdsNaming(memberships, userIds, groupIds)
- .filter((membershipId) => !existing.has(membershipId))
- .map((membershipId) => ({ delegationId: row.id, membershipId }));
- if (added.length) await agentVaultDelegationSubjectDAL.insertMany(added, tx);
+ refuseAllMembers(row.scope);
+ const added = await agentVaultDelegationDAL.insertSubjectsSkippingNamed(
+ { delegationId: row.id, membershipIds: membershipIdsNaming(memberships, userIds, groupIds) },
+ tx
+ );
+ // Read in the transaction because the replica may not have the write yet.
const {
delegations: [written]
} = await agentVaultDelegationDAL.findViews({ projectId, identityIds: [machineIdentityId] }, tx);
- return { written, isChanged: added.length > 0 };
+ return { delegation: written, isChanged: added > 0 };
});
// isChanged lets the caller audit only a real change: naming users and groups already in it writes nothing.
- return { delegation: delegation.written, isChanged: delegation.isChanged };
+ return { delegation, isChanged };
};
// Names the delegation doesn't hold are skipped. Taking out the last one leaves a delegation that names no one, which
diff --git a/frontend/src/components/agent-vault/ManageDelegationSheet.tsx b/frontend/src/components/agent-vault/ManageDelegationSheet.tsx
index efcc3a5626..3b94188d3e 100644
--- a/frontend/src/components/agent-vault/ManageDelegationSheet.tsx
+++ b/frontend/src/components/agent-vault/ManageDelegationSheet.tsx
@@ -228,8 +228,13 @@ const ManageDelegationContent = ({
const deleteDelegation = useDeleteAgentVaultDelegation();
const addSubjects = useAddAgentVaultDelegationSubjects();
const removeSubjects = useRemoveAgentVaultDelegationSubjects();
+ // Every write's response replaces the cached delegation, so one at a time keeps a slower earlier
+ // response from overwriting a later one.
const isChanging =
- setDelegation.isPending || deleteDelegation.isPending || removeSubjects.isPending;
+ setDelegation.isPending ||
+ deleteDelegation.isPending ||
+ removeSubjects.isPending ||
+ addSubjects.isPending;
const subjects: TDelegationSubjectRow[] = [
...(delegation?.groups ?? []).map((group) => ({
@@ -257,7 +262,7 @@ const ManageDelegationContent = ({
const candidateCount = available?.totalCount ?? 0;
const isAvailableLoading = isAvailablePending || (isAvailablePlaceholder && !candidates.length);
// an added candidate stays in this list until the refetch lands
- const isAddLocked = addSubjects.isPending || isAvailableFetching;
+ const isAddLocked = isChanging || isAvailableFetching;
// A delegation that names no one has nothing above the fold, so the add list starts open. This
// content remounts per identity, so the first settled result is always this identity's own.