Skip to content

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

feat(agent-vault): show which bundles a delegation's identity can't act on

Scott Wilson63edb11aaed6
diff --git a/backend/e2e-test/routes/v1/agent-vault.spec.ts b/backend/e2e-test/routes/v1/agent-vault.spec.ts
index 17d6ed0137..eee4cea4ec 100644
--- a/backend/e2e-test/routes/v1/agent-vault.spec.ts
+++ b/backend/e2e-test/routes/v1/agent-vault.spec.ts
@@ -3954,14 +3954,17 @@ describe("Agent Vault V1 Router", async () => {
expect((await inject("POST", bundleMembersUrl(accessBundleId), body)).statusCode).toBe(200);
};
+ type TMissing = { missingAccessBundles: { id: string; name: string }[] };
+ type TDelegationDetail = TMissing & {
+ scope: string;
+ users: (TMissing & { id: string; addedAt: string })[];
+ groups: (TMissing & { id: string; addedAt: string })[];
+ };
+
const delegate = async (bot: TMember, body: Record<string, unknown>) => {
const res = await inject("PUT", delegationUrl(bot.id), body);
expect(res.statusCode).toBe(200);
- return res.json().delegation as {
- scope: string;
- users: { id: string; addedAt: string }[];
- groups: { id: string; addedAt: string }[];
- };
+ return res.json().delegation as TDelegationDetail;
};
const mintFor = (bot: TMember, onBehalfOf: Record<string, string>, accessBundle: string, ttl?: string) =>
@@ -4321,6 +4324,88 @@ describe("Agent Vault V1 Router", async () => {
await deleteUsers([alice.userId, outsider.userId]);
}
});
+
+ test("a delegation shows the bundles each user and group can use that the identity can't", async () => {
+ const projectId = await getProjectId();
+ const stamp = Date.now();
+ const shared = await createAccessBundle(`obo-gap-shared-${stamp}`);
+ const alicesOnly = await createAccessBundle(`obo-gap-alice-${stamp}`);
+ const groupsOnly = await createAccessBundle(`obo-gap-group-${stamp}`);
+ const bot = await createMemberIdentity(`obo-gap-bot-${stamp}`);
+ const alice = await createAgentVaultUser("obo-gap-alice", projectId);
+ const group = await createProjectGroup(projectId, `obo-gap-group-${stamp}`, ProjectMembershipRole.Member);
+ const admins = await createProjectGroup(projectId, `obo-gap-admins-${stamp}`, ProjectMembershipRole.Admin);
+ const names = (row: TMissing) => row.missingAccessBundles.map((bundle) => bundle.name);
+ const read = async () => {
+ const res = await inject("GET", delegationUrl(bot.id));
+ expect(res.statusCode).toBe(200);
+ const delegation = res.json().delegation as TDelegationDetail;
+ return {
+ delegation,
+ user: (id: string) => delegation.users.find((row) => row.id === id)!,
+ group: (id: string) => delegation.groups.find((row) => row.id === id)!
+ };
+ };
+ try {
+ await grantBundle(shared.id, { userIds: [alice.userId], machineIdentityIds: [bot.id] });
+ await grantBundle(alicesOnly.id, { userIds: [alice.userId] });
+ await grantBundle(groupsOnly.id, { groupIds: [group.id] });
+
+ const set = await delegate(bot, {
+ scope: "selected",
+ userIds: [alice.userId, seedData1.id],
+ groupIds: [group.id, admins.id]
+ });
+ expect(names(set.users.find((row) => row.id === alice.userId)!)).toEqual([alicesOnly.name]);
+
+ const before = await read();
+ expect(names(before.user(alice.userId))).toEqual([alicesOnly.name]);
+ expect(names(before.group(group.id))).toEqual([groupsOnly.name]);
+ // An admin, directly or through a group, can use every bundle, so it lacks every bundle the identity can't use.
+ [names(before.user(seedData1.id)), names(before.group(admins.id)), names(before.delegation)].forEach((row) => {
+ expect(row).toEqual(expect.arrayContaining([alicesOnly.name, groupsOnly.name]));
+ expect(row).not.toContain(shared.name);
+ });
+
+ await grantBundle(alicesOnly.id, { machineIdentityIds: [bot.id] });
+ const after = await read();
+ expect(names(after.user(alice.userId))).toEqual([]);
+ expect(names(after.delegation)).not.toContain(alicesOnly.name);
+
+ // All-members covers the admins too, so it lacks every bundle the identity can't use.
+ const allMembers = await delegate(bot, { scope: "all-members" });
+ expect(names(allMembers)).toContain(groupsOnly.name);
+ expect(names(allMembers)).not.toContain(shared.name);
+ expect(names(allMembers)).not.toContain(alicesOnly.name);
+
+ // An admin identity can use every bundle, so nothing is missing. It's promoted before anything reads its
+ // permission, since a role change reaches the permission cache only after its marker expires.
+ const adminBot = await createMemberIdentity(`obo-gap-admin-bot-${stamp}`);
+ try {
+ expect(
+ (await inject("PATCH", "/api/v1/agent-vault/members", { machineIdentityIds: [adminBot.id], role: "admin" }))
+ .statusCode
+ ).toBe(200);
+ const adminSet = await delegate(adminBot, {
+ scope: "selected",
+ userIds: [alice.userId, seedData1.id],
+ groupIds: [group.id, admins.id]
+ });
+ expect([adminSet, ...adminSet.users, ...adminSet.groups].flatMap((row) => names(row))).toEqual([]);
+ } finally {
+ await adminBot.cleanup();
+ }
+
+ // The list stays lean: working the gaps out reads every covered user's access.
+ const listed = await inject("GET", `${delegationsUrl}?machineIdentityIds=${bot.id}`);
+ expect(listed.json().delegations[0]).not.toHaveProperty("missingAccessBundles");
+ } finally {
+ await bot.cleanup();
+ await deleteUsers([alice.userId]);
+ await group.cleanup();
+ await admins.cleanup();
+ }
+ });
});
describe("session resolve", async () => {
diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-delegation-router.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-delegation-router.ts
index 506ca6c825..387341ee2f 100644
--- a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-delegation-router.ts
+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-delegation-router.ts
@@ -12,6 +12,21 @@ import { actorContext } from "./agent-vault-router-fns";
const MAX_DELEGATION_SUBJECTS = 100;
+const DelegationUserSchema = z.object({
+ id: z.string().uuid().describe(AGENT_VAULT.DELEGATION.userId),
+ username: z.string().describe(AGENT_VAULT.DELEGATION.username),
+ email: z.string().nullable().describe(AGENT_VAULT.DELEGATION.email),
+ firstName: z.string().nullable().describe(AGENT_VAULT.DELEGATION.firstName),
+ lastName: z.string().nullable().describe(AGENT_VAULT.DELEGATION.lastName),
+ addedAt: z.date().describe(AGENT_VAULT.DELEGATION.addedAt)
+});
+
+const DelegationGroupSchema = z.object({
+ id: z.string().uuid().describe(AGENT_VAULT.DELEGATION.groupId),
+ name: z.string().describe(AGENT_VAULT.DELEGATION.groupName),
+ addedAt: z.date().describe(AGENT_VAULT.DELEGATION.addedAt)
+});
+
const DelegationSchema = z.object({
machineIdentity: z
.object({
@@ -20,27 +35,35 @@ const DelegationSchema = z.object({
})
.describe(AGENT_VAULT.DELEGATION.machineIdentity),
scope: z.nativeEnum(AgentVaultDelegationScope).describe(AGENT_VAULT.DELEGATION.scope),
- users: z
+ users: DelegationUserSchema.array().describe(AGENT_VAULT.DELEGATION.users),
+ groups: DelegationGroupSchema.array().describe(AGENT_VAULT.DELEGATION.groups),
+ createdAt: z.date(),
+ updatedAt: z.date()
+});
+
+const missingAccessBundlesSchema = (description: string) =>
+ z
.object({
- id: z.string().uuid().describe(AGENT_VAULT.DELEGATION.userId),
- username: z.string().describe(AGENT_VAULT.DELEGATION.username),
- email: z.string().nullable().describe(AGENT_VAULT.DELEGATION.email),
- firstName: z.string().nullable().describe(AGENT_VAULT.DELEGATION.firstName),
- lastName: z.string().nullable().describe(AGENT_VAULT.DELEGATION.lastName),
- addedAt: z.date().describe(AGENT_VAULT.DELEGATION.addedAt)
+ id: z.string().uuid().describe(AGENT_VAULT.DELEGATION.accessBundleId),
+ name: z.string().describe(AGENT_VAULT.DELEGATION.accessBundleName)
})
+ .array()
+ .describe(description);
+
+// Only one delegation at a time says which bundles its machine identity can't act on: working that out reads the
+// access of every user it covers, too much for a list.
+const DelegationDetailSchema = DelegationSchema.extend({
+ users: DelegationUserSchema.extend({
+ missingAccessBundles: missingAccessBundlesSchema(AGENT_VAULT.DELEGATION.userMissingAccessBundles)
+ })
.array()
.describe(AGENT_VAULT.DELEGATION.users),
- groups: z
- .object({
- id: z.string().uuid().describe(AGENT_VAULT.DELEGATION.groupId),
- name: z.string().describe(AGENT_VAULT.DELEGATION.groupName),
- addedAt: z.date().describe(AGENT_VAULT.DELEGATION.addedAt)
- })
+ groups: DelegationGroupSchema.extend({
+ missingAccessBundles: missingAccessBundlesSchema(AGENT_VAULT.DELEGATION.groupMissingAccessBundles)
+ })
.array()
.describe(AGENT_VAULT.DELEGATION.groups),
- createdAt: z.date(),
- updatedAt: z.date()
+ missingAccessBundles: missingAccessBundlesSchema(AGENT_VAULT.DELEGATION.missingAccessBundles)
});
const machineIdentityParams = z.object({
@@ -100,7 +123,7 @@ export const registerAgentVaultDelegationRouter = async (server: FastifyZodProvi
"Get which users a machine identity can start Agent Vault sessions on behalf of. A machine identity can read its own.",
tags: [ApiDocsTags.AgentVaultDelegations],
params: machineIdentityParams,
- response: { 200: z.object({ delegation: DelegationSchema }) }
+ response: { 200: z.object({ delegation: DelegationDetailSchema }) }
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) =>
@@ -158,7 +181,7 @@ export const registerAgentVaultDelegationRouter = async (server: FastifyZodProvi
});
}
}),
- response: { 200: z.object({ delegation: DelegationSchema }) }
+ response: { 200: z.object({ delegation: DelegationDetailSchema }) }
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
diff --git a/backend/src/ee/services/agent-vault-delegation/agent-vault-delegation-service.ts b/backend/src/ee/services/agent-vault-delegation/agent-vault-delegation-service.ts
index da8352660a..f961a63819 100644
--- a/backend/src/ee/services/agent-vault-delegation/agent-vault-delegation-service.ts
+++ b/backend/src/ee/services/agent-vault-delegation/agent-vault-delegation-service.ts
@@ -1,13 +1,16 @@
-import { AccessScope } from "@app/db/schemas";
+import { AccessScope, ProjectMembershipRole, RESOURCE_SCOPE, ResourceType } from "@app/db/schemas";
import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";
+import { isActiveRole } from "@app/ee/services/permission/permission-fns";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
import { TGenericPermission } from "@app/lib/types";
import { ActorType } from "@app/services/auth/auth-type";
import { TMembershipDALFactory } from "@app/services/membership/membership-dal";
+import { TMembershipRoleDALFactory } from "@app/services/membership/membership-role-dal";
import { AgentVaultDelegationScope } from "../agent-vault/agent-vault-enums";
-import { getAgentVaultPermission } from "../agent-vault/agent-vault-permission";
+import { getAgentVaultPermission, getAgentVaultReachability } from "../agent-vault/agent-vault-permission";
+import { TAgentVaultAccessBundleDALFactory } from "../agent-vault-access-bundle/agent-vault-access-bundle-dal";
import {
TAgentVaultDelegationDALFactory,
TAgentVaultDelegationSubjectDALFactory,
@@ -26,13 +29,17 @@ type TAgentVaultDelegationServiceFactoryDep = {
"upsertScope" | "findViews" | "delete" | "transaction"
>;
agentVaultDelegationSubjectDAL: Pick<TAgentVaultDelegationSubjectDALFactory, "find" | "delete" | "insertMany">;
- membershipDAL: Pick<TMembershipDALFactory, "find" | "findOne">;
+ agentVaultAccessBundleDAL: Pick<TAgentVaultAccessBundleDALFactory, "find">;
+ membershipDAL: Pick<TMembershipDALFactory, "find" | "findOne" | "findResourceMembershipsForActor">;
+ membershipRoleDAL: Pick<TMembershipRoleDALFactory, "find">;
userGroupMembershipDAL: Pick<TUserGroupMembershipDALFactory, "find">;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
};
export type TAgentVaultDelegationServiceFactory = ReturnType<typeof agentVaultDelegationServiceFactory>;
+type TMissingAccessBundle = { id: string; name: string };
+
// The row id stays internal: a delegation is named by its machine identity, the one id a client sends back.
const toDelegation = ({ id, ...delegation }: TAgentVaultDelegationView) => delegation;
@@ -41,7 +48,9 @@ const quoted = (ids: string[]) => ids.map((id) => `'${id}'`).join(", ");
export const agentVaultDelegationServiceFactory = ({
agentVaultDelegationDAL,
agentVaultDelegationSubjectDAL,
+ agentVaultAccessBundleDAL,
membershipDAL,
+ membershipRoleDAL,
userGroupMembershipDAL,
permissionService
}: TAgentVaultDelegationServiceFactoryDep) => {
@@ -118,6 +127,127 @@ export const agentVaultDelegationServiceFactory = ({
throw new BadRequestError({ message: reasons.join(" ") });
};
+ // Users and the identity go through the same reachability as mint, so the view can't disagree with what mint allows.
+ const reachOf = async ({
+ projectId,
+ orgId,
+ actor
+ }: {
+ projectId: string;
+ orgId: string;
+ actor: { type: ActorType.USER | ActorType.IDENTITY; id: string };
+ }) => {
+ try {
+ const { accessBundleIds } = await getAgentVaultReachability(
+ { permissionService, membershipDAL },
+ { projectId, ctx: { actor: actor.type, actorId: actor.id, actorOrgId: orgId, actorAuthMethod: null } }
+ );
+ return accessBundleIds;
+ } catch (error) {
+ if (error instanceof ForbiddenRequestError && error.name === "ProjectMembershipNotFound") return [];
+ throw error;
+ }
+ };
+
+ // A group reaches nothing without a live Agent Vault role, every bundle with the admin role, and otherwise the
+ // bundles granted to it, which is what a group's grants add to its members' reach.
+ const groupReachOf = async ({ projectId, groupIds }: { projectId: string; groupIds: string[] }) => {
+ const reaches = new Map<string, string[] | null>();
+ if (!groupIds.length) return reaches;
+
+ const [memberships, grants] = await Promise.all([
+ membershipDAL.find({ scope: AccessScope.Project, scopeProjectId: projectId, $in: { actorGroupId: groupIds } }),
+ membershipDAL.find({
+ scope: RESOURCE_SCOPE,
+ scopeProjectId: projectId,
+ scopeResourceType: ResourceType.AgentVaultAccessBundle,
+ $in: { actorGroupId: groupIds }
+ })
+ ]);
+ const roles = memberships.length
+ ? await membershipRoleDAL.find({ $in: { membershipId: memberships.map((membership) => membership.id) } })
+ : [];
+
+ groupIds.forEach((groupId) => {
+ const membershipIds = new Set(
+ memberships.filter((m) => m.actorGroupId === groupId && m.isActive).map((membership) => membership.id)
+ );
+ const liveRoles = roles.filter((role) => membershipIds.has(role.membershipId) && isActiveRole(role));
+ if (!liveRoles.length) {
+ reaches.set(groupId, []);
+ } else if (liveRoles.some((role) => role.role === ProjectMembershipRole.Admin)) {
+ reaches.set(groupId, null);
+ } else {
+ reaches.set(
+ groupId,
+ grants
+ .filter((grant) => grant.actorGroupId === groupId && grant.isActive)
+ .map((grant) => grant.scopeResourceId!)
+ );
+ }
+ });
+ return reaches;
+ };
+
+ // A session on a user's behalf can use only the bundles both the user and the identity reach, so these are the
+ // bundles the identity can't act on for each user and group it covers. All-members covers Agent Vault admins, who
+ // reach every bundle, so there it is every bundle the identity can't reach.
+ const withMissingAccessBundles = async ({
+ projectId,
+ ctx,
+ delegation
+ }: {
+ projectId: string;
+ ctx: TGenericPermission;
+ delegation: TAgentVaultDelegationView;
+ }) => {
+ const identityReach = await reachOf({
+ projectId,
+ orgId: ctx.actorOrgId,
+ actor: { type: ActorType.IDENTITY, id: delegation.machineIdentity.id }
+ });
+ const lacking: TMissingAccessBundle[] =
+ identityReach === null
+ ? []
+ : (await agentVaultAccessBundleDAL.find({ projectId }, { sort: [["name", "asc"]] }))
+ .filter((bundle) => !identityReach.includes(bundle.id))
+ .map((bundle) => ({ id: bundle.id, name: bundle.name }));
+ const missingFrom = (reach: string[] | null) =>
+ reach === null ? lacking : lacking.filter((bundle) => reach.includes(bundle.id));
+
+ const [userReaches, groupReaches] = lacking.length
+ ? await Promise.all([
+ Promise.all(
+ delegation.users.map((user) =>
+ reachOf({ projectId, orgId: ctx.actorOrgId, actor: { type: ActorType.USER, id: user.id } })
+ )
+ ),
+ groupReachOf({ projectId, groupIds: delegation.groups.map((group) => group.id) })
+ ])
+ : [[], new Map<string, string[] | null>()];
+
+ // Each reach ran getProjectPermission for someone else, and the audit log reads the caller's permission metadata
+ // from the request context. Running the caller's check again, memoized so it costs no query, puts it back.
+ await getAgentVaultPermission({ permissionService }, { projectId, ctx });
+
+ const users = delegation.users.map((user, index) => ({
+ ...user,
+ missingAccessBundles: lacking.length ? missingFrom(userReaches[index]) : []
+ }));
+ const groups = delegation.groups.map((group) => {
+ // A null reach is every bundle, so it can't fall back with ??.
+ const reach = groupReaches.get(group.id);
+ return { ...group, missingAccessBundles: reach === undefined ? [] : missingFrom(reach) };
+ });
+ const missingIds = new Set([...users, ...groups].flatMap((s) => s.missingAccessBundles.map((bundle) => bundle.id)));
+ const missingAccessBundles =
+ delegation.scope === AgentVaultDelegationScope.AllMembers
+ ? lacking
+ : lacking.filter((bundle) => missingIds.has(bundle.id));
+
+ return { ...toDelegation(delegation), users, groups, missingAccessBundles };
+ };
+
const listDelegations = async ({ projectId, ctx, machineIdentityIds, limit, offset }: TListDelegationsDTO) => {
await checkAdmin(projectId, ctx);
const { delegations, totalCount } = await agentVaultDelegationDAL.findViews({
@@ -143,7 +273,7 @@ export const agentVaultDelegationServiceFactory = ({
delegations: [delegation]
} = await agentVaultDelegationDAL.findViews({ projectId, identityIds: [machineIdentityId] });
if (!delegation) throw notFound(machineIdentityId);
- return { delegation: toDelegation(delegation) };
+ return { delegation: await withMissingAccessBundles({ projectId, ctx, delegation }) };
};
const setDelegation = async ({ projectId, ctx, machineIdentityId, scope, userIds, groupIds }: TSetDelegationDTO) => {
@@ -195,7 +325,8 @@ export const agentVaultDelegationServiceFactory = ({
return written;
});
- return { delegation: toDelegation(delegation) };
+ // After the commit: reading every covered user's reach is many queries, none of which belong in the transaction.
+ return { delegation: await withMissingAccessBundles({ projectId, ctx, delegation }) };
};
const deleteDelegation = async ({ projectId, ctx, machineIdentityId }: TDeleteDelegationDTO) => {
diff --git a/backend/src/ee/services/agent-vault/AGENTS.md b/backend/src/ee/services/agent-vault/AGENTS.md
index 5d631878d4..470af97058 100644
--- a/backend/src/ee/services/agent-vault/AGENTS.md
+++ b/backend/src/ee/services/agent-vault/AGENTS.md
@@ -140,6 +140,11 @@ is one
who is in the org until an admin has delegated it and granted it the bundle, and an unknown user gets the same message
as an uncovered one. Only a machine identity may send `onBehalfOf`. The user must be an active, accepted org member,
as resolve requires.
+- **The delegation read and write return `missingAccessBundles`**, per user and group and in total: the bundles they
+ can use and the identity can't. Users and the identity go through `getAgentVaultReachability`, the function mint
+ uses, so the view can't disagree with mint; a group's reach is its own live role and grants, read directly since a
+ group never holds a session. The list leaves it out, because it reads every covered user's access, and the write
+ works it out after its transaction commits.
- **Mint runs `getProjectPermission` for the user, then once more for the caller.** The permission service leaves
the last actor it ran for in the request context, where the audit log reads the caller's permission metadata. The
second call is memoized, so it costs no query; dropping it attributes the user's metadata to the identity.
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index 70b0c0c699..eccbbe87c4 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -4778,6 +4778,14 @@ export const AGENT_VAULT = {
groupId: "The ID of the group.",
groupName: "The name of the group.",
addedAt: "When the user or group was added to the delegation.",
+ missingAccessBundles:
+ "The access bundles that users the delegation covers can use and the machine identity can't. A session on behalf of a user can use only an access bundle that both can use, so the machine identity can't start sessions over these. With all-members, this is every access bundle the machine identity can't use, since Agent Vault admins can use every bundle.",
+ userMissingAccessBundles:
+ "The access bundles this user can use and the machine identity can't, so the machine identity can't start sessions over them on the user's behalf. For an Agent Vault admin, this is every access bundle the machine identity can't use.",
+ groupMissingAccessBundles:
+ "The access bundles granted to this group, or every bundle if the group has the Admin role, that the machine identity can't use.",
+ accessBundleId: "The ID of the access bundle.",
+ accessBundleName: "The name of the access bundle.",
limit: "The maximum number of delegations to return.",
offset: "How many delegations to skip."
}
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 5e0927002e..414091ec54 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -2071,7 +2071,9 @@ export const registerRoutes = async (
const agentVaultDelegationService = agentVaultDelegationServiceFactory({
agentVaultDelegationDAL,
agentVaultDelegationSubjectDAL,
+ agentVaultAccessBundleDAL,
membershipDAL,
+ membershipRoleDAL,
userGroupMembershipDAL,
permissionService
});
diff --git a/docs/documentation/platform/agent-vault/sessions-on-behalf-of-users.mdx b/docs/documentation/platform/agent-vault/sessions-on-behalf-of-users.mdx
index 4b3f78f35a..ecfa972654 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
@@ -1,11 +1,11 @@
---
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, with each user's own personal values."
+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. A session created on behalf of a user belongs to that user, so the proxy uses the user's own [personal values](/documentation/platform/agent-vault/services#member-provided-values). 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. A session created on behalf of a user belongs to that user, so the [proxy](/documentation/platform/agent-vault/proxies) uses the user's own [personal values](/documentation/platform/agent-vault/services#member-provided-values). 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, and uses that person's own credential wherever a service leaves part of its credential to members.
+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.
```mermaid
sequenceDiagram
@@ -28,7 +28,7 @@ sequenceDiagram
- The **Admin** role in [Agent Vault](/documentation/platform/agent-vault/access-control#product-membership), or an Agent Vault admin who can [set up the delegation](#set-up-a-delegation) for you
- A machine identity that's a member of Agent Vault and can log in with [Universal Auth](/documentation/platform/identities/universal-auth), as [Step 1 of Create sessions with the API](/documentation/platform/agent-vault/sessions-api#step-1-set-up-a-machine-identity) describes
- A [grant](/documentation/platform/agent-vault/access-bundles#manage-access-to-access-bundles) for the machine identity on each access bundle its sessions use
-- Users who are members of Agent Vault and have a grant on the access bundles their agents use
+- Users who are [members of Agent Vault](/documentation/platform/agent-vault/access-control#product-membership) and have a grant on the access bundles their agents use
## Set up a delegation
@@ -40,11 +40,15 @@ sequenceDiagram
</Step>
<Step>
In the **Delegation** section, select **Add Users or Groups**.
+
+ <Frame>
+ <img src="/images/platform/agent-vault/machine-identity-delegation.png" alt="The Delegation section of a machine identity, listing two groups and a user with the date each was added, and the Add Users or Groups button" />
+ </Frame>
</Step>
<Step>
- Pick the users and groups in **Users and Groups**, and select **Add**. A group covers every member of the group.
+ In **Users and Groups**, select the users and groups to add, then select **Add**. A group covers every member of the group.
- To cover every user in Agent Vault instead, including users added later, turn on **All Agent Vault Members** and select **Allow All Members**.
+ To cover every current and future user in Agent Vault instead, turn on **All Agent Vault Members** and select **Allow All Members**.
</Step>
</Steps>
</Tab>
@@ -62,9 +66,9 @@ sequenceDiagram
</Tab>
</Tabs>
-You can pick only users and groups that are members of Agent Vault. If a user is in Agent Vault only through a group, pick the group.
+You can add only users and groups that are members of Agent Vault. If a user is in Agent Vault only through a group, add the group.
-To take a user or group out of the delegation, open its actions menu in the **Delegation** section, select **Remove**, and confirm. If you remove the last user or group, or the **All Agent Vault Members** row, the machine identity can no longer act on behalf of anyone.
+To take a user or group out of the delegation, select the actions menu on its row in the **Delegation** section, select **Remove**, then select **Remove** again to confirm. If you remove the last user or group, or the **All Agent Vault Members** row, the machine identity can no longer act on behalf of anyone.
<Warning>
If a machine identity has a delegation, anyone who can log in as the machine identity can send requests with the personal values of every user the delegation covers. Protect the machine identity's credentials as carefully as you'd protect those users' own credentials.
@@ -95,6 +99,8 @@ A session created on behalf of a user can use an access bundle only if both the
- The machine identity can use the access bundles granted to it, directly or through a group (if the machine identity is an Agent Vault admin, every bundle)
- The proxy refuses the session's requests to a service until the user [sets up their personal values](/documentation/platform/agent-vault/access-bundles#set-up-your-personal-values) for it
+If a user or group in the delegation can use an access bundle that isn't granted to the machine identity, their row in the machine identity's **Delegation** section shows the number of excluded bundles, and hovering over the number lists them. Through the API, [the endpoint that reads a delegation](/api-reference/endpoints/agent-vault-delegations/get) returns the same bundles in `missingAccessBundles`. To let the machine identity create sessions over one of them, [grant the bundle](/documentation/platform/agent-vault/access-bundles#manage-access-to-access-bundles) to the machine identity.
+
## When the session stops working
Infisical checks the delegation again each time the proxy polls, once every [poll interval](/documentation/platform/agent-vault/proxies#poll-interval) (60 seconds by default). The proxy refuses every request on the session if any of these happen:
@@ -113,12 +119,12 @@ If the user or the machine identity can no longer use the access bundle, the ses
These people and identities can see the session and revoke it:
- The user, under **My Sessions**
-- The machine identity, through the API that [reads a session](/api-reference/endpoints/agent-vault-sessions/get) and the API that [revokes a session](/api-reference/endpoints/agent-vault-sessions/revoke)
+- 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**
On the **Sessions** page, the **Identity** column shows the user, followed by "via" and the machine identity's name. The session's details list the machine identity under **Started By**.
-When the machine identity creates the session, the audit event names the machine identity as the actor, and records the user in `onBehalfOfUserId`, `onBehalfOfUserName`, and `onBehalfOfUserEmail`. Infisical also writes an audit event when an admin sets up, changes, or removes a delegation.
+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.
## Troubleshooting
diff --git a/docs/images/platform/agent-vault/machine-identity-delegation.png b/docs/images/platform/agent-vault/machine-identity-delegation.png
new file mode 100644
index 0000000000..5f2eb9aa9e
Binary files /dev/null and b/docs/images/platform/agent-vault/machine-identity-delegation.png differ
diff --git a/frontend/src/components/agent-vault/IdentityDelegationSection.tsx b/frontend/src/components/agent-vault/IdentityDelegationSection.tsx
index 8d740c4118..d5c5e5bff8 100644
--- a/frontend/src/components/agent-vault/IdentityDelegationSection.tsx
+++ b/frontend/src/components/agent-vault/IdentityDelegationSection.tsx
@@ -40,23 +40,27 @@ import {
import { useProjectPermission } from "@app/context";
import {
useDeleteAgentVaultDelegation,
- useListAgentVaultDelegations,
+ useGetAgentVaultDelegation,
useSetAgentVaultDelegation
} from "@app/hooks/api/agentVault";
import { AgentVaultDelegationScope, AgentVaultMemberType } from "@app/hooks/api/agentVault/enums";
-import { TAgentVaultActor } from "@app/hooks/api/agentVault/types";
+import { TAgentVaultActor, TAgentVaultMissingAccessBundle } from "@app/hooks/api/agentVault/types";
import { ProjectMembershipRole } from "@app/hooks/api/roles/types";
import { AgentVaultDocsUrls } from "@app/pages/agent-vault/agent-vault-docs-urls";
import { AddDelegationSubjectsDialog } from "./AddDelegationSubjectsDialog";
import { memberDisplayName, MemberName } from "./MemberName";
+import { MissingAccessBundlesHint } from "./MissingAccessBundlesHint";
type Props = {
machineIdentityId: string;
machineIdentityName: string;
};
-type TSubjectRow = TAgentVaultActor & { addedAt: string };
+type TSubjectRow = TAgentVaultActor & {
+ addedAt: string;
+ missingAccessBundles: TAgentVaultMissingAccessBundle[];
+};
type TPendingRemoval = { kind: "subject"; subject: TSubjectRow } | { kind: "all-members" };
@@ -65,11 +69,8 @@ export const IdentityDelegationSection = ({ machineIdentityId, machineIdentityNa
const { hasProjectRole } = useProjectPermission();
const isAdmin = hasProjectRole(ProjectMembershipRole.Admin);
- const { data: delegations, isPending } = useListAgentVaultDelegations(
- [machineIdentityId],
- isAdmin
- );
- const delegation = delegations?.[0] ?? null;
+ const { data, isPending } = useGetAgentVaultDelegation(machineIdentityId, isAdmin);
+ const delegation = data ?? null;
const setDelegation = useSetAgentVaultDelegation();
const deleteDelegation = useDeleteAgentVaultDelegation();
@@ -196,8 +197,15 @@ export const IdentityDelegationSection = ({ machineIdentityId, machineIdentityNa
<UsersRoundIcon className="size-4 shrink-0 text-muted" />
<div className="min-w-0">
<div className="truncate">All Agent Vault Members</div>
- <div className="truncate text-xs leading-4 text-muted">
- Every user in Agent Vault, including users added later
+ <div className="flex min-w-0 items-center gap-2 text-xs leading-4 text-muted">
+ <span className="min-w-0 truncate">
+ Every user in Agent Vault, including users added later
+ </span>
+ <MissingAccessBundlesHint
+ bundles={delegation.missingAccessBundles}
+ machineIdentityName={machineIdentityName}
+ onBehalfOf="Agent Vault members"
+ />
</div>
</div>
</div>
@@ -213,7 +221,20 @@ export const IdentityDelegationSection = ({ machineIdentityId, machineIdentityNa
subjects.map((subject) => (
<TableRow key={`${subject.type}:${subject.id}`}>
<TableCell>
- <MemberName member={subject} />
+ <MemberName
+ member={subject}
+ subtitleAddon={
+ <MissingAccessBundlesHint
+ bundles={subject.missingAccessBundles}
+ machineIdentityName={machineIdentityName}
+ onBehalfOf={
+ subject.type === AgentVaultMemberType.Group
+ ? `members of "${memberDisplayName(subject)}"`
+ : `"${memberDisplayName(subject)}"`
+ }
+ />
+ }
+ />
</TableCell>
<TableCell>{format(new Date(subject.addedAt), "MMM d, yyyy")}</TableCell>
<TableCell variant="action">
diff --git a/frontend/src/components/agent-vault/MemberName.tsx b/frontend/src/components/agent-vault/MemberName.tsx
index d6618657ba..ed7fb889ed 100644
--- a/frontend/src/components/agent-vault/MemberName.tsx
+++ b/frontend/src/components/agent-vault/MemberName.tsx
@@ -21,7 +21,13 @@ export const memberSubtitle = (actor: TAgentVaultActor | TAgentVaultSessionActor
return actor.email || actor.username;
};
-export const MemberName = ({ member }: { member: TAgentVaultActor }) => {
+export const MemberName = ({
+ member,
+ subtitleAddon
+}: {
+ member: TAgentVaultActor;
+ subtitleAddon?: React.ReactNode;
+}) => {
const { label, icon: Icon } = MEMBER_KIND[member.type];
return (
@@ -30,7 +36,14 @@ export const MemberName = ({ member }: { member: TAgentVaultActor }) => {
<span className="sr-only">{label}</span>
<div className="min-w-0">
<div className="truncate">{memberDisplayName(member)}</div>
- <div className="truncate text-xs leading-4 text-muted">{memberSubtitle(member)}</div>
+ {subtitleAddon ? (
+ <div className="flex min-w-0 items-center gap-2 text-xs leading-4 text-muted">
+ <span className="min-w-0 truncate">{memberSubtitle(member)}</span>
+ {subtitleAddon}
+ </div>
+ ) : (
+ <div className="truncate text-xs leading-4 text-muted">{memberSubtitle(member)}</div>
+ )}
</div>
</div>
);
diff --git a/frontend/src/components/agent-vault/MissingAccessBundlesHint.tsx b/frontend/src/components/agent-vault/MissingAccessBundlesHint.tsx
new file mode 100644
index 0000000000..543e8650bc
--- /dev/null
+++ b/frontend/src/components/agent-vault/MissingAccessBundlesHint.tsx
@@ -0,0 +1,56 @@
+import { Link } from "@tanstack/react-router";
+import { PackageIcon } from "lucide-react";
+
+import { Badge, HoverCard, HoverCardContent, HoverCardTrigger } from "@app/components/v3";
+import { useOrganization } from "@app/context";
+import { TAgentVaultMissingAccessBundle } from "@app/hooks/api/agentVault/types";
+
+type Props = {
+ bundles: TAgentVaultMissingAccessBundle[];
+ machineIdentityName: string;
+ // Finishes "Sessions on behalf of ...", so it names who the sessions are for.
+ onBehalfOf: string;
+};
+
+// An admin can leave bundles out of a delegation on purpose, so this informs rather than warns.
+export const MissingAccessBundlesHint = ({ bundles, machineIdentityName, onBehalfOf }: Props) => {
+ const { currentOrg } = useOrganization();
+ if (!bundles.length) return null;
+
+ const label = `${bundles.length} ${bundles.length === 1 ? "bundle" : "bundles"} excluded`;
+
+ return (
+ <HoverCard openDelay={150} closeDelay={100}>
+ <HoverCardTrigger asChild>
+ <button
+ type="button"
+ className="inline-flex shrink-0 items-center gap-1 rounded-sm text-xs leading-4 text-muted outline-hidden hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50"
+ >
+ <PackageIcon className="size-3" />
+ <span className="underline decoration-dotted underline-offset-2">{label}</span>
+ </button>
+ </HoverCardTrigger>
+ <HoverCardContent align="start" className="flex w-80 flex-col gap-2.5">
+ <p className="text-xs text-muted">
+ {`Sessions on behalf of ${onBehalfOf} can't use these access bundles, because "${machineIdentityName}" isn't granted them.`}
+ </p>
+ <div className="flex flex-wrap gap-1.5">
+ {bundles.map((bundle) => (
+ <Badge key={bundle.id} variant="neutral" iconPosition="left" asChild>
+ <Link
+ to="/organizations/$orgId/agent-vault/access-bundles/$accessBundleId"
+ params={{ orgId: currentOrg.id, accessBundleId: bundle.id }}
+ >
+ <PackageIcon />
+ {bundle.name}
+ </Link>
+ </Badge>
+ ))}
+ </div>
+ <p className="text-xs text-muted">
+ {`To include one, grant it to "${machineIdentityName}" from the bundle's Manage Access.`}
+ </p>
+ </HoverCardContent>
+ </HoverCard>
+ );
+};
diff --git a/frontend/src/hooks/api/agentVault/mutations.tsx b/frontend/src/hooks/api/agentVault/mutations.tsx
index 07161afd91..07f24b15fe 100644
--- a/frontend/src/hooks/api/agentVault/mutations.tsx
+++ b/frontend/src/hooks/api/agentVault/mutations.tsx
@@ -13,6 +13,7 @@ import {
TAgentVaultActorIdsDTO,
TAgentVaultActorRef,
TAgentVaultDelegation,
+ TAgentVaultDelegationDetail,
TAgentVaultGrantedMember,
TAgentVaultMemberWriteResult,
TAgentVaultMintedSession,
@@ -43,7 +44,7 @@ export const useSetAgentVaultDelegation = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async ({ machineIdentityId, ...body }: TSetAgentVaultDelegationDTO) => {
- const { data } = await apiRequest.put<{ delegation: TAgentVaultDelegation }>(
+ const { data } = await apiRequest.put<{ delegation: TAgentVaultDelegationDetail }>(
`/api/v1/agent-vault/delegations/${machineIdentityId}`,
body
);
diff --git a/frontend/src/hooks/api/agentVault/queries.tsx b/frontend/src/hooks/api/agentVault/queries.tsx
index c4f9e67e1f..feb640c356 100644
--- a/frontend/src/hooks/api/agentVault/queries.tsx
+++ b/frontend/src/hooks/api/agentVault/queries.tsx
@@ -22,7 +22,7 @@ import {
TAgentVaultAccessBundleDetails,
TAgentVaultAccessBundleListItem,
TAgentVaultDecryptedSessionLogPage,
- TAgentVaultDelegation,
+ TAgentVaultDelegationDetail,
TAgentVaultMember,
TAgentVaultProductActor,
TAgentVaultProductMember,
@@ -104,8 +104,8 @@ export const agentVaultKeys = {
availableMemberList: (orgId: string, params?: TListAgentVaultMembersDTO) =>
[...agentVaultKeys.availableMembers(orgId), params] as const,
delegations: (orgId: string) => [...agentVaultKeys.all(orgId), "delegations"] as const,
- delegationsOf: (orgId: string, machineIdentityIds: string[]) =>
- [...agentVaultKeys.delegations(orgId), machineIdentityIds] as const,
+ delegation: (orgId: string, machineIdentityId: string) =>
+ [...agentVaultKeys.delegations(orgId), machineIdentityId] as const,
sessionLogSettings: (orgId: string) =>
[...agentVaultKeys.all(orgId), "settings", "session-logs"] as const,
sessionLogHealth: (orgId: string) =>
@@ -138,21 +138,26 @@ export const useListAgentVaultMembers = <T extends AgentVaultMemberType = AgentV
});
};
-// Read through the list, so an identity with no delegation is an empty result rather than a 404. Admins only.
-export const useListAgentVaultDelegations = (machineIdentityIds: string[], enabled = true) => {
+// An identity with no delegation reads as null rather than an error. Admins only. Refetched on every visit, because the
+// bundles the identity can't act on change with grants and roles anywhere in Agent Vault.
+export const useGetAgentVaultDelegation = (machineIdentityId: string, enabled = true) => {
const { currentOrg } = useOrganization();
return useQuery({
- queryKey: agentVaultKeys.delegationsOf(currentOrg.id, machineIdentityIds),
+ queryKey: agentVaultKeys.delegation(currentOrg.id, machineIdentityId),
queryFn: async () => {
- const { data } = await apiRequest.get<{ delegations: TAgentVaultDelegation[] }>(
- "/api/v1/agent-vault/delegations",
- { params: { machineIdentityIds: machineIdentityIds.join(","), limit: 100 } }
- );
- return data.delegations;
+ try {
+ const { data } = await apiRequest.get<{ delegation: TAgentVaultDelegationDetail }>(
+ `/api/v1/agent-vault/delegations/${machineIdentityId}`
+ );
+ return data.delegation;
+ } catch (error) {
+ if (axios.isAxiosError(error) && error.response?.status === 404) return null;
+ throw error;
+ }
},
- enabled: enabled && machineIdentityIds.length > 0,
- placeholderData: (prev) => prev
+ enabled,
+ staleTime: 0
});
};
diff --git a/frontend/src/hooks/api/agentVault/types.ts b/frontend/src/hooks/api/agentVault/types.ts
index 05549024b4..cc5014fcf7 100644
--- a/frontend/src/hooks/api/agentVault/types.ts
+++ b/frontend/src/hooks/api/agentVault/types.ts
@@ -259,6 +259,20 @@ export type TAgentVaultDelegation = {
updatedAt: string;
};
+export type TAgentVaultMissingAccessBundle = { id: string; name: string };
+
+// Reading or writing one delegation also says which bundles its machine identity can't act on: the ones each user and
+// group can use and the identity can't.
+export type TAgentVaultDelegationDetail = Omit<TAgentVaultDelegation, "users" | "groups"> & {
+ users: (TAgentVaultDelegation["users"][number] & {
+ missingAccessBundles: TAgentVaultMissingAccessBundle[];
+ })[];
+ groups: (TAgentVaultDelegation["groups"][number] & {
+ missingAccessBundles: TAgentVaultMissingAccessBundle[];
+ })[];
+ missingAccessBundles: TAgentVaultMissingAccessBundle[];
+};
+
export type TSetAgentVaultDelegationDTO = {
machineIdentityId: string;
scope: AgentVaultDelegationScope;