Skip to content

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

feat(agent-vault): sessions on behalf of users

Scott Wilson10b939082cf2
diff --git a/backend/e2e-test/routes/v1/agent-vault.spec.ts b/backend/e2e-test/routes/v1/agent-vault.spec.ts
index aa09133db7..8d3a2a8a32 100644
--- a/backend/e2e-test/routes/v1/agent-vault.spec.ts
+++ b/backend/e2e-test/routes/v1/agent-vault.spec.ts
@@ -9,6 +9,7 @@ import { AccessScope, ActionProjectType, OrgMembershipRole, ProjectMembershipRol
import { seedData1 } from "@app/db/seed-data";
import { agentVaultServiceCustomHeaderDALFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-service-custom-header-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 { 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 {
@@ -53,7 +54,7 @@ initLogger();
const authHeader = { authorization: `Bearer ${jwtAuthToken}` };
-const inject = (method: "GET" | "POST" | "PATCH" | "DELETE", url: string, body?: Record<string, unknown>) =>
+const inject = (method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE", url: string, body?: Record<string, unknown>) =>
testServer.inject({ method, url, headers: authHeader, ...(body ? { body } : {}) });
const createOrgIdentity = async (name: string) => {
@@ -235,7 +236,7 @@ const createMemberIdentity = async (name: string) => {
return {
id: identity.id,
- as: (method: "GET" | "POST" | "PATCH" | "DELETE", url: string, body?: Record<string, unknown>) =>
+ as: (method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE", url: string, body?: Record<string, unknown>) =>
testServer.inject({ method, url, headers: { authorization: `Bearer ${token}` }, ...(body ? { body } : {}) }),
cleanup: () => inject("DELETE", `/api/v1/identities/${identity.id}`)
};
@@ -3922,6 +3923,362 @@ describe("Agent Vault V1 Router", async () => {
});
});
+ 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);
+ };
+
+ 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 { scope: string; users: { id: string }[]; groups: { id: string }[] };
+ };
+
+ 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] });
+
+ 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] });
+
+ 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("the session reaches the bundles the user reaches, never the identity's own", async () => {
+ const projectId = await getProjectId();
+ const theirs = await createAccessBundle(`obo-theirs-${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(theirs.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 }, theirs.name)).statusCode).toBe(200);
+
+ const notTheirs = await mintFor(bot, { userId: alice.userId }, botsOnly.name);
+ expect(notTheirs.statusCode).toBe(400);
+ expect(notTheirs.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("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] });
+ 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, and never more than a day", 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);
+
+ expect((await mintFor(bot, { userId: alice.userId }, bundle.name, "24h")).statusCode).toBe(200);
+ for (const ttl of ["25h", "never"]) {
+ // eslint-disable-next-line no-await-in-loop
+ const refused = await mintFor(bot, { userId: alice.userId }, bundle.name, ttl);
+ expect(refused.statusCode).toBe(400);
+ expect(refused.json().message).toBe(
+ "A session started on behalf of a user lasts at most 24h. Set ttl to 24h or less."
+ );
+ }
+
+ // 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`, {
+ 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()}`);
+ try {
+ 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);
+
+ // 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] });
+ 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]);
+ }
+ });
+
+ 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 })] });
+
+ expect((await bot.as("GET", delegationUrl(bot.id))).statusCode).toBe(200);
+ expect((await other.as("GET", delegationUrl(bot.id))).statusCode).toBe(403);
+ expect((await other.as("PUT", delegationUrl(other.id), { scope: "all-members" })).statusCode).toBe(403);
+ expect((await bot.as("GET", delegationsUrl)).statusCode).toBe(403);
+
+ 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]);
+ }
+ });
+ });
+
describe("session resolve", async () => {
const buildResolver = (
overrides: Partial<
@@ -3936,6 +4293,7 @@ describe("Agent Vault V1 Router", async () => {
agentVaultVariableDAL: agentVaultVariableDALFactory(testDb),
agentVaultPersonalValueDAL: agentVaultPersonalValueDALFactory(testDb),
agentVaultSessionDAL: agentVaultSessionDALFactory(testDb),
+ agentVaultDelegationDAL: agentVaultDelegationDALFactory(testDb),
agentVaultSessionLogConfigDAL: agentVaultSessionLogConfigDALFactory(testDb),
membershipDAL: membershipDALFactory(testDb),
orgDAL: orgDALFactory(testDb),
@@ -4069,6 +4427,7 @@ describe("Agent Vault V1 Router", async () => {
agentVaultVariableDAL: agentVaultVariableDALFactory(testDb),
agentVaultPersonalValueDAL: agentVaultPersonalValueDALFactory(testDb),
agentVaultSessionDAL: agentVaultSessionDALFactory(testDb),
+ agentVaultDelegationDAL: agentVaultDelegationDALFactory(testDb),
agentVaultSessionLogConfigDAL: agentVaultSessionLogConfigDALFactory(testDb),
membershipDAL: membershipDALFactory(testDb),
orgDAL: orgDALFactory(testDb),
@@ -4237,6 +4596,7 @@ describe("Agent Vault V1 Router", async () => {
agentVaultVariableDAL: agentVaultVariableDALFactory(testDb),
agentVaultPersonalValueDAL: agentVaultPersonalValueDALFactory(testDb),
agentVaultSessionDAL: agentVaultSessionDALFactory(testDb),
+ agentVaultDelegationDAL: agentVaultDelegationDALFactory(testDb),
agentVaultSessionLogConfigDAL: agentVaultSessionLogConfigDALFactory(testDb),
membershipDAL: membershipDALFactory(testDb),
orgDAL: orgDALFactory(testDb),
@@ -5195,6 +5555,7 @@ describe("Agent Vault V1 Router", async () => {
agentVaultVariableDAL: agentVaultVariableDALFactory(testDb),
agentVaultPersonalValueDAL: agentVaultPersonalValueDALFactory(testDb),
agentVaultSessionDAL: agentVaultSessionDALFactory(testDb),
+ agentVaultDelegationDAL: agentVaultDelegationDALFactory(testDb),
agentVaultSessionLogConfigDAL: agentVaultSessionLogConfigDALFactory(testDb),
membershipDAL: membershipDALFactory(testDb),
orgDAL: orgDALFactory(testDb),
@@ -5295,6 +5656,7 @@ describe("Agent Vault V1 Router", async () => {
agentVaultVariableDAL: agentVaultVariableDALFactory(testDb),
agentVaultPersonalValueDAL: agentVaultPersonalValueDALFactory(testDb),
agentVaultSessionDAL: agentVaultSessionDALFactory(testDb),
+ agentVaultDelegationDAL: agentVaultDelegationDALFactory(testDb),
agentVaultSessionLogConfigDAL: agentVaultSessionLogConfigDALFactory(testDb),
membershipDAL: membershipDALFactory(testDb),
orgDAL: orgDALFactory(testDb),
diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.ts
index 51a4c4e59b..248d715230 100644
--- a/backend/src/@types/fastify.d.ts
+++ b/backend/src/@types/fastify.d.ts
@@ -7,6 +7,7 @@ import { TAccessApprovalPolicyServiceFactory } from "@app/ee/services/access-app
import { 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 { 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";
@@ -393,6 +394,7 @@ declare module "fastify" {
agentVaultSession: TAgentVaultSessionServiceFactory;
agentVaultSessionLog: TAgentVaultSessionLogServiceFactory;
agentVaultMembership: TAgentVaultMembershipServiceFactory;
+ agentVaultDelegation: TAgentVaultDelegationServiceFactory;
certManagerInstance: TCertManagerInstanceServiceFactory;
certManagerExport: TCertManagerExportServiceFactory;
certificateAuthority: TCertificateAuthorityServiceFactory;
diff --git a/backend/src/@types/knex.d.ts b/backend/src/@types/knex.d.ts
index 16b5fec5d5..82eba39ba2 100644
--- a/backend/src/@types/knex.d.ts
+++ b/backend/src/@types/knex.d.ts
@@ -23,6 +23,12 @@ import {
TAgentVaultAccessBundles,
TAgentVaultAccessBundlesInsert,
TAgentVaultAccessBundlesUpdate,
+ TAgentVaultDelegations,
+ TAgentVaultDelegationsInsert,
+ TAgentVaultDelegationSubjects,
+ TAgentVaultDelegationSubjectsInsert,
+ TAgentVaultDelegationSubjectsUpdate,
+ TAgentVaultDelegationsUpdate,
TAgentVaultPersonalValueReferences,
TAgentVaultPersonalValueReferencesInsert,
TAgentVaultPersonalValueReferencesUpdate,
@@ -1861,6 +1867,16 @@ declare module "knex/types/tables" {
TAgentVaultSessionAccessBundlesInsert,
TAgentVaultSessionAccessBundlesUpdate
>;
+ [TableName.AgentVaultDelegation]: KnexOriginal.CompositeTableType<
+ TAgentVaultDelegations,
+ TAgentVaultDelegationsInsert,
+ TAgentVaultDelegationsUpdate
+ >;
+ [TableName.AgentVaultDelegationSubject]: KnexOriginal.CompositeTableType<
+ TAgentVaultDelegationSubjects,
+ TAgentVaultDelegationSubjectsInsert,
+ TAgentVaultDelegationSubjectsUpdate
+ >;
[TableName.AgentVaultProxy]: KnexOriginal.CompositeTableType<
TAgentVaultProxies,
TAgentVaultProxiesInsert,
diff --git a/backend/src/db/migrations/20261019120000_agent-vault-delegations.ts b/backend/src/db/migrations/20261019120000_agent-vault-delegations.ts
new file mode 100644
index 0000000000..7adec08cc9
--- /dev/null
+++ b/backend/src/db/migrations/20261019120000_agent-vault-delegations.ts
@@ -0,0 +1,123 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils";
+
+const SESSION_ACTING_IDENTITY_CHECK = "agent_vault_sessions_acting_identity_check";
+
+export async function up(knex: Knex): Promise<void> {
+ // A session a machine identity starts on a user's behalf belongs to the user and names the identity here. The
+ // name is snapshotted like actorName, and it is what still marks the session as on-behalf-of once deleting the
+ // identity sets the id to NULL.
+ if (!(await knex.schema.hasColumn(TableName.AgentVaultSession, "actingIdentityId"))) {
+ await knex.schema.alterTable(TableName.AgentVaultSession, (t) => {
+ t.uuid("actingIdentityId");
+ t.foreign("actingIdentityId").references("id").inTable(TableName.Identity).onDelete("SET NULL");
+ t.string("actingIdentityName", 255);
+ });
+ await knex.raw(
+ `CREATE INDEX agent_vault_session_by_acting_identity ON ?? ("actingIdentityId") WHERE "actingIdentityId" IS NOT NULL`,
+ [TableName.AgentVaultSession]
+ );
+ // An on-behalf-of session is always a user's, and an id is never stored without the name.
+ await knex.raw(
+ `ALTER TABLE ?? ADD CONSTRAINT ?? CHECK (("actingIdentityName" IS NULL OR "identityId" IS NULL) AND ("actingIdentityId" IS NULL OR "actingIdentityName" IS NOT NULL))`,
+ [TableName.AgentVaultSession, SESSION_ACTING_IDENTITY_CHECK]
+ );
+ }
+
+ // Which users a machine identity may start sessions on behalf of: everyone in Agent Vault, or the users and
+ // groups listed in agent_vault_delegation_subjects. One row per identity.
+ if (!(await knex.schema.hasTable(TableName.AgentVaultDelegation))) {
+ await knex.schema.createTable(TableName.AgentVaultDelegation, (t) => {
+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
+
+ t.string("projectId", 36).notNullable();
+ t.foreign("projectId").references("id").inTable(TableName.Project).onDelete("CASCADE");
+ t.index("projectId");
+
+ t.uuid("identityId").notNullable();
+ t.foreign("identityId").references("id").inTable(TableName.Identity).onDelete("CASCADE");
+
+ t.string("scope", 32).notNullable();
+
+ t.timestamps(true, true, true);
+
+ // identityId leads, so the index also serves the identity foreign key's cascade.
+ t.unique(["identityId", "projectId"]);
+ });
+
+ await knex.raw(
+ `ALTER TABLE ?? ADD CONSTRAINT "agent_vault_delegations_scope_check" CHECK ("scope" IN ('all-members', 'selected'))`,
+ [TableName.AgentVaultDelegation]
+ );
+
+ await createOnUpdateTrigger(knex, TableName.AgentVaultDelegation);
+ }
+
+ if (!(await knex.schema.hasTable(TableName.AgentVaultDelegationSubject))) {
+ await knex.schema.createTable(TableName.AgentVaultDelegationSubject, (t) => {
+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
+
+ t.uuid("delegationId").notNullable();
+ t.foreign("delegationId").references("id").inTable(TableName.AgentVaultDelegation).onDelete("CASCADE");
+ t.index("delegationId");
+
+ t.uuid("userId");
+ t.foreign("userId").references("id").inTable(TableName.Users).onDelete("CASCADE");
+
+ t.uuid("groupId");
+ t.foreign("groupId").references("id").inTable(TableName.Groups).onDelete("CASCADE");
+
+ t.timestamps(true, true, true);
+ });
+
+ await knex.raw(
+ `ALTER TABLE ?? ADD CONSTRAINT "agent_vault_delegation_subjects_one_subject" CHECK (num_nonnulls("userId", "groupId") = 1)`,
+ [TableName.AgentVaultDelegationSubject]
+ );
+ // The subject column leads, so each index also serves its foreign key's cascade.
+ await knex.raw(
+ `CREATE UNIQUE INDEX "agent_vault_delegation_subjects_user_unique" ON ?? ("userId", "delegationId") WHERE "userId" IS NOT NULL`,
+ [TableName.AgentVaultDelegationSubject]
+ );
+ await knex.raw(
+ `CREATE UNIQUE INDEX "agent_vault_delegation_subjects_group_unique" ON ?? ("groupId", "delegationId") WHERE "groupId" IS NOT NULL`,
+ [TableName.AgentVaultDelegationSubject]
+ );
+
+ await createOnUpdateTrigger(knex, TableName.AgentVaultDelegationSubject);
+ }
+}
+
+export async function down(knex: Knex): Promise<void> {
+ await knex.raw(`DROP VIEW IF EXISTS analytics.??`, [TableName.AgentVaultDelegationSubject]);
+ await knex.schema.dropTableIfExists(TableName.AgentVaultDelegationSubject);
+ await dropOnUpdateTrigger(knex, TableName.AgentVaultDelegationSubject);
+
+ await knex.raw(`DROP VIEW IF EXISTS analytics.??`, [TableName.AgentVaultDelegation]);
+ await knex.schema.dropTableIfExists(TableName.AgentVaultDelegation);
+ await dropOnUpdateTrigger(knex, TableName.AgentVaultDelegation);
+
+ if (await knex.schema.hasColumn(TableName.AgentVaultSession, "actingIdentityId")) {
+ // Without the columns an on-behalf-of session reads as the user's own and would resolve with no delegation
+ // behind it, so every one still live is revoked first.
+ await knex(TableName.AgentVaultSession)
+ .whereNotNull("actingIdentityName")
+ .whereNull("revokedAt")
+ .update({ revokedAt: new Date() });
+
+ // The analytics view selects these columns, and Postgres won't drop a column a view uses.
+ await knex.raw(`DROP VIEW IF EXISTS analytics.??`, [TableName.AgentVaultSession]);
+ await knex.raw(`ALTER TABLE ?? DROP CONSTRAINT IF EXISTS ??`, [
+ TableName.AgentVaultSession,
+ SESSION_ACTING_IDENTITY_CHECK
+ ]);
+ await knex.raw(`DROP INDEX IF EXISTS agent_vault_session_by_acting_identity`);
+ await knex.schema.alterTable(TableName.AgentVaultSession, (t) => {
+ t.dropForeign(["actingIdentityId"]);
+ t.dropColumn("actingIdentityId");
+ t.dropColumn("actingIdentityName");
+ });
+ }
+}
diff --git a/backend/src/db/sanitized-schema.yaml b/backend/src/db/sanitized-schema.yaml
index 977cfc7884..ad4b60d156 100644
--- a/backend/src/db/sanitized-schema.yaml
+++ b/backend/src/db/sanitized-schema.yaml
@@ -43,6 +43,26 @@ tables:
- createdAt
- updatedAt
+ - name: agent_vault_delegation_subjects
+ source: public.agent_vault_delegation_subjects
+ columns:
+ - id
+ - delegationId
+ - userId
+ - groupId
+ - createdAt
+ - updatedAt
+
+ - name: agent_vault_delegations
+ source: public.agent_vault_delegations
+ columns:
+ - id
+ - projectId
+ - identityId
+ - scope
+ - createdAt
+ - updatedAt
+
- name: agent_vault_personal_values
source: public.agent_vault_personal_values
columns:
@@ -119,6 +139,7 @@ tables:
- userId
- identityId
- actorType
+ - actingIdentityId
- expiresAt
- revokedAt
- createdAt
diff --git a/backend/src/db/schemas/agent-vault-delegation-subjects.ts b/backend/src/db/schemas/agent-vault-delegation-subjects.ts
new file mode 100644
index 0000000000..615a7db83d
--- /dev/null
+++ b/backend/src/db/schemas/agent-vault-delegation-subjects.ts
@@ -0,0 +1,26 @@
+// Code generated by automation script, DO NOT EDIT.
+// Automated by pulling database and generating zod schema
+// To update. Just run npm run generate:schema
+// Written by akhilmhdh.
+
+import { z } from "zod";
+
+import { TImmutableDBKeys } from "./models";
+
+export const AgentVaultDelegationSubjectsSchema = z.object({
+ id: z.string().uuid(),
+ delegationId: z.string().uuid(),
+ userId: z.string().uuid().nullable().optional(),
+ groupId: z.string().uuid().nullable().optional(),
+ createdAt: z.date(),
+ updatedAt: z.date()
+});
+
+export type TAgentVaultDelegationSubjects = z.infer<typeof AgentVaultDelegationSubjectsSchema>;
+export type TAgentVaultDelegationSubjectsInsert = Omit<
+ z.input<typeof AgentVaultDelegationSubjectsSchema>,
+ TImmutableDBKeys
+>;
+export type TAgentVaultDelegationSubjectsUpdate = Partial<
+ Omit<z.input<typeof AgentVaultDelegationSubjectsSchema>, TImmutableDBKeys>
+>;
diff --git a/backend/src/db/schemas/agent-vault-delegations.ts b/backend/src/db/schemas/agent-vault-delegations.ts
new file mode 100644
index 0000000000..fc074adc4b
--- /dev/null
+++ b/backend/src/db/schemas/agent-vault-delegations.ts
@@ -0,0 +1,21 @@
+// Code generated by automation script, DO NOT EDIT.
+// Automated by pulling database and generating zod schema
+// To update. Just run npm run generate:schema
+// Written by akhilmhdh.
+
+import { z } from "zod";
+
+import { TImmutableDBKeys } from "./models";
+
+export const AgentVaultDelegationsSchema = z.object({
+ id: z.string().uuid(),
+ projectId: z.string(),
+ identityId: z.string().uuid(),
+ scope: z.string(),
+ createdAt: z.date(),
+ updatedAt: z.date()
+});
+
+export type TAgentVaultDelegations = z.infer<typeof AgentVaultDelegationsSchema>;
+export type TAgentVaultDelegationsInsert = Omit<z.input<typeof AgentVaultDelegationsSchema>, TImmutableDBKeys>;
+export type TAgentVaultDelegationsUpdate = Partial<Omit<z.input<typeof AgentVaultDelegationsSchema>, TImmutableDBKeys>>;
diff --git a/backend/src/db/schemas/agent-vault-sessions.ts b/backend/src/db/schemas/agent-vault-sessions.ts
index 740b8d2ba0..c7ef0ff01f 100644
--- a/backend/src/db/schemas/agent-vault-sessions.ts
+++ b/backend/src/db/schemas/agent-vault-sessions.ts
@@ -22,7 +22,9 @@ export const AgentVaultSessionsSchema = z.object({
createdAt: z.date(),
updatedAt: z.date(),
encryptedSessionLogKey: zodBuffer.nullable().optional(),
- actorType: z.string().nullable().optional()
+ actorType: z.string().nullable().optional(),
+ actingIdentityId: z.string().uuid().nullable().optional(),
+ actingIdentityName: z.string().nullable().optional()
});
export type TAgentVaultSessions = z.infer<typeof AgentVaultSessionsSchema>;
diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.ts
index 6cbf752782..aceb90ec4f 100644
--- a/backend/src/db/schemas/index.ts
+++ b/backend/src/db/schemas/index.ts
@@ -5,6 +5,8 @@ export * from "./access-approval-requests";
export * from "./access-approval-requests-reviewers";
export * from "./additional-privileges";
export * from "./agent-vault-access-bundles";
+export * from "./agent-vault-delegation-subjects";
+export * from "./agent-vault-delegations";
export * from "./agent-vault-personal-value-references";
export * from "./agent-vault-personal-values";
export * from "./agent-vault-proxies";
diff --git a/backend/src/db/schemas/models.ts b/backend/src/db/schemas/models.ts
index bf1f16a92f..58a3fd037d 100644
--- a/backend/src/db/schemas/models.ts
+++ b/backend/src/db/schemas/models.ts
@@ -284,6 +284,8 @@ export enum TableName {
AgentVaultPersonalValueReference = "agent_vault_personal_value_references",
AgentVaultSession = "agent_vault_sessions",
AgentVaultSessionAccessBundle = "agent_vault_session_access_bundles",
+ AgentVaultDelegation = "agent_vault_delegations",
+ AgentVaultDelegationSubject = "agent_vault_delegation_subjects",
AgentVaultProxy = "agent_vault_proxies",
AgentVaultSessionLogConfig = "agent_vault_session_log_configs",
// Dropped; kept only for the migrations that create and drop it.
diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-delegation-router.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-delegation-router.ts
new file mode 100644
index 0000000000..293e6c2d85
--- /dev/null
+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-delegation-router.ts
@@ -0,0 +1,223 @@
+import { z } from "zod";
+
+import { AgentVaultDelegationScope } from "@app/ee/services/agent-vault/agent-vault-enums";
+import { EventType } from "@app/ee/services/audit-log/audit-log-types";
+import { AGENT_VAULT } from "@app/lib/api-docs";
+import { ApiDocsTags } from "@app/lib/api-docs/constants";
+import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
+import { AuthMode } from "@app/services/auth/auth-type";
+
+import { actorContext } from "./agent-vault-router-fns";
+
+const MAX_DELEGATION_SUBJECTS = 100;
+
+const DelegationSchema = z.object({
+ machineIdentity: z
+ .object({
+ id: z.string().uuid().describe(AGENT_VAULT.DELEGATION.machineIdentityId),
+ name: z.string().describe(AGENT_VAULT.DELEGATION.machineIdentityName)
+ })
+ .describe(AGENT_VAULT.DELEGATION.machineIdentity),
+ scope: z.nativeEnum(AgentVaultDelegationScope).describe(AGENT_VAULT.DELEGATION.scope),
+ users: z
+ .object({
+ id: z.string().uuid().describe(AGENT_VAULT.DELEGATION.userId),
+ username: z.string().describe(AGENT_VAULT.DELEGATION.username),
+ email: z.string().nullable().describe(AGENT_VAULT.DELEGATION.email),
+ firstName: z.string().nullable().describe(AGENT_VAULT.DELEGATION.firstName),
+ lastName: z.string().nullable().describe(AGENT_VAULT.DELEGATION.lastName)
+ })
+ .array()
+ .describe(AGENT_VAULT.DELEGATION.users),
+ groups: z
+ .object({
+ id: z.string().uuid().describe(AGENT_VAULT.DELEGATION.groupId),
+ name: z.string().describe(AGENT_VAULT.DELEGATION.groupName)
+ })
+ .array()
+ .describe(AGENT_VAULT.DELEGATION.groups),
+ createdAt: z.date(),
+ updatedAt: z.date()
+});
+
+const machineIdentityParams = z.object({
+ machineIdentityId: z.string().uuid().describe(AGENT_VAULT.DELEGATION.machineIdentityId)
+});
+
+const auditDelegationFields = (delegation: z.infer<typeof DelegationSchema>) => ({
+ machineIdentityId: delegation.machineIdentity.id,
+ machineIdentityName: delegation.machineIdentity.name
+});
+
+// None of these accept AuthMode.OAUTH. The admin check reads the role, which a delegated token's scopes don't narrow,
+// and a delegation lets an identity act as other users, which no third-party application should be able to grant.
+export const registerAgentVaultDelegationRouter = async (server: FastifyZodProvider) => {
+ server.route({
+ method: "GET",
+ url: "/",
+ config: { rateLimit: readLimit },
+ schema: {
+ hide: false,
+ operationId: "listAgentVaultDelegations",
+ description: "List the machine identities that can start Agent Vault sessions on behalf of users",
+ tags: [ApiDocsTags.AgentVaultDelegations],
+ querystring: z.object({
+ machineIdentityIds: z
+ .string()
+ .trim()
+ .max(100 * 37)
+ .optional()
+ .transform((val) => (val ? [...new Set(val.split(",").map((id) => id.trim()))] : undefined))
+ .pipe(z.string().uuid().array().max(100).optional())
+ .describe(AGENT_VAULT.DELEGATION.machineIdentityIds),
+ limit: z.coerce.number().int().min(1).max(100).default(100).describe(AGENT_VAULT.DELEGATION.limit),
+ offset: z.coerce.number().int().min(0).max(10000).default(0).describe(AGENT_VAULT.DELEGATION.offset)
+ }),
+ response: {
+ 200: z.object({ delegations: DelegationSchema.array(), totalCount: z.number() })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) =>
+ server.services.agentVaultDelegation.listDelegations({
+ projectId: req.internalAgentVaultProjectId,
+ ctx: actorContext(req),
+ ...req.query
+ })
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:machineIdentityId",
+ config: { rateLimit: readLimit },
+ schema: {
+ hide: false,
+ operationId: "getAgentVaultDelegation",
+ description:
+ "Get which users a machine identity can start Agent Vault sessions on behalf of. A machine identity can read its own.",
+ tags: [ApiDocsTags.AgentVaultDelegations],
+ params: machineIdentityParams,
+ response: { 200: z.object({ delegation: DelegationSchema }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) =>
+ server.services.agentVaultDelegation.getDelegation({
+ projectId: req.internalAgentVaultProjectId,
+ ctx: actorContext(req),
+ machineIdentityId: req.params.machineIdentityId
+ })
+ });
+
+ server.route({
+ method: "PUT",
+ url: "/:machineIdentityId",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: false,
+ operationId: "setAgentVaultDelegation",
+ description:
+ "Set which users a machine identity can start Agent Vault sessions on behalf of, replacing any delegation it has",
+ tags: [ApiDocsTags.AgentVaultDelegations],
+ params: machineIdentityParams,
+ body: z
+ .object({
+ scope: z.nativeEnum(AgentVaultDelegationScope).describe(AGENT_VAULT.DELEGATION.scope),
+ userIds: z
+ .string()
+ .uuid()
+ .array()
+ .max(MAX_DELEGATION_SUBJECTS)
+ .default([])
+ .transform((ids) => [...new Set(ids)])
+ .describe(AGENT_VAULT.DELEGATION.userIds),
+ groupIds: z
+ .string()
+ .uuid()
+ .array()
+ .max(MAX_DELEGATION_SUBJECTS)
+ .default([])
+ .transform((ids) => [...new Set(ids)])
+ .describe(AGENT_VAULT.DELEGATION.groupIds)
+ })
+ .superRefine((val, ctx) => {
+ const named = val.userIds.length + val.groupIds.length;
+ if (val.scope === AgentVaultDelegationScope.AllMembers && named) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message:
+ "A delegation to all members names no users or groups. Remove them, or set the scope to selected."
+ });
+ }
+ if (val.scope === AgentVaultDelegationScope.Selected && !named) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "Name at least one user or group, or set the scope to all-members."
+ });
+ }
+ }),
+ response: { 200: z.object({ delegation: DelegationSchema }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const { delegation } = await server.services.agentVaultDelegation.setDelegation({
+ projectId: req.internalAgentVaultProjectId,
+ ctx: actorContext(req),
+ machineIdentityId: req.params.machineIdentityId,
+ ...req.body
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: req.internalAgentVaultProjectId,
+ event: {
+ type: EventType.AGENT_VAULT_DELEGATION_SET,
+ metadata: {
+ ...auditDelegationFields(delegation),
+ scope: delegation.scope,
+ users: delegation.users.map((user) => ({ userId: user.id, userName: user.username })),
+ groups: delegation.groups.map((group) => ({ groupId: group.id, groupName: group.name }))
+ }
+ }
+ });
+
+ return { delegation };
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: "/:machineIdentityId",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: false,
+ operationId: "deleteAgentVaultDelegation",
+ description:
+ "Stop a machine identity from starting Agent Vault sessions on behalf of users. Sessions it already started stop working.",
+ tags: [ApiDocsTags.AgentVaultDelegations],
+ params: machineIdentityParams,
+ response: { 200: z.object({ delegation: DelegationSchema }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const { delegation } = await server.services.agentVaultDelegation.deleteDelegation({
+ projectId: req.internalAgentVaultProjectId,
+ ctx: actorContext(req),
+ machineIdentityId: req.params.machineIdentityId
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: req.internalAgentVaultProjectId,
+ event: {
+ type: EventType.AGENT_VAULT_DELEGATION_DELETE,
+ metadata: auditDelegationFields(delegation)
+ }
+ });
+
+ return { delegation };
+ }
+ });
+};
diff --git 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
index 3195db7c30..f88999b6c5 100644
--- 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
@@ -7,7 +7,6 @@ import {
import { AgentVaultSessionScope, AgentVaultSessionStatus } from "@app/ee/services/agent-vault/agent-vault-enums";
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";
@@ -35,6 +34,13 @@ const SessionAccessBundleSchema = z.object({
const SessionSchema = z.object({
id: z.string().uuid().describe(AGENT_VAULT.SESSION.sessionId),
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(),
@@ -127,7 +133,8 @@ export const registerAgentVaultSessionRouter = async (server: FastifyZodProvider
schema: {
hide: false,
operationId: "createAgentVaultSession",
- description: "Create an Agent Vault session with an access bundle you can reach",
+ description:
+ "Create an Agent Vault session with an access bundle you can reach, or, as a machine identity with a delegation, on behalf of a user",
tags: [ApiDocsTags.AgentVaultSessions],
body: z.object({
accessBundles: slugSchema({ max: 64, field: "Access bundle" })
@@ -135,11 +142,13 @@ export const registerAgentVaultSessionRouter = async (server: FastifyZodProvider
.min(1)
.max(AGENT_VAULT_MAX_SESSION_BUNDLES)
.describe(AGENT_VAULT.SESSION.accessBundles),
+ // Optional rather than defaulted: the default depends on whether the session is on a user's behalf.
ttl: z
.string()
.trim()
- .default(AGENT_VAULT_SESSION_DEFAULT_TTL)
+ .optional()
.superRefine((val, ctx) => {
+ if (val === undefined) return;
if (val === AGENT_VAULT_SESSION_TTL_NEVER) return;
let parsed: number | undefined;
try {
@@ -161,7 +170,24 @@ export const registerAgentVaultSessionRouter = async (server: FastifyZodProvider
});
}
})
- .describe(AGENT_VAULT.SESSION.ttl)
+ .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(AGENT_VAULT.SESSION.onBehalfOf)
}),
response: {
200: z.object({
@@ -188,7 +214,7 @@ export const registerAgentVaultSessionRouter = async (server: FastifyZodProvider
actorName = req.auth.identityName;
}
- const { session, token } = await server.services.agentVaultSession.mintSession({
+ const { session, token, ttl, onBehalfOf } = await server.services.agentVaultSession.mintSession({
actorName,
actorEmail,
projectId: req.internalAgentVaultProjectId,
@@ -206,7 +232,12 @@ export const registerAgentVaultSessionRouter = async (server: FastifyZodProvider
sessionId: session.id,
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 })
+ })
}
}
});
@@ -216,7 +247,8 @@ export const registerAgentVaultSessionRouter = async (server: FastifyZodProvider
properties: {
sessionId: session.id,
accessBundleId: session.accessBundles[0].id,
- ttlSeconds: req.body.ttl === AGENT_VAULT_SESSION_TTL_NEVER ? null : Math.floor(ms(req.body.ttl) / 1000)
+ ttlSeconds: ttl === AGENT_VAULT_SESSION_TTL_NEVER ? null : Math.floor(ms(ttl) / 1000),
+ isOnBehalfOfUser: Boolean(onBehalfOf)
}
});
diff --git a/backend/src/ee/routes/v1/agent-vault-routers/index.ts b/backend/src/ee/routes/v1/agent-vault-routers/index.ts
index 21ead9ad82..346dbb1c7d 100644
--- a/backend/src/ee/routes/v1/agent-vault-routers/index.ts
+++ b/backend/src/ee/routes/v1/agent-vault-routers/index.ts
@@ -1,5 +1,6 @@
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 { registerAgentVaultProjectRouter } from "./agent-vault-project-router";
import { registerAgentVaultProxyAgentRouter } from "./agent-vault-proxy-agent-router";
@@ -24,6 +25,7 @@ export const registerAgentVaultRouters = async (server: FastifyZodProvider) => {
await 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" });
// Separate prefix so the preValidation project hook still matches while these routes authenticate as the proxy.
await server.register(registerAgentVaultProxyAgentRouter, { prefix: "/proxy" });
};
diff --git a/backend/src/ee/services/agent-vault-delegation/agent-vault-delegation-dal.ts b/backend/src/ee/services/agent-vault-delegation/agent-vault-delegation-dal.ts
new file mode 100644
index 0000000000..9c1fd95466
--- /dev/null
+++ b/backend/src/ee/services/agent-vault-delegation/agent-vault-delegation-dal.ts
@@ -0,0 +1,187 @@
+import { Knex } from "knex";
+
+import { TDbClient } from "@app/db";
+import { TableName, TAgentVaultDelegations } from "@app/db/schemas";
+import { DatabaseError } from "@app/lib/errors";
+import { ormify, selectAllTableCols } from "@app/lib/knex";
+
+import { AgentVaultDelegationScope } from "../agent-vault/agent-vault-enums";
+
+export type TAgentVaultDelegationDALFactory = ReturnType<typeof agentVaultDelegationDALFactory>;
+export type TAgentVaultDelegationSubjectDALFactory = ReturnType<typeof agentVaultDelegationSubjectDALFactory>;
+
+export type TAgentVaultDelegationView = {
+ id: string;
+ machineIdentity: { id: string; name: string };
+ scope: AgentVaultDelegationScope;
+ users: { id: string; username: string; email: string | null; firstName: string | null; lastName: string | null }[];
+ groups: { id: string; name: string }[];
+ createdAt: Date;
+ updatedAt: Date;
+};
+
+export const agentVaultDelegationDALFactory = (db: TDbClient) => {
+ const orm = ormify(db, TableName.AgentVaultDelegation);
+
+ // The row a conflict hits stays locked until the transaction ends, so two writes to one identity's delegation
+ // run one after the other.
+ const upsertScope = async (
+ { projectId, identityId, scope }: { projectId: string; identityId: string; scope: AgentVaultDelegationScope },
+ tx: Knex
+ ): Promise<TAgentVaultDelegations> => {
+ try {
+ const [row] = (await tx(TableName.AgentVaultDelegation)
+ .insert({ projectId, identityId, scope })
+ .onConflict(["identityId", "projectId"])
+ .merge({ scope })
+ .returning("*")) as TAgentVaultDelegations[];
+ return row;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Upsert Agent Vault delegation" });
+ }
+ };
+
+ const findViews = async (
+ {
+ projectId,
+ identityIds,
+ limit,
+ offset = 0
+ }: { projectId: string; identityIds?: string[]; limit?: number; offset?: number },
+ tx?: Knex
+ ): Promise<{ delegations: TAgentVaultDelegationView[]; totalCount: number }> => {
+ try {
+ const conn = tx || db.replicaNode();
+ const filtered = () => {
+ const query = conn(TableName.AgentVaultDelegation).where(
+ `${TableName.AgentVaultDelegation}.projectId`,
+ projectId
+ );
+ if (identityIds) void query.whereIn(`${TableName.AgentVaultDelegation}.identityId`, identityIds);
+ return query;
+ };
+
+ const countResult = (await filtered().count(`${TableName.AgentVaultDelegation}.id as count`).first()) as
+ | { count: string }
+ | undefined;
+ const totalCount = parseInt(countResult?.count || "0", 10);
+
+ const pageQuery = filtered()
+ .join(TableName.Identity, `${TableName.Identity}.id`, `${TableName.AgentVaultDelegation}.identityId`)
+ .select(
+ selectAllTableCols(TableName.AgentVaultDelegation),
+ db.ref("name").withSchema(TableName.Identity).as("identityName")
+ )
+ .orderBy(`${TableName.Identity}.name`, "asc")
+ .orderBy(`${TableName.AgentVaultDelegation}.id`, "asc");
+ if (limit !== undefined) void pageQuery.limit(limit).offset(offset);
+ const rows = (await pageQuery) as (TAgentVaultDelegations & { identityName: string })[];
+ if (!rows.length) return { delegations: [], totalCount };
+
+ const subjects = (await conn(TableName.AgentVaultDelegationSubject)
+ .whereIn(
+ `${TableName.AgentVaultDelegationSubject}.delegationId`,
+ rows.map((row) => row.id)
+ )
+ .leftJoin(TableName.Users, `${TableName.Users}.id`, `${TableName.AgentVaultDelegationSubject}.userId`)
+ .leftJoin(TableName.Groups, `${TableName.Groups}.id`, `${TableName.AgentVaultDelegationSubject}.groupId`)
+ .select(
+ db.ref("delegationId").withSchema(TableName.AgentVaultDelegationSubject),
+ db.ref("userId").withSchema(TableName.AgentVaultDelegationSubject),
+ db.ref("groupId").withSchema(TableName.AgentVaultDelegationSubject),
+ db.ref("username").withSchema(TableName.Users),
+ db.ref("email").withSchema(TableName.Users),
+ db.ref("firstName").withSchema(TableName.Users),
+ db.ref("lastName").withSchema(TableName.Users),
+ db.ref("name").withSchema(TableName.Groups).as("groupName")
+ )
+ .orderBy(`${TableName.Users}.username`, "asc")
+ .orderBy(`${TableName.Groups}.name`, "asc")) as {
+ delegationId: string;
+ userId: string | null;
+ groupId: string | null;
+ username: string | null;
+ email: string | null;
+ firstName: string | null;
+ lastName: string | null;
+ groupName: string | null;
+ }[];
+
+ const delegations = rows.map(
+ (row): TAgentVaultDelegationView => ({
+ id: row.id,
+ machineIdentity: { id: row.identityId, name: row.identityName },
+ scope: row.scope as AgentVaultDelegationScope,
+ users: subjects
+ .filter((subject) => subject.delegationId === row.id && subject.userId && subject.username)
+ .map((subject) => ({
+ id: subject.userId!,
+ username: subject.username!,
+ email: subject.email,
+ firstName: subject.firstName,
+ lastName: subject.lastName
+ })),
+ groups: subjects
+ .filter((subject) => subject.delegationId === row.id && subject.groupId && subject.groupName)
+ .map((subject) => ({ id: subject.groupId!, name: subject.groupName! })),
+ createdAt: row.createdAt,
+ updatedAt: row.updatedAt
+ })
+ );
+
+ return { delegations, totalCount };
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find Agent Vault delegations" });
+ }
+ };
+
+ /**
+ * Under all-members every user is covered, otherwise the users the delegation names and the members of the groups
+ * it names. Group membership is read the way the permission engine reads it, without isPending.
+ */
+ const coversUser = async (
+ { delegation, userId }: { delegation: Pick<TAgentVaultDelegations, "id" | "scope">; userId: string },
+ tx?: Knex
+ ): Promise<boolean> => {
+ if (delegation.scope === AgentVaultDelegationScope.AllMembers) return true;
+ try {
+ const conn = tx || db.replicaNode();
+ const subject = await conn(TableName.AgentVaultDelegationSubject)
+ .where(`${TableName.AgentVaultDelegationSubject}.delegationId`, delegation.id)
+ .where((qb) => {
+ void qb
+ .where(`${TableName.AgentVaultDelegationSubject}.userId`, userId)
+ .orWhereIn(
+ `${TableName.AgentVaultDelegationSubject}.groupId`,
+ conn(TableName.UserGroupMembership).select("groupId").where({ userId })
+ );
+ })
+ .select(db.ref("id").withSchema(TableName.AgentVaultDelegationSubject))
+ .first();
+ return Boolean(subject);
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Check Agent Vault delegation coverage" });
+ }
+ };
+
+ // False when the identity has no delegation at all.
+ const identityCoversUser = async (
+ { projectId, identityId, userId }: { projectId: string; identityId: string; userId: string },
+ tx?: Knex
+ ): Promise<boolean> => {
+ let delegation: TAgentVaultDelegations | undefined;
+ try {
+ delegation = (await (tx || db.replicaNode())(TableName.AgentVaultDelegation)
+ .where({ projectId, identityId })
+ .first()) as TAgentVaultDelegations | undefined;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find Agent Vault delegation" });
+ }
+ return delegation ? coversUser({ delegation, userId }, tx) : false;
+ };
+
+ return { ...orm, upsertScope, findViews, coversUser, identityCoversUser };
+};
+
+export const agentVaultDelegationSubjectDALFactory = (db: TDbClient) =>
+ ormify(db, TableName.AgentVaultDelegationSubject);
diff --git a/backend/src/ee/services/agent-vault-delegation/agent-vault-delegation-service.ts b/backend/src/ee/services/agent-vault-delegation/agent-vault-delegation-service.ts
new file mode 100644
index 0000000000..bcd0a62ffa
--- /dev/null
+++ b/backend/src/ee/services/agent-vault-delegation/agent-vault-delegation-service.ts
@@ -0,0 +1,211 @@
+import { AccessScope } from "@app/db/schemas";
+import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";
+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
+import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
+import { TGenericPermission } from "@app/lib/types";
+import { ActorType } from "@app/services/auth/auth-type";
+import { TMembershipDALFactory } from "@app/services/membership/membership-dal";
+
+import { AgentVaultDelegationScope } from "../agent-vault/agent-vault-enums";
+import { getAgentVaultPermission } from "../agent-vault/agent-vault-permission";
+import {
+ TAgentVaultDelegationDALFactory,
+ TAgentVaultDelegationSubjectDALFactory,
+ TAgentVaultDelegationView
+} from "./agent-vault-delegation-dal";
+import {
+ TDeleteDelegationDTO,
+ TGetDelegationDTO,
+ TListDelegationsDTO,
+ TSetDelegationDTO
+} from "./agent-vault-delegation-types";
+
+type TAgentVaultDelegationServiceFactoryDep = {
+ agentVaultDelegationDAL: Pick<
+ TAgentVaultDelegationDALFactory,
+ "upsertScope" | "findViews" | "delete" | "transaction"
+ >;
+ agentVaultDelegationSubjectDAL: Pick<TAgentVaultDelegationSubjectDALFactory, "delete" | "insertMany">;
+ membershipDAL: Pick<TMembershipDALFactory, "find" | "findOne">;
+ userGroupMembershipDAL: Pick<TUserGroupMembershipDALFactory, "find">;
+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
+};
+
+export type TAgentVaultDelegationServiceFactory = ReturnType<typeof agentVaultDelegationServiceFactory>;
+
+// The row id stays internal: a delegation is named by its machine identity, the one id a client sends back.
+const toDelegation = ({ id, ...delegation }: TAgentVaultDelegationView) => delegation;
+
+const quoted = (ids: string[]) => ids.map((id) => `'${id}'`).join(", ");
+
+export const agentVaultDelegationServiceFactory = ({
+ agentVaultDelegationDAL,
+ agentVaultDelegationSubjectDAL,
+ membershipDAL,
+ userGroupMembershipDAL,
+ permissionService
+}: TAgentVaultDelegationServiceFactoryDep) => {
+ const checkAdmin = async (projectId: string, ctx: TGenericPermission) => {
+ const { isAdmin } = await getAgentVaultPermission({ permissionService }, { projectId, ctx });
+ if (!isAdmin) {
+ throw new ForbiddenRequestError({
+ message: "Only Agent Vault admins can manage which users a machine identity acts on behalf of"
+ });
+ }
+ };
+
+ const notFound = (machineIdentityId: string) =>
+ new NotFoundError({
+ message: `Machine identity with ID '${machineIdentityId}' has no delegation, so it can't act on behalf of users`
+ });
+
+ // The same rule as granting an access bundle: a subject is named by its own Agent Vault membership.
+ const assertSubjectsInAgentVault = async ({
+ projectId,
+ userIds,
+ groupIds
+ }: {
+ projectId: string;
+ userIds: string[];
+ groupIds: string[];
+ }) => {
+ const projectScoped = (column: "actorUserId" | "actorGroupId", ids: string[]) =>
+ ids.length
+ ? membershipDAL.find({ scope: AccessScope.Project, scopeProjectId: projectId, $in: { [column]: ids } })
+ : [];
+ const [userRows, groupRows] = await Promise.all([
+ projectScoped("actorUserId", userIds),
+ projectScoped("actorGroupId", groupIds)
+ ]);
+
+ const memberGroups = new Set(groupRows.map((row) => row.actorGroupId));
+ const missingGroups = groupIds.filter((id) => !memberGroups.has(id));
+ if (missingGroups.length) {
+ throw new BadRequestError({
+ message: `Group(s) ${quoted(missingGroups)} are not members of Agent Vault. Add them under Access Control first.`
+ });
+ }
+
+ const memberUsers = new Set(userRows.map((row) => row.actorUserId));
+ const missingUsers = userIds.filter((id) => !memberUsers.has(id));
+ if (!missingUsers.length) return;
+
+ const groupMemberships = await userGroupMembershipDAL.find({ $in: { userId: missingUsers } });
+ const groupsInAgentVault = groupMemberships.length
+ ? await membershipDAL.find({
+ scope: AccessScope.Project,
+ scopeProjectId: projectId,
+ $in: { actorGroupId: [...new Set(groupMemberships.map((row) => row.groupId))] }
+ })
+ : [];
+ const memberGroupIds = new Set(groupsInAgentVault.map((row) => row.actorGroupId));
+ const throughGroup = new Set(
+ groupMemberships.filter((row) => memberGroupIds.has(row.groupId)).map((row) => row.userId)
+ );
+
+ // Both reasons in one message, so a batch that holds both is fixed in one round trip.
+ const viaGroup = missingUsers.filter((id) => throughGroup.has(id));
+ const strangers = missingUsers.filter((id) => !throughGroup.has(id));
+ const reasons: string[] = [];
+ if (viaGroup.length) {
+ reasons.push(
+ `User(s) ${quoted(viaGroup)} are in Agent Vault through a group. Name the group instead, or add them directly under Access Control first.`
+ );
+ }
+ if (strangers.length) {
+ reasons.push(`User(s) ${quoted(strangers)} are not members of Agent Vault. Add them under Access Control first.`);
+ }
+ throw new BadRequestError({ message: reasons.join(" ") });
+ };
+
+ const listDelegations = async ({ projectId, ctx, machineIdentityIds, limit, offset }: TListDelegationsDTO) => {
+ await checkAdmin(projectId, ctx);
+ const { delegations, totalCount } = await agentVaultDelegationDAL.findViews({
+ projectId,
+ identityIds: machineIdentityIds,
+ limit,
+ offset
+ });
+ return { delegations: delegations.map(toDelegation), totalCount };
+ };
+
+ // An identity may read its own, so an orchestrator can check what it was allowed before it acts.
+ const getDelegation = async ({ projectId, ctx, machineIdentityId }: TGetDelegationDTO) => {
+ const { isAdmin } = await getAgentVaultPermission({ permissionService }, { projectId, ctx });
+ const isSelf = ctx.actor === ActorType.IDENTITY && ctx.actorId === machineIdentityId;
+ if (!isAdmin && !isSelf) {
+ throw new ForbiddenRequestError({
+ message: "Only Agent Vault admins, and the machine identity itself, can read a machine identity's delegation"
+ });
+ }
+
+ const {
+ delegations: [delegation]
+ } = await agentVaultDelegationDAL.findViews({ projectId, identityIds: [machineIdentityId] });
+ if (!delegation) throw notFound(machineIdentityId);
+ return { delegation: toDelegation(delegation) };
+ };
+
+ const setDelegation = async ({ projectId, ctx, machineIdentityId, scope, userIds, groupIds }: TSetDelegationDTO) => {
+ await checkAdmin(projectId, ctx);
+
+ // Project-scoped, so an identity from another org is a 404 like one that doesn't exist.
+ const identityMembership = await membershipDAL.findOne({
+ scope: AccessScope.Project,
+ scopeProjectId: projectId,
+ actorIdentityId: machineIdentityId
+ });
+ if (!identityMembership) {
+ throw new NotFoundError({
+ message: `Machine identity with ID '${machineIdentityId}' is not a member of Agent Vault. Add it under Access Control first.`
+ });
+ }
+
+ if (scope === AgentVaultDelegationScope.Selected) {
+ await assertSubjectsInAgentVault({ projectId, userIds, groupIds });
+ }
+
+ const delegation = await agentVaultDelegationDAL.transaction(async (tx) => {
+ const row = await agentVaultDelegationDAL.upsertScope({ projectId, identityId: machineIdentityId, scope }, tx);
+
+ // A write replaces the whole list, so a subject left out is no longer covered.
+ await agentVaultDelegationSubjectDAL.delete({ delegationId: row.id }, tx);
+ const subjects =
+ scope === AgentVaultDelegationScope.Selected
+ ? [
+ ...userIds.map((userId) => ({ delegationId: row.id, userId })),
+ ...groupIds.map((groupId) => ({ delegationId: row.id, groupId }))
+ ]
+ : [];
+ if (subjects.length) await agentVaultDelegationSubjectDAL.insertMany(subjects, tx);
+
+ const {
+ delegations: [written]
+ } = await agentVaultDelegationDAL.findViews({ projectId, identityIds: [machineIdentityId] }, tx);
+ return written;
+ });
+
+ return { delegation: toDelegation(delegation) };
+ };
+
+ const deleteDelegation = async ({ projectId, ctx, machineIdentityId }: TDeleteDelegationDTO) => {
+ await checkAdmin(projectId, ctx);
+
+ const deleted = await agentVaultDelegationDAL.transaction(async (tx) => {
+ const {
+ delegations: [delegation]
+ } = await agentVaultDelegationDAL.findViews({ projectId, identityIds: [machineIdentityId] }, tx);
+ if (!delegation) return undefined;
+
+ // Two concurrent deletes both read it; only the one whose delete removed the row reports it, so the audit
+ // trail holds a single deletion.
+ const removed = await agentVaultDelegationDAL.delete({ id: delegation.id }, tx);
+ return removed.length ? delegation : undefined;
+ });
+ if (!deleted) throw notFound(machineIdentityId);
+
+ return { delegation: toDelegation(deleted) };
+ };
+
+ return { listDelegations, getDelegation, setDelegation, deleteDelegation };
+};
diff --git a/backend/src/ee/services/agent-vault-delegation/agent-vault-delegation-types.ts b/backend/src/ee/services/agent-vault-delegation/agent-vault-delegation-types.ts
new file mode 100644
index 0000000000..330be63b66
--- /dev/null
+++ b/backend/src/ee/services/agent-vault-delegation/agent-vault-delegation-types.ts
@@ -0,0 +1,26 @@
+import { TGenericPermission } from "@app/lib/types";
+
+import { AgentVaultDelegationScope } from "../agent-vault/agent-vault-enums";
+
+type TAgentVaultDelegationScoped = {
+ projectId: string;
+ ctx: TGenericPermission;
+};
+
+export type TListDelegationsDTO = TAgentVaultDelegationScoped & {
+ machineIdentityIds?: string[];
+ limit: number;
+ offset: number;
+};
+
+export type TGetDelegationDTO = TAgentVaultDelegationScoped & {
+ machineIdentityId: string;
+};
+
+export type TSetDelegationDTO = TGetDelegationDTO & {
+ scope: AgentVaultDelegationScope;
+ userIds: string[];
+ groupIds: string[];
+};
+
+export type TDeleteDelegationDTO = TGetDelegationDTO;
diff --git a/backend/src/ee/services/agent-vault-member/agent-vault-membership-service.test.ts b/backend/src/ee/services/agent-vault-member/agent-vault-membership-service.test.ts
index 09c85d46ee..79434a8e33 100644
--- a/backend/src/ee/services/agent-vault-member/agent-vault-membership-service.test.ts
+++ b/backend/src/ee/services/agent-vault-member/agent-vault-membership-service.test.ts
@@ -106,7 +106,8 @@ const buildService = ({
usageMeteringService: { emitForProject: vi.fn() },
agentVaultPersonalValueDAL: { deleteForActorsWithoutGrant: vi.fn().mockResolvedValue(0) },
userGroupMembershipDAL: { find: vi.fn().mockResolvedValue([]) },
- identityGroupMembershipDAL: { find: vi.fn().mockResolvedValue([]) }
+ identityGroupMembershipDAL: { find: vi.fn().mockResolvedValue([]) },
+ agentVaultDelegationDAL: { delete: vi.fn().mockResolvedValue([]) }
};
const service = agentVaultMembershipServiceFactory(
@@ -196,6 +197,22 @@ describe("agentVaultMembership guards", () => {
);
});
+ // A delegation left in place would let the identity act for users again the moment it is added back.
+ test("deletes the delegation of an identity it removes, in the same transaction", async () => {
+ const { service, deps, txs } = buildService({
+ identityProjectId: null,
+ productMemberships: [{ id: "mem-1" }],
+ adminMembershipIds: ["mem-other"]
+ });
+
+ await service.revokeProductMembers({ projectId: PROJECT_ID, ...addIds, ctx });
+
+ expect(deps.agentVaultDelegationDAL.delete).toHaveBeenCalledWith(
+ { projectId: PROJECT_ID, $in: { identityId: [IDENTITY_ID] } },
+ txs[0]
+ );
+ });
+
// A sub-organization reaches one of its parent's groups through a membership of its own, and the group
// row keeps pointing at the parent. Judging it by that row refused every linked group.
test("accepts a group the organization reaches but does not own", async () => {
diff --git a/backend/src/ee/services/agent-vault-member/agent-vault-membership-service.ts b/backend/src/ee/services/agent-vault-member/agent-vault-membership-service.ts
index c1f1c8d431..14cb5e73f9 100644
--- a/backend/src/ee/services/agent-vault-member/agent-vault-membership-service.ts
+++ b/backend/src/ee/services/agent-vault-member/agent-vault-membership-service.ts
@@ -35,6 +35,7 @@ import { resolveUsersBySsoExternalId } from "@app/services/user-alias/user-alias
import { resolveAgentVaultActorNames, TAgentVaultActorName } from "../agent-vault/agent-vault-actor-name-fns";
import { AgentVaultMemberType } from "../agent-vault/agent-vault-enums";
+import { TAgentVaultDelegationDALFactory } from "../agent-vault-delegation/agent-vault-delegation-dal";
import {
clearPersonalValuesAfterRevoke,
TClearPersonalValuesDeps
@@ -53,6 +54,7 @@ type TAgentVaultMembershipServiceFactoryDep = {
orgDAL: Pick<TOrgDALFactory, "findById">;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
usageMeteringService: Pick<TUsageMeteringServiceFactory, "emitForProject">;
+ agentVaultDelegationDAL: Pick<TAgentVaultDelegationDALFactory, "delete">;
} & TClearPersonalValuesDeps;
export type TAgentVaultMembershipServiceFactory = ReturnType<typeof agentVaultMembershipServiceFactory>;
@@ -142,7 +144,8 @@ export const agentVaultMembershipServiceFactory = ({
usageMeteringService,
agentVaultPersonalValueDAL,
userGroupMembershipDAL,
- identityGroupMembershipDAL
+ identityGroupMembershipDAL,
+ agentVaultDelegationDAL
}: TAgentVaultMembershipServiceFactoryDep) => {
const getActorPermission = (projectId: string, ctx: TGenericPermission) =>
permissionService.getProjectPermission({
@@ -672,6 +675,13 @@ export const agentVaultMembershipServiceFactory = ({
// membership_roles cascades on the membership FK, so the roles go with these rows.
await membershipDAL.delete({ $in: { id: membershipIds } }, tx);
+ // A delegation left behind would come back with a later add, so an identity rejoining acts for no one until an
+ // admin allows it again.
+ const removedIdentityIds = named(held, AgentVaultMemberType.MachineIdentity);
+ if (removedIdentityIds.length) {
+ await agentVaultDelegationDAL.delete({ projectId, $in: { identityId: removedIdentityIds } }, tx);
+ }
+
// Their bundle grants went above. Their own variables stay, as they would if they only lost a bundle.
await clearPersonalValuesAfterRevoke(
{ agentVaultPersonalValueDAL, userGroupMembershipDAL, identityGroupMembershipDAL },
diff --git a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.ts b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.ts
index 8767065d20..f35eeb94ac 100644
--- 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
@@ -34,6 +34,7 @@ import { findReachableAccessBundleIds, liveGroupIdsFrom } from "../agent-vault/a
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 { 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";
@@ -80,6 +81,7 @@ type TAgentVaultProxyServiceFactoryDep = {
agentVaultVariableDAL: Pick<TAgentVaultVariableDALFactory, "findValuesForResolve">;
agentVaultPersonalValueDAL: Pick<TAgentVaultPersonalValueDALFactory, "findForResolve">;
agentVaultSessionDAL: Pick<TAgentVaultSessionDALFactory, "findByTokenHash">;
+ agentVaultDelegationDAL: Pick<TAgentVaultDelegationDALFactory, "identityCoversUser">;
agentVaultSessionLogConfigDAL: Pick<TAgentVaultSessionLogConfigDALFactory, "findOne" | "findByProjectIdFromPrimary">;
membershipDAL: Pick<TMembershipDALFactory, "findResourceMembershipsForActor">;
orgDAL: Pick<TOrgDALFactory, "findEffectiveOrgMembership">;
@@ -124,6 +126,7 @@ export const agentVaultProxyServiceFactory = ({
agentVaultVariableDAL,
agentVaultPersonalValueDAL,
agentVaultSessionDAL,
+ agentVaultDelegationDAL,
agentVaultSessionLogConfigDAL,
membershipDAL,
orgDAL,
@@ -627,6 +630,56 @@ export const agentVaultProxyServiceFactory = ({
return 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.
+ const $assertActingIdentityStillDelegated = async ({
+ projectId,
+ orgId,
+ userId,
+ actingIdentityId
+ }: {
+ projectId: string;
+ orgId: string;
+ userId: string | null;
+ actingIdentityId: 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();
+
+ try {
+ const { permission } = 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();
+ }
+ } catch (error) {
+ if (error instanceof ForbiddenRequestError && error.name === "ProjectMembershipNotFound") throw refused();
+ throw error;
+ }
+
+ if (!(await agentVaultDelegationDAL.identityCoversUser({ projectId, identityId: actingIdentityId, userId }))) {
+ throw refused();
+ }
+ };
+
/** 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) => {
const session = await agentVaultSessionDAL.findByTokenHash(hashSessionToken(sessionToken));
@@ -648,6 +701,15 @@ export const agentVaultProxyServiceFactory = ({
if (!session.userId && !session.identityId) {
throw new UnauthorizedError({ message: "The identity this session belonged to has been deleted" });
}
+ // The name marks an on-behalf-of session even after deleting the identity nulls its id.
+ if (session.actingIdentityName) {
+ await $assertActingIdentityStillDelegated({
+ projectId: session.projectId,
+ orgId,
+ userId: session.userId ?? null,
+ actingIdentityId: session.actingIdentityId ?? null
+ });
+ }
const actor = session.userId
? { type: ActorType.USER as const, id: session.userId }
diff --git a/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-service.ts b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-service.ts
index 30c48cd079..faf9bae0ea 100644
--- a/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-service.ts
+++ b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-service.ts
@@ -27,7 +27,7 @@ import { ObjectStorageType } from "@app/services/object-storage/object-storage-t
import { getAgentVaultPermission } from "../agent-vault/agent-vault-permission";
import { TAgentVaultProxyDALFactory } from "../agent-vault-proxy/agent-vault-proxy-dal";
import { TAgentVaultSessionDALFactory } from "../agent-vault-session/agent-vault-session-dal";
-import { isOwnerlessSession, isSessionOwnedBy } from "../agent-vault-session/agent-vault-session-fns";
+import { isOrphanedSession, isSessionOwnedBy } from "../agent-vault-session/agent-vault-session-fns";
import { TAgentVaultSessionLogConfigDALFactory } from "./agent-vault-session-log-config-dal";
import {
AGENT_VAULT_SESSION_LOG_CHUNK_ID_TIME_TOLERANCE_MS,
@@ -189,7 +189,7 @@ export const agentVaultSessionLogServiceFactory = ({
const retirements = [
session.revokedAt,
session.expiresAt && session.expiresAt <= now ? session.expiresAt : null,
- isOwnerlessSession(session) ? session.updatedAt : null
+ isOrphanedSession(session) ? session.updatedAt : null
]
.filter((at): at is Date => Boolean(at))
.map((at) => at.getTime());
diff --git 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
index 48946623d7..956ad26b38 100644
--- 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
@@ -8,7 +8,7 @@ import { ormify } from "@app/lib/knex";
import { ActorType } from "@app/services/auth/auth-type";
import { AgentVaultMemberType, AgentVaultSessionStatus } from "../agent-vault/agent-vault-enums";
-import { TAgentVaultSessionActor } from "./agent-vault-session-types";
+import { TAgentVaultSessionActingIdentity, TAgentVaultSessionActor } from "./agent-vault-session-types";
export type TAgentVaultSessionDALFactory = ReturnType<typeof agentVaultSessionDALFactory>;
@@ -16,39 +16,63 @@ export type TAgentVaultSessionListRow = {
id: string;
userId: string | null;
identityId: string | null;
+ actingIdentityId: string | null;
+ actingIdentityName: string | null;
actor: TAgentVaultSessionActor;
+ actingIdentity: TAgentVaultSessionActingIdentity | null;
expiresAt: Date | null;
revokedAt: Date | null;
createdAt: Date;
accessBundles: { id: string | null; name: string; position: number }[];
};
-// Mirrors deriveSessionStatus: a session with neither actor id counts as revoked.
-const ownerless = (qb: Knex.QueryBuilder) =>
- void qb.whereNull(`${TableName.AgentVaultSession}.userId`).whereNull(`${TableName.AgentVaultSession}.identityId`);
-const owned = (qb: Knex.QueryBuilder) =>
+// The acting identity's own alias, since the actor's identity is joined under the table's name.
+const ACTING_IDENTITY = "actingIdentity";
+
+// Mirrors deriveSessionStatus: a session with neither actor id, or whose acting identity was deleted, counts as revoked.
+const orphaned = (qb: Knex.QueryBuilder) =>
+ void qb
+ .where((sub) => {
+ void sub
+ .whereNull(`${TableName.AgentVaultSession}.userId`)
+ .whereNull(`${TableName.AgentVaultSession}.identityId`);
+ })
+ .orWhere((sub) => {
+ void sub
+ .whereNotNull(`${TableName.AgentVaultSession}.actingIdentityName`)
+ .whereNull(`${TableName.AgentVaultSession}.actingIdentityId`);
+ });
+const live = (qb: Knex.QueryBuilder) =>
void qb
- .whereNotNull(`${TableName.AgentVaultSession}.userId`)
- .orWhereNotNull(`${TableName.AgentVaultSession}.identityId`);
+ .where((sub) => {
+ void sub
+ .whereNotNull(`${TableName.AgentVaultSession}.userId`)
+ .orWhereNotNull(`${TableName.AgentVaultSession}.identityId`);
+ })
+ .where((sub) => {
+ void sub
+ .whereNull(`${TableName.AgentVaultSession}.actingIdentityName`)
+ .orWhereNotNull(`${TableName.AgentVaultSession}.actingIdentityId`);
+ });
const statusFilter = (query: Knex.QueryBuilder, status: AgentVaultSessionStatus, now: Date) => {
if (status === AgentVaultSessionStatus.Revoked) {
void query.where((qb) => {
- void qb.whereNotNull(`${TableName.AgentVaultSession}.revokedAt`).orWhere(ownerless);
+ void qb.whereNotNull(`${TableName.AgentVaultSession}.revokedAt`).orWhere(orphaned);
});
return;
}
if (status === AgentVaultSessionStatus.Expired) {
void query
.whereNull(`${TableName.AgentVaultSession}.revokedAt`)
- .where(owned)
+ .where(live)
.whereNotNull(`${TableName.AgentVaultSession}.expiresAt`)
.where(`${TableName.AgentVaultSession}.expiresAt`, "<=", now);
return;
}
void query
.whereNull(`${TableName.AgentVaultSession}.revokedAt`)
- .where(owned)
+ .where(live)
.where((qb) => {
void qb
.whereNull(`${TableName.AgentVaultSession}.expiresAt`)
@@ -137,7 +161,14 @@ export const agentVaultSessionDALFactory = (db: TDbClient) => {
void query.where(`${TableName.AgentVaultSession}.projectId`, projectId);
if (sessionId) void query.where(`${TableName.AgentVaultSession}.id`, sessionId);
if (actor?.type === ActorType.USER) void query.where(`${TableName.AgentVaultSession}.userId`, actor.id);
- if (actor?.type === ActorType.IDENTITY) void query.where(`${TableName.AgentVaultSession}.identityId`, actor.id);
+ // An identity's own sessions, and the ones it started on a user's behalf.
+ if (actor?.type === ActorType.IDENTITY) {
+ void query.where((qb) => {
+ void qb
+ .where(`${TableName.AgentVaultSession}.identityId`, actor.id)
+ .orWhere(`${TableName.AgentVaultSession}.actingIdentityId`, actor.id);
+ });
+ }
if (statuses?.length) {
void query.where((qb) => {
statuses.forEach((status) => {
@@ -152,7 +183,12 @@ export const agentVaultSessionDALFactory = (db: TDbClient) => {
// snapshot alone would miss a renamed actor and match a name no longer shown.
void query
.leftJoin(TableName.Users, `${TableName.AgentVaultSession}.userId`, `${TableName.Users}.id`)
- .leftJoin(TableName.Identity, `${TableName.AgentVaultSession}.identityId`, `${TableName.Identity}.id`);
+ .leftJoin(TableName.Identity, `${TableName.AgentVaultSession}.identityId`, `${TableName.Identity}.id`)
+ .leftJoin(
+ `${TableName.Identity} as ${ACTING_IDENTITY}`,
+ `${TableName.AgentVaultSession}.actingIdentityId`,
+ `${ACTING_IDENTITY}.id`
+ );
void query.where((qb) => {
void qb
@@ -166,6 +202,8 @@ export const agentVaultSessionDALFactory = (db: TDbClient) => {
])
.orWhereILike(`${TableName.AgentVaultSession}.actorName`, term)
.orWhereILike(`${TableName.AgentVaultSession}.actorEmail`, term)
+ .orWhereILike(`${ACTING_IDENTITY}.name`, term)
+ .orWhereILike(`${TableName.AgentVaultSession}.actingIdentityName`, term)
.orWhereExists((sub) => {
void sub
.select(db.raw("1"))
@@ -212,6 +250,11 @@ export const agentVaultSessionDALFactory = (db: TDbClient) => {
)
.leftJoin(TableName.Users, `${TableName.AgentVaultSession}.userId`, `${TableName.Users}.id`)
.leftJoin(TableName.Identity, `${TableName.AgentVaultSession}.identityId`, `${TableName.Identity}.id`)
+ .leftJoin(
+ `${TableName.Identity} as ${ACTING_IDENTITY}`,
+ `${TableName.AgentVaultSession}.actingIdentityId`,
+ `${ACTING_IDENTITY}.id`
+ )
.leftJoin(
TableName.AgentVaultSessionAccessBundle,
`${TableName.AgentVaultSessionAccessBundle}.sessionId`,
@@ -239,6 +282,9 @@ export const agentVaultSessionDALFactory = (db: TDbClient) => {
db.ref("name").withSchema(TableName.Identity).as("identityName"),
db.ref("actorName").withSchema(TableName.AgentVaultSession),
db.ref("actorEmail").withSchema(TableName.AgentVaultSession),
+ db.ref("actingIdentityId").withSchema(TableName.AgentVaultSession),
+ db.ref("actingIdentityName").withSchema(TableName.AgentVaultSession),
+ db.ref("name").withSchema(ACTING_IDENTITY).as("actingIdentityLiveName"),
db.ref("accessBundleId").withSchema(TableName.AgentVaultSessionAccessBundle),
db.ref("accessBundleName").withSchema(TableName.AgentVaultSessionAccessBundle),
db.ref("name").withSchema(TableName.AgentVaultAccessBundle).as("liveAccessBundleName"),
@@ -260,6 +306,9 @@ export const agentVaultSessionDALFactory = (db: TDbClient) => {
identityName: string | null;
actorName: string;
actorEmail: string | null;
+ actingIdentityId: string | null;
+ actingIdentityName: string | null;
+ actingIdentityLiveName: string | null;
accessBundleId: string | null;
accessBundleName: string | null;
liveAccessBundleName: string | null;
@@ -274,7 +323,12 @@ export const agentVaultSessionDALFactory = (db: TDbClient) => {
id: row.id,
userId: row.userId,
identityId: row.identityId,
+ actingIdentityId: row.actingIdentityId,
+ actingIdentityName: row.actingIdentityName,
actor: toSessionActor(row),
+ actingIdentity: row.actingIdentityName
+ ? { id: row.actingIdentityId, name: row.actingIdentityLiveName ?? row.actingIdentityName }
+ : null,
expiresAt: row.expiresAt,
revokedAt: row.revokedAt,
createdAt: row.createdAt,
diff --git 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
new file mode 100644
index 0000000000..00061a4dbe
--- /dev/null
+++ b/backend/src/ee/services/agent-vault-session/agent-vault-session-fns.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, test } from "vitest";
+
+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";
+
+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);
+ });
+
+ 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);
+ });
+});
diff --git a/backend/src/ee/services/agent-vault-session/agent-vault-session-fns.ts b/backend/src/ee/services/agent-vault-session/agent-vault-session-fns.ts
index f8d9722db9..36c8e00cce 100644
--- a/backend/src/ee/services/agent-vault-session/agent-vault-session-fns.ts
+++ b/backend/src/ee/services/agent-vault-session/agent-vault-session-fns.ts
@@ -14,23 +14,30 @@ export const generateSessionToken = () => {
return { token, tokenHash: hashSessionToken(token) };
};
-// The actor columns are SET NULL when the owner is deleted, so the row outlives them. Resolve refuses such
-// a session; the status says the same, or the list would show it Active with nobody left to revoke it.
-export const isOwnerlessSession = (session: { userId?: string | null; identityId?: string | null }) =>
- !session.userId && !session.identityId;
-
-export const isSessionOwnedBy = (
- ctx: { actor: ActorType; actorId: string },
- session: { userId?: string | null; identityId?: string | null }
-) =>
+type TSessionOwnerColumns = {
+ userId?: string | null;
+ identityId?: string | null;
+ actingIdentityId?: string | null;
+ actingIdentityName?: string | null;
+};
+
+// The actor columns are SET NULL when the owner is deleted, so the row outlives them, and an on-behalf-of session
+// keeps its acting identity's name once that identity is deleted. Resolve refuses either; the status says the same,
+// or the list would show it Active when nothing can use it.
+export const isOrphanedSession = (session: TSessionOwnerColumns) =>
+ (!session.userId && !session.identityId) || (Boolean(session.actingIdentityName) && !session.actingIdentityId);
+
+// The machine identity that started a session on a user's behalf holds it alongside the user.
+export const isSessionOwnedBy = (ctx: { actor: ActorType; actorId: string }, session: TSessionOwnerColumns) =>
(ctx.actor === ActorType.USER && session.userId === ctx.actorId) ||
- (ctx.actor === ActorType.IDENTITY && session.identityId === ctx.actorId);
+ (ctx.actor === ActorType.IDENTITY &&
+ (session.identityId === ctx.actorId || session.actingIdentityId === ctx.actorId));
export const deriveSessionStatus = (
- session: { expiresAt: Date | null; revokedAt: Date | null; userId?: string | null; identityId?: string | null },
+ session: { expiresAt: Date | null; revokedAt: Date | null } & TSessionOwnerColumns,
now = new Date()
): AgentVaultSessionStatus => {
- if (session.revokedAt || isOwnerlessSession(session)) return AgentVaultSessionStatus.Revoked;
+ if (session.revokedAt || isOrphanedSession(session)) return AgentVaultSessionStatus.Revoked;
if (session.expiresAt && session.expiresAt <= now) return AgentVaultSessionStatus.Expired;
return AgentVaultSessionStatus.Active;
};
diff --git a/backend/src/ee/services/agent-vault-session/agent-vault-session-service.ts b/backend/src/ee/services/agent-vault-session/agent-vault-session-service.ts
index 637e46ee1a..903698e12c 100644
--- a/backend/src/ee/services/agent-vault-session/agent-vault-session-service.ts
+++ b/backend/src/ee/services/agent-vault-session/agent-vault-session-service.ts
@@ -1,5 +1,6 @@
import { ForbiddenError } from "@casl/ability";
+import { OrgMembershipStatus } from "@app/db/schemas";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import {
ProjectPermissionAgentVaultSessionActions,
@@ -8,18 +9,28 @@ import {
import { crypto } from "@app/lib/crypto/cryptography";
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
import { ms } from "@app/lib/ms";
+import { TGenericPermission } from "@app/lib/types";
import { ActorType } from "@app/services/auth/auth-type";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { TMembershipDALFactory } from "@app/services/membership/membership-dal";
+import { TOrgDALFactory } from "@app/services/org/org-dal";
+import { TUserDALFactory } from "@app/services/user/user-dal";
import { AgentVaultMemberType, AgentVaultSessionScope } from "../agent-vault/agent-vault-enums";
import { getAgentVaultPermission, getAgentVaultReachability } from "../agent-vault/agent-vault-permission";
import { TAgentVaultAccessBundleDALFactory } from "../agent-vault-access-bundle/agent-vault-access-bundle-dal";
+import { TAgentVaultDelegationDALFactory } from "../agent-vault-delegation/agent-vault-delegation-dal";
import { generateSessionLogKey, wrapSessionLogKey } from "../agent-vault-session-log/agent-vault-session-log-secrets";
import { TAgentVaultSessionAccessBundleDALFactory } from "./agent-vault-session-access-bundle-dal";
import { TAgentVaultSessionDALFactory, TAgentVaultSessionListRow } from "./agent-vault-session-dal";
import { deriveSessionStatus, generateSessionToken } from "./agent-vault-session-fns";
-import { TGetSessionByIdDTO, TListSessionsDTO, TMintSessionDTO, TRevokeSessionDTO } from "./agent-vault-session-types";
+import {
+ TGetSessionByIdDTO,
+ TListSessionsDTO,
+ TMintSessionDTO,
+ TOnBehalfOfUser,
+ TRevokeSessionDTO
+} from "./agent-vault-session-types";
// V1 ships one bundle per session; the junction table, `position` and the proxy matcher all handle more.
export const AGENT_VAULT_MAX_SESSION_BUNDLES = 1;
@@ -28,12 +39,19 @@ export const AGENT_VAULT_SESSION_TTL_NEVER = "never";
// Past roughly 1e8 days the expiry overflows Date and Postgres rejects the row as a 500. A century is
// far beyond any real lifetime and keeps the message honest; "never" exists for no expiry at all.
export const AGENT_VAULT_SESSION_MAX_TTL_MS = 100 * 365 * 24 * 60 * 60 * 1000;
+// The user an on-behalf-of session acts for didn't start it and may not know it exists, so it is short by default
+// and never outlives a day.
+export const AGENT_VAULT_ON_BEHALF_OF_SESSION_DEFAULT_TTL = "1h";
+export const AGENT_VAULT_ON_BEHALF_OF_SESSION_MAX_TTL = "24h";
type TAgentVaultSessionServiceFactoryDep = {
agentVaultSessionDAL: TAgentVaultSessionDALFactory;
agentVaultSessionAccessBundleDAL: TAgentVaultSessionAccessBundleDALFactory;
agentVaultAccessBundleDAL: Pick<TAgentVaultAccessBundleDALFactory, "find">;
+ agentVaultDelegationDAL: Pick<TAgentVaultDelegationDALFactory, "findOne" | "coversUser">;
membershipDAL: Pick<TMembershipDALFactory, "findResourceMembershipsForActor">;
+ userDAL: Pick<TUserDALFactory, "findOne">;
+ orgDAL: Pick<TOrgDALFactory, "findEffectiveOrgMembership">;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
kmsService: Pick<TKmsServiceFactory, "wrapKey">;
};
@@ -44,7 +62,10 @@ export const agentVaultSessionServiceFactory = ({
agentVaultSessionDAL,
agentVaultSessionAccessBundleDAL,
agentVaultAccessBundleDAL,
+ agentVaultDelegationDAL,
membershipDAL,
+ userDAL,
+ orgDAL,
permissionService,
kmsService
}: TAgentVaultSessionServiceFactoryDep) => {
@@ -55,22 +76,141 @@ export const agentVaultSessionServiceFactory = ({
return { 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 }: TMintSessionDTO) => {
- const actor = requireSessionActor(ctx);
- const { permission, accessBundleIds: reachable } = await getAgentVaultReachability(
- { permissionService, membershipDAL },
- { projectId, ctx }
+ // The delegation is checked before the user is looked up, so an identity no admin delegated learns nothing about
+ // who is in the org, and a user who doesn't exist reads exactly like one the delegation doesn't cover.
+ const resolveOnBehalfOfUser = async ({
+ projectId,
+ ctx,
+ onBehalfOf
+ }: {
+ projectId: string;
+ ctx: TGenericPermission;
+ onBehalfOf: TOnBehalfOfUser;
+ }) => {
+ if (ctx.actor !== ActorType.IDENTITY) {
+ throw new BadRequestError({ message: "Only a machine identity can start a session on behalf of a user" });
+ }
+
+ const delegation = await agentVaultDelegationDAL.findOne({ projectId, identityId: ctx.actorId });
+ if (!delegation) {
+ throw new ForbiddenRequestError({
+ message:
+ "This machine identity isn't allowed to start sessions on behalf of users. An Agent Vault admin can allow it by setting its delegation under Access Control."
+ });
+ }
+
+ const identifier = onBehalfOf.userId ?? onBehalfOf.userEmail ?? "";
+ const notCovered = () =>
+ new ForbiddenRequestError({
+ message: `This machine identity can't start sessions on behalf of '${identifier}'. Check the user's ID or email, or ask an Agent Vault admin to add them to the identity's delegation.`
+ });
+
+ const user = await userDAL.findOne(
+ onBehalfOf.userId ? { id: onBehalfOf.userId, isGhost: false } : { username: onBehalfOf.userEmail, isGhost: false }
);
+ if (!user) throw notCovered();
+
+ // Resolve refuses a session whose actor isn't an active, accepted org member, so mint does too.
+ const orgMembership = await orgDAL.findEffectiveOrgMembership({
+ actorType: ActorType.USER,
+ actorId: user.id,
+ orgId: ctx.actorOrgId,
+ status: OrgMembershipStatus.Accepted
+ });
+ if (!orgMembership?.isActive) throw notCovered();
+
+ if (!(await agentVaultDelegationDAL.coversUser({ delegation, userId: user.id }))) throw notCovered();
+
+ // The session reaches what the user reaches, so their own role and grants decide the bundle, never the
+ // identity's. actorAuthMethod is null as in resolve: the session row stores no auth method.
+ const userCtx: TGenericPermission = {
+ actor: ActorType.USER,
+ actorId: user.id,
+ actorOrgId: ctx.actorOrgId,
+ actorAuthMethod: null
+ };
+ let reachability: Awaited<ReturnType<typeof getAgentVaultReachability>>;
+ try {
+ reachability = await getAgentVaultReachability({ permissionService, membershipDAL }, { projectId, ctx: userCtx });
+ } catch (error) {
+ if (error instanceof ForbiddenRequestError && error.name === "ProjectMembershipNotFound") {
+ throw new BadRequestError({
+ message: `'${identifier}' doesn't have access to Agent Vault, so no session can be started on their behalf. An Agent Vault admin can add them under Access Control.`
+ });
+ }
+ throw error;
+ }
+ // Not thrown through CASL: the denial would be recorded against the identity making the request.
+ if (
+ !reachability.permission.can(
+ ProjectPermissionAgentVaultSessionActions.Create,
+ ProjectPermissionSub.AgentVaultSessions
+ )
+ ) {
+ throw new ForbiddenRequestError({
+ message: `'${identifier}' can't start Agent Vault sessions, so no session can be started on their behalf.`
+ });
+ }
+
+ return { user, accessBundleIds: reachability.accessBundleIds };
+ };
+
+ const resolveSessionTtl = (ttl: string | undefined, isOnBehalfOf: boolean) => {
+ if (!isOnBehalfOf) return ttl ?? AGENT_VAULT_SESSION_DEFAULT_TTL;
+
+ const resolved = ttl ?? AGENT_VAULT_ON_BEHALF_OF_SESSION_DEFAULT_TTL;
+ if (resolved === AGENT_VAULT_SESSION_TTL_NEVER || ms(resolved) > ms(AGENT_VAULT_ON_BEHALF_OF_SESSION_MAX_TTL)) {
+ throw new BadRequestError({
+ message: `A session started on behalf of a user lasts at most ${AGENT_VAULT_ON_BEHALF_OF_SESSION_MAX_TTL}. Set ttl to ${AGENT_VAULT_ON_BEHALF_OF_SESSION_MAX_TTL} or less.`
+ });
+ }
+ return resolved;
+ };
+
+ const mintSession = async ({
+ projectId,
+ ctx,
+ accessBundles,
+ actorName,
+ actorEmail,
+ ttl: requestedTtl,
+ onBehalfOf
+ }: 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
);
+ let reachable: string[] | null;
+ let onBehalfOfUser: Awaited<ReturnType<typeof resolveOnBehalfOfUser>> | null = null;
+ if (onBehalfOf) {
+ onBehalfOfUser = await resolveOnBehalfOfUser({ projectId, ctx, onBehalfOf });
+ reachable = onBehalfOfUser.accessBundleIds;
+ // getProjectPermission leaves the last actor it ran for in the request context, where the audit log reads the
+ // caller's permission metadata. Running the caller's check again, memoized so it costs no query, puts it back.
+ await getAgentVaultPermission({ permissionService }, { projectId, ctx });
+ } else {
+ ({ accessBundleIds: reachable } = await getAgentVaultReachability(
+ { permissionService, membershipDAL },
+ { projectId, ctx }
+ ));
+ }
+
if (!accessBundles.length) {
throw new BadRequestError({ message: "Name the access bundle this session should carry" });
}
@@ -90,7 +230,9 @@ export const agentVaultSessionServiceFactory = ({
});
if (unreachable) {
throw new BadRequestError({
- message: `No access bundle named '${unreachable}' is granted to you. Check the name, or ask an Agent Vault admin to grant it.`
+ message: onBehalfOfUser
+ ? `No access bundle named '${unreachable}' is granted to '${onBehalfOfUser.user.username}'. Check the name, or ask an Agent Vault admin to grant it to them.`
+ : `No access bundle named '${unreachable}' is granted to you. Check the name, or ask an Agent Vault admin to grant it.`
});
}
@@ -103,17 +245,35 @@ export const agentVaultSessionServiceFactory = ({
kmsService
);
+ // An on-behalf-of session belongs to the user, so resolve uses their reach and their personal values, and the
+ // caller is kept as the acting identity.
+ const owner = onBehalfOfUser
+ ? {
+ userId: onBehalfOfUser.user.id,
+ identityId: null,
+ actorType: AgentVaultMemberType.User,
+ actorName:
+ `${onBehalfOfUser.user.firstName ?? ""} ${onBehalfOfUser.user.lastName ?? ""}`.trim() ||
+ (onBehalfOfUser.user.email ?? onBehalfOfUser.user.username),
+ actorEmail: onBehalfOfUser.user.email ?? null,
+ actingIdentityId: caller.id,
+ actingIdentityName: actorName
+ }
+ : {
+ userId: caller.type === ActorType.USER ? caller.id : null,
+ identityId: caller.type === ActorType.IDENTITY ? caller.id : null,
+ actorType:
+ caller.type === ActorType.IDENTITY ? AgentVaultMemberType.MachineIdentity : AgentVaultMemberType.User,
+ actorName,
+ actorEmail
+ };
+
const session = await agentVaultSessionDAL.transaction(async (tx) => {
const created = await agentVaultSessionDAL.createWithId(
{
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,
tokenHash,
expiresAt,
encryptedSessionLogKey
@@ -145,7 +305,11 @@ export const agentVaultSessionServiceFactory = ({
position
}))
},
- token
+ token,
+ ttl,
+ onBehalfOf: onBehalfOfUser
+ ? { userId: onBehalfOfUser.user.id, username: onBehalfOfUser.user.username, email: onBehalfOfUser.user.email }
+ : null
};
};
diff --git 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
index 99c1b88d64..a21688bf0e 100644
--- 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
@@ -6,13 +6,18 @@ import {
AgentVaultSessionStatus
} from "../agent-vault/agent-vault-enums";
+/** Exactly one of the two names the user. */
+export type TOnBehalfOfUser = { userId?: string; userEmail?: string };
+
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;
};
export type TListSessionsDTO = {
@@ -33,6 +38,9 @@ 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 TAgentVaultSessionActor =
| {
type: AgentVaultMemberType.User;
diff --git a/backend/src/ee/services/agent-vault/AGENTS.md b/backend/src/ee/services/agent-vault/AGENTS.md
index f3e9dde214..12656f7d13 100644
--- a/backend/src/ee/services/agent-vault/AGENTS.md
+++ b/backend/src/ee/services/agent-vault/AGENTS.md
@@ -20,6 +20,7 @@ agent-vault/ shared: enums, host grammar, conflict detection, re
agent-vault-access-bundle/ bundles, services, credential encryption, grants
agent-vault-variable/ global and personal variables and the reads behind Used By
agent-vault-member/ product membership (list, add, role, remove)
+agent-vault-delegation/ which users a machine identity may start sessions on behalf of
agent-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-project/ the per-org project's lazy bootstrap and resolver
@@ -113,6 +114,49 @@ and `packages/agentvault/` in the CLI repo. Frontend: `frontend/src/pages/agent-
- **Sessions are never deleted**, so the Sessions page is a full history and a session's row keeps the key its
logs need. Settled with the product owner.
+## Sessions on behalf of users
+
+A machine identity with a **delegation** can mint a session on behalf of a user (`onBehalfOf` on mint). The session
+belongs to the user: `userId` is the user, so resolve uses the user's role, reach and personal values without a branch
+of its own. The identity is kept as `actingIdentityId` and `actingIdentityName`. A delegation is one
+`agent_vault_delegations` row per identity, with a scope of `all-members` or `selected`, plus
+`agent_vault_delegation_subjects` rows naming users and groups.
+
+- **Never put the acting identity in `identityId`.** Resolve reads `userId` first and falls back to `identityId`, so
+ deleting the user would quietly turn the session into the identity's own, with the identity's grants. The DB check
+ `agent_vault_sessions_acting_identity_check` keeps an on-behalf-of session a user's.
+- **`actingIdentityName` is what marks the session on-behalf-of** once deleting the identity sets the id to NULL, the
+ same lesson as `actorType`. A session with the name and no id is orphaned: it reads as revoked
+ (`isOrphanedSession`) and resolve refuses it.
+- **Resolve re-checks the acting identity every time**: active in the org, a live Agent Vault role, and a delegation
+ that still covers the user (`$assertActingIdentityStillDelegated`). Any miss is a 401, like an actor removed from
+ Agent Vault. Removing a delegation revokes nothing, so its sessions work again if it comes back; revoking is what
+ ends one. Settled the same way as removal from Agent Vault.
+- **Reach is the user's alone, never intersected with the identity's.** Intersection is a possible later option,
+ not a bug. An admin user reaches every bundle, so an all-members delegation covers every bundle too.
+- **Mint checks the delegation before it looks the user up**, so an identity no admin delegated learns nothing about
+ who is in the org, and an unknown user gets the same message as an uncovered one. Only a machine identity may send
+ `onBehalfOf`. The user must be an active, accepted org member, as resolve requires.
+- **Mint runs `getProjectPermission` for the user, then once more for the caller.** The permission service leaves
+ the last actor it ran for in the request context, where the audit log reads the caller's permission metadata. The
+ second call is memoized, so it costs no query; dropping it attributes the user's metadata to the identity.
+- **The user's session permission is checked with `can()`, not thrown through CASL**, since a CASL denial would be
+ recorded against the identity making the request.
+- **TTL defaults to 1h and caps at 24h, and `never` is refused**: the user didn't start the session and may not know
+ it exists. The route's `ttl` is optional rather than defaulted because the default depends on `onBehalfOf`.
+- **The acting identity holds the session alongside the user**: the identity's list, get, revoke and session log
+ reads match `actingIdentityId` as well as `identityId` (`isSessionOwnedBy`, the session DAL's actor filter).
+- **Coverage reads group membership without `isPending`**, the way the permission engine grants access through a
+ group. Filtering it would refuse accepted users, since the flag is no longer cleared.
+- **A subject is named by its own Agent Vault membership**, the rule bundle grants use: a user who reaches Agent
+ Vault only through a group is covered by naming the group. Coverage itself is read live, so leaving the group
+ ends it.
+- **Removing an identity from Agent Vault deletes its delegation**, in the revoke transaction, so adding it back
+ restores nothing. Platform paths (org removal, the generic project membership routes) don't, and a delegation can
+ outlive the membership there; resolve still refuses, because it requires the identity's live Agent Vault role.
+- **Delegation routes take no `AuthMode.OAUTH`.** The admin check reads the role, which a delegated token's scopes
+ don't narrow, and a delegation lets an identity act as other users.
+
## Proxies
- There is no enrollment. Create and rotate return a proxy token (the non-expiring access JWT) and every proxy
@@ -270,8 +314,10 @@ reference.
a variable the caller may not act on is a 404, never a 403: someone else's personal one, and a global one for a
member. Global keys are unique per project (500 cap), personal ones per owner (100 cap), each enforced by a partial
unique index plus an advisory lock per project or per owner.
-- **Everything personal is scoped to the caller, never to an id the caller sends.** No route names another actor,
- so an admin can't list, read or set anyone else's variables or values. The owner is a user or a machine identity
+- **Everything personal is scoped to the caller, never to an id the caller sends.** No route that reads or writes
+ personal values or variables names another actor, so an admin can't list, read or set anyone else's variables or
+ values. An on-behalf-of mint names a user, but only to own the session (see
+ [Sessions on behalf of users](#sessions-on-behalf-of-users)). The owner is a user or a machine identity
(`ownerOf`); the UI only covers users for now, but resolve and the API already work for an identity's own
sessions.
- **Resolve fills member fields last**: the admin's fields are expanded against global variables first, then each
diff --git a/backend/src/ee/services/agent-vault/agent-vault-enums.ts b/backend/src/ee/services/agent-vault/agent-vault-enums.ts
index c8debd63b7..d928a42dc4 100644
--- a/backend/src/ee/services/agent-vault/agent-vault-enums.ts
+++ b/backend/src/ee/services/agent-vault/agent-vault-enums.ts
@@ -47,6 +47,12 @@ export enum AgentVaultSessionScope {
All = "all"
}
+/** Which users a machine identity may start sessions on behalf of. */
+export enum AgentVaultDelegationScope {
+ AllMembers = "all-members",
+ Selected = "selected"
+}
+
/** Which part of a service a variable reference sits in. A basic credential's password is its value. */
export enum AgentVaultVariableReferenceField {
CredentialValue = "credential-value",
diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.ts
index 70ba856527..5169da14ac 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -832,6 +832,8 @@ export enum EventType {
AGENT_VAULT_ACCESS_BUNDLE_MEMBER_REMOVE = "agent-vault-access-bundle-member-remove",
AGENT_VAULT_SESSION_MINT = "agent-vault-session-mint",
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",
@@ -6756,6 +6758,10 @@ interface AgentVaultSessionMintEvent {
accessBundleId: string;
accessBundleName: string;
expiresAt: string | null;
+ // Set when a machine identity started the session on this user's behalf.
+ onBehalfOfUserId?: string;
+ onBehalfOfUserName?: string;
+ onBehalfOfUserEmail?: string;
};
}
@@ -6766,6 +6772,25 @@ interface AgentVaultSessionRevokeEvent {
};
}
+interface AgentVaultDelegationSetEvent {
+ type: EventType.AGENT_VAULT_DELEGATION_SET;
+ metadata: {
+ machineIdentityId: string;
+ machineIdentityName: string;
+ scope: string;
+ users: { userId: string; userName: string }[];
+ groups: { groupId: string; groupName: string }[];
+ };
+}
+
+interface AgentVaultDelegationDeleteEvent {
+ type: EventType.AGENT_VAULT_DELEGATION_DELETE;
+ metadata: {
+ machineIdentityId: string;
+ machineIdentityName: string;
+ };
+}
+
interface PamAccountCreateEvent {
type: EventType.PAM_ACCOUNT_CREATE;
metadata: {
@@ -8680,6 +8705,8 @@ export type Event =
| AgentVaultAccessBundleMemberAddEvent
| AgentVaultAccessBundleMemberRemoveEvent
| AgentVaultSessionMintEvent
+ | AgentVaultDelegationSetEvent
+ | AgentVaultDelegationDeleteEvent
| AgentVaultSessionRevokeEvent
| AgentVaultProxyRegisterEvent
| AgentVaultProxyTokenReissueEvent
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index 07613e9068..6f49e6cbb2 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -108,6 +108,7 @@ export enum ApiDocsTags {
AgentVaultSessions = "Agent Vault Sessions",
AgentVaultProxies = "Agent Vault Proxies",
AgentVaultMembers = "Agent Vault Members",
+ AgentVaultDelegations = "Agent Vault Delegations",
AgentVaultSessionLogs = "Agent Vault Session Logs",
AgentVaultSettings = "Agent Vault Settings",
AgentVaultAppConnections = "Agent Vault App Connections",
@@ -4727,13 +4728,17 @@ 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. A session started on behalf of a user defaults to 1h and lasts at most 24h, so never isn't allowed for it.",
+ 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 then reaches the access bundles the user reaches and uses the user's personal values. Name the user by userId or by userEmail.",
+ 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 or access bundle name.",
+ search: "Match sessions by 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.",
@@ -4744,7 +4749,36 @@ export const AGENT_VAULT = {
"The first name of the user. Once the user is deleted, the full name recorded when the session was created.",
lastName: "The last name of the user, or null once the user is deleted.",
identityName:
- "The name of the machine identity. Once the machine identity is deleted, the name recorded when the session was created."
+ "The name of the machine identity. Once the machine identity is deleted, the name recorded when the session was created.",
+ actingIdentity:
+ "The machine identity that started the session on the actor's behalf, or null when the actor started it.",
+ actingIdentityId: "The ID of the acting machine identity, or null once it is deleted.",
+ actingIdentityName:
+ "The name of the acting machine identity. Once it is deleted, the name recorded when the session was created."
+ },
+ DELEGATION: {
+ machineIdentityId: "The ID of the machine identity the delegation belongs to.",
+ machineIdentityIds:
+ "Return only the delegations of these machine identities. Separate several IDs with commas, up to 100.",
+ machineIdentity: "The machine identity that can start sessions on behalf of users.",
+ machineIdentityName: "The name of the machine identity.",
+ scope:
+ "Which users the machine identity can start sessions on behalf of: every Agent Vault member (all-members), or only the users and the members of the groups in the delegation (selected).",
+ userIds:
+ "The users the machine identity can act on behalf of. Each must be a member of Agent Vault. Only allowed when the scope is selected.",
+ groupIds:
+ "The groups whose members the machine identity can act on behalf of. Each must be a member of Agent Vault. Only allowed when the scope is selected.",
+ users: "The users in the delegation.",
+ groups: "The groups in the delegation. Their members are covered while they stay in the group.",
+ userId: "The ID of the user.",
+ username: "The username of the user.",
+ email: "The email address of the user.",
+ firstName: "The first name of the user.",
+ lastName: "The last name of the user.",
+ groupId: "The ID of the group.",
+ groupName: "The name of the group.",
+ limit: "The maximum number of delegations to return.",
+ offset: "How many delegations to skip."
}
};
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index e88e4191fd..5e0927002e 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -30,6 +30,11 @@ import { agentVaultServiceCustomHeaderDALFactory } from "@app/ee/services/agent-
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 { 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 {
@@ -2009,6 +2014,8 @@ export const registerRoutes = async (
const agentVaultProxyDAL = agentVaultProxyDALFactory(db);
const agentVaultResolveDAL = agentVaultResolveDALFactory(db);
const agentVaultSessionLogConfigDAL = agentVaultSessionLogConfigDALFactory(db);
+ const agentVaultDelegationDAL = agentVaultDelegationDALFactory(db);
+ const agentVaultDelegationSubjectDAL = agentVaultDelegationSubjectDALFactory(db);
const agentVaultVariableService = agentVaultVariableServiceFactory({
agentVaultVariableDAL,
@@ -2053,11 +2060,22 @@ export const registerRoutes = async (
agentVaultSessionDAL,
agentVaultSessionAccessBundleDAL,
agentVaultAccessBundleDAL,
+ agentVaultDelegationDAL,
membershipDAL,
+ userDAL,
+ orgDAL,
permissionService,
kmsService
});
+ const agentVaultDelegationService = agentVaultDelegationServiceFactory({
+ agentVaultDelegationDAL,
+ agentVaultDelegationSubjectDAL,
+ membershipDAL,
+ userGroupMembershipDAL,
+ permissionService
+ });
+
const agentVaultProjectResolver = agentVaultProjectResolverFactory({
db,
projectDAL,
@@ -2080,7 +2098,8 @@ export const registerRoutes = async (
usageMeteringService,
agentVaultPersonalValueDAL,
userGroupMembershipDAL,
- identityGroupMembershipDAL
+ identityGroupMembershipDAL,
+ agentVaultDelegationDAL
});
const pamProjectResolver = pamProjectResolverFactory({
@@ -2170,6 +2189,7 @@ export const registerRoutes = async (
agentVaultVariableDAL,
agentVaultPersonalValueDAL,
agentVaultSessionDAL,
+ agentVaultDelegationDAL,
agentVaultSessionLogConfigDAL,
membershipDAL,
orgDAL,
@@ -4752,6 +4772,7 @@ export const registerRoutes = async (
agentVaultSession: agentVaultSessionService,
agentVaultSessionLog: agentVaultSessionLogService,
agentVaultMembership: agentVaultMembershipService,
+ agentVaultDelegation: agentVaultDelegationService,
pamAccountTemplate: pamAccountTemplateService,
pamFolder: pamFolderService,
pamAccount: pamAccountService,
diff --git a/backend/src/services/telemetry/telemetry-types.ts b/backend/src/services/telemetry/telemetry-types.ts
index 5a56f576cb..2b94dfca1c 100644
--- a/backend/src/services/telemetry/telemetry-types.ts
+++ b/backend/src/services/telemetry/telemetry-types.ts
@@ -2532,6 +2532,7 @@ export type TAgentVaultSessionCreatedEvent = {
sessionId: string;
accessBundleId: string;
ttlSeconds: number | null;
+ isOnBehalfOfUser: boolean;
};
};
diff --git a/docs/api-reference/endpoints/agent-vault-delegations/delete.mdx b/docs/api-reference/endpoints/agent-vault-delegations/delete.mdx
new file mode 100644
index 0000000000..96a9da2227
--- /dev/null
+++ b/docs/api-reference/endpoints/agent-vault-delegations/delete.mdx
@@ -0,0 +1,4 @@
+---
+title: "Delete delegation"
+openapi: "DELETE /api/v1/agent-vault/delegations/{machineIdentityId}"
+---
diff --git a/docs/api-reference/endpoints/agent-vault-delegations/get.mdx b/docs/api-reference/endpoints/agent-vault-delegations/get.mdx
new file mode 100644
index 0000000000..f2a59fc338
--- /dev/null
+++ b/docs/api-reference/endpoints/agent-vault-delegations/get.mdx
@@ -0,0 +1,4 @@
+---
+title: "Get delegation"
+openapi: "GET /api/v1/agent-vault/delegations/{machineIdentityId}"
+---
diff --git a/docs/api-reference/endpoints/agent-vault-delegations/list.mdx b/docs/api-reference/endpoints/agent-vault-delegations/list.mdx
new file mode 100644
index 0000000000..4eb324cb0a
--- /dev/null
+++ b/docs/api-reference/endpoints/agent-vault-delegations/list.mdx
@@ -0,0 +1,4 @@
+---
+title: "List delegations"
+openapi: "GET /api/v1/agent-vault/delegations"
+---
diff --git a/docs/api-reference/endpoints/agent-vault-delegations/set.mdx b/docs/api-reference/endpoints/agent-vault-delegations/set.mdx
new file mode 100644
index 0000000000..4502867d55
--- /dev/null
+++ b/docs/api-reference/endpoints/agent-vault-delegations/set.mdx
@@ -0,0 +1,4 @@
+---
+title: "Set delegation"
+openapi: "PUT /api/v1/agent-vault/delegations/{machineIdentityId}"
+---
diff --git a/docs/docs.json b/docs/docs.json
index ca7443882c..dd34daea5b 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -733,6 +733,7 @@
"pages": [
"documentation/platform/agent-vault/sessions-cli",
"documentation/platform/agent-vault/sessions-api",
+ "documentation/platform/agent-vault/sessions-on-behalf-of-users",
"documentation/platform/agent-vault/session-logs"
]
},
@@ -4539,6 +4540,15 @@
"api-reference/endpoints/agent-vault-members/revoke"
]
},
+ {
+ "group": "Delegations",
+ "pages": [
+ "api-reference/endpoints/agent-vault-delegations/list",
+ "api-reference/endpoints/agent-vault-delegations/get",
+ "api-reference/endpoints/agent-vault-delegations/set",
+ "api-reference/endpoints/agent-vault-delegations/delete"
+ ]
+ },
{
"group": "Proxies",
"pages": [
diff --git a/docs/documentation/platform/agent-vault/access-control.mdx b/docs/documentation/platform/agent-vault/access-control.mdx
index 04329d197d..0a94681023 100644
--- a/docs/documentation/platform/agent-vault/access-control.mdx
+++ b/docs/documentation/platform/agent-vault/access-control.mdx
@@ -25,7 +25,7 @@ Agent Vault has one member list for your whole organization, instead of one per
| Role | What they can do |
|------|------------------|
-| **Admin** | <ul><li>Create and manage access bundles, services, variables, and proxies</li><li>Grant access bundles</li><li>Manage membership</li><li>Read audit logs</li></ul> |
+| **Admin** | <ul><li>Create and manage access bundles, services, variables, and proxies</li><li>Grant access bundles</li><li>Manage membership</li><li>Let machine identities [create sessions on behalf of users](/documentation/platform/agent-vault/sessions-on-behalf-of-users)</li><li>Read audit logs</li></ul> |
| **Member** | <ul><li>Create sessions with the access bundles granted to them</li><li>Revoke their own sessions</li><li>Set up their [personal values](/documentation/platform/agent-vault/access-bundles#set-up-your-personal-values) and keep [personal variables](/documentation/platform/agent-vault/variables#personal-variables)</li></ul> |
An admin can use every access bundle without a grant. A member can't use an access bundle until an admin grants it, and only sees the bundles granted to them. On the **Sessions** page, members see their own sessions, and admins can switch between **All Sessions** and **My Sessions**.
diff --git a/docs/documentation/platform/agent-vault/sessions-api.mdx b/docs/documentation/platform/agent-vault/sessions-api.mdx
index 903570a77c..cf10fde884 100644
--- a/docs/documentation/platform/agent-vault/sessions-api.mdx
+++ b/docs/documentation/platform/agent-vault/sessions-api.mdx
@@ -58,6 +58,10 @@ curl -X POST https://app.infisical.com/api/v1/agent-vault/sessions \
- `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)
+<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 gets that person's access bundles and personal values.
+</Tip>
+
The response includes the session's ID, the session token, and when the session expires:
```json
diff --git a/docs/documentation/platform/agent-vault/sessions-on-behalf-of-users.mdx b/docs/documentation/platform/agent-vault/sessions-on-behalf-of-users.mdx
new file mode 100644
index 0000000000..d20683e9f5
--- /dev/null
+++ b/docs/documentation/platform/agent-vault/sessions-on-behalf-of-users.mdx
@@ -0,0 +1,151 @@
+---
+title: "Sessions on behalf of users"
+description: "Let a machine identity, such as a chat bot or a task runner, create sessions that use a user's own access bundles and personal values."
+---
+
+A delegation lets a [machine identity](/documentation/platform/identities/machine-identities) create [sessions](/documentation/platform/agent-vault/sessions) on behalf of users in Agent Vault. A session created on behalf of a user belongs to that user, so it reaches only the [access bundles](/documentation/platform/agent-vault/access-bundles) granted to the user, and the proxy uses the user's own [personal values](/documentation/platform/agent-vault/services#member-provided-values).
+
+Use a delegation when one service starts agents for many people, such as a chat bot that runs an agent for each message, or a task runner that runs an agent for each ticket. Each agent then gets only the access of the person who asked for it, and uses that person's own credential wherever a service leaves part of its credential to members.
+
+```mermaid
+sequenceDiagram
+ participant User
+ participant Bot as Chat bot (machine identity)
+ participant Infisical
+ participant Agent
+ participant Proxy
+ participant API as GitHub API
+ User->>Bot: Asks for a task
+ Bot->>Infisical: Create a session on behalf of the user
+ Infisical-->>Bot: Session token
+ Bot->>Agent: Start the agent with the session token
+ Agent->>Proxy: Request to the GitHub API
+ Proxy->>API: Request with the user's personal token
+```
+
+## Prerequisites
+
+- The **Admin** role in [Agent Vault](/documentation/platform/agent-vault/access-control#product-membership), or an Agent Vault admin who can [set up the delegation](#set-up-a-delegation) for you
+- A machine identity that's a member of Agent Vault and can log in with [Universal Auth](/documentation/platform/identities/universal-auth), as [Step 1 of Create sessions with the API](/documentation/platform/agent-vault/sessions-api#step-1-set-up-a-machine-identity) describes
+- Users who are members of Agent Vault and have a grant on the access bundles their agents use
+
+## Set up a delegation
+
+<Tabs>
+ <Tab title="Dashboard">
+ <Steps>
+ <Step>
+ In Agent Vault, go to **Access Control**, select the **Machine Identities** tab, and select the machine identity.
+ </Step>
+ <Step>
+ In the **Delegation** section, select **Set Up Delegation**.
+ </Step>
+ <Step>
+ Select which users the machine identity can act on behalf of:
+
+ - **Selected Users and Groups**: the users you pick, and every member of the groups you pick
+ - **All Agent Vault Members**: every user in Agent Vault, including users added later
+ </Step>
+ <Step>
+ For **Selected Users and Groups**, pick the users and groups in **Users and Groups**. Then select **Save Delegation**.
+ </Step>
+ </Steps>
+ </Tab>
+ <Tab title="API">
+ Call [the endpoint that sets a delegation](/api-reference/endpoints/agent-vault-delegations/set) with the machine identity's ID:
+
+ ```bash
+ curl -X PUT https://app.infisical.com/api/v1/agent-vault/delegations/<machine-identity-id> \
+ -H "Authorization: Bearer <access-token>" \
+ -H "Content-Type: application/json" \
+ -d '{"scope": "selected", "groupIds": ["<group-id>"]}'
+ ```
+
+ Set `scope` to `all-members` to cover every Agent Vault member, or to `selected` with `userIds`, `groupIds`, or both. The request replaces any delegation the machine identity already has.
+ </Tab>
+</Tabs>
+
+You can pick only users and groups that are members of Agent Vault. If a user is in Agent Vault only through a group, pick the group.
+
+To change the delegation later, select **Edit Delegation** in the same section. To remove it, select **Remove**, type `remove`, and select **Remove Delegation**.
+
+<Warning>
+ If a machine identity has a delegation, anyone who can log in as the machine identity can send requests with the personal values of every user the delegation covers. Protect the machine identity's credentials as carefully as you'd protect those users' own credentials.
+</Warning>
+
+## Create a session on behalf of a user
+
+Log in as the machine identity, as [Step 2 of Create sessions with the API](/documentation/platform/agent-vault/sessions-api#step-2-log-in-as-the-machine-identity) describes. Then call [the endpoint that creates a session](/api-reference/endpoints/agent-vault-sessions/create), and name the user in `onBehalfOf`:
+
+```bash
+curl -X POST https://app.infisical.com/api/v1/agent-vault/sessions \
+ -H "Authorization: Bearer <access-token>" \
+ -H "Content-Type: application/json" \
+ -d '{"accessBundles": ["<access-bundle-name>"], "onBehalfOf": {"userEmail": "<user-email>"}, "ttl": "15m"}'
+```
+
+- In `onBehalfOf`, set either `userEmail` or `userId`, not both
+- In `accessBundles`, name a bundle that's granted to the user, not to the machine identity
+- `ttl` defaults to `1h` and can be at most `24h`, so `never` isn't allowed
+
+Start the agent with the session token from the response, and revoke the session when the agent finishes, as [Step 4 of Create sessions with the API](/documentation/platform/agent-vault/sessions-api#step-4-start-the-agent-with-the-session-token) describes.
+
+## What the session can reach
+
+A session created on behalf of a user gets the user's access, not the machine identity's:
+
+- The session can use only the access bundles granted to the user, directly or through a group (if the user is an Agent Vault admin, every bundle)
+- The proxy uses the user's personal values, and refuses the session's requests to a service until the user [sets up their personal values](/documentation/platform/agent-vault/access-bundles#set-up-your-personal-values) for it
+
+## When the session stops working
+
+Infisical checks the delegation again each time the proxy polls, once every [poll interval](/documentation/platform/agent-vault/proxies#poll-interval) (60 seconds by default). The proxy refuses every request on the session if any of these happen:
+
+- An admin removes the delegation, or edits it so it no longer covers the user
+- The delegation covered the user only through a group, and the user leaves that group
+- An admin removes the machine identity from Agent Vault, which also deletes its delegation
+- Someone deletes the machine identity (the session then shows as **Revoked**)
+
+If an admin sets up the delegation again, or adds the user back to it, the session works again. To end a session for good, [revoke it](/documentation/platform/agent-vault/sessions#revoke-a-session).
+
+Changes to the user's own access, such as losing a grant on the access bundle, affect the session the same way they affect the user's other sessions, as [Access changes](/documentation/platform/agent-vault/sessions#access-changes) describes.
+
+## Track sessions created on behalf of users
+
+These people and identities can see the session and revoke it:
+
+- The user, under **My Sessions**
+- The machine identity, through the API that [reads a session](/api-reference/endpoints/agent-vault-sessions/get) and the API that [revokes a session](/api-reference/endpoints/agent-vault-sessions/revoke)
+- Admins, under **All Sessions**
+
+On the **Sessions** page, the **Identity** column shows the user, followed by "via" and the machine identity's name. The session's details list the machine identity under **Started By**.
+
+When the machine identity creates the session, the audit event names the machine identity as the actor, and records the user in `onBehalfOfUserId`, `onBehalfOfUserName`, and `onBehalfOfUserEmail`. Infisical also writes an audit event when an admin sets up, changes, or removes a delegation.
+
+## Troubleshooting
+
+<AccordionGroup>
+ <Accordion title="Creating the session fails with &quot;This machine identity isn't allowed to start sessions on behalf of users&quot;">
+ The machine identity has no delegation. [Set one up](#set-up-a-delegation), or ask an Agent Vault admin to.
+ </Accordion>
+ <Accordion title="Creating the session fails with &quot;This machine identity can't start sessions on behalf of ...&quot;">
+ The delegation doesn't cover the user, or no active member of your organization has that email or ID. Check the email or ID you sent, then check the users and groups in the machine identity's delegation.
+ </Accordion>
+ <Accordion title="Creating the session fails with &quot;No access bundle named ... is granted to ...&quot;">
+ The access bundle isn't granted to the user. [Grant the bundle](/documentation/platform/agent-vault/access-bundles#manage-access-to-access-bundles) to the user, or name a bundle the user already has.
+ </Accordion>
+ <Accordion title="Creating the session fails with &quot;A session started on behalf of a user lasts at most 24h&quot;">
+ Set `ttl` to `24h` or less. If the agent runs longer than a day, create a new session before the old one expires, as [Choose how long a session lasts](/documentation/platform/agent-vault/sessions-api#choose-how-long-a-session-lasts) describes.
+ </Accordion>
+</AccordionGroup>
+
+## Next steps
+
+<CardGroup cols={2}>
+ <Card title="Create sessions with the API" icon="code" href="/documentation/platform/agent-vault/sessions-api">
+ Create, use, and revoke a session from your own code.
+ </Card>
+ <Card title="Services" icon="plug" href="/documentation/platform/agent-vault/services#member-provided-values">
+ Leave part of a service's credential to each member.
+ </Card>
+</CardGroup>
diff --git a/docs/documentation/platform/agent-vault/sessions.mdx b/docs/documentation/platform/agent-vault/sessions.mdx
index 7dc84700e8..72874bc4fc 100644
--- a/docs/documentation/platform/agent-vault/sessions.mdx
+++ b/docs/documentation/platform/agent-vault/sessions.mdx
@@ -12,7 +12,7 @@ Every session is scoped to one access bundle and expires on a schedule you set.
Anyone granted at least one access bundle can create a session. Admins can create one with any access bundle.
<Tip>
- If you want to create sessions programmatically, you can have a [machine identity](/documentation/platform/identities/machine-identities) create a new session for each run using [the CLI](/documentation/platform/agent-vault/sessions-cli) or [the API](/documentation/platform/agent-vault/sessions-api).
+ If you want to create sessions programmatically, you can have a [machine identity](/documentation/platform/identities/machine-identities) create a new session for each run using [the CLI](/documentation/platform/agent-vault/sessions-cli) or [the API](/documentation/platform/agent-vault/sessions-api). A machine identity can also create sessions [on behalf of users](/documentation/platform/agent-vault/sessions-on-behalf-of-users), so that each agent gets the access and personal values of the person it runs for.
</Tip>
<Tabs>
diff --git a/frontend/src/components/agent-vault/DelegationDialog.tsx b/frontend/src/components/agent-vault/DelegationDialog.tsx
new file mode 100644
index 0000000000..9adeb0ce71
--- /dev/null
+++ b/frontend/src/components/agent-vault/DelegationDialog.tsx
@@ -0,0 +1,252 @@
+import { useEffect, useMemo, useState } from "react";
+
+import { createNotification } from "@app/components/notifications";
+import {
+ Button,
+ Combobox,
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ Field,
+ FieldContent,
+ FieldDescription,
+ FieldLabel,
+ FieldTitle,
+ RadioGroup,
+ RadioGroupItem
+} from "@app/components/v3";
+import { useDebounce } from "@app/hooks";
+import { useListAgentVaultMembers, useSetAgentVaultDelegation } from "@app/hooks/api/agentVault";
+import { AgentVaultDelegationScope, AgentVaultMemberType } from "@app/hooks/api/agentVault/enums";
+import { TAgentVaultDelegation } from "@app/hooks/api/agentVault/types";
+
+import { MEMBER_KIND, memberDisplayName, memberSubtitle } from "./MemberName";
+
+type SubjectOption = {
+ type: AgentVaultMemberType.User | AgentVaultMemberType.Group;
+ id: string;
+ label: string;
+ subtitle: string;
+};
+
+const PICKER_LIMIT = 50;
+
+const userOption = (user: TAgentVaultDelegation["users"][number]): SubjectOption => {
+ const actor = { type: AgentVaultMemberType.User as const, ...user };
+ return {
+ type: AgentVaultMemberType.User,
+ id: user.id,
+ label: memberDisplayName(actor),
+ subtitle: memberSubtitle(actor)
+ };
+};
+
+const groupOption = (group: TAgentVaultDelegation["groups"][number]): SubjectOption => ({
+ type: AgentVaultMemberType.Group,
+ id: group.id,
+ label: group.name,
+ subtitle: MEMBER_KIND[AgentVaultMemberType.Group].label
+});
+
+type Props = {
+ isOpen: boolean;
+ onOpenChange: (isOpen: boolean) => void;
+ machineIdentityId: string;
+ machineIdentityName: string;
+ delegation: TAgentVaultDelegation | null;
+};
+
+export const DelegationDialog = ({
+ isOpen,
+ onOpenChange,
+ machineIdentityId,
+ machineIdentityName,
+ delegation
+}: Props) => {
+ const setDelegation = useSetAgentVaultDelegation();
+
+ const [scope, setScope] = useState(AgentVaultDelegationScope.Selected);
+ const [selected, setSelected] = useState<SubjectOption[]>([]);
+ const [search, setSearch] = useState("");
+ const [debouncedSearch] = useDebounce(search);
+
+ useEffect(() => {
+ if (!isOpen) return;
+ setScope(delegation?.scope ?? AgentVaultDelegationScope.Selected);
+ setSelected([
+ ...(delegation?.users ?? []).map(userOption),
+ ...(delegation?.groups ?? []).map(groupOption)
+ ]);
+ setSearch("");
+ }, [isOpen]);
+
+ // A subject has to be an Agent Vault member, so the picker lists members rather than the whole org.
+ const isPickerOpen = isOpen && scope === AgentVaultDelegationScope.Selected;
+ const memberSearch = { search: debouncedSearch.trim() || undefined, limit: PICKER_LIMIT };
+ const { data: users, isFetching: isFetchingUsers } = useListAgentVaultMembers(
+ { ...memberSearch, actorType: AgentVaultMemberType.User },
+ isPickerOpen
+ );
+ const { data: groups, isFetching: isFetchingGroups } = useListAgentVaultMembers(
+ { ...memberSearch, actorType: AgentVaultMemberType.Group },
+ isPickerOpen
+ );
+
+ const options = useMemo<SubjectOption[]>(
+ () => [...(users?.members ?? []).map(userOption), ...(groups?.members ?? []).map(groupOption)],
+ [users, groups]
+ );
+
+ const isListTruncated =
+ (users?.totalCount ?? 0) > (users?.members.length ?? 0) ||
+ (groups?.totalCount ?? 0) > (groups?.members.length ?? 0);
+
+ const handleSave = async () => {
+ try {
+ const isSelected = scope === AgentVaultDelegationScope.Selected;
+ await setDelegation.mutateAsync({
+ machineIdentityId,
+ scope,
+ userIds: isSelected
+ ? selected
+ .filter((option) => option.type === AgentVaultMemberType.User)
+ .map((option) => option.id)
+ : [],
+ groupIds: isSelected
+ ? selected
+ .filter((option) => option.type === AgentVaultMemberType.Group)
+ .map((option) => option.id)
+ : []
+ });
+ createNotification({
+ text: `Delegation for "${machineIdentityName}" saved`,
+ type: "success"
+ });
+ onOpenChange(false);
+ } catch {
+ // A failed request returns a 4xx that the global request handler surfaces as a toast
+ }
+ };
+
+ return (
+ <Dialog open={isOpen} onOpenChange={onOpenChange}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>{delegation ? "Edit Delegation" : "Set Up Delegation"}</DialogTitle>
+ <DialogDescription>
+ &quot;{machineIdentityName}&quot; can start sessions on behalf of these users. Each
+ session reaches only the user&apos;s access bundles and uses their personal values.
+ </DialogDescription>
+ </DialogHeader>
+
+ <RadioGroup
+ value={scope}
+ onValueChange={(value) => setScope(value as AgentVaultDelegationScope)}
+ >
+ <FieldLabel htmlFor="agent-vault-delegation-selected" variant="av">
+ <Field orientation="horizontal">
+ <FieldContent>
+ <FieldTitle>Selected Users and Groups</FieldTitle>
+ <FieldDescription>
+ The users you pick, and the members of the groups you pick.
+ </FieldDescription>
+ </FieldContent>
+ <RadioGroupItem
+ value={AgentVaultDelegationScope.Selected}
+ id="agent-vault-delegation-selected"
+ />
+ </Field>
+ </FieldLabel>
+ <FieldLabel htmlFor="agent-vault-delegation-all-members" variant="av">
+ <Field orientation="horizontal">
+ <FieldContent>
+ <FieldTitle>All Agent Vault Members</FieldTitle>
+ <FieldDescription>
+ Every user with access to Agent Vault, including users added later.
+ </FieldDescription>
+ </FieldContent>
+ <RadioGroupItem
+ value={AgentVaultDelegationScope.AllMembers}
+ id="agent-vault-delegation-all-members"
+ />
+ </Field>
+ </FieldLabel>
+ </RadioGroup>
+
+ {scope === AgentVaultDelegationScope.Selected && (
+ <Field>
+ <FieldLabel htmlFor="agent-vault-delegation-subjects">Users and Groups</FieldLabel>
+ <FieldContent>
+ <Combobox
+ id="agent-vault-delegation-subjects"
+ multiple
+ options={options}
+ value={selected}
+ isLoading={isFetchingUsers || isFetchingGroups}
+ onSearchChange={setSearch}
+ getOptionValue={(option) => `${option.type}:${option.id}`}
+ getOptionLabel={(option) => option.label}
+ placeholder="Pick users or groups..."
+ searchPlaceholder="Pick users or groups..."
+ searchAriaLabel="Search users and groups"
+ emptyMessage={(inputValue) =>
+ inputValue
+ ? "No Agent Vault users or groups match your search."
+ : "No users or groups are members of Agent Vault yet."
+ }
+ clearAriaLabel="Clear all users and groups"
+ modal
+ onValueChange={(next) => setSelected([...next])}
+ renderValue={(option) => {
+ const { icon: Icon } = MEMBER_KIND[option.type];
+ return (
+ <span className="flex min-w-0 items-center gap-1.5">
+ <Icon className="size-3.5 shrink-0 text-muted" />
+ <span className="truncate">{option.label}</span>
+ </span>
+ );
+ }}
+ renderOption={(option) => {
+ const { icon: Icon } = MEMBER_KIND[option.type];
+ return (
+ <span className="flex min-w-0 items-center gap-2.5">
+ <Icon className="size-4 shrink-0 text-muted" />
+ <span className="min-w-0">
+ <span className="block truncate">{option.label}</span>
+ <span className="block truncate text-xs leading-4 text-muted">
+ {option.subtitle}
+ </span>
+ </span>
+ </span>
+ );
+ }}
+ />
+ <FieldDescription>
+ {isListTruncated
+ ? "Search by name to find users and groups that are not listed."
+ : "Only members of Agent Vault are listed. A user who is in Agent Vault through a group is covered by picking the group."}
+ </FieldDescription>
+ </FieldContent>
+ </Field>
+ )}
+
+ <DialogFooter>
+ <Button
+ variant="av"
+ isDisabled={scope === AgentVaultDelegationScope.Selected && !selected.length}
+ isPending={setDelegation.isPending}
+ onClick={async () => handleSave()}
+ >
+ Save Delegation
+ </Button>
+ <Button variant="outline" onClick={() => onOpenChange(false)}>
+ Cancel
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/frontend/src/components/agent-vault/IdentityDelegationSection.tsx b/frontend/src/components/agent-vault/IdentityDelegationSection.tsx
new file mode 100644
index 0000000000..812f96f610
--- /dev/null
+++ b/frontend/src/components/agent-vault/IdentityDelegationSection.tsx
@@ -0,0 +1,164 @@
+import { useState } from "react";
+import { PencilIcon, PlusIcon, Trash2Icon } from "lucide-react";
+
+import { createNotification } from "@app/components/notifications";
+import {
+ Badge,
+ Button,
+ Card,
+ CardAction,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+ DeleteConfirmDialog,
+ Detail,
+ DetailGroup,
+ DetailLabel,
+ DetailValue,
+ DocumentationLinkBadge,
+ Skeleton
+} from "@app/components/v3";
+import { useProjectPermission } from "@app/context";
+import {
+ useDeleteAgentVaultDelegation,
+ useListAgentVaultDelegations
+} from "@app/hooks/api/agentVault";
+import { AgentVaultDelegationScope, AgentVaultMemberType } from "@app/hooks/api/agentVault/enums";
+import { ProjectMembershipRole } from "@app/hooks/api/roles/types";
+import { AgentVaultDocsUrls } from "@app/pages/agent-vault/agent-vault-docs-urls";
+
+import { DelegationDialog } from "./DelegationDialog";
+import { MEMBER_KIND, memberDisplayName } from "./MemberName";
+
+type Props = {
+ machineIdentityId: string;
+ machineIdentityName: string;
+};
+
+// Only admins can read or change a delegation, so members don't see the section at all.
+export const IdentityDelegationSection = ({ machineIdentityId, machineIdentityName }: Props) => {
+ const { hasProjectRole } = useProjectPermission();
+ const isAdmin = hasProjectRole(ProjectMembershipRole.Admin);
+
+ const { data: delegations, isPending } = useListAgentVaultDelegations(
+ [machineIdentityId],
+ isAdmin
+ );
+ const delegation = delegations?.[0] ?? null;
+ const deleteDelegation = useDeleteAgentVaultDelegation();
+
+ const [isEditOpen, setIsEditOpen] = useState(false);
+ const [isRemoveOpen, setIsRemoveOpen] = useState(false);
+
+ if (!isAdmin) return null;
+
+ const handleRemove = async () => {
+ try {
+ await deleteDelegation.mutateAsync({ machineIdentityId });
+ createNotification({
+ text: `Delegation for "${machineIdentityName}" removed`,
+ type: "success"
+ });
+ setIsRemoveOpen(false);
+ } catch {
+ // A failed request returns a 4xx that the global request handler surfaces as a toast
+ }
+ };
+
+ const UserIcon = MEMBER_KIND[AgentVaultMemberType.User].icon;
+ const GroupIcon = MEMBER_KIND[AgentVaultMemberType.Group].icon;
+
+ const renderCoverage = () => {
+ if (!delegation) {
+ return (
+ <p className="text-sm text-muted">
+ This machine identity can&apos;t start sessions on behalf of users.
+ </p>
+ );
+ }
+ return (
+ <DetailGroup>
+ <Detail>
+ <DetailLabel>Acts On Behalf Of</DetailLabel>
+ <DetailValue>
+ {delegation.scope === AgentVaultDelegationScope.AllMembers ? (
+ "Every Agent Vault member"
+ ) : (
+ <div className="flex flex-wrap gap-1.5">
+ {delegation.groups.map((group) => (
+ <Badge key={group.id} variant="neutral">
+ <GroupIcon />
+ {group.name}
+ </Badge>
+ ))}
+ {delegation.users.map((user) => (
+ <Badge key={user.id} variant="neutral">
+ <UserIcon />
+ {memberDisplayName({ type: AgentVaultMemberType.User, ...user })}
+ </Badge>
+ ))}
+ </div>
+ )}
+ </DetailValue>
+ </Detail>
+ </DetailGroup>
+ );
+ };
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>
+ Delegation
+ <DocumentationLinkBadge href={AgentVaultDocsUrls.sessionsOnBehalfOfUsers} />
+ </CardTitle>
+ <CardDescription>
+ Let this machine identity start sessions on behalf of users, with their access bundles and
+ personal values.
+ </CardDescription>
+ {!isPending && (
+ <CardAction className="flex gap-2">
+ {delegation ? (
+ <>
+ <Button variant="outline" onClick={() => setIsEditOpen(true)}>
+ <PencilIcon />
+ Edit Delegation
+ </Button>
+ <Button variant="danger" onClick={() => setIsRemoveOpen(true)}>
+ <Trash2Icon />
+ Remove
+ </Button>
+ </>
+ ) : (
+ <Button variant="av" onClick={() => setIsEditOpen(true)}>
+ <PlusIcon />
+ Set Up Delegation
+ </Button>
+ )}
+ </CardAction>
+ )}
+ </CardHeader>
+ <CardContent>{isPending ? <Skeleton className="h-4 w-1/2" /> : renderCoverage()}</CardContent>
+
+ <DelegationDialog
+ isOpen={isEditOpen}
+ onOpenChange={setIsEditOpen}
+ machineIdentityId={machineIdentityId}
+ machineIdentityName={machineIdentityName}
+ delegation={delegation}
+ />
+
+ <DeleteConfirmDialog
+ isOpen={isRemoveOpen}
+ onOpenChange={setIsRemoveOpen}
+ title={`Remove Delegation for "${machineIdentityName}"`}
+ description="It can no longer start sessions on behalf of users, and the sessions it already started on their behalf stop working."
+ confirmKey="remove"
+ confirmLabel="Remove Delegation"
+ isPending={deleteDelegation.isPending}
+ onConfirm={handleRemove}
+ />
+ </Card>
+ );
+};
diff --git a/frontend/src/hooks/api/agentVault/enums.ts b/frontend/src/hooks/api/agentVault/enums.ts
index 5e2d5502c6..61cf40551c 100644
--- a/frontend/src/hooks/api/agentVault/enums.ts
+++ b/frontend/src/hooks/api/agentVault/enums.ts
@@ -43,6 +43,12 @@ export enum AgentVaultSessionScope {
All = "all"
}
+/** Which users a machine identity can start sessions on behalf of. */
+export enum AgentVaultDelegationScope {
+ AllMembers = "all-members",
+ Selected = "selected"
+}
+
/** Global variables are an admin's, for services; personal ones are the caller's own, for their personal values. */
export enum AgentVaultVariableScope {
Global = "global",
diff --git a/frontend/src/hooks/api/agentVault/mutations.tsx b/frontend/src/hooks/api/agentVault/mutations.tsx
index 00ebdd0842..07161afd91 100644
--- a/frontend/src/hooks/api/agentVault/mutations.tsx
+++ b/frontend/src/hooks/api/agentVault/mutations.tsx
@@ -12,6 +12,7 @@ import {
TAgentVaultAccessBundle,
TAgentVaultActorIdsDTO,
TAgentVaultActorRef,
+ TAgentVaultDelegation,
TAgentVaultGrantedMember,
TAgentVaultMemberWriteResult,
TAgentVaultMintedSession,
@@ -28,6 +29,7 @@ import {
TCreateAgentVaultSessionDTO,
TCreateAgentVaultVariableDTO,
TDeleteAgentVaultPersonalValuesDTO,
+ TSetAgentVaultDelegationDTO,
TSetAgentVaultPersonalValuesDTO,
TUpdateAgentVaultAccessBundleDTO,
TUpdateAgentVaultMemberRolesDTO,
@@ -36,6 +38,39 @@ import {
TUpdateAgentVaultVariableDTO
} from "./types";
+export const useSetAgentVaultDelegation = () => {
+ const { currentOrg } = useOrganization();
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async ({ machineIdentityId, ...body }: TSetAgentVaultDelegationDTO) => {
+ const { data } = await apiRequest.put<{ delegation: TAgentVaultDelegation }>(
+ `/api/v1/agent-vault/delegations/${machineIdentityId}`,
+ body
+ );
+ return data.delegation;
+ },
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: agentVaultKeys.delegations(currentOrg.id) });
+ }
+ });
+};
+
+export const useDeleteAgentVaultDelegation = () => {
+ const { currentOrg } = useOrganization();
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async ({ machineIdentityId }: { machineIdentityId: string }) => {
+ const { data } = await apiRequest.delete<{ delegation: TAgentVaultDelegation }>(
+ `/api/v1/agent-vault/delegations/${machineIdentityId}`
+ );
+ return data.delegation;
+ },
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: agentVaultKeys.delegations(currentOrg.id) });
+ }
+ });
+};
+
export const useCreateAgentVaultAccessBundle = () => {
const { currentOrg } = useOrganization();
const queryClient = useQueryClient();
diff --git a/frontend/src/hooks/api/agentVault/queries.tsx b/frontend/src/hooks/api/agentVault/queries.tsx
index 61afbfcae8..c4f9e67e1f 100644
--- a/frontend/src/hooks/api/agentVault/queries.tsx
+++ b/frontend/src/hooks/api/agentVault/queries.tsx
@@ -22,6 +22,7 @@ import {
TAgentVaultAccessBundleDetails,
TAgentVaultAccessBundleListItem,
TAgentVaultDecryptedSessionLogPage,
+ TAgentVaultDelegation,
TAgentVaultMember,
TAgentVaultProductActor,
TAgentVaultProductMember,
@@ -102,6 +103,9 @@ export const agentVaultKeys = {
availableMembers: (orgId: string) => [...agentVaultKeys.members(orgId), "available"] as const,
availableMemberList: (orgId: string, params?: TListAgentVaultMembersDTO) =>
[...agentVaultKeys.availableMembers(orgId), params] as const,
+ delegations: (orgId: string) => [...agentVaultKeys.all(orgId), "delegations"] as const,
+ delegationsOf: (orgId: string, machineIdentityIds: string[]) =>
+ [...agentVaultKeys.delegations(orgId), machineIdentityIds] as const,
sessionLogSettings: (orgId: string) =>
[...agentVaultKeys.all(orgId), "settings", "session-logs"] as const,
sessionLogHealth: (orgId: string) =>
@@ -134,6 +138,24 @@ export const useListAgentVaultMembers = <T extends AgentVaultMemberType = AgentV
});
};
+// Read through the list, so an identity with no delegation is an empty result rather than a 404. Admins only.
+export const useListAgentVaultDelegations = (machineIdentityIds: string[], enabled = true) => {
+ const { currentOrg } = useOrganization();
+
+ return useQuery({
+ queryKey: agentVaultKeys.delegationsOf(currentOrg.id, machineIdentityIds),
+ queryFn: async () => {
+ const { data } = await apiRequest.get<{ delegations: TAgentVaultDelegation[] }>(
+ "/api/v1/agent-vault/delegations",
+ { params: { machineIdentityIds: machineIdentityIds.join(","), limit: 100 } }
+ );
+ return data.delegations;
+ },
+ enabled: enabled && machineIdentityIds.length > 0,
+ placeholderData: (prev) => prev
+ });
+};
+
// One page is enough for a picker: past it the admin searches. The default lives here so both add
// dialogs page the same way.
const AVAILABLE_MEMBER_LIMIT = 50;
diff --git a/frontend/src/hooks/api/agentVault/types.ts b/frontend/src/hooks/api/agentVault/types.ts
index e515df2d6c..65d3f34c42 100644
--- a/frontend/src/hooks/api/agentVault/types.ts
+++ b/frontend/src/hooks/api/agentVault/types.ts
@@ -1,5 +1,6 @@
import {
AgentVaultCredentialType,
+ AgentVaultDelegationScope,
AgentVaultHttpMethod,
AgentVaultMemberType,
AgentVaultSessionLogDecision,
@@ -231,9 +232,13 @@ export type TAgentVaultSessionActor =
id: 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;
actor: TAgentVaultSessionActor;
+ actingIdentity: TAgentVaultSessionActingIdentity | null;
status: AgentVaultSessionStatus;
expiresAt: string | null;
revokedAt: string | null;
@@ -241,6 +246,22 @@ export type TAgentVaultSession = {
accessBundles: TAgentVaultSessionAccessBundle[];
};
+export type TAgentVaultDelegation = {
+ machineIdentity: { id: string; name: string };
+ scope: AgentVaultDelegationScope;
+ users: Omit<Extract<TAgentVaultActor, { type: AgentVaultMemberType.User }>, "type">[];
+ groups: Omit<Extract<TAgentVaultActor, { type: AgentVaultMemberType.Group }>, "type">[];
+ createdAt: string;
+ updatedAt: string;
+};
+
+export type TSetAgentVaultDelegationDTO = {
+ machineIdentityId: string;
+ scope: AgentVaultDelegationScope;
+ userIds?: string[];
+ groupIds?: string[];
+};
+
export type TAgentVaultMintedSession = {
id: string;
token: string;
diff --git a/frontend/src/hooks/api/auditLogs/constants.tsx b/frontend/src/hooks/api/auditLogs/constants.tsx
index 4568b48ff7..005f8dfe1f 100644
--- a/frontend/src/hooks/api/auditLogs/constants.tsx
+++ b/frontend/src/hooks/api/auditLogs/constants.tsx
@@ -493,6 +493,8 @@ export const eventToNameMap: { [K in EventType]: string } = {
[EventType.AGENT_VAULT_ACCESS_BUNDLE_MEMBER_REMOVE]: "Revoke access bundle",
[EventType.AGENT_VAULT_SESSION_MINT]: "Create session",
[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",
@@ -577,6 +579,8 @@ export const projectToEventsMap: Partial<Record<ProjectType, EventType[]>> = {
EventType.AGENT_VAULT_ACCESS_BUNDLE_MEMBER_REMOVE,
EventType.AGENT_VAULT_SESSION_MINT,
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 --git a/frontend/src/hooks/api/auditLogs/enums.tsx b/frontend/src/hooks/api/auditLogs/enums.tsx
index ececd5f701..edcd46076a 100644
--- a/frontend/src/hooks/api/auditLogs/enums.tsx
+++ b/frontend/src/hooks/api/auditLogs/enums.tsx
@@ -491,6 +491,8 @@ export enum EventType {
AGENT_VAULT_ACCESS_BUNDLE_MEMBER_REMOVE = "agent-vault-access-bundle-member-remove",
AGENT_VAULT_SESSION_MINT = "agent-vault-session-mint",
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 --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/AgentVaultSessionsPage.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/AgentVaultSessionsPage.tsx
index a9a9ee948a..747da44696 100644
--- a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/AgentVaultSessionsPage.tsx
+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/AgentVaultSessionsPage.tsx
@@ -407,12 +407,19 @@ export const AgentVaultSessionsPage = () => {
<UserIcon className="size-4 text-muted" />
)}
{memberDisplayName(session.actor)}
+ {session.actingIdentity && (
+ <span className="text-muted">
+ via {session.actingIdentity.name}
+ </span>
+ )}
</div>
</TooltipTrigger>
<TooltipContent>
{session.actor.type === AgentVaultMemberType.MachineIdentity
? `${session.actor.id ?? "Deleted"} (machine identity)`
: memberSubtitle(session.actor)}
+ {session.actingIdentity &&
+ `, started by the machine identity "${session.actingIdentity.name}"`}
</TooltipContent>
</Tooltip>
</TableCell>
diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionDetailSheet.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionDetailSheet.tsx
index af0bad9751..7d935e4001 100644
--- a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionDetailSheet.tsx
+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionDetailSheet.tsx
@@ -99,6 +99,23 @@ export const SessionDetailSheet = ({ session, isPending = false, onRevoke }: Pro
)}
</DetailValue>
</Detail>
+ {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 className="min-w-0">
<DetailLabel>
{session.accessBundles.length === 1 ? "Access Bundle" : "Access Bundles"}
diff --git a/frontend/src/pages/agent-vault/agent-vault-docs-urls.ts b/frontend/src/pages/agent-vault/agent-vault-docs-urls.ts
index e1182d205d..5f20e8143b 100644
--- a/frontend/src/pages/agent-vault/agent-vault-docs-urls.ts
+++ b/frontend/src/pages/agent-vault/agent-vault-docs-urls.ts
@@ -8,6 +8,7 @@ export const AgentVaultDocsUrls = {
memberProvidedValues: `${AGENT_VAULT_DOCS_BASE_URL}/services#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 --git a/frontend/src/pages/project/IdentityDetailsByIDPage/IdentityDetailsByIDPage.tsx b/frontend/src/pages/project/IdentityDetailsByIDPage/IdentityDetailsByIDPage.tsx
index 1b8187d010..ff9940b78c 100644
--- a/frontend/src/pages/project/IdentityDetailsByIDPage/IdentityDetailsByIDPage.tsx
+++ b/frontend/src/pages/project/IdentityDetailsByIDPage/IdentityDetailsByIDPage.tsx
@@ -15,6 +15,7 @@ import {
VenetianMaskIcon
} 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 { OrgPermissionCan, ProjectPermissionCan } from "@app/components/permissions";
@@ -404,6 +405,12 @@ const Page = () => {
</CardContent>
</Card>
)}
+ {isAgentVault && (
+ <IdentityDelegationSection
+ machineIdentityId={identityId}
+ machineIdentityName={identityMembershipDetails.identity.name}
+ />
+ )}
{!isAgentVault && (
<IdentityRoleDetailsSection
identityMembershipDetails={identityMembershipDetails}