Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat(agent-vault): sessions on a user's behalf belong to the machine identity
Scott Wilson1d2c5af423ac
diff --git a/backend/e2e-test/routes/v1/agent-vault-session-logs.spec.ts b/backend/e2e-test/routes/v1/agent-vault-session-logs.spec.tsindex f24f717504..8f4f698590 100644--- a/backend/e2e-test/routes/v1/agent-vault-session-logs.spec.ts+++ b/backend/e2e-test/routes/v1/agent-vault-session-logs.spec.ts@@ -4,6 +4,7 @@ import { fakeAwsConnection } from "e2e-test/fakes/aws-connection-fns";import { FAKE_DEFAULT_STORAGE, fakeDefaultStorage } from "e2e-test/fakes/object-storage-default-fns";import { fakeS3Bucket } from "e2e-test/fakes/s3";import { createAwsAppConnection, deleteAwsAppConnection } from "e2e-test/testUtils/app-connections";+import { addUserMembership, createUser, createUserAccessToken, deleteUsers } from "e2e-test/testUtils/users";import { v7 as uuidv7 } from "uuid";import { OrgMembershipRole, ProjectMembershipRole, ProjectType } from "@app/db/schemas";@@ -782,7 +783,7 @@ describe("Agent Vault session logs", async () => {const relabelled = await inject("PATCH", `/api/v1/agent-vault/sessions/${sessionId}`, { label: "afterwards" });expect(relabelled.statusCode).toBe(400);expect(relabelled.json().message).toBe(- "The user or machine identity that owned or started this session was deleted, so its label can't be changed."+ "The user or machine identity that owned this session, or the user it was started on behalf of, was deleted, so its label can't be changed.");const revoked = await inject("POST", `/api/v1/agent-vault/sessions/${sessionId}/revoke`);@@ -1208,5 +1209,58 @@ describe("Agent Vault session logs", async () => {await member.cleanup();}});++ test("a session on a user's behalf is the identity's: its logs go to the identity and admins, never the user", async () => {+ await configure();+ const projectId = await getProjectId();+ const bundle = await createAccessBundle(`session-logs-obo-${Date.now()}`);+ const bot = await createMemberIdentity(`session-logs-obo-bot-${Date.now()}`);+ const alice = await createUser("session-logs-obo-alice");+ try {+ const orgId = seedData1.organization.id;+ await addUserMembership({ userId: alice.userId, orgId, role: OrgMembershipRole.Member });+ await addUserMembership({ userId: alice.userId, orgId, projectId, role: ProjectMembershipRole.Member });+ const granted = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/members`, {+ userIds: [alice.userId],+ machineIdentityIds: [bot.id]+ });+ expect(granted.statusCode).toBe(200);+ const delegated = await testServer.inject({+ method: "PUT",+ url: `/api/v1/agent-vault/delegations/${bot.id}`,+ headers: authHeader,+ body: { scope: "selected", userIds: [alice.userId] }+ });+ expect(delegated.statusCode).toBe(200);++ const minted = await bot.as("POST", "/api/v1/agent-vault/sessions", {+ accessBundles: [bundle.name],+ onBehalfOf: { userId: alice.userId }+ });+ expect(minted.statusCode, minted.payload).toBe(200);+ const sessionId = minted.json().session.id as string;++ const proxy = await createProxy(`session-logs-obo-${Date.now()}`);+ const { uploadUrl } = await requestUploadUrl(proxy, sessionId);+ fakeS3Bucket.put(uploadUrl, Buffer.alloc(CHUNK_BYTES));++ const aliceToken = await createUserAccessToken({ userId: alice.userId, orgId });+ for await (const suffix of ["logs", "logs/tail"]) {+ const url = `/api/v1/agent-vault/sessions/${sessionId}/${suffix}`;+ const [byBot, byAdmin, byAlice] = await Promise.all([+ bot.as("GET", url),+ inject("GET", url),+ testServer.inject({ method: "GET", url, headers: { authorization: `Bearer ${aliceToken}` } })+ ]);+ expect([suffix, byBot.statusCode, byAdmin.statusCode, byAlice.statusCode]).toEqual([suffix, 200, 200, 404]);+ expect(byBot.json().chunks).toHaveLength(1);+ expect(byAdmin.json().chunks).toHaveLength(1);+ expect(byAlice.json().message).toBe(`Session with ID '${sessionId}' not found`);+ }+ } finally {+ await bot.cleanup();+ await deleteUsers([alice.userId]);+ }+ });});});diff --git a/backend/e2e-test/routes/v1/agent-vault.spec.ts b/backend/e2e-test/routes/v1/agent-vault.spec.tsindex a10c0d3f3f..791e60fbe8 100644--- a/backend/e2e-test/routes/v1/agent-vault.spec.ts+++ b/backend/e2e-test/routes/v1/agent-vault.spec.ts@@ -4591,8 +4591,8 @@ describe("Agent Vault V1 Router", async () => {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-") }+ actor: { type: "machineIdentity", id: bot.id, name: expect.stringContaining("obo-cover-bot-") },+ onBehalfOf: expect.objectContaining({ type: "user", id: alice.userId, username: alice.username })});// Bob is in Agent Vault but not in the delegation, and a user who doesn't exist reads the same.@@ -4634,7 +4634,7 @@ describe("Agent Vault V1 Router", async () => {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 });+ expect(read.json().session.onBehalfOf).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);@@ -4944,7 +4944,7 @@ describe("Agent Vault V1 Router", async () => {}});- test("the acting identity can see and revoke what it started, and deleting it ends those sessions", async () => {+ test("the identity can see and revoke what it started on a user's behalf, 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()}`;@@ -4967,18 +4967,21 @@ describe("Agent Vault V1 Router", async () => {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])- );+ // An admin finds them by either side: the identity that owns them or the user they act for.+ for await (const term of [botName, alice.username]) {+ const found = await inject("GET", `${sessionsUrl}?scope=all&limit=100&search=${encodeURIComponent(term)}`);+ 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 }+ actor: { type: "machineIdentity", id: null, name: botName },+ onBehalfOf: expect.objectContaining({ id: alice.userId })});} finally {await bot.cleanup();@@ -4986,10 +4989,12 @@ describe("Agent Vault V1 Router", async () => {}});- // Nothing stops an identity being named "", and the name is what marks a session as started on someone's behalf.- test("a session started by an identity named '' is checked like any other on a user's behalf", async () => {- const bundle = await createAccessBundle(`obo-unnamed-${Date.now()}`);- const proxy = await inject("POST", "/api/v1/agent-vault/proxies", { name: `obo-unnamed-${Date.now()}` });+ // Deleting the user nulls the id and leaves the name, which is what keeps the session from reading as the+ // identity's own.+ test("deleting the user ends a session on their behalf instead of leaving it to the identity", async () => {+ const projectId = await getProjectId();+ const bundle = await createAccessBundle(`obo-user-gone-${Date.now()}`);+ const proxy = await inject("POST", "/api/v1/agent-vault/proxies", { name: `obo-user-gone-${Date.now()}` });expect(proxy.statusCode).toBe(200);const proxyToken = proxy.json().proxyToken as string;const resolve = (sessionToken: string) =>@@ -4999,35 +5004,37 @@ describe("Agent Vault V1 Router", async () => {headers: { authorization: `Bearer ${proxyToken}`, "x-infisical-agent-session": sessionToken }});- const bot = await createMemberIdentity("");+ const bot = await createMemberIdentity(`obo-user-gone-bot-${Date.now()}`);+ const alice = await createAgentVaultUser("obo-user-gone-alice", projectId);try {- await grantBundle(bundle.id, { machineIdentityIds: [bot.id] });- await delegate(bot, { scope: "selected", userIds: [seedData1.id] });- const minted = await mintFor(bot, { userId: seedData1.id }, bundle.name);+ await grantBundle(bundle.id, { userIds: [alice.userId], machineIdentityIds: [bot.id] });+ await delegate(bot, { scope: "selected", userIds: [alice.userId] });+ const minted = await mintFor(bot, { userId: alice.userId }, bundle.name);expect(minted.statusCode).toBe(200);const { id, token } = minted.json().session as { id: string; token: string };-- expect((await inject("GET", `${sessionsUrl}/${id}`)).json().session.actingIdentity).toEqual({- id: bot.id,- name: ""- });expect((await resolve(token)).statusCode).toBe(200);- // The seeded admin still reaches the bundle, so only the delegation check can stop the session.- expect((await inject("DELETE", delegationUrl(bot.id))).statusCode).toBe(200);+ await deleteUsers([alice.userId]);expect((await resolve(token)).statusCode).toBe(401);- await bot.cleanup();- expect((await inject("GET", `${sessionsUrl}/${id}`)).json().session).toMatchObject({+ const read = await bot.as("GET", `${sessionsUrl}/${id}`);+ expect(read.statusCode).toBe(200);+ expect(read.json().session).toMatchObject({status: "revoked",- actingIdentity: { id: null, name: "" }+ actor: { type: "machineIdentity", id: bot.id },+ onBehalfOf: expect.objectContaining({ id: null, username: alice.username })});++ const relabel = await bot.as("PATCH", `${sessionsUrl}/${id}`, { label: "after" });+ expect(relabel.statusCode).toBe(400);+ expect(relabel.json().message).toContain("the user it was started on behalf of, was deleted");} finally {await bot.cleanup();+ await deleteUsers([alice.userId]);}});- test("a revoke that finds the acting identity just deleted reports the session as it is now", async () => {+ test("a revoke that finds the session's user just deleted reports the session as it is now", async () => {const bundle = await createAccessBundle(`obo-revoke-race-${Date.now()}`);const bot = await createMemberIdentity(`obo-revoke-race-bot-${Date.now()}`);try {@@ -5037,8 +5044,8 @@ describe("Agent Vault V1 Router", async () => {expect(minted.statusCode).toBe(200);const sessionId = minted.json().session.id as string;- // The revoke reads the session first, then queues its write behind this lock. Deleting the identity sets- // actingIdentityId to NULL, so the write skips the row and the answer comes from a read of the primary.+ // The revoke reads the session first, then queues its write behind this lock. Deleting the user sets+ // onBehalfOfUserId to NULL, so the write skips the row and the answer comes from a read of the primary.const trx = await testDb.transaction();try {const { rows } = await trx.raw("select pg_backend_pid() as pid");@@ -5046,7 +5053,7 @@ describe("Agent Vault V1 Router", async () => {const pending = inject("POST", `${sessionsUrl}/${sessionId}/revoke`);await waitUntilBlockedBy(rows[0].pid);- await trx("agent_vault_sessions").where({ id: sessionId }).update({ actingIdentityId: null });+ await trx("agent_vault_sessions").where({ id: sessionId }).update({ onBehalfOfUserId: null });await trx.commit();const revoked = await pending;@@ -5054,7 +5061,7 @@ describe("Agent Vault V1 Router", async () => {expect(revoked.json().session).toMatchObject({status: "revoked",revokedAt: null,- actingIdentity: { id: null, name: expect.stringContaining("obo-revoke-race-bot-") }+ onBehalfOf: expect.objectContaining({ id: null })});} catch (err) {if (!trx.isCompleted()) await trx.rollback();@@ -5106,7 +5113,7 @@ describe("Agent Vault V1 Router", async () => {}});- test("the identity's session list and reads leave out sessions the user started themselves", async () => {+ test("the identity and the user each see only their own sessions, not what the identity started for the user", async () => {const projectId = await getProjectId();const bundle = await createAccessBundle(`obo-own-${Date.now()}`);const bot = await createMemberIdentity(`obo-own-bot-${Date.now()}`);@@ -5131,6 +5138,23 @@ describe("Agent Vault V1 Router", async () => {expect(listedIds).toContain(startedForAlice);expect(listedIds).not.toContain(alicesOwn);expect((await bot.as("GET", `${sessionsUrl}/${alicesOwn}`)).statusCode).toBe(404);++ // The session is the identity's, so to the user it reads exactly like one that doesn't exist.+ const asAlice = (method: "GET" | "POST" | "PATCH", url: string, body?: Record<string, unknown>) =>+ testServer.inject({ method, url, headers: { authorization: `Bearer ${aliceToken}` }, ...(body ? { body } : {}) });+ const alicesList = await asAlice("GET", `${sessionsUrl}?limit=100`);+ const alicesListIds = (alicesList.json().sessions as { id: string }[]).map((row) => row.id);+ expect(alicesListIds).toContain(alicesOwn);+ expect(alicesListIds).not.toContain(startedForAlice);+ const refused = await Promise.all([+ asAlice("GET", `${sessionsUrl}/${startedForAlice}`),+ asAlice("POST", `${sessionsUrl}/${startedForAlice}/revoke`),+ asAlice("PATCH", `${sessionsUrl}/${startedForAlice}`, { label: "mine now" }),+ asAlice("GET", `${sessionsUrl}/${startedForAlice}/logs`),+ asAlice("GET", `${sessionsUrl}/${startedForAlice}/logs/tail`)+ ]);+ refused.forEach((res) => expect(res.statusCode, res.payload).toBe(404));+ expect((await inject("GET", `${sessionsUrl}/${startedForAlice}`)).json().session.status).toBe("active");} finally {await bot.cleanup();await deleteUsers([alice.userId]);diff --git a/backend/src/db/migrations/20261019120000_agent-vault-delegations.ts b/backend/src/db/migrations/20261019120000_agent-vault-delegations.tsindex 5ceb9a8f11..8b957f2bfc 100644--- a/backend/src/db/migrations/20261019120000_agent-vault-delegations.ts+++ b/backend/src/db/migrations/20261019120000_agent-vault-delegations.ts@@ -3,27 +3,28 @@ import { Knex } from "knex";import { TableName } from "../schemas";import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils";-const SESSION_ACTING_IDENTITY_CHECK = "agent_vault_sessions_acting_identity_check";+const SESSION_ON_BEHALF_OF_CHECK = "agent_vault_sessions_on_behalf_of_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"))) {+ // A session a machine identity starts on a user's behalf belongs to the identity and names the user here. The name+ // and email are snapshotted like actorName and actorEmail, and the name is what still marks the session as+ // on-behalf-of once deleting the user sets the id to NULL.+ if (!(await knex.schema.hasColumn(TableName.AgentVaultSession, "onBehalfOfUserId"))) {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);+ t.uuid("onBehalfOfUserId");+ t.foreign("onBehalfOfUserId").references("id").inTable(TableName.Users).onDelete("SET NULL");+ t.string("onBehalfOfUserName", 255);+ t.string("onBehalfOfUserEmail", 255);});await knex.raw(- `CREATE INDEX agent_vault_session_by_acting_identity ON ?? ("actingIdentityId") WHERE "actingIdentityId" IS NOT NULL`,+ `CREATE INDEX agent_vault_session_by_on_behalf_of_user ON ?? ("onBehalfOfUserId") WHERE "onBehalfOfUserId" IS NOT NULL`,[TableName.AgentVaultSession]);- // An on-behalf-of session is always a user's, and an id is never stored without the name. actorType can be NULL on- // rows the previous release writes during a rolling deploy.+ // An on-behalf-of session is always a machine identity's, and an id is never stored without the name. actorType can+ // be NULL on rows the previous release writes during a rolling deploy.await knex.raw(- `ALTER TABLE ?? ADD CONSTRAINT ?? CHECK (("actingIdentityName" IS NULL OR ("identityId" IS NULL AND ("actorType" IS NULL OR "actorType" = 'user'))) AND ("actingIdentityId" IS NULL OR "actingIdentityName" IS NOT NULL))`,- [TableName.AgentVaultSession, SESSION_ACTING_IDENTITY_CHECK]+ `ALTER TABLE ?? ADD CONSTRAINT ?? CHECK (("onBehalfOfUserName" IS NULL OR ("userId" IS NULL AND ("actorType" IS NULL OR "actorType" = 'machineIdentity'))) AND ("onBehalfOfUserId" IS NULL OR "onBehalfOfUserName" IS NOT NULL))`,+ [TableName.AgentVaultSession, SESSION_ON_BEHALF_OF_CHECK]);}@@ -90,11 +91,11 @@ export async function down(knex: Knex): Promise<void> {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.+ if (await knex.schema.hasColumn(TableName.AgentVaultSession, "onBehalfOfUserId")) {+ // Without the columns an on-behalf-of session reads as the identity's own and would resolve with no delegation or+ // user behind it, so every one still live is revoked first.await knex(TableName.AgentVaultSession)- .whereNotNull("actingIdentityName")+ .whereNotNull("onBehalfOfUserName").whereNull("revokedAt").update({ revokedAt: new Date() });@@ -102,13 +103,14 @@ export async function down(knex: Knex): Promise<void> {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+ SESSION_ON_BEHALF_OF_CHECK]);- await knex.raw(`DROP INDEX IF EXISTS agent_vault_session_by_acting_identity`);+ await knex.raw(`DROP INDEX IF EXISTS agent_vault_session_by_on_behalf_of_user`);await knex.schema.alterTable(TableName.AgentVaultSession, (t) => {- t.dropForeign(["actingIdentityId"]);- t.dropColumn("actingIdentityId");- t.dropColumn("actingIdentityName");+ t.dropForeign(["onBehalfOfUserId"]);+ t.dropColumn("onBehalfOfUserId");+ t.dropColumn("onBehalfOfUserName");+ t.dropColumn("onBehalfOfUserEmail");});}}diff --git a/backend/src/db/sanitized-schema.yaml b/backend/src/db/sanitized-schema.yamlindex f7741e8f6c..77a537b585 100644--- a/backend/src/db/sanitized-schema.yaml+++ b/backend/src/db/sanitized-schema.yaml@@ -139,7 +139,7 @@ tables:- userId- identityId- actorType- - actingIdentityId+ - onBehalfOfUserId- expiresAt- revokedAt- createdAtdiff --git a/backend/src/db/schemas/agent-vault-sessions.ts b/backend/src/db/schemas/agent-vault-sessions.tsindex 8c52d62eaf..c2029aa0ac 100644--- a/backend/src/db/schemas/agent-vault-sessions.ts+++ b/backend/src/db/schemas/agent-vault-sessions.ts@@ -23,8 +23,9 @@ export const AgentVaultSessionsSchema = z.object({updatedAt: z.date(),encryptedSessionLogKey: zodBuffer.nullable().optional(),actorType: z.string().nullable().optional(),- actingIdentityId: z.string().uuid().nullable().optional(),- actingIdentityName: z.string().nullable().optional(),+ onBehalfOfUserId: z.string().uuid().nullable().optional(),+ onBehalfOfUserName: z.string().nullable().optional(),+ onBehalfOfUserEmail: z.string().nullable().optional(),label: z.string().nullable().optional()});diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-schemas.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-schemas.tsindex 62acfd26dc..23953a7c8a 100644--- a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-schemas.ts+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-schemas.ts@@ -676,6 +676,12 @@ export const AgentVaultSessionActorSchema = z.discriminatedUnion("type", [sessionActorSchemas.machineIdentity]);+// Shaped like a session's user actor, so a client shows the user a session acts for the way it shows an owner.+export const AgentVaultSessionOnBehalfOfSchema = sessionActorSchemas.user.extend({+ type: z.literal(AgentVaultMemberType.User).describe(AGENT_VAULT.SESSION.onBehalfOfType),+ id: z.string().uuid().nullable().describe(AGENT_VAULT.SESSION.onBehalfOfUserIdRead)+});+// No .default().optional(): the optional wraps the default and the default never applies.export const agentVaultListQuery = (docs: { search: string; limit: string; offset: string }) => ({search: zdiff --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.tsindex 46a6f8c167..3755027a31 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@@ -28,7 +28,7 @@ import { AuthMode } from "@app/services/auth/auth-type";import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";import { actorContext } from "./agent-vault-router-fns";-import { AgentVaultSessionActorSchema } from "./agent-vault-schemas";+import { AgentVaultSessionActorSchema, AgentVaultSessionOnBehalfOfSchema } from "./agent-vault-schemas";const SessionAccessBundleSchema = z.object({id: z.string().uuid().nullable(),@@ -40,13 +40,7 @@ const SessionSchema = z.object({id: z.string().uuid().describe(AGENT_VAULT.SESSION.sessionId),label: z.string().nullable().describe(AGENT_VAULT.SESSION.label),actor: AgentVaultSessionActorSchema,- actingIdentity: z- .object({- id: z.string().uuid().nullable().describe(AGENT_VAULT.SESSION.actingIdentityId),- name: z.string().describe(AGENT_VAULT.SESSION.actingIdentityName)- })- .nullable()- .describe(AGENT_VAULT.SESSION.actingIdentity),+ onBehalfOf: AgentVaultSessionOnBehalfOfSchema.nullable().describe(AGENT_VAULT.SESSION.onBehalfOfSession),status: z.nativeEnum(AgentVaultSessionStatus),expiresAt: z.date().nullable().describe(AGENT_VAULT.SESSION.expiresAt),revokedAt: z.date().nullable(),diff --git a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.test.ts b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.test.tsindex bf09948d6c..3aa06bbbfe 100644--- a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.test.ts+++ b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.test.ts@@ -303,11 +303,13 @@ describe("resolve for a session on a user's behalf", () => {const setupOnBehalfOf = ({user = {},identity = {},- delegationCoversUser = true+ delegationCoversUser = true,+ isUserDeleted = false}: {user?: TActorSetup;identity?: TActorSetup;delegationCoversUser?: boolean;+ isUserDeleted?: boolean;}) => {const actor = (actorId: string) => (actorId === IDENTITY_ID ? identity : user);const findResolvableServices = vi.fn(async () => [] as TResolveServiceRow[]);@@ -325,10 +327,10 @@ describe("resolve for a session on a user's behalf", () => {({id: "session-1",projectId: PROJECT_ID,- userId: USER_ID,- identityId: null,- actingIdentityId: IDENTITY_ID,- actingIdentityName: "slack-bot",+ userId: null,+ identityId: IDENTITY_ID,+ onBehalfOfUserId: isUserDeleted ? null : USER_ID,+ onBehalfOfUserName: "Alice Nguyen",revokedAt: null,expiresAt: null}) as never@@ -409,4 +411,15 @@ describe("resolve for a session on a user's behalf", () => {const { resolve } = setupOnBehalfOf({ user: { grants: ["bundle-a"] }, identity: { isActive: false } });await expect(resolve()).rejects.toThrow(UnauthorizedError);});++ test("a user deactivated in the org is a 401", async () => {+ const { resolve } = setupOnBehalfOf({ user: { grants: ["bundle-a"], isActive: false } });+ await expect(resolve()).rejects.toThrow(UnauthorizedError);+ });++ // The name is left behind, so the session must not fall back to resolving as the identity's own.+ test("a session whose user was deleted is a 401, not the identity's own session", async () => {+ const { resolve } = setupOnBehalfOf({ identity: { isAdmin: true }, isUserDeleted: true });+ await expect(resolve()).rejects.toThrow(UnauthorizedError);+ });});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.tsindex 5ac1aed17b..523ef657bc 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@@ -1,6 +1,12 @@import { ForbiddenError } from "@casl/ability";-import { ActionProjectType, OrgMembershipStatus, ProjectMembershipRole, TAgentVaultProxies } from "@app/db/schemas";+import {+ ActionProjectType,+ OrgMembershipStatus,+ ProjectMembershipRole,+ TAgentVaultProxies,+ TAgentVaultSessions+} from "@app/db/schemas";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";import {ProjectPermissionAgentVaultProxyActions,@@ -112,6 +118,16 @@ type TAgentVaultProxyServiceFactoryDep = {export type TAgentVaultProxyServiceFactory = ReturnType<typeof agentVaultProxyServiceFactory>;+// A session on a user's behalf uses that user's personal values, never those of the identity that owns it. Called only+// after the session is authorized, which refuses one whose owner or user is gone.+const personalValuesOwner = (+ session: Pick<TAgentVaultSessions, "userId" | "identityId" | "onBehalfOfUserId">+): TAgentVaultOwner => {+ if (session.onBehalfOfUserId) return { userId: session.onBehalfOfUserId };+ if (session.userId) return { userId: session.userId };+ return { identityId: session.identityId! };+};+// Opens each variable at most once per resolve. An id with no row stays as text, and the service that used it is// recorded so one log line can name every service affected.const createVariableLookup = (@@ -558,10 +574,10 @@ export const agentVaultProxyServiceFactory = ({};/**- * A member-provided field comes from what the session's actor saved for the service, expanded against their own- * personal variables only, after the admin's fields were expanded against the global ones: a value is never- * expanded twice. A service whose actor hasn't set every field the admin leaves to them goes out flagged and- * without a credential, so the proxy refuses it instead of sending a half-built one.+ * A member-provided field comes from what the session's owner saved for the service, or, on a user's behalf, what+ * that user saved, expanded against their own personal variables only, after the admin's fields were expanded+ * against the global ones: a value is never expanded twice. If they haven't set every field the admin leaves to them,+ * the service goes out flagged and without a credential, so the proxy refuses it instead of sending a half-built one.*/const $applyPersonalValues = async ({sessionId,@@ -657,30 +673,30 @@ 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. Returns the bundles the identity reaches (null for every bundle), since the session reaches- // only what both the identity and the user reach.- const $getActingIdentityReach = async ({+ // The user a session was started on behalf of has to still be in the org and in Agent Vault, and the delegation of the+ // identity that owns the session has to still cover them. Read on every resolve, so taking any of them away ends the+ // session on the proxy's next poll. Returns the bundles the user reaches (null for every bundle), since the session+ // reaches only what both the identity and the user reach.+ const $getOnBehalfOfUserReach = async ({projectId,orgId,- userId,- actingIdentityId+ identityId,+ userId}: {projectId: string;orgId: string;+ identityId: string | null;userId: string | null;- actingIdentityId: string | null;}): Promise<string[] | null> => {const refused = () =>new UnauthorizedError({- message: "The machine identity that started this session is no longer allowed to act on behalf of its user"+ message: "The machine identity that owns this session is no longer allowed to act on behalf of its user"});- if (!actingIdentityId || !userId) throw refused();+ if (!identityId || !userId) throw refused();const orgMembership = await orgDAL.findEffectiveOrgMembership({- actorType: ActorType.IDENTITY,- actorId: actingIdentityId,+ actorType: ActorType.USER,+ actorId: userId,orgId,status: OrgMembershipStatus.Accepted});@@ -690,8 +706,8 @@ export const agentVaultProxyServiceFactory = ({let liveGroupIds: string[];try {const { permission, hasRole, memberships } = await permissionService.getProjectPermission({- actor: ActorType.IDENTITY,- actorId: actingIdentityId,+ actor: ActorType.USER,+ actorId: userId,projectId,actorAuthMethod: null,actorOrgId: orgId,@@ -707,14 +723,14 @@ export const agentVaultProxyServiceFactory = ({throw error;}- if (!(await agentVaultDelegationDAL.identityCoversUser({ projectId, identityId: actingIdentityId, userId }))) {+ if (!(await agentVaultDelegationDAL.identityCoversUser({ projectId, identityId, userId }))) {throw refused();}if (isAdmin) return null;return findReachableAccessBundleIds(membershipDAL, {projectId,- actor: { type: ActorType.IDENTITY, id: actingIdentityId },+ actor: { type: ActorType.USER, id: userId },groupIds: liveGroupIds});};@@ -744,15 +760,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 an empty one, and even after deleting the identity nulls its id.- const actingIdentity =- session.actingIdentityName != null+ // The name marks an on-behalf-of session, even after deleting the user nulls its id.+ const onBehalfOf =+ session.onBehalfOfUserName != null? {- reach: await $getActingIdentityReach({+ reach: await $getOnBehalfOfUserReach({projectId: session.projectId,orgId,- userId: session.userId ?? null,- actingIdentityId: session.actingIdentityId ?? null+ identityId: session.identityId ?? null,+ userId: session.onBehalfOfUserId ?? null})}: null;@@ -809,7 +825,7 @@ export const agentVaultProxyServiceFactory = ({actor,groupIds: liveGroupIds});- const accessBundleIds = actingIdentity ? intersectAccessBundleIds(actorReach, actingIdentity.reach) : actorReach;+ const accessBundleIds = onBehalfOf ? intersectAccessBundleIds(actorReach, onBehalfOf.reach) : actorReach;return { session, proxy, accessBundleIds };};@@ -954,7 +970,7 @@ export const agentVaultProxyServiceFactory = ({const services = await $applyPersonalValues({sessionId: session.id,projectId: session.projectId,- owner: session.userId ? { userId: session.userId } : { identityId: session.identityId! },+ owner: personalValuesOwner(session),rows,services: await $expandVariableReferences({sessionId: session.id,diff --git a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-types.ts b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-types.tsindex 82c7326408..0e3a229bfc 100644--- a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-types.ts+++ b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-types.ts@@ -97,7 +97,7 @@ export type TResolvedService = {| { type: AgentVaultCredentialType.Passthrough };customHeaders: { name: string; prefix: string; value: string }[];substitutions: { placeholder: string; surfaces: string[]; value: string }[];- // The service takes part of its credential from each member and the session's actor has not set their values,- // so the proxy refuses its requests rather than sending them without one.+ // The service takes part of its credential from each member and the member whose values the session uses (its owner,+ // or the user it acts for) hasn't set them, so the proxy refuses its requests rather than sending them without one.personalValuesMissing: boolean;};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.tsindex a0d28786b1..dae223a7e5 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 { TAgentVaultSessionActingIdentity, TAgentVaultSessionActor } from "./agent-vault-session-types";+import { TAgentVaultSessionActor, TAgentVaultSessionOnBehalfOf } from "./agent-vault-session-types";export type TAgentVaultSessionDALFactory = ReturnType<typeof agentVaultSessionDALFactory>;@@ -16,21 +16,21 @@ export type TAgentVaultSessionListRow = {id: string;userId: string | null;identityId: string | null;- actingIdentityId: string | null;- actingIdentityName: string | null;+ onBehalfOfUserId: string | null;+ onBehalfOfUserName: string | null;label: string | null;actor: TAgentVaultSessionActor;- actingIdentity: TAgentVaultSessionActingIdentity | null;+ onBehalfOf: TAgentVaultSessionOnBehalfOf | null;expiresAt: Date | null;revokedAt: Date | null;createdAt: Date;accessBundles: { id: string | null; name: string; position: number }[];};-// The acting identity's own alias, since the actor's identity is joined under the table's name.-const ACTING_IDENTITY = "actingIdentity";+// The on-behalf-of user's own alias, since the actor's user is joined under the table's name.+const ON_BEHALF_OF_USER = "onBehalfOfUser";-// Mirrors deriveSessionStatus: a session with neither actor id, or whose acting identity was deleted, counts as revoked.+// Mirrors deriveSessionStatus: a session with neither actor id, or whose on-behalf-of user was deleted, counts as revoked.const orphaned = (qb: Knex.QueryBuilder) =>void qb.where((sub) => {@@ -40,8 +40,8 @@ const orphaned = (qb: Knex.QueryBuilder) =>}).orWhere((sub) => {void sub- .whereNotNull(`${TableName.AgentVaultSession}.actingIdentityName`)- .whereNull(`${TableName.AgentVaultSession}.actingIdentityId`);+ .whereNotNull(`${TableName.AgentVaultSession}.onBehalfOfUserName`)+ .whereNull(`${TableName.AgentVaultSession}.onBehalfOfUserId`);});const live = (qb: Knex.QueryBuilder) =>void qb@@ -52,8 +52,8 @@ const live = (qb: Knex.QueryBuilder) =>}).where((sub) => {void sub- .whereNull(`${TableName.AgentVaultSession}.actingIdentityName`)- .orWhereNotNull(`${TableName.AgentVaultSession}.actingIdentityId`);+ .whereNull(`${TableName.AgentVaultSession}.onBehalfOfUserName`)+ .orWhereNotNull(`${TableName.AgentVaultSession}.onBehalfOfUserId`);});const statusFilter = (query: Knex.QueryBuilder, status: AgentVaultSessionStatus, now: Date) => {@@ -81,7 +81,39 @@ const statusFilter = (query: Knex.QueryBuilder, status: AgentVaultSessionStatus,});};-// A deleted owner leaves only the snapshot mint took, which holds a user's full name in one field.+type TJoinedUser = {+ id: string | null;+ username: string | null;+ email: string | null;+ firstName: string | null;+ lastName: string | null;+};++// A deleted user leaves only the snapshot mint took, which holds the full name in one field.+const toSessionUser = (+ user: TJoinedUser,+ snapshot: { name: string; email: string | null }+): TAgentVaultSessionOnBehalfOf => {+ if (user.id && user.username) {+ return {+ type: AgentVaultMemberType.User,+ id: user.id,+ username: user.username,+ email: user.email,+ firstName: user.firstName,+ lastName: user.lastName+ };+ }+ return {+ type: AgentVaultMemberType.User,+ id: null,+ username: snapshot.email ?? snapshot.name,+ email: snapshot.email,+ firstName: snapshot.name || null,+ lastName: null+ };+};+const toSessionActor = (row: {actorType?: string | null;userId: string | null;@@ -103,24 +135,16 @@ const toSessionActor = (row: {if (actorType === AgentVaultMemberType.MachineIdentity) {return { type: AgentVaultMemberType.MachineIdentity, id: row.identityId, name: row.identityName ?? row.actorName };}- if (row.userId && row.userUsername) {- return {- type: AgentVaultMemberType.User,+ return toSessionUser(+ {id: row.userId,username: row.userUsername,email: row.userEmail,firstName: row.userFirstName,lastName: row.userLastName- };- }- return {- type: AgentVaultMemberType.User,- id: null,- username: row.actorEmail ?? row.actorName,- email: row.actorEmail,- firstName: row.actorName || null,- lastName: null- };+ },+ { name: row.actorName, email: row.actorEmail }+ );};export const agentVaultSessionDALFactory = (db: TDbClient) => {@@ -161,15 +185,9 @@ export const agentVaultSessionDALFactory = (db: TDbClient) => {const applyFilters = (query: Knex.QueryBuilder) => {void query.where(`${TableName.AgentVaultSession}.projectId`, projectId);if (sessionId) void query.where(`${TableName.AgentVaultSession}.id`, sessionId);+ // A session on a user's behalf is the identity's, so it is never in the user's own list.if (actor?.type === ActorType.USER) void query.where(`${TableName.AgentVaultSession}.userId`, 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 (actor?.type === ActorType.IDENTITY) void query.where(`${TableName.AgentVaultSession}.identityId`, actor.id);if (statuses?.length) {void query.where((qb) => {statuses.forEach((status) => {@@ -186,9 +204,9 @@ 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`+ `${TableName.Users} as ${ON_BEHALF_OF_USER}`,+ `${TableName.AgentVaultSession}.onBehalfOfUserId`,+ `${ON_BEHALF_OF_USER}.id`);void query.where((qb) => {@@ -204,8 +222,14 @@ 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)+ .orWhereILike(`${ON_BEHALF_OF_USER}.username`, term)+ .orWhereRaw(`CONCAT_WS(' ', ??, ??) ILIKE ?`, [+ `${ON_BEHALF_OF_USER}.firstName`,+ `${ON_BEHALF_OF_USER}.lastName`,+ term+ ])+ .orWhereILike(`${TableName.AgentVaultSession}.onBehalfOfUserName`, term)+ .orWhereILike(`${TableName.AgentVaultSession}.onBehalfOfUserEmail`, term).orWhereExists((sub) => {void sub.select(db.raw("1"))@@ -253,9 +277,9 @@ 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`+ `${TableName.Users} as ${ON_BEHALF_OF_USER}`,+ `${TableName.AgentVaultSession}.onBehalfOfUserId`,+ `${ON_BEHALF_OF_USER}.id`).leftJoin(TableName.AgentVaultSessionAccessBundle,@@ -285,9 +309,13 @@ 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("onBehalfOfUserId").withSchema(TableName.AgentVaultSession),+ db.ref("onBehalfOfUserName").withSchema(TableName.AgentVaultSession),+ db.ref("onBehalfOfUserEmail").withSchema(TableName.AgentVaultSession),+ db.ref("username").withSchema(ON_BEHALF_OF_USER).as("onBehalfOfUserLiveUsername"),+ db.ref("email").withSchema(ON_BEHALF_OF_USER).as("onBehalfOfUserLiveEmail"),+ db.ref("firstName").withSchema(ON_BEHALF_OF_USER).as("onBehalfOfUserLiveFirstName"),+ db.ref("lastName").withSchema(ON_BEHALF_OF_USER).as("onBehalfOfUserLiveLastName"),db.ref("accessBundleId").withSchema(TableName.AgentVaultSessionAccessBundle),db.ref("accessBundleName").withSchema(TableName.AgentVaultSessionAccessBundle),db.ref("name").withSchema(TableName.AgentVaultAccessBundle).as("liveAccessBundleName"),@@ -310,9 +338,13 @@ export const agentVaultSessionDALFactory = (db: TDbClient) => {identityName: string | null;actorName: string;actorEmail: string | null;- actingIdentityId: string | null;- actingIdentityName: string | null;- actingIdentityLiveName: string | null;+ onBehalfOfUserId: string | null;+ onBehalfOfUserName: string | null;+ onBehalfOfUserEmail: string | null;+ onBehalfOfUserLiveUsername: string | null;+ onBehalfOfUserLiveEmail: string | null;+ onBehalfOfUserLiveFirstName: string | null;+ onBehalfOfUserLiveLastName: string | null;accessBundleId: string | null;accessBundleName: string | null;liveAccessBundleName: string | null;@@ -327,13 +359,22 @@ export const agentVaultSessionDALFactory = (db: TDbClient) => {id: row.id,userId: row.userId,identityId: row.identityId,- actingIdentityId: row.actingIdentityId,- actingIdentityName: row.actingIdentityName,+ onBehalfOfUserId: row.onBehalfOfUserId,+ onBehalfOfUserName: row.onBehalfOfUserName,label: row.label,actor: toSessionActor(row),- actingIdentity:- row.actingIdentityName !== null- ? { id: row.actingIdentityId, name: row.actingIdentityLiveName ?? row.actingIdentityName }+ onBehalfOf:+ row.onBehalfOfUserName !== null+ ? toSessionUser(+ {+ id: row.onBehalfOfUserId,+ username: row.onBehalfOfUserLiveUsername,+ email: row.onBehalfOfUserLiveEmail,+ firstName: row.onBehalfOfUserLiveFirstName,+ lastName: row.onBehalfOfUserLiveLastName+ },+ { name: row.onBehalfOfUserName, email: row.onBehalfOfUserEmail }+ ): null,expiresAt: row.expiresAt,revokedAt: row.revokedAt,@@ -357,9 +398,9 @@ export const agentVaultSessionDALFactory = (db: TDbClient) => {};// Conditional so two concurrent revokes cannot both believe they were the one that revoked it. The loser- // gets no row back, which is what keeps the audit trail down to a single revocation. A session whose owner, or- // whose acting identity, was deleted is skipped too: updatedAt is the only record of when, and this write would- // move it.+ // gets no row back, which is what keeps the audit trail down to a single revocation. A session whose owner, or the+ // user it was started on behalf of, was deleted is skipped too: updatedAt is the only record of when, and this write+ // would move it.const revokeIfActive = async (id: string, revokedAt: Date, tx?: Knex) => {try {const [row] = (await (tx || db)(TableName.AgentVaultSession)@@ -369,7 +410,7 @@ export const agentVaultSessionDALFactory = (db: TDbClient) => {void qb.whereNotNull("userId").orWhereNotNull("identityId");}).where((qb) => {- void qb.whereNull("actingIdentityName").orWhereNotNull("actingIdentityId");+ void qb.whereNull("onBehalfOfUserName").orWhereNotNull("onBehalfOfUserId");}).update({ revokedAt }, "*")) as TAgentVaultSessions[];return row as TAgentVaultSessions | undefined;@@ -379,7 +420,7 @@ export const agentVaultSessionDALFactory = (db: TDbClient) => {};// One statement on the primary: the row is locked, then rewritten only if it still has an owner (and, on a- // user's behalf, its acting identity), and its label+ // user's behalf, its user), and its label// before the write comes back. So two quick edits can't both read a stale label, the caller audits what// actually changed, and a session whose owner was just deleted isn't written even if a replica hasn't seen// that yet: updatedAt is the only record of when the owner went. No row back means no such session.@@ -387,12 +428,12 @@ export const agentVaultSessionDALFactory = (db: TDbClient) => {try {const { rows } = (await (tx || db).raw(`WITH previous AS (- SELECT id, label, "userId", "identityId", "actingIdentityId", "actingIdentityName"+ SELECT id, label, "userId", "identityId", "onBehalfOfUserId", "onBehalfOfUserName"FROM ?? WHERE id = ? AND "projectId" = ? FOR UPDATE), updated AS (UPDATE ?? AS session SET label = ? FROM previousWHERE session.id = previous.id AND (previous."userId" IS NOT NULL OR previous."identityId" IS NOT NULL)- AND (previous."actingIdentityName" IS NULL OR previous."actingIdentityId" IS NOT NULL)+ AND (previous."onBehalfOfUserName" IS NULL OR previous."onBehalfOfUserId" IS NOT NULL)RETURNING session.id)SELECT previous.label AS "previousLabel", EXISTS (SELECT 1 FROM updated) AS "isUpdated" FROM previous`,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.tsindex 0de2492ada..6546e84210 100644--- 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@@ -18,39 +18,39 @@ describe("agent vault session status", () => {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" };+ // The name outlives the user, which is how the row still says it was started on someone's behalf.+ test("an on-behalf-of session whose user was deleted reads as revoked", () => {+ const session = { ...live, identityId: "identity-1", onBehalfOfUserId: null, onBehalfOfUserName: "Alice Nguyen" };expect(isOrphanedSession(session)).toBe(true);expect(deriveSessionStatus(session)).toBe(AgentVaultSessionStatus.Revoked);});- // An identity can be named "", so a session is on someone's behalf when the name is set, not when it's truthy.- test("an empty acting identity name still marks an on-behalf-of session", () => {- const session = { ...live, userId: "user-1", actingIdentityId: null, actingIdentityName: "" };- expect(isOrphanedSession(session)).toBe(true);- expect(deriveSessionStatus(session)).toBe(AgentVaultSessionStatus.Revoked);- });-- test("an on-behalf-of session with both its user and its acting identity is active", () => {- const session = { ...live, userId: "user-1", actingIdentityId: "identity-1", actingIdentityName: "slack-bot" };+ test("an on-behalf-of session with both its identity and its user is active", () => {+ const session = {+ ...live,+ identityId: "identity-1",+ onBehalfOfUserId: "user-1",+ onBehalfOfUserName: "Alice Nguyen"+ };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" };+ const onBehalfOf = { userId: null, identityId: "identity-1", onBehalfOfUserId: "user-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);+ test("only the identity holds a session it started on a user's behalf, not the user", () => {expect(isSessionOwnedBy({ actor: ActorType.IDENTITY, actorId: "identity-1" }, onBehalfOf)).toBe(true);+ expect(isSessionOwnedBy({ actor: ActorType.USER, actorId: "user-1" }, onBehalfOf)).toBe(false);});// 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", () => {+ const own = { userId: "user-1", identityId: null };+ expect(isSessionOwnedBy({ actor: ActorType.USER, actorId: "user-1" }, own)).toBe(true);+ expect(isSessionOwnedBy({ actor: ActorType.IDENTITY, actorId: "user-1" }, own)).toBe(false);expect(isSessionOwnedBy({ actor: ActorType.USER, actorId: "identity-1" }, onBehalfOf)).toBe(false);- expect(isSessionOwnedBy({ actor: ActorType.IDENTITY, actorId: "user-1" }, onBehalfOf)).toBe(false);});});@@ -66,6 +66,7 @@ describe("describeSessionForAudit", () => {firstName: "Alice",lastName: null},+ onBehalfOf: null,accessBundles: [{ name: "release" }]})).toEqual({ sessionOwner: "[email protected]", accessBundleName: "release" });@@ -82,6 +83,7 @@ describe("describeSessionForAudit", () => {firstName: null,lastName: null},+ onBehalfOf: null,accessBundles: [{ name: "release" }]}).sessionOwner).toBe("alice");@@ -91,8 +93,40 @@ describe("describeSessionForAudit", () => {expect(describeSessionForAudit({actor: { type: AgentVaultMemberType.MachineIdentity, id: "i1", name: "github-actions" },+ onBehalfOf: null,accessBundles: []})).toEqual({ sessionOwner: "github-actions", accessBundleName: null });});++ test("names the identity as the owner of a session on a user's behalf, and the user it acts for", () => {+ const user = {+ type: AgentVaultMemberType.User as const,+ username: "alice",+ firstName: "Alice",+ lastName: null+ };+ expect(+ describeSessionForAudit({+ actor: { type: AgentVaultMemberType.MachineIdentity, id: "i1", name: "slack-assistant" },+ onBehalfOf: { ...user, id: "u1", email: "[email protected]" },+ accessBundles: [{ name: "release" }]+ })+ ).toEqual({+ sessionOwner: "slack-assistant",+ accessBundleName: "release",+ onBehalfOfUserId: "u1",+ onBehalfOfUserName: "alice",+ onBehalfOfUserEmail: "[email protected]"+ });++ // Once the user is deleted only the snapshot is left, with no id to record.+ expect(+ describeSessionForAudit({+ actor: { type: AgentVaultMemberType.MachineIdentity, id: "i1", name: "slack-assistant" },+ onBehalfOf: { ...user, id: null, email: null },+ accessBundles: []+ })+ ).toEqual({ sessionOwner: "slack-assistant", accessBundleName: null, onBehalfOfUserName: "alice" });+ });});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.tsindex b3a1371d52..d663ac9668 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@@ -6,7 +6,7 @@ import { z } from "zod";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 { TAgentVaultSessionActor, TAgentVaultSessionOnBehalfOf } from "./agent-vault-session-types";export const AGENT_VAULT_SESSION_TOKEN_PREFIX = "agv_";@@ -54,21 +54,20 @@ export const generateSessionToken = () => {type TSessionOwnerColumns = {userId?: string | null;identityId?: string | null;- actingIdentityId?: string | null;- actingIdentityName?: string | null;+ onBehalfOfUserId?: string | null;+ onBehalfOfUserName?: 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.+// keeps its user's name once that user 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) || (session.actingIdentityName != null && !session.actingIdentityId);+ (!session.userId && !session.identityId) || (session.onBehalfOfUserName != null && !session.onBehalfOfUserId);-// The machine identity that started a session on a user's behalf holds it alongside the user.+// A session started on a user's behalf belongs to the machine identity alone, so the user can't see it or its logs.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 || session.actingIdentityId === ctx.actorId));+ (ctx.actor === ActorType.IDENTITY && session.identityId === ctx.actorId);export const deriveSessionStatus = (session: { expiresAt: Date | null; revokedAt: Date | null } & TSessionOwnerColumns,@@ -82,11 +81,17 @@ export const deriveSessionStatus = (// Most sessions have no label, so a session's audit event also names whose session it is and what it carried.export const describeSessionForAudit = (session: {actor: TAgentVaultSessionActor;+ onBehalfOf: TAgentVaultSessionOnBehalfOf | null;accessBundles: { name: string }[];}) => ({sessionOwner:session.actor.type === AgentVaultMemberType.MachineIdentity? session.actor.name: (session.actor.email ?? session.actor.username),- accessBundleName: session.accessBundles[0]?.name ?? null+ accessBundleName: session.accessBundles[0]?.name ?? null,+ ...(session.onBehalfOf && {+ ...(session.onBehalfOf.id && { onBehalfOfUserId: session.onBehalfOf.id }),+ onBehalfOfUserName: session.onBehalfOf.username,+ ...(session.onBehalfOf.email && { onBehalfOfUserEmail: session.onBehalfOf.email })+ })});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.tsindex 1c0c1f9d09..f871ccd331 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@@ -77,12 +77,12 @@ export const agentVaultSessionServiceFactory = ({const toSessionView = ({userId,identityId,- actingIdentityId,- actingIdentityName,+ onBehalfOfUserId,+ onBehalfOfUserName,...session}: TAgentVaultSessionListRow) => ({...session,- status: deriveSessionStatus({ ...session, userId, identityId, actingIdentityId, actingIdentityName })+ status: deriveSessionStatus({ ...session, userId, identityId, onBehalfOfUserId, onBehalfOfUserName })});const resolveSessionTtl = (ttl: string | undefined, isOnBehalfOf: boolean) =>@@ -180,28 +180,22 @@ export const agentVaultSessionServiceFactory = ({kmsService);- // An on-behalf-of session belongs to the user, so resolve uses their personal values, and the caller is kept as- // the acting identity, whose reach resolve intersects with the user's.- 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- };+ // A session on a user's behalf belongs to the identity, so only it and admins see the session and its logs. The+ // user is kept alongside: resolve uses their personal values and intersects their reach with the identity's.+ const owner = {+ 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,+ ...(onBehalfOfUser && {+ onBehalfOfUserId: onBehalfOfUser.user.id,+ onBehalfOfUserName:+ `${onBehalfOfUser.user.firstName ?? ""} ${onBehalfOfUser.user.lastName ?? ""}`.trim() ||+ (onBehalfOfUser.user.email ?? onBehalfOfUser.user.username),+ onBehalfOfUserEmail: onBehalfOfUser.user.email ?? null+ })+ };const session = await agentVaultSessionDAL.transaction(async (tx) => {const created = await agentVaultSessionDAL.createWithId(@@ -324,8 +318,8 @@ export const agentVaultSessionServiceFactory = ({return { session: toSessionView({ ...session, revokedAt: revoked.revokedAt ?? null }), revokedNow: true };}- // Nothing was written: a concurrent revoke won, or the owner was deleted, which already reads as revoked and is- // left untouched. Report the row as it is now, which the read above may not have seen.+ // Nothing was written: a concurrent revoke won, or the owner or the user it acts for was deleted, which already+ // reads as revoked and is left untouched. Report the row as it is now, which the read above may not have seen.const current = await agentVaultSessionDAL.findByIdOnPrimary(session.id, projectId);return {session: toSessionView(@@ -335,11 +329,8 @@ export const agentVaultSessionServiceFactory = ({revokedAt: current.revokedAt ?? null,userId: current.userId ?? null,identityId: current.identityId ?? null,- actingIdentityId: current.actingIdentityId ?? null,- actingIdentity: session.actingIdentity && {- ...session.actingIdentity,- id: current.actingIdentityId ?? null- }+ onBehalfOfUserId: current.onBehalfOfUserId ?? null,+ onBehalfOf: session.onBehalfOf && { ...session.onBehalfOf, id: current.onBehalfOfUserId ?? null }}: session),@@ -362,7 +353,7 @@ export const agentVaultSessionServiceFactory = ({if (!updated.isUpdated) {throw new BadRequestError({message:- "The user or machine identity that owned or started this session was deleted, so its label can't be changed."+ "The user or machine identity that owned this session, or the user it was started on behalf of, was deleted, so its label can't be changed."});}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.tsindex 4f53758057..53a272701c 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@@ -39,8 +39,6 @@ export type TRevokeSessionDTO = {export type TGetSessionByIdDTO = TRevokeSessionDTO;-/** The machine identity that started a session on its actor's behalf. `id` is null once the identity is deleted. */-export type TAgentVaultSessionActingIdentity = { id: string | null; name: string };export type TUpdateSessionLabelDTO = TRevokeSessionDTO & {label: string | null;};@@ -55,3 +53,6 @@ export type TAgentVaultSessionActor =lastName: string | null;}| { type: AgentVaultMemberType.MachineIdentity; id: string | null; name: string };++/** The user a machine identity started a session on behalf of. `id` is null once the user is deleted. */+export type TAgentVaultSessionOnBehalfOf = Extract<TAgentVaultSessionActor, { type: AgentVaultMemberType.User }>;diff --git a/backend/src/ee/services/agent-vault/AGENTS.md b/backend/src/ee/services/agent-vault/AGENTS.mdindex 1e0f316fb4..3804912e2c 100644--- a/backend/src/ee/services/agent-vault/AGENTS.md+++ b/backend/src/ee/services/agent-vault/AGENTS.md@@ -104,7 +104,7 @@ and `packages/agentvault/` in the CLI repo. Frontend: `frontend/src/pages/agent-surfaces as `ProjectMembershipNotFound`, which resolve turns into a 401 so the proxy drops the session onthe next poll instead of riding its grace window.- Removing an actor from Agent Vault does not revoke their sessions. The sessions resolve to nothing while- the actor is out and work again if the actor is added back. Settled with the product owner.+ the actor is out and work again if the actor is added back.- Session actor columns are `SET NULL` so history survives the actor. Resolve refuses a session with neitherid: a null actor id reaches the membership lookups as `IS NULL`, matches user rows, and resolved as admin.`actorType` is stored at mint because `SET NULL` erases which kind of owner it was. It stays nullable (a pod@@ -119,30 +119,33 @@ and `packages/agentvault/` in the CLI repo. Frontend: `frontend/src/pages/agent-actor id reads as revoked in the list and the status filter, so they agree with resolve refusing it. Expiryis enforced against the clock on every resolve; there is no expiry audit event, matching every other product.- **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.+ logs need.## Sessions on behalf of usersA 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 and personal values without a branch of its-own. The identity is kept as `actingIdentityId` and `actingIdentityName`, and its reach narrows the user's. A delegation+belongs to the identity: `identityId` is the identity, so only it and Agent Vault admins can list, read, label or revoke+the session or read its session logs, and the user never sees it. The user is kept as+`onBehalfOfUserId`, with `onBehalfOfUserName` and `onBehalfOfUserEmail` snapshotted like `actorName` and `actorEmail`;+resolve uses the user's personal values, and the user's reach narrows the identity's. A delegationis one `agent_vault_delegations` row per identity, with a scope of `all-members` or `selected`, plus`agent_vault_delegation_subjects` rows naming users and groups. Both reference an Agent Vault membership (`membershipId`,`ON DELETE CASCADE`): the delegation its identity's, and each subject the user's or group's.-- **Never put the acting identity in `identityId`.** Resolve reads `userId` first and falls back to `identityId`, 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+- **Never put the user in `userId`.** Ownership is `userId` or `identityId` alone (`isSessionOwnedBy`, the list's actor+ filter), so a user in `userId` would see the session and its logs. The DB check+ `agent_vault_sessions_on_behalf_of_check` keeps an on-behalf-of session an identity's.+- **`onBehalfOfUserName` is what marks the session on-behalf-of** once deleting the user sets the id to NULL, thesame 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 (`$getActingIdentityReach`). 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 intersection of the user's and the identity's** (`intersectAccessBundleIds`): a bundle needs both,- through the admin role or a grant, at mint and on every resolve. Settled with the product owner. The identity losing- a grant drops the bundle's services like a user's lost grant, with no 401.+ (`isOrphanedSession`) and resolve refuses it, rather than resolving as the identity's own session with the+ identity's personal values.+- **Resolve re-checks the user every time**: active in the org, a live Agent Vault role, and a delegation of the owning+ identity that still covers them (`$getOnBehalfOfUserReach`). The identity gets the checks every owner gets. 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 intersection of the identity's and the user's** (`intersectAccessBundleIds`): a bundle needs both,+ through the admin role or a grant, at mint and on every resolve. The user losing+ a grant drops the bundle's services like an owner's lost grant, with no 401.- **Listing access bundles with `onBehalfOfUserId` or `onBehalfOfUserEmail` runs mint's delegation and user checks**(`agent-vault-on-behalf-of-fns.ts`, shared by both), then returns the bundles the user and the identity both reach,with setup state from the user's personal values, so an orchestrator can choose a bundle before it mints.@@ -164,8 +167,9 @@ is one `agent_vault_delegations` row per identity, with a scope of `all-members`- **TTL defaults to 1h, with no maximum for now**: the user didn't start the session and may not know it exists, so acap probably belongs here too, but any TTL is allowed for now, `never` included. The route's `ttl` is optional ratherthan 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).+- **The user can't see a session started on their behalf**: their list leaves it out, and get, label, revoke and+ session log reads answer 404, as for any session someone else owns. An admin finds it by either name, since search+ matches the on-behalf-of user too.- **Coverage reads group membership without `isPending`**, the way the permission engine grants access through agroup. 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@@ -348,14 +352,15 @@ reference.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 that reads or writespersonal values or variables names another actor, so an admin can't list, read or set anyone else's variables or- values. Two on-behalf-of routes name a user: minting, to own the session, and the access bundle list, to report+ values. Two on-behalf-of routes name a user: minting, to use their values, and the access bundle list, to reportwhich of the user's services still need setup (see [Sessions on behalf of users](#sessions-on-behalf-of-users)). Theowner is a user or a machine identity (`ownerOf`); the UI only covers users for now, but resolve and the API alreadywork for an identity's own sessions.- **Resolve fills member fields last**: the admin's fields are expanded against global variables first, then each- personal value against the session actor's personal variables only, so neither is ever expanded twice and a- personal `{{KEY}}` can't reach a global variable. A service whose actor hasn't set every member-provided field goes- out with `personalValuesMissing: true` and a passthrough credential. The proxy refuses it with a 403 from current+ personal value against the personal variables of the member it belongs to (the session's owner, or the user an+ on-behalf-of session acts for) only, so neither is ever expanded twice and a personal `{{KEY}}` can't reach a global+ variable. A service whose member hasn't set every member-provided field goes out with `personalValuesMissing: true`+ and a passthrough credential. The proxy refuses it with a 403 from currentCLIs; an older proxy that ignores the flag forwards it with the service's custom headers and substitutions but nocredential, never the admin's.- **A save is a PATCH**: a field sent replaces that field's saved value, a field left out keeps it, and every@@ -570,7 +575,7 @@ hostile input: nothing it sends may erase or hide its own records, so the proxypin checked before anything is written. Re-enrolling a proxy replaces its CA, so pins, mounted copies,keychain entries and any agent already running through it break until updated or restarted.- No sandbox, nothing stripped. The agent gets the parent's whole environment plus the proxy URL (session- token inside) and the CA trust variables. Settled with the product owner.+ token inside) and the CA trust variables.- The session flag is `--session-token`, not `--token`, so the root command's Infisical-token handling neverreads it. The minting identity comes from `--client-id`/`--client-secret`, the access-token env vars, or thekeyring login.diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex 709cd13beb..62b0a4b914 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -6825,6 +6825,10 @@ interface AgentVaultSessionUpdateEvent {previousLabel: string | null;sessionOwner: string;accessBundleName: string | null;+ // Set when the machine identity in sessionOwner started the session on this user's behalf.+ onBehalfOfUserId?: string;+ onBehalfOfUserName?: string;+ onBehalfOfUserEmail?: string;};}@@ -6835,6 +6839,10 @@ interface AgentVaultSessionRevokeEvent {label: string | null;sessionOwner: string;accessBundleName: string | null;+ // Set when the machine identity in sessionOwner started the session on this user's behalf.+ onBehalfOfUserId?: string;+ onBehalfOfUserName?: string;+ onBehalfOfUserEmail?: string;};}diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex 0d51f03986..7fa2143658 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -4903,9 +4903,9 @@ export const AGENT_VAULT = {label:"A short description of what the session is for, such as `nightly deploy` or `support ticket triage`. Up to 128 characters, without line breaks, tabs, or invisible characters. Shown wherever the session is listed.",updateLabel:- "The new label for the session, up to 128 characters, without line breaks, tabs, or invisible characters. Send null or an empty string to remove the label. You can't change the label once the session's owner, or the machine identity that started it on the owner's behalf, is deleted.",+ "The new label for the session, up to 128 characters, without line breaks, tabs, or invisible characters. Send null or an empty string to remove the label. You can't change the label once the session's owner, or the user it was started on behalf of, is deleted.",onBehalfOf:- "Start the session on behalf of a user instead of yourself. Only a machine identity whose delegation covers the user can do this. The session can use only an access bundle that both the user and the machine identity can use, and it uses the user's personal values. Name the user by userId or by userEmail, not both.",+ "Start the session on behalf of a user instead of yourself. Only a machine identity whose delegation covers the user can do this. The session can use only an access bundle that both the user and the machine identity can use, and it uses the user's personal values. The session still belongs to the machine identity, so only the machine identity and Agent Vault admins can see it and its session logs, not the user. Name the user by userId or by userEmail, not both.",onBehalfOfUserId: "The ID of the user to start the session on behalf of.",onBehalfOfUserEmail: "The email address of the user to start the session on behalf of.",token: "The session token. Returned once, at mint, and never again.",@@ -4913,7 +4913,8 @@ export const AGENT_VAULT = {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 label, actor name, actor email, acting machine identity name or access bundle name.",+ search:+ "Match sessions by label, actor name, actor email, the name or email of the user a session was started on behalf of, 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.",@@ -4925,11 +4926,10 @@ export const AGENT_VAULT = {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.",- 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."+ onBehalfOfSession:+ "The user the machine identity in actor started this session on behalf of, or null when the session is the actor's own.",+ onBehalfOfType: "Always user: a machine identity starts sessions only on behalf of users.",+ onBehalfOfUserIdRead: "The ID of the user, or null once the user is deleted."},DELEGATION: {machineIdentityId: "The ID of the machine identity the delegation belongs to.",diff --git a/docs/documentation/platform/agent-vault/sessions-on-behalf-of-users.mdx b/docs/documentation/platform/agent-vault/sessions-on-behalf-of-users.mdxindex 9f50c1e55e..311e53f1d8 100644--- a/docs/documentation/platform/agent-vault/sessions-on-behalf-of-users.mdx+++ b/docs/documentation/platform/agent-vault/sessions-on-behalf-of-users.mdx@@ -3,7 +3,7 @@ title: "Sessions on behalf of users"description: "Let a machine identity, such as a chat bot or a task runner, create sessions on behalf of users, so each session uses the personal values of the user it's for."----A delegation lets a [machine identity](/documentation/platform/identities/machine-identities) create [sessions](/documentation/platform/agent-vault/sessions) on behalf of users in Agent Vault. The machine identity can still create sessions as itself. It creates a session on behalf of a user only if it sends the user's email or ID in `onBehalfOf`. A session created on behalf of a user belongs to that user, so the [proxy](/documentation/platform/agent-vault/proxies) uses the user's own [personal values](/documentation/platform/agent-vault/http-apis#member-provided-values), not the machine identity's. The session can use an [access bundle](/documentation/platform/agent-vault/access-bundles) only if both the user and the machine identity can use the bundle.+A delegation lets a [machine identity](/documentation/platform/identities/machine-identities) create [sessions](/documentation/platform/agent-vault/sessions) on behalf of users in Agent Vault. The machine identity can still create sessions as itself. It creates a session on behalf of a user only if it sends the user's email or ID in `onBehalfOf`. For a session created on behalf of a user, the [proxy](/documentation/platform/agent-vault/proxies) uses the user's own [personal values](/documentation/platform/agent-vault/http-apis#member-provided-values), not the machine identity's. The session can use an [access bundle](/documentation/platform/agent-vault/access-bundles) only if both the user and the machine identity can use the bundle.Use a delegation when one service starts agents for many people, such as a chat bot that runs an agent for each message, or a task runner that runs an agent for each ticket. Each agent then gets no more access than the person who asked for it.@@ -130,7 +130,7 @@ Infisical checks the delegation again each time the proxy polls, once every [pol- The delegation covered the user only through a group, and either the user leaves that group or the group is removed from Agent Vault- The user is removed from Agent Vault or from your organization, which also takes the user out of the delegation- An admin removes the machine identity from Agent Vault, which also deletes its delegation-- Someone deletes the machine identity (the session then shows as **Revoked**)+- Someone deletes the machine identity or the user (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).@@ -138,15 +138,14 @@ If the user or the machine identity can no longer use the access bundle, the ses## Track sessions created on behalf of users-These people and identities can see the session and revoke it:+A session created on behalf of a user belongs to the machine identity, so the user can't see it. Only the machine identity and Agent Vault admins can see the session, read its [session logs](/documentation/platform/agent-vault/session-logs), and revoke it:-- The user, under **My Sessions**-- The machine identity, through the endpoints that [read a session](/api-reference/endpoints/agent-vault-sessions/get) and [revoke a session](/api-reference/endpoints/agent-vault-sessions/revoke)-- Admins, under **All Sessions**+- The machine identity, through the endpoints that [read a session](/api-reference/endpoints/agent-vault-sessions/get), [list its session logs](/api-reference/endpoints/agent-vault-session-logs/list), and [revoke a session](/api-reference/endpoints/agent-vault-sessions/revoke)+- Admins, under **All Sessions** on the **Sessions** page-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**.+On the **Sessions** page, the **Identity** column shows the machine identity's name, followed by "on behalf of" and the user's name. The session's details list the user under **On Behalf Of**.-When the machine identity creates the session, Infisical writes an audit event with the machine identity as the actor and the user in `onBehalfOfUserId`, `onBehalfOfUserName`, and `onBehalfOfUserEmail`. Infisical also writes an audit event when an admin sets up, changes, or removes a delegation.+When the machine identity creates the session, Infisical writes an audit event with the machine identity as the actor and the user in `onBehalfOfUserId`, `onBehalfOfUserName`, and `onBehalfOfUserEmail`. The audit events for changing the session's label and revoking the session include the same three fields. Infisical also writes an audit event when an admin sets up, changes, or removes a delegation.## Troubleshootingdiff --git a/frontend/src/hooks/api/agentVault/types.ts b/frontend/src/hooks/api/agentVault/types.tsindex a4a62095db..a01404415d 100644--- a/frontend/src/hooks/api/agentVault/types.ts+++ b/frontend/src/hooks/api/agentVault/types.ts@@ -260,14 +260,17 @@ 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 };+/** The user a machine identity started a session on behalf of. `id` is null once the user is deleted. */+export type TAgentVaultSessionOnBehalfOf = Extract<+ TAgentVaultSessionActor,+ { type: AgentVaultMemberType.User }+>;export type TAgentVaultSession = {id: string;label: string | null;actor: TAgentVaultSessionActor;- actingIdentity: TAgentVaultSessionActingIdentity | null;+ onBehalfOf: TAgentVaultSessionOnBehalfOf | null;status: AgentVaultSessionStatus;expiresAt: string | null;revokedAt: string | null;diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/AgentVaultSessionsPage.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/AgentVaultSessionsPage.tsxindex e0d5243c25..9daf4e9867 100644--- a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/AgentVaultSessionsPage.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/AgentVaultSessionsPage.tsx@@ -3,7 +3,6 @@ import { Link, linkOptions } from "@tanstack/react-router";import { format } from "date-fns";import {BanIcon,- BotIcon,CircleAlertIcon,FilterIcon,IdCardIcon,@@ -13,12 +12,10 @@ import {PencilIcon,PlusIcon,SearchIcon,- TriangleAlertIcon,- UserIcon+ TriangleAlertIcon} from "lucide-react";import { AgentVaultSessionLogUpgradeModal } from "@app/components/agent-vault/AgentVaultSessionLogUpgradeModal";-import { memberDisplayName, memberSubtitle } from "@app/components/agent-vault/MemberName";import {useAgentVaultSetupProgress,useOpenAgentVaultSetupStep@@ -76,7 +73,6 @@ import {} from "@app/helpers/userTablePreferences";import { useDebounce, useResetPageHelper } from "@app/hooks";import {- AgentVaultMemberType,AgentVaultSessionScope,AgentVaultSessionStatus,useGetAgentVaultSession,@@ -101,6 +97,7 @@ import { SampleSessionSheet, SampleSessionTable } from "./components/SampleSessiimport { SessionCreatedDialog } from "./components/SessionCreatedDialog";import { SessionDetailSheet } from "./components/SessionDetailSheet";import { SessionExpiry } from "./components/SessionExpiry";+import { SessionIdentity } from "./components/SessionIdentity";import { SessionLabel } from "./components/SessionLabel";import { SESSION_STATUS_PRESENTATION, SessionStatusBadge } from "./components/SessionStatusBadge";@@ -455,30 +452,7 @@ export const AgentVaultSessionsPage = () => {)}</TableCell><TableCell>- <Tooltip>- <TooltipTrigger asChild>- <div className="flex w-fit items-center gap-2">- {session.actor.type === AgentVaultMemberType.MachineIdentity ? (- <BotIcon className="size-4 text-muted" />- ) : (- <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>+ <SessionIdentity session={session} /></TableCell><TableCell><div className="max-w-72">@@ -506,7 +480,11 @@ export const AgentVaultSessionsPage = () => {{format(new Date(session.createdAt), "MMM dd, yyyy hh:mm a")}</TableCell><TableCell>- <SessionExpiry expiresAt={session.expiresAt} />+ {session.status === AgentVaultSessionStatus.Revoked ? (+ <span className="text-muted">—</span>+ ) : (+ <SessionExpiry expiresAt={session.expiresAt} />+ )}</TableCell><TableCell><SessionStatusBadge status={session.status} />@@ -549,8 +527,8 @@ export const AgentVaultSessionsPage = () => {<LogsIcon />View Session Logs</DropdownMenuItem>- {/* The API refuses label edits once the session's owner, or the identity that started it on their behalf, is deleted */}- {session.actor.id !== null && session.actingIdentity?.id !== null && (+ {/* The API refuses label edits once the session's owner, or the user it acts on behalf of, is deleted */}+ {session.actor.id !== null && session.onBehalfOf?.id !== null && (<DropdownMenuItem onClick={() => setSessionToLabel(session)}><PencilIcon />{session.label ? "Edit Label" : "Add Label"}diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionDetailSheet.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionDetailSheet.tsxindex 55f411722e..34c69a6d04 100644--- a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionDetailSheet.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionDetailSheet.tsx@@ -47,8 +47,8 @@ export const SessionDetailSheet = ({const { currentOrg } = useOrganization();const isOwnerDeleted = session?.actor.id === null;- // The API refuses label edits once the owner, or the identity that started it on their behalf, is deleted.- const canEditLabel = !isOwnerDeleted && session?.actingIdentity?.id !== null;+ // The API refuses label edits once the owner, or the user it acts on behalf of, is deleted.+ const canEditLabel = !isOwnerDeleted && session?.onBehalfOf?.id !== null;const isMachineIdentity = session?.actor.type === AgentVaultMemberType.MachineIdentity;const hasExpired = Boolean(session?.expiresAt && new Date(session.expiresAt).getTime() <= Date.now()@@ -114,20 +114,25 @@ export const SessionDetailSheet = ({)}</DetailValue></Detail>- {session.actingIdentity && (+ {session.onBehalfOf && (<Detail className="min-w-0">- <DetailLabel>Started By</DetailLabel>+ <DetailLabel>On Behalf Of</DetailLabel><DetailValueclassName={twMerge("flex items-center gap-2",- !session.actingIdentity.id && "text-muted"+ !session.onBehalfOf.id && "text-muted")}>- <BotIcon className="size-4 shrink-0 text-muted" />+ <UserIcon className="size-4 shrink-0 text-muted" /><span className="truncate">- {session.actingIdentity.name}- {!session.actingIdentity.id && " (deleted)"}+ {memberDisplayName(session.onBehalfOf)}+ {!session.onBehalfOf.id && " (deleted)"}</span>+ {session.onBehalfOf.id && (+ <span className="truncate text-muted">+ {memberSubtitle(session.onBehalfOf)}+ </span>+ )}</DetailValue></Detail>)}diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionIdentity.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionIdentity.tsxnew file mode 100644index 0000000000..fed124f42c--- /dev/null+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionIdentity.tsx@@ -0,0 +1,64 @@+import { ReactElement } from "react";+import { BotIcon, UserIcon } from "lucide-react";++import { memberDisplayName, memberSubtitle } from "@app/components/agent-vault/MemberName";+import { Badge, Tooltip, TooltipContent, TooltipTrigger } from "@app/components/v3";+import { AgentVaultMemberType, TAgentVaultSession } from "@app/hooks/api/agentVault";++// Deleting the machine identity or the user it acts for ends the session, so the cell names whichever was deleted.+const describeDeleted = ({ actor, onBehalfOf }: TAgentVaultSession) => {+ const names = [+ actor.id === null ? memberDisplayName(actor) : null,+ onBehalfOf && onBehalfOf.id === null ? memberDisplayName(onBehalfOf) : null+ ].filter((name): name is string => name !== null);+ if (!names.length) return null;+ return `${names.map((name) => `"${name}"`).join(" and ")} ${names.length === 1 ? "was" : "were"} deleted`;+};++export const SessionIdentity = ({ session }: { session: TAgentVaultSession }) => {+ const { actor, onBehalfOf } = session;++ if (actor.type === AgentVaultMemberType.User) {+ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <div className="flex w-fit items-center gap-2">+ <UserIcon className="size-4 text-muted" />+ {memberDisplayName(actor)}+ </div>+ </TooltipTrigger>+ <TooltipContent>{memberSubtitle(actor)}</TooltipContent>+ </Tooltip>+ );+ }++ const deleted = describeDeleted(session);+ const explained = (trigger: ReactElement) =>+ deleted ? (+ <Tooltip>+ <TooltipTrigger asChild>{trigger}</TooltipTrigger>+ <TooltipContent>{deleted}</TooltipContent>+ </Tooltip>+ ) : (+ trigger+ );++ return (+ <div className="flex w-fit items-center gap-2">+ <BotIcon className="size-4 text-muted" />+ {onBehalfOf ? memberDisplayName(actor) : explained(<span>{memberDisplayName(actor)}</span>)}+ {onBehalfOf &&+ explained(+ <Badge+ variant="neutral"+ iconPosition="left"+ isTruncatable+ className={deleted ? "max-w-60 text-muted" : "max-w-60"}+ >+ <UserIcon />+ <span>On Behalf Of {memberDisplayName(onBehalfOf)}</span>+ </Badge>+ )}+ </div>+ );+};