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
feat(agent-vault): manage delegations one user or group at a time
Scott Wilsone9fecfc91f53
diff --git a/backend/e2e-test/routes/v1/agent-vault.spec.ts b/backend/e2e-test/routes/v1/agent-vault.spec.tsindex 17111bf8d3..445a03404d 100644--- a/backend/e2e-test/routes/v1/agent-vault.spec.ts+++ b/backend/e2e-test/routes/v1/agent-vault.spec.ts@@ -5064,6 +5064,180 @@ describe("Agent Vault V1 Router", async () => {}});+ test("a non-admin user losing a grant mid-session takes the bundle's services away", async () => {+ const projectId = await getProjectId();+ const bundle = await createAccessBundle(`obo-user-grant-${Date.now()}`);+ const created = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {+ type: "http",+ name: "github",+ hostPattern: "api.github.com",+ credential: { type: "bearer", value: "shared_token" }+ });+ expect(created.statusCode).toBe(200);+ const proxy = await inject("POST", "/api/v1/agent-vault/proxies", { name: `obo-user-grant-${Date.now()}` });+ const proxyToken = proxy.json().proxyToken as string;+ const resolve = (sessionToken: string) =>+ testServer.inject({+ method: "POST",+ url: "/api/v1/agent-vault/proxy/resolve",+ headers: { authorization: `Bearer ${proxyToken}`, "x-infisical-agent-session": sessionToken }+ });+ const bot = await createMemberIdentity(`obo-user-grant-bot-${Date.now()}`);+ // A member, so their reach is their grants rather than every bundle.+ const alice = await createAgentVaultUser("obo-user-grant-alice", projectId);+ try {+ await grantBundle(bundle.id, { userIds: [alice.userId], machineIdentityIds: [bot.id] });+ await delegate(bot, { scope: "selected", userIds: [alice.userId] });+ const minted = await mintFor(bot, { userId: alice.userId }, bundle.name);+ expect(minted.statusCode).toBe(200);+ const token = minted.json().session.token as string;+ const serviceNames = async () =>+ ((await resolve(token)).json().services as { name: string }[]).map((service) => service.name);++ expect(await serviceNames()).toEqual(["github"]);+ expect((await inject("DELETE", bundleMembersUrl(bundle.id), { userIds: [alice.userId] })).statusCode).toBe(200);+ const withoutGrant = await resolve(token);+ expect(withoutGrant.statusCode).toBe(200);+ expect(await serviceNames()).toEqual([]);+ } finally {+ await bot.cleanup();+ await deleteUsers([alice.userId]);+ }+ });++ test("the identity's session list and reads leave out sessions the user started themselves", async () => {+ const projectId = await getProjectId();+ const bundle = await createAccessBundle(`obo-own-${Date.now()}`);+ const bot = await createMemberIdentity(`obo-own-bot-${Date.now()}`);+ const alice = await createAgentVaultUser("obo-own-alice", projectId);+ try {+ await grantBundle(bundle.id, { userIds: [alice.userId], machineIdentityIds: [bot.id] });+ await delegate(bot, { scope: "selected", userIds: [alice.userId] });+ const startedForAlice = (await mintFor(bot, { userId: alice.userId }, bundle.name)).json().session.id as string;++ const aliceToken = await createUserAccessToken({ userId: alice.userId, orgId: seedData1.organization.id });+ const ownSession = await testServer.inject({+ method: "POST",+ url: sessionsUrl,+ headers: { authorization: `Bearer ${aliceToken}` },+ body: { accessBundles: [bundle.name] }+ });+ expect(ownSession.statusCode).toBe(200);+ const alicesOwn = ownSession.json().session.id as string;++ const listed = await bot.as("GET", `${sessionsUrl}?limit=100`);+ const listedIds = (listed.json().sessions as { id: string }[]).map((row) => row.id);+ expect(listedIds).toContain(startedForAlice);+ expect(listedIds).not.toContain(alicesOwn);+ expect((await bot.as("GET", `${sessionsUrl}/${alicesOwn}`)).statusCode).toBe(404);+ } finally {+ await bot.cleanup();+ await deleteUsers([alice.userId]);+ }+ });++ test("a save replaces a delegation whose subjects all left, instead of reviving it", async () => {+ const projectId = await getProjectId();+ const bot = await createMemberIdentity(`obo-revive-bot-${Date.now()}`);+ const alice = await createAgentVaultUser("obo-revive-alice", projectId);+ const bob = await createAgentVaultUser("obo-revive-bob", projectId);+ try {+ const first = await delegate(bot, { scope: "selected", userIds: [alice.userId] });+ await testDb("memberships")+ .where({ scope: AccessScope.Project, scopeProjectId: projectId, actorUserId: alice.userId })+ .delete();+ expect((await inject("GET", delegationUrl(bot.id))).statusCode).toBe(404);++ const replaced = (+ await inject("PUT", delegationUrl(bot.id), { scope: "selected", userIds: [bob.userId] })+ ).json().delegation as { createdAt: string };+ expect(new Date(replaced.createdAt).getTime()).toBeGreaterThan(+ new Date((first as unknown as { createdAt: string }).createdAt).getTime()+ );+ } finally {+ await bot.cleanup();+ await deleteUsers([alice.userId, bob.userId]);+ }+ });++ test("users and groups are added and taken out one change at a time", async () => {+ const projectId = await getProjectId();+ const bot = await createMemberIdentity(`obo-subjects-bot-${Date.now()}`);+ const alice = await createAgentVaultUser("obo-subjects-alice", projectId);+ const bob = await createAgentVaultUser("obo-subjects-bob", projectId);+ const carol = await createAgentVaultUser("obo-subjects-carol", projectId);+ const outsider = await createAgentVaultUser("obo-subjects-outsider", null);+ const group = await createProjectGroup(projectId, `obo-subjects-group-${Date.now()}`, ProjectMembershipRole.Member);+ const subjectsUrl = `${delegationUrl(bot.id)}/subjects`;+ const ours = new Set([alice.userId, bob.userId, carol.userId, group.id]);+ const available = async (query = "") => {+ const res = await inject("GET", `${subjectsUrl}/available?limit=100${query}`);+ expect(res.statusCode).toBe(200);+ return (res.json().members as { id: string }[]).map((row) => row.id).filter((id) => ours.has(id));+ };+ const named = (res: { json: () => { delegation: TDelegationDetail | null } }) => {+ const { delegation } = res.json();+ return delegation && { users: delegation.users.map((row) => row.id).sort(), groups: delegation.groups.map((row) => row.id) };+ };+ try {+ expect((await available()).sort()).toEqual([...ours].sort());++ // Adding to an identity with no delegation creates one to the users and groups named.+ const first = await inject("POST", subjectsUrl, { userIds: [alice.userId] });+ expect(first.statusCode).toBe(200);+ expect(named(first)).toEqual({ users: [alice.userId], groups: [] });+ const aliceAddedAt = (first.json().delegation as TDelegationDetail).users[0].addedAt;++ // Two admins adding at once both land, and the row that was already there keeps its addedAt.+ const [withBob, withGroup] = await Promise.all([+ inject("POST", subjectsUrl, { userIds: [bob.userId] }),+ inject("POST", subjectsUrl, { groupIds: [group.id] })+ ]);+ expect([withBob.statusCode, withGroup.statusCode]).toEqual([200, 200]);+ const now = await inject("GET", delegationUrl(bot.id));+ expect(named(now)).toEqual({ users: [alice.userId, bob.userId].sort(), groups: [group.id] });+ expect((now.json().delegation as TDelegationDetail).users.find((row) => row.id === alice.userId)?.addedAt).toBe(+ aliceAddedAt+ );++ expect(await available()).toEqual([carol.userId]);+ expect(await available("&actorType=group")).toEqual([]);++ 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");+ expect((await inject("POST", subjectsUrl, {})).statusCode).toBe(422);++ // A name the delegation doesn't hold is skipped, and taking out the last one ends the delegation.+ 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] });+ const emptied = await inject("DELETE", subjectsUrl, { userIds: [bob.userId], groupIds: [group.id] });+ expect(emptied.statusCode).toBe(200);+ expect(emptied.json().delegation).toBeNull();+ expect((await inject("GET", delegationUrl(bot.id))).statusCode).toBe(404);+ expect((await inject("DELETE", subjectsUrl, { userIds: [bob.userId] })).statusCode).toBe(404);++ // An all-members delegation names no one, so there's nothing to add to or take out of it.+ await delegate(bot, { scope: "all-members" });+ const addToAll = await inject("POST", subjectsUrl, { userIds: [alice.userId] });+ expect(addToAll.statusCode).toBe(400);+ expect(addToAll.json().message).toContain("already acts on behalf of every Agent Vault member");+ expect((await inject("DELETE", subjectsUrl, { userIds: [alice.userId] })).statusCode).toBe(400);++ const refused = await Promise.all([+ bot.as("POST", subjectsUrl, { userIds: [alice.userId] }),+ bot.as("DELETE", subjectsUrl, { userIds: [alice.userId] }),+ bot.as("GET", `${subjectsUrl}/available`)+ ]);+ refused.forEach((res) => expect(res.statusCode).toBe(403));+ } finally {+ await bot.cleanup();+ await deleteUsers([alice.userId, bob.userId, carol.userId, outsider.userId]);+ await group.cleanup();+ }+ });+test("a delegation names Agent Vault members, and only an admin or the identity itself reads it", async () => {const projectId = await getProjectId();const bot = await createMemberIdentity(`obo-api-bot-${Date.now()}`);diff --git a/backend/src/db/migrations/20261019120000_agent-vault-delegations.ts b/backend/src/db/migrations/20261019120000_agent-vault-delegations.tsindex 0f17bd5358..5ceb9a8f11 100644--- a/backend/src/db/migrations/20261019120000_agent-vault-delegations.ts+++ b/backend/src/db/migrations/20261019120000_agent-vault-delegations.ts@@ -19,9 +19,10 @@ export async function up(knex: Knex): Promise<void> {`CREATE INDEX agent_vault_session_by_acting_identity ON ?? ("actingIdentityId") WHERE "actingIdentityId" IS NOT NULL`,[TableName.AgentVaultSession]);- // An on-behalf-of session is always a user's, and an id is never stored without the name.+ // An on-behalf-of session is always a user's, and an id is never stored without the name. actorType can be NULL on+ // rows the previous release writes during a rolling deploy.await knex.raw(- `ALTER TABLE ?? ADD CONSTRAINT ?? CHECK (("actingIdentityName" IS NULL OR "identityId" IS NULL) AND ("actingIdentityId" IS NULL OR "actingIdentityName" IS NOT NULL))`,+ `ALTER TABLE ?? ADD CONSTRAINT ?? CHECK (("actingIdentityName" IS NULL OR ("identityId" IS NULL AND ("actorType" IS NULL OR "actorType" = 'user'))) AND ("actingIdentityId" IS NULL OR "actingIdentityName" IS NOT NULL))`,[TableName.AgentVaultSession, SESSION_ACTING_IDENTITY_CHECK]);}diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-delegation-router.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-delegation-router.tsindex 3a4ce1962b..e1e5116f13 100644--- a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-delegation-router.ts+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-delegation-router.ts@@ -1,14 +1,17 @@import { z } from "zod";-import { AgentVaultDelegationScope } from "@app/ee/services/agent-vault/agent-vault-enums";+import { AgentVaultDelegationScope, AgentVaultMemberType } from "@app/ee/services/agent-vault/agent-vault-enums";import { EventType } from "@app/ee/services/audit-log/audit-log-types";import { AGENT_VAULT } from "@app/lib/api-docs";import { ApiDocsTags } from "@app/lib/api-docs/constants";import { readLimit, writeLimit } from "@app/server/config/rateLimiter";+import { emitAgentVaultTelemetry } from "@app/server/lib/telemetry";import { verifyAuth } from "@app/server/plugins/auth/verify-auth";import { AuthMode } from "@app/services/auth/auth-type";+import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";import { actorContext } from "./agent-vault-router-fns";+import { AgentVaultProductMemberSchema, agentVaultListQuery } from "./agent-vault-schemas";const MAX_DELEGATION_SUBJECTS = 100;@@ -70,13 +73,42 @@ const DelegationDetailSchema = DelegationSchema.extend({missingAccessBundles: missingAccessBundlesSchema(AGENT_VAULT.DELEGATION.missingAccessBundles)});+const subjectIdsSchema = (description: string, example: string) =>+ z+ .string()+ .uuid()+ .array()+ .max(MAX_DELEGATION_SUBJECTS)+ .default([])+ .transform((ids) => [...new Set(ids)])+ .describe(JSON.stringify({ description, example: [example] }));++const SubjectChangeBodySchema = (docs: { userIds: string; groupIds: string }) =>+ z+ .object({+ userIds: subjectIdsSchema(docs.userIds, "3c90c3cc-0d44-4b50-8888-8dd25736052a"),+ groupIds: subjectIdsSchema(docs.groupIds, "7b1e4f2a-9c3d-4a6b-8e5f-1d2c3b4a5e6f")+ })+ .refine((val) => val.userIds.length + val.groupIds.length > 0, {+ message: "Name at least one user or group."+ });+const machineIdentityParams = z.object({machineIdentityId: z.string().uuid().describe(AGENT_VAULT.DELEGATION.machineIdentityId)});const auditDelegationFields = (delegation: z.infer<typeof DelegationSchema>) => ({machineIdentityId: delegation.machineIdentity.id,- machineIdentityName: delegation.machineIdentity.name+ machineIdentityName: delegation.machineIdentity.name,+ scope: delegation.scope,+ users: delegation.users.map((user) => ({ userId: user.id, userName: user.username })),+ groups: delegation.groups.map((group) => ({ groupId: group.id, groupName: group.name }))+});++const telemetryDelegationFields = (delegation: z.infer<typeof DelegationSchema>) => ({+ scope: delegation.scope,+ userCount: delegation.users.length,+ groupCount: delegation.groups.length});// None of these accept AuthMode.OAUTH. The admin check reads the role, which a delegated token's scopes don't narrow,@@ -95,7 +127,8 @@ export const registerAgentVaultDelegationRouter = async (server: FastifyZodProvimachineIdentityIds: z.string().trim()- .max(100 * 37)+ // Room for 100 IDs with a separator and spaces, so the 100-ID limit below is the one that answers.+ .max(100 * 40).optional().transform((val) => (val ? [...new Set(val.split(",").map((id) => id.trim()))] : undefined)).pipe(z.string().uuid().array().max(100).optional())@@ -202,28 +235,176 @@ export const registerAgentVaultDelegationRouter = async (server: FastifyZodProvi},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),handler: async (req) => {- const { delegation } = await server.services.agentVaultDelegation.setDelegation({+ const { delegation: saved } = await server.services.agentVaultDelegation.setDelegation({projectId: req.internalAgentVaultProjectId,ctx: actorContext(req),machineIdentityId: req.params.machineIdentityId,...req.body});+ // Before the missing bundles are worked out, so a failure there still leaves the committed save audited.await server.services.auditLog.createAuditLog({...req.auditLogInfo,orgId: req.permission.orgId,projectId: req.internalAgentVaultProjectId,- event: {- type: EventType.AGENT_VAULT_DELEGATION_SET,- metadata: {- ...auditDelegationFields(delegation),- scope: delegation.scope,- users: delegation.users.map((user) => ({ userId: user.id, userName: user.username })),- groups: delegation.groups.map((group) => ({ groupId: group.id, groupName: group.name }))- }- }+ event: { type: EventType.AGENT_VAULT_DELEGATION_SET, metadata: auditDelegationFields(saved) }+ });+ emitAgentVaultTelemetry(server.services.telemetry, req, {+ event: PostHogEventTypes.AgentVaultDelegationSet,+ properties: telemetryDelegationFields(saved)});+ const delegation = await server.services.agentVaultDelegation.withMissingAccessBundles({+ projectId: req.internalAgentVaultProjectId,+ ctx: actorContext(req),+ delegation: saved+ });+ return { delegation };+ }+ });++ server.route({+ method: "GET",+ url: "/:machineIdentityId/subjects/available",+ config: { rateLimit: readLimit },+ schema: {+ hide: false,+ operationId: "listAvailableAgentVaultDelegationSubjects",+ description: "List the Agent Vault users and groups that can still be added to a machine identity's delegation",+ tags: [ApiDocsTags.AgentVaultDelegations],+ params: machineIdentityParams,+ querystring: z.object({+ actorType: z+ .enum([AgentVaultMemberType.User, AgentVaultMemberType.Group])+ .optional()+ .describe(AGENT_VAULT.AVAILABLE_DELEGATION_SUBJECT.actorTypeFilter),+ ...agentVaultListQuery(AGENT_VAULT.AVAILABLE_DELEGATION_SUBJECT)+ }),+ response: {+ 200: z.object({+ members: AgentVaultProductMemberSchema.array(),+ totalCount: z.number().describe(AGENT_VAULT.AVAILABLE_DELEGATION_SUBJECT.totalCount)+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) =>+ server.services.agentVaultDelegation.listAvailableDelegationSubjects({+ projectId: req.internalAgentVaultProjectId,+ ctx: actorContext(req),+ machineIdentityId: req.params.machineIdentityId,+ ...req.query+ })+ });++ server.route({+ method: "POST",+ url: "/:machineIdentityId/subjects",+ config: { rateLimit: writeLimit },+ schema: {+ hide: false,+ operationId: "addAgentVaultDelegationSubjects",+ description:+ "Add users and groups to a machine identity's delegation, keeping the ones it already names. Creates a delegation to the users and groups named if the machine identity has none.",+ tags: [ApiDocsTags.AgentVaultDelegations],+ params: machineIdentityParams,+ body: SubjectChangeBodySchema({+ userIds: AGENT_VAULT.DELEGATION.addUserIds,+ groupIds: AGENT_VAULT.DELEGATION.addGroupIds+ }),+ response: { 200: z.object({ delegation: DelegationDetailSchema }) }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const { delegation: saved, isChanged } = await server.services.agentVaultDelegation.addDelegationSubjects({+ projectId: req.internalAgentVaultProjectId,+ ctx: actorContext(req),+ machineIdentityId: req.params.machineIdentityId,+ ...req.body+ });++ if (isChanged) {+ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ orgId: req.permission.orgId,+ projectId: req.internalAgentVaultProjectId,+ event: { type: EventType.AGENT_VAULT_DELEGATION_SET, metadata: auditDelegationFields(saved) }+ });+ emitAgentVaultTelemetry(server.services.telemetry, req, {+ event: PostHogEventTypes.AgentVaultDelegationSet,+ properties: telemetryDelegationFields(saved)+ });+ }++ const delegation = await server.services.agentVaultDelegation.withMissingAccessBundles({+ projectId: req.internalAgentVaultProjectId,+ ctx: actorContext(req),+ delegation: saved+ });+ return { delegation };+ }+ });++ server.route({+ method: "DELETE",+ url: "/:machineIdentityId/subjects",+ config: { rateLimit: writeLimit },+ schema: {+ hide: false,+ operationId: "removeAgentVaultDelegationSubjects",+ description:+ "Take users and groups out of a machine identity's delegation. Taking out the last one removes the delegation, and the sessions it started for them stop working.",+ tags: [ApiDocsTags.AgentVaultDelegations],+ params: machineIdentityParams,+ body: SubjectChangeBodySchema({+ userIds: AGENT_VAULT.DELEGATION.removeUserIds,+ groupIds: AGENT_VAULT.DELEGATION.removeGroupIds+ }),+ response: {+ 200: z.object({+ delegation: DelegationDetailSchema.nullable().describe(AGENT_VAULT.DELEGATION.afterRemove)+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const {+ delegation: saved,+ previous,+ isChanged+ } = await server.services.agentVaultDelegation.removeDelegationSubjects({+ projectId: req.internalAgentVaultProjectId,+ ctx: actorContext(req),+ machineIdentityId: req.params.machineIdentityId,+ ...req.body+ });++ // Taking out the last user or group ends the delegation, so it's audited as one being removed, naming who it+ // covered. Naming only users and groups it doesn't hold changes nothing and writes nothing.+ if (isChanged) {+ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ orgId: req.permission.orgId,+ projectId: req.internalAgentVaultProjectId,+ event: saved+ ? { type: EventType.AGENT_VAULT_DELEGATION_SET, metadata: auditDelegationFields(saved) }+ : { type: EventType.AGENT_VAULT_DELEGATION_DELETE, metadata: auditDelegationFields(previous) }+ });+ emitAgentVaultTelemetry(+ server.services.telemetry,+ req,+ saved+ ? { event: PostHogEventTypes.AgentVaultDelegationSet, properties: telemetryDelegationFields(saved) }+ : { event: PostHogEventTypes.AgentVaultDelegationDeleted, properties: telemetryDelegationFields(previous) }+ );+ }++ if (!saved) return { delegation: null };+ const delegation = await server.services.agentVaultDelegation.withMissingAccessBundles({+ projectId: req.internalAgentVaultProjectId,+ ctx: actorContext(req),+ delegation: saved+ });return { delegation };}});@@ -258,6 +439,10 @@ export const registerAgentVaultDelegationRouter = async (server: FastifyZodProvimetadata: auditDelegationFields(delegation)}});+ emitAgentVaultTelemetry(server.services.telemetry, req, {+ event: PostHogEventTypes.AgentVaultDelegationDeleted,+ properties: telemetryDelegationFields(delegation)+ });return { delegation };}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 4624f2131c..8d3ca34a04 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,58 @@ export const agentVaultDelegationDALFactory = (db: TDbClient) => {}};+ // 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) => {+ try {+ await tx(DELEGATION)+ .where(`${DELEGATION}.projectId`, projectId)+ .where(`${DELEGATION}.identityId`, identityId)+ .where(`${DELEGATION}.scope`, AgentVaultDelegationScope.Selected)+ .whereNotExists(+ tx(SUBJECTS).whereRaw(`??.?? = ??.??`, [SUBJECTS, "delegationId", DELEGATION, "id"]).select(tx.raw("1"))+ )+ .delete();+ } catch (error) {+ throw new DatabaseError({ error, name: "Delete emptied Agent Vault delegation" });+ }+ };++ // The delegation row, locked until the transaction ends, so an add or a remove can't interleave with a save.+ const lockForIdentity = async ({ projectId, identityId }: { projectId: string; identityId: string }, tx: Knex) => {+ try {+ return (await tx(DELEGATION).where({ projectId, identityId }).forUpdate().first()) as+ | TAgentVaultDelegations+ | undefined;+ } catch (error) {+ throw new DatabaseError({ error, name: "Lock Agent Vault delegation" });+ }+ };++ // Takes the named users and groups out of one delegation. Names it doesn't hold are skipped.+ const removeSubjectsByActors = async (+ { delegationId, userIds, groupIds }: { delegationId: string; userIds: string[]; groupIds: string[] },+ tx: Knex+ ) => {+ if (!userIds.length && !groupIds.length) return 0;+ try {+ return await tx(SUBJECTS)+ .where(`${SUBJECTS}.delegationId`, delegationId)+ .whereIn(+ `${SUBJECTS}.membershipId`,+ tx(TableName.Membership)+ .where((actor) => {+ if (userIds.length) void actor.orWhereIn(`${TableName.Membership}.actorUserId`, userIds);+ if (groupIds.length) void actor.orWhereIn(`${TableName.Membership}.actorGroupId`, groupIds);+ })+ .select(`${TableName.Membership}.id`)+ )+ .delete();+ } catch (error) {+ throw new DatabaseError({ error, name: "Remove users and groups from an Agent Vault delegation" });+ }+ };+const findViews = async ({projectId,@@ -255,6 +307,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.+ .orderBy(`${TableName.Membership}.id`).forShare().select(db.ref("id").withSchema(TableName.Membership),@@ -267,7 +321,18 @@ export const agentVaultDelegationDALFactory = (db: TDbClient) => {}};- return { ...orm, upsertScope, findViews, coversUser, findForIdentity, identityCoversUser, lockMemberships };+ return {+ ...orm,+ upsertScope,+ deleteIfNamesNoOne,+ lockForIdentity,+ removeSubjectsByActors,+ 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.tsindex 23fb65a5db..e8aeba9c27 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@@ -13,7 +13,8 @@ import { TMembershipDALFactory } from "@app/services/membership/membership-dal";import { TMembershipRoleDALFactory } from "@app/services/membership/membership-role-dal";import { TAgentVaultAccessBundleDALFactory } from "../agent-vault-access-bundle/agent-vault-access-bundle-dal";-import { AgentVaultDelegationScope } from "../agent-vault/agent-vault-enums";+import { TAgentVaultMemberDALFactory } from "../agent-vault-member/agent-vault-member-dal";+import { AgentVaultDelegationScope, AgentVaultMemberType } from "../agent-vault/agent-vault-enums";import { getAgentVaultPermission, getAgentVaultReachability } from "../agent-vault/agent-vault-permission";import {TAgentVaultDelegationDALFactory,@@ -21,8 +22,10 @@ import {TAgentVaultDelegationView} from "./agent-vault-delegation-dal";import {+ TChangeDelegationSubjectsDTO,TDeleteDelegationDTO,TGetDelegationDTO,+ TListAvailableDelegationSubjectsDTO,TListDelegationsDTO,TSetDelegationDTO} from "./agent-vault-delegation-types";@@ -30,10 +33,19 @@ import {type TAgentVaultDelegationServiceFactoryDep = {agentVaultDelegationDAL: Pick<TAgentVaultDelegationDALFactory,- "upsertScope" | "findViews" | "delete" | "transaction" | "lockMemberships"+ | "upsertScope"+ | "deleteIfNamesNoOne"+ | "lockForIdentity"+ | "removeSubjectsByActors"+ | "findViews"+ | "findForIdentity"+ | "delete"+ | "transaction"+ | "lockMemberships">;agentVaultDelegationSubjectDAL: Pick<TAgentVaultDelegationSubjectDALFactory, "find" | "delete" | "insertMany">;agentVaultAccessBundleDAL: Pick<TAgentVaultAccessBundleDALFactory, "find">;+ agentVaultMemberDAL: Pick<TAgentVaultMemberDALFactory, "findProductMembers">;membershipDAL: Pick<TMembershipDALFactory, "find" | "findResourceMembershipsForActor">;membershipRoleDAL: Pick<TMembershipRoleDALFactory, "find">;userGroupMembershipDAL: Pick<TUserGroupMembershipDALFactory, "find">;@@ -56,10 +68,23 @@ const withNoMissingAccessBundles = (delegation: TAgentVaultDelegationView) => ({const quoted = (ids: string[]) => ids.map((id) => `'${id}'`).join(", ");+type TLockedMembership = Pick<TMemberships, "id" | "actorIdentityId" | "actorUserId" | "actorGroupId">;++// The Agent Vault memberships of the named users and groups, which is what a delegation's subject rows reference.+const membershipIdsNaming = (memberships: TLockedMembership[], userIds: string[], groupIds: string[]) =>+ memberships+ .filter(+ (membership) =>+ (membership.actorUserId && userIds.includes(membership.actorUserId)) ||+ (membership.actorGroupId && groupIds.includes(membership.actorGroupId))+ )+ .map((membership) => membership.id);+export const agentVaultDelegationServiceFactory = ({agentVaultDelegationDAL,agentVaultDelegationSubjectDAL,agentVaultAccessBundleDAL,+ agentVaultMemberDAL,membershipDAL,membershipRoleDAL,userGroupMembershipDAL,@@ -80,6 +105,17 @@ export const agentVaultDelegationServiceFactory = ({);};+ // Project-scoped, so an identity from another org is a 404 like one that doesn't exist.+ 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.`+ });+ }+ return identityMembership;+ };+const notFound = (machineIdentityId: string) =>new NotFoundError({message: `Machine identity with ID '${machineIdentityId}' has no delegation, so it can't act on behalf of users`@@ -310,32 +346,19 @@ export const agentVaultDelegationServiceFactory = ({{ projectId, identityId: machineIdentityId, userIds: wantedUserIds, groupIds: wantedGroupIds },tx);- // Project-scoped, so an identity from another org is a 404 like one that doesn't exist.- 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.`- });- }+ const identityMembership = requireIdentityMembership(memberships, machineIdentityId);await assertSubjectsInAgentVault({ projectId, userIds: wantedUserIds, groupIds: wantedGroupIds, memberships },tx);+ await agentVaultDelegationDAL.deleteIfNamesNoOne({ projectId, identityId: machineIdentityId }, 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)- );+ const wantedMembershipIds = new Set(membershipIdsNaming(memberships, wantedUserIds, wantedGroupIds));// 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 stale = existing.filter((named) => !wantedMembershipIds.has(named.membershipId));@@ -354,8 +377,122 @@ export const agentVaultDelegationServiceFactory = ({return written;});- // After the commit: reading every covered user's reach is many queries, none of which belong in the transaction.- return { delegation: await withMissingAccessBundles({ projectId, ctx, delegation }) };+ // The missing bundles are left to the caller, through withMissingAccessBundles: reading every covered user's reach+ // is many queries, none of which belong in the transaction, and a failure there mustn't stop the save from being+ // audited.+ return { delegation };+ };++ // Adds to what the delegation already names rather than replacing it, so a client that never saw the current list+ // can't overwrite it. Creates a selected delegation if the identity has none.+ const addDelegationSubjects = async ({+ projectId,+ ctx,+ machineIdentityId,+ userIds,+ groupIds+ }: TChangeDelegationSubjectsDTO) => {+ await checkIdentityPermission({ projectId, ctx, machineIdentityId }, ProjectPermissionIdentityActions.Edit);++ const delegation = 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 },+ tx+ );+ const identityMembership = requireIdentityMembership(memberships, machineIdentityId);+ 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.`+ });+ }++ await agentVaultDelegationDAL.deleteIfNamesNoOne({ projectId, identityId: machineIdentityId }, tx);+ const row = await agentVaultDelegationDAL.upsertScope(+ {+ projectId,+ identityId: machineIdentityId,+ membershipId: identityMembership.id,+ scope: AgentVaultDelegationScope.Selected+ },+ 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);++ const {+ delegations: [written]+ } = await agentVaultDelegationDAL.findViews({ projectId, identityIds: [machineIdentityId] }, tx);+ return { written, isChanged: added.length > 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 };+ };++ // Names the delegation doesn't hold are skipped. Taking out the last one leaves a delegation that names no one, which+ // reads as none, so the result is null.+ const removeDelegationSubjects = async ({+ projectId,+ ctx,+ machineIdentityId,+ userIds,+ groupIds+ }: TChangeDelegationSubjectsDTO) => {+ await checkIdentityPermission({ projectId, ctx, machineIdentityId }, ProjectPermissionIdentityActions.Edit);++ const changed = await agentVaultDelegationDAL.transaction(async (tx) => {+ const current = await agentVaultDelegationDAL.lockForIdentity({ projectId, identityId: machineIdentityId }, tx);+ const viewNow = async () =>+ (await agentVaultDelegationDAL.findViews({ projectId, identityIds: [machineIdentityId] }, tx)).delegations[0];+ const before = current ? await viewNow() : undefined;+ if (!current || !before) return undefined;+ if (current.scope === AgentVaultDelegationScope.AllMembers) {+ throw new BadRequestError({+ message: `Machine identity with ID '${machineIdentityId}' acts on behalf of every Agent Vault member, so it names no users or groups to remove.`+ });+ }++ const removed = await agentVaultDelegationDAL.removeSubjectsByActors(+ { delegationId: current.id, userIds, groupIds },+ tx+ );+ return { before, after: (await viewNow()) ?? null, isChanged: removed > 0 };+ });+ if (!changed) throw notFound(machineIdentityId);++ return { delegation: changed.after, previous: changed.before, isChanged: changed.isChanged };+ };++ const listAvailableDelegationSubjects = async ({+ projectId,+ ctx,+ machineIdentityId,+ actorType,+ search,+ limit,+ offset+ }: TListAvailableDelegationSubjectsDTO) => {+ await checkIdentityPermission({ projectId, ctx, machineIdentityId }, ProjectPermissionIdentityActions.Read);++ const delegation = await agentVaultDelegationDAL.findForIdentity({ projectId, identityId: machineIdentityId });+ return agentVaultMemberDAL.findProductMembers({+ projectId,+ orgId: ctx.actorOrgId,+ actorTypes: actorType ? [actorType] : [AgentVaultMemberType.User, AgentVaultMemberType.Group],+ search,+ limit,+ offset,+ excludeDelegationId: delegation?.id+ });};const deleteDelegation = async ({ projectId, ctx, machineIdentityId }: TDeleteDelegationDTO) => {@@ -377,5 +514,14 @@ export const agentVaultDelegationServiceFactory = ({return { delegation: toDelegation(deleted) };};- return { listDelegations, getDelegation, setDelegation, deleteDelegation };+ return {+ listDelegations,+ getDelegation,+ setDelegation,+ addDelegationSubjects,+ removeDelegationSubjects,+ listAvailableDelegationSubjects,+ withMissingAccessBundles,+ deleteDelegation+ };};diff --git a/backend/src/ee/services/agent-vault-delegation/agent-vault-delegation-types.ts b/backend/src/ee/services/agent-vault-delegation/agent-vault-delegation-types.tsindex 330be63b66..8c9fc7ff34 100644--- a/backend/src/ee/services/agent-vault-delegation/agent-vault-delegation-types.ts+++ b/backend/src/ee/services/agent-vault-delegation/agent-vault-delegation-types.ts@@ -1,6 +1,6 @@import { TGenericPermission } from "@app/lib/types";-import { AgentVaultDelegationScope } from "../agent-vault/agent-vault-enums";+import { AgentVaultDelegationScope, AgentVaultMemberType } from "../agent-vault/agent-vault-enums";type TAgentVaultDelegationScoped = {projectId: string;@@ -24,3 +24,15 @@ export type TSetDelegationDTO = TGetDelegationDTO & {};export type TDeleteDelegationDTO = TGetDelegationDTO;++export type TChangeDelegationSubjectsDTO = TGetDelegationDTO & {+ userIds: string[];+ groupIds: string[];+};++export type TListAvailableDelegationSubjectsDTO = TGetDelegationDTO & {+ actorType?: AgentVaultMemberType.User | AgentVaultMemberType.Group;+ search?: string;+ limit: number;+ offset: number;+};diff --git a/backend/src/ee/services/agent-vault-member/agent-vault-member-dal.ts b/backend/src/ee/services/agent-vault-member/agent-vault-member-dal.tsindex dad38d8366..1790166a56 100644--- a/backend/src/ee/services/agent-vault-member/agent-vault-member-dal.ts+++ b/backend/src/ee/services/agent-vault-member/agent-vault-member-dal.ts@@ -95,13 +95,24 @@ type TFindProductMembersDTO = {offset: number;// Set to list the members who could still be granted that bundle.excludeAccessBundleId?: string;+ // Set to list the members who could still be added to that delegation.+ excludeDelegationId?: string;};-type TFindAvailableActorsDTO = Omit<TFindProductMembersDTO, "excludeAccessBundleId">;+type TFindAvailableActorsDTO = Omit<TFindProductMembersDTO, "excludeAccessBundleId" | "excludeDelegationId">;export const agentVaultMemberDALFactory = (db: TDbClient) => {const findProductMembers = async (- { projectId, orgId, actorTypes, search, limit, offset, excludeAccessBundleId }: TFindProductMembersDTO,+ {+ projectId,+ orgId,+ actorTypes,+ search,+ limit,+ offset,+ excludeAccessBundleId,+ excludeDelegationId+ }: TFindProductMembersDTO,tx?: Knex): Promise<{ members: TAgentVaultProductMember[]; totalCount: number }> => {if (!actorTypes.length) return { members: [], totalCount: 0 };@@ -142,6 +153,21 @@ export const agentVaultMemberDALFactory = (db: TDbClient) => {});});+ // A delegation names a member by its membership row, so this needs no per-type column.+ if (excludeDelegationId) {+ void query.whereNotExists(+ conn(TableName.AgentVaultDelegationSubject)+ .where(`${TableName.AgentVaultDelegationSubject}.delegationId`, excludeDelegationId)+ .whereRaw(`??.?? = ??.??`, [+ TableName.AgentVaultDelegationSubject,+ "membershipId",+ TableName.Membership,+ "id"+ ])+ .select(conn.raw("1"))+ );+ }+if (search) {const term = `%${sanitizeSqlLikeString(search)}%`;void query.where((qb) => {diff --git a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.test.ts b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.test.tsindex 81d18c66a2..bf09948d6c 100644--- a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.test.ts+++ b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.test.ts@@ -5,7 +5,7 @@ import {ProjectPermissionAgentVaultSessionActions,ProjectPermissionSub} from "@app/ee/services/permission/project-permission";-import { ConflictError } from "@app/lib/errors";+import { ConflictError, UnauthorizedError } from "@app/lib/errors";import { ObjectStorageType } from "@app/services/object-storage/object-storage-types";import { AGENT_VAULT_SERVICE_MOVED_MESSAGE } from "../agent-vault-oauth/agent-vault-oauth-service";@@ -293,3 +293,120 @@ describe("resolve's lazy refresh", () => {});});});++describe("resolve for a session on a user's behalf", () => {+ const USER_ID = "user-1";+ const IDENTITY_ID = "identity-1";+ type TActorSetup = { isAdmin?: boolean; grants?: string[]; isActive?: boolean };++ // Each actor gets its own org status, role and bundle grants, and resolve's reach is read off the bundles it asks for.+ const setupOnBehalfOf = ({+ user = {},+ identity = {},+ delegationCoversUser = true+ }: {+ user?: TActorSetup;+ identity?: TActorSetup;+ delegationCoversUser?: boolean;+ }) => {+ const actor = (actorId: string) => (actorId === IDENTITY_ID ? identity : user);+ const findResolvableServices = vi.fn(async () => [] as TResolveServiceRow[]);+ const service = agentVaultProxyServiceFactory({+ agentVaultProxyDAL: {+ findByIdWithOrg: async () => ({ projectId: PROJECT_ID, orgId: "org-1", pollInterval: 60 })+ } as never,+ agentVaultResolveDAL: { findResolvableServices },+ agentVaultServiceCustomHeaderDAL: { findByServiceIds: async () => [] },+ agentVaultServiceSubstitutionDAL: { findByServiceIds: async () => [] },+ agentVaultVariableDAL: { findValuesForResolve: async () => [] },+ agentVaultPersonalValueDAL: { findForResolve: async () => [] },+ agentVaultSessionDAL: {+ findByTokenHash: async () =>+ ({+ id: "session-1",+ projectId: PROJECT_ID,+ userId: USER_ID,+ identityId: null,+ actingIdentityId: IDENTITY_ID,+ actingIdentityName: "slack-bot",+ revokedAt: null,+ expiresAt: null+ }) as never+ },+ agentVaultDelegationDAL: { identityCoversUser: async () => delegationCoversUser },+ agentVaultSessionLogConfigDAL: {+ findOne: async () => sessionLogConfig,+ findByProjectIdFromPrimary: async () => sessionLogConfig+ },+ membershipDAL: {+ findResourceMembershipsForActor: async ({ actorId }: { actorId: string }) =>+ (actor(actorId).grants ?? []).map((scopeResourceId) => ({+ isActive: true,+ actorGroupId: null,+ scopeResourceId+ }))+ } as never,+ orgDAL: {+ findEffectiveOrgMembership: async ({ actorId }: { actorId: string }) =>+ ({ isActive: actor(actorId).isActive ?? true }) as never+ },+ permissionService: {+ getProjectPermission: async ({ actorId }: { actorId: string }) =>+ ({+ permission: createMongoAbility([+ {+ action: ProjectPermissionAgentVaultSessionActions.Read,+ subject: ProjectPermissionSub.AgentVaultSessions+ }+ ]),+ hasRole: () => Boolean(actor(actorId).isAdmin),+ memberships: []+ }) as never+ },+ kmsService: {+ createCipherPairWithDataKey: async () =>+ ({ decryptor: ({ cipherTextBlob }: { cipherTextBlob: Buffer }) => cipherTextBlob }) as never+ },+ licenseService: {} as never,+ resourceAuthMethodService: {} as never,+ agentVaultOauthService: {+ refreshServiceToken: vi.fn() as never,+ reportMissingScopes: vi.fn() as never+ }+ });+ const resolve = () =>+ service.resolveSession({ proxyId: "proxy-1", orgId: "org-1", sessionToken: "token", hasSessionLogKey: false });+ const reachedBundles = () =>+ (findResolvableServices.mock.calls[0] as unknown as [{ accessBundleIds: string[] | null }])[0].accessBundleIds;+ return { resolve, reachedBundles };+ };++ test("a non-admin user's reach is narrowed to the bundles the identity reaches too", async () => {+ const { resolve, reachedBundles } = setupOnBehalfOf({+ user: { grants: ["bundle-a", "bundle-b"] },+ identity: { grants: ["bundle-b", "bundle-c"] }+ });+ await resolve();+ expect(reachedBundles()).toEqual(["bundle-b"]);+ });++ test("an admin on either side leaves the other side's reach", async () => {+ const adminIdentity = setupOnBehalfOf({ user: { grants: ["bundle-a"] }, identity: { isAdmin: true } });+ await adminIdentity.resolve();+ expect(adminIdentity.reachedBundles()).toEqual(["bundle-a"]);++ const adminUser = setupOnBehalfOf({ user: { isAdmin: true }, identity: { grants: ["bundle-c"] } });+ await adminUser.resolve();+ expect(adminUser.reachedBundles()).toEqual(["bundle-c"]);+ });++ test("a delegation that no longer covers the user is a 401", async () => {+ const { resolve } = setupOnBehalfOf({ user: { grants: ["bundle-a"] }, delegationCoversUser: false });+ await expect(resolve()).rejects.toThrow(UnauthorizedError);+ });++ test("an identity deactivated in the org is a 401", async () => {+ const { resolve } = setupOnBehalfOf({ user: { grants: ["bundle-a"] }, identity: { isActive: false } });+ await expect(resolve()).rejects.toThrow(UnauthorizedError);+ });+});diff --git a/backend/src/ee/services/agent-vault/AGENTS.md b/backend/src/ee/services/agent-vault/AGENTS.mdindex 5d68b59fce..87535fb907 100644--- a/backend/src/ee/services/agent-vault/AGENTS.md+++ b/backend/src/ee/services/agent-vault/AGENTS.md@@ -126,9 +126,9 @@ and `packages/agentvault/` in the CLI repo. Frontend: `frontend/src/pages/agent-A machine identity with a **delegation** can mint a session on behalf of a user (`onBehalfOf` on mint). The sessionbelongs to the user: `userId` is the user, so resolve uses the user's role and personal values without a branch of itsown. The identity is kept as `actingIdentityId` and `actingIdentityName`, and its reach narrows the user's. A delegation-is one-`agent_vault_delegations` row per identity, with a scope of `all-members` or `selected`, plus-`agent_vault_delegation_subjects` rows naming users and groups.+is one `agent_vault_delegations` row per identity, with a scope of `all-members` or `selected`, plus+`agent_vault_delegation_subjects` rows naming users and groups. Both reference an Agent Vault membership (`membershipId`,+`ON DELETE CASCADE`): the delegation its identity's, and each subject the user's or group's.- **Never put the acting identity in `identityId`.** Resolve reads `userId` first and falls back to `identityId`, sodeleting the user would quietly turn the session into the identity's own, with the identity's grants. The DB check@@ -153,8 +153,9 @@ is one- **The delegation read and write return `missingAccessBundles`**, per user and group and in total: the bundles theycan use and the identity can't. Users and the identity go through `getAgentVaultReachability`, the function mintuses, so the view can't disagree with mint; a group's reach is its own live role and grants, read directly since a- group never holds a session. The list leaves it out, because it reads every covered user's access, and the write- works it out after its transaction commits.+ group never holds a session. The list leaves it out, because it reads every covered user's access. The write works+ it out after its transaction commits and after the router writes the audit event, so a failure there can't leave a+ committed save unaudited.- **Mint runs `getProjectPermission` for the user, then once more for the caller.** The permission service leavesthe last actor it ran for in the request context, where the audit log reads the caller's permission metadata. Thesecond call is memoized, so it costs no query; dropping it attributes the user's metadata to the identity.@@ -170,9 +171,19 @@ is one- **A subject is named by its own Agent Vault membership**, the rule bundle grants use: a user who reaches AgentVault only through a group is covered by naming the group. Coverage itself is read live, so leaving the groupends it.-- **Removing an identity from Agent Vault deletes its delegation**, in the revoke transaction, so adding it back- restores nothing. Platform paths (org removal, the generic project membership routes) don't, and a delegation can- outlive the membership there; resolve still refuses, because it requires the identity's live Agent Vault role.+- **Leaving Agent Vault by any path deletes the delegation rows**, through the membership FK cascade: Agent Vault's own+ removal, the generic project membership routes, leaving the org, SCIM delete, and deleting the actor. So adding the+ identity, user or group back restores nothing. Deactivating (SCIM or org) deletes nothing; mint and resolve refuse+ through the `isActive` check. Membership rows keep their id while the actor stays a member (role changes only touch+ `membership_roles`), so a one-off migration that rewrites membership rows has to repoint these keys.+- **The dashboard changes a delegation one user or group at a time** (`POST` and `DELETE .../subjects`, candidates from+ `.../subjects/available`), never through the whole-list `PUT`, so two admins editing at once, or a page holding an+ old list, can't undo each other's changes. `PUT` stays for API callers that set the whole list, and for scope.+- **A selected delegation whose subjects have all left reads as none** (404, left out of the list, refused at mint), and+ 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.- **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/backend/src/ee/services/agent-vault/agent-vault-permission.test.ts b/backend/src/ee/services/agent-vault/agent-vault-permission.test.tsnew file mode 100644index 0000000000..374b6f5c5b--- /dev/null+++ b/backend/src/ee/services/agent-vault/agent-vault-permission.test.ts@@ -0,0 +1,18 @@+import { describe, expect, test } from "vitest";++import { intersectAccessBundleIds } from "./agent-vault-permission";++describe("intersectAccessBundleIds", () => {+ // null is every bundle, the admin role's reach.+ test.each([+ { a: null, b: null, expected: null },+ { a: null, b: [], expected: [] },+ { a: [], b: null, expected: [] },+ { a: null, b: ["x"], expected: ["x"] },+ { a: ["x"], b: null, expected: ["x"] },+ { a: ["x", "y"], b: ["y", "z"], expected: ["y"] },+ { a: ["x"], b: ["z"], expected: [] }+ ])("$a and $b reach $expected", ({ a, b, expected }) => {+ expect(intersectAccessBundleIds(a, b)).toEqual(expected);+ });+});diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex c0292f17a2..709cd13beb 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -6854,6 +6854,9 @@ interface AgentVaultDelegationDeleteEvent {metadata: {machineIdentityId: string;machineIdentityName: string;+ scope: string;+ users: { userId: string; userName: string }[];+ groups: { groupId: string; groupName: string }[];};}diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex fe9038fa95..0d51f03986 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -4940,9 +4940,9 @@ export const AGENT_VAULT = {scope:"Which users the machine identity can start sessions on behalf of: every Agent Vault member (all-members), or only the users and the members of the groups in the delegation (selected).",userIds:- "The users the machine identity can act on behalf of. Each must be a member of Agent Vault. Only allowed when the scope is selected.",+ "The users the machine identity can act on behalf of, up to 100. Each must be a member of Agent Vault. Only allowed when the scope is selected.",groupIds:- "The groups whose members the machine identity can act on behalf of. Each must be a member of Agent Vault. Only allowed when the scope is selected.",+ "The groups whose members the machine identity can act on behalf of, up to 100. Each must be a member of Agent Vault. Only allowed when the scope is selected.",users: "The users in the delegation.",groups: "The groups in the delegation. Their members are covered while they stay in the group.",userId: "The ID of the user.",@@ -4965,7 +4965,22 @@ export const AGENT_VAULT = {updatedAt: "When the delegation was last saved.",limit: "The maximum number of delegations to return.",offset: "How many delegations to skip.",- totalCount: "How many delegations match, across every page."+ totalCount: "How many delegations match, across every page.",+ addUserIds:+ "The users to add, up to 100. Each must be a member of Agent Vault. Users the delegation already names are skipped.",+ addGroupIds:+ "The groups to add, up to 100. Each must be a member of Agent Vault. Groups the delegation already names are skipped.",+ removeUserIds: "The users to take out of the delegation, up to 100. Users it doesn't name are skipped.",+ removeGroupIds: "The groups to take out of the delegation, up to 100. Groups it doesn't name are skipped.",+ afterRemove:+ "The delegation after the change, or null if it no longer names anyone. A delegation that names no one is removed."+ },+ AVAILABLE_DELEGATION_SUBJECT: {+ actorTypeFilter: "List only users, or only groups.",+ search: "Match users by name, username or email address, and groups by name.",+ limit: "The maximum number of users and groups to return.",+ offset: "How many users and groups to skip.",+ totalCount: "How many users and groups match, across every page."}};diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 8fa05b772c..112a1f3afa 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -2136,6 +2136,7 @@ export const registerRoutes = async (agentVaultDelegationDAL,agentVaultDelegationSubjectDAL,agentVaultAccessBundleDAL,+ agentVaultMemberDAL,membershipDAL,membershipRoleDAL,userGroupMembershipDAL,diff --git a/backend/src/services/telemetry/telemetry-types.ts b/backend/src/services/telemetry/telemetry-types.tsindex 2916a9023d..89f456555e 100644--- a/backend/src/services/telemetry/telemetry-types.ts+++ b/backend/src/services/telemetry/telemetry-types.ts@@ -343,6 +343,8 @@ export enum PostHogEventTypes {AgentVaultProductMemberAdded = "Agent Vault Product Member Added",AgentVaultProductMemberUpdated = "Agent Vault Product Member Updated",AgentVaultProductMemberRemoved = "Agent Vault Product Member Removed",+ AgentVaultDelegationSet = "Agent Vault Delegation Set",+ AgentVaultDelegationDeleted = "Agent Vault Delegation Deleted",// Billing trials. Cloud-only: the self-hosted license backend rejects startTrial outright.// "awaiting_card" gets its own event rather than an outcome property on TrialStarted, because it@@ -2613,6 +2615,17 @@ export type TAgentVaultProductMemberRemovedEvent = {properties: TAgentVaultEventBase & { memberType: AgentVaultMemberType };};+// Counts only: a delegation's users and groups are never sent.+export type TAgentVaultDelegationSetEvent = {+ event: PostHogEventTypes.AgentVaultDelegationSet;+ properties: TAgentVaultEventBase & { scope: string; userCount: number; groupCount: number };+};++export type TAgentVaultDelegationDeletedEvent = {+ event: PostHogEventTypes.AgentVaultDelegationDeleted;+ properties: TAgentVaultEventBase & { scope: string; userCount: number; groupCount: number };+};+export type TAgentVaultPostHogEvent =| TAgentVaultAccessBundleCreatedEvent| TAgentVaultAccessBundleUpdatedEvent@@ -2636,7 +2649,9 @@ export type TAgentVaultPostHogEvent =| TAgentVaultSessionLogChunkAcceptedEvent| TAgentVaultProductMemberAddedEvent| TAgentVaultProductMemberUpdatedEvent- | TAgentVaultProductMemberRemovedEvent;+ | TAgentVaultProductMemberRemovedEvent+ | TAgentVaultDelegationSetEvent+ | TAgentVaultDelegationDeletedEvent;export type TAgentVaultActorPostHogEvent = Exclude<TAgentVaultPostHogEvent, TAgentVaultSessionLogChunkAcceptedEvent>;diff --git a/docs/api-reference/endpoints/agent-vault-delegations/add-subjects.mdx b/docs/api-reference/endpoints/agent-vault-delegations/add-subjects.mdxnew file mode 100644index 0000000000..65de88fd4e--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-delegations/add-subjects.mdx@@ -0,0 +1,4 @@+---+title: "Add users and groups"+openapi: "POST /api/v1/agent-vault/delegations/{machineIdentityId}/subjects"+---diff --git a/docs/api-reference/endpoints/agent-vault-delegations/list-available-subjects.mdx b/docs/api-reference/endpoints/agent-vault-delegations/list-available-subjects.mdxnew file mode 100644index 0000000000..f6ed9ba559--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-delegations/list-available-subjects.mdx@@ -0,0 +1,4 @@+---+title: "List available users and groups"+openapi: "GET /api/v1/agent-vault/delegations/{machineIdentityId}/subjects/available"+---diff --git a/docs/api-reference/endpoints/agent-vault-delegations/remove-subjects.mdx b/docs/api-reference/endpoints/agent-vault-delegations/remove-subjects.mdxnew file mode 100644index 0000000000..dc76f196ab--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-delegations/remove-subjects.mdx@@ -0,0 +1,4 @@+---+title: "Remove users and groups"+openapi: "DELETE /api/v1/agent-vault/delegations/{machineIdentityId}/subjects"+---diff --git a/docs/docs.json b/docs/docs.jsonindex 717eec0b7e..301aa85972 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -4595,6 +4595,9 @@"api-reference/endpoints/agent-vault-delegations/list","api-reference/endpoints/agent-vault-delegations/get","api-reference/endpoints/agent-vault-delegations/set",+ "api-reference/endpoints/agent-vault-delegations/add-subjects",+ "api-reference/endpoints/agent-vault-delegations/remove-subjects",+ "api-reference/endpoints/agent-vault-delegations/list-available-subjects","api-reference/endpoints/agent-vault-delegations/delete"]},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.mdxindex 57515beea8..9f50c1e55e 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@@ -3,7 +3,7 @@ title: "Sessions on behalf of users"description: "Let a machine identity, such as a chat bot or a task runner, create sessions on behalf of users, so each session uses the personal values of the user it's for."----A delegation lets a [machine identity](/documentation/platform/identities/machine-identities) create [sessions](/documentation/platform/agent-vault/sessions) on behalf of users in Agent Vault. The machine identity can still create sessions as itself. It creates a session on behalf of a user only if it sends the user's email or ID in `onBehalfOf`. A session created on behalf of a user belongs to that user, so the [proxy](/documentation/platform/agent-vault/proxies) uses the user's own [personal values](/documentation/platform/agent-vault/services#member-provided-values), not the machine identity's. The session can use an [access bundle](/documentation/platform/agent-vault/access-bundles) only if both the user and the machine identity can use the bundle.+A delegation lets a [machine identity](/documentation/platform/identities/machine-identities) create [sessions](/documentation/platform/agent-vault/sessions) on behalf of users in Agent Vault. The machine identity can still create sessions as itself. It creates a session on behalf of a user only if it sends the user's email or ID in `onBehalfOf`. A session created on behalf of a user belongs to that user, so the [proxy](/documentation/platform/agent-vault/proxies) uses the user's own [personal values](/documentation/platform/agent-vault/http-apis#member-provided-values), not the machine identity's. The session can use an [access bundle](/documentation/platform/agent-vault/access-bundles) only if both the user and the machine identity can use the bundle.Use a delegation when one service starts agents for many people, such as a chat bot that runs an agent for each message, or a task runner that runs an agent for each ticket. Each agent then gets no more access than the person who asked for it.@@ -39,14 +39,14 @@ sequenceDiagramIn Agent Vault, go to **Access Control**, select the **Machine Identities** tab, and select the machine identity.</Step><Step>- In the **Delegation** section, select **Add Users or Groups**.+ In the **Delegation** section, select **Manage Delegation**.<Frame>- <img src="/images/platform/agent-vault/machine-identity-delegation.png" alt="The Delegation section of a machine identity, listing two groups and a user with the date each was added, and the Add Users or Groups button" />+ <img src="/images/platform/agent-vault/machine-identity-delegation.png" alt="The Delegation section of a machine identity, listing two groups and a user with the date each was added, and the Manage Delegation button" /></Frame></Step><Step>- In **Users and Groups**, select the users and groups to add, then select **Add**. A group covers every member of the group.+ Expand **Not in Delegation**, then select **Add** next to each user or group to add. A group covers every member of the group. If someone isn't listed, search for them by name. Changes save as you make them.To cover every current and future user in Agent Vault instead, turn on **All Agent Vault Members** and select **Allow All Members**.</Step>@@ -63,15 +63,20 @@ sequenceDiagram```Set `scope` to `all-members` to cover every Agent Vault member, or to `selected` with `userIds`, `groupIds`, or both. The request replaces any delegation the machine identity already has.++ To add or remove users and groups without sending the whole list, call [the endpoint that adds users and groups](/api-reference/endpoints/agent-vault-delegations/add-subjects) or [the endpoint that removes them](/api-reference/endpoints/agent-vault-delegations/remove-subjects).</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. 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.+To take a user or group out of the delegation, select **Manage Delegation**, select **In Delegation** on its row, select **Remove**, then select **Remove** again to confirm. If you remove the last user or group, or turn off **All Agent Vault Members**, the machine identity can no longer act on behalf of anyone.<Warning>- If a machine identity has a delegation, anyone who can log in as the machine identity can send requests with the personal values of every user the delegation covers. Protect the machine identity's credentials as carefully as you'd protect those users' own credentials.+ A delegation lets a machine identity use other people's personal values, so protect who can set one and who can use one:++ - If a machine identity has a delegation, anyone who can log in as the machine identity can send requests with the personal values of every user the delegation covers. Protect the machine identity's credentials as carefully as you'd protect those users' own credentials+ - A machine identity with the Agent Vault **Admin** role can set delegations, including one for itself that covers every member, Agent Vault admins included. Give a machine identity the **Admin** role only if it needs it</Warning>## Create a session on behalf of a user@@ -166,7 +171,7 @@ When the machine identity creates the session, Infisical writes an audit event w<Card title="Create sessions with the API" icon="code" href="/documentation/platform/agent-vault/sessions-api">Create, use, and revoke a session from your own code.</Card>- <Card title="Services" icon="plug" href="/documentation/platform/agent-vault/services#member-provided-values">+ <Card title="HTTP APIs" icon="plug" href="/documentation/platform/agent-vault/http-apis#member-provided-values">Leave part of a service's credential to each member.</Card></CardGroup>diff --git a/docs/images/platform/agent-vault/machine-identity-delegation.png b/docs/images/platform/agent-vault/machine-identity-delegation.pngindex 5f2eb9aa9e..424ed36a1e 100644Binary files a/docs/images/platform/agent-vault/machine-identity-delegation.png and b/docs/images/platform/agent-vault/machine-identity-delegation.png differdiff --git a/frontend/src/components/agent-vault/AddDelegationSubjectsDialog.tsx b/frontend/src/components/agent-vault/AddDelegationSubjectsDialog.tsxdeleted file mode 100644index 839ad61f8c..0000000000--- a/frontend/src/components/agent-vault/AddDelegationSubjectsDialog.tsx+++ /dev/null@@ -1,258 +0,0 @@-import { useEffect, useMemo, useState } from "react";-import { TriangleAlertIcon } from "lucide-react";--import { createNotification } from "@app/components/notifications";-import {- Alert,- AlertDescription,- Button,- Combobox,- Dialog,- DialogContent,- DialogDescription,- DialogFooter,- DialogHeader,- DialogTitle,- Field,- FieldContent,- FieldDescription,- FieldLabel,- FieldTitle,- Toggle-} from "@app/components/v3";-import { useDebounce } from "@app/hooks";-import { useListAgentVaultMembers, useSetAgentVaultDelegation } from "@app/hooks/api/agentVault";-import { AgentVaultDelegationScope, AgentVaultMemberType } from "@app/hooks/api/agentVault/enums";-import { TAgentVaultDelegation } from "@app/hooks/api/agentVault/types";--import { MEMBER_KIND, memberDisplayName, memberSubtitle } from "./MemberName";--type SubjectOption = {- type: AgentVaultMemberType.User | AgentVaultMemberType.Group;- id: string;- label: string;- subtitle: string;-};--const PICKER_LIMIT = 50;--type Props = {- isOpen: boolean;- onOpenChange: (isOpen: boolean) => void;- machineIdentityId: string;- machineIdentityName: string;- delegation: TAgentVaultDelegation | null;-};--export const AddDelegationSubjectsDialog = ({- isOpen,- onOpenChange,- machineIdentityId,- machineIdentityName,- delegation-}: Props) => {- const setDelegation = useSetAgentVaultDelegation();-- const isCurrentlyAllMembers = delegation?.scope === AgentVaultDelegationScope.AllMembers;- const [isAllMembers, setIsAllMembers] = useState(false);- const [selected, setSelected] = useState<SubjectOption[]>([]);- const [search, setSearch] = useState("");- const [debouncedSearch] = useDebounce(search);-- useEffect(() => {- if (!isOpen) return;- setIsAllMembers(isCurrentlyAllMembers);- setSelected([]);- setSearch("");- }, [isOpen]);-- // A subject has to be an Agent Vault member, so the picker lists members rather than the whole org.- const isPickerShown = isOpen && !isAllMembers;- const memberSearch = { search: debouncedSearch.trim() || undefined, limit: PICKER_LIMIT };- const { data: users, isFetching: isFetchingUsers } = useListAgentVaultMembers(- { ...memberSearch, actorType: AgentVaultMemberType.User },- isPickerShown- );- const { data: groups, isFetching: isFetchingGroups } = useListAgentVaultMembers(- { ...memberSearch, actorType: AgentVaultMemberType.Group },- isPickerShown- );-- const listedUserIds = new Set(delegation?.users.map((user) => user.id));- const listedGroupIds = new Set(delegation?.groups.map((group) => group.id));-- const options = useMemo<SubjectOption[]>(- () => [- ...(users?.members ?? [])- .filter((user) => !listedUserIds.has(user.id))- .map((user) => ({- type: AgentVaultMemberType.User as const,- id: user.id,- label: memberDisplayName(user),- subtitle: memberSubtitle(user)- })),- ...(groups?.members ?? [])- .filter((group) => !listedGroupIds.has(group.id))- .map((group) => ({- type: AgentVaultMemberType.Group as const,- id: group.id,- label: group.name,- subtitle: MEMBER_KIND[AgentVaultMemberType.Group].label- }))- ],- [users, groups, delegation]- );-- const isListTruncated =- (users?.totalCount ?? 0) > (users?.members.length ?? 0) ||- (groups?.totalCount ?? 0) > (groups?.members.length ?? 0);-- const isUnchanged = isAllMembers ? isCurrentlyAllMembers : !selected.length;-- const handleSave = async () => {- try {- if (isAllMembers) {- await setDelegation.mutateAsync({- machineIdentityId,- scope: AgentVaultDelegationScope.AllMembers- });- createNotification({- text: `"${machineIdentityName}" now acts on behalf of every Agent Vault member`,- type: "success"- });- } else {- const idsOf = (type: SubjectOption["type"]) =>- selected.filter((option) => option.type === type).map((option) => option.id);- await setDelegation.mutateAsync({- machineIdentityId,- scope: AgentVaultDelegationScope.Selected,- userIds: [...listedUserIds, ...idsOf(AgentVaultMemberType.User)],- groupIds: [...listedGroupIds, ...idsOf(AgentVaultMemberType.Group)]- });- createNotification({- text:- selected.length === 1- ? `"${selected[0].label}" added to the delegation`- : `${selected.length} users and groups added to the delegation`,- type: "success"- });- }- onOpenChange(false);- } catch {- // A failed request returns a 4xx that the global request handler surfaces as a toast- }- };-- // Only narrowing gets a note: switching to all members still covers everyone listed.- const note =- !isAllMembers && isCurrentlyAllMembers- ? "This replaces All Agent Vault Members with the users and groups you pick."- : null;-- return (- <Dialog open={isOpen} onOpenChange={onOpenChange}>- <DialogContent>- <DialogHeader>- <DialogTitle>Add Users or Groups</DialogTitle>- <DialogDescription>- "{machineIdentityName}" can start sessions on behalf of the users you add, and- of every member of the groups you add.- </DialogDescription>- </DialogHeader>-- <Field orientation="horizontal" className="rounded-md border border-border p-4">- <FieldContent>- <FieldTitle>All Agent Vault Members</FieldTitle>- <FieldDescription>- Act on behalf of every user in Agent Vault, including users added later.- </FieldDescription>- </FieldContent>- <Toggle- id="agent-vault-delegation-all-members"- variant="av"- checked={isAllMembers}- onCheckedChange={setIsAllMembers}- />- </Field>-- {!isAllMembers && (- <Field>- <FieldLabel htmlFor="agent-vault-delegation-subjects">Users and Groups</FieldLabel>- <FieldContent>- <Combobox- id="agent-vault-delegation-subjects"- multiple- options={options}- value={selected}- isLoading={isFetchingUsers || isFetchingGroups}- onSearchChange={setSearch}- getOptionValue={(option) => `${option.type}:${option.id}`}- getOptionLabel={(option) => option.label}- placeholder="Pick users or groups..."- searchPlaceholder="Pick users or groups..."- searchAriaLabel="Search users and groups"- emptyMessage={(inputValue) =>- inputValue- ? "No Agent Vault users or groups that aren't already added match your search."- : "Every Agent Vault user and group is already in the delegation."- }- clearAriaLabel="Clear all users and groups"- modal- onValueChange={(next) => setSelected([...next])}- renderValue={(option) => {- const { icon: Icon } = MEMBER_KIND[option.type];- return (- <span className="flex min-w-0 items-center gap-1.5">- <Icon className="size-3.5 shrink-0 text-muted" />- <span className="truncate">{option.label}</span>- </span>- );- }}- renderOption={(option) => {- const { icon: Icon } = MEMBER_KIND[option.type];- return (- <span className="flex min-w-0 items-center gap-2.5">- <Icon className="size-4 shrink-0 text-muted" />- <span className="min-w-0">- <span className="block truncate">{option.label}</span>- <span className="block truncate text-xs leading-4 text-muted">- {option.subtitle}- </span>- </span>- </span>- );- }}- />- <FieldDescription>- {isListTruncated- ? "Search by name to find users and groups that are not listed."- : "Only members of Agent Vault are listed. A user who is in Agent Vault through a group is covered by adding the group."}- </FieldDescription>- </FieldContent>- </Field>- )}-- {note && (- <Alert variant="warning">- <TriangleAlertIcon />- <AlertDescription>{note}</AlertDescription>- </Alert>- )}-- <DialogFooter>- <Button variant="ghost" onClick={() => onOpenChange(false)}>- Cancel- </Button>- <Button- variant="av"- isDisabled={isUnchanged}- isPending={setDelegation.isPending}- onClick={async () => handleSave()}- >- {isAllMembers ? "Allow All Members" : "Add"}- </Button>- </DialogFooter>- </DialogContent>- </Dialog>- );-};diff --git a/frontend/src/components/agent-vault/IdentityDelegationSection.tsx b/frontend/src/components/agent-vault/IdentityDelegationSection.tsxindex c32b451f97..02584740b7 100644--- a/frontend/src/components/agent-vault/IdentityDelegationSection.tsx+++ b/frontend/src/components/agent-vault/IdentityDelegationSection.tsx@@ -1,17 +1,8 @@import { useState } from "react";import { format } from "date-fns";-import { MoreHorizontalIcon, Trash2Icon, UserPlusIcon, UsersRoundIcon } from "lucide-react";+import { UserCogIcon, UsersRoundIcon } from "lucide-react";-import { createNotification } from "@app/components/notifications";import {- AlertDialog,- AlertDialogAction,- AlertDialogCancel,- AlertDialogContent,- AlertDialogDescription,- AlertDialogFooter,- AlertDialogHeader,- AlertDialogTitle,Button,Card,CardAction,@@ -20,16 +11,11 @@ import {CardHeader,CardTitle,DocumentationLinkBadge,- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuTrigger,Empty,EmptyContent,EmptyDescription,EmptyHeader,EmptyTitle,- IconButton,Skeleton,Table,TableBody,@@ -39,17 +25,12 @@ import {TableRow} from "@app/components/v3";import { useProjectPermission } from "@app/context";-import {- useDeleteAgentVaultDelegation,- useGetAgentVaultDelegation,- useSetAgentVaultDelegation-} from "@app/hooks/api/agentVault";+import { useGetAgentVaultDelegation } from "@app/hooks/api/agentVault";import { AgentVaultDelegationScope, AgentVaultMemberType } from "@app/hooks/api/agentVault/enums";-import { TAgentVaultActor, TAgentVaultMissingAccessBundle } from "@app/hooks/api/agentVault/types";import { ProjectMembershipRole } from "@app/hooks/api/roles/types";import { AgentVaultDocsUrls } from "@app/pages/agent-vault/agent-vault-docs-urls";-import { AddDelegationSubjectsDialog } from "./AddDelegationSubjectsDialog";+import { ManageDelegationSheet, TDelegationSubjectRow } from "./ManageDelegationSheet";import { memberDisplayName, MemberName } from "./MemberName";import { MissingAccessBundlesHint } from "./MissingAccessBundlesHint";@@ -58,14 +39,8 @@ type Props = {machineIdentityName: string;};-type TSubjectRow = TAgentVaultActor & {- addedAt: string;- missingAccessBundles: TAgentVaultMissingAccessBundle[];-};--type TPendingRemoval = { kind: "subject"; subject: TSubjectRow } | { kind: "all-members" };--// Only admins can read or change a delegation, so members don't see the section at all.+// Only admins can read or change a delegation, so members don't see the section at all. Changes happen+// in the Manage Delegation sheet; this lists who the delegation covers.export const IdentityDelegationSection = ({ machineIdentityId, machineIdentityName }: Props) => {const { hasProjectRole } = useProjectPermission();const isAdmin = hasProjectRole(ProjectMembershipRole.Admin);@@ -75,18 +50,14 @@ export const IdentityDelegationSection = ({ machineIdentityId, machineIdentityNaisAdmin);const delegation = data ?? null;- // A save sends the whole list, so without a successful read it would replace what's there.+ // Without a successful read the sheet would start from a list it never saw.const isLoadError = isError && data === undefined;- const setDelegation = useSetAgentVaultDelegation();- const deleteDelegation = useDeleteAgentVaultDelegation();-- const [isAddOpen, setIsAddOpen] = useState(false);- const [pendingRemoval, setPendingRemoval] = useState<TPendingRemoval | null>(null);+ const [isManageOpen, setIsManageOpen] = useState(false);if (!isAdmin) return null;const isAllMembers = delegation?.scope === AgentVaultDelegationScope.AllMembers;- const subjects: TSubjectRow[] = [+ const subjects: TDelegationSubjectRow[] = [...(delegation?.groups ?? []).map((group) => ({type: AgentVaultMemberType.Group as const,...group@@ -96,81 +67,6 @@ export const IdentityDelegationSection = ({ machineIdentityId, machineIdentityNa...user}))];- const isMutating = setDelegation.isPending || deleteDelegation.isPending;- // A delegation to selected users names at least one, so taking out the last one removes the delegation.- const removesDelegation = pendingRemoval?.kind === "all-members" || subjects.length === 1;-- const applyRemoval = async () => {- if (!pendingRemoval) return;- try {- if (removesDelegation) {- await deleteDelegation.mutateAsync({ machineIdentityId });- createNotification({- text: `Delegation for "${machineIdentityName}" removed`,- type: "success"- });- } else if (pendingRemoval.kind === "subject") {- const { subject } = pendingRemoval;- const remaining = subjects.filter(- (row) => !(row.type === subject.type && row.id === subject.id)- );- await setDelegation.mutateAsync({- machineIdentityId,- scope: AgentVaultDelegationScope.Selected,- userIds: remaining- .filter((row) => row.type === AgentVaultMemberType.User)- .map((row) => row.id),- groupIds: remaining- .filter((row) => row.type === AgentVaultMemberType.Group)- .map((row) => row.id)- });- createNotification({- text: `"${memberDisplayName(subject)}" removed from the delegation`,- type: "success"- });- }- setPendingRemoval(null);- } catch {- // A failed request returns a 4xx that the global request handler surfaces as a toast- }- };-- const removalCopy = () => {- if (!pendingRemoval) return { title: "", description: "" };- if (pendingRemoval.kind === "all-members") {- return {- title: "Stop Acting on Behalf of All Members",- description: `"${machineIdentityName}" can no longer start sessions on behalf of anyone until you add users or groups, and the sessions it started stop working at the next proxy poll.`- };- }- const { subject } = pendingRemoval;- const name = memberDisplayName(subject);- const whose =- subject.type === AgentVaultMemberType.Group ? `the members of "${name}"` : `"${name}"`;- return {- title: `Remove "${name}" From the Delegation`,- description: `"${machineIdentityName}" can no longer start sessions on behalf of ${whose}, and the sessions it started for them stop working at the next proxy poll.${- removesDelegation ? " This is the last user or group, so the delegation is removed." : ""- }`- };- };- const copy = removalCopy();-- const rowActions = (label: string, onRemove: () => void) => (- <DropdownMenu>- <DropdownMenuTrigger asChild>- <IconButton variant="ghost" size="xs" aria-label={`Actions for ${label}`}>- <MoreHorizontalIcon />- </IconButton>- </DropdownMenuTrigger>- <DropdownMenuContent sideOffset={2} align="end">- <DropdownMenuItem variant="danger" onClick={onRemove}>- <Trash2Icon />- Remove- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- );const renderList = () => {if (isPending) return <Skeleton className="h-16 w-full" />;@@ -202,7 +98,8 @@ export const IdentityDelegationSection = ({ machineIdentityId, machineIdentityNa<EmptyHeader><EmptyTitle>No users or groups yet</EmptyTitle><EmptyDescription>- Add a user or group to let this machine identity start sessions on their behalf.+ Manage the delegation to let this machine identity start sessions on behalf of users+ and groups.</EmptyDescription></EmptyHeader></Empty>@@ -239,9 +136,6 @@ export const IdentityDelegationSection = ({ machineIdentityId, machineIdentityNamachineIdentityName={machineIdentityName}onBehalfOf="Agent Vault members"/>- {rowActions("All Agent Vault Members", () =>- setPendingRemoval({ kind: "all-members" })- )}</div></TableCell></TableRow>@@ -263,9 +157,6 @@ export const IdentityDelegationSection = ({ machineIdentityId, machineIdentityNa: `"${memberDisplayName(subject)}"`}/>- {rowActions(memberDisplayName(subject), () =>- setPendingRemoval({ kind: "subject", subject })- )}</div></TableCell></TableRow>@@ -289,49 +180,19 @@ export const IdentityDelegationSection = ({ machineIdentityId, machineIdentityNa</CardDescription>{!isPending && !isLoadError && (<CardAction>- <Button variant="av" onClick={() => setIsAddOpen(true)}>- <UserPlusIcon />- Add Users or Groups+ <Button variant="av" onClick={() => setIsManageOpen(true)}>+ <UserCogIcon />+ Manage Delegation</Button></CardAction>)}</CardHeader><CardContent>{renderList()}</CardContent>- <AddDelegationSubjectsDialog- isOpen={isAddOpen}- onOpenChange={setIsAddOpen}- machineIdentityId={machineIdentityId}- machineIdentityName={machineIdentityName}- delegation={delegation}+ <ManageDelegationSheet+ machineIdentity={isManageOpen ? { id: machineIdentityId, name: machineIdentityName } : null}+ onOpenChange={setIsManageOpen}/>-- <AlertDialog- open={Boolean(pendingRemoval)}- onOpenChange={(isOpen) => {- if (!isOpen && !isMutating) setPendingRemoval(null);- }}- >- <AlertDialogContent>- <AlertDialogHeader>- <AlertDialogTitle>{copy.title}</AlertDialogTitle>- <AlertDialogDescription>{copy.description}</AlertDialogDescription>- </AlertDialogHeader>- <AlertDialogFooter>- <AlertDialogCancel isDisabled={isMutating}>Cancel</AlertDialogCancel>- <AlertDialogAction- variant="danger"- isPending={isMutating}- onClick={async (event) => {- event.preventDefault();- await applyRemoval();- }}- >- Remove- </AlertDialogAction>- </AlertDialogFooter>- </AlertDialogContent>- </AlertDialog></Card>);};diff --git a/frontend/src/components/agent-vault/ManageDelegationSheet.tsx b/frontend/src/components/agent-vault/ManageDelegationSheet.tsxnew file mode 100644index 0000000000..efcc3a5626--- /dev/null+++ b/frontend/src/components/agent-vault/ManageDelegationSheet.tsx@@ -0,0 +1,669 @@+import { useEffect, useRef, useState } from "react";+import { format } from "date-fns";+import {+ BotIcon,+ ChevronDownIcon,+ FilterIcon,+ SearchIcon,+ Trash2Icon,+ UsersIcon,+ UsersRoundIcon,+ XIcon+} from "lucide-react";++import { createNotification } from "@app/components/notifications";+import {+ Accordion,+ AccordionContent,+ AccordionItem,+ AccordionTrigger,+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+ Button,+ DocumentationLinkBadge,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuRadioGroup,+ DropdownMenuRadioItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+ Empty,+ EmptyDescription,+ EmptyHeader,+ EmptyMedia,+ EmptyTitle,+ Field,+ FieldContent,+ FieldDescription,+ FieldTitle,+ IconButton,+ InputGroup,+ InputGroupAddon,+ InputGroupButton,+ InputGroupInput,+ Separator,+ Sheet,+ SheetContent,+ SheetFooter,+ SheetHeader,+ SheetTitle,+ Skeleton,+ Toggle,+ Tooltip,+ TooltipContent,+ TooltipTrigger+} from "@app/components/v3";+import { useDebounce } from "@app/hooks";+import {+ useAddAgentVaultDelegationSubjects,+ useDeleteAgentVaultDelegation,+ useGetAgentVaultDelegation,+ useListAvailableAgentVaultDelegationSubjects,+ useRemoveAgentVaultDelegationSubjects,+ useSetAgentVaultDelegation+} from "@app/hooks/api/agentVault";+import { AgentVaultDelegationScope, AgentVaultMemberType } from "@app/hooks/api/agentVault/enums";+import {+ TAgentVaultActor,+ TAgentVaultMissingAccessBundle,+ TAgentVaultProductMember+} from "@app/hooks/api/agentVault/types";+import { AgentVaultDocsUrls } from "@app/pages/agent-vault/agent-vault-docs-urls";++import { MEMBER_KIND, memberDisplayName, memberSubtitle } from "./MemberName";+import { MissingAccessBundlesHint } from "./MissingAccessBundlesHint";+import { PendingInvitationBadge } from "./PendingInvitationBadge";++// users and groups not in the delegation aren't paged, so the list is capped and search narrows it+const AVAILABLE_PREVIEW_LIMIT = 20;+const NOT_IN_DELEGATION_SECTION = "not-in-delegation";+const ALL_TYPES = "all";+const ROW_CLASS_NAME = "flex items-center gap-3 py-3";++type TSubjectType = AgentVaultMemberType.User | AgentVaultMemberType.Group;++const TYPE_OPTIONS = [+ { value: AgentVaultMemberType.User as TSubjectType, label: "Users" },+ { value: AgentVaultMemberType.Group as TSubjectType, label: "Groups" }+].map((option) => ({ ...option, icon: MEMBER_KIND[option.value].icon }));++export type TDelegationSubjectRow = TAgentVaultActor & {+ addedAt: string;+ missingAccessBundles: TAgentVaultMissingAccessBundle[];+};++const initialsOf = (value: string) =>+ value+ .split(/[\s@._-]+/)+ .filter(Boolean)+ .slice(0, 2)+ .map((part) => part[0]?.toUpperCase() ?? "")+ .join("") || "?";++const SubjectIdentity = ({+ member,+ badge+}: {+ member: TAgentVaultActor;+ badge?: React.ReactNode;+}) => {+ const name = memberDisplayName(member);+ const { label, icon: Icon } = MEMBER_KIND[member.type];++ return (+ <>+ <div className="flex size-8 shrink-0 items-center justify-center rounded-lg border border-border bg-neutral/10 text-xs font-semibold text-accent">+ {member.type === AgentVaultMemberType.User ? initialsOf(name) : <Icon className="size-4" />}+ <span className="sr-only">{label}</span>+ </div>+ <div className="min-w-0 flex-1">+ <div className="flex min-w-0 items-center gap-2">+ <p className="truncate text-sm font-medium text-foreground">{name}</p>+ {badge}+ </div>+ <p className="truncate text-xs text-muted">{memberSubtitle(member)}</p>+ </div>+ </>+ );+};++const SubjectTypeFilter = ({+ value,+ onChange+}: {+ value: TSubjectType | null;+ onChange: (value: TSubjectType | null) => void;+}) => (+ <DropdownMenu>+ <Tooltip>+ <TooltipTrigger asChild>+ <DropdownMenuTrigger asChild>+ <IconButton+ aria-label="Filter users and groups"+ size="md"+ variant={value ? "av" : "outline"}+ >+ <FilterIcon />+ </IconButton>+ </DropdownMenuTrigger>+ </TooltipTrigger>+ <TooltipContent>Filter users and groups</TooltipContent>+ </Tooltip>+ <DropdownMenuContent align="end" className="w-60">+ <DropdownMenuLabel>Type</DropdownMenuLabel>+ <DropdownMenuRadioGroup+ value={value ?? ALL_TYPES}+ onValueChange={(next) => onChange(next === ALL_TYPES ? null : (next as TSubjectType))}+ >+ <DropdownMenuRadioItem value={ALL_TYPES}>+ <UsersIcon />+ All Types+ </DropdownMenuRadioItem>+ {TYPE_OPTIONS.map((option) => (+ <DropdownMenuRadioItem key={option.value} value={option.value}>+ <option.icon />+ {option.label}+ </DropdownMenuRadioItem>+ ))}+ </DropdownMenuRadioGroup>+ </DropdownMenuContent>+ </DropdownMenu>+);++const matchesSearch = (member: TAgentVaultActor, search: string) => {+ if (!search) return true;+ const term = search.toLowerCase();+ return [memberDisplayName(member), memberSubtitle(member)].some((value) =>+ value.toLowerCase().includes(term)+ );+};++type TPendingChange =+ | { kind: "remove"; subject: TDelegationSubjectRow }+ | { kind: "all-members-on" }+ | { kind: "all-members-off" };++type TIdentity = { id: string; name: string };++const ManageDelegationContent = ({+ identity,+ isOpen+}: {+ identity: TIdentity;+ isOpen: boolean;+}) => {+ const [search, setSearch] = useState("");+ const [debouncedSearch] = useDebounce(search);+ const [typeFilter, setTypeFilter] = useState<TSubjectType | null>(null);+ const [notInDelegationSection, setNotInDelegationSection] = useState("");+ const [pendingChange, setPendingChange] = useState<TPendingChange | null>(null);+ const hasPickedInitialSection = useRef(false);++ const searchParam = debouncedSearch.trim() || undefined;+ const { data, isPending } = useGetAgentVaultDelegation(identity.id, isOpen);+ const delegation = data ?? null;+ const isAllMembers = delegation?.scope === AgentVaultDelegationScope.AllMembers;++ const {+ data: available,+ isPending: isAvailablePending,+ isPlaceholderData: isAvailablePlaceholder,+ isError: isAvailableError,+ isFetching: isAvailableFetching+ } = useListAvailableAgentVaultDelegationSubjects(+ identity.id,+ { actorType: typeFilter ?? undefined, search: searchParam, limit: AVAILABLE_PREVIEW_LIMIT },+ isOpen && !isAllMembers+ );++ const setDelegation = useSetAgentVaultDelegation();+ const deleteDelegation = useDeleteAgentVaultDelegation();+ const addSubjects = useAddAgentVaultDelegationSubjects();+ const removeSubjects = useRemoveAgentVaultDelegationSubjects();+ const isChanging =+ setDelegation.isPending || deleteDelegation.isPending || removeSubjects.isPending;++ const subjects: TDelegationSubjectRow[] = [+ ...(delegation?.groups ?? []).map((group) => ({+ type: AgentVaultMemberType.Group as const,+ ...group+ })),+ ...(delegation?.users ?? []).map((user) => ({+ type: AgentVaultMemberType.User as const,+ ...user+ }))+ ];+ // The delegation is read whole, so search and the type filter narrow it here.+ const shownSubjects = subjects.filter(+ (subject) =>+ (!typeFilter || subject.type === typeFilter) && matchesSearch(subject, searchParam ?? "")+ );++ // The candidate list keeps the previous result while a new filter loads, so rows of the previous type+ // are hidden here, and a list that hides everything reads as loading rather than empty.+ const candidates = (available?.members ?? []).filter(+ (member): member is TAgentVaultProductMember & { type: TSubjectType } =>+ member.type !== AgentVaultMemberType.MachineIdentity &&+ (!typeFilter || member.type === typeFilter)+ );+ 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;++ // 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.+ useEffect(() => {+ if (isPending || hasPickedInitialSection.current) return;+ hasPickedInitialSection.current = true;+ if (!subjects.length) setNotInDelegationSection(NOT_IN_DELEGATION_SECTION);+ }, [isPending, subjects.length]);++ const isFiltered = Boolean(searchParam || typeFilter);+ const isSearchMiss =+ isFiltered &&+ !shownSubjects.length &&+ !isAvailableLoading &&+ !isAvailableError &&+ !candidateCount;++ const handleAdd = async (member: TAgentVaultProductMember & { type: TSubjectType }) => {+ const name = memberDisplayName(member);+ try {+ await addSubjects.mutateAsync({+ machineIdentityId: identity.id,+ ...(member.type === AgentVaultMemberType.User+ ? { userIds: [member.id] }+ : { groupIds: [member.id] })+ });+ createNotification({ text: `"${name}" added to the delegation`, type: "success" });+ } catch {+ // A failed request returns a 4xx that the global request handler surfaces as a toast+ }+ };++ const applyPendingChange = async () => {+ if (!pendingChange) return;+ try {+ if (pendingChange.kind === "all-members-on") {+ await setDelegation.mutateAsync({+ machineIdentityId: identity.id,+ scope: AgentVaultDelegationScope.AllMembers+ });+ createNotification({+ text: `"${identity.name}" now acts on behalf of every Agent Vault member`,+ type: "success"+ });+ } else if (pendingChange.kind === "all-members-off") {+ await deleteDelegation.mutateAsync({ machineIdentityId: identity.id });+ createNotification({+ text: `Delegation for "${identity.name}" removed`,+ type: "success"+ });+ setNotInDelegationSection(NOT_IN_DELEGATION_SECTION);+ } else {+ const { subject } = pendingChange;+ const remaining = await removeSubjects.mutateAsync({+ machineIdentityId: identity.id,+ ...(subject.type === AgentVaultMemberType.User+ ? { userIds: [subject.id] }+ : { groupIds: [subject.id] })+ });+ createNotification({+ text: remaining+ ? `"${memberDisplayName(subject)}" removed from the delegation`+ : `"${memberDisplayName(subject)}" removed, which removes the delegation for "${identity.name}"`,+ type: "success"+ });+ }+ setPendingChange(null);+ } catch {+ // A failed request returns a 4xx that the global request handler surfaces as a toast+ }+ };++ const pendingCopy = () => {+ if (!pendingChange) return { title: "", description: "", action: "" };+ if (pendingChange.kind === "all-members-on") {+ return {+ title: "Act on Behalf of All Members",+ description: `"${identity.name}" can start sessions on behalf of every Agent Vault member, including Agent Vault admins and users added later. ${+ subjects.length ? "This replaces the users and groups listed now. " : ""+ }Anyone who can log in as this machine identity can use their personal values.`,+ action: "Allow All Members"+ };+ }+ if (pendingChange.kind === "all-members-off") {+ return {+ title: "Stop Acting on Behalf of All Members",+ description: `"${identity.name}" can no longer start sessions on behalf of anyone until you add users or groups, and the sessions it started stop working at the next proxy poll.`,+ action: "Stop"+ };+ }+ const { subject } = pendingChange;+ const name = memberDisplayName(subject);+ const whose =+ subject.type === AgentVaultMemberType.Group ? `the members of "${name}"` : `"${name}"`;+ return {+ title: `Remove "${name}" From the Delegation`,+ description: `"${identity.name}" can no longer start sessions on behalf of ${whose}, and the sessions it started for them stop working at the next proxy poll.${+ subjects.length === 1+ ? " This is the last user or group, so the delegation is removed."+ : ""+ }`,+ action: "Remove"+ };+ };+ const copy = pendingCopy();++ const renderCandidates = () => {+ if (isAvailableLoading) {+ return (+ <div className="space-y-2 py-2">+ <Skeleton className="h-14 w-full" />+ <Skeleton className="h-14 w-full" />+ </div>+ );+ }+ if (isAvailableError) {+ return (+ <p className="py-2.5 text-xs text-danger">+ Could not load the users and groups that can be added. Close this panel and open it again+ to retry.+ </p>+ );+ }+ if (!candidates.length) {+ if (isSearchMiss) return null;+ return (+ <p className="py-2.5 text-xs text-muted">+ {isFiltered+ ? "No users or groups outside the delegation match your search and filters."+ : "Every Agent Vault user and group is already in the delegation."}+ </p>+ );+ }+ return (+ <>+ <section className="flex flex-col">+ {candidates.map((member) => (+ <div key={`${member.type}:${member.id}`} className={ROW_CLASS_NAME}>+ <SubjectIdentity+ member={member}+ badge={+ <PendingInvitationBadge+ isPending={+ member.type === AgentVaultMemberType.User && member.isOrgMembershipPending+ }+ />+ }+ />+ <Button+ variant="av"+ size="sm"+ className="shrink-0"+ isDisabled={isAddLocked}+ aria-label={`Add ${memberDisplayName(member)} to the delegation`}+ onClick={() => handleAdd(member)}+ >+ Add+ </Button>+ </div>+ ))}+ </section>+ {candidateCount > candidates.length && (+ <p className="py-2.5 text-xs text-muted">+ Showing the first {AVAILABLE_PREVIEW_LIMIT} of {candidateCount}. Search to find someone+ else.+ </p>+ )}+ </>+ );+ };++ const renderSubjects = () => {+ if (!subjects.length && !isFiltered) {+ return (+ <Empty className="border">+ <EmptyHeader>+ <EmptyMedia variant="icon">+ <UsersIcon />+ </EmptyMedia>+ <EmptyTitle>No users or groups yet</EmptyTitle>+ <EmptyDescription>+ Add users and groups from the Not in Delegation section to let this machine identity+ start sessions on their behalf.+ </EmptyDescription>+ </EmptyHeader>+ </Empty>+ );+ }+ if (!shownSubjects.length) return null;+ return (+ <section className="flex flex-col">+ {shownSubjects.map((subject) => (+ <div key={`${subject.type}:${subject.id}`} className={ROW_CLASS_NAME}>+ <SubjectIdentity member={subject} />+ <MissingAccessBundlesHint+ bundles={subject.missingAccessBundles}+ machineIdentityName={identity.name}+ onBehalfOf={+ subject.type === AgentVaultMemberType.Group+ ? `members of "${memberDisplayName(subject)}"`+ : `"${memberDisplayName(subject)}"`+ }+ />+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ variant="ghost"+ size="sm"+ className="shrink-0"+ aria-label={`In Delegation: ${memberDisplayName(subject)}`}+ >+ In Delegation+ <ChevronDownIcon />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-60">+ <DropdownMenuLabel>+ Added {format(new Date(subject.addedAt), "MMM d, yyyy")}+ </DropdownMenuLabel>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ variant="danger"+ onClick={() => setPendingChange({ kind: "remove", subject })}+ >+ <Trash2Icon />+ Remove+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ ))}+ </section>+ );+ };++ return (+ <>+ <SheetHeader>+ <SheetTitle className="flex items-center gap-2">+ 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">+ <Field orientation="horizontal" className="rounded-md border border-border p-4">+ <FieldContent>+ <FieldTitle>All Agent Vault Members</FieldTitle>+ <FieldDescription>+ Act on behalf of every user in Agent Vault, including admins and users added later.+ </FieldDescription>+ </FieldContent>+ <Toggle+ id="agent-vault-delegation-all-members"+ variant="av"+ checked={isAllMembers}+ disabled={isPending || isChanging}+ onCheckedChange={(checked) =>+ setPendingChange({ kind: checked ? "all-members-on" : "all-members-off" })+ }+ />+ </Field>++ {isPending && (+ <div className="space-y-2">+ <Skeleton className="h-14 w-full" />+ <Skeleton className="h-14 w-full" />+ </div>+ )}++ {!isPending && isAllMembers && (+ <div className="flex items-center gap-2.5 rounded-md border border-border px-4 py-3">+ <UsersRoundIcon className="size-4 shrink-0 text-muted" />+ <p className="min-w-0 flex-1 text-sm text-muted">+ Every Agent Vault member is covered. Turn this off to pick users and groups instead.+ </p>+ {delegation && (+ <MissingAccessBundlesHint+ bundles={delegation.missingAccessBundles}+ machineIdentityName={identity.name}+ onBehalfOf="Agent Vault members"+ />+ )}+ </div>+ )}++ {!isPending && !isAllMembers && (+ <>+ <div className="flex items-center gap-2">+ <InputGroup className="flex-1">+ <InputGroupAddon>+ <SearchIcon />+ </InputGroupAddon>+ <InputGroupInput+ value={search}+ onChange={(e) => {+ setSearch(e.target.value);+ if (e.target.value.trim()) setNotInDelegationSection(NOT_IN_DELEGATION_SECTION);+ }}+ placeholder="Search users and groups..."+ />+ {search && (+ <InputGroupAddon align="inline-end">+ <InputGroupButton aria-label="Clear search" onClick={() => setSearch("")}>+ <XIcon />+ </InputGroupButton>+ </InputGroupAddon>+ )}+ </InputGroup>+ <SubjectTypeFilter value={typeFilter} onChange={setTypeFilter} />+ </div>++ {isSearchMiss && (+ <p className="text-sm text-muted">+ No users or groups match your search and filters.+ </p>+ )}++ {renderSubjects()}++ <Accordion+ type="single"+ collapsible+ variant="ghost"+ value={notInDelegationSection}+ onValueChange={setNotInDelegationSection}+ >+ <AccordionItem value={NOT_IN_DELEGATION_SECTION}>+ <AccordionTrigger>+ <span className="shrink-0">Not in Delegation</span>+ <span className="flex-1">+ <Separator />+ </span>+ </AccordionTrigger>+ <AccordionContent>{renderCandidates()}</AccordionContent>+ </AccordionItem>+ </Accordion>+ </>+ )}+ </div>++ <SheetFooter className="border-t">+ <span className="text-xs text-muted">Changes save automatically</span>+ </SheetFooter>++ <AlertDialog+ open={Boolean(pendingChange)}+ onOpenChange={(open) => {+ if (!open && !isChanging) setPendingChange(null);+ }}+ >+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>{copy.title}</AlertDialogTitle>+ <AlertDialogDescription>{copy.description}</AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel isDisabled={isChanging}>Cancel</AlertDialogCancel>+ <AlertDialogAction+ variant={pendingChange?.kind === "all-members-on" ? "av" : "danger"}+ isPending={isChanging}+ onClick={async (event) => {+ event.preventDefault();+ await applyPendingChange();+ }}+ >+ {copy.action}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </>+ );+};++type Props = {+ machineIdentity: TIdentity | null;+ onOpenChange: (isOpen: boolean) => void;+};++export const ManageDelegationSheet = ({ machineIdentity, onOpenChange }: Props) => {+ // Holds the last identity so the content stays on screen while the sheet animates closed.+ const [shownIdentity, setShownIdentity] = useState(machineIdentity);+ if (+ machineIdentity &&+ (machineIdentity.id !== shownIdentity?.id || machineIdentity.name !== shownIdentity?.name)+ ) {+ setShownIdentity(machineIdentity);+ }++ // Keyed per identity so another identity starts with fresh state rather than this one's filters.+ return (+ <Sheet open={Boolean(machineIdentity)} onOpenChange={onOpenChange}>+ <SheetContent className="gap-y-0 sm:max-w-[640px]">+ {shownIdentity && (+ <ManageDelegationContent+ key={shownIdentity.id}+ identity={shownIdentity}+ isOpen={Boolean(machineIdentity)}+ />+ )}+ </SheetContent>+ </Sheet>+ );+};diff --git a/frontend/src/hooks/api/agentVault/mutations.tsx b/frontend/src/hooks/api/agentVault/mutations.tsxindex bd7421b7d4..89d687f211 100644--- a/frontend/src/hooks/api/agentVault/mutations.tsx+++ b/frontend/src/hooks/api/agentVault/mutations.tsx@@ -27,6 +27,7 @@ import {TAgentVaultSessionLogSettingsState,TAgentVaultVariable,TAgentVaultWrittenMember,+ TChangeAgentVaultDelegationSubjectsDTO,TCompleteAgentVaultOauthAuthorizationDTO,TCreateAgentVaultAccessBundleDTO,TCreateAgentVaultOauthAuthorizationDTO,@@ -45,9 +46,25 @@ import {TUpdateAgentVaultVariableDTO} from "./types";-export const useSetAgentVaultDelegation = () => {+// A save sends the whole list, so the next edit has to start from its result, not from a refetch that+// reads a replica which may not have the write yet. A read already in flight is cancelled first, or+// it could land after this and put the old list back. The candidates are refetched, since they+// depend on who is in the delegation.+const useWriteDelegationResult = () => {const { currentOrg } = useOrganization();const queryClient = useQueryClient();+ return async (machineIdentityId: string, delegation: TAgentVaultDelegationDetail | null) => {+ const queryKey = agentVaultKeys.delegation(currentOrg.id, machineIdentityId);+ await queryClient.cancelQueries({ queryKey, exact: true });+ queryClient.setQueryData(queryKey, delegation);+ await queryClient.invalidateQueries({+ queryKey: agentVaultKeys.availableDelegationSubjects(currentOrg.id, machineIdentityId)+ });+ };+};++export const useSetAgentVaultDelegation = () => {+ const writeResult = useWriteDelegationResult();return useMutation({mutationFn: async ({ machineIdentityId, ...body }: TSetAgentVaultDelegationDTO) => {const { data } = await apiRequest.put<{ delegation: TAgentVaultDelegationDetail }>(@@ -56,20 +73,12 @@ export const useSetAgentVaultDelegation = () => {);return data.delegation;},- // A save sends the whole list, so the next edit has to start from this one, not from a refetch- // that reads a replica which may not have the write yet.- onSuccess: (delegation, { machineIdentityId }) => {- queryClient.setQueryData(- agentVaultKeys.delegation(currentOrg.id, machineIdentityId),- delegation- );- }+ onSuccess: (delegation, { machineIdentityId }) => writeResult(machineIdentityId, delegation)});};export const useDeleteAgentVaultDelegation = () => {- const { currentOrg } = useOrganization();- const queryClient = useQueryClient();+ const writeResult = useWriteDelegationResult();return useMutation({mutationFn: async ({ machineIdentityId }: { machineIdentityId: string }) => {const { data } = await apiRequest.delete<{ delegation: TAgentVaultDelegation }>(@@ -77,9 +86,37 @@ export const useDeleteAgentVaultDelegation = () => {);return data.delegation;},- onSuccess: (_, { machineIdentityId }) => {- queryClient.setQueryData(agentVaultKeys.delegation(currentOrg.id, machineIdentityId), null);- }+ onSuccess: (_, { machineIdentityId }) => writeResult(machineIdentityId, null)+ });+};++// Adds to the delegation without resending who is already in it, so it can't undo another change.+export const useAddAgentVaultDelegationSubjects = () => {+ const writeResult = useWriteDelegationResult();+ return useMutation({+ mutationFn: async ({ machineIdentityId, ...body }: TChangeAgentVaultDelegationSubjectsDTO) => {+ const { data } = await apiRequest.post<{ delegation: TAgentVaultDelegationDetail }>(+ `/api/v1/agent-vault/delegations/${machineIdentityId}/subjects`,+ body+ );+ return data.delegation;+ },+ onSuccess: (delegation, { machineIdentityId }) => writeResult(machineIdentityId, delegation)+ });+};++// null once the delegation names no one, which reads as no delegation.+export const useRemoveAgentVaultDelegationSubjects = () => {+ const writeResult = useWriteDelegationResult();+ return useMutation({+ mutationFn: async ({ machineIdentityId, ...body }: TChangeAgentVaultDelegationSubjectsDTO) => {+ const { data } = await apiRequest.delete<{ delegation: TAgentVaultDelegationDetail | null }>(+ `/api/v1/agent-vault/delegations/${machineIdentityId}/subjects`,+ { data: body }+ );+ return data.delegation;+ },+ onSuccess: (delegation, { machineIdentityId }) => writeResult(machineIdentityId, delegation)});};diff --git a/frontend/src/hooks/api/agentVault/queries.tsx b/frontend/src/hooks/api/agentVault/queries.tsxindex 088fe739c2..acc66b1d51 100644--- a/frontend/src/hooks/api/agentVault/queries.tsx+++ b/frontend/src/hooks/api/agentVault/queries.tsx@@ -130,6 +130,15 @@ export const agentVaultKeys = {delegations: (orgId: string) => [...agentVaultKeys.all(orgId), "delegations"] as const,delegation: (orgId: string, machineIdentityId: string) =>[...agentVaultKeys.delegations(orgId), machineIdentityId] as const,+ // Nested under delegation() so changing the delegation can invalidate the candidates alone: the+ // delegation itself is written from each change's result.+ availableDelegationSubjects: (orgId: string, machineIdentityId: string) =>+ [...agentVaultKeys.delegation(orgId, machineIdentityId), "available"] as const,+ availableDelegationSubjectList: (+ orgId: string,+ machineIdentityId: string,+ params?: TListAgentVaultMembersDTO+ ) => [...agentVaultKeys.availableDelegationSubjects(orgId, machineIdentityId), params] as const,sessionLogSettings: (orgId: string) =>[...agentVaultKeys.all(orgId), "settings", "session-logs"] as const,sessionLogHealth: (orgId: string) =>@@ -240,6 +249,33 @@ export const useListAvailableAgentVaultAccessBundleMembers = (});};+// The Agent Vault users and groups not yet in the machine identity's delegation. Admins only.+export const useListAvailableAgentVaultDelegationSubjects = (+ machineIdentityId: string,+ { limit = AVAILABLE_MEMBER_LIMIT, ...rest }: TListAgentVaultMembersDTO = {},+ enabled = true+) => {+ const { currentOrg } = useOrganization();+ const params = { ...rest, limit };++ return useQuery({+ queryKey: agentVaultKeys.availableDelegationSubjectList(+ currentOrg.id,+ machineIdentityId,+ params+ ),+ queryFn: async () => {+ const { data } = await apiRequest.get<{+ members: TAgentVaultProductMember[];+ totalCount: number;+ }>(`/api/v1/agent-vault/delegations/${machineIdentityId}/subjects/available`, { params });+ return data;+ },+ enabled: enabled && Boolean(machineIdentityId),+ placeholderData: (prev) => prev+ });+};+export const useListAvailableAgentVaultMembers = <T extends AgentVaultMemberType = AgentVaultMemberType>(diff --git a/frontend/src/hooks/api/agentVault/types.ts b/frontend/src/hooks/api/agentVault/types.tsindex 0b3ac30337..a4a62095db 100644--- a/frontend/src/hooks/api/agentVault/types.ts+++ b/frontend/src/hooks/api/agentVault/types.ts@@ -302,6 +302,12 @@ export type TAgentVaultDelegationDetail = Omit<TAgentVaultDelegation, "users" |missingAccessBundles: TAgentVaultMissingAccessBundle[];};+export type TChangeAgentVaultDelegationSubjectsDTO = {+ machineIdentityId: string;+ userIds?: string[];+ groupIds?: string[];+};+export type TSetAgentVaultDelegationDTO = {machineIdentityId: string;scope: AgentVaultDelegationScope;