Skip to content

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

fix(agent-vault): hang delegations off Agent Vault memberships

Scott Wilsonb768fb0920f2
diff --git a/backend/e2e-test/routes/v1/agent-vault.spec.ts b/backend/e2e-test/routes/v1/agent-vault.spec.ts
index 83a0673459..30d0060dfe 100644
--- a/backend/e2e-test/routes/v1/agent-vault.spec.ts
+++ b/backend/e2e-test/routes/v1/agent-vault.spec.ts
@@ -5138,36 +5138,52 @@ describe("Agent Vault V1 Router", async () => {
}
});
- test("a save checks only the users and groups it adds", async () => {
+ test("leaving the organization takes a user out of every delegation", async () => {
const projectId = await getProjectId();
const bot = await createMemberIdentity(`obo-departed-bot-${Date.now()}`);
+ const carolOnlyBot = await createMemberIdentity(`obo-departed-carol-bot-${Date.now()}`);
const alice = await createAgentVaultUser("obo-departed-alice", projectId);
const carol = await createAgentVaultUser("obo-departed-carol", projectId);
- const dave = await createAgentVaultUser("obo-departed-dave", projectId);
- const userIdsOf = (delegation: TDelegationDetail) => delegation.users.map((row) => row.id).sort();
+ const userIdsOf = (res: { json: () => { delegation: TDelegationDetail } }) =>
+ res.json().delegation.users.map((row) => row.id);
try {
await delegate(bot, { scope: "selected", userIds: [alice.userId, carol.userId] });
- // Leaving the organization deletes the Agent Vault membership without Agent Vault's own removal.
- await testDb("memberships")
- .where({ scope: AccessScope.Project, scopeProjectId: projectId, actorUserId: carol.userId })
- .delete();
-
- const kept = await delegate(bot, { scope: "selected", userIds: [alice.userId, carol.userId, dave.userId] });
- expect(userIdsOf(kept)).toEqual([alice.userId, carol.userId, dave.userId].sort());
- const removed = await delegate(bot, { scope: "selected", userIds: [alice.userId, dave.userId] });
- expect(userIdsOf(removed)).toEqual([alice.userId, dave.userId].sort());
+ await delegate(carolOnlyBot, { scope: "selected", userIds: [carol.userId] });
- const added = await inject("PUT", delegationUrl(bot.id), {
+ const orgMembership = await testDb("memberships")
+ .where({ scope: AccessScope.Organization, scopeOrgId: seedData1.organization.id, actorUserId: carol.userId })
+ .first();
+ const left = await inject(
+ "DELETE",
+ `/api/v2/organizations/${seedData1.organization.id}/memberships/${orgMembership.id as string}`
+ );
+ expect(left.statusCode).toBe(200);
+
+ expect(userIdsOf(await inject("GET", delegationUrl(bot.id)))).toEqual([alice.userId]);
+ // A selected delegation left naming no one reads like none at all, at every endpoint.
+ expect((await inject("GET", delegationUrl(carolOnlyBot.id))).statusCode).toBe(404);
+ const listed = await inject("GET", `${delegationsUrl}?machineIdentityIds=${carolOnlyBot.id}`);
+ expect(listed.json()).toMatchObject({ delegations: [], totalCount: 0 });
+ const minted = await mintFor(carolOnlyBot, { userId: alice.userId }, "any-bundle");
+ expect(minted.statusCode).toBe(403);
+ expect(minted.json().message).toContain("isn't allowed to start sessions on behalf of users");
+
+ // Carol is a new subject again, so naming her is checked like any other addition.
+ const readded = await inject("PUT", delegationUrl(bot.id), {
scope: "selected",
userIds: [alice.userId, carol.userId]
});
- expect(added.statusCode).toBe(400);
- expect(added.json().message).toBe(
+ expect(readded.statusCode).toBe(400);
+ expect(readded.json().message).toBe(
`User(s) '${carol.userId}' are not members of Agent Vault. Add them under Access Control first.`
);
+ // An emptied delegation is replaced like any other.
+ const replaced = await delegate(carolOnlyBot, { scope: "selected", userIds: [alice.userId] });
+ expect(replaced.users.map((row) => row.id)).toEqual([alice.userId]);
} finally {
await bot.cleanup();
- await deleteUsers([alice.userId, carol.userId, dave.userId]);
+ await carolOnlyBot.cleanup();
+ await deleteUsers([alice.userId, carol.userId]);
}
});
@@ -5244,7 +5260,7 @@ describe("Agent Vault V1 Router", async () => {
}
});
- test("a user or group stops covering anyone once it leaves Agent Vault some other way", async () => {
+ test("a user or group leaves every delegation when it leaves Agent Vault some other way", async () => {
const projectId = await getProjectId();
const stamp = Date.now();
const bundle = await createAccessBundle(`obo-stale-${stamp}`);
@@ -5259,7 +5275,7 @@ describe("Agent Vault V1 Router", async () => {
{ groupId: named.id, userId: dave.userId },
{ groupId: other.id, userId: dave.userId }
]);
- // The generic project membership routes remove a member without clearing delegations.
+ // Stands in for the generic project membership routes, which delete the membership and nothing else.
const leaveAgentVault = (actor: { actorUserId: string } | { actorGroupId: string }) =>
testDb("memberships")
.where({ scope: AccessScope.Project, scopeProjectId: projectId, ...actor })
@@ -5275,6 +5291,8 @@ describe("Agent Vault V1 Router", async () => {
await leaveAgentVault({ actorUserId: carol.userId });
expect((await mintFor(bot, { userId: carol.userId }, bundle.name)).statusCode).toBe(403);
+ // Each subject went with its membership, so the emptied delegation is gone too.
+ expect((await inject("GET", delegationUrl(bot.id))).statusCode).toBe(404);
} finally {
await bot.cleanup();
await deleteUsers([carol.userId, dave.userId]);
diff --git a/backend/src/db/migrations/20261019120000_agent-vault-delegations.ts b/backend/src/db/migrations/20261019120000_agent-vault-delegations.ts
index 855e9df43f..0f17bd5358 100644
--- a/backend/src/db/migrations/20261019120000_agent-vault-delegations.ts
+++ b/backend/src/db/migrations/20261019120000_agent-vault-delegations.ts
@@ -27,7 +27,9 @@ export async function up(knex: Knex): Promise<void> {
}
// Which users a machine identity may start sessions on behalf of: everyone in Agent Vault, or the users and
- // groups listed in agent_vault_delegation_subjects. One row per identity.
+ // groups listed in agent_vault_delegation_subjects. One row per identity. A delegation and each of its subjects
+ // hang off an Agent Vault membership, so every way of leaving Agent Vault (Agent Vault's own removal, the generic
+ // project membership routes, leaving the organization, deleting the actor) takes them with it.
if (!(await knex.schema.hasTable(TableName.AgentVaultDelegation))) {
await knex.schema.createTable(TableName.AgentVaultDelegation, (t) => {
t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
@@ -39,6 +41,10 @@ export async function up(knex: Knex): Promise<void> {
t.uuid("identityId").notNullable();
t.foreign("identityId").references("id").inTable(TableName.Identity).onDelete("CASCADE");
+ // The identity's own Agent Vault membership. Unique, so the index also serves the cascade.
+ t.uuid("membershipId").notNullable().unique();
+ t.foreign("membershipId").references("id").inTable(TableName.Membership).onDelete("CASCADE");
+
t.string("scope", 32).notNullable();
t.timestamps(true, true, true);
@@ -63,28 +69,15 @@ export async function up(knex: Knex): Promise<void> {
t.foreign("delegationId").references("id").inTable(TableName.AgentVaultDelegation).onDelete("CASCADE");
t.index("delegationId");
- t.uuid("userId");
- t.foreign("userId").references("id").inTable(TableName.Users).onDelete("CASCADE");
-
- t.uuid("groupId");
- t.foreign("groupId").references("id").inTable(TableName.Groups).onDelete("CASCADE");
+ // The Agent Vault membership of the user or group the delegation names.
+ t.uuid("membershipId").notNullable();
+ t.foreign("membershipId").references("id").inTable(TableName.Membership).onDelete("CASCADE");
t.timestamp("createdAt", { useTz: true }).notNullable().defaultTo(knex.fn.now());
- });
- await knex.raw(
- `ALTER TABLE ?? ADD CONSTRAINT "agent_vault_delegation_subjects_one_subject" CHECK (num_nonnulls("userId", "groupId") = 1)`,
- [TableName.AgentVaultDelegationSubject]
- );
- // The subject column leads, so each index also serves its foreign key's cascade.
- await knex.raw(
- `CREATE UNIQUE INDEX "agent_vault_delegation_subjects_user_unique" ON ?? ("userId", "delegationId") WHERE "userId" IS NOT NULL`,
- [TableName.AgentVaultDelegationSubject]
- );
- await knex.raw(
- `CREATE UNIQUE INDEX "agent_vault_delegation_subjects_group_unique" ON ?? ("groupId", "delegationId") WHERE "groupId" IS NOT NULL`,
- [TableName.AgentVaultDelegationSubject]
- );
+ // membershipId leads, so the index also serves the membership foreign key's cascade.
+ t.unique(["membershipId", "delegationId"]);
+ });
}
}
diff --git a/backend/src/db/sanitized-schema.yaml b/backend/src/db/sanitized-schema.yaml
index c502ac8e5f..f7741e8f6c 100644
--- a/backend/src/db/sanitized-schema.yaml
+++ b/backend/src/db/sanitized-schema.yaml
@@ -48,8 +48,7 @@ tables:
columns:
- id
- delegationId
- - userId
- - groupId
+ - membershipId
- createdAt
- name: agent_vault_delegations
@@ -58,6 +57,7 @@ tables:
- id
- projectId
- identityId
+ - membershipId
- scope
- createdAt
- updatedAt
diff --git a/backend/src/db/schemas/agent-vault-delegation-subjects.ts b/backend/src/db/schemas/agent-vault-delegation-subjects.ts
index f9eeb33a32..dd683af432 100644
--- a/backend/src/db/schemas/agent-vault-delegation-subjects.ts
+++ b/backend/src/db/schemas/agent-vault-delegation-subjects.ts
@@ -10,8 +10,7 @@ import { TImmutableDBKeys } from "./models";
export const AgentVaultDelegationSubjectsSchema = z.object({
id: z.string().uuid(),
delegationId: z.string().uuid(),
- userId: z.string().uuid().nullable().optional(),
- groupId: z.string().uuid().nullable().optional(),
+ membershipId: z.string().uuid(),
createdAt: z.date()
});
diff --git a/backend/src/db/schemas/agent-vault-delegations.ts b/backend/src/db/schemas/agent-vault-delegations.ts
index fc074adc4b..73c1665a2a 100644
--- a/backend/src/db/schemas/agent-vault-delegations.ts
+++ b/backend/src/db/schemas/agent-vault-delegations.ts
@@ -11,6 +11,7 @@ export const AgentVaultDelegationsSchema = z.object({
id: z.string().uuid(),
projectId: z.string(),
identityId: z.string().uuid(),
+ membershipId: z.string().uuid(),
scope: z.string(),
createdAt: z.date(),
updatedAt: z.date()
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 f827777a01..e1a839bfef 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
@@ -27,20 +27,41 @@ export type TAgentVaultDelegationView = {
updatedAt: Date;
};
+const DELEGATION = TableName.AgentVaultDelegation;
+const SUBJECTS = TableName.AgentVaultDelegationSubject;
+
+/**
+ * A selected delegation counts only while it names someone. Each subject cascades away with its Agent Vault membership,
+ * which can empty one, and an empty one covers no one, so it reads exactly like no delegation at all.
+ */
+const whereNamesSomeone = (query: Knex.QueryBuilder, conn: Knex) =>
+ query.where((live) => {
+ void live
+ .where(`${DELEGATION}.scope`, AgentVaultDelegationScope.AllMembers)
+ .orWhereExists(
+ conn(SUBJECTS).whereRaw(`??.?? = ??.??`, [SUBJECTS, "delegationId", DELEGATION, "id"]).select(conn.raw("1"))
+ );
+ });
+
export const agentVaultDelegationDALFactory = (db: TDbClient) => {
const orm = ormify(db, TableName.AgentVaultDelegation);
// The row a conflict hits stays locked until the transaction ends, so two writes to one identity's delegation
// run one after the other.
const upsertScope = async (
- { projectId, identityId, scope }: { projectId: string; identityId: string; scope: AgentVaultDelegationScope },
+ {
+ projectId,
+ identityId,
+ membershipId,
+ scope
+ }: { projectId: string; identityId: string; membershipId: string; scope: AgentVaultDelegationScope },
tx: Knex
): Promise<TAgentVaultDelegations> => {
try {
const [row] = (await tx(TableName.AgentVaultDelegation)
- .insert({ projectId, identityId, scope })
+ .insert({ projectId, identityId, membershipId, scope })
.onConflict(["identityId", "projectId"])
- .merge({ scope })
+ .merge({ membershipId, scope })
.returning("*")) as TAgentVaultDelegations[];
return row;
} catch (error) {
@@ -65,7 +86,7 @@ export const agentVaultDelegationDALFactory = (db: TDbClient) => {
projectId
);
if (identityIds) void query.whereIn(`${TableName.AgentVaultDelegation}.identityId`, identityIds);
- return query;
+ return whereNamesSomeone(query, conn);
};
const countResult = (await filtered().count(`${TableName.AgentVaultDelegation}.id as count`).first()) as
@@ -90,12 +111,17 @@ export const agentVaultDelegationDALFactory = (db: TDbClient) => {
`${TableName.AgentVaultDelegationSubject}.delegationId`,
rows.map((row) => row.id)
)
- .leftJoin(TableName.Users, `${TableName.Users}.id`, `${TableName.AgentVaultDelegationSubject}.userId`)
- .leftJoin(TableName.Groups, `${TableName.Groups}.id`, `${TableName.AgentVaultDelegationSubject}.groupId`)
+ .join(
+ TableName.Membership,
+ `${TableName.Membership}.id`,
+ `${TableName.AgentVaultDelegationSubject}.membershipId`
+ )
+ .leftJoin(TableName.Users, `${TableName.Users}.id`, `${TableName.Membership}.actorUserId`)
+ .leftJoin(TableName.Groups, `${TableName.Groups}.id`, `${TableName.Membership}.actorGroupId`)
.select(
db.ref("delegationId").withSchema(TableName.AgentVaultDelegationSubject),
- db.ref("userId").withSchema(TableName.AgentVaultDelegationSubject),
- db.ref("groupId").withSchema(TableName.AgentVaultDelegationSubject),
+ db.ref("actorUserId").withSchema(TableName.Membership).as("userId"),
+ db.ref("actorGroupId").withSchema(TableName.Membership).as("groupId"),
db.ref("createdAt").withSchema(TableName.AgentVaultDelegationSubject).as("addedAt"),
db.ref("username").withSchema(TableName.Users),
db.ref("email").withSchema(TableName.Users),
@@ -147,38 +173,28 @@ export const agentVaultDelegationDALFactory = (db: TDbClient) => {
/**
* Under all-members every user is covered, otherwise the users the delegation names and the members of the groups
- * it names. Group membership is read the way the permission engine reads it, without isPending. A named user or
- * group counts only while it holds its own Agent Vault membership, so a row left behind by a removal that didn't
- * clear it, such as through the generic project membership routes, covers no one.
+ * it names. Group membership is read the way the permission engine reads it, without isPending. A subject exists
+ * only while its user's or group's own Agent Vault membership does, so this needs no membership check of its own.
*/
const coversUser = async (
- { delegation, userId }: { delegation: Pick<TAgentVaultDelegations, "id" | "scope" | "projectId">; userId: string },
+ { delegation, userId }: { delegation: Pick<TAgentVaultDelegations, "id" | "scope">; userId: string },
tx?: Knex
): Promise<boolean> => {
if (delegation.scope === AgentVaultDelegationScope.AllMembers) return true;
try {
const conn = tx || db.replicaNode();
- const subjects = TableName.AgentVaultDelegationSubject;
- const inAgentVault = (column: "actorUserId" | "actorGroupId", subjectColumn: "userId" | "groupId") =>
- conn(TableName.Membership)
- .where(`${TableName.Membership}.scope`, AccessScope.Project)
- .where(`${TableName.Membership}.scopeProjectId`, delegation.projectId)
- .whereRaw(`??.?? = ??.??`, [TableName.Membership, column, subjects, subjectColumn])
- .select(conn.raw("1"));
- const subject = await conn(subjects)
- .where(`${subjects}.delegationId`, delegation.id)
+ const subject = await conn(SUBJECTS)
+ .join(TableName.Membership, `${TableName.Membership}.id`, `${SUBJECTS}.membershipId`)
+ .where(`${SUBJECTS}.delegationId`, delegation.id)
.where((qb) => {
void qb
- .where((named) => {
- void named.where(`${subjects}.userId`, userId).whereExists(inAgentVault("actorUserId", "userId"));
- })
- .orWhere((viaGroup) => {
- void viaGroup
- .whereIn(`${subjects}.groupId`, conn(TableName.UserGroupMembership).select("groupId").where({ userId }))
- .whereExists(inAgentVault("actorGroupId", "groupId"));
- });
+ .where(`${TableName.Membership}.actorUserId`, userId)
+ .orWhereIn(
+ `${TableName.Membership}.actorGroupId`,
+ conn(TableName.UserGroupMembership).select("groupId").where({ userId })
+ );
})
- .select(db.ref("id").withSchema(TableName.AgentVaultDelegationSubject))
+ .select(db.ref("id").withSchema(SUBJECTS))
.first();
return Boolean(subject);
} catch (error) {
@@ -186,19 +202,30 @@ export const agentVaultDelegationDALFactory = (db: TDbClient) => {
}
};
- // False when the identity has no delegation at all.
- const identityCoversUser = async (
- { projectId, identityId, userId }: { projectId: string; identityId: string; userId: string },
+ // Undefined when the identity has no delegation, or only one left naming no one.
+ const findForIdentity = async (
+ { projectId, identityId }: { projectId: string; identityId: string },
tx?: Knex
- ): Promise<boolean> => {
- let delegation: TAgentVaultDelegations | undefined;
+ ): Promise<TAgentVaultDelegations | undefined> => {
try {
- delegation = (await (tx || db.replicaNode())(TableName.AgentVaultDelegation)
- .where({ projectId, identityId })
+ const conn = tx || db.replicaNode();
+ return (await whereNamesSomeone(
+ conn(DELEGATION).where(`${DELEGATION}.projectId`, projectId).where(`${DELEGATION}.identityId`, identityId),
+ conn
+ )
+ .select(selectAllTableCols(DELEGATION))
.first()) as TAgentVaultDelegations | undefined;
} catch (error) {
throw new DatabaseError({ error, name: "Find Agent Vault delegation" });
}
+ };
+
+ // False when the identity has no delegation at all.
+ const identityCoversUser = async (
+ { projectId, identityId, userId }: { projectId: string; identityId: string; userId: string },
+ tx?: Knex
+ ): Promise<boolean> => {
+ const delegation = await findForIdentity({ projectId, identityId }, tx);
return delegation ? coversUser({ delegation, userId }, tx) : false;
};
@@ -232,58 +259,17 @@ export const agentVaultDelegationDALFactory = (db: TDbClient) => {
})
.forShare()
.select(
+ db.ref("id").withSchema(TableName.Membership),
db.ref("actorIdentityId").withSchema(TableName.Membership),
db.ref("actorUserId").withSchema(TableName.Membership),
db.ref("actorGroupId").withSchema(TableName.Membership)
- )) as Pick<TMemberships, "actorIdentityId" | "actorUserId" | "actorGroupId">[];
+ )) as Pick<TMemberships, "id" | "actorIdentityId" | "actorUserId" | "actorGroupId">[];
} catch (error) {
throw new DatabaseError({ error, name: "Lock Agent Vault memberships for a delegation" });
}
};
- /**
- * Takes users and groups leaving Agent Vault out of the project's delegations, and deletes a selected delegation
- * left naming no one. The delegations that name them are locked first, so a save to one waits instead of changing
- * it between these statements.
- */
- const removeSubjects = async (
- { projectId, userIds, groupIds }: { projectId: string; userIds: string[]; groupIds: string[] },
- tx: Knex
- ) => {
- if (!userIds.length && !groupIds.length) return;
- const subjects = TableName.AgentVaultDelegationSubject;
- const ofDelegation = () =>
- tx(subjects)
- .whereRaw(`??.?? = ??.??`, [subjects, "delegationId", TableName.AgentVaultDelegation, "id"])
- .select(tx.raw("1"));
- const namingThem = (query: Knex.QueryBuilder) =>
- query.where((subject) => {
- if (userIds.length) void subject.orWhereIn(`${subjects}.userId`, userIds);
- if (groupIds.length) void subject.orWhereIn(`${subjects}.groupId`, groupIds);
- });
-
- try {
- const delegationIds = (
- (await tx(TableName.AgentVaultDelegation)
- .where(`${TableName.AgentVaultDelegation}.projectId`, projectId)
- .whereExists(namingThem(ofDelegation()))
- .forUpdate()
- .select(db.ref("id").withSchema(TableName.AgentVaultDelegation))) as { id: string }[]
- ).map((row) => row.id);
- if (!delegationIds.length) return;
-
- await namingThem(tx(subjects).whereIn(`${subjects}.delegationId`, delegationIds)).delete();
- await tx(TableName.AgentVaultDelegation)
- .whereIn(`${TableName.AgentVaultDelegation}.id`, delegationIds)
- .where(`${TableName.AgentVaultDelegation}.scope`, AgentVaultDelegationScope.Selected)
- .whereNotExists(ofDelegation())
- .delete();
- } catch (error) {
- throw new DatabaseError({ error, name: "Remove users and groups from Agent Vault delegations" });
- }
- };
-
- return { ...orm, upsertScope, findViews, coversUser, identityCoversUser, lockMemberships, removeSubjects };
+ return { ...orm, upsertScope, findViews, coversUser, findForIdentity, identityCoversUser, lockMemberships };
};
export const agentVaultDelegationSubjectDALFactory = (db: TDbClient) =>
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 d7150167f7..dc4cf91da2 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
@@ -311,35 +311,41 @@ export const agentVaultDelegationServiceFactory = ({
tx
);
// Project-scoped, so an identity from another org is a 404 like one that doesn't exist.
- if (!memberships.some((row) => row.actorIdentityId === machineIdentityId)) {
+ 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.`
});
}
+ await assertSubjectsInAgentVault(
+ { projectId, userIds: wantedUserIds, groupIds: wantedGroupIds, memberships },
+ tx
+ );
- const row = await agentVaultDelegationDAL.upsertScope({ projectId, identityId: machineIdentityId, scope }, tx);
+ const row = await agentVaultDelegationDAL.upsertScope(
+ { projectId, identityId: machineIdentityId, membershipId: identityMembership.id, scope },
+ tx
+ );
+ const wantedMembershipIds = new Set(
+ memberships
+ .filter(
+ (membership) =>
+ (membership.actorUserId && wantedUserIds.includes(membership.actorUserId)) ||
+ (membership.actorGroupId && wantedGroupIds.includes(membership.actorGroupId))
+ )
+ .map((membership) => membership.id)
+ );
// Rows that stay are kept rather than rewritten, so each one's addedAt still says when it was added.
const existing = await agentVaultDelegationSubjectDAL.find({ delegationId: row.id }, { tx });
- const keptUserIds = new Set(existing.map((named) => named.userId).filter(Boolean));
- const keptGroupIds = new Set(existing.map((named) => named.groupId).filter(Boolean));
- const addedUserIds = wantedUserIds.filter((id) => !keptUserIds.has(id));
- const addedGroupIds = wantedGroupIds.filter((id) => !keptGroupIds.has(id));
-
- // Only the subjects being added, so one that has left Agent Vault some other way, such as by leaving the
- // organization, can still be kept or taken out.
- await assertSubjectsInAgentVault({ projectId, userIds: addedUserIds, groupIds: addedGroupIds, memberships }, tx);
-
- const stale = existing.filter((named) =>
- named.userId ? !wantedUserIds.includes(named.userId) : !wantedGroupIds.includes(named.groupId!)
- );
+ const stale = existing.filter((named) => !wantedMembershipIds.has(named.membershipId));
if (stale.length) {
await agentVaultDelegationSubjectDAL.delete({ $in: { id: stale.map((named) => named.id) } }, tx);
}
- const added = [
- ...addedUserIds.map((userId) => ({ delegationId: row.id, userId })),
- ...addedGroupIds.map((groupId) => ({ delegationId: row.id, groupId }))
- ];
+ const keptMembershipIds = new Set(existing.map((named) => named.membershipId));
+ const added = [...wantedMembershipIds]
+ .filter((membershipId) => !keptMembershipIds.has(membershipId))
+ .map((membershipId) => ({ delegationId: row.id, membershipId }));
if (added.length) await agentVaultDelegationSubjectDAL.insertMany(added, tx);
const {
diff --git a/backend/src/ee/services/agent-vault-delegation/agent-vault-on-behalf-of-fns.ts b/backend/src/ee/services/agent-vault-delegation/agent-vault-on-behalf-of-fns.ts
index 6631f3b461..14f1d41957 100644
--- a/backend/src/ee/services/agent-vault-delegation/agent-vault-on-behalf-of-fns.ts
+++ b/backend/src/ee/services/agent-vault-delegation/agent-vault-on-behalf-of-fns.ts
@@ -16,7 +16,7 @@ import { TOnBehalfOfUser } from "../agent-vault-session/agent-vault-session-type
import { TAgentVaultDelegationDALFactory } from "./agent-vault-delegation-dal";
export type TOnBehalfOfDeps = {
- agentVaultDelegationDAL: Pick<TAgentVaultDelegationDALFactory, "findOne" | "coversUser">;
+ agentVaultDelegationDAL: Pick<TAgentVaultDelegationDALFactory, "findForIdentity" | "coversUser">;
userDAL: Pick<TUserDALFactory, "findOne">;
orgDAL: Pick<TOrgDALFactory, "findEffectiveOrgMembership">;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
@@ -31,7 +31,7 @@ export const findCallerDelegation = async (
throw new BadRequestError({ message: "Only a machine identity can start a session on behalf of a user" });
}
- const delegation = await agentVaultDelegationDAL.findOne({ projectId, identityId: ctx.actorId });
+ const delegation = await agentVaultDelegationDAL.findForIdentity({ projectId, identityId: ctx.actorId });
if (!delegation) {
throw new ForbiddenRequestError({
message:
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.ts
index c67d109050..83d69e7e90 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
@@ -132,11 +132,7 @@ const buildService = ({
usageMeteringService: { emitForProject: vi.fn() },
agentVaultPersonalValueDAL: { deleteForActorsWithoutGrant: vi.fn().mockResolvedValue(0) },
userGroupMembershipDAL: { find: vi.fn().mockResolvedValue([]) },
- identityGroupMembershipDAL: { find: vi.fn().mockResolvedValue([]) },
- agentVaultDelegationDAL: {
- delete: vi.fn().mockResolvedValue([]),
- removeSubjects: vi.fn().mockResolvedValue(undefined)
- }
+ identityGroupMembershipDAL: { find: vi.fn().mockResolvedValue([]) }
};
const service = agentVaultMembershipServiceFactory(
@@ -226,22 +222,6 @@ describe("agentVaultMembership guards", () => {
);
});
- // A delegation left in place would let the identity act for users again the moment it is added back.
- test("deletes the delegation of an identity it removes, in the same transaction", async () => {
- const { service, deps, txs } = buildService({
- identityProjectId: null,
- productMemberships: [{ id: "mem-1" }],
- adminMembershipIds: ["mem-other"]
- });
-
- await service.revokeProductMembers({ projectId: PROJECT_ID, ...addIds, ctx });
-
- expect(deps.agentVaultDelegationDAL.delete).toHaveBeenCalledWith(
- { projectId: PROJECT_ID, $in: { identityId: [IDENTITY_ID] } },
- txs[0]
- );
- });
-
// A sub-organization reaches one of its parent's groups through a membership of its own, and the group
// row keeps pointing at the parent. Judging it by that row refused every linked group.
test("accepts a group the organization reaches but does not own", async () => {
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.ts
index 8a3628a25c..5b887c1756 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
@@ -36,7 +36,6 @@ import { resolveUsersBySsoExternalId } from "@app/services/user-alias/user-alias
import { resolveAgentVaultActorNames, TAgentVaultActorName } from "../agent-vault/agent-vault-actor-name-fns";
import { AgentVaultMemberType } from "../agent-vault/agent-vault-enums";
-import { TAgentVaultDelegationDALFactory } from "../agent-vault-delegation/agent-vault-delegation-dal";
import {
clearPersonalValuesAfterRevoke,
TClearPersonalValuesDeps
@@ -55,7 +54,6 @@ type TAgentVaultMembershipServiceFactoryDep = {
orgDAL: Pick<TOrgDALFactory, "findById" | "findActorsWithActiveOrgAccess" | "lockActorsForOrgAccess">;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
usageMeteringService: Pick<TUsageMeteringServiceFactory, "emitForProject">;
- agentVaultDelegationDAL: Pick<TAgentVaultDelegationDALFactory, "delete" | "removeSubjects">;
} & TClearPersonalValuesDeps;
export type TAgentVaultMembershipServiceFactory = ReturnType<typeof agentVaultMembershipServiceFactory>;
@@ -145,8 +143,7 @@ export const agentVaultMembershipServiceFactory = ({
usageMeteringService,
agentVaultPersonalValueDAL,
userGroupMembershipDAL,
- identityGroupMembershipDAL,
- agentVaultDelegationDAL
+ identityGroupMembershipDAL
}: TAgentVaultMembershipServiceFactoryDep) => {
const getActorPermission = (projectId: string, ctx: TGenericPermission) =>
permissionService.getProjectPermission({
@@ -688,24 +685,10 @@ export const agentVaultMembershipServiceFactory = ({
})
);
- // membership_roles cascades on the membership FK, so the roles go with these rows.
+ // membership_roles and the delegation rows cascade on the membership FK, so the roles go with these rows, as do
+ // an identity's delegation and the users and groups a delegation names.
await membershipDAL.delete({ $in: { id: membershipIds } }, tx);
- // A delegation left behind would come back with a later add, so an identity rejoining acts for no one until an
- // admin allows it again. Users and groups come out of the delegations that name them for the same reason.
- const removedIdentityIds = named(held, AgentVaultMemberType.MachineIdentity);
- if (removedIdentityIds.length) {
- await agentVaultDelegationDAL.delete({ projectId, $in: { identityId: removedIdentityIds } }, tx);
- }
- await agentVaultDelegationDAL.removeSubjects(
- {
- projectId,
- userIds: named(held, AgentVaultMemberType.User),
- groupIds: named(held, AgentVaultMemberType.Group)
- },
- tx
- );
-
// Their bundle grants went above. Their own variables stay, as they would if they only lost a bundle.
await clearPersonalValuesAfterRevoke(
{ agentVaultPersonalValueDAL, userGroupMembershipDAL, identityGroupMembershipDAL },
diff --git a/backend/src/ee/services/agent-vault-session/agent-vault-session-service.ts b/backend/src/ee/services/agent-vault-session/agent-vault-session-service.ts
index d550fe61b7..065e78307b 100644
--- a/backend/src/ee/services/agent-vault-session/agent-vault-session-service.ts
+++ b/backend/src/ee/services/agent-vault-session/agent-vault-session-service.ts
@@ -46,7 +46,7 @@ type TAgentVaultSessionServiceFactoryDep = {
agentVaultSessionDAL: TAgentVaultSessionDALFactory;
agentVaultSessionAccessBundleDAL: TAgentVaultSessionAccessBundleDALFactory;
agentVaultAccessBundleDAL: Pick<TAgentVaultAccessBundleDALFactory, "find">;
- agentVaultDelegationDAL: Pick<TAgentVaultDelegationDALFactory, "findOne" | "coversUser">;
+ agentVaultDelegationDAL: Pick<TAgentVaultDelegationDALFactory, "findForIdentity" | "coversUser">;
membershipDAL: Pick<TMembershipDALFactory, "findResourceMembershipsForActor">;
userDAL: Pick<TUserDALFactory, "findOne">;
orgDAL: Pick<TOrgDALFactory, "findEffectiveOrgMembership">;
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 52004fc833..01fd72b4d4 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -2147,8 +2147,7 @@ export const registerRoutes = async (
usageMeteringService,
agentVaultPersonalValueDAL,
userGroupMembershipDAL,
- identityGroupMembershipDAL,
- agentVaultDelegationDAL
+ identityGroupMembershipDAL
});
const pamProjectResolver = pamProjectResolverFactory({
diff --git a/docs/documentation/platform/agent-vault/sessions-on-behalf-of-users.mdx b/docs/documentation/platform/agent-vault/sessions-on-behalf-of-users.mdx
index 3aa861011a..57515beea8 100644
--- a/docs/documentation/platform/agent-vault/sessions-on-behalf-of-users.mdx
+++ b/docs/documentation/platform/agent-vault/sessions-on-behalf-of-users.mdx
@@ -66,7 +66,7 @@ sequenceDiagram
</Tab>
</Tabs>
-You can add only users and groups that are members of Agent Vault. If a user is in Agent Vault only through a group, add the group.
+You can add only users and groups that are members of Agent Vault. If a user is in Agent Vault only through a group, add the group. If a user or group leaves Agent Vault, Infisical takes them out of the delegation, and adding them back to Agent Vault doesn't add them back to the delegation.
To take a user or group out of the delegation, select the actions menu on its row in the **Delegation** section, select **Remove**, then select **Remove** again to confirm. If you remove the last user or group, or the **All Agent Vault Members** row, the machine identity can no longer act on behalf of anyone.
@@ -122,8 +122,8 @@ To let the machine identity create sessions over one of them, [grant the bundle]
Infisical checks the delegation again each time the proxy polls, once every [poll interval](/documentation/platform/agent-vault/proxies#poll-interval) (60 seconds by default). The proxy refuses every request on the session if any of these happen:
- An admin removes the delegation, or edits it so it no longer covers the user
-- The delegation covered the user only through a group, and either the user leaves that group or an admin removes the group from Agent Vault
-- An admin removes the user from Agent Vault, which also takes the user out of the delegation
+- The delegation covered the user only through a group, and either the user leaves that group or the group is removed from Agent Vault
+- The user is removed from Agent Vault or from your organization, which also takes the user out of the delegation
- An admin removes the machine identity from Agent Vault, which also deletes its delegation
- Someone deletes the machine identity (the session then shows as **Revoked**)