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): list the access bundles a session on a user's behalf could use
Scott Wilson6143c522d8b1
diff --git a/backend/e2e-test/routes/v1/agent-vault.spec.ts b/backend/e2e-test/routes/v1/agent-vault.spec.tsindex 771a811033..a1f71bd6a1 100644--- a/backend/e2e-test/routes/v1/agent-vault.spec.ts+++ b/backend/e2e-test/routes/v1/agent-vault.spec.ts@@ -4102,6 +4102,100 @@ describe("Agent Vault V1 Router", async () => {}});+ test("an identity lists the bundles a session on a user's behalf could use", async () => {+ const projectId = await getProjectId();+ const stamp = String(Date.now());+ const shared = await createAccessBundle(`obo-list-shared-${stamp}`);+ const usersOnly = await createAccessBundle(`obo-list-users-${stamp}`);+ const botsOnly = await createAccessBundle(`obo-list-bots-${stamp}`);+ const needsSetup = await createAccessBundle(`obo-list-setup-${stamp}`);+ const service = await inject("POST", `/api/v1/agent-vault/access-bundles/${needsSetup.id}/services`, {+ name: "github",+ hostPattern: "api.github.com",+ credential: { type: "bearer", memberProvidedFields: ["credential-value"] }+ });+ expect(service.statusCode).toBe(200);+ const bot = await createMemberIdentity(`obo-list-bot-${stamp}`);+ const alice = await createAgentVaultUser("obo-list-alice", projectId);+ const outsider = await createAgentVaultUser("obo-list-outsider", projectId);+ const bundlesUrl = (query: string) => `/api/v1/agent-vault/access-bundles?limit=100&${query}`;+ type TListed = { name: string; servicesRequiringSetup: { name: string }[] }[];+ const listed = (res: { json: () => { accessBundles: TListed } }) =>+ res+ .json()+ .accessBundles.filter((bundle) => bundle.name.endsWith(stamp))+ .map((bundle) => ({+ name: bundle.name,+ setup: bundle.servicesRequiringSetup.map((pending) => pending.name)+ }));+ try {+ await grantBundle(shared.id, { userIds: [alice.userId], machineIdentityIds: [bot.id] });+ await grantBundle(usersOnly.id, { userIds: [alice.userId] });+ await grantBundle(botsOnly.id, { machineIdentityIds: [bot.id] });+ await grantBundle(needsSetup.id, { machineIdentityIds: [bot.id] });+ await delegate(bot, { scope: "selected", userIds: [alice.userId, seedData1.id] });++ const byId = await bot.as("GET", bundlesUrl(`onBehalfOfUserId=${alice.userId}`));+ expect(byId.statusCode).toBe(200);+ expect(listed(byId)).toEqual([{ name: shared.name, setup: [] }]);+ const byEmail = await bot.as("GET", bundlesUrl(`onBehalfOfUserEmail=${encodeURIComponent(alice.username)}`));+ expect(listed(byEmail)).toEqual(listed(byId));++ // Without onBehalfOf the identity still lists its own bundles.+ const own = await bot.as("GET", bundlesUrl("orderBy=name&orderDirection=asc"));+ expect(listed(own).map((bundle) => bundle.name)).toEqual([botsOnly.name, needsSetup.name, shared.name]);++ // A user the delegation doesn't cover reads exactly like one who doesn't exist.+ const missingId = crypto.randomUUID();+ const uncovered = await bot.as("GET", bundlesUrl(`onBehalfOfUserId=${outsider.userId}`));+ const unknown = await bot.as("GET", bundlesUrl(`onBehalfOfUserId=${missingId}`));+ expect([uncovered.statusCode, unknown.statusCode]).toEqual([403, 403]);+ expect(uncovered.json().message.replace(outsider.userId, "<user>")).toBe(+ unknown.json().message.replace(missingId, "<user>")+ );++ const asUser = await inject("GET", bundlesUrl(`onBehalfOfUserId=${alice.userId}`));+ expect(asUser.statusCode).toBe(400);+ expect(asUser.json().message).toBe("Only a machine identity can start a session on behalf of a user");+ expect(+ (+ await bot.as(+ "GET",+ bundlesUrl(`onBehalfOfUserId=${alice.userId}&onBehalfOfUserEmail=${encodeURIComponent(alice.username)}`)+ )+ ).statusCode+ ).toBe(422);+ const withGranted = await bot.as("GET", bundlesUrl(`onBehalfOfUserId=${alice.userId}&granted=true`));+ expect(withGranted.statusCode).toBe(422);++ // The setup state is the user's: the seeded admin reaches every bundle, so the identity's grants decide the+ // list, and the service asks for a value the admin hasn't saved yet.+ const forAdmin = (requiresSetup: string) =>+ bot.as(+ "GET",+ bundlesUrl(+ `onBehalfOfUserId=${seedData1.id}&requiresSetup=${requiresSetup}&orderBy=name&orderDirection=asc`+ )+ );+ expect(listed(await forAdmin("true"))).toEqual([{ name: needsSetup.name, setup: ["github"] }]);+ const saved = await inject(+ "PATCH",+ `/api/v1/agent-vault/access-bundles/${needsSetup.id}/services/${service.json().service.id as string}/personal-values`,+ { values: [{ field: "credential-value", value: "admin_personal_token" }] }+ );+ expect(saved.statusCode).toBe(200);+ expect(listed(await forAdmin("true"))).toEqual([]);+ expect(listed(await forAdmin("false"))).toEqual([+ { name: botsOnly.name, setup: [] },+ { name: needsSetup.name, setup: [] },+ { name: shared.name, setup: [] }+ ]);+ } finally {+ await bot.cleanup();+ await deleteUsers([alice.userId, outsider.userId]);+ }+ });+test("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()}`);diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-access-bundle-router.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-access-bundle-router.tsindex 11e38e5522..56b3b80e42 100644--- a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-access-bundle-router.ts+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-access-bundle-router.ts@@ -70,24 +70,41 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodProoperationId: "listAgentVaultAccessBundles",description: "List the Agent Vault access bundles you can reach",tags: [ApiDocsTags.AgentVaultAccessBundles],- querystring: z.object({- requiresSetup: z- .enum(["true", "false"])- .transform((value) => value === "true")- .optional()- .describe(AGENT_VAULT.ACCESS_BUNDLE.requiresSetup),- granted: z- .enum(["true", "false"])- .transform((value) => value === "true")- .optional()- .describe(AGENT_VAULT.ACCESS_BUNDLE.granted),- orderBy: z- .enum(["name", "serviceCount", "createdAt"])- .default("createdAt")- .describe(AGENT_VAULT.ACCESS_BUNDLE.orderBy),- orderDirection: z.enum(["asc", "desc"]).default("desc").describe(AGENT_VAULT.ACCESS_BUNDLE.orderDirection),- ...agentVaultListQuery(AGENT_VAULT.ACCESS_BUNDLE)- }),+ querystring: z+ .object({+ requiresSetup: z+ .enum(["true", "false"])+ .transform((value) => value === "true")+ .optional()+ .describe(AGENT_VAULT.ACCESS_BUNDLE.requiresSetup),+ granted: z+ .enum(["true", "false"])+ .transform((value) => value === "true")+ .optional()+ .describe(AGENT_VAULT.ACCESS_BUNDLE.granted),+ orderBy: z+ .enum(["name", "serviceCount", "createdAt"])+ .default("createdAt")+ .describe(AGENT_VAULT.ACCESS_BUNDLE.orderBy),+ orderDirection: z.enum(["asc", "desc"]).default("desc").describe(AGENT_VAULT.ACCESS_BUNDLE.orderDirection),+ onBehalfOfUserId: z.string().uuid().optional().describe(AGENT_VAULT.ACCESS_BUNDLE.onBehalfOfUserId),+ onBehalfOfUserEmail: z+ .string()+ .trim()+ .toLowerCase()+ .email()+ .max(255)+ .optional()+ .describe(AGENT_VAULT.ACCESS_BUNDLE.onBehalfOfUserEmail),+ ...agentVaultListQuery(AGENT_VAULT.ACCESS_BUNDLE)+ })+ .refine((query) => !(query.onBehalfOfUserId && query.onBehalfOfUserEmail), {+ message: "Name the user by onBehalfOfUserId or by onBehalfOfUserEmail, not both"+ })+ .refine((query) => query.granted === undefined || !(query.onBehalfOfUserId || query.onBehalfOfUserEmail), {+ message:+ "granted filters your own access bundles, so it can't be combined with onBehalfOfUserId or onBehalfOfUserEmail"+ }),response: {200: z.object({accessBundles: AccessBundleSchema.extend({@@ -107,12 +124,18 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodPro}},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),- handler: async (req) =>- server.services.agentVaultAccessBundle.listAccessBundles({+ handler: async (req) => {+ const { onBehalfOfUserId, onBehalfOfUserEmail, ...query } = req.query;+ return server.services.agentVaultAccessBundle.listAccessBundles({projectId: req.internalAgentVaultProjectId,ctx: actorContext(req),- ...req.query- })+ ...query,+ onBehalfOf:+ onBehalfOfUserId || onBehalfOfUserEmail+ ? { userId: onBehalfOfUserId, userEmail: onBehalfOfUserEmail }+ : undefined+ });+ }});server.route({diff --git a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service.ts b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service.tsindex f3d7768573..881f9b2522 100644--- a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service.ts+++ b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service.ts@@ -46,13 +46,22 @@ import {TAgentVaultMemberProvidedField} from "../agent-vault/agent-vault-enums";import { ownerOrNullOf } from "../agent-vault/agent-vault-owner-fns";-import { getAgentVaultGrantedReachability, getAgentVaultReachability } from "../agent-vault/agent-vault-permission";+import {+ getAgentVaultGrantedReachability,+ getAgentVaultReachability,+ intersectAccessBundleIds+} from "../agent-vault/agent-vault-permission";import {findStoredVariableIds,findVariableKeys,toStoredVariableReferences,toVariableReference} from "../agent-vault/agent-vault-variable-fns";+import {+ findCallerDelegation,+ resolveOnBehalfOfUser,+ TOnBehalfOfDeps+} from "../agent-vault-delegation/agent-vault-on-behalf-of-fns";import { TAgentVaultMemberDALFactory } from "../agent-vault-member/agent-vault-member-dal";import { TAgentVaultPersonalValueDALFactory } from "../agent-vault-personal-value/agent-vault-personal-value-dal";import {@@ -123,6 +132,9 @@ type TAgentVaultAccessBundleServiceFactoryDep = {agentVaultMemberDAL: Pick<TAgentVaultMemberDALFactory, "findProductMembers">;userGroupMembershipDAL: Pick<TUserGroupMembershipDALFactory, "find">;identityGroupMembershipDAL: Pick<TIdentityGroupMembershipDALFactory, "find">;+ agentVaultDelegationDAL: TOnBehalfOfDeps["agentVaultDelegationDAL"];+ orgDAL: TOnBehalfOfDeps["orgDAL"];+ userDAL: TOnBehalfOfDeps["userDAL"];} & TAgentVaultActorNameDALs;export type TAgentVaultAccessBundleServiceFactory = ReturnType<typeof agentVaultAccessBundleServiceFactory>;@@ -155,7 +167,9 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundidentityGroupMembershipDAL,userDAL,groupDAL,- identityDAL+ identityDAL,+ agentVaultDelegationDAL,+ orgDAL} = deps;const bundleScope = (projectId: string, accessBundleId: string) => ({@@ -590,9 +604,41 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundreturn { bundle, ...reachability };};+ // What a session on the user's behalf could use: the bundles both the user and the caller reach, counted against+ // the user's personal values. It runs the same checks as minting that session, so it reveals no more about the org.+ const $onBehalfOfListScope = async ({+ projectId,+ ctx,+ onBehalfOf,+ callerAccessBundleIds+ }: {+ projectId: string;+ ctx: TListAccessBundlesDTO["ctx"];+ onBehalfOf: NonNullable<TListAccessBundlesDTO["onBehalfOf"]>;+ callerAccessBundleIds: string[] | null;+ }) => {+ const delegation = await findCallerDelegation({ agentVaultDelegationDAL }, { projectId, ctx });+ const { user, accessBundleIds: userAccessBundleIds } = await resolveOnBehalfOfUser(+ { agentVaultDelegationDAL, userDAL, orgDAL, permissionService, membershipDAL },+ { projectId, ctx, onBehalfOf, delegation }+ );+ return {+ scopeIds: intersectAccessBundleIds(userAccessBundleIds, callerAccessBundleIds),+ excludeIds: [] as string[],+ owner: { userId: user.id }+ };+ };+// Setup is counted over every bundle the caller reaches, since an admin can start a session on one they were never// granted.- const listAccessBundles = async ({ projectId, ctx, requiresSetup, granted, ...page }: TListAccessBundlesDTO) => {+ const listAccessBundles = async ({+ projectId,+ ctx,+ requiresSetup,+ granted,+ onBehalfOf,+ ...page+ }: TListAccessBundlesDTO) => {const { permission, accessBundleIds, grantedAccessBundleIds } = await getAgentVaultGrantedReachability({ permissionService, membershipDAL },{ projectId, ctx }@@ -602,12 +648,15 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundProjectPermissionSub.AgentVaultAccessBundles);- // null is every bundle in the project, which only an admin reaches.- const scopeIds = granted ? grantedAccessBundleIds : accessBundleIds;- const excludeIds = granted === false ? grantedAccessBundleIds : [];+ const { scopeIds, excludeIds, owner } = onBehalfOf+ ? await $onBehalfOfListScope({ projectId, ctx, onBehalfOf, callerAccessBundleIds: accessBundleIds })+ : {+ // null is every bundle in the project, which only an admin reaches.+ scopeIds: granted ? grantedAccessBundleIds : accessBundleIds,+ excludeIds: granted === false ? grantedAccessBundleIds : [],+ owner: ownerOrNullOf(ctx)+ };const excluded = new Set(excludeIds);-- const owner = ownerOrNullOf(ctx);const pendingByBundleOf = async (bundleIds: string[] | null) => {const byBundle = new Map<string, { id: string; name: string }[]>();if (!owner || bundleIds?.length === 0) return byBundle;diff --git a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-types.ts b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-types.tsindex 6c27bf0733..8154271aea 100644--- a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-types.ts+++ b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-types.ts@@ -6,6 +6,7 @@ import {AgentVaultSubstitutionSurface,AgentVaultVariableReferenceField} from "../agent-vault/agent-vault-enums";+import { TOnBehalfOfUser } from "../agent-vault-session/agent-vault-session-types";import { TAgentVaultAccessBundleOrderBy } from "./agent-vault-access-bundle-dal";export type TAgentVaultBearerMemberField = AgentVaultVariableReferenceField.CredentialValue;@@ -53,6 +54,7 @@ export type TAgentVaultProjectScoped = { projectId: string; ctx: TGenericPermissexport type TListAccessBundlesDTO = TAgentVaultProjectScoped & {requiresSetup?: boolean;granted?: boolean;+ onBehalfOf?: TOnBehalfOfUser;search?: string;orderBy: TAgentVaultAccessBundleOrderBy;orderDirection: "asc" | "desc";diff --git a/backend/src/ee/services/agent-vault-delegation/agent-vault-on-behalf-of-fns.ts b/backend/src/ee/services/agent-vault-delegation/agent-vault-on-behalf-of-fns.tsnew file mode 100644index 0000000000..6631f3b461--- /dev/null+++ b/backend/src/ee/services/agent-vault-delegation/agent-vault-on-behalf-of-fns.ts@@ -0,0 +1,113 @@+import { OrgMembershipStatus } from "@app/db/schemas";+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";+import {+ ProjectPermissionAgentVaultSessionActions,+ ProjectPermissionSub+} from "@app/ee/services/permission/project-permission";+import { BadRequestError, ForbiddenRequestError } 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 { TOrgDALFactory } from "@app/services/org/org-dal";+import { TUserDALFactory } from "@app/services/user/user-dal";++import { getAgentVaultReachability } from "../agent-vault/agent-vault-permission";+import { TOnBehalfOfUser } from "../agent-vault-session/agent-vault-session-types";+import { TAgentVaultDelegationDALFactory } from "./agent-vault-delegation-dal";++export type TOnBehalfOfDeps = {+ agentVaultDelegationDAL: Pick<TAgentVaultDelegationDALFactory, "findOne" | "coversUser">;+ userDAL: Pick<TUserDALFactory, "findOne">;+ orgDAL: Pick<TOrgDALFactory, "findEffectiveOrgMembership">;+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;+ membershipDAL: Pick<TMembershipDALFactory, "findResourceMembershipsForActor">;+};++export const findCallerDelegation = async (+ { agentVaultDelegationDAL }: Pick<TOnBehalfOfDeps, "agentVaultDelegationDAL">,+ { projectId, ctx }: { projectId: string; ctx: TGenericPermission }+) => {+ 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."+ });+ }+ return delegation;+};++// A user who doesn't exist reads exactly like one the delegation doesn't cover.+export const resolveOnBehalfOfUser = async (+ { agentVaultDelegationDAL, userDAL, orgDAL, permissionService, membershipDAL }: TOnBehalfOfDeps,+ {+ projectId,+ ctx,+ onBehalfOf,+ delegation+ }: {+ projectId: string;+ ctx: TGenericPermission;+ onBehalfOf: TOnBehalfOfUser;+ delegation: Awaited<ReturnType<typeof findCallerDelegation>>;+ }+) => {+ 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 user's own role and grants decide what they reach. 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, identifier, accessBundleIds: reachability.accessBundleIds };+};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 33c688b2d8..43720dd504 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,6 +1,5 @@import { ForbiddenError } from "@casl/ability";-import { OrgMembershipStatus } from "@app/db/schemas";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";import {ProjectPermissionAgentVaultSessionActions,@@ -9,7 +8,6 @@ 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";@@ -20,17 +18,12 @@ import { AgentVaultMemberType, AgentVaultSessionScope } from "../agent-vault/ageimport { 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 { findCallerDelegation, resolveOnBehalfOfUser } from "../agent-vault-delegation/agent-vault-on-behalf-of-fns";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,- TOnBehalfOfUser,- TRevokeSessionDTO-} from "./agent-vault-session-types";+import { TGetSessionByIdDTO, TListSessionsDTO, TMintSessionDTO, 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;@@ -86,89 +79,6 @@ export const agentVaultSessionServiceFactory = ({status: deriveSessionStatus({ ...session, userId, identityId, actingIdentityId, actingIdentityName })});- const findCallerDelegation = async ({ projectId, ctx }: { projectId: string; ctx: TGenericPermission }) => {- 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."- });- }- return delegation;- };-- // A user who doesn't exist reads exactly like one the delegation doesn't cover.- const resolveOnBehalfOfUser = async ({- projectId,- ctx,- onBehalfOf,- delegation- }: {- projectId: string;- ctx: TGenericPermission;- onBehalfOf: TOnBehalfOfUser;- delegation: Awaited<ReturnType<typeof findCallerDelegation>>;- }) => {- 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 user's own role and grants decide what they reach. 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, identifier, accessBundleIds: reachability.accessBundleIds };- };-const resolveSessionTtl = (ttl: string | undefined, isOnBehalfOf: boolean) =>ttl ?? (isOnBehalfOf ? AGENT_VAULT_ON_BEHALF_OF_SESSION_DEFAULT_TTL : AGENT_VAULT_SESSION_DEFAULT_TTL);@@ -214,7 +124,7 @@ export const agentVaultSessionServiceFactory = ({// A session on a user's behalf can use only the bundles both the user and the identity reach. The delegation is// checked first and the identity's own bundles next, so an identity learns nothing about who is in the org until// an admin has delegated it and granted it the bundle it asks for.- const delegation = await findCallerDelegation({ projectId, ctx });+ const delegation = await findCallerDelegation({ agentVaultDelegationDAL }, { projectId, ctx });const { accessBundleIds: identityReach } = await getAgentVaultReachability({ permissionService, membershipDAL },{ projectId, ctx }@@ -226,7 +136,10 @@ export const agentVaultSessionServiceFactory = ({});}- onBehalfOfUser = await resolveOnBehalfOfUser({ projectId, ctx, onBehalfOf, delegation });+ onBehalfOfUser = await resolveOnBehalfOfUser(+ { agentVaultDelegationDAL, userDAL, orgDAL, permissionService, membershipDAL },+ { projectId, ctx, onBehalfOf, delegation }+ );// 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 });diff --git a/backend/src/ee/services/agent-vault/AGENTS.md b/backend/src/ee/services/agent-vault/AGENTS.mdindex fa1e71e4ed..d3ec3733fa 100644--- a/backend/src/ee/services/agent-vault/AGENTS.md+++ b/backend/src/ee/services/agent-vault/AGENTS.md@@ -136,6 +136,9 @@ is one- **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 losinga grant drops the bundle's services like a user'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.- **Mint checks the delegation, then the identity's own bundles, then the user**, so an identity learns nothing aboutwho is in the org until an admin has delegated it and granted it the bundle, and an unknown user gets the same messageas an uncovered one. Only a machine identity may send `onBehalfOf`. The user must be an active, accepted org member,@@ -325,10 +328,10 @@ 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. 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.+ values. Two on-behalf-of routes name a user: minting, to own the session, and the access bundle list, to report+ which of the user's services still need setup (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 eachpersonal value against the session actor's personal variables only, so neither is ever expanded twice and apersonal `{{KEY}}` can't reach a global variable. A service whose actor hasn't set every member-provided field goesdiff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex 31791f441d..554adfb74a 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -4490,6 +4490,10 @@ export const AGENT_VAULT = {"true lists only the access bundles granted to you, directly or through a group. false lists the ones you reach only as an admin. Omit to list them all.",servicesRequiringSetup: "The services in this access bundle that still require your personal values.",servicesRequiringSetupId: "The ID of the service, for setting your personal values on it.",+ onBehalfOfUserId:+ "List the access bundles a session on behalf of this user could use: those both the user and your machine identity can use. requiresSetup and servicesRequiringSetup then refer to the user's personal values. Only a machine identity whose delegation covers the user can do this, and granted can't be combined with it. Set this or onBehalfOfUserEmail, not both.",+ onBehalfOfUserEmail:+ "Like onBehalfOfUserId, naming the user by email address instead. Set this or onBehalfOfUserId, not both.",servicesRequiringSetupName: "The name of the service."},SERVICE: {diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 414091ec54..8d6327df04 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -2053,7 +2053,9 @@ export const registerRoutes = async (identityGroupMembershipDAL,userDAL,groupDAL,- identityDAL+ identityDAL,+ agentVaultDelegationDAL,+ orgDAL});const agentVaultSessionService = agentVaultSessionServiceFactory({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 04421c5675..c14ff1e480 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@@ -91,6 +91,17 @@ curl -X POST https://app.infisical.com/api/v1/agent-vault/sessions \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.+### Find the access bundles a session can use++To choose an access bundle for the user, call [the endpoint that lists access bundles](/api-reference/endpoints/agent-vault-access-bundles/list) as the machine identity, and name the user in `onBehalfOfUserEmail` or `onBehalfOfUserId`:++```bash+curl "https://app.infisical.com/api/v1/agent-vault/access-bundles?onBehalfOfUserEmail=<user-email>" \+ -H "Authorization: Bearer <access-token>"+```++The response lists only the access bundles that both the user and the machine identity can use. For each bundle, `servicesRequiringSetup` lists the services the user hasn't set up their personal values for yet. The proxy refuses the session's requests to those services, so add `requiresSetup=false` to list only the bundles the user has set up.+## What the session can reachA session created on behalf of a user can use an access bundle only if both the user and the machine identity can use the bundle, and the session uses the user's personal values: