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 a delegation as a table, with an add dialog
Scott Wilson9b93e7da9b57
diff --git a/backend/e2e-test/routes/v1/agent-vault.spec.ts b/backend/e2e-test/routes/v1/agent-vault.spec.tsindex 8d3a2a8a32..70ef6ffa9b 100644--- a/backend/e2e-test/routes/v1/agent-vault.spec.ts+++ b/backend/e2e-test/routes/v1/agent-vault.spec.ts@@ -3957,7 +3957,11 @@ describe("Agent Vault V1 Router", async () => {const delegate = async (bot: TMember, body: Record<string, unknown>) => {const res = await inject("PUT", delegationUrl(bot.id), body);expect(res.statusCode).toBe(200);- return res.json().delegation as { scope: string; users: { id: string }[]; groups: { id: string }[] };+ return res.json().delegation as {+ scope: string;+ users: { id: string; addedAt: string }[];+ groups: { id: string; addedAt: string }[];+ };};const mintFor = (bot: TMember, onBehalfOf: Record<string, string>, accessBundle: string, ttl?: string) =>@@ -4253,6 +4257,16 @@ describe("Agent Vault V1 Router", async () => {const set = await delegate(bot, { scope: "selected", userIds: [alice.userId] });expect(set).toMatchObject({ scope: "selected", users: [expect.objectContaining({ id: alice.userId })] });+ // A save keeps the rows that stay, so each one's addedAt still says when it was added.+ const group = await createProjectGroup(projectId, `obo-api-group-${Date.now()}`, ProjectMembershipRole.Member);+ try {+ const widened = await delegate(bot, { scope: "selected", userIds: [alice.userId], groupIds: [group.id] });+ expect(widened.users).toEqual([expect.objectContaining({ id: alice.userId, addedAt: set.users[0].addedAt })]);+ expect(widened.groups).toEqual([expect.objectContaining({ id: group.id })]);+ } finally {+ await group.cleanup();+ }+expect((await bot.as("GET", delegationUrl(bot.id))).statusCode).toBe(200);expect((await other.as("GET", delegationUrl(bot.id))).statusCode).toBe(403);expect((await other.as("PUT", delegationUrl(other.id), { scope: "all-members" })).statusCode).toBe(403);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.tsindex 293e6c2d85..506ca6c825 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@@ -26,14 +26,16 @@ const DelegationSchema = z.object({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)+ lastName: z.string().nullable().describe(AGENT_VAULT.DELEGATION.lastName),+ addedAt: z.date().describe(AGENT_VAULT.DELEGATION.addedAt)}).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)+ name: z.string().describe(AGENT_VAULT.DELEGATION.groupName),+ addedAt: z.date().describe(AGENT_VAULT.DELEGATION.addedAt)}).array().describe(AGENT_VAULT.DELEGATION.groups),diff --git a/backend/src/ee/services/agent-vault-delegation/agent-vault-delegation-dal.ts b/backend/src/ee/services/agent-vault-delegation/agent-vault-delegation-dal.tsindex 9c1fd95466..f0c5ad4cef 100644--- a/backend/src/ee/services/agent-vault-delegation/agent-vault-delegation-dal.ts+++ b/backend/src/ee/services/agent-vault-delegation/agent-vault-delegation-dal.ts@@ -14,8 +14,15 @@ export type TAgentVaultDelegationView = {id: string;machineIdentity: { id: string; name: string };scope: AgentVaultDelegationScope;- users: { id: string; username: string; email: string | null; firstName: string | null; lastName: string | null }[];- groups: { id: string; name: string }[];+ users: {+ id: string;+ username: string;+ email: string | null;+ firstName: string | null;+ lastName: string | null;+ addedAt: Date;+ }[];+ groups: { id: string; name: string; addedAt: Date }[];createdAt: Date;updatedAt: Date;};@@ -89,6 +96,7 @@ export const agentVaultDelegationDALFactory = (db: TDbClient) => {db.ref("delegationId").withSchema(TableName.AgentVaultDelegationSubject),db.ref("userId").withSchema(TableName.AgentVaultDelegationSubject),db.ref("groupId").withSchema(TableName.AgentVaultDelegationSubject),+ db.ref("createdAt").withSchema(TableName.AgentVaultDelegationSubject).as("addedAt"),db.ref("username").withSchema(TableName.Users),db.ref("email").withSchema(TableName.Users),db.ref("firstName").withSchema(TableName.Users),@@ -105,6 +113,7 @@ export const agentVaultDelegationDALFactory = (db: TDbClient) => {firstName: string | null;lastName: string | null;groupName: string | null;+ addedAt: Date;}[];const delegations = rows.map(@@ -119,11 +128,12 @@ export const agentVaultDelegationDALFactory = (db: TDbClient) => {username: subject.username!,email: subject.email,firstName: subject.firstName,- lastName: subject.lastName+ lastName: subject.lastName,+ addedAt: subject.addedAt})),groups: subjects.filter((subject) => subject.delegationId === row.id && subject.groupId && subject.groupName)- .map((subject) => ({ id: subject.groupId!, name: subject.groupName! })),+ .map((subject) => ({ id: subject.groupId!, name: subject.groupName!, addedAt: subject.addedAt })),createdAt: row.createdAt,updatedAt: row.updatedAt})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.tsindex bcd0a62ffa..da8352660a 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@@ -25,7 +25,7 @@ type TAgentVaultDelegationServiceFactoryDep = {TAgentVaultDelegationDALFactory,"upsertScope" | "findViews" | "delete" | "transaction">;- agentVaultDelegationSubjectDAL: Pick<TAgentVaultDelegationSubjectDALFactory, "delete" | "insertMany">;+ agentVaultDelegationSubjectDAL: Pick<TAgentVaultDelegationSubjectDALFactory, "find" | "delete" | "insertMany">;membershipDAL: Pick<TMembershipDALFactory, "find" | "findOne">;userGroupMembershipDAL: Pick<TUserGroupMembershipDALFactory, "find">;permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;@@ -168,16 +168,26 @@ export const agentVaultDelegationServiceFactory = ({const delegation = await agentVaultDelegationDAL.transaction(async (tx) => {const row = await agentVaultDelegationDAL.upsertScope({ projectId, identityId: machineIdentityId, scope }, tx);- // A write replaces the whole list, so a subject left out is no longer covered.- await agentVaultDelegationSubjectDAL.delete({ delegationId: row.id }, tx);- const subjects =- scope === AgentVaultDelegationScope.Selected- ? [- ...userIds.map((userId) => ({ delegationId: row.id, userId })),- ...groupIds.map((groupId) => ({ delegationId: row.id, groupId }))- ]- : [];- if (subjects.length) await agentVaultDelegationSubjectDAL.insertMany(subjects, tx);+ // A write replaces the whole list, so a subject left out is no longer covered. Rows that stay are kept rather+ // than rewritten, so each one's addedAt still says when it was added.+ const wantedUserIds = new Set(scope === AgentVaultDelegationScope.Selected ? userIds : []);+ const wantedGroupIds = new Set(scope === AgentVaultDelegationScope.Selected ? groupIds : []);+ const existing = await agentVaultDelegationSubjectDAL.find({ delegationId: row.id }, { tx });+ const stale = existing.filter((subject) =>+ subject.userId ? !wantedUserIds.has(subject.userId) : !wantedGroupIds.has(subject.groupId!)+ );+ if (stale.length) {+ await agentVaultDelegationSubjectDAL.delete({ $in: { id: stale.map((subject) => subject.id) } }, tx);+ }+ const keptUserIds = new Set(existing.map((subject) => subject.userId).filter(Boolean));+ const keptGroupIds = new Set(existing.map((subject) => subject.groupId).filter(Boolean));+ const added = [+ ...[...wantedUserIds].filter((id) => !keptUserIds.has(id)).map((userId) => ({ delegationId: row.id, userId })),+ ...[...wantedGroupIds]+ .filter((id) => !keptGroupIds.has(id))+ .map((groupId) => ({ delegationId: row.id, groupId }))+ ];+ if (added.length) await agentVaultDelegationSubjectDAL.insertMany(added, tx);const {delegations: [written]diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex 6f49e6cbb2..6f385a1d07 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -4777,6 +4777,7 @@ export const AGENT_VAULT = {lastName: "The last name of the user.",groupId: "The ID of the group.",groupName: "The name of the group.",+ addedAt: "When the user or group was added to the delegation.",limit: "The maximum number of delegations to return.",offset: "How many delegations to skip."}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 d20683e9f5..e2fcc323b2 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@@ -38,16 +38,12 @@ sequenceDiagramIn Agent Vault, go to **Access Control**, select the **Machine Identities** tab, and select the machine identity.</Step><Step>- In the **Delegation** section, select **Set Up Delegation**.+ In the **Delegation** section, select **Add Users or Groups**.</Step><Step>- Select which users the machine identity can act on behalf of:+ Pick the users and groups in **Users and Groups**, and select **Add**. A group covers every member of the group.- - **Selected Users and Groups**: the users you pick, and every member of the groups you pick- - **All Agent Vault Members**: every user in Agent Vault, including users added later- </Step>- <Step>- For **Selected Users and Groups**, pick the users and groups in **Users and Groups**. Then select **Save Delegation**.+ To cover every user in Agent Vault instead, including users added later, turn on **All Agent Vault Members** and select **Allow All Members**.</Step></Steps></Tab>@@ -67,7 +63,7 @@ sequenceDiagramYou can pick only users and groups that are members of Agent Vault. If a user is in Agent Vault only through a group, pick the group.-To change the delegation later, select **Edit Delegation** in the same section. To remove it, select **Remove**, type `remove`, and select **Remove Delegation**.+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.<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.diff --git a/frontend/src/components/agent-vault/DelegationDialog.tsx b/frontend/src/components/agent-vault/AddDelegationSubjectsDialog.tsxsimilarity index 57%rename from frontend/src/components/agent-vault/DelegationDialog.tsxrename to frontend/src/components/agent-vault/AddDelegationSubjectsDialog.tsxindex 9adeb0ce71..590b0ada57 100644--- a/frontend/src/components/agent-vault/DelegationDialog.tsx+++ b/frontend/src/components/agent-vault/AddDelegationSubjectsDialog.tsx@@ -1,7 +1,10 @@import { useEffect, useMemo, useState } from "react";+import { TriangleAlertIcon } from "lucide-react";import { createNotification } from "@app/components/notifications";import {+ Alert,+ AlertDescription,Button,Combobox,Dialog,@@ -15,8 +18,7 @@ import {FieldDescription,FieldLabel,FieldTitle,- RadioGroup,- RadioGroupItem+ Toggle} from "@app/components/v3";import { useDebounce } from "@app/hooks";import { useListAgentVaultMembers, useSetAgentVaultDelegation } from "@app/hooks/api/agentVault";@@ -34,23 +36,6 @@ type SubjectOption = {const PICKER_LIMIT = 50;-const userOption = (user: TAgentVaultDelegation["users"][number]): SubjectOption => {- const actor = { type: AgentVaultMemberType.User as const, ...user };- return {- type: AgentVaultMemberType.User,- id: user.id,- label: memberDisplayName(actor),- subtitle: memberSubtitle(actor)- };-};--const groupOption = (group: TAgentVaultDelegation["groups"][number]): SubjectOption => ({- type: AgentVaultMemberType.Group,- id: group.id,- label: group.name,- subtitle: MEMBER_KIND[AgentVaultMemberType.Group].label-});-type Props = {isOpen: boolean;onOpenChange: (isOpen: boolean) => void;@@ -59,7 +44,7 @@ type Props = {delegation: TAgentVaultDelegation | null;};-export const DelegationDialog = ({+export const AddDelegationSubjectsDialog = ({isOpen,onOpenChange,machineIdentityId,@@ -68,115 +53,135 @@ export const DelegationDialog = ({}: Props) => {const setDelegation = useSetAgentVaultDelegation();- const [scope, setScope] = useState(AgentVaultDelegationScope.Selected);+ const isCurrentlyAllMembers = delegation?.scope === AgentVaultDelegationScope.AllMembers;+ const [isAllMembers, setIsAllMembers] = useState(false);const [selected, setSelected] = useState<SubjectOption[]>([]);const [search, setSearch] = useState("");const [debouncedSearch] = useDebounce(search);useEffect(() => {if (!isOpen) return;- setScope(delegation?.scope ?? AgentVaultDelegationScope.Selected);- setSelected([- ...(delegation?.users ?? []).map(userOption),- ...(delegation?.groups ?? []).map(groupOption)- ]);+ setIsAllMembers(isCurrentlyAllMembers);+ setSelected([]);setSearch("");}, [isOpen]);// A subject has to be an Agent Vault member, so the picker lists members rather than the whole org.- const isPickerOpen = isOpen && scope === AgentVaultDelegationScope.Selected;+ const isPickerShown = isOpen && !isAllMembers;const memberSearch = { search: debouncedSearch.trim() || undefined, limit: PICKER_LIMIT };const { data: users, isFetching: isFetchingUsers } = useListAgentVaultMembers({ ...memberSearch, actorType: AgentVaultMemberType.User },- isPickerOpen+ isPickerShown);const { data: groups, isFetching: isFetchingGroups } = useListAgentVaultMembers({ ...memberSearch, actorType: AgentVaultMemberType.Group },- isPickerOpen+ isPickerShown);+ const listedUserIds = new Set(delegation?.users.map((user) => user.id));+ const listedGroupIds = new Set(delegation?.groups.map((group) => group.id));+ const listedCount = listedUserIds.size + listedGroupIds.size;+const options = useMemo<SubjectOption[]>(- () => [...(users?.members ?? []).map(userOption), ...(groups?.members ?? []).map(groupOption)],- [users, groups]+ () => [+ ...(users?.members ?? [])+ .filter((user) => !listedUserIds.has(user.id))+ .map((user) => ({+ type: AgentVaultMemberType.User as const,+ id: user.id,+ label: memberDisplayName(user),+ subtitle: memberSubtitle(user)+ })),+ ...(groups?.members ?? [])+ .filter((group) => !listedGroupIds.has(group.id))+ .map((group) => ({+ type: AgentVaultMemberType.Group as const,+ id: group.id,+ label: group.name,+ subtitle: MEMBER_KIND[AgentVaultMemberType.Group].label+ }))+ ],+ [users, groups, delegation]);const isListTruncated =(users?.totalCount ?? 0) > (users?.members.length ?? 0) ||(groups?.totalCount ?? 0) > (groups?.members.length ?? 0);+ const isUnchanged = isAllMembers ? isCurrentlyAllMembers : !selected.length;+const handleSave = async () => {try {- const isSelected = scope === AgentVaultDelegationScope.Selected;- await setDelegation.mutateAsync({- machineIdentityId,- scope,- userIds: isSelected- ? selected- .filter((option) => option.type === AgentVaultMemberType.User)- .map((option) => option.id)- : [],- groupIds: isSelected- ? selected- .filter((option) => option.type === AgentVaultMemberType.Group)- .map((option) => option.id)- : []- });- createNotification({- text: `Delegation for "${machineIdentityName}" saved`,- type: "success"- });+ if (isAllMembers) {+ await setDelegation.mutateAsync({+ machineIdentityId,+ scope: AgentVaultDelegationScope.AllMembers+ });+ createNotification({+ text: `"${machineIdentityName}" now acts on behalf of every Agent Vault member`,+ type: "success"+ });+ } else {+ const idsOf = (type: SubjectOption["type"]) =>+ selected.filter((option) => option.type === type).map((option) => option.id);+ await setDelegation.mutateAsync({+ machineIdentityId,+ scope: AgentVaultDelegationScope.Selected,+ userIds: [...listedUserIds, ...idsOf(AgentVaultMemberType.User)],+ groupIds: [...listedGroupIds, ...idsOf(AgentVaultMemberType.Group)]+ });+ createNotification({+ text:+ selected.length === 1+ ? `"${selected[0].label}" added to the delegation`+ : `${selected.length} users and groups added to the delegation`,+ type: "success"+ });+ }onOpenChange(false);} catch {// A failed request returns a 4xx that the global request handler surfaces as a toast}};+ const replacementNote = () => {+ if (isAllMembers && listedCount) {+ return `This replaces the ${listedCount} ${listedCount === 1 ? "user or group" : "users and groups"} listed.`;+ }+ if (!isAllMembers && isCurrentlyAllMembers) {+ return "This replaces All Agent Vault Members with the users and groups you pick.";+ }+ return null;+ };+ const note = replacementNote();+return (<Dialog open={isOpen} onOpenChange={onOpenChange}><DialogContent><DialogHeader>- <DialogTitle>{delegation ? "Edit Delegation" : "Set Up Delegation"}</DialogTitle>+ <DialogTitle>Add Users or Groups</DialogTitle><DialogDescription>- "{machineIdentityName}" can start sessions on behalf of these users. Each- session reaches only the user's access bundles and uses their personal values.+ "{machineIdentityName}" can start sessions on behalf of the users you add, and+ of every member of the groups you add.</DialogDescription></DialogHeader>- <RadioGroup- value={scope}- onValueChange={(value) => setScope(value as AgentVaultDelegationScope)}- >- <FieldLabel htmlFor="agent-vault-delegation-selected" variant="av">- <Field orientation="horizontal">- <FieldContent>- <FieldTitle>Selected Users and Groups</FieldTitle>- <FieldDescription>- The users you pick, and the members of the groups you pick.- </FieldDescription>- </FieldContent>- <RadioGroupItem- value={AgentVaultDelegationScope.Selected}- id="agent-vault-delegation-selected"- />- </Field>- </FieldLabel>- <FieldLabel htmlFor="agent-vault-delegation-all-members" variant="av">- <Field orientation="horizontal">- <FieldContent>- <FieldTitle>All Agent Vault Members</FieldTitle>- <FieldDescription>- Every user with access to Agent Vault, including users added later.- </FieldDescription>- </FieldContent>- <RadioGroupItem- value={AgentVaultDelegationScope.AllMembers}- id="agent-vault-delegation-all-members"- />- </Field>- </FieldLabel>- </RadioGroup>+ <Field orientation="horizontal" className="rounded-md border border-border p-4">+ <FieldContent>+ <FieldTitle>All Agent Vault Members</FieldTitle>+ <FieldDescription>+ Act on behalf of every user in Agent Vault, including users added later.+ </FieldDescription>+ </FieldContent>+ <Toggle+ id="agent-vault-delegation-all-members"+ variant="av"+ checked={isAllMembers}+ onCheckedChange={setIsAllMembers}+ />+ </Field>- {scope === AgentVaultDelegationScope.Selected && (+ {!isAllMembers && (<Field><FieldLabel htmlFor="agent-vault-delegation-subjects">Users and Groups</FieldLabel><FieldContent>@@ -194,8 +199,8 @@ export const DelegationDialog = ({searchAriaLabel="Search users and groups"emptyMessage={(inputValue) =>inputValue- ? "No Agent Vault users or groups match your search."- : "No users or groups are members of Agent Vault yet."+ ? "No Agent Vault users or groups that aren't already added match your search."+ : "Every Agent Vault user and group is already in the delegation."}clearAriaLabel="Clear all users and groups"modal@@ -227,20 +232,27 @@ export const DelegationDialog = ({<FieldDescription>{isListTruncated? "Search by name to find users and groups that are not listed."- : "Only members of Agent Vault are listed. A user who is in Agent Vault through a group is covered by picking the group."}+ : "Only members of Agent Vault are listed. A user who is in Agent Vault through a group is covered by adding the group."}</FieldDescription></FieldContent></Field>)}+ {note && (+ <Alert variant="warning">+ <TriangleAlertIcon />+ <AlertDescription>{note}</AlertDescription>+ </Alert>+ )}+<DialogFooter><Buttonvariant="av"- isDisabled={scope === AgentVaultDelegationScope.Selected && !selected.length}+ isDisabled={isUnchanged}isPending={setDelegation.isPending}onClick={async () => handleSave()}>- Save Delegation+ {isAllMembers ? "Allow All Members" : "Add"}</Button><Button variant="outline" onClick={() => onOpenChange(false)}>Canceldiff --git a/frontend/src/components/agent-vault/IdentityDelegationSection.tsx b/frontend/src/components/agent-vault/IdentityDelegationSection.tsxindex 812f96f610..5c505b2873 100644--- a/frontend/src/components/agent-vault/IdentityDelegationSection.tsx+++ b/frontend/src/components/agent-vault/IdentityDelegationSection.tsx@@ -1,9 +1,17 @@import { useState } from "react";-import { PencilIcon, PlusIcon, Trash2Icon } from "lucide-react";+import { format } from "date-fns";+import { MoreHorizontalIcon, Trash2Icon, UserPlusIcon, UsersRoundIcon } from "lucide-react";import { createNotification } from "@app/components/notifications";import {- Badge,+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,Button,Card,CardAction,@@ -11,31 +19,47 @@ import {CardDescription,CardHeader,CardTitle,- DeleteConfirmDialog,- Detail,- DetailGroup,- DetailLabel,- DetailValue,DocumentationLinkBadge,- Skeleton+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+ Empty,+ EmptyDescription,+ EmptyHeader,+ EmptyTitle,+ IconButton,+ Skeleton,+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow} from "@app/components/v3";import { useProjectPermission } from "@app/context";import {useDeleteAgentVaultDelegation,- useListAgentVaultDelegations+ useListAgentVaultDelegations,+ useSetAgentVaultDelegation} from "@app/hooks/api/agentVault";import { AgentVaultDelegationScope, AgentVaultMemberType } from "@app/hooks/api/agentVault/enums";+import { TAgentVaultActor } 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 { DelegationDialog } from "./DelegationDialog";-import { MEMBER_KIND, memberDisplayName } from "./MemberName";+import { AddDelegationSubjectsDialog } from "./AddDelegationSubjectsDialog";+import { memberDisplayName, MemberName } from "./MemberName";type Props = {machineIdentityId: string;machineIdentityName: string;};+type TSubjectRow = TAgentVaultActor & { addedAt: string };++type TPendingRemoval = { kind: "subject"; subject: TSubjectRow } | { kind: "all-members" };+// Only admins can read or change a delegation, so members don't see the section at all.export const IdentityDelegationSection = ({ machineIdentityId, machineIdentityName }: Props) => {const { hasProjectRole } = useProjectPermission();@@ -46,63 +70,162 @@ export const IdentityDelegationSection = ({ machineIdentityId, machineIdentityNaisAdmin);const delegation = delegations?.[0] ?? null;+ const setDelegation = useSetAgentVaultDelegation();const deleteDelegation = useDeleteAgentVaultDelegation();- const [isEditOpen, setIsEditOpen] = useState(false);- const [isRemoveOpen, setIsRemoveOpen] = useState(false);+ const [isAddOpen, setIsAddOpen] = useState(false);+ const [pendingRemoval, setPendingRemoval] = useState<TPendingRemoval | null>(null);if (!isAdmin) return null;- const handleRemove = async () => {+ const isAllMembers = delegation?.scope === AgentVaultDelegationScope.AllMembers;+ const subjects: TSubjectRow[] = [+ ...(delegation?.groups ?? []).map((group) => ({+ type: AgentVaultMemberType.Group as const,+ ...group+ })),+ ...(delegation?.users ?? []).map((user) => ({+ type: AgentVaultMemberType.User as const,+ ...user+ }))+ ];+ const isMutating = setDelegation.isPending || deleteDelegation.isPending;+ // A delegation to selected users names at least one, so taking out the last one removes the delegation.+ const removesDelegation = pendingRemoval?.kind === "all-members" || subjects.length === 1;++ const applyRemoval = async () => {+ if (!pendingRemoval) return;try {- await deleteDelegation.mutateAsync({ machineIdentityId });- createNotification({- text: `Delegation for "${machineIdentityName}" removed`,- type: "success"- });- setIsRemoveOpen(false);+ if (removesDelegation) {+ await deleteDelegation.mutateAsync({ machineIdentityId });+ createNotification({+ text: `Delegation for "${machineIdentityName}" removed`,+ type: "success"+ });+ } else if (pendingRemoval.kind === "subject") {+ const { subject } = pendingRemoval;+ const remaining = subjects.filter(+ (row) => !(row.type === subject.type && row.id === subject.id)+ );+ await setDelegation.mutateAsync({+ machineIdentityId,+ scope: AgentVaultDelegationScope.Selected,+ userIds: remaining+ .filter((row) => row.type === AgentVaultMemberType.User)+ .map((row) => row.id),+ groupIds: remaining+ .filter((row) => row.type === AgentVaultMemberType.Group)+ .map((row) => row.id)+ });+ createNotification({+ text: `"${memberDisplayName(subject)}" removed from the delegation`,+ type: "success"+ });+ }+ setPendingRemoval(null);} catch {// A failed request returns a 4xx that the global request handler surfaces as a toast}};- const UserIcon = MEMBER_KIND[AgentVaultMemberType.User].icon;- const GroupIcon = MEMBER_KIND[AgentVaultMemberType.Group].icon;+ const removalCopy = () => {+ if (!pendingRemoval) return { title: "", description: "" };+ if (pendingRemoval.kind === "all-members") {+ return {+ title: "Stop Acting on Behalf of All Members",+ description: `"${machineIdentityName}" can no longer start sessions on behalf of anyone until you add users or groups, and the sessions it started stop working at the next proxy poll.`+ };+ }+ const { subject } = pendingRemoval;+ const name = memberDisplayName(subject);+ const whose =+ subject.type === AgentVaultMemberType.Group ? `the members of "${name}"` : `"${name}"`;+ return {+ title: `Remove "${name}" From the Delegation`,+ description: `"${machineIdentityName}" can no longer start sessions on behalf of ${whose}, and the sessions it started for them stop working at the next proxy poll.${+ removesDelegation ? " This is the last user or group, so the delegation is removed." : ""+ }`+ };+ };+ const copy = removalCopy();++ const rowActions = (label: string, onRemove: () => void) => (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <IconButton variant="ghost" size="xs" aria-label={`Actions for ${label}`}>+ <MoreHorizontalIcon />+ </IconButton>+ </DropdownMenuTrigger>+ <DropdownMenuContent sideOffset={2} align="end">+ <DropdownMenuItem variant="danger" onClick={onRemove}>+ <Trash2Icon />+ Remove+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ );- const renderCoverage = () => {+ const renderList = () => {+ if (isPending) return <Skeleton className="h-16 w-full" />;if (!delegation) {return (- <p className="text-sm text-muted">- This machine identity can't start sessions on behalf of users.- </p>+ <Empty className="border">+ <EmptyHeader>+ <EmptyTitle>No users or groups yet</EmptyTitle>+ <EmptyDescription>+ Add the users and groups this machine identity can start sessions for.+ </EmptyDescription>+ </EmptyHeader>+ </Empty>);}return (- <DetailGroup>- <Detail>- <DetailLabel>Acts On Behalf Of</DetailLabel>- <DetailValue>- {delegation.scope === AgentVaultDelegationScope.AllMembers ? (- "Every Agent Vault member"- ) : (- <div className="flex flex-wrap gap-1.5">- {delegation.groups.map((group) => (- <Badge key={group.id} variant="neutral">- <GroupIcon />- {group.name}- </Badge>- ))}- {delegation.users.map((user) => (- <Badge key={user.id} variant="neutral">- <UserIcon />- {memberDisplayName({ type: AgentVaultMemberType.User, ...user })}- </Badge>- ))}- </div>- )}- </DetailValue>- </Detail>- </DetailGroup>+ <Table className="overflow-hidden rounded-md border border-border">+ <TableHeader>+ <TableRow>+ <TableHead>User or Group</TableHead>+ <TableHead>Added</TableHead>+ <TableHead variant="action" />+ </TableRow>+ </TableHeader>+ <TableBody>+ {isAllMembers ? (+ <TableRow>+ <TableCell>+ <div className="flex min-w-0 items-center gap-2.5">+ <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>+ </div>+ </div>+ </TableCell>+ <TableCell>{format(new Date(delegation.updatedAt), "MMM d, yyyy")}</TableCell>+ <TableCell variant="action">+ {rowActions("All Agent Vault Members", () =>+ setPendingRemoval({ kind: "all-members" })+ )}+ </TableCell>+ </TableRow>+ ) : (+ subjects.map((subject) => (+ <TableRow key={`${subject.type}:${subject.id}`}>+ <TableCell>+ <MemberName member={subject} />+ </TableCell>+ <TableCell>{format(new Date(subject.addedAt), "MMM d, yyyy")}</TableCell>+ <TableCell variant="action">+ {rowActions(memberDisplayName(subject), () =>+ setPendingRemoval({ kind: "subject", subject })+ )}+ </TableCell>+ </TableRow>+ ))+ )}+ </TableBody>+ </Table>);};@@ -114,51 +237,54 @@ export const IdentityDelegationSection = ({ machineIdentityId, machineIdentityNa<DocumentationLinkBadge href={AgentVaultDocsUrls.sessionsOnBehalfOfUsers} /></CardTitle><CardDescription>- Let this machine identity start sessions on behalf of users, with their access bundles and- personal values.+ The users this machine identity can start sessions on behalf of. Each session uses that+ user's access bundles and personal values.</CardDescription>{!isPending && (- <CardAction className="flex gap-2">- {delegation ? (- <>- <Button variant="outline" onClick={() => setIsEditOpen(true)}>- <PencilIcon />- Edit Delegation- </Button>- <Button variant="danger" onClick={() => setIsRemoveOpen(true)}>- <Trash2Icon />- Remove- </Button>- </>- ) : (- <Button variant="av" onClick={() => setIsEditOpen(true)}>- <PlusIcon />- Set Up Delegation- </Button>- )}+ <CardAction>+ <Button variant="av" onClick={() => setIsAddOpen(true)}>+ <UserPlusIcon />+ Add Users or Groups+ </Button></CardAction>)}</CardHeader>- <CardContent>{isPending ? <Skeleton className="h-4 w-1/2" /> : renderCoverage()}</CardContent>+ <CardContent>{renderList()}</CardContent>- <DelegationDialog- isOpen={isEditOpen}- onOpenChange={setIsEditOpen}+ <AddDelegationSubjectsDialog+ isOpen={isAddOpen}+ onOpenChange={setIsAddOpen}machineIdentityId={machineIdentityId}machineIdentityName={machineIdentityName}delegation={delegation}/>- <DeleteConfirmDialog- isOpen={isRemoveOpen}- onOpenChange={setIsRemoveOpen}- title={`Remove Delegation for "${machineIdentityName}"`}- description="It can no longer start sessions on behalf of users, and the sessions it already started on their behalf stop working."- confirmKey="remove"- confirmLabel="Remove Delegation"- isPending={deleteDelegation.isPending}- onConfirm={handleRemove}- />+ <AlertDialog+ open={Boolean(pendingRemoval)}+ onOpenChange={(isOpen) => {+ if (!isOpen && !isMutating) setPendingRemoval(null);+ }}+ >+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>{copy.title}</AlertDialogTitle>+ <AlertDialogDescription>{copy.description}</AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel isDisabled={isMutating}>Cancel</AlertDialogCancel>+ <AlertDialogAction+ variant="danger"+ isPending={isMutating}+ onClick={async (event) => {+ event.preventDefault();+ await applyRemoval();+ }}+ >+ Remove+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog></Card>);};diff --git a/frontend/src/components/agent-vault/MemberName.tsx b/frontend/src/components/agent-vault/MemberName.tsxindex c7bdf983f5..d6618657ba 100644--- a/frontend/src/components/agent-vault/MemberName.tsx+++ b/frontend/src/components/agent-vault/MemberName.tsx@@ -1,11 +1,7 @@import { BotIcon, UserIcon, UsersIcon } from "lucide-react";import { AgentVaultMemberType } from "@app/hooks/api/agentVault/enums";-import {- TAgentVaultActor,- TAgentVaultMember,- TAgentVaultSessionActor-} from "@app/hooks/api/agentVault/types";+import { TAgentVaultActor, TAgentVaultSessionActor } from "@app/hooks/api/agentVault/types";export const MEMBER_KIND: Record<AgentVaultMemberType, { label: string; icon: typeof UserIcon }> = {[AgentVaultMemberType.User]: { label: "User", icon: UserIcon },@@ -25,7 +21,7 @@ export const memberSubtitle = (actor: TAgentVaultActor | TAgentVaultSessionActorreturn actor.email || actor.username;};-export const MemberName = ({ member }: { member: TAgentVaultMember }) => {+export const MemberName = ({ member }: { member: TAgentVaultActor }) => {const { label, icon: Icon } = MEMBER_KIND[member.type];return (diff --git a/frontend/src/hooks/api/agentVault/types.ts b/frontend/src/hooks/api/agentVault/types.tsindex 65d3f34c42..05549024b4 100644--- a/frontend/src/hooks/api/agentVault/types.ts+++ b/frontend/src/hooks/api/agentVault/types.ts@@ -249,8 +249,12 @@ export type TAgentVaultSession = {export type TAgentVaultDelegation = {machineIdentity: { id: string; name: string };scope: AgentVaultDelegationScope;- users: Omit<Extract<TAgentVaultActor, { type: AgentVaultMemberType.User }>, "type">[];- groups: Omit<Extract<TAgentVaultActor, { type: AgentVaultMemberType.Group }>, "type">[];+ users: (Omit<Extract<TAgentVaultActor, { type: AgentVaultMemberType.User }>, "type"> & {+ addedAt: string;+ })[];+ groups: (Omit<Extract<TAgentVaultActor, { type: AgentVaultMemberType.Group }>, "type"> & {+ addedAt: string;+ })[];createdAt: string;updatedAt: string;};