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
Merge remote-tracking branch 'origin/main' into agent-vault-on-behalf-of
Scott Wilson874c1d079713
diff --cc backend/e2e-test/routes/v1/agent-vault-session-logs.spec.tsindex 802a0e18e8,2c885b3e96..f24f717504--- a/backend/e2e-test/routes/v1/agent-vault-session-logs.spec.ts+++ b/backend/e2e-test/routes/v1/agent-vault-session-logs.spec.ts@@@ -759,6 -760,42 +760,42 @@@ describe("Agent Vault session logs", asexpect(res.statusCode).toBe(401);});+ test("leaves a session whose owner was deleted untouched, so its late-log window stays closed", async () => {+ await configure();+ const bundle = await createAccessBundle(`session-logs-ownerless-${Date.now()}`);+ const member = await createMemberIdentity(`session-logs-ownerless-${Date.now()}`);+ const granted = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/members`, {+ machineIdentityIds: [member.id]+ });+ expect(granted.statusCode).toBe(200);+ const minted = await member.as("POST", "/api/v1/agent-vault/sessions", {+ accessBundles: [bundle.name],+ ttl: "1h"+ });+ expect(minted.statusCode, minted.payload).toBe(200);+ const { id: sessionId } = minted.json().session as { id: string };++ expect((await member.cleanup()).statusCode).toBe(200);+ const before = await testDb("agent_vault_sessions").where({ id: sessionId }).first();+ expect(before.identityId).toBeNull();++ const relabelled = await inject("PATCH", `/api/v1/agent-vault/sessions/${sessionId}`, { label: "afterwards" });+ expect(relabelled.statusCode).toBe(400);+ expect(relabelled.json().message).toBe(- "The user or machine identity that owned this session was deleted, so its label can't be changed."++ "The user or machine identity that owned or started this session was deleted, so its label can't be changed."+ );++ const revoked = await inject("POST", `/api/v1/agent-vault/sessions/${sessionId}/revoke`);+ expect(revoked.statusCode).toBe(200);+ expect(revoked.json().session.status).toBe("revoked");++ // updatedAt is the only record of when the owner went, so neither call may move it.+ const after = await testDb("agent_vault_sessions").where({ id: sessionId }).first();+ expect(after.updatedAt.getTime()).toBe(before.updatedAt.getTime());+ expect(after.revokedAt).toBeNull();+ expect(after.label).toBeNull();+ });+test("still accepts a chunk from a session revoked minutes ago", async () => {await configure();const { session, proxy } = await setup("grace");diff --cc backend/e2e-test/routes/v1/agent-vault.spec.tsindex bdedfe76bc,0bcf0e46d1..4cfd206587--- a/backend/e2e-test/routes/v1/agent-vault.spec.ts+++ b/backend/e2e-test/routes/v1/agent-vault.spec.ts@@@ -8,8 -8,10 +8,11 @@@ import { addUserMembership, createUserimport { AccessScope, ActionProjectType, OrgMembershipRole, ProjectMembershipRole, ProjectType } from "@app/db/schemas";import { seedData1 } from "@app/db/seed-data";import { agentVaultServiceCustomHeaderDALFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-service-custom-header-dal";+ import { agentVaultServiceDALFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-service-dal";import { agentVaultServiceSubstitutionDALFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-service-substitution-dal";+import { agentVaultDelegationDALFactory } from "@app/ee/services/agent-vault-delegation/agent-vault-delegation-dal";+ import { MAX_OAUTH_SCOPES } from "@app/ee/services/agent-vault-oauth/agent-vault-oauth-discovery-fns";+ import { AGENT_VAULT_SERVICE_MOVED_MESSAGE } from "@app/ee/services/agent-vault-oauth/agent-vault-oauth-service";import { agentVaultPersonalValueDALFactory } from "@app/ee/services/agent-vault-personal-value/agent-vault-personal-value-dal";import { agentVaultProxyDALFactory } from "@app/ee/services/agent-vault-proxy/agent-vault-proxy-dal";import {@@@ -3923,801 -4511,6 +4512,803 @@@ describe("Agent Vault V1 Router", asyn});});+ describe("sessions on behalf of users", async () => {+ const sessionsUrl = "/api/v1/agent-vault/sessions";+ const delegationsUrl = "/api/v1/agent-vault/delegations";+ const delegationUrl = (machineIdentityId: string) => `${delegationsUrl}/${machineIdentityId}`;+ const bundleMembersUrl = (accessBundleId: string) => `/api/v1/agent-vault/access-bundles/${accessBundleId}/members`;++ type TMember = Awaited<ReturnType<typeof createMemberIdentity>>;++ // The rows are written directly, so the user can be acted for but can't log in.+ const createAgentVaultUser = async (label: string, projectId: string | null) => {+ const user = await createUser(label);+ await addUserMembership({+ userId: user.userId,+ orgId: seedData1.organization.id,+ role: OrgMembershipRole.Member+ });+ if (projectId) {+ await addUserMembership({+ userId: user.userId,+ orgId: seedData1.organization.id,+ projectId,+ role: ProjectMembershipRole.Member+ });+ }+ return user;+ };++ const grantBundle = async (accessBundleId: string, body: Record<string, string[]>) => {+ expect((await inject("POST", bundleMembersUrl(accessBundleId), body)).statusCode).toBe(200);+ };++ type TMissing = { missingAccessBundles: { id: string; name: string }[] };+ type TDelegationDetail = TMissing & {+ scope: string;+ users: (TMissing & { id: string; addedAt: string })[];+ groups: (TMissing & { id: string; addedAt: string })[];+ };++ const delegate = async (bot: TMember, body: Record<string, unknown>) => {+ const res = await inject("PUT", delegationUrl(bot.id), body);+ expect(res.statusCode).toBe(200);+ return res.json().delegation as TDelegationDetail;+ };++ const mintFor = (bot: TMember, onBehalfOf: Record<string, string>, accessBundle: string, ttl?: string) =>+ bot.as("POST", sessionsUrl, { accessBundles: [accessBundle], onBehalfOf, ...(ttl ? { ttl } : {}) });++ test("only an identity whose delegation covers the user can start a session on their behalf", async () => {+ const projectId = await getProjectId();+ const bundle = await createAccessBundle(`obo-cover-${Date.now()}`);+ const bot = await createMemberIdentity(`obo-cover-bot-${Date.now()}`);+ const alice = await createAgentVaultUser("obo-alice", projectId);+ const bob = await createAgentVaultUser("obo-bob", projectId);+ try {+ await grantBundle(bundle.id, { userIds: [alice.userId, bob.userId], machineIdentityIds: [bot.id] });++ const undelegated = await mintFor(bot, { userId: alice.userId }, bundle.name);+ expect(undelegated.statusCode).toBe(403);+ expect(undelegated.json().message).toContain("isn't allowed to start sessions on behalf of users");++ const asUser = await inject("POST", sessionsUrl, {+ accessBundles: [bundle.name],+ onBehalfOf: { userId: alice.userId }+ });+ expect(asUser.statusCode).toBe(400);+ expect(asUser.json().message).toBe("Only a machine identity can start a session on behalf of a user");++ await delegate(bot, { scope: "selected", userIds: [alice.userId] });++ // Emails are matched the way users are stored, lowercase.+ const minted = await mintFor(bot, { userEmail: alice.username.toUpperCase() }, bundle.name);+ expect(minted.statusCode).toBe(200);+ const { session } = minted.json() as { session: { id: string } };++ const read = await bot.as("GET", `${sessionsUrl}/${session.id}`);+ expect(read.statusCode).toBe(200);+ expect(read.json().session).toMatchObject({+ status: "active",+ actor: expect.objectContaining({ type: "user", id: alice.userId, username: alice.username }),+ actingIdentity: { id: bot.id, name: expect.stringContaining("obo-cover-bot-") }+ });++ // Bob is in Agent Vault but not in the delegation, and a user who doesn't exist reads the same.+ const missingId = crypto.randomUUID();+ const uncovered = await mintFor(bot, { userId: bob.userId }, bundle.name);+ const unknown = await mintFor(bot, { userId: missingId }, bundle.name);+ expect([uncovered.statusCode, unknown.statusCode]).toEqual([403, 403]);+ expect(uncovered.json().message.replace(bob.userId, "<user>")).toBe(+ unknown.json().message.replace(missingId, "<user>")+ );++ expect((await mintFor(bot, { userId: alice.userId, userEmail: alice.username }, bundle.name)).statusCode).toBe(+ 422+ );+ } finally {+ await bot.cleanup();+ await deleteUsers([alice.userId, bob.userId]);+ }+ });++ test("a group in the delegation covers its members while they stay in the group", async () => {+ const projectId = await getProjectId();+ const bundle = await createAccessBundle(`obo-group-${Date.now()}`);+ const bot = await createMemberIdentity(`obo-group-bot-${Date.now()}`);+ const group = await createProjectGroup(projectId, `obo-group-${Date.now()}`, ProjectMembershipRole.Member);+ // In Agent Vault only through the group.+ const carol = await createAgentVaultUser("obo-carol", null);+ await testDb("user_group_membership").insert({ groupId: group.id, userId: carol.userId });+ try {+ await grantBundle(bundle.id, { groupIds: [group.id], machineIdentityIds: [bot.id] });++ const direct = await inject("PUT", delegationUrl(bot.id), { scope: "selected", userIds: [carol.userId] });+ expect(direct.statusCode).toBe(400);+ expect(direct.json().message).toContain("are in Agent Vault through a group. Name the group instead");++ const delegation = await delegate(bot, { scope: "selected", groupIds: [group.id] });+ expect(delegation.groups.map((row) => row.id)).toEqual([group.id]);++ const minted = await mintFor(bot, { userId: carol.userId }, bundle.name);+ expect(minted.statusCode).toBe(200);+ const read = await bot.as("GET", `${sessionsUrl}/${minted.json().session.id as string}`);+ expect(read.json().session.actor).toMatchObject({ type: "user", id: carol.userId });++ await testDb("user_group_membership").where({ groupId: group.id, userId: carol.userId }).delete();+ expect((await mintFor(bot, { userId: carol.userId }, bundle.name)).statusCode).toBe(403);+ } finally {+ await bot.cleanup();+ await deleteUsers([carol.userId]);+ await group.cleanup();+ }+ });++ test("a session on a user's behalf can use only a bundle both the user and the identity can use", async () => {+ const projectId = await getProjectId();+ const shared = await createAccessBundle(`obo-shared-${Date.now()}`);+ const usersOnly = await createAccessBundle(`obo-users-only-${Date.now()}`);+ const botsOnly = await createAccessBundle(`obo-bots-only-${Date.now()}`);+ const bot = await createMemberIdentity(`obo-reach-bot-${Date.now()}`);+ const alice = await createAgentVaultUser("obo-reach-alice", projectId);+ try {+ await grantBundle(shared.id, { userIds: [alice.userId], machineIdentityIds: [bot.id] });+ await grantBundle(usersOnly.id, { userIds: [alice.userId] });+ await grantBundle(botsOnly.id, { machineIdentityIds: [bot.id] });+ await delegate(bot, { scope: "selected", userIds: [alice.userId] });++ expect((await mintFor(bot, { userId: alice.userId }, shared.name)).statusCode).toBe(200);++ // The identity's own bundles are checked before the user is looked up, so a name that doesn't exist and a user+ // who doesn't exist read exactly like a bundle the identity isn't granted.+ const notTheBots = await Promise.all([+ mintFor(bot, { userId: alice.userId }, usersOnly.name),+ mintFor(bot, { userId: crypto.randomUUID() }, usersOnly.name),+ mintFor(bot, { userId: alice.userId }, `obo-no-such-bundle-${Date.now()}`)+ ]);+ notTheBots.forEach((refused) => {+ expect(refused.statusCode).toBe(400);+ expect(refused.json().message).toMatch(+ /^No access bundle named '[^']+' is granted to this machine identity\. A session on behalf of a user can use only bundles granted to both the user and the machine identity, so check the name, or ask an Agent Vault admin to grant the bundle to the machine identity\.$/+ );+ });++ // The refusal names the user the way the request did.+ const [byId, byEmail] = await Promise.all([+ mintFor(bot, { userId: alice.userId }, botsOnly.name),+ mintFor(bot, { userEmail: alice.username }, botsOnly.name)+ ]);+ expect([byId.statusCode, byEmail.statusCode]).toEqual([400, 400]);+ expect(byId.json().message).toBe(+ `No access bundle named '${botsOnly.name}' is granted to '${alice.userId}'. Check the name, or ask an Agent Vault admin to grant it to them.`+ );+ expect(byEmail.json().message).toBe(+ `No access bundle named '${botsOnly.name}' is granted to '${alice.username}'. Check the name, or ask an Agent Vault admin to grant it to them.`+ );+ } finally {+ await bot.cleanup();+ await deleteUsers([alice.userId]);+ }+ });++ test("an identity lists the bundles a session on a user's behalf could use", async () => {+ const projectId = await getProjectId();+ const stamp = String(Date.now());+ const shared = await createAccessBundle(`obo-list-shared-${stamp}`);+ const usersOnly = await createAccessBundle(`obo-list-users-${stamp}`);+ const botsOnly = await createAccessBundle(`obo-list-bots-${stamp}`);+ const needsSetup = await createAccessBundle(`obo-list-setup-${stamp}`);+ const service = await inject("POST", `/api/v1/agent-vault/access-bundles/${needsSetup.id}/services`, {++ type: "http",+ name: "github",+ hostPattern: "api.github.com",+ credential: { type: "bearer", memberProvidedFields: ["credential-value"] }+ });+ expect(service.statusCode).toBe(200);+ const bot = await createMemberIdentity(`obo-list-bot-${stamp}`);+ const alice = await createAgentVaultUser("obo-list-alice", projectId);+ const outsider = await createAgentVaultUser("obo-list-outsider", projectId);+ const bundlesUrl = (query: string) => `/api/v1/agent-vault/access-bundles?limit=100&${query}`;+ type TListed = { name: string; servicesRequiringSetup: { name: string }[] }[];+ const listed = (res: { json: () => { accessBundles: TListed } }) =>+ res+ .json()+ .accessBundles.filter((bundle) => bundle.name.endsWith(stamp))+ .map((bundle) => ({+ name: bundle.name,+ setup: bundle.servicesRequiringSetup.map((pending) => pending.name)+ }));+ try {+ await grantBundle(shared.id, { userIds: [alice.userId], machineIdentityIds: [bot.id] });+ await grantBundle(usersOnly.id, { userIds: [alice.userId] });+ await grantBundle(botsOnly.id, { machineIdentityIds: [bot.id] });+ await grantBundle(needsSetup.id, { machineIdentityIds: [bot.id] });+ await delegate(bot, { scope: "selected", userIds: [alice.userId, seedData1.id] });++ const byId = await bot.as("GET", bundlesUrl(`onBehalfOfUserId=${alice.userId}`));+ expect(byId.statusCode).toBe(200);+ expect(listed(byId)).toEqual([{ name: shared.name, setup: [] }]);+ const byEmail = await bot.as("GET", bundlesUrl(`onBehalfOfUserEmail=${encodeURIComponent(alice.username)}`));+ expect(listed(byEmail)).toEqual(listed(byId));++ // Without onBehalfOf the identity still lists its own bundles.+ const own = await bot.as("GET", bundlesUrl("orderBy=name&orderDirection=asc"));+ expect(listed(own).map((bundle) => bundle.name)).toEqual([botsOnly.name, needsSetup.name, shared.name]);++ // A user the delegation doesn't cover reads exactly like one who doesn't exist.+ const missingId = crypto.randomUUID();+ const uncovered = await bot.as("GET", bundlesUrl(`onBehalfOfUserId=${outsider.userId}`));+ const unknown = await bot.as("GET", bundlesUrl(`onBehalfOfUserId=${missingId}`));+ expect([uncovered.statusCode, unknown.statusCode]).toEqual([403, 403]);+ expect(uncovered.json().message.replace(outsider.userId, "<user>")).toBe(+ unknown.json().message.replace(missingId, "<user>")+ );++ const asUser = await inject("GET", bundlesUrl(`onBehalfOfUserId=${alice.userId}`));+ expect(asUser.statusCode).toBe(400);+ expect(asUser.json().message).toBe("Only a machine identity can start a session on behalf of a user");+ expect(+ (+ await bot.as(+ "GET",+ bundlesUrl(`onBehalfOfUserId=${alice.userId}&onBehalfOfUserEmail=${encodeURIComponent(alice.username)}`)+ )+ ).statusCode+ ).toBe(422);+ const withGranted = await bot.as("GET", bundlesUrl(`onBehalfOfUserId=${alice.userId}&granted=true`));+ expect(withGranted.statusCode).toBe(422);++ // The setup state is the user's: the seeded admin reaches every bundle, so the identity's grants decide the+ // list, and the service asks for a value the admin hasn't saved yet.+ const forAdmin = (requiresSetup: string) =>+ bot.as(+ "GET",+ bundlesUrl(+ `onBehalfOfUserId=${seedData1.id}&requiresSetup=${requiresSetup}&orderBy=name&orderDirection=asc`+ )+ );+ expect(listed(await forAdmin("true"))).toEqual([{ name: needsSetup.name, setup: ["github"] }]);+ const saved = await inject(+ "PATCH",+ `/api/v1/agent-vault/access-bundles/${needsSetup.id}/services/${service.json().service.id as string}/personal-values`,+ { values: [{ field: "credential-value", value: "admin_personal_token" }] }+ );+ expect(saved.statusCode).toBe(200);+ expect(listed(await forAdmin("true"))).toEqual([]);+ expect(listed(await forAdmin("false"))).toEqual([+ { name: botsOnly.name, setup: [] },+ { name: needsSetup.name, setup: [] },+ { name: shared.name, setup: [] }+ ]);+ } finally {+ await bot.cleanup();+ await deleteUsers([alice.userId, outsider.userId]);+ }+ });++ test("an identity granted no bundles learns nothing about a user by listing on their behalf", async () => {+ const projectId = await getProjectId();+ const bot = await createMemberIdentity(`obo-probe-bot-${Date.now()}`);+ const alice = await createAgentVaultUser("obo-probe-alice", projectId);+ const outsider = await createAgentVaultUser("obo-probe-outsider", null);+ const bundle = await createAccessBundle(`obo-probe-${Date.now()}`);+ const listFor = (query: string) => bot.as("GET", `/api/v1/agent-vault/access-bundles?${query}`);+ try {+ await grantBundle(bundle.id, { userIds: [alice.userId] });+ await delegate(bot, { scope: "all-members" });++ // A member of Agent Vault, an org member outside it, and no one at all read the same.+ const replies = await Promise.all([+ listFor(`onBehalfOfUserId=${alice.userId}`),+ listFor(`onBehalfOfUserId=${outsider.userId}`),+ listFor(`onBehalfOfUserId=${crypto.randomUUID()}`),+ listFor(`onBehalfOfUserEmail=${encodeURIComponent(`obo-probe-nobody-${Date.now()}@example.com`)}`)+ ]);+ replies.forEach((reply) => {+ expect(reply.statusCode).toBe(200);+ expect(reply.json()).toMatchObject({ accessBundles: [], totalCount: 0 });+ });+ } finally {+ await bot.cleanup();+ await deleteUsers([alice.userId, outsider.userId]);+ }+ });++ test("all-members covers every Agent Vault member and no one outside Agent Vault", async () => {+ const projectId = await getProjectId();+ const bundle = await createAccessBundle(`obo-all-${Date.now()}`);+ const bot = await createMemberIdentity(`obo-all-bot-${Date.now()}`);+ const alice = await createAgentVaultUser("obo-all-alice", projectId);+ const outsider = await createAgentVaultUser("obo-all-outsider", null);+ try {+ await grantBundle(bundle.id, { userIds: [alice.userId], machineIdentityIds: [bot.id] });+ const delegation = await delegate(bot, { scope: "all-members" });+ expect(delegation).toMatchObject({ scope: "all-members", users: [], groups: [] });++ expect((await mintFor(bot, { userId: alice.userId }, bundle.name)).statusCode).toBe(200);++ const outside = await mintFor(bot, { userId: outsider.userId }, bundle.name);+ expect(outside.statusCode).toBe(400);+ expect(outside.json().message).toContain("doesn't have access to Agent Vault");+ } finally {+ await bot.cleanup();+ await deleteUsers([alice.userId, outsider.userId]);+ }+ });++ test("a session on a user's behalf lasts an hour unless asked", async () => {+ const projectId = await getProjectId();+ const bundle = await createAccessBundle(`obo-ttl-${Date.now()}`);+ const bot = await createMemberIdentity(`obo-ttl-bot-${Date.now()}`);+ const alice = await createAgentVaultUser("obo-ttl-alice", projectId);+ const hoursFromNow = (expiresAt: string) => (new Date(expiresAt).getTime() - Date.now()) / (60 * 60 * 1000);+ try {+ await grantBundle(bundle.id, { userIds: [alice.userId], machineIdentityIds: [bot.id] });+ await delegate(bot, { scope: "selected", userIds: [alice.userId] });++ const byDefault = await mintFor(bot, { userId: alice.userId }, bundle.name);+ expect(byDefault.statusCode).toBe(200);+ expect(hoursFromNow(byDefault.json().session.expiresAt as string)).toBeCloseTo(1, 1);++ // There's no maximum for now, never included.+ const longer = await mintFor(bot, { userId: alice.userId }, bundle.name, "25h");+ expect(longer.statusCode).toBe(200);+ expect(hoursFromNow(longer.json().session.expiresAt as string)).toBeCloseTo(25, 1);+ const unending = await mintFor(bot, { userId: alice.userId }, bundle.name, "never");+ expect(unending.statusCode).toBe(200);+ expect(unending.json().session.expiresAt).toBeNull();++ // A session the identity starts for itself keeps the usual default.+ const own = await bot.as("POST", sessionsUrl, { accessBundles: [bundle.name] });+ expect(own.statusCode).toBe(200);+ expect(hoursFromNow(own.json().session.expiresAt as string)).toBeCloseTo(7 * 24, 0);+ } finally {+ await bot.cleanup();+ await deleteUsers([alice.userId]);+ }+ });++ test("resolve uses the user's personal values, and stops once the identity can no longer act for them", async () => {+ const bundle = await createAccessBundle(`obo-resolve-${Date.now()}`);+ const serviceRes = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {++ type: "http",+ name: "github",+ hostPattern: "api.github.com",+ credential: { type: "bearer", memberProvidedFields: ["credential-value"] }+ });+ expect(serviceRes.statusCode).toBe(200);+ const serviceId = serviceRes.json().service.id as string;++ // The seeded admin is the user acted for here, since it is the one user that can save its own values.+ const setValue = await inject(+ "PATCH",+ `/api/v1/agent-vault/access-bundles/${bundle.id}/services/${serviceId}/personal-values`,+ { values: [{ field: "credential-value", value: "admin_personal_token" }] }+ );+ expect(setValue.statusCode).toBe(200);++ const proxy = await inject("POST", "/api/v1/agent-vault/proxies", { name: `obo-resolve-${Date.now()}` });+ expect(proxy.statusCode).toBe(200);+ 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-resolve-bot-${Date.now()}`);+ const serviceNames = (res: Awaited<ReturnType<typeof resolve>>) =>+ (res.json().services as { name: string }[]).map((service) => service.name);+ try {+ await grantBundle(bundle.id, { machineIdentityIds: [bot.id] });+ await delegate(bot, { scope: "selected", userIds: [seedData1.id] });+ const minted = await mintFor(bot, { userId: seedData1.id }, bundle.name);+ expect(minted.statusCode).toBe(200);+ const token = minted.json().session.token as string;++ const resolved = await resolve(token);+ expect(resolved.statusCode).toBe(200);+ expect(+ (resolved.json().services as { name: string; credential: Record<string, string> }[]).find(+ (service) => service.name === "github"+ )?.credential+ ).toMatchObject({ type: "bearer", value: "admin_personal_token" });++ // Taking the delegation away stops the session, and giving it back restores it, as with a grant.+ expect((await inject("DELETE", delegationUrl(bot.id))).statusCode).toBe(200);+ expect((await resolve(token)).statusCode).toBe(401);+ await delegate(bot, { scope: "selected", userIds: [seedData1.id] });+ expect((await resolve(token)).statusCode).toBe(200);++ // The admin user still reaches the bundle, but the identity losing its grant takes the bundle's services away,+ // the way losing a user's grant does, and granting it again brings them back.+ expect((await inject("DELETE", bundleMembersUrl(bundle.id), { machineIdentityIds: [bot.id] })).statusCode).toBe(+ 200+ );+ const withoutGrant = await resolve(token);+ expect(withoutGrant.statusCode).toBe(200);+ expect(serviceNames(withoutGrant)).not.toContain("github");+ await grantBundle(bundle.id, { machineIdentityIds: [bot.id] });+ expect(serviceNames(await resolve(token))).toContain("github");++ // Removing the identity from Agent Vault deletes its delegation, so adding it back restores nothing.+ expect(+ (await inject("DELETE", "/api/v1/agent-vault/members", { machineIdentityIds: [bot.id] })).statusCode+ ).toBe(200);+ expect((await inject("GET", delegationUrl(bot.id))).statusCode).toBe(404);+ expect((await resolve(token)).statusCode).toBe(401);+ } finally {+ await bot.cleanup();+ }+ });++ test("the acting identity can see and revoke what it started, and deleting it ends those sessions", async () => {+ const projectId = await getProjectId();+ const bundle = await createAccessBundle(`obo-owner-${Date.now()}`);+ const botName = `obo-owner-bot-${Date.now()}`;+ const bot = await createMemberIdentity(botName);+ const alice = await createAgentVaultUser("obo-owner-alice", projectId);+ try {+ await grantBundle(bundle.id, { userIds: [alice.userId], machineIdentityIds: [bot.id] });+ await delegate(bot, { scope: "selected", userIds: [alice.userId] });++ const first = (await mintFor(bot, { userId: alice.userId }, bundle.name)).json().session.id as string;+ const second = (await mintFor(bot, { userId: alice.userId }, bundle.name)).json().session.id as string;++ const mine = await bot.as("GET", `${sessionsUrl}?limit=100`);+ expect(mine.statusCode).toBe(200);+ expect((mine.json().sessions as { id: string }[]).map((row) => row.id)).toEqual(+ expect.arrayContaining([first, second])+ );++ const revoked = await bot.as("POST", `${sessionsUrl}/${first}/revoke`);+ expect(revoked.statusCode).toBe(200);+ expect(revoked.json().session.status).toBe("revoked");++ const found = await inject("GET", `${sessionsUrl}?scope=all&limit=100&search=${botName}`);+ expect((found.json().sessions as { id: string }[]).map((row) => row.id)).toEqual(+ expect.arrayContaining([first, second])+ );++ await bot.cleanup();+ const orphaned = await inject("GET", `${sessionsUrl}/${second}`);+ expect(orphaned.statusCode).toBe(200);+ expect(orphaned.json().session).toMatchObject({+ status: "revoked",+ actor: expect.objectContaining({ id: alice.userId }),+ actingIdentity: { id: null, name: botName }+ });+ } finally {+ await bot.cleanup();+ await deleteUsers([alice.userId]);+ }+ });++ // Nothing stops an identity being named "", and the name is what marks a session as started on someone's behalf.+ test("a session started by an identity named '' is checked like any other on a user's behalf", async () => {+ const bundle = await createAccessBundle(`obo-unnamed-${Date.now()}`);+ const proxy = await inject("POST", "/api/v1/agent-vault/proxies", { name: `obo-unnamed-${Date.now()}` });+ expect(proxy.statusCode).toBe(200);+ 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("");+ try {+ await grantBundle(bundle.id, { machineIdentityIds: [bot.id] });+ await delegate(bot, { scope: "selected", userIds: [seedData1.id] });+ const minted = await mintFor(bot, { userId: seedData1.id }, bundle.name);+ expect(minted.statusCode).toBe(200);+ const { id, token } = minted.json().session as { id: string; token: string };++ expect((await inject("GET", `${sessionsUrl}/${id}`)).json().session.actingIdentity).toEqual({+ id: bot.id,+ name: ""+ });+ expect((await resolve(token)).statusCode).toBe(200);++ // The seeded admin still reaches the bundle, so only the delegation check can stop the session.+ expect((await inject("DELETE", delegationUrl(bot.id))).statusCode).toBe(200);+ expect((await resolve(token)).statusCode).toBe(401);++ await bot.cleanup();+ expect((await inject("GET", `${sessionsUrl}/${id}`)).json().session).toMatchObject({+ status: "revoked",+ actingIdentity: { id: null, name: "" }+ });+ } finally {+ await bot.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()}`);+ const other = await createMemberIdentity(`obo-api-other-${Date.now()}`);+ const outsideIdentity = await createOrgIdentity(`obo-api-outside-${Date.now()}`);+ const alice = await createAgentVaultUser("obo-api-alice", projectId);+ const outsider = await createAgentVaultUser("obo-api-outsider", null);+ try {+ expect((await inject("PUT", delegationUrl(bot.id), { scope: "selected" })).statusCode).toBe(422);+ expect(+ (await inject("PUT", delegationUrl(bot.id), { scope: "all-members", userIds: [alice.userId] })).statusCode+ ).toBe(422);++ const notMember = await inject("PUT", delegationUrl(outsideIdentity.id), { scope: "all-members" });+ expect(notMember.statusCode).toBe(404);++ const stranger = await inject("PUT", delegationUrl(bot.id), { scope: "selected", userIds: [outsider.userId] });+ expect(stranger.statusCode).toBe(400);+ expect(stranger.json().message).toContain("are not members of Agent Vault");++ const set = await delegate(bot, { scope: "selected", userIds: [alice.userId] });+ expect(set).toMatchObject({ scope: "selected", users: [expect.objectContaining({ id: alice.userId })] });++ // A save keeps the rows that stay, so each one's addedAt still says when it was added.+ const group = await createProjectGroup(projectId, `obo-api-group-${Date.now()}`, ProjectMembershipRole.Member);+ try {+ const widened = await delegate(bot, { scope: "selected", userIds: [alice.userId], groupIds: [group.id] });+ expect(widened.users).toEqual([expect.objectContaining({ id: alice.userId, addedAt: set.users[0].addedAt })]);+ expect(widened.groups).toEqual([expect.objectContaining({ id: group.id })]);+ } finally {+ await group.cleanup();+ }++ expect((await bot.as("GET", delegationUrl(bot.id))).statusCode).toBe(200);+ // Each refusal is a CASL denial, which is what the audit log records as a permission denial.+ const refused = await Promise.all([+ other.as("GET", delegationUrl(bot.id)),+ other.as("PUT", delegationUrl(other.id), { scope: "all-members" }),+ other.as("DELETE", delegationUrl(bot.id)),+ bot.as("GET", delegationsUrl)+ ]);+ refused.forEach((res) => {+ expect(res.statusCode).toBe(403);+ expect(res.json().error).toBe("PermissionDenied");+ });++ const listed = await inject("GET", `${delegationsUrl}?machineIdentityIds=${bot.id},${other.id}`);+ expect(listed.statusCode).toBe(200);+ expect(listed.json()).toMatchObject({+ totalCount: 1,+ delegations: [expect.objectContaining({ machineIdentity: expect.objectContaining({ id: bot.id }) })]+ });++ const removed = await inject("DELETE", delegationUrl(bot.id));+ expect(removed.statusCode).toBe(200);+ expect(removed.json().delegation.machineIdentity.id).toBe(bot.id);+ expect((await inject("DELETE", delegationUrl(bot.id))).statusCode).toBe(404);+ expect((await inject("GET", delegationUrl(bot.id))).statusCode).toBe(404);+ } finally {+ await bot.cleanup();+ await other.cleanup();+ await deleteOrgIdentity(outsideIdentity.id);+ await deleteUsers([alice.userId, outsider.userId]);+ }+ });++ test("removing a user or group from Agent Vault takes them out of every delegation", async () => {+ const projectId = await getProjectId();+ const membersUrl = "/api/v1/agent-vault/members";+ const bot = await createMemberIdentity(`obo-leave-bot-${Date.now()}`);+ const aliceOnlyBot = await createMemberIdentity(`obo-leave-alice-bot-${Date.now()}`);+ const everyoneBot = await createMemberIdentity(`obo-leave-everyone-bot-${Date.now()}`);+ const alice = await createAgentVaultUser("obo-leave-alice", projectId);+ const bob = await createAgentVaultUser("obo-leave-bob", projectId);+ const group = await createProjectGroup(projectId, `obo-leave-group-${Date.now()}`, ProjectMembershipRole.Member);+ const namedBy = async (identity: TMember) => {+ const res = await inject("GET", delegationUrl(identity.id));+ if (res.statusCode === 404) return null;+ const delegation = res.json().delegation as TDelegationDetail;+ return { users: delegation.users.map((row) => row.id), groups: delegation.groups.map((row) => row.id) };+ };+ try {+ await delegate(bot, { scope: "selected", userIds: [alice.userId, bob.userId], groupIds: [group.id] });+ await delegate(aliceOnlyBot, { scope: "selected", userIds: [alice.userId] });+ await delegate(everyoneBot, { scope: "all-members" });++ // A selected delegation left naming no one goes, since it would act for no one.+ expect((await inject("DELETE", membersUrl, { userIds: [alice.userId] })).statusCode).toBe(200);+ expect(await namedBy(bot)).toEqual({ users: [bob.userId], groups: [group.id] });+ expect(await namedBy(aliceOnlyBot)).toBeNull();++ expect((await inject("DELETE", membersUrl, { groupIds: [group.id] })).statusCode).toBe(200);+ expect(await namedBy(bot)).toEqual({ users: [bob.userId], groups: [] });++ // Adding Alice back to Agent Vault doesn't add her back to any delegation.+ const readded = await inject("POST", membersUrl, {+ userIds: [alice.userId],+ role: ProjectMembershipRole.Member+ });+ expect(readded.statusCode).toBe(200);+ expect(await namedBy(bot)).toEqual({ users: [bob.userId], groups: [] });+ expect(await namedBy(aliceOnlyBot)).toBeNull();+ expect(await namedBy(everyoneBot)).toEqual({ users: [], groups: [] });+ } finally {+ await bot.cleanup();+ await aliceOnlyBot.cleanup();+ await everyoneBot.cleanup();+ await deleteUsers([alice.userId, bob.userId]);+ await group.cleanup();+ }+ });++ test("a save checks only the users and groups it adds", async () => {+ const projectId = await getProjectId();+ const bot = await createMemberIdentity(`obo-departed-bot-${Date.now()}`);+ const alice = await createAgentVaultUser("obo-departed-alice", projectId);+ const carol = await createAgentVaultUser("obo-departed-carol", projectId);+ const dave = await createAgentVaultUser("obo-departed-dave", projectId);+ const userIdsOf = (delegation: TDelegationDetail) => delegation.users.map((row) => row.id).sort();+ try {+ await delegate(bot, { scope: "selected", userIds: [alice.userId, carol.userId] });+ // Leaving the organization deletes the Agent Vault membership without Agent Vault's own removal.+ await testDb("memberships")+ .where({ scope: AccessScope.Project, scopeProjectId: projectId, actorUserId: carol.userId })+ .delete();++ const kept = await delegate(bot, { scope: "selected", userIds: [alice.userId, carol.userId, dave.userId] });+ expect(userIdsOf(kept)).toEqual([alice.userId, carol.userId, dave.userId].sort());+ const removed = await delegate(bot, { scope: "selected", userIds: [alice.userId, dave.userId] });+ expect(userIdsOf(removed)).toEqual([alice.userId, dave.userId].sort());++ const added = await inject("PUT", delegationUrl(bot.id), {+ scope: "selected",+ userIds: [alice.userId, carol.userId]+ });+ expect(added.statusCode).toBe(400);+ expect(added.json().message).toBe(+ `User(s) '${carol.userId}' are not members of Agent Vault. Add them under Access Control first.`+ );+ } finally {+ await bot.cleanup();+ await deleteUsers([alice.userId, carol.userId, dave.userId]);+ }+ });++ test("a save waits for a removal from Agent Vault in flight, and then refuses what it removed", async () => {+ const projectId = await getProjectId();+ const bot = await createMemberIdentity(`obo-race-bot-${Date.now()}`);+ const alice = await createAgentVaultUser("obo-race-alice", projectId);+ // Stands in for a removal: its transaction deletes the membership, and commits once the rest of its cleanup is done.+ const saveDuringRemoval = async (+ actor: { actorIdentityId: string } | { actorUserId: string },+ save: () => ReturnType<typeof inject>+ ) => {+ const trx = await testDb.transaction();+ try {+ const { rows } = await trx.raw("select pg_backend_pid() as pid");+ await trx("memberships")+ .where({ scope: AccessScope.Project, scopeProjectId: projectId, ...actor })+ .delete();++ const pending = save();+ await waitUntilBlockedBy(rows[0].pid);+ await trx.commit();+ return await pending;+ } catch (err) {+ if (!trx.isCompleted()) await trx.rollback();+ throw err;+ }+ };+ try {+ const forAlice = await saveDuringRemoval({ actorUserId: alice.userId }, () =>+ inject("PUT", delegationUrl(bot.id), { scope: "selected", userIds: [alice.userId] })+ );+ expect(forAlice.statusCode).toBe(400);+ expect(forAlice.json().message).toContain("are not members of Agent Vault");++ const ofBot = await saveDuringRemoval({ actorIdentityId: bot.id }, () =>+ inject("PUT", delegationUrl(bot.id), { scope: "all-members" })+ );+ expect(ofBot.statusCode).toBe(404);+ expect((await inject("GET", delegationUrl(bot.id))).statusCode).toBe(404);+ } finally {+ await bot.cleanup();+ await deleteUsers([alice.userId]);+ }+ });++ test("a delegation shows the bundles each user and group can use that the identity can't", async () => {+ const projectId = await getProjectId();+ const stamp = Date.now();+ const shared = await createAccessBundle(`obo-gap-shared-${stamp}`);+ const alicesOnly = await createAccessBundle(`obo-gap-alice-${stamp}`);+ const groupsOnly = await createAccessBundle(`obo-gap-group-${stamp}`);+ const bot = await createMemberIdentity(`obo-gap-bot-${stamp}`);+ const alice = await createAgentVaultUser("obo-gap-alice", projectId);+ const group = await createProjectGroup(projectId, `obo-gap-group-${stamp}`, ProjectMembershipRole.Member);+ const admins = await createProjectGroup(projectId, `obo-gap-admins-${stamp}`, ProjectMembershipRole.Admin);+ const names = (row: TMissing) => row.missingAccessBundles.map((bundle) => bundle.name);+ // The missing bundles were never granted to the identity, so its own read leaves every list empty.+ const expectOwnReadWithoutMissing = async () => {+ const res = await bot.as("GET", delegationUrl(bot.id));+ expect(res.statusCode).toBe(200);+ const own = res.json().delegation as TDelegationDetail;+ expect([own, ...own.users, ...own.groups].flatMap((row) => names(row))).toEqual([]);+ return own;+ };+ const read = async () => {+ const res = await inject("GET", delegationUrl(bot.id));+ expect(res.statusCode).toBe(200);+ const delegation = res.json().delegation as TDelegationDetail;+ return {+ delegation,+ user: (id: string) => delegation.users.find((row) => row.id === id)!,+ group: (id: string) => delegation.groups.find((row) => row.id === id)!+ };+ };+ try {+ await grantBundle(shared.id, { userIds: [alice.userId], machineIdentityIds: [bot.id] });+ await grantBundle(alicesOnly.id, { userIds: [alice.userId] });+ await grantBundle(groupsOnly.id, { groupIds: [group.id] });++ const set = await delegate(bot, {+ scope: "selected",+ userIds: [alice.userId, seedData1.id],+ groupIds: [group.id, admins.id]+ });+ expect(names(set.users.find((row) => row.id === alice.userId)!)).toEqual([alicesOnly.name]);++ const before = await read();+ expect(names(before.user(alice.userId))).toEqual([alicesOnly.name]);+ expect(names(before.group(group.id))).toEqual([groupsOnly.name]);+ // An admin, directly or through a group, can use every bundle, so it lacks every bundle the identity can't use.+ [names(before.user(seedData1.id)), names(before.group(admins.id)), names(before.delegation)].forEach((row) => {+ expect(row).toEqual(expect.arrayContaining([alicesOnly.name, groupsOnly.name]));+ expect(row).not.toContain(shared.name);+ });+ const own = await expectOwnReadWithoutMissing();+ expect(own.users.map((row) => row.id)).toEqual(expect.arrayContaining([alice.userId, seedData1.id]));+ expect(own.groups.map((row) => row.id)).toEqual(expect.arrayContaining([group.id, admins.id]));++ await grantBundle(alicesOnly.id, { machineIdentityIds: [bot.id] });+ const after = await read();+ expect(names(after.user(alice.userId))).toEqual([]);+ expect(names(after.delegation)).not.toContain(alicesOnly.name);++ // All-members covers the admins too, so it lacks every bundle the identity can't use.+ const allMembers = await delegate(bot, { scope: "all-members" });+ expect(names(allMembers)).toContain(groupsOnly.name);+ expect(names(allMembers)).not.toContain(shared.name);+ expect(names(allMembers)).not.toContain(alicesOnly.name);+ await expectOwnReadWithoutMissing();++ // An admin identity can use every bundle, so nothing is missing. It's promoted before anything reads its+ // permission, since a role change reaches the permission cache only after its marker expires.+ const adminBot = await createMemberIdentity(`obo-gap-admin-bot-${stamp}`);+ try {+ expect(+ (await inject("PATCH", "/api/v1/agent-vault/members", { machineIdentityIds: [adminBot.id], role: "admin" }))+ .statusCode+ ).toBe(200);+ const adminSet = await delegate(adminBot, {+ scope: "selected",+ userIds: [alice.userId, seedData1.id],+ groupIds: [group.id, admins.id]+ });+ expect([adminSet, ...adminSet.users, ...adminSet.groups].flatMap((row) => names(row))).toEqual([]);+ } finally {+ await adminBot.cleanup();+ }++ // The list stays lean: working the gaps out reads every covered user's access.+ const listed = await inject("GET", `${delegationsUrl}?machineIdentityIds=${bot.id}`);+ expect(listed.json().delegations[0]).not.toHaveProperty("missingAccessBundles");+ } finally {+ await bot.cleanup();+ await deleteUsers([alice.userId]);+ await group.cleanup();+ await admins.cleanup();+ }+ });+ });+describe("session resolve", async () => {const buildResolver = (overrides: Partial<diff --cc backend/src/@types/fastify.d.tsindex 248d715230,b671cbbb21..777eac7af9--- a/backend/src/@types/fastify.d.ts+++ b/backend/src/@types/fastify.d.ts@@@ -7,8 -7,8 +7,9 @@@ import { TAccessApprovalPolicyServiceFaimport { TAccessApprovalRequestServiceFactory } from "@app/ee/services/access-approval-request/access-approval-request-types";import { TAgentProxyCaServiceFactory } from "@app/ee/services/agent-proxy-ca/agent-proxy-ca-service";import { TAgentVaultAccessBundleServiceFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service";+import { TAgentVaultDelegationServiceFactory } from "@app/ee/services/agent-vault-delegation/agent-vault-delegation-service";import { TAgentVaultMembershipServiceFactory } from "@app/ee/services/agent-vault-member/agent-vault-membership-service";+ import { TAgentVaultOauthServiceFactory } from "@app/ee/services/agent-vault-oauth/agent-vault-oauth-service";import { TAgentVaultPersonalValueServiceFactory } from "@app/ee/services/agent-vault-personal-value/agent-vault-personal-value-service";import { TAgentVaultProjectResolverFactory } from "@app/ee/services/agent-vault-project/agent-vault-project-resolver";import { TAgentVaultProxyServiceFactory } from "@app/ee/services/agent-vault-proxy/agent-vault-proxy-service";diff --cc backend/src/db/schemas/agent-vault-sessions.tsindex c7ef0ff01f,fafabf1dcd..8c52d62eaf--- a/backend/src/db/schemas/agent-vault-sessions.ts+++ b/backend/src/db/schemas/agent-vault-sessions.ts@@@ -23,8 -23,7 +23,9 @@@ export const AgentVaultSessionsSchemaupdatedAt: z.date(),encryptedSessionLogKey: zodBuffer.nullable().optional(),actorType: z.string().nullable().optional(),+ actingIdentityId: z.string().uuid().nullable().optional(),- actingIdentityName: z.string().nullable().optional()++ actingIdentityName: z.string().nullable().optional(),+ label: z.string().nullable().optional()});export type TAgentVaultSessions = z.infer<typeof AgentVaultSessionsSchema>;diff --cc backend/src/ee/routes/v1/agent-vault-routers/agent-vault-session-router.tsindex e42d5c6f7a,d6f1bb342f..feb3e4750e--- a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-session-router.ts+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-session-router.ts@@@ -5,8 -5,14 +5,13 @@@ importAGENT_VAULT_NO_CONTROL_CHARS_RE} from "@app/ee/services/agent-vault/agent-vault-credential-schemas";import { AgentVaultSessionScope, AgentVaultSessionStatus } from "@app/ee/services/agent-vault/agent-vault-enums";+ import {+ agentVaultSessionLabelSchema,+ agentVaultSessionLabelUpdateSchema,+ describeSessionForAudit+ } from "@app/ee/services/agent-vault-session/agent-vault-session-fns";import {AGENT_VAULT_MAX_SESSION_BUNDLES,- AGENT_VAULT_SESSION_DEFAULT_TTL,AGENT_VAULT_SESSION_MAX_TTL_MS,AGENT_VAULT_SESSION_TTL_NEVER} from "@app/ee/services/agent-vault-session/agent-vault-session-service";@@@ -33,14 -39,8 +38,15 @@@ const SessionAccessBundleSchema = z.objconst SessionSchema = z.object({id: z.string().uuid().describe(AGENT_VAULT.SESSION.sessionId),+ label: z.string().nullable().describe(AGENT_VAULT.SESSION.label),actor: AgentVaultSessionActorSchema,+ actingIdentity: z+ .object({+ id: z.string().uuid().nullable().describe(AGENT_VAULT.SESSION.actingIdentityId),+ name: z.string().describe(AGENT_VAULT.SESSION.actingIdentityName)+ })+ .nullable()+ .describe(AGENT_VAULT.SESSION.actingIdentity),status: z.nativeEnum(AgentVaultSessionStatus),expiresAt: z.date().nullable().describe(AGENT_VAULT.SESSION.expiresAt),revokedAt: z.date().nullable(),@@@ -171,28 -168,7 +177,29 @@@ export const registerAgentVaultSessionR}}).describe(AGENT_VAULT.SESSION.ttl),+ onBehalfOf: z+ .object({+ userId: z.string().uuid().optional().describe(AGENT_VAULT.SESSION.onBehalfOfUserId),+ userEmail: z+ .string()+ .trim()+ .toLowerCase()+ .email()+ .max(255)+ .optional()+ .describe(AGENT_VAULT.SESSION.onBehalfOfUserEmail)+ })+ .refine((val) => Boolean(val.userId) !== Boolean(val.userEmail), {+ message: "Name the user by userId or by userEmail, not both"+ })+ .optional()+ .describe(+ JSON.stringify({+ description: AGENT_VAULT.SESSION.onBehalfOf,+ example: { userEmail: "[email protected]" }+ })- )++ ),+ label: agentVaultSessionLabelSchema.describe(AGENT_VAULT.SESSION.label)}),response: {200: z.object({@@@ -235,14 -212,10 +243,15 @@@type: EventType.AGENT_VAULT_SESSION_MINT,metadata: {sessionId: session.id,+ label: session.label,accessBundleId: session.accessBundles[0].id,accessBundleName: session.accessBundles[0].name,- expiresAt: session.expiresAt?.toISOString() ?? null+ expiresAt: session.expiresAt?.toISOString() ?? null,+ ...(onBehalfOf && {+ onBehalfOfUserId: onBehalfOf.userId,+ onBehalfOfUserName: onBehalfOf.username,+ ...(onBehalfOf.email && { onBehalfOfUserEmail: onBehalfOf.email })+ })}}});diff --cc backend/src/ee/routes/v1/agent-vault-routers/index.tsindex 346dbb1c7d,114bdc527d..4c7daaa7ed--- a/backend/src/ee/routes/v1/agent-vault-routers/index.ts+++ b/backend/src/ee/routes/v1/agent-vault-routers/index.ts@@@ -1,7 -1,7 +1,8 @@@import { registerAgentVaultAccessBundleRouter } from "./agent-vault-access-bundle-router";import { registerAgentVaultAppConnectionRouter } from "./agent-vault-app-connection-router";+import { registerAgentVaultDelegationRouter } from "./agent-vault-delegation-router";import { registerAgentVaultMembershipRouter } from "./agent-vault-membership-router";+ import { registerAgentVaultOauthRouter } from "./agent-vault-oauth-router";import { registerAgentVaultProjectRouter } from "./agent-vault-project-router";import { registerAgentVaultProxyAgentRouter } from "./agent-vault-proxy-agent-router";import { registerAgentVaultProxyRouter } from "./agent-vault-proxy-router";@@@ -25,7 -25,7 +26,8 @@@ export const registerAgentVaultRoutersawait server.register(registerAgentVaultAppConnectionRouter, { prefix: "/app-connections/aws" });await server.register(registerAgentVaultProxyRouter, { prefix: "/proxies" });await server.register(registerAgentVaultMembershipRouter, { prefix: "/members" });+ await server.register(registerAgentVaultDelegationRouter, { prefix: "/delegations" });+ await server.register(registerAgentVaultOauthRouter, { prefix: "/oauth" });// Separate prefix so the preValidation project hook still matches while these routes authenticate as the proxy.await server.register(registerAgentVaultProxyAgentRouter, { prefix: "/proxy" });};diff --cc backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service.tsindex 9418b42b9d,4b625dfe0d..54be7a4934--- a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service.ts+++ b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service.ts@@@ -46,23 -48,31 +48,40 @@@ importTAgentVaultMemberProvidedField} from "../agent-vault/agent-vault-enums";import { ownerOrNullOf } from "../agent-vault/agent-vault-owner-fns";-import { getAgentVaultGrantedReachability, getAgentVaultReachability } from "../agent-vault/agent-vault-permission";+import {+ getAgentVaultGrantedReachability,+ getAgentVaultReachability,+ intersectAccessBundleIds+} from "../agent-vault/agent-vault-permission";+ import {+ assertCredentialTypeSupported,+ assertServiceFieldsSupported,+ buildServiceConfig,+ dropReadBackServiceFields,+ getAgentVaultServiceType,+ getServiceServerUrl,+ resolveServiceHostPattern,+ TAgentVaultServiceConfig+ } from "../agent-vault/agent-vault-service-type-fns";import {findStoredVariableIds,findVariableKeys,toStoredVariableReferences,toVariableReference} from "../agent-vault/agent-vault-variable-fns";+import {+ findCallerDelegation,+ resolveOnBehalfOfUser,+ TOnBehalfOfDeps+} from "../agent-vault-delegation/agent-vault-on-behalf-of-fns";import { TAgentVaultMemberDALFactory } from "../agent-vault-member/agent-vault-member-dal";+ import {+ checkOauthClaimUnderLock,+ checkOauthServerUnderLock,+ OAUTH_SERVER_URL_NEEDS_AUTHORIZATION_MESSAGE,+ TAgentVaultOauthServiceFactory+ } from "../agent-vault-oauth/agent-vault-oauth-service";+ import { AGENT_VAULT_OAUTH_HEADER_NAME, TAgentVaultOauthConfig } from "../agent-vault-oauth/agent-vault-oauth-types";import { TAgentVaultPersonalValueDALFactory } from "../agent-vault-personal-value/agent-vault-personal-value-dal";import {clearPersonalValuesAfterRevoke,@@@ -132,9 -142,10 +151,13 @@@ type TAgentVaultAccessBundleServiceFactagentVaultMemberDAL: Pick<TAgentVaultMemberDALFactory, "findProductMembers">;userGroupMembershipDAL: Pick<TUserGroupMembershipDALFactory, "find">;identityGroupMembershipDAL: Pick<TIdentityGroupMembershipDALFactory, "find">;+ agentVaultDelegationDAL: TOnBehalfOfDeps["agentVaultDelegationDAL"];+ orgDAL: TOnBehalfOfDeps["orgDAL"];+ userDAL: TOnBehalfOfDeps["userDAL"];+ agentVaultOauthService: Pick<+ TAgentVaultOauthServiceFactory,+ "claimAuthorization" | "buildCredentialFromAuthorization"+ >;} & TAgentVaultActorNameDALs;export type TAgentVaultAccessBundleServiceFactory = ReturnType<typeof agentVaultAccessBundleServiceFactory>;@@@ -165,11 -176,10 +188,12 @@@ export const agentVaultAccessBundleServagentVaultMemberDAL,userGroupMembershipDAL,identityGroupMembershipDAL,+ agentVaultOauthService,userDAL,groupDAL,- identityDAL+ identityDAL,+ agentVaultDelegationDAL,+ orgDAL} = deps;const bundleScope = (projectId: string, accessBundleId: string) => ({diff --cc backend/src/ee/services/agent-vault-member/agent-vault-membership-service.tsindex b252ac2b0b,8d244befe6..8a3628a25c--- a/backend/src/ee/services/agent-vault-member/agent-vault-membership-service.ts+++ b/backend/src/ee/services/agent-vault-member/agent-vault-membership-service.ts@@@ -51,10 -51,9 +52,10 @@@ type TAgentVaultMembershipServiceFactorprojectAccessRequestDAL: Pick<TProjectAccessRequestDALFactory, "delete">;userDAL: Pick<TUserDALFactory, "find">;userAliasDAL: Pick<TUserAliasDALFactory, "findBySsoExternalIds">;- orgDAL: Pick<TOrgDALFactory, "findById">;+ orgDAL: Pick<TOrgDALFactory, "findById" | "findActorsWithActiveOrgAccess" | "lockActorsForOrgAccess">;permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;usageMeteringService: Pick<TUsageMeteringServiceFactory, "emitForProject">;+ agentVaultDelegationDAL: Pick<TAgentVaultDelegationDALFactory, "delete" | "removeSubjects">;} & TClearPersonalValuesDeps;export type TAgentVaultMembershipServiceFactory = ReturnType<typeof agentVaultMembershipServiceFactory>;diff --cc backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.test.tsindex 0000000000,7e4eac796f..275efb7feemode 000000,100644..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@@@ -1,0 -1,294 +1,295 @@@+ import { createMongoAbility } from "@casl/ability";+ import { describe, expect, test, vi } from "vitest";++ import {+ ProjectPermissionAgentVaultSessionActions,+ ProjectPermissionSub+ } from "@app/ee/services/permission/project-permission";+ import { ConflictError } from "@app/lib/errors";+ import { ObjectStorageType } from "@app/services/object-storage/object-storage-types";++ import {+ AgentVaultCredentialType,+ AgentVaultOauthStatus,+ AgentVaultServiceType+ } from "../agent-vault/agent-vault-enums";+ import { AGENT_VAULT_SERVICE_MOVED_MESSAGE } from "../agent-vault-oauth/agent-vault-oauth-service";+ import { TRefreshServiceTokenDTO } from "../agent-vault-oauth/agent-vault-oauth-types";+ import { agentVaultProxyServiceFactory } from "./agent-vault-proxy-service";+ import { TResolveServiceRow } from "./agent-vault-resolve-dal";++ vi.mock("@app/lib/logger", () => ({+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }+ }));+ vi.mock("@app/services/object-storage/object-storage-default-fns", () => ({+ isDefaultStorageConfigured: () => false+ }));++ const PROJECT_ID = "11111111-1111-4111-8111-111111111111";+ const SERVICE_ID = "33333333-3333-4333-8333-333333333333";+ const SERVER_URL = "https://mcp.linear.app/mcp";++ const serviceRow = (overrides: Partial<TResolveServiceRow> = {}): TResolveServiceRow => ({+ id: SERVICE_ID,+ name: "linear",+ accessBundleName: "bundle",+ type: AgentVaultServiceType.Mcp,+ hostPattern: "mcp.linear.app",+ config: { serverUrl: SERVER_URL, transport: "streamable-http" },+ credentialType: AgentVaultCredentialType.OAuth,+ credentialConfig: {+ status: AgentVaultOauthStatus.Connected,+ // Inside the refresh horizon, so resolve refreshes it.+ expiresAt: new Date(Date.now() + 10_000).toISOString()+ },+ encryptedCredential: Buffer.from(JSON.stringify({ accessToken: "snapshot-access" })),+ allowedMethods: null,+ allowedPathPrefixes: null,+ memberProvidedFields: null,+ position: 0,+ ...overrides+ });++ const sessionLogConfig = {+ id: "logs-config",+ projectId: PROJECT_ID,+ enabled: false,+ storageType: ObjectStorageType.Default,+ createdAt: new Date(),+ updatedAt: new Date()+ };++ const setup = (+ refresh: (dto: TRefreshServiceTokenDTO) => Promise<unknown>,+ rows = [serviceRow()],+ variables: { id: string; encryptedValue: Buffer }[] = []+ ) => {+ const refreshServiceToken = vi.fn(refresh);+ const reportMissingScopes = vi.fn(async () => {});+ const service = agentVaultProxyServiceFactory({+ agentVaultProxyDAL: {+ findByIdWithOrg: async () => ({ projectId: PROJECT_ID, orgId: "org-1", pollInterval: 60 })+ } as never,+ agentVaultResolveDAL: { findResolvableServices: async () => rows },+ agentVaultServiceCustomHeaderDAL: { findByServiceIds: async () => [] },+ agentVaultServiceSubstitutionDAL: { findByServiceIds: async () => [] },+ agentVaultVariableDAL: { findValuesForResolve: async () => variables },+ agentVaultPersonalValueDAL: { findForResolve: async () => [] },+ agentVaultSessionDAL: {+ findByTokenHash: async () =>+ ({ id: "session-1", projectId: PROJECT_ID, userId: "user-1", revokedAt: null, expiresAt: null }) as never+ },++ agentVaultDelegationDAL: { identityCoversUser: async () => false },+ agentVaultSessionLogConfigDAL: {+ findOne: async () => sessionLogConfig,+ findByProjectIdFromPrimary: async () => sessionLogConfig+ },+ membershipDAL: { findResourceMembershipsForActor: async () => [] },+ orgDAL: { findEffectiveOrgMembership: async () => ({ isActive: true }) as never },+ permissionService: {+ getProjectPermission: async () =>+ ({+ permission: createMongoAbility([+ {+ action: ProjectPermissionAgentVaultSessionActions.Read,+ subject: ProjectPermissionSub.AgentVaultSessions+ }+ ]),+ hasRole: () => true,+ memberships: []+ }) as never+ },+ kmsService: {+ createCipherPairWithDataKey: async () =>+ ({ decryptor: ({ cipherTextBlob }: { cipherTextBlob: Buffer }) => cipherTextBlob }) as never+ },+ licenseService: {} as never,+ resourceAuthMethodService: {} as never,+ agentVaultOauthService: {+ refreshServiceToken: refreshServiceToken as never,+ reportMissingScopes: reportMissingScopes as never+ }+ });+ return { service, refreshServiceToken, reportMissingScopes };+ };++ const refreshed = {+ credential: {+ type: "bearer",+ headerName: "Authorization",+ headerPrefix: "Bearer",+ value: "refreshed-access",+ source: "oauth",+ expiresAt: null+ },+ status: AgentVaultOauthStatus.Connected+ };++ const refreshArgs = {+ proxyId: "proxy-1",+ orgId: "org-1",+ sessionToken: "token",+ serviceId: SERVICE_ID,+ rejectedTokenHash: "a".repeat(64)+ };++ describe("credential refresh", () => {+ test("a host pattern that no longer matches the service is a 409, before any refresh", async () => {+ const { service, refreshServiceToken } = setup(async () => refreshed);+ const result = service.refreshCredential({ ...refreshArgs, hostPattern: "old.example.com" });+ await expect(result).rejects.toThrow(ConflictError);+ await expect(result).rejects.toThrow(AGENT_VAULT_SERVICE_MOVED_MESSAGE);+ expect(refreshServiceToken).not.toHaveBeenCalled();+ });++ test("a matching host pattern is passed on, so the refresh re-checks it on the rows it reads", async () => {+ const { service, refreshServiceToken } = setup(async () => refreshed);+ await expect(service.refreshCredential({ ...refreshArgs, hostPattern: "mcp.linear.app" })).resolves.toEqual(+ refreshed+ );+ expect(refreshServiceToken.mock.calls[0][0].destination).toEqual({ hostPattern: "mcp.linear.app" });+ });+ });++ describe("missing scopes report", () => {+ test("a host pattern that no longer matches the service is a 409, before anything is recorded", async () => {+ const { service, reportMissingScopes } = setup(async () => refreshed);+ const result = service.reportMissingScopes({+ ...refreshArgs,+ hostPattern: "old.example.com",+ requiredScopes: ["admin"]+ });+ await expect(result).rejects.toThrow(AGENT_VAULT_SERVICE_MOVED_MESSAGE);+ expect(reportMissingScopes).not.toHaveBeenCalled();+ });++ test("records the scopes against the rejected token without refreshing", async () => {+ const { service, refreshServiceToken, reportMissingScopes } = setup(async () => refreshed);+ await service.reportMissingScopes({+ ...refreshArgs,+ rejectedTokenHash: "A".repeat(64),+ hostPattern: "mcp.linear.app",+ requiredScopes: ["admin"]+ });+ expect(reportMissingScopes).toHaveBeenCalledWith({+ serviceId: SERVICE_ID,+ rejectedTokenHash: "a".repeat(64),+ requiredScopes: ["admin"],+ hostPattern: "mcp.linear.app"+ });+ expect(refreshServiceToken).not.toHaveBeenCalled();+ });+ });++ describe("resolve's lazy refresh", () => {+ const resolve = (service: ReturnType<typeof setup>["service"]) =>+ service.resolveSession({ proxyId: "proxy-1", orgId: "org-1", sessionToken: "token", hasSessionLogKey: false });++ test("pins the refresh to the snapshot's host and server URL, and sends what it returns", async () => {+ const { service, refreshServiceToken } = setup(async () => refreshed);+ const { services } = await resolve(service);+ expect(refreshServiceToken.mock.calls[0][0].destination).toEqual({+ hostPattern: "mcp.linear.app",+ serverUrl: SERVER_URL+ });+ expect(services[0]).toMatchObject({ hostPattern: "mcp.linear.app", credential: { value: "refreshed-access" } });+ });++ test("a service that moved during the refresh keeps the snapshot's host with the snapshot's own token", async () => {+ const { service } = setup(async () => {+ throw new ConflictError({ message: AGENT_VAULT_SERVICE_MOVED_MESSAGE });+ });+ const { services } = await resolve(service);+ expect(services[0]).toMatchObject({+ hostPattern: "mcp.linear.app",+ credential: { type: "bearer", value: "snapshot-access", source: "oauth" }+ });+ });++ test("waits at most 4 seconds for a refresh, then sends the stored token", async () => {+ vi.useFakeTimers();+ try {+ const { service } = setup(() => new Promise(() => {}));+ let settled = false;+ const result = resolve(service).finally(() => {+ settled = true;+ });+ await vi.advanceTimersByTimeAsync(3_999);+ expect(settled).toBe(false);+ await vi.advanceTimersByTimeAsync(1);+ const { services } = await result;+ expect(services[0].credential).toMatchObject({ value: "snapshot-access" });+ } finally {+ vi.useRealTimers();+ }+ });++ test("a service that needs reauthorization isn't refreshed, even when its token is about to expire", async () => {+ const { service, refreshServiceToken } = setup(+ async () => refreshed,+ [+ serviceRow({+ credentialConfig: {+ status: AgentVaultOauthStatus.NeedsReauthorization,+ expiresAt: new Date(Date.now() + 10_000).toISOString()+ }+ })+ ]+ );+ const { services } = await resolve(service);+ expect(refreshServiceToken).not.toHaveBeenCalled();+ expect(services[0].credential).toMatchObject({ value: "snapshot-access" });+ });++ test("a variable reference inside an OAuth token is sent as is, while a Bearer token's is expanded", async () => {+ const variableId = "44444444-4444-4444-8444-444444444444";+ const reference = `{{${variableId}}}`;+ const { service } = setup(+ async () => refreshed,+ [+ serviceRow({+ credentialConfig: { status: AgentVaultOauthStatus.Connected, expiresAt: null },+ encryptedCredential: Buffer.from(JSON.stringify({ accessToken: `oauth-${reference}` }))+ }),+ serviceRow({+ id: "55555555-5555-4555-8555-555555555555",+ type: AgentVaultServiceType.Http,+ hostPattern: "api.example.com",+ config: null,+ credentialType: AgentVaultCredentialType.Bearer,+ credentialConfig: { headerName: "Authorization", headerPrefix: "Bearer" },+ encryptedCredential: Buffer.from(JSON.stringify({ value: `bearer-${reference}` }))+ })+ ],+ [{ id: variableId, encryptedValue: Buffer.from(JSON.stringify({ value: "expanded" })) }]+ );+ const { services } = await resolve(service);+ expect(services[0].credential).toMatchObject({ value: `oauth-${reference}` });+ expect(services[1].credential).toMatchObject({ value: "bearer-expanded" });+ });++ test("an OAuth token is always sent as Authorization: Bearer, whatever its config holds", async () => {+ const { service } = setup(+ async () => refreshed,+ [+ serviceRow({+ credentialConfig: {+ headerName: "X-Api-Key",+ headerPrefix: "Token",+ status: AgentVaultOauthStatus.Connected,+ expiresAt: null+ }+ })+ ]+ );+ const { services } = await resolve(service);+ expect(services[0].credential).toEqual({+ type: "bearer",+ headerName: "Authorization",+ headerPrefix: "Bearer",+ value: "snapshot-access",+ source: "oauth",+ expiresAt: null+ });+ });+ });diff --cc backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.tsindex 6887f8a5ee,430ec8576e..1dfd1bb11f--- a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.ts+++ b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.ts@@@ -30,15 -33,17 +33,22 @@@ importTAgentVaultMemberProvidedField} from "../agent-vault/agent-vault-enums";import { TAgentVaultOwner } from "../agent-vault/agent-vault-owner-fns";-import { findReachableAccessBundleIds, liveGroupIdsFrom } from "../agent-vault/agent-vault-permission";+import {+ findReachableAccessBundleIds,+ intersectAccessBundleIds,+ liveGroupIdsFrom+} from "../agent-vault/agent-vault-permission";+ import { getServiceServerUrl } from "../agent-vault/agent-vault-service-type-fns";import { expandStoredVariableReferences, findStoredVariableIds } from "../agent-vault/agent-vault-variable-fns";import { TAgentVaultServiceCustomHeaderDALFactory } from "../agent-vault-access-bundle/agent-vault-service-custom-header-dal";import { TAgentVaultServiceSubstitutionDALFactory } from "../agent-vault-access-bundle/agent-vault-service-substitution-dal";+import { TAgentVaultDelegationDALFactory } from "../agent-vault-delegation/agent-vault-delegation-dal";+ import {+ AGENT_VAULT_SERVICE_MOVED_MESSAGE,+ TAgentVaultOauthServiceFactory+ } from "../agent-vault-oauth/agent-vault-oauth-service";+ import { toResolvedOauthCredential } from "../agent-vault-oauth/agent-vault-oauth-token-fns";+ import { TAgentVaultOauthConfig } from "../agent-vault-oauth/agent-vault-oauth-types";import { TAgentVaultPersonalValueDALFactory } from "../agent-vault-personal-value/agent-vault-personal-value-dal";import { TAgentVaultSessionDALFactory } from "../agent-vault-session/agent-vault-session-dal";import { hashSessionToken } from "../agent-vault-session/agent-vault-session-fns";@@@ -634,70 -650,12 +657,74 @@@ export const agentVaultProxyServiceFactreturn resolved;};+ // The identity that started a session on a user's behalf has to still be in the org and in Agent Vault, and its+ // delegation has to still cover the user. Read on every resolve, so taking any of them away ends the session on+ // the proxy's next poll. Returns the bundles the identity reaches (null for every bundle), since the session reaches+ // only what both the identity and the user reach.+ const $getActingIdentityReach = async ({+ projectId,+ orgId,+ userId,+ actingIdentityId+ }: {+ projectId: string;+ orgId: string;+ userId: string | null;+ actingIdentityId: string | null;+ }): Promise<string[] | null> => {+ const refused = () =>+ new UnauthorizedError({+ message: "The machine identity that started this session is no longer allowed to act on behalf of its user"+ });+ if (!actingIdentityId || !userId) throw refused();++ const orgMembership = await orgDAL.findEffectiveOrgMembership({+ actorType: ActorType.IDENTITY,+ actorId: actingIdentityId,+ orgId,+ status: OrgMembershipStatus.Accepted+ });+ if (!orgMembership?.isActive) throw refused();++ let isAdmin: boolean;+ let liveGroupIds: string[];+ try {+ const { permission, hasRole, memberships } = await permissionService.getProjectPermission({+ actor: ActorType.IDENTITY,+ actorId: actingIdentityId,+ projectId,+ actorAuthMethod: null,+ actorOrgId: orgId,+ actionProjectType: ActionProjectType.AgentVault+ });+ if (!permission.can(ProjectPermissionAgentVaultSessionActions.Read, ProjectPermissionSub.AgentVaultSessions)) {+ throw refused();+ }+ isAdmin = hasRole(ProjectMembershipRole.Admin);+ liveGroupIds = liveGroupIdsFrom(memberships);+ } catch (error) {+ if (error instanceof ForbiddenRequestError && error.name === "ProjectMembershipNotFound") throw refused();+ throw error;+ }++ if (!(await agentVaultDelegationDAL.identityCoversUser({ projectId, identityId: actingIdentityId, userId }))) {+ throw refused();+ }++ if (isAdmin) return null;+ return findReachableAccessBundleIds(membershipDAL, {+ projectId,+ actor: { type: ActorType.IDENTITY, id: actingIdentityId },+ groupIds: liveGroupIds+ });+ };+- /** The only endpoint that decrypts a credential. The proxy's JWT authorizes; the session token is a selector. */- const resolveSession = async ({ proxyId, orgId, sessionToken, hasSessionLogKey }: TResolveSessionDTO) => {+ // Shared by resolve and credential refresh, so a refresh can never reach a service resolve would not.+ const $authorizeSession = async ({+ proxyId,+ orgId,+ sessionToken+ }: Pick<TResolveSessionDTO, "proxyId" | "orgId" | "sessionToken">) => {const session = await agentVaultSessionDAL.findByTokenHash(hashSessionToken(sessionToken));if (!session) throw new NotFoundError({ message: "Session not found" });@@@ -782,8 -728,14 +809,15 @@@actor,groupIds: liveGroupIds});+ const accessBundleIds = actingIdentity ? intersectAccessBundleIds(actorReach, actingIdentity.reach) : actorReach;+ return { session, proxy, accessBundleIds };+ };++ /** Resolve services and decrypt their credentials. The proxy's JWT authorizes; the session token is a selector. */+ const resolveSession = async ({ proxyId, orgId, sessionToken, hasSessionLogKey }: TResolveSessionDTO) => {+ const { session, proxy, accessBundleIds } = await $authorizeSession({ proxyId, orgId, sessionToken });+const rows = await agentVaultResolveDAL.findResolvableServices({sessionId: session.id,projectId: session.projectId,diff --cc backend/src/ee/services/agent-vault-session/agent-vault-session-dal.tsindex 0d8b2ff2bf,febf786762..a0d28786b1--- a/backend/src/ee/services/agent-vault-session/agent-vault-session-dal.ts+++ b/backend/src/ee/services/agent-vault-session/agent-vault-session-dal.ts@@@ -16,10 -16,8 +16,11 @@@ export type TAgentVaultSessionListRowid: string;userId: string | null;identityId: string | null;+ actingIdentityId: string | null;+ actingIdentityName: string | null;+ label: string | null;actor: TAgentVaultSessionActor;+ actingIdentity: TAgentVaultSessionActingIdentity | null;expiresAt: Date | null;revokedAt: Date | null;createdAt: Date;@@@ -323,13 -278,8 +327,14 @@@ export const agentVaultSessionDALFactorid: row.id,userId: row.userId,identityId: row.identityId,+ actingIdentityId: row.actingIdentityId,+ actingIdentityName: row.actingIdentityName,+ label: row.label,actor: toSessionActor(row),+ actingIdentity:+ row.actingIdentityName !== null+ ? { id: row.actingIdentityId, name: row.actingIdentityLiveName ?? row.actingIdentityName }+ : null,expiresAt: row.expiresAt,revokedAt: row.revokedAt,createdAt: row.createdAt,@@@ -352,12 -302,16 +357,20 @@@};// Conditional so two concurrent revokes cannot both believe they were the one that revoked it. The loser- // gets no row back, which is what keeps the audit trail down to a single revocation.- // gets no row back, which is what keeps the audit trail down to a single revocation. A session whose owner- // was deleted is skipped too: updatedAt is the only record of when, and this write would move it.++ // gets no row back, which is what keeps the audit trail down to a single revocation. A session whose owner, or++ // whose acting identity, was deleted is skipped too: updatedAt is the only record of when, and this write would++ // move it.const revokeIfActive = async (id: string, revokedAt: Date, tx?: Knex) => {try {const [row] = (await (tx || db)(TableName.AgentVaultSession).where({ id }).whereNull("revokedAt")+ .where((qb) => {+ void qb.whereNotNull("userId").orWhereNotNull("identityId");+ })++ .where((qb) => {++ void qb.whereNull("actingIdentityName").orWhereNotNull("actingIdentityId");++ }).update({ revokedAt }, "*")) as TAgentVaultSessions[];return row as TAgentVaultSessions | undefined;} catch (error) {@@@ -365,6 -319,40 +378,43 @@@}};- // One statement on the primary: the row is locked, then rewritten only if it still has an owner, and its label++ // One statement on the primary: the row is locked, then rewritten only if it still has an owner (and, on a++ // user's behalf, its acting identity), and its label+ // before the write comes back. So two quick edits can't both read a stale label, the caller audits what+ // actually changed, and a session whose owner was just deleted isn't written even if a replica hasn't seen+ // that yet: updatedAt is the only record of when the owner went. No row back means no such session.+ const updateLabel = async (id: string, projectId: string, label: string | null, tx?: Knex) => {+ try {+ const { rows } = (await (tx || db).raw(+ `WITH previous AS (- SELECT id, label, "userId", "identityId" FROM ?? WHERE id = ? AND "projectId" = ? FOR UPDATE++ SELECT id, label, "userId", "identityId", "actingIdentityId", "actingIdentityName"++ FROM ?? WHERE id = ? AND "projectId" = ? FOR UPDATE+ ), updated AS (+ UPDATE ?? AS session SET label = ? FROM previous+ WHERE session.id = previous.id AND (previous."userId" IS NOT NULL OR previous."identityId" IS NOT NULL)++ AND (previous."actingIdentityName" IS NULL OR previous."actingIdentityId" IS NOT NULL)+ RETURNING session.id+ )+ SELECT previous.label AS "previousLabel", EXISTS (SELECT 1 FROM updated) AS "isUpdated" FROM previous`,+ [TableName.AgentVaultSession, id, projectId, TableName.AgentVaultSession, label]+ )) as { rows: { previousLabel: string | null; isUpdated: boolean }[] };+ return rows[0] as { previousLabel: string | null; isUpdated: boolean } | undefined;+ } catch (error) {+ throw new DatabaseError({ error, name: "Update agent vault session label" });+ }+ };++ // Read after a write that didn't happen, so the answer reflects the row as it is, not as a replica last saw it.+ const findByIdOnPrimary = async (id: string, projectId: string, tx?: Knex) => {+ try {+ return (await (tx || db)(TableName.AgentVaultSession).where({ id, projectId }).first()) as+ | TAgentVaultSessions+ | undefined;+ } catch (error) {+ throw new DatabaseError({ error, name: "Find agent vault session" });+ }+ };+// The id is chosen by the caller because the session log key is wrapped with it before the row exists.const createWithId = async (data: TAgentVaultSessionsInsert & { id: string }, tx?: Knex) => {try {diff --cc backend/src/ee/services/agent-vault-session/agent-vault-session-fns.test.tsindex 951a3633a0,a1d1bfe279..0de2492ada--- a/backend/src/ee/services/agent-vault-session/agent-vault-session-fns.test.ts+++ b/backend/src/ee/services/agent-vault-session/agent-vault-session-fns.test.ts@@@ -1,50 -1,47 +1,98 @@@import { describe, expect, test } from "vitest";-import { AgentVaultMemberType } from "../agent-vault/agent-vault-enums";-import { describeSessionForAudit } from "./agent-vault-session-fns";+import { ActorType } from "@app/services/auth/auth-type";+- import { AgentVaultSessionStatus } from "../agent-vault/agent-vault-enums";- import { deriveSessionStatus, isOrphanedSession, isSessionOwnedBy } from "./agent-vault-session-fns";++import { AgentVaultMemberType, AgentVaultSessionStatus } from "../agent-vault/agent-vault-enums";++import {++ deriveSessionStatus,++ describeSessionForAudit,++ isOrphanedSession,++ isSessionOwnedBy++} from "./agent-vault-session-fns";++const live = { expiresAt: null, revokedAt: null };++describe("agent vault session status", () => {+ test("a session whose owner was deleted reads as revoked", () => {+ expect(isOrphanedSession({ userId: null, identityId: null })).toBe(true);+ expect(deriveSessionStatus({ ...live, userId: null, identityId: null })).toBe(AgentVaultSessionStatus.Revoked);+ });++ // The name outlives the identity, which is how the row still says it was started on someone's behalf.+ test("an on-behalf-of session whose acting identity was deleted reads as revoked", () => {+ const session = { ...live, userId: "user-1", actingIdentityId: null, actingIdentityName: "slack-bot" };+ expect(isOrphanedSession(session)).toBe(true);+ expect(deriveSessionStatus(session)).toBe(AgentVaultSessionStatus.Revoked);+ });++ // An identity can be named "", so a session is on someone's behalf when the name is set, not when it's truthy.+ test("an empty acting identity name still marks an on-behalf-of session", () => {+ const session = { ...live, userId: "user-1", actingIdentityId: null, actingIdentityName: "" };+ expect(isOrphanedSession(session)).toBe(true);+ expect(deriveSessionStatus(session)).toBe(AgentVaultSessionStatus.Revoked);+ });++ test("an on-behalf-of session with both its user and its acting identity is active", () => {+ const session = { ...live, userId: "user-1", actingIdentityId: "identity-1", actingIdentityName: "slack-bot" };+ expect(isOrphanedSession(session)).toBe(false);+ expect(deriveSessionStatus(session)).toBe(AgentVaultSessionStatus.Active);+ });+});++describe("agent vault session ownership", () => {+ const onBehalfOf = { userId: "user-1", identityId: null, actingIdentityId: "identity-1" };++ test("the user and the identity that started it on their behalf both hold the session", () => {+ expect(isSessionOwnedBy({ actor: ActorType.USER, actorId: "user-1" }, onBehalfOf)).toBe(true);+ expect(isSessionOwnedBy({ actor: ActorType.IDENTITY, actorId: "identity-1" }, onBehalfOf)).toBe(true);+ });++ // Ids of users and identities are both UUIDs, so the actor type has to be matched as well as the id.+ test("an id is matched only against the column for its actor type", () => {+ expect(isSessionOwnedBy({ actor: ActorType.USER, actorId: "identity-1" }, onBehalfOf)).toBe(false);+ expect(isSessionOwnedBy({ actor: ActorType.IDENTITY, actorId: "user-1" }, onBehalfOf)).toBe(false);+ });+});++ describe("describeSessionForAudit", () => {+ test("names a user's session by email, and the bundle it carried", () => {+ expect(+ describeSessionForAudit({+ actor: {+ type: AgentVaultMemberType.User,+ id: "u1",+ username: "alice",+ email: "[email protected]",+ firstName: "Alice",+ lastName: null+ },+ accessBundles: [{ name: "release" }]+ })+ ).toEqual({ sessionOwner: "[email protected]", accessBundleName: "release" });+ });++ test("falls back to the username when a user has no email", () => {+ expect(+ describeSessionForAudit({+ actor: {+ type: AgentVaultMemberType.User,+ id: null,+ username: "alice",+ email: null,+ firstName: null,+ lastName: null+ },+ accessBundles: [{ name: "release" }]+ }).sessionOwner+ ).toBe("alice");+ });++ test("names a machine identity's session by the identity, and allows a session with no bundle left", () => {+ expect(+ describeSessionForAudit({+ actor: { type: AgentVaultMemberType.MachineIdentity, id: "i1", name: "github-actions" },+ accessBundles: []+ })+ ).toEqual({ sessionOwner: "github-actions", accessBundleName: null });+ });+ });diff --cc backend/src/ee/services/agent-vault-session/agent-vault-session-service.tsindex 43720dd504,acdf823ff8..d550fe61b7--- a/backend/src/ee/services/agent-vault-session/agent-vault-session-service.ts+++ b/backend/src/ee/services/agent-vault-session/agent-vault-session-service.ts@@@ -68,33 -61,17 +74,34 @@@ export const agentVaultSessionServiceFareturn { type: ctx.actor, id: ctx.actorId };};- const toSessionView = ({ userId, identityId, ...session }: TAgentVaultSessionListRow) => ({+ const toSessionView = ({+ userId,+ identityId,+ actingIdentityId,+ actingIdentityName,+ ...session+ }: TAgentVaultSessionListRow) => ({...session,- status: deriveSessionStatus({ ...session, userId, identityId })+ status: deriveSessionStatus({ ...session, userId, identityId, actingIdentityId, actingIdentityName })});- const mintSession = async ({ projectId, ctx, accessBundles, actorName, actorEmail, ttl, label }: TMintSessionDTO) => {- const actor = requireSessionActor(ctx);- const { permission, accessBundleIds: reachable } = await getAgentVaultReachability(- { permissionService, membershipDAL },- { projectId, ctx }- );+ const resolveSessionTtl = (ttl: string | undefined, isOnBehalfOf: boolean) =>+ ttl ?? (isOnBehalfOf ? AGENT_VAULT_ON_BEHALF_OF_SESSION_DEFAULT_TTL : AGENT_VAULT_SESSION_DEFAULT_TTL);++ const mintSession = async ({+ projectId,+ ctx,+ accessBundles,+ actorName,+ actorEmail,+ ttl: requestedTtl,- onBehalfOf++ onBehalfOf,++ label+ }: TMintSessionDTO) => {+ const caller = requireSessionActor(ctx);+ const ttl = resolveSessionTtl(requestedTtl, Boolean(onBehalfOf));++ const { permission } = await getAgentVaultPermission({ permissionService }, { projectId, ctx });ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionAgentVaultSessionActions.Create,ProjectPermissionSub.AgentVaultSessions@@@ -201,7 -114,13 +208,8 @@@{id: sessionId,projectId,- userId: actor.type === ActorType.USER ? actor.id : null,- identityId: actor.type === ActorType.IDENTITY ? actor.id : null,- actorType:- actor.type === ActorType.IDENTITY ? AgentVaultMemberType.MachineIdentity : AgentVaultMemberType.User,- actorName,- actorEmail,+ ...owner,+ label: label || null,tokenHash,expiresAt,encryptedSessionLogKey@@@ -323,6 -249,27 +342,28 @@@};};+ const updateSessionLabel = async ({ projectId, ctx, sessionId, label }: TUpdateSessionLabelDTO) => {+ const { permission, isAdmin } = await getAgentVaultPermission({ permissionService }, { projectId, ctx });+ ForbiddenError.from(permission).throwUnlessCan(+ ProjectPermissionAgentVaultSessionActions.Edit,+ ProjectPermissionSub.AgentVaultSessions+ );++ const session = await findVisibleSession({ projectId, ctx, sessionId, isAdmin });+ // The visible session can come from a replica that lags, so the owner check and the previous label come from+ // the write itself.+ const updated = await agentVaultSessionDAL.updateLabel(session.id, projectId, label);+ if (!updated) throw new NotFoundError({ message: `Session with ID '${sessionId}' not found` });+ if (!updated.isUpdated) {+ throw new BadRequestError({- message: "The user or machine identity that owned this session was deleted, so its label can't be changed."++ message:++ "The user or machine identity that owned or started this session was deleted, so its label can't be changed."+ });+ }++ return { session: toSessionView({ ...session, label }), previousLabel: updated.previousLabel };+ };+return {mintSession,listSessions,diff --cc backend/src/ee/services/agent-vault-session/agent-vault-session-types.tsindex a21688bf0e,979af15106..4f53758057--- a/backend/src/ee/services/agent-vault-session/agent-vault-session-types.ts+++ b/backend/src/ee/services/agent-vault-session/agent-vault-session-types.ts@@@ -13,11 -10,10 +13,12 @@@ export type TMintSessionDTO =projectId: string;ctx: TGenericPermission;accessBundles: string[];+ /** The caller's name and email, snapshotted from the request. */actorName: string;actorEmail: string | null;- ttl: string;+ ttl?: string;+ onBehalfOf?: TOnBehalfOfUser;+ label: string | null;};export type TListSessionsDTO = {@@@ -38,8 -34,9 +39,11 @@@ export type TRevokeSessionDTO =export type TGetSessionByIdDTO = TRevokeSessionDTO;+/** The machine identity that started a session on its actor's behalf. `id` is null once the identity is deleted. */+export type TAgentVaultSessionActingIdentity = { id: string | null; name: string };+ export type TUpdateSessionLabelDTO = TRevokeSessionDTO & {+ label: string | null;+ };export type TAgentVaultSessionActor =| {diff --cc backend/src/ee/services/agent-vault/AGENTS.mdindex d3ec3733fa,2363480fc6..ea1383a50a--- a/backend/src/ee/services/agent-vault/AGENTS.md+++ b/backend/src/ee/services/agent-vault/AGENTS.md@@@ -20,11 -20,11 +20,12 @@@ agent-vault/ shared: enagent-vault-access-bundle/ bundles, services, credential encryption, grantsagent-vault-variable/ global and personal variables and the reads behind Used Byagent-vault-member/ product membership (list, add, role, remove)+agent-vault-delegation/ which users a machine identity may start sessions on behalf ofagent-vault-personal-value/ each actor's own values for the fields a service leaves to members- agent-vault-session/ mint, revoke, list, get+ agent-vault-session/ mint, revoke, list, get, edit labelagent-vault-project/ the per-org project's lazy bootstrap and resolver- agent-vault-proxy/ create/rotate (proxy token + CA), bootstrap, heartbeat, resolve+ agent-vault-proxy/ create/rotate (proxy token + CA), bootstrap, heartbeat, resolve, credential refresh+ agent-vault-oauth/ OAuth for MCP services: discovery, client registration, authorizations, refreshagent-vault-session-log/ storage settings, chunk ingest, playback```diff --cc backend/src/ee/services/audit-log/audit-log-types.tsindex 5169da14ac,bcd8c9d64f..3141d684ee--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@@ -831,9 -833,8 +833,10 @@@ export enum EventTypeAGENT_VAULT_ACCESS_BUNDLE_MEMBER_ADD = "agent-vault-access-bundle-member-add",AGENT_VAULT_ACCESS_BUNDLE_MEMBER_REMOVE = "agent-vault-access-bundle-member-remove",AGENT_VAULT_SESSION_MINT = "agent-vault-session-mint",+ AGENT_VAULT_SESSION_UPDATE = "agent-vault-session-update",AGENT_VAULT_SESSION_REVOKE = "agent-vault-session-revoke",+ AGENT_VAULT_DELEGATION_SET = "agent-vault-delegation-set",+ AGENT_VAULT_DELEGATION_DELETE = "agent-vault-delegation-delete",AGENT_VAULT_PROXY_REGISTER = "agent-vault-proxy-register",AGENT_VAULT_PROXY_TOKEN_REISSUE = "agent-vault-proxy-token-reissue",AGENT_VAULT_PROXY_TOKEN_ROTATE = "agent-vault-proxy-token-rotate",@@@ -8705,8 -8767,7 +8792,9 @@@ export type Event| AgentVaultAccessBundleMemberAddEvent| AgentVaultAccessBundleMemberRemoveEvent| AgentVaultSessionMintEvent+ | AgentVaultDelegationSetEvent+ | AgentVaultDelegationDeleteEvent+ | AgentVaultSessionUpdateEvent| AgentVaultSessionRevokeEvent| AgentVaultProxyRegisterEvent| AgentVaultProxyTokenReissueEventdiff --cc backend/src/lib/api-docs/constants.tsindex d192daaa8a,c3419e9a4f..1ceb5421d1--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@@ -4732,17 -4815,17 +4820,21 @@@ export const AGENT_VAULT =SESSION: {sessionId: "The ID of the session.",accessBundles: "The access bundle this session carries, by name. A list that accepts exactly one name.",- ttl: "How long the session lasts: a duration such as 30m, 8h or 7d (at least 1m), or never. Defaults to 7d.",+ ttl: "How long the session lasts: a duration such as 30m, 8h or 7d (at least 1m), or never. Defaults to 7d, or to 1h for a session started on behalf of a user.",+ label:+ "A short description of what the session is for, such as `nightly deploy` or `support ticket triage`. Up to 128 characters, without line breaks, tabs, or invisible characters. Shown wherever the session is listed.",+ updateLabel:- "The new label for the session, up to 128 characters, without line breaks, tabs, or invisible characters. Send null or an empty string to remove the label. You can't change the label once the session's owner is deleted.",++ "The new label for the session, up to 128 characters, without line breaks, tabs, or invisible characters. Send null or an empty string to remove the label. You can't change the label once the session's owner, or the machine identity that started it on the owner's behalf, is deleted.",+ onBehalfOf:+ "Start the session on behalf of a user instead of yourself. Only a machine identity whose delegation covers the user can do this. The session can use only an access bundle that both the user and the machine identity can use, and it uses the user's personal values. Name the user by userId or by userEmail, not both.",+ onBehalfOfUserId: "The ID of the user to start the session on behalf of.",+ onBehalfOfUserEmail: "The email address of the user to start the session on behalf of.",token: "The session token. Returned once, at mint, and never again.",expiresAt: "When the session expires, or null when it never does.",scope: "Whose sessions to list: your own (mine) or everyone's (all, administrators only).",status:"Filter by session status: `active`, `revoked` or `expired`. Separate several with commas to match any of them.",- search: "Match sessions by actor name, actor email, acting machine identity name or access bundle name.",- search: "Match sessions by label, actor name, actor email or access bundle name.",++ search: "Match sessions by label, actor name, actor email, acting machine identity name or access bundle name.",limit: "The maximum number of sessions to return.",offset: "How many sessions to skip.",actorType: "Whether the session belongs to a user or a machine identity.",diff --cc backend/src/server/routes/index.tsindex 8d6327df04,fefd2b60a5..52004fc833--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@@ -30,13 -30,9 +30,14 @@@ import { agentVaultServiceCustomHeaderDimport { agentVaultServiceDALFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-service-dal";import { agentVaultServiceSubstitutionDALFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-service-substitution-dal";import { agentVaultServiceVariableReferenceDALFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-service-variable-reference-dal";+import {+ agentVaultDelegationDALFactory,+ agentVaultDelegationSubjectDALFactory+} from "@app/ee/services/agent-vault-delegation/agent-vault-delegation-dal";+import { agentVaultDelegationServiceFactory } from "@app/ee/services/agent-vault-delegation/agent-vault-delegation-service";import { agentVaultMemberDALFactory } from "@app/ee/services/agent-vault-member/agent-vault-member-dal";import { agentVaultMembershipServiceFactory } from "@app/ee/services/agent-vault-member/agent-vault-membership-service";+ import { agentVaultOauthServiceFactory } from "@app/ee/services/agent-vault-oauth/agent-vault-oauth-service";import {agentVaultPersonalValueDALFactory,agentVaultPersonalValueReferenceDALFactory@@@ -2014,9 -2044,16 +2049,18 @@@ export const registerRoutes = asyncconst agentVaultProxyDAL = agentVaultProxyDALFactory(db);const agentVaultResolveDAL = agentVaultResolveDALFactory(db);const agentVaultSessionLogConfigDAL = agentVaultSessionLogConfigDALFactory(db);+ const agentVaultDelegationDAL = agentVaultDelegationDALFactory(db);+ const agentVaultDelegationSubjectDAL = agentVaultDelegationSubjectDALFactory(db);+ const agentVaultOauthService = agentVaultOauthServiceFactory({+ keyStore,+ kmsService,+ agentVaultServiceDAL,+ agentVaultAccessBundleDAL,+ permissionService,+ membershipDAL+ });+const agentVaultVariableService = agentVaultVariableServiceFactory({agentVaultVariableDAL,agentVaultPersonalValueDAL,@@@ -2051,11 -2088,10 +2095,12 @@@agentVaultMemberDAL,userGroupMembershipDAL,identityGroupMembershipDAL,+ agentVaultOauthService,userDAL,groupDAL,- identityDAL+ identityDAL,+ agentVaultDelegationDAL,+ orgDAL});const agentVaultSessionService = agentVaultSessionServiceFactory({diff --cc docs/documentation/platform/agent-vault/sessions-api.mdxindex 8d0f108869,84176d6b73..675fa661a7--- a/docs/documentation/platform/agent-vault/sessions-api.mdx+++ b/docs/documentation/platform/agent-vault/sessions-api.mdx@@@ -57,12 -57,9 +57,13 @@@ curl -X POST https://app.infisical.com/- `accessBundles` takes a list, but a session can have only one access bundle, so the list must have exactly one name- `ttl` accepts a duration of at least one minute, such as `30m`, `8h`, or `7d`, or `never`, and defaults to `7d` (see [Choose how long a session lasts](#choose-how-long-a-session-lasts) to pick a value)+ - `label` is optional and describes what the session is for, in up to 128 characters (see [Label a session](/documentation/platform/agent-vault/sessions#label-a-session))+<Tip>+ If your code runs agents for other people, as a chat bot does, the machine identity can create each session [on behalf of the person who asked](/documentation/platform/agent-vault/sessions-on-behalf-of-users), so the session uses that person's personal values and gets no more access than that person.+</Tip>+- The response includes the session's ID, the session token, and when the session expires:+ The response includes the session's ID, its label, the session token, and when the session expires:```json{diff --cc frontend/src/hooks/api/agentVault/queries.tsxindex feb640c356,01fd6fa746..088fe739c2--- a/frontend/src/hooks/api/agentVault/queries.tsx+++ b/frontend/src/hooks/api/agentVault/queries.tsx@@@ -22,8 -32,8 +32,9 @@@ importTAgentVaultAccessBundleDetails,TAgentVaultAccessBundleListItem,TAgentVaultDecryptedSessionLogPage,+ TAgentVaultDelegationDetail,TAgentVaultMember,+ TAgentVaultOauthAuthorization,TAgentVaultProductActor,TAgentVaultProductMember,TAgentVaultProductMemberOf,diff --cc frontend/src/hooks/api/agentVault/types.tsindex cc5014fcf7,4ee16f0af4..0b3ac30337--- a/frontend/src/hooks/api/agentVault/types.ts+++ b/frontend/src/hooks/api/agentVault/types.ts@@@ -1,8 -1,11 +1,12 @@@import {AgentVaultCredentialType,+ AgentVaultDelegationScope,AgentVaultHttpMethod,+ AgentVaultMcpTransport,AgentVaultMemberType,+ AgentVaultOauthAuthorizationStatus,+ AgentVaultOauthStatus,+ AgentVaultServiceType,AgentVaultSessionLogDecision,AgentVaultSessionLogStorageType,AgentVaultSessionScope,@@@ -232,13 -259,10 +260,14 @@@ export type TAgentVaultSessionActorid: string | null;});+/** The machine identity that started a session on its actor's behalf. `id` is null once it is deleted. */+export type TAgentVaultSessionActingIdentity = { id: string | null; name: string };+export type TAgentVaultSession = {id: string;+ label: string | null;actor: TAgentVaultSessionActor;+ actingIdentity: TAgentVaultSessionActingIdentity | null;status: AgentVaultSessionStatus;expiresAt: string | null;revokedAt: string | null;@@@ -246,42 -270,9 +275,43 @@@accessBundles: TAgentVaultSessionAccessBundle[];};+export type TAgentVaultDelegation = {+ machineIdentity: { id: string; name: string };+ scope: AgentVaultDelegationScope;+ users: (Omit<Extract<TAgentVaultActor, { type: AgentVaultMemberType.User }>, "type"> & {+ addedAt: string;+ })[];+ groups: (Omit<Extract<TAgentVaultActor, { type: AgentVaultMemberType.Group }>, "type"> & {+ addedAt: string;+ })[];+ createdAt: string;+ updatedAt: string;+};++export type TAgentVaultMissingAccessBundle = { id: string; name: string };++// Reading or writing one delegation also says which bundles its machine identity can't act on: the ones each user and+// group can use and the identity can't.+export type TAgentVaultDelegationDetail = Omit<TAgentVaultDelegation, "users" | "groups"> & {+ users: (TAgentVaultDelegation["users"][number] & {+ missingAccessBundles: TAgentVaultMissingAccessBundle[];+ })[];+ groups: (TAgentVaultDelegation["groups"][number] & {+ missingAccessBundles: TAgentVaultMissingAccessBundle[];+ })[];+ missingAccessBundles: TAgentVaultMissingAccessBundle[];+};++export type TSetAgentVaultDelegationDTO = {+ machineIdentityId: string;+ scope: AgentVaultDelegationScope;+ userIds?: string[];+ groupIds?: string[];+};+export type TAgentVaultMintedSession = {id: string;+ label: string | null;token: string;expiresAt: string | null;createdAt: string;diff --cc frontend/src/hooks/api/auditLogs/constants.tsxindex 005f8dfe1f,78ead5dbc6..59253d7031--- a/frontend/src/hooks/api/auditLogs/constants.tsx+++ b/frontend/src/hooks/api/auditLogs/constants.tsx@@@ -492,9 -494,8 +494,10 @@@ export const eventToNameMap: { [K in Ev[EventType.AGENT_VAULT_ACCESS_BUNDLE_MEMBER_ADD]: "Grant access bundle",[EventType.AGENT_VAULT_ACCESS_BUNDLE_MEMBER_REMOVE]: "Revoke access bundle",[EventType.AGENT_VAULT_SESSION_MINT]: "Create session",+ [EventType.AGENT_VAULT_SESSION_UPDATE]: "Update session label",[EventType.AGENT_VAULT_SESSION_REVOKE]: "Revoke session",+ [EventType.AGENT_VAULT_DELEGATION_SET]: "Set machine identity delegation",+ [EventType.AGENT_VAULT_DELEGATION_DELETE]: "Remove machine identity delegation",[EventType.AGENT_VAULT_PROXY_REGISTER]: "Create proxy",[EventType.AGENT_VAULT_PROXY_TOKEN_REISSUE]: "Generate proxy enrollment token",[EventType.AGENT_VAULT_PROXY_ENROLL]: "Enroll proxy",@@@ -578,9 -580,8 +582,10 @@@ export const projectToEventsMap: PartiaEventType.AGENT_VAULT_ACCESS_BUNDLE_MEMBER_ADD,EventType.AGENT_VAULT_ACCESS_BUNDLE_MEMBER_REMOVE,EventType.AGENT_VAULT_SESSION_MINT,+ EventType.AGENT_VAULT_SESSION_UPDATE,EventType.AGENT_VAULT_SESSION_REVOKE,+ EventType.AGENT_VAULT_DELEGATION_SET,+ EventType.AGENT_VAULT_DELEGATION_DELETE,EventType.AGENT_VAULT_PROXY_REGISTER,EventType.AGENT_VAULT_PROXY_TOKEN_REISSUE,EventType.AGENT_VAULT_PROXY_ENROLL,diff --cc frontend/src/hooks/api/auditLogs/enums.tsxindex edcd46076a,ac14e2d56d..4a3a60d38a--- a/frontend/src/hooks/api/auditLogs/enums.tsx+++ b/frontend/src/hooks/api/auditLogs/enums.tsx@@@ -490,9 -492,8 +492,10 @@@ export enum EventTypeAGENT_VAULT_ACCESS_BUNDLE_MEMBER_ADD = "agent-vault-access-bundle-member-add",AGENT_VAULT_ACCESS_BUNDLE_MEMBER_REMOVE = "agent-vault-access-bundle-member-remove",AGENT_VAULT_SESSION_MINT = "agent-vault-session-mint",+ AGENT_VAULT_SESSION_UPDATE = "agent-vault-session-update",AGENT_VAULT_SESSION_REVOKE = "agent-vault-session-revoke",+ AGENT_VAULT_DELEGATION_SET = "agent-vault-delegation-set",+ AGENT_VAULT_DELEGATION_DELETE = "agent-vault-delegation-delete",AGENT_VAULT_PROXY_REGISTER = "agent-vault-proxy-register",AGENT_VAULT_PROXY_TOKEN_REISSUE = "agent-vault-proxy-token-reissue",AGENT_VAULT_PROXY_ENROLL = "agent-vault-proxy-enroll",diff --cc frontend/src/pages/agent-vault/AgentVaultSessionsPage/AgentVaultSessionsPage.tsxindex 747da44696,b7ee0f21d0..e0d5243c25--- a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/AgentVaultSessionsPage.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/AgentVaultSessionsPage.tsx@@@ -492,6 -542,13 +549,13 @@@ export const AgentVaultSessionsPage = (<LogsIcon />View Session Logs</DropdownMenuItem>- {/* The API refuses label edits once the session's owner is deleted */}- {session.actor.id !== null && (++ {/* The API refuses label edits once the session's owner, or the identity that started it on their behalf, is deleted */}++ {session.actor.id !== null && session.actingIdentity?.id !== null && (+ <DropdownMenuItem onClick={() => setSessionToLabel(session)}>+ <PencilIcon />+ {session.label ? "Edit Label" : "Add Label"}+ </DropdownMenuItem>+ )}<DropdownMenuItemvariant="danger"isDisabled={session.status !== AgentVaultSessionStatus.Active}diff --cc frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionDetailSheet.tsxindex 7d935e4001,c7a0a20303..55f411722e--- a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionDetailSheet.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionDetailSheet.tsx@@@ -40,6 -47,6 +47,8 @@@ export const SessionDetailSheet = (const { currentOrg } = useOrganization();const isOwnerDeleted = session?.actor.id === null;++ // The API refuses label edits once the owner, or the identity that started it on their behalf, is deleted.++ const canEditLabel = !isOwnerDeleted && session?.actingIdentity?.id !== null;const isMachineIdentity = session?.actor.type === AgentVaultMemberType.MachineIdentity;const hasExpired = Boolean(session?.expiresAt && new Date(session.expiresAt).getTime() <= Date.now()@@@ -105,85 -93,114 +95,131 @@@<DetailValueclassName={twMerge("flex items-center gap-2",- !session.actingIdentity.id && "text-muted"+ isOwnerDeleted && "text-muted")}>- <BotIcon className="size-4 shrink-0 text-muted" />+ {isMachineIdentity ? (+ <BotIcon className="size-4 shrink-0 text-muted" />+ ) : (+ <UserIcon className="size-4 shrink-0 text-muted" />+ )}<span className="truncate">- {session.actingIdentity.name}- {!session.actingIdentity.id && " (deleted)"}+ {memberDisplayName(session.actor)}+ {isOwnerDeleted && " (deleted)"}</span>+ {!isMachineIdentity && (+ <span className="truncate text-muted">+ {memberSubtitle(session.actor)}+ </span>+ )}</DetailValue></Detail>- )}- <Detail className="min-w-0">- <DetailLabel>- {session.accessBundles.length === 1 ? "Access Bundle" : "Access Bundles"}- </DetailLabel>- <DetailValue className="flex flex-wrap gap-x-4 gap-y-1">- {session.accessBundles.map((bundle) =>- bundle.id ? (- <Link- key={bundle.id}- to="/organizations/$orgId/agent-vault/access-bundles/$accessBundleId"- params={{ orgId: currentOrg.id, accessBundleId: bundle.id }}- className="group flex min-w-0 items-center gap-2"- >- <PackageIcon className="size-4 shrink-0 text-muted" />- <span className="truncate group-hover:underline group-hover:underline-offset-2">- {bundle.name}- </span>- </Link>- ) : (- <span- key={bundle.name}- className="flex min-w-0 items-center gap-2 text-muted"- >- <PackageIcon className="size-4 shrink-0" />- <span className="truncate">{bundle.name} (deleted)</span>++ {session.actingIdentity && (++ <Detail className="min-w-0">++ <DetailLabel>Started By</DetailLabel>++ <DetailValue++ className={twMerge(++ "flex items-center gap-2",++ !session.actingIdentity.id && "text-muted"++ )}++ >++ <BotIcon className="size-4 shrink-0 text-muted" />++ <span className="truncate">++ {session.actingIdentity.name}++ {!session.actingIdentity.id && " (deleted)"}+ </span>- )- )}- </DetailValue>- </Detail>- <Detail>- <DetailLabel>Created</DetailLabel>- <DetailValue>- {format(new Date(session.createdAt), "MMM d, yyyy h:mm a")}- </DetailValue>- </Detail>- {session.revokedAt && (- <Detail>- <DetailLabel>Revoked</DetailLabel>- <DetailValue>- {format(new Date(session.revokedAt), "MMM d, yyyy h:mm a")}++ </DetailValue>++ </Detail>++ )}+ <Detail className="min-w-0">+ <DetailLabel>+ {session.accessBundles.length === 1 ? "Access Bundle" : "Access Bundles"}+ </DetailLabel>+ <DetailValue className="flex flex-wrap gap-x-4 gap-y-1">+ {session.accessBundles.map((bundle) =>+ bundle.id ? (+ <Link+ key={bundle.id}+ to="/organizations/$orgId/agent-vault/access-bundles/$accessBundleId"+ params={{ orgId: currentOrg.id, accessBundleId: bundle.id }}+ className="group flex min-w-0 items-center gap-2"+ >+ <PackageIcon className="size-4 shrink-0 text-muted" />+ <span className="truncate group-hover:underline group-hover:underline-offset-2">+ {bundle.name}+ </span>+ </Link>+ ) : (+ <span+ key={bundle.name}+ className="flex min-w-0 items-center gap-2 text-muted"+ >+ <PackageIcon className="size-4 shrink-0" />+ <span className="truncate">{bundle.name} (deleted)</span>+ </span>+ )+ )}</DetailValue></Detail>- )}- {session.status !== AgentVaultSessionStatus.Revoked && (<Detail>- <DetailLabel>{hasExpired ? "Expired" : "Expires"}</DetailLabel>+ <DetailLabel>Created</DetailLabel><DetailValue>- <SessionExpiry expiresAt={session.expiresAt} />+ {format(new Date(session.createdAt), "MMM d, yyyy h:mm a")}</DetailValue></Detail>+ {session.revokedAt && (+ <Detail>+ <DetailLabel>Revoked</DetailLabel>+ <DetailValue>+ {format(new Date(session.revokedAt), "MMM d, yyyy h:mm a")}+ </DetailValue>+ </Detail>+ )}+ {session.status !== AgentVaultSessionStatus.Revoked && (+ <Detail>+ <DetailLabel>{hasExpired ? "Expired" : "Expires"}</DetailLabel>+ <DetailValue>+ <SessionExpiry expiresAt={session.expiresAt} />+ </DetailValue>+ </Detail>+ )}+ <Detail className="items-start">+ <DetailLabel>Status</DetailLabel>+ <SessionStatusBadge status={session.status} />+ </Detail>+ </div>+ {session.status === AgentVaultSessionStatus.Active && (+ <Button+ variant="danger"+ size="sm"+ className="shrink-0"+ onClick={() => onRevoke(session)}+ >+ <BanIcon />+ Revoke Session+ </Button>)}- <Detail className="items-start">- <DetailLabel>Status</DetailLabel>- <SessionStatusBadge status={session.status} />+ </div>+ <div className="flex items-start gap-2 border-t border-border px-4 py-3">+ <Detail className="min-w-0 flex-1">+ <DetailLabel>Label</DetailLabel>+ <DetailValue+ className={twMerge("min-w-0 break-words", !session.label && "text-muted")}+ >+ {session.label ?? "No label"}+ </DetailValue></Detail>- {!isOwnerDeleted && (++ {canEditLabel && (+ <IconButton+ variant="ghost"+ size="xs"+ aria-label={session.label ? "Edit label" : "Add label"}+ onClick={() => onEditLabel(session)}+ >+ <PencilIcon />+ </IconButton>+ )}</div>- {session.status === AgentVaultSessionStatus.Active && (- <Button- variant="danger"- size="sm"- className="shrink-0"- onClick={() => onRevoke(session)}- >- <BanIcon />- Revoke Session- </Button>- )}</div><div className="flex min-h-0 flex-1 flex-col">diff --cc frontend/src/pages/agent-vault/agent-vault-docs-urls.tsindex 5f20e8143b,e25e18d86f..c4f3575e44--- a/frontend/src/pages/agent-vault/agent-vault-docs-urls.ts+++ b/frontend/src/pages/agent-vault/agent-vault-docs-urls.ts@@@ -5,10 -5,9 +5,10 @@@ export const AgentVaultDocsUrls =quickstart: `${AGENT_VAULT_DOCS_BASE_URL}/quickstart`,accessBundles: `${AGENT_VAULT_DOCS_BASE_URL}/access-bundles`,services: `${AGENT_VAULT_DOCS_BASE_URL}/services`,- memberProvidedValues: `${AGENT_VAULT_DOCS_BASE_URL}/services#member-provided-values`,+ memberProvidedValues: `${AGENT_VAULT_DOCS_BASE_URL}/http-apis#member-provided-values`,variables: `${AGENT_VAULT_DOCS_BASE_URL}/variables`,sessions: `${AGENT_VAULT_DOCS_BASE_URL}/sessions`,+ sessionsOnBehalfOfUsers: `${AGENT_VAULT_DOCS_BASE_URL}/sessions-on-behalf-of-users`,proxies: `${AGENT_VAULT_DOCS_BASE_URL}/proxies`,sessionLogs: `${AGENT_VAULT_DOCS_BASE_URL}/session-logs`} as const;diff --cc frontend/src/pages/project/IdentityDetailsByIDPage/IdentityDetailsByIDPage.tsxindex ff9940b78c,2eac75b9f2..4be99d49ca--- a/frontend/src/pages/project/IdentityDetailsByIDPage/IdentityDetailsByIDPage.tsx+++ b/frontend/src/pages/project/IdentityDetailsByIDPage/IdentityDetailsByIDPage.tsx@@@ -15,9 -14,9 +14,10 @@@ importVenetianMaskIcon} from "lucide-react";+import { IdentityDelegationSection } from "@app/components/agent-vault/IdentityDelegationSection";import { AssumePrivilegesDialog } from "@app/components/assume-privileges";import { createNotification } from "@app/components/notifications";+ import { PageTitle } from "@app/components/PageTitle";import { OrgPermissionCan, ProjectPermissionCan } from "@app/components/permissions";import {Alert,