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): method and path rules, custom headers, and substitutions (#8130)
Saif Ur Rahman24875b15965d
diff --git a/backend/e2e-test/routes/v1/agent-vault.spec.ts b/backend/e2e-test/routes/v1/agent-vault.spec.tsindex 5c975ed9fb..91226ac093 100644--- a/backend/e2e-test/routes/v1/agent-vault.spec.ts+++ b/backend/e2e-test/routes/v1/agent-vault.spec.ts@@ -3,6 +3,8 @@ import crypto from "node:crypto";import { AccessScope, ActionProjectType, OrgMembershipRole, ProjectMembershipRole, ProjectType } from "@app/db/schemas";import { seedData1 } from "@app/db/seed-data";import { agentVaultAccessBundleDALFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-dal";+import { agentVaultServiceCustomHeaderDALFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-service-custom-header-dal";+import { agentVaultServiceSubstitutionDALFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-service-substitution-dal";import { agentVaultProxyDALFactory } from "@app/ee/services/agent-vault-proxy/agent-vault-proxy-dal";import { agentVaultProxyServiceFactory } from "@app/ee/services/agent-vault-proxy/agent-vault-proxy-service";import { agentVaultResolveDALFactory } from "@app/ee/services/agent-vault-proxy/agent-vault-resolve-dal";@@ -221,13 +223,71 @@ describe("Agent Vault V1 Router", async () => {test("the creator is granted the access bundle they just made", async () => {const bundle = await createAccessBundle("creator-grant");- const res = await inject("GET", `/api/v1/agent-vault/access-bundles/${bundle.id}`);- const { accessBundle } = JSON.parse(res.payload) as {- accessBundle: { members: { userId: string | null; identityId: string | null }[] };+ const res = await inject("GET", `/api/v1/agent-vault/access-bundles/${bundle.id}/members`);+ const { members, totalCount } = JSON.parse(res.payload) as {+ members: { actor: { type: string; id: string } }[];+ totalCount: number;+ };++ expect(totalCount).toBe(1);+ expect(members).toHaveLength(1);+ expect(members[0].actor).toMatchObject({ type: "user", id: seedData1.id });++ // The detail response no longer carries a members array, so there is one source for the list.+ const detail = await inject("GET", `/api/v1/agent-vault/access-bundles/${bundle.id}`);+ expect(JSON.parse(detail.payload).accessBundle).not.toHaveProperty("members");+ });++ test("the bundle list sorts and pages on the server, and the count follows the search", async () => {+ const names = ["zz-page-c", "zz-page-a", "zz-page-b"];+ for await (const name of names) await createAccessBundle(name);++ const list = async (query: string) => {+ const res = await inject("GET", `/api/v1/agent-vault/access-bundles?${query}`);+ expect(res.statusCode).toBe(200);+ return JSON.parse(res.payload) as { accessBundles: { id: string; name: string }[]; totalCount: number };};- expect(accessBundle.members).toHaveLength(1);- expect(accessBundle.members[0].userId).toBe(seedData1.id);+ const searched = await list("search=zz-page&orderBy=name&orderDirection=asc&limit=100");+ expect(searched.totalCount).toBe(3);+ expect(searched.accessBundles.map((bundle) => bundle.name)).toEqual(["zz-page-a", "zz-page-b", "zz-page-c"]);++ const descending = await list("search=zz-page&orderBy=name&orderDirection=desc&limit=100");+ expect(descending.accessBundles.map((bundle) => bundle.name)).toEqual(["zz-page-c", "zz-page-b", "zz-page-a"]);++ // The sort has to happen before the page is cut, or a page is sorted rather than the set.+ const firstPage = await list("search=zz-page&orderBy=name&orderDirection=asc&limit=1&offset=0");+ expect(firstPage.totalCount).toBe(3);+ expect(firstPage.accessBundles.map((bundle) => bundle.name)).toEqual(["zz-page-a"]);++ const lastPage = await list("search=zz-page&orderBy=name&orderDirection=asc&limit=1&offset=2");+ expect(lastPage.accessBundles.map((bundle) => bundle.name)).toEqual(["zz-page-c"]);++ expect((await inject("GET", "/api/v1/agent-vault/access-bundles?orderBy=nonsense")).statusCode).toBe(422);+ expect((await inject("GET", "/api/v1/agent-vault/access-bundles?limit=101")).statusCode).toBe(422);+ });++ test("updatedAt moves when a bundle changes, and matches createdAt until it does", async () => {+ const bundle = await createAccessBundle("stamped");++ const read = async () =>+ (+ JSON.parse((await inject("GET", `/api/v1/agent-vault/access-bundles/${bundle.id}`)).payload) as {+ accessBundle: { createdAt: string; updatedAt: string };+ }+ ).accessBundle;++ const fresh = await read();+ expect(fresh.updatedAt).toBe(fresh.createdAt);++ expect(+ (await inject("PATCH", `/api/v1/agent-vault/access-bundles/${bundle.id}`, { description: "touched" }))+ .statusCode+ ).toBe(200);++ const touched = await read();+ expect(new Date(touched.updatedAt).getTime()).toBeGreaterThan(new Date(fresh.updatedAt).getTime());+ expect(touched.createdAt).toBe(fresh.createdAt);});test("two concurrent creates for the same host do not both get in", async () => {@@ -409,65 +469,367 @@ describe("Agent Vault V1 Router", async () => {});expect(res.statusCode).toBe(422);});- });- describe("product membership", async () => {- const memberships = "/api/v1/agent-vault/memberships";+ test("methods and path prefixes default to unrestricted, and null clears them again", async () => {+ const bundle = await createAccessBundle("service-policy");- test("a machine identity can be given Agent Vault, have its role changed, and lose it again", async () => {- const identity = await createOrgIdentity(`av-membership-${Date.now()}`);+ const created = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {+ name: "github",+ hostPattern: "api.github.com",+ allowedMethods: ["GET", "HEAD"],+ allowedPathPrefixes: ["/repos/", "/user"],+ credential: { type: "passthrough" }+ });+ expect(created.statusCode).toBe(200);+ const { service } = JSON.parse(created.payload) as {+ service: { id: string; allowedMethods: string[]; allowedPathPrefixes: string[] };+ };+ expect(service.allowedMethods).toEqual(["GET", "HEAD"]);+ expect(service.allowedPathPrefixes).toEqual(["/repos", "/user"]);- const added = await inject("POST", `${memberships}/identities/${identity.id}`, { role: "member" });- expect(added.statusCode).toBe(200);+ const url = `/api/v1/agent-vault/access-bundles/${bundle.id}/services/${service.id}`;++ const renamed = await inject("PATCH", url, { name: "github-read" });+ expect(JSON.parse(renamed.payload).service.allowedMethods).toEqual(["GET", "HEAD"]);- const listed = await inject("GET", `${memberships}/identities`);- const { members } = JSON.parse(listed.payload) as {- members: { identityId: string; role: string; name: string }[];+ const cleared = await inject("PATCH", url, { allowedMethods: null, allowedPathPrefixes: null });+ expect(cleared.statusCode).toBe(200);+ expect(JSON.parse(cleared.payload).service.allowedMethods).toBeNull();+ expect(JSON.parse(cleared.payload).service.allowedPathPrefixes).toBeNull();++ expect((await inject("PATCH", url, { allowedMethods: [] })).statusCode).toBe(422);+ expect((await inject("PATCH", url, { allowedPathPrefixes: [] })).statusCode).toBe(422);+ });++ test("a path prefix that would need normalising to judge is rejected", async () => {+ const bundle = await createAccessBundle("path-grammar");+ const reject = async (prefix: string) =>+ (+ await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {+ name: `svc-${Math.random().toString(36).slice(2, 8)}`,+ hostPattern: `h${Math.random().toString(36).slice(2, 8)}.example.com`,+ allowedPathPrefixes: [prefix],+ credential: { type: "passthrough" }+ })+ ).statusCode;++ for (const prefix of [+ "repos",+ "/repos/../admin",+ "/repos//x",+ "/repos%2fx",+ "/repos;x",+ "/repos\\x",+ "/repos,x"+ ]) {+ // eslint-disable-next-line no-await-in-loop+ expect(await reject(prefix)).toBe(422);+ }+ });++ test("headers and substitutions round-trip without ever echoing a value", async () => {+ const bundle = await createAccessBundle("transformations");++ const created = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {+ name: "github",+ hostPattern: "api.github.com",+ credential: { type: "passthrough" },+ customHeaders: [{ name: "X-Org-Id", value: "org_secret_value" }],+ substitutions: [{ placeholder: "__GITHUB_PAT__", surfaces: ["header", "path"], value: "ghp_real_value" }]+ });+ expect(created.statusCode).toBe(200);+ expect(created.payload).not.toContain("org_secret_value");+ expect(created.payload).not.toContain("ghp_real_value");++ const { service } = JSON.parse(created.payload) as {+ service: {+ id: string;+ customHeaders: { id: string; name: string; prefix: string }[];+ substitutions: { id: string; placeholder: string; surfaces: string[] }[];+ };};- const row = members.find((m) => m.identityId === identity.id);- expect(row?.role).toBe("member");- expect(row?.name).toBeTruthy();+ expect(service.customHeaders).toHaveLength(1);+ expect(service.customHeaders[0].name).toBe("X-Org-Id");+ expect(service.substitutions[0].surfaces).toEqual(["header", "path"]);- const promoted = await inject("PATCH", `${memberships}/identities/${identity.id}`, { role: "admin" });- expect(promoted.statusCode).toBe(200);- expect(JSON.parse(promoted.payload).role).toBe("admin");+ const detail = await inject("GET", `/api/v1/agent-vault/access-bundles/${bundle.id}`);+ expect(detail.payload).not.toContain("org_secret_value");+ expect(detail.payload).not.toContain("ghp_real_value");++ const customHeaderRow = await testDb("agent_vault_service_custom_headers")+ .where({ serviceId: service.id })+ .first();+ expect(customHeaderRow.encryptedValue.toString("utf-8")).not.toContain("org_secret_value");- const removed = await inject("DELETE", `${memberships}/identities/${identity.id}`);+ const removed = await inject("DELETE", `/api/v1/agent-vault/access-bundles/${bundle.id}/services/${service.id}`);expect(removed.statusCode).toBe(200);+ expect(removed.payload).not.toContain("org_secret_value");+ expect(JSON.parse(removed.payload).service.customHeaders).toHaveLength(1);+ expect(await testDb("agent_vault_service_custom_headers").where({ serviceId: service.id })).toHaveLength(0);+ });++ test("a row keeps its stored value whether it is named by id or by name", async () => {+ const bundle = await createAccessBundle("keep-stored-value");- const after = JSON.parse((await inject("GET", `${memberships}/identities`)).payload) as {- members: { identityId: string }[];+ const created = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {+ name: "github",+ hostPattern: "api.github.com",+ credential: { type: "passthrough" },+ customHeaders: [{ name: "X-Org-Id", value: "first_value" }]+ });+ const { service } = JSON.parse(created.payload) as {+ service: { id: string; customHeaders: { id: string }[] };};- expect(after.members.some((m) => m.identityId === identity.id)).toBe(false);+ const url = `/api/v1/agent-vault/access-bundles/${bundle.id}/services/${service.id}`;+ const customHeaderId = service.customHeaders[0].id;+ const sealed = async () =>+ (await testDb("agent_vault_service_custom_headers").where({ serviceId: service.id }).first())+ .encryptedValue as Buffer;+ const before = await sealed();- await deleteOrgIdentity(identity.id);+ const renamed = await inject("PATCH", url, {+ customHeaders: [{ id: customHeaderId, name: "X-Organization-Id" }]+ });+ expect(renamed.statusCode).toBe(200);+ expect(JSON.parse(renamed.payload).service.customHeaders[0].id).toBe(customHeaderId);+ expect(JSON.parse(renamed.payload).service.customHeaders[0].name).toBe("X-Organization-Id");+ expect((await sealed()).equals(before)).toBe(true);++ const byName = await inject("PATCH", url, { customHeaders: [{ name: "X-Organization-Id", prefix: "Token" }] });+ expect(byName.statusCode).toBe(200);+ expect(JSON.parse(byName.payload).service.customHeaders[0].id).toBe(customHeaderId);+ expect(JSON.parse(byName.payload).service.customHeaders[0].prefix).toBe("Token");+ expect((await sealed()).equals(before)).toBe(true);++ const newRowNoValue = await inject("PATCH", url, {+ customHeaders: [{ name: "X-Organization-Id" }, { name: "X-New" }]+ });+ expect(newRowNoValue.statusCode).toBe(400);++ const duplicateId = await inject("PATCH", url, {+ customHeaders: [+ { id: customHeaderId, name: "X-A", value: "a" },+ { id: customHeaderId, name: "X-B", value: "b" }+ ]+ });+ expect(duplicateId.statusCode).toBe(400);++ const emptied = await inject("PATCH", url, { customHeaders: [] });+ expect(emptied.statusCode).toBe(200);+ expect(JSON.parse(emptied.payload).service.customHeaders).toHaveLength(0);+ expect(await testDb("agent_vault_service_custom_headers").where({ serviceId: service.id })).toHaveLength(0);+ });++ test("a custom header cannot shadow the credential's own header, from either side", async () => {+ const bundle = await createAccessBundle("header-shadowing");++ const clash = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {+ name: "clash",+ hostPattern: "api.clash.example.com",+ credential: { type: "bearer", headerName: "X-Api-Key", headerPrefix: "", value: "k" },+ customHeaders: [{ name: "x-api-key", value: "shadow" }]+ });+ expect(clash.statusCode).toBe(400);+ expect(JSON.parse(clash.payload).message).toContain("X-Api-Key");++ const created = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {+ name: "github",+ hostPattern: "api.github.com",+ credential: { type: "bearer", headerName: "X-Api-Key", headerPrefix: "", value: "k" },+ customHeaders: [{ name: "X-Org-Id", value: "org" }]+ });+ expect(created.statusCode).toBe(200);+ const { service } = JSON.parse(created.payload) as { service: { id: string } };+ const url = `/api/v1/agent-vault/access-bundles/${bundle.id}/services/${service.id}`;++ const headersOnly = await inject("PATCH", url, { customHeaders: [{ name: "X-Api-Key", value: "shadow" }] });+ expect(headersOnly.statusCode).toBe(400);++ const credentialOnly = await inject("PATCH", url, {+ credential: { type: "bearer", headerName: "X-Org-Id" }+ });+ expect(credentialOnly.statusCode).toBe(400);+ expect(JSON.parse(credentialOnly.payload).message).toContain("X-Org-Id");++ const basicClash = await inject("PATCH", url, {+ credential: { type: "basic", username: "u", password: "p" },+ customHeaders: [{ name: "Authorization", value: "shadow" }]+ });+ expect(basicClash.statusCode).toBe(400);+ });++ test("a header the proxy controls is refused, from either side", async () => {+ const bundle = await createAccessBundle("reserved-headers");+ const res = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {+ name: "reserved",+ hostPattern: "api.reserved.example.com",+ credential: { type: "passthrough" },+ customHeaders: [{ name: "Host", value: "evil.example.com" }]+ });+ expect(res.statusCode).toBe(422);++ const asCredential = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {+ name: "reserved-credential",+ hostPattern: "api.reserved-credential.example.com",+ credential: { type: "bearer", headerName: "Content-Length", value: "t" }+ });+ expect(asCredential.statusCode).toBe(422);});+ });- test("the user and group lists carry the names the Access Control page shows", async () => {- const users = JSON.parse((await inject("GET", `${memberships}/users`)).payload) as {- members: { userId: string; role: string; email: string | null; isOrgMembershipPending: boolean }[];+ describe("product membership", async () => {+ const membersUrl = "/api/v1/agent-vault/members";++ type TListedMember = {+ id: string;+ role: string;+ isActive: boolean;+ createdAt: string;+ actor: Record<string, unknown> & { type: string; id: string };+ };++ const listMembers = async (query = "") => {+ const res = await inject("GET", `${membersUrl}${query ? `?${query}` : ""}`);+ expect(res.statusCode).toBe(200);+ return JSON.parse(res.payload) as { members: TListedMember[]; totalCount: number };+ };++ test("one list answers for all three actor kinds, and each arm carries what its table renders", async () => {+ const { projectId } = JSON.parse((await inject("GET", "/api/v1/agent-vault/project")).payload) as {+ projectId: string;};- const self = users.members.find((m) => m.userId === seedData1.id);- expect(self?.role).toBe("admin");- expect(self?.email).toBe(seedData1.email);- expect(self?.isOrgMembershipPending).toBe(false);+ const identity = await createOrgIdentity(`av-merged-list-${Date.now()}`);+ const group = await createProjectGroup(projectId, "av-merged-list-group", ProjectMembershipRole.Member);+ try {+ expect(+ (await inject("POST", membersUrl, { machineIdentityIds: [identity.id], role: "member" })).statusCode+ ).toBe(200);++ const { members, totalCount } = await listMembers();+ expect(totalCount).toBe(members.length);++ const byType = Object.fromEntries(members.map((member) => [member.actor.type, member]));+ expect(Object.keys(byType).sort()).toEqual(["group", "machineIdentity", "user"]);++ expect(byType.user.actor).toMatchObject({ id: seedData1.id, username: expect.any(String) });+ expect(byType.user.actor.isOrgMembershipPending).toBe(false);+ expect(byType.user.role).toBe("admin");+ expect(byType.user.isActive).toBe(true);++ expect(byType.group.actor).toMatchObject({ id: group.id, name: "av-merged-list-group" });++ // An organization-owned identity can be detached; one Agent Vault created can only be deleted,+ // and the table needs to know which before it offers a button.+ expect(byType.machineIdentity.actor).toMatchObject({ id: identity.id, isManagedByAgentVault: false });+ expect(byType.machineIdentity.actor.orgId).toBe(seedData1.organization.id);++ members.forEach((member) => {+ expect(member).not.toHaveProperty("membershipId");+ expect(member).not.toHaveProperty("userId");+ expect(member).not.toHaveProperty("identityId");+ expect(member).not.toHaveProperty("groupId");+ });+ } finally {+ await group.cleanup();+ await deleteOrgIdentity(identity.id);+ }+ });++ test("the list filters, searches and pages on the server, and the count follows the filter", async () => {const { projectId } = JSON.parse((await inject("GET", "/api/v1/agent-vault/project")).payload) as {projectId: string;};- const group = await createProjectGroup(projectId, "av-list-groups", ProjectMembershipRole.Member);+ const identity = await createOrgIdentity(`av-paging-zzz-${Date.now()}`);+ const group = await createProjectGroup(projectId, "av-paging-group", ProjectMembershipRole.Member);+try {- const groups = JSON.parse((await inject("GET", `${memberships}/groups`)).payload) as {- members: { groupId: string; role: string; name: string }[];- };- const row = groups.members.find((m) => m.groupId === group.id);- expect(row?.role).toBe("member");- expect(row?.name).toBe("av-list-groups");+ expect(+ (await inject("POST", membersUrl, { machineIdentityIds: [identity.id], role: "member" })).statusCode+ ).toBe(200);++ const all = await listMembers();+ expect(all.totalCount).toBeGreaterThanOrEqual(3);++ const identities = await listMembers("actorType=machineIdentity");+ expect(identities.members.every((member) => member.actor.type === "machineIdentity")).toBe(true);+ expect(identities.totalCount).toBe(identities.members.length);+ expect(identities.totalCount).toBeLessThan(all.totalCount);++ // The count describes the filtered set, not the whole one, or the pager promises pages it will+ // not serve.+ const searched = await listMembers("search=av-paging-group");+ expect(searched.totalCount).toBe(1);+ expect(searched.members[0].actor.id).toBe(group.id);++ // A user matches on their full name even though no column holds it.+ const byFullName = await listMembers(`search=${encodeURIComponent(seedData1.email)}`);+ expect(byFullName.members.some((member) => member.actor.id === seedData1.id)).toBe(true);++ // Walking the pages one row at a time reaches every member exactly once, which is what the+ // membership-id tiebreak buys on rows that share a name or a createdAt.+ const walked: string[] = [];+ for (let offset = 0; offset < all.totalCount; offset += 1) {+ // eslint-disable-next-line no-await-in-loop+ const page = await listMembers(`limit=1&offset=${offset}`);+ expect(page.members).toHaveLength(1);+ expect(page.totalCount).toBe(all.totalCount);+ walked.push(page.members[0].id);+ }+ expect(new Set(walked).size).toBe(all.totalCount);+ expect(walked.sort()).toEqual(all.members.map((member) => member.id).sort());++ expect((await inject("GET", `${membersUrl}?limit=0`)).statusCode).toBe(422);+ expect((await inject("GET", `${membersUrl}?limit=101`)).statusCode).toBe(422);+ expect((await inject("GET", `${membersUrl}?offset=10001`)).statusCode).toBe(422);+ expect((await inject("GET", `${membersUrl}?actorType=nonsense`)).statusCode).toBe(422);} finally {await group.cleanup();+ await deleteOrgIdentity(identity.id);}});+ test("a machine identity can be given Agent Vault, have its role changed, and lose it again", async () => {+ const identity = await createOrgIdentity(`av-membership-${Date.now()}`);++ const added = await inject("POST", membersUrl, { machineIdentityIds: [identity.id], role: "member" });+ expect(added.statusCode).toBe(200);+ expect(JSON.parse(added.payload).members[0].actor).toMatchObject({+ type: "machineIdentity",+ id: identity.id+ });++ const listed = await listMembers("actorType=machineIdentity");+ const row = listed.members.find((member) => member.actor.id === identity.id);+ expect(row?.role).toBe("member");+ expect(row?.actor.name).toBeTruthy();++ const promoted = await inject("PATCH", `${membersUrl}/machine-identities/${identity.id}`, { role: "admin" });+ expect(promoted.statusCode).toBe(200);+ expect(JSON.parse(promoted.payload).member.role).toBe("admin");++ const removed = await inject("POST", `${membersUrl}/revoke`, { machineIdentityIds: [identity.id] });+ expect(removed.statusCode).toBe(200);+ expect(JSON.parse(removed.payload)).toMatchObject({+ members: [{ actor: { type: "machineIdentity", id: identity.id } }],+ skipped: []+ });++ // A second revoke has nothing to remove, so it reports the actor as skipped rather than failing:+ // that is what makes the call safe to retry.+ const again = await inject("POST", `${membersUrl}/revoke`, { machineIdentityIds: [identity.id] });+ expect(again.statusCode).toBe(200);+ expect(JSON.parse(again.payload)).toMatchObject({+ members: [],+ skipped: [{ type: "machineIdentity", id: identity.id, identifier: identity.id }]+ });++ const after = await listMembers("actorType=machineIdentity");+ expect(after.members.some((member) => member.actor.id === identity.id)).toBe(false);++ await deleteOrgIdentity(identity.id);+ });+test("removing a user from the organization takes their grants too", async () => {const bundle = await createAccessBundle("org-removal-reap");const { projectId } = JSON.parse((await inject("GET", "/api/v1/agent-vault/project")).payload) as {@@ -521,39 +883,214 @@ describe("Agent Vault V1 Router", async () => {const identity = await createOrgIdentity(`av-reap-${Date.now()}`);- expect((await inject("POST", `${memberships}/identities/${identity.id}`, { role: "member" })).statusCode).toBe(+ expect((await inject("POST", membersUrl, { machineIdentityIds: [identity.id], role: "member" })).statusCode).toBe(200);expect((await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/members`, {- identityIds: [identity.id]+ machineIdentityIds: [identity.id]})).statusCode).toBe(200);expect(await grantRows(bundle.id, { actorIdentityId: identity.id })).toHaveLength(1);- expect((await inject("DELETE", `${memberships}/identities/${identity.id}`)).statusCode).toBe(200);+ expect((await inject("POST", `${membersUrl}/revoke`, { machineIdentityIds: [identity.id] })).statusCode).toBe(+ 200+ );expect(await grantRows(bundle.id, { actorIdentityId: identity.id })).toHaveLength(0);await deleteOrgIdentity(identity.id);});+ // Each refusal below asserts the rows as well as the status: a 400 that applied half the batch would+ // pass a status-only check.+ test("a member can be added by email alone, and the cap counts emails", async () => {+ // The add body is one object, not an intersection: zod parses each side of an intersection on its+ // own, so an id-side object would strip emails before the refines ran, 422ing this exact call.+ const byEmail = await inject("POST", membersUrl, { emails: [seedData1.email], role: "member" });+ expect(byEmail.statusCode).toBe(200);+ // The seed admin is already a member, and skipped echoes the identifier the caller sent -- the+ // email, not the uuid it resolved to.+ expect(JSON.parse(byEmail.payload)).toMatchObject({+ members: [],+ skipped: [{ type: "user", id: seedData1.id, identifier: seedData1.email }]+ });++ const tooMany = await inject("POST", membersUrl, {+ userIds: ["00000000-0000-0000-0000-000000000001"],+ emails: Array.from({ length: 100 }, (_, i) => `av-cap-${i}@example.com`),+ role: "member"+ });+ expect(tooMany.statusCode).toBe(422);+ });++ test("a deactivated member is refused even while one of their groups is still active", async () => {+ const suffix = Date.now();+ const [user] = (await testDb("users")+ .insert({ username: `av-suspended-${suffix}@example.com`, isAccepted: true, isGhost: false })+ .returning("*")) as { id: string }[];+ const [group] = (await testDb("groups")+ .insert({ orgId: seedData1.organization.id, name: `av-active-${suffix}`, slug: `av-active-${suffix}` })+ .returning("*")) as { id: string }[];++ try {+ await testDb("memberships").insert({+ scope: AccessScope.Organization,+ scopeOrgId: seedData1.organization.id,+ actorUserId: user.id,+ status: "accepted",+ isActive: false+ });+ await testDb("memberships").insert({+ scope: AccessScope.Organization,+ scopeOrgId: seedData1.organization.id,+ actorGroupId: group.id,+ isActive: true+ });+ await testDb("user_group_membership").insert({ groupId: group.id, userId: user.id });++ // Their own membership is the authoritative one: deactivation suspends the person even while a+ // group they belong to stays active, so the group row must not vouch for them.+ const refused = await inject("POST", membersUrl, { userIds: [user.id], role: "member" });+ expect(refused.statusCode).toBe(400);+ expect(JSON.parse(refused.payload).message).toContain("not an active member");+ } finally {+ await testDb("user_group_membership").where({ userId: user.id }).delete();+ await testDb("memberships").where({ actorUserId: user.id }).delete();+ await testDb("memberships").where({ actorGroupId: group.id }).delete();+ await testDb("groups").where({ id: group.id }).delete();+ await testDb("users").where({ id: user.id }).delete();+ }+ });++ test("a batch that would leave no admin is refused whole, and nobody is removed", async () => {+ const projectId = await getProjectId();+ const one = await createOrgIdentity(`av-batch-admin-a-${Date.now()}`);+ const two = await createOrgIdentity(`av-batch-admin-b-${Date.now()}`);++ try {+ expect(+ (+ await inject("POST", membersUrl, {+ machineIdentityIds: [one.id, two.id],+ role: ProjectMembershipRole.Admin+ })+ ).statusCode+ ).toBe(200);++ const adminCount = async () =>+ (+ (await testDb("membership_roles")+ .join("memberships", "memberships.id", "membership_roles.membershipId")+ .where({ scope: AccessScope.Project, scopeProjectId: projectId, role: ProjectMembershipRole.Admin })+ .select("membership_roles.id")) as unknown[]+ ).length;++ const before = await adminCount();+ expect(before).toBe(3);++ // Revoking each of these on its own would pass the guard, because the other two are still+ // standing. Naming all three in one call is what the batch check exists for.+ const refused = await inject("POST", `${membersUrl}/revoke`, {+ userIds: [seedData1.id],+ machineIdentityIds: [one.id, two.id]+ });+ expect(refused.statusCode).toBe(403);++ // It refuses on the self check before it reaches the admin count, so take the caller out and the+ // batch still cannot go through.+ const withoutSelf = await inject("POST", `${membersUrl}/revoke`, {+ machineIdentityIds: [one.id, two.id]+ });+ expect(withoutSelf.statusCode).toBe(200);+ expect(await adminCount()).toBe(1);+ } finally {+ await deleteOrgIdentity(one.id);+ await deleteOrgIdentity(two.id);+ }+ });++ test("naming yourself anywhere in a revoke refuses the whole call", async () => {+ const identity = await createOrgIdentity(`av-batch-self-${Date.now()}`);++ try {+ expect(+ (await inject("POST", membersUrl, { machineIdentityIds: [identity.id], role: "member" })).statusCode+ ).toBe(200);++ const refused = await inject("POST", `${membersUrl}/revoke`, {+ userIds: [seedData1.id],+ machineIdentityIds: [identity.id]+ });+ expect(refused.statusCode).toBe(403);+ expect(JSON.parse(refused.payload).message).toContain("your own access");++ // The other actor named in the same call still has access.+ const listed = await listMembers("actorType=machineIdentity");+ expect(listed.members.some((member) => member.actor.id === identity.id)).toBe(true);+ } finally {+ await inject("POST", `${membersUrl}/revoke`, { machineIdentityIds: [identity.id] });+ await deleteOrgIdentity(identity.id);+ }+ });++ test("one add names every actor kind at once, dedupes a repeat, and skips whoever already had access", async () => {+ const projectId = await getProjectId();+ const identity = await createOrgIdentity(`av-batch-add-${Date.now()}`);+ const group = await createProjectGroup(projectId, "av-batch-add-group", ProjectMembershipRole.Member);++ try {+ // The group is already a member from createProjectGroup, and so is the seed admin.+ const added = await inject("POST", membersUrl, {+ userIds: [seedData1.id, seedData1.id],+ groupIds: [group.id],+ machineIdentityIds: [identity.id],+ role: "member"+ });+ expect(added.statusCode).toBe(200);++ const { members, skipped } = JSON.parse(added.payload) as {+ members: { actor: { type: string; id: string } }[];+ skipped: { type: string; id: string }[];+ };++ expect(members).toHaveLength(1);+ expect(members[0].actor).toMatchObject({ type: "machineIdentity", id: identity.id });+ expect(skipped.map((el) => el.id).sort()).toEqual([group.id, seedData1.id].sort());+ } finally {+ await group.cleanup();+ await deleteOrgIdentity(identity.id);+ }+ });+test("the guards that keep the product administrable hold", async () => {- const self = await inject("DELETE", `${memberships}/users/${seedData1.id}`);+ const self = await inject("POST", `${membersUrl}/revoke`, { userIds: [seedData1.id] });expect(self.statusCode).toBe(403);- const unknown = await inject("POST", `${memberships}/identities/00000000-0000-0000-0000-000000000000`, {+ const unknown = await inject("POST", membersUrl, {+ machineIdentityIds: ["00000000-0000-0000-0000-000000000000"],role: "member"});expect(unknown.statusCode).toBe(404);- const badRole = await inject("PATCH", `${memberships}/users/${seedData1.id}`, { role: "viewer" });+ // Adding someone who already has access is not a failure, so the rest of a batch still lands.+ const duplicate = await inject("POST", membersUrl, { userIds: [seedData1.id], role: "member" });+ expect(duplicate.statusCode).toBe(200);+ expect(JSON.parse(duplicate.payload)).toMatchObject({+ members: [],+ skipped: [{ type: "user", id: seedData1.id }]+ });++ const badRole = await inject("PATCH", `${membersUrl}/users/${seedData1.id}`, { role: "viewer" });expect(badRole.statusCode).toBe(422);- const notAnId = await inject("DELETE", `${memberships}/users/not-a-uuid`);+ const badSegment = await inject("PATCH", `${membersUrl}/identities/${seedData1.id}`, { role: "member" });+ expect(badSegment.statusCode).toBe(422);++ const notAnId = await inject("POST", `${membersUrl}/revoke`, { userIds: ["not-a-uuid"] });expect(notAnId.statusCode).toBe(422);});});@@ -595,7 +1132,10 @@ describe("Agent Vault V1 Router", async () => {"POST",`/api/v1/agent-vault/access-bundles/${unknown}/services`,{ name: "c", hostPattern: "api.foo.com", credential: { type: "passthrough" } }- ]+ ],+ // The bundle is the path resource, so a missing one is still 404 even though a missing actor in+ // the body is reported as skipped.+ ["POST", `/api/v1/agent-vault/access-bundles/${unknown}/members/revoke`, { userIds: [seedData1.id] }]];for await (const [method, url, body] of routes) {@@ -906,6 +1446,8 @@ describe("Agent Vault V1 Router", async () => {agentVaultProxyServiceFactory({agentVaultProxyDAL: agentVaultProxyDALFactory(testDb),agentVaultResolveDAL: agentVaultResolveDALFactory(testDb),+ agentVaultServiceCustomHeaderDAL: agentVaultServiceCustomHeaderDALFactory(testDb),+ agentVaultServiceSubstitutionDAL: agentVaultServiceSubstitutionDALFactory(testDb),agentVaultSessionDAL: agentVaultSessionDALFactory(testDb),membershipDAL: membershipDALFactory(testDb),orgDAL: orgDALFactory(testDb),@@ -916,6 +1458,64 @@ describe("Agent Vault V1 Router", async () => {resourceAuthMethodService: {} as never});+ test("resolve carries the policy and the decrypted transformations", async () => {+ const bundle = await createAccessBundle("resolve-transformations");+ const created = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {+ name: "github",+ hostPattern: "api.github.com",+ allowedMethods: ["GET"],+ allowedPathPrefixes: ["/repos"],+ credential: { type: "passthrough" },+ customHeaders: [{ name: "X-Org-Id", prefix: "Org", value: "org_secret" }],+ substitutions: [{ placeholder: "__GITHUB_PAT__", surfaces: ["header"], value: "ghp_secret" }]+ });+ expect(created.statusCode).toBe(200);++ const mint = await inject("POST", "/api/v1/agent-vault/sessions", {+ accessBundles: [bundle.name],+ ttl: "1h"+ });+ expect(mint.statusCode).toBe(200);+ const { session } = JSON.parse(mint.payload) as { session: { token: string } };++ const proxyRes = await inject("POST", "/api/v1/agent-vault/proxies", {+ name: "resolve-transformations"+ });+ expect(proxyRes.statusCode).toBe(200);+ const { proxy } = JSON.parse(proxyRes.payload) as { proxy: { id: string } };++ const resolver = agentVaultProxyServiceFactory({+ agentVaultProxyDAL: agentVaultProxyDALFactory(testDb),+ agentVaultResolveDAL: agentVaultResolveDALFactory(testDb),+ agentVaultServiceCustomHeaderDAL: agentVaultServiceCustomHeaderDALFactory(testDb),+ agentVaultServiceSubstitutionDAL: agentVaultServiceSubstitutionDALFactory(testDb),+ agentVaultSessionDAL: agentVaultSessionDALFactory(testDb),+ membershipDAL: membershipDALFactory(testDb),+ orgDAL: orgDALFactory(testDb),+ permissionService: buildPermissionService(),+ kmsService: {+ createCipherPairWithDataKey: () =>+ Promise.resolve({ decryptor: () => Buffer.from(JSON.stringify({ value: "unsealed" })) })+ } as never,+ resourceAuthMethodService: {} as never+ });++ const resolved = await resolver.resolveSession({+ proxyId: proxy.id,+ orgId: seedData1.organization.id,+ sessionToken: session.token+ });++ expect(resolved.services).toHaveLength(1);+ const [service] = resolved.services;+ expect(service.allowedMethods).toEqual(["GET"]);+ expect(service.allowedPathPrefixes).toEqual(["/repos"]);+ expect(service.customHeaders).toEqual([{ name: "X-Org-Id", prefix: "Org", value: "unsealed" }]);+ expect(service.substitutions).toEqual([+ { placeholder: "__GITHUB_PAT__", surfaces: ["header"], value: "unsealed" }+ ]);+ });+test("a deactivated actor stops resolving, and resolves again once reactivated", async () => {const bundle = await createAccessBundle("resolve-deactivation");const service = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {@@ -1040,6 +1640,8 @@ describe("Agent Vault V1 Router", async () => {const resolver = agentVaultProxyServiceFactory({agentVaultProxyDAL: agentVaultProxyDALFactory(testDb),agentVaultResolveDAL: agentVaultResolveDALFactory(testDb),+ agentVaultServiceCustomHeaderDAL: agentVaultServiceCustomHeaderDALFactory(testDb),+ agentVaultServiceSubstitutionDAL: agentVaultServiceSubstitutionDALFactory(testDb),agentVaultSessionDAL: agentVaultSessionDALFactory(testDb),membershipDAL: membershipDALFactory(testDb),orgDAL: orgDALFactory(testDb),@@ -1099,10 +1701,7 @@ describe("Agent Vault V1 Router", async () => {expect(body.token).toBeTruthy();expect(body.expiresAt).toBeTruthy();- const reissued = await inject(- "POST",- `/api/v1/agent-vault/proxies/${body.proxy.id}/token-auth/generate-enrollment-token`- );+ const reissued = await inject("POST", `/api/v1/agent-vault/proxies/${body.proxy.id}/token-auth/enrollment-token`);expect(reissued.statusCode).toBe(200);const again = JSON.parse(reissued.payload) as { token: string; expiresAt: string };expect(again.token).toBeTruthy();@@ -1283,7 +1882,8 @@ describe("Agent Vault V1 Router", async () => {const membership = await seedMembership(projectId);const other = await createOrgIdentity(`av-second-admin-${Date.now()}`);expect(- (await inject("POST", `/api/v1/agent-vault/memberships/identities/${other.id}`, { role: "admin" })).statusCode+ (await inject("POST", "/api/v1/agent-vault/members", { machineIdentityIds: [other.id], role: "admin" }))+ .statusCode).toBe(200);try {@@ -1428,7 +2028,7 @@ describe("Agent Vault V1 Router", async () => {const outsider = await createOrgIdentity(`av-outsider-${Date.now()}`);const res = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/members`, {- identityIds: [outsider.id]+ machineIdentityIds: [outsider.id]});expect(res.statusCode).toBe(400);expect(JSON.parse(res.payload).message).toContain("not a member of Agent Vault");@@ -1460,7 +2060,7 @@ describe("Agent Vault V1 Router", async () => {try {const res = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/members`, {- identityIds: [insider.id]+ machineIdentityIds: [insider.id]});expect(res.statusCode).toBe(400);expect(JSON.parse(res.payload).message).toContain("through a group");@@ -1487,7 +2087,7 @@ describe("Agent Vault V1 Router", async () => {const empty = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/members`, {userIds: [],- identityIds: [],+ machineIdentityIds: [],groupIds: []});expect(empty.statusCode).toBe(422);@@ -1498,6 +2098,60 @@ describe("Agent Vault V1 Router", async () => {expect(notAnId.statusCode).toBe(422);});+ test("listing members discriminates the user, machine identity and group arms", async () => {+ const projectId = await getProjectId();+ const bundle = await createAccessBundle("member-arms");+ const group = await createProjectGroup(projectId, "av-arms-group", ProjectMembershipRole.Member);+ const identity = await createOrgIdentity(`av-arms-identity-${Date.now()}`);++ try {+ expect(+ (await inject("POST", "/api/v1/agent-vault/members", { machineIdentityIds: [identity.id], role: "member" }))+ .statusCode+ ).toBe(200);++ expect(+ (+ await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/members`, {+ groupIds: [group.id],+ machineIdentityIds: [identity.id]+ })+ ).statusCode+ ).toBe(200);++ const res = await inject("GET", `/api/v1/agent-vault/access-bundles/${bundle.id}/members`);+ expect(res.statusCode).toBe(200);+ const { members } = JSON.parse(res.payload) as {+ members: {+ id: string;+ actor: { type: string; id: string; name?: string; username?: string };+ }[];+ };++ // The creator's own grant is already there, so all three arms are on one response.+ const byType = Object.fromEntries(members.map((member) => [member.actor.type, member]));+ expect(Object.keys(byType).sort()).toEqual(["group", "machineIdentity", "user"]);++ expect(byType.group.actor).toMatchObject({ type: "group", id: group.id });+ expect(byType.machineIdentity.actor).toMatchObject({ type: "machineIdentity", id: identity.id });+ expect(byType.user.actor).toMatchObject({ type: "user", id: seedData1.id });+ expect(byType.user.actor.username).toBeTruthy();++ members.forEach((member) => {+ expect(member).not.toHaveProperty("accessBundleId");+ expect(member).not.toHaveProperty("userId");+ expect(member).not.toHaveProperty("identityId");+ expect(member).not.toHaveProperty("groupId");+ expect(member).not.toHaveProperty("user");+ expect(member).not.toHaveProperty("identity");+ expect(member).not.toHaveProperty("group");+ });+ } finally {+ await deleteOrgIdentity(identity.id);+ await group.cleanup();+ }+ });+test("one call grants several actors, dedupes repeats and skips the already granted", async () => {const projectId = await getProjectId();const bundle = await createAccessBundle("member-batch");@@ -1518,9 +2172,13 @@ describe("Agent Vault V1 Router", async () => {groupIds: [first.id, second.id]});expect(again.statusCode).toBe(200);- const repeat = JSON.parse(again.payload) as { members: unknown[]; skipped: string[] };+ const repeat = JSON.parse(again.payload) as {+ members: unknown[];+ skipped: { type: string; id: string }[];+ };expect(repeat.members).toEqual([]);- expect(repeat.skipped.sort()).toEqual([first.id, second.id].sort());+ expect(repeat.skipped.map((actor) => actor.id).sort()).toEqual([first.id, second.id].sort());+ expect(repeat.skipped.every((actor) => actor.type === "group")).toBe(true);} finally {await first.cleanup();await second.cleanup();@@ -1536,7 +2194,8 @@ describe("Agent Vault V1 Router", async () => {try {for await (const identity of [one, two]) {- const added = await inject("POST", `/api/v1/agent-vault/memberships/identities/${identity.id}`, {+ const added = await inject("POST", "/api/v1/agent-vault/members", {+ machineIdentityIds: [identity.id],role: ProjectMembershipRole.Admin});expect(added.statusCode).toBe(200);@@ -1549,7 +2208,7 @@ describe("Agent Vault V1 Router", async () => {await Promise.all([one, two].map((identity) =>- inject("PATCH", `/api/v1/agent-vault/memberships/identities/${identity.id}`, {+ inject("PATCH", `/api/v1/agent-vault/members/machine-identities/${identity.id}`, {role: ProjectMembershipRole.Member}))@@ -1570,7 +2229,7 @@ describe("Agent Vault V1 Router", async () => {test("an actor from outside the organization is refused, and an unknown id does not 500", async () => {// Users join through the bulk route; only groups and identities are named in the URL.- const stranger = await inject("POST", "/api/v1/agent-vault/memberships/users", {+ const stranger = await inject("POST", "/api/v1/agent-vault/members", {userIds: ["99999999-8888-7777-6666-555555555555"],emails: [],role: ProjectMembershipRole.Member@@ -1597,7 +2256,8 @@ describe("Agent Vault V1 Router", async () => {try {await testDb("memberships").where({ id: orgMembership.id }).update({ isActive: false });- const res = await inject("POST", `/api/v1/agent-vault/memberships/identities/${identityId}`, {+ const res = await inject("POST", "/api/v1/agent-vault/members", {+ machineIdentityIds: [identityId],role: ProjectMembershipRole.Member});expect(res.statusCode).toBe(400);@@ -1647,6 +2307,8 @@ describe("Agent Vault V1 Router", async () => {const resolver = agentVaultProxyServiceFactory({agentVaultProxyDAL: agentVaultProxyDALFactory(testDb),agentVaultResolveDAL: agentVaultResolveDALFactory(testDb),+ agentVaultServiceCustomHeaderDAL: agentVaultServiceCustomHeaderDALFactory(testDb),+ agentVaultServiceSubstitutionDAL: agentVaultServiceSubstitutionDALFactory(testDb),agentVaultSessionDAL: agentVaultSessionDALFactory(testDb),membershipDAL: membershipDALFactory(testDb),orgDAL: orgDALFactory(testDb),@@ -1670,9 +2332,12 @@ describe("Agent Vault V1 Router", async () => {).toBe(200);expect((await resolve()).services).toHaveLength(1);- const [grant] = await grantRows(bundle.id, { actorGroupId: group.id });expect(- (await inject("DELETE", `/api/v1/agent-vault/access-bundles/${bundle.id}/members/${grant.id}`)).statusCode+ (+ await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/members/revoke`, {+ groupIds: [group.id]+ })+ ).statusCode).toBe(200);expect((await resolve()).services).toHaveLength(0);@@ -1706,7 +2371,8 @@ describe("Agent Vault V1 Router", async () => {const group = await createProjectGroup(projectId, "av-lapsing", ProjectMembershipRole.Member);const agent = await createUaIdentity(`av-lapse-${Date.now()}`);expect(- (await inject("POST", `/api/v1/agent-vault/memberships/identities/${agent.id}`, { role: "member" })).statusCode+ (await inject("POST", "/api/v1/agent-vault/members", { machineIdentityIds: [agent.id], role: "member" }))+ .statusCode).toBe(200);await testDb("identity_group_membership").insert({ groupId: group.id, identityId: agent.id });expect(@@ -1732,6 +2398,8 @@ describe("Agent Vault V1 Router", async () => {const resolver = agentVaultProxyServiceFactory({agentVaultProxyDAL: agentVaultProxyDALFactory(testDb),agentVaultResolveDAL: agentVaultResolveDALFactory(testDb),+ agentVaultServiceCustomHeaderDAL: agentVaultServiceCustomHeaderDALFactory(testDb),+ agentVaultServiceSubstitutionDAL: agentVaultServiceSubstitutionDALFactory(testDb),agentVaultSessionDAL: agentVaultSessionDALFactory(testDb),membershipDAL: membershipDALFactory(testDb),orgDAL: orgDALFactory(testDb),@@ -1812,12 +2480,67 @@ describe("Agent Vault V1 Router", async () => {expect(await testDb("membership_roles").where({ membershipId: grant.id })).toHaveLength(0);});- test("a member id from another scope is refused, and grants are not seats", async () => {+ test("a revoke is confined to the named bundle, actor and actor type", async () => {+ const projectId = await getProjectId();+ const [held, other] = [await createAccessBundle("revoke-held"), await createAccessBundle("revoke-other")];+ const group = await createProjectGroup(projectId, "av-revoke-group", ProjectMembershipRole.Member);++ try {+ expect(+ (await inject("POST", `/api/v1/agent-vault/access-bundles/${held.id}/members`, { groupIds: [group.id] }))+ .statusCode+ ).toBe(200);++ const stillGranted = async () => (await grantRows(held.id, { actorGroupId: group.id })).length;+ const revoke = (accessBundleId: string, body: Record<string, unknown>) =>+ inject("POST", `/api/v1/agent-vault/access-bundles/${accessBundleId}/members/revoke`, body);++ // Every miss below is a 200 with the actor reported in skipped, not a 404: a batch cannot fail+ // wholesale on one absent id and stay useful, and the grant it does not name has to survive.+ // That surviving grant is the assertion that matters; the status alone would not catch a revoke+ // that reached the wrong bundle.+ const wrongBundle = await revoke(other.id, { groupIds: [group.id] });+ expect(wrongBundle.statusCode).toBe(200);+ expect(JSON.parse(wrongBundle.payload)).toMatchObject({+ members: [],+ skipped: [{ type: "group", id: group.id }]+ });+ expect(await stillGranted()).toBe(1);++ // The same id sent as the wrong actor kind names nobody, so the group's grant stands.+ const wrongType = await revoke(held.id, { userIds: [group.id] });+ expect(wrongType.statusCode).toBe(200);+ expect(JSON.parse(wrongType.payload).skipped).toMatchObject([{ type: "user", id: group.id }]);+ expect(await stillGranted()).toBe(1);++ const unknownActor = await revoke(held.id, { userIds: [crypto.randomUUID()] });+ expect(unknownActor.statusCode).toBe(200);+ expect(JSON.parse(unknownActor.payload).members).toHaveLength(0);+ expect(await stillGranted()).toBe(1);++ const correct = await revoke(held.id, { groupIds: [group.id] });+ expect(correct.statusCode).toBe(200);+ expect(JSON.parse(correct.payload)).toMatchObject({+ members: [{ actor: { type: "group", id: group.id } }],+ skipped: []+ });+ expect(await stillGranted()).toBe(0);++ // Repeating it changes nothing, which is what makes the bulk call safe to retry.+ const again = await revoke(held.id, { groupIds: [group.id] });+ expect(again.statusCode).toBe(200);+ expect(JSON.parse(again.payload)).toMatchObject({ members: [], skipped: [{ type: "group", id: group.id }] });+ } finally {+ await group.cleanup();+ }+ });++ test("a revoke reaches only this bundle's grant for this actor, and grants are not seats", async () => {const projectId = await getProjectId();const bundle = await createAccessBundle("scoped-member-ids");const identity = await createOrgIdentity(`av-seats-${Date.now()}`);expect(- (await inject("POST", `/api/v1/agent-vault/memberships/identities/${identity.id}`, { role: "member" }))+ (await inject("POST", "/api/v1/agent-vault/members", { machineIdentityIds: [identity.id], role: "member" })).statusCode).toBe(200);@@ -1826,11 +2549,17 @@ describe("Agent Vault V1 Router", async () => {const projectMembership = await testDb("memberships").where({ scope: AccessScope.Project, scopeProjectId: projectId, actorIdentityId: identity.id }).first();- const refused = await inject(- "DELETE",- `/api/v1/agent-vault/access-bundles/${bundle.id}/members/${projectMembership.id}`- );- expect(refused.statusCode).toBe(404);+ // The actor holds a project membership but no grant on this bundle, so the revoke reports it as+ // skipped and, crucially, leaves the project membership alone. That is the property this test+ // defends: the two scopes share one table, so a revoke that lost its scope filter would take it.+ const refused = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/members/revoke`, {+ machineIdentityIds: [identity.id]+ });+ expect(refused.statusCode).toBe(200);+ expect(JSON.parse(refused.payload)).toMatchObject({+ members: [],+ skipped: [{ type: "machineIdentity", id: identity.id }]+ });expect(await testDb("memberships").where({ id: projectMembership.id })).toHaveLength(1);for (const name of ["seats-a", "seats-b", "seats-c"]) {@@ -1838,19 +2567,22 @@ describe("Agent Vault V1 Router", async () => {const extra = await createAccessBundle(name);// eslint-disable-next-line no-await-in-loopconst granted = await inject("POST", `/api/v1/agent-vault/access-bundles/${extra.id}/members`, {- identityIds: [identity.id]+ machineIdentityIds: [identity.id]});expect(granted.statusCode).toBe(200);}const duplicate = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/members`, {- identityIds: [identity.id]+ machineIdentityIds: [identity.id]});expect(duplicate.statusCode).toBe(200);const again = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/members`, {- identityIds: [identity.id]+ machineIdentityIds: [identity.id]});expect(again.statusCode).toBe(200);- expect(JSON.parse(again.payload)).toMatchObject({ members: [], skipped: [identity.id] });+ expect(JSON.parse(again.payload)).toMatchObject({+ members: [],+ skipped: [{ type: "machineIdentity", id: identity.id }]+ });expect(await usageCounterDALFactory(testDb).countAgentVaultIdentities(seedData1.organization.id)).toBe(seatsBeforediff --git a/backend/src/@types/knex.d.ts b/backend/src/@types/knex.d.tsindex ae09541361..3ada435e42 100644--- a/backend/src/@types/knex.d.ts+++ b/backend/src/@types/knex.d.ts@@ -26,8 +26,14 @@ import {TAgentVaultProxies,TAgentVaultProxiesInsert,TAgentVaultProxiesUpdate,+ TAgentVaultServiceCustomHeaders,+ TAgentVaultServiceCustomHeadersInsert,+ TAgentVaultServiceCustomHeadersUpdate,TAgentVaultServices,TAgentVaultServicesInsert,+ TAgentVaultServiceSubstitutions,+ TAgentVaultServiceSubstitutionsInsert,+ TAgentVaultServiceSubstitutionsUpdate,TAgentVaultServicesUpdate,TAgentVaultSessionAccessBundles,TAgentVaultSessionAccessBundlesInsert,@@ -1785,6 +1791,16 @@ declare module "knex/types/tables" {TAgentVaultServicesInsert,TAgentVaultServicesUpdate>;+ [TableName.AgentVaultServiceCustomHeader]: KnexOriginal.CompositeTableType<+ TAgentVaultServiceCustomHeaders,+ TAgentVaultServiceCustomHeadersInsert,+ TAgentVaultServiceCustomHeadersUpdate+ >;+ [TableName.AgentVaultServiceSubstitution]: KnexOriginal.CompositeTableType<+ TAgentVaultServiceSubstitutions,+ TAgentVaultServiceSubstitutionsInsert,+ TAgentVaultServiceSubstitutionsUpdate+ >;[TableName.AgentVaultSession]: KnexOriginal.CompositeTableType<TAgentVaultSessions,TAgentVaultSessionsInsert,diff --git a/backend/src/db/migrations/20260914090000_agent-vault-service-policy-and-transformations.ts b/backend/src/db/migrations/20260914090000_agent-vault-service-policy-and-transformations.tsnew file mode 100644index 0000000000..ac15fcea1c--- /dev/null+++ b/backend/src/db/migrations/20260914090000_agent-vault-service-policy-and-transformations.ts@@ -0,0 +1,78 @@+import { Knex } from "knex";++import { TableName } from "../schemas";+import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils";++export async function up(knex: Knex): Promise<void> {+ const hasAllowedMethods = await knex.schema.hasColumn(TableName.AgentVaultService, "allowedMethods");+ const hasAllowedPathPrefixes = await knex.schema.hasColumn(TableName.AgentVaultService, "allowedPathPrefixes");++ if (!hasAllowedMethods || !hasAllowedPathPrefixes) {+ await knex.schema.alterTable(TableName.AgentVaultService, (t) => {+ // NULL is the only "unrestricted": an empty array is never stored, so there is one representation of "all".+ // Arrays rather than the comma-separated strings hostPattern uses, because a comma is legal in a path.+ if (!hasAllowedMethods) t.specificType("allowedMethods", "text[]");+ if (!hasAllowedPathPrefixes) t.specificType("allowedPathPrefixes", "text[]");+ });+ }++ if (!(await knex.schema.hasTable(TableName.AgentVaultServiceCustomHeader))) {+ await knex.schema.createTable(TableName.AgentVaultServiceCustomHeader, (t) => {+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());++ t.uuid("serviceId").notNullable();+ t.foreign("serviceId").references("id").inTable(TableName.AgentVaultService).onDelete("CASCADE");+ t.index("serviceId");++ t.string("name", 128).notNullable();+ t.string("prefix", 64).notNullable();++ t.binary("encryptedValue").notNullable();++ t.integer("position").notNullable();++ t.timestamps(true, true, true);+ });++ await createOnUpdateTrigger(knex, TableName.AgentVaultServiceCustomHeader);+ }++ if (!(await knex.schema.hasTable(TableName.AgentVaultServiceSubstitution))) {+ await knex.schema.createTable(TableName.AgentVaultServiceSubstitution, (t) => {+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());++ t.uuid("serviceId").notNullable();+ t.foreign("serviceId").references("id").inTable(TableName.AgentVaultService).onDelete("CASCADE");+ t.index("serviceId");++ t.string("placeholder", 255).notNullable();+ t.specificType("surfaces", "text[]").notNullable();++ t.binary("encryptedValue").notNullable();++ t.integer("position").notNullable();++ t.timestamps(true, true, true);+ });++ await createOnUpdateTrigger(knex, TableName.AgentVaultServiceSubstitution);+ }+}++export async function down(knex: Knex): Promise<void> {+ await knex.schema.dropTableIfExists(TableName.AgentVaultServiceSubstitution);+ await dropOnUpdateTrigger(knex, TableName.AgentVaultServiceSubstitution);++ await knex.schema.dropTableIfExists(TableName.AgentVaultServiceCustomHeader);+ await dropOnUpdateTrigger(knex, TableName.AgentVaultServiceCustomHeader);++ const hasAllowedMethods = await knex.schema.hasColumn(TableName.AgentVaultService, "allowedMethods");+ const hasAllowedPathPrefixes = await knex.schema.hasColumn(TableName.AgentVaultService, "allowedPathPrefixes");++ if (hasAllowedMethods || hasAllowedPathPrefixes) {+ await knex.schema.alterTable(TableName.AgentVaultService, (t) => {+ if (hasAllowedMethods) t.dropColumn("allowedMethods");+ if (hasAllowedPathPrefixes) t.dropColumn("allowedPathPrefixes");+ });+ }+}diff --git a/backend/src/db/schemas/agent-vault-service-custom-headers.ts b/backend/src/db/schemas/agent-vault-service-custom-headers.tsnew file mode 100644index 0000000000..d8b07ad2b3--- /dev/null+++ b/backend/src/db/schemas/agent-vault-service-custom-headers.ts@@ -0,0 +1,30 @@+// Code generated by automation script, DO NOT EDIT.+// Automated by pulling database and generating zod schema+// To update. Just run npm run generate:schema+// Written by akhilmhdh.++import { z } from "zod";++import { zodBuffer } from "@app/lib/zod";++import { TImmutableDBKeys } from "./models";++export const AgentVaultServiceCustomHeadersSchema = z.object({+ id: z.string().uuid(),+ serviceId: z.string().uuid(),+ name: z.string(),+ prefix: z.string(),+ encryptedValue: zodBuffer,+ position: z.number(),+ createdAt: z.date(),+ updatedAt: z.date()+});++export type TAgentVaultServiceCustomHeaders = z.infer<typeof AgentVaultServiceCustomHeadersSchema>;+export type TAgentVaultServiceCustomHeadersInsert = Omit<+ z.input<typeof AgentVaultServiceCustomHeadersSchema>,+ TImmutableDBKeys+>;+export type TAgentVaultServiceCustomHeadersUpdate = Partial<+ Omit<z.input<typeof AgentVaultServiceCustomHeadersSchema>, TImmutableDBKeys>+>;diff --git a/backend/src/db/schemas/agent-vault-service-substitutions.ts b/backend/src/db/schemas/agent-vault-service-substitutions.tsnew file mode 100644index 0000000000..c7a0c8720e--- /dev/null+++ b/backend/src/db/schemas/agent-vault-service-substitutions.ts@@ -0,0 +1,30 @@+// Code generated by automation script, DO NOT EDIT.+// Automated by pulling database and generating zod schema+// To update. Just run npm run generate:schema+// Written by akhilmhdh.++import { z } from "zod";++import { zodBuffer } from "@app/lib/zod";++import { TImmutableDBKeys } from "./models";++export const AgentVaultServiceSubstitutionsSchema = z.object({+ id: z.string().uuid(),+ serviceId: z.string().uuid(),+ placeholder: z.string(),+ surfaces: z.string().array(),+ encryptedValue: zodBuffer,+ position: z.number(),+ createdAt: z.date(),+ updatedAt: z.date()+});++export type TAgentVaultServiceSubstitutions = z.infer<typeof AgentVaultServiceSubstitutionsSchema>;+export type TAgentVaultServiceSubstitutionsInsert = Omit<+ z.input<typeof AgentVaultServiceSubstitutionsSchema>,+ TImmutableDBKeys+>;+export type TAgentVaultServiceSubstitutionsUpdate = Partial<+ Omit<z.input<typeof AgentVaultServiceSubstitutionsSchema>, TImmutableDBKeys>+>;diff --git a/backend/src/db/schemas/agent-vault-services.ts b/backend/src/db/schemas/agent-vault-services.tsindex 84cdc220e4..cf9dc6c62a 100644--- a/backend/src/db/schemas/agent-vault-services.ts+++ b/backend/src/db/schemas/agent-vault-services.ts@@ -18,7 +18,9 @@ export const AgentVaultServicesSchema = z.object({credentialConfig: z.unknown(),encryptedCredential: zodBuffer.nullable().optional(),createdAt: z.date(),- updatedAt: z.date()+ updatedAt: z.date(),+ allowedMethods: z.string().array().nullable().optional(),+ allowedPathPrefixes: z.string().array().nullable().optional()});export type TAgentVaultServices = z.infer<typeof AgentVaultServicesSchema>;diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.tsindex fedb48bf30..583cd69421 100644--- a/backend/src/db/schemas/index.ts+++ b/backend/src/db/schemas/index.ts@@ -6,6 +6,8 @@ export * from "./access-approval-requests-reviewers";export * from "./additional-privileges";export * from "./agent-vault-access-bundles";export * from "./agent-vault-proxies";+export * from "./agent-vault-service-custom-headers";+export * from "./agent-vault-service-substitutions";export * from "./agent-vault-services";export * from "./agent-vault-session-access-bundles";export * from "./agent-vault-sessions";diff --git a/backend/src/db/schemas/models.ts b/backend/src/db/schemas/models.tsindex c3883e5a85..cd02c1a28f 100644--- a/backend/src/db/schemas/models.ts+++ b/backend/src/db/schemas/models.ts@@ -274,6 +274,8 @@ export enum TableName {PamAccountPolicy = "pam_account_policies",AgentVaultAccessBundle = "agent_vault_access_bundles",AgentVaultService = "agent_vault_services",+ AgentVaultServiceCustomHeader = "agent_vault_service_custom_headers",+ AgentVaultServiceSubstitution = "agent_vault_service_substitutions",AgentVaultSession = "agent_vault_sessions",AgentVaultSessionAccessBundle = "agent_vault_session_access_bundles",AgentVaultProxy = "agent_vault_proxies",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 4409ac9a93..904769656d 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@@ -1,8 +1,6 @@-import { FastifyRequest } from "fastify";import { z } from "zod";import { AgentVaultAccessBundlesSchema } from "@app/db/schemas";-import { TAgentVaultActorContext } from "@app/ee/services/agent-vault/agent-vault-actor-types";import {AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE,AGENT_VAULT_NO_CONTROL_CHARS_RE@@ -18,16 +16,26 @@ import { verifyAuth } from "@app/server/plugins/auth/verify-auth";import { AuthMode } from "@app/services/auth/auth-type";import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";+import { actorContext, auditActorFields } from "./agent-vault-router-fns";import {+ AgentVaultActorRefSchema,+ AgentVaultAllowedMethodsSchema,+ AgentVaultAllowedPathPrefixesSchema,AgentVaultCreatedMemberSchema,AgentVaultCredentialInputSchema,AgentVaultCredentialUpdateSchema,+ AgentVaultCustomHeadersInputSchema,+ AgentVaultCustomHeadersUpdateSchema,AgentVaultHostPatternSchema,+ agentVaultListQuery,AgentVaultMemberIdsSchema,+ AgentVaultMemberRevokeIdsSchema,AgentVaultMemberSchema,AgentVaultNameSchema,AgentVaultRemovedMemberSchema,- AgentVaultServiceSchema+ AgentVaultServiceSchema,+ AgentVaultSubstitutionsInputSchema,+ AgentVaultSubstitutionsUpdateSchema} from "./agent-vault-schemas";const AccessBundleDescriptionSchema = z@@ -41,20 +49,8 @@ const AccessBundleSchema = AgentVaultAccessBundlesSchema.pick({id: true,name: true,description: true,- createdAt: true-});--const memberTypeOf = (member: { userId?: string | null; identityId?: string | null; groupId?: string | null }) => {- if (member.userId) return "user" as const;- if (member.identityId) return "identity" as const;- return "group" as const;-};--const actorContext = (req: FastifyRequest): TAgentVaultActorContext => ({- actorId: req.permission.id,- actor: req.permission.type,- actorOrgId: req.permission.orgId,- actorAuthMethod: req.permission.authMethod+ createdAt: true,+ updatedAt: true});// A passthrough switch is a replacement: mergeCredential returns a null secret and updateService nulls@@ -78,24 +74,32 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodProoperationId: "listAgentVaultAccessBundles",description: "List the Agent Vault access bundles you can reach",tags: [ApiDocsTags.AgentVaultAccessBundles],+ querystring: z.object({+ 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)+ }),response: {200: z.object({accessBundles: AccessBundleSchema.extend({serviceCount: z.number().describe(AGENT_VAULT.ACCESS_BUNDLE.serviceCount),memberCount: z.number().describe(AGENT_VAULT.ACCESS_BUNDLE.memberCount),hostPatterns: z.string().array().describe(AGENT_VAULT.ACCESS_BUNDLE.hostPatterns)- }).array()+ }).array(),+ totalCount: z.number()})}},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),- handler: async (req) => {- const accessBundles = await server.services.agentVaultAccessBundle.listAccessBundles({+ handler: async (req) =>+ server.services.agentVaultAccessBundle.listAccessBundles({projectId: req.internalAgentVaultProjectId,- ctx: actorContext(req)- });- return { accessBundles };- }+ ctx: actorContext(req),+ ...req.query+ })});server.route({@@ -156,10 +160,7 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodPro}),response: {200: z.object({- accessBundle: AccessBundleSchema.extend({- services: AgentVaultServiceSchema.array(),- members: AgentVaultMemberSchema.array().optional()- })+ accessBundle: AccessBundleSchema.extend({ services: AgentVaultServiceSchema.array() })})}},@@ -191,7 +192,7 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodProdescription: AccessBundleDescriptionSchema.nullable().optional()}).refine(- (body) => body.name !== undefined || body.description !== undefined,+ (body) => Object.values(body).some((value) => value !== undefined),"Provide at least one of 'name' or 'description' to update"),response: { 200: z.object({ accessBundle: AccessBundleSchema }) }@@ -274,7 +275,7 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodProconfig: { rateLimit: writeLimit },schema: {operationId: "createAgentVaultService",- description: "Add a service to an Agent Vault access bundle",+ description: "Create a service in an Agent Vault access bundle",tags: [ApiDocsTags.AgentVaultAccessBundles],params: z.object({accessBundleId: z.string().uuid().describe(AGENT_VAULT.ACCESS_BUNDLE.accessBundleId)@@ -282,7 +283,11 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodProbody: z.object({name: AgentVaultNameSchema.describe(AGENT_VAULT.SERVICE.name),hostPattern: AgentVaultHostPatternSchema,- credential: AgentVaultCredentialInputSchema+ allowedMethods: AgentVaultAllowedMethodsSchema.optional(),+ allowedPathPrefixes: AgentVaultAllowedPathPrefixesSchema.optional(),+ credential: AgentVaultCredentialInputSchema,+ customHeaders: AgentVaultCustomHeadersInputSchema.optional(),+ substitutions: AgentVaultSubstitutionsInputSchema.optional()}),response: {200: z.object({ service: AgentVaultServiceSchema })@@ -312,7 +317,11 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodProheaderName:service.credential.type === AgentVaultCredentialType.Bearer ? service.credential.headerName : undefined,headerPrefix:- service.credential.type === AgentVaultCredentialType.Bearer ? service.credential.headerPrefix : undefined+ service.credential.type === AgentVaultCredentialType.Bearer ? service.credential.headerPrefix : undefined,+ allowedMethods: service.allowedMethods,+ allowedPathPrefixes: service.allowedPathPrefixes,+ customHeaderNames: service.customHeaders.map((header) => header.name),+ substitutionPlaceholders: service.substitutions.map((substitution) => substitution.placeholder)}}});@@ -323,7 +332,11 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodProaccessBundleId: req.params.accessBundleId,serviceId: service.id,credentialType: service.credential.type,- hostPatternCount: parseHostPatterns(service.hostPattern).patterns.length+ hostPatternCount: parseHostPatterns(service.hostPattern).patterns.length,+ allowedMethodCount: service.allowedMethods?.length ?? 0,+ allowedPathPrefixCount: service.allowedPathPrefixes?.length ?? 0,+ customHeaderCount: service.customHeaders.length,+ substitutionCount: service.substitutions.length}});@@ -347,11 +360,15 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodPro.object({name: AgentVaultNameSchema.optional().describe(AGENT_VAULT.SERVICE.name),hostPattern: AgentVaultHostPatternSchema.optional(),- credential: AgentVaultCredentialUpdateSchema.optional()+ allowedMethods: AgentVaultAllowedMethodsSchema.optional(),+ allowedPathPrefixes: AgentVaultAllowedPathPrefixesSchema.optional(),+ credential: AgentVaultCredentialUpdateSchema.optional(),+ customHeaders: AgentVaultCustomHeadersUpdateSchema.optional(),+ substitutions: AgentVaultSubstitutionsUpdateSchema.optional()}).refine(- (body) => body.name !== undefined || body.hostPattern !== undefined || body.credential !== undefined,- "Provide at least one of 'name', 'hostPattern' or 'credential' to update"+ (body) => Object.values(body).some((value) => value !== undefined),+ "Provide at least one of 'name', 'hostPattern', 'allowedMethods', 'allowedPathPrefixes', 'credential', 'customHeaders' or 'substitutions' to update"),response: {200: z.object({ service: AgentVaultServiceSchema })@@ -388,6 +405,18 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodProreq.body.credential?.type === AgentVaultCredentialType.Bearer? req.body.credential.headerPrefix: undefined,+ allowedMethods: req.body.allowedMethods,+ allowedPathPrefixes: req.body.allowedPathPrefixes,+ customHeaderNames: req.body.customHeaders?.map((header) => header.name),+ // A row omitting a value keeps the stored secret, so sending one is what marks a rotation.+ // Without this a rotation and a no-op save write the same row.+ customHeadersReplaced: req.body.customHeaders+ ?.filter((header) => header.value !== undefined)+ .map((header) => header.name),+ substitutionPlaceholders: req.body.substitutions?.map((substitution) => substitution.placeholder),+ substitutionsReplaced: req.body.substitutions+ ?.filter((substitution) => substitution.value !== undefined)+ .map((substitution) => substitution.placeholder),credentialReplaced: isStoredSecretReplaced(req.body.credential)}}@@ -399,7 +428,11 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodProaccessBundleId: req.params.accessBundleId,serviceId: service.id,credentialType: service.credential.type,- hostPatternCount: parseHostPatterns(service.hostPattern).patterns.length+ hostPatternCount: parseHostPatterns(service.hostPattern).patterns.length,+ allowedMethodCount: service.allowedMethods?.length ?? 0,+ allowedPathPrefixCount: service.allowedPathPrefixes?.length ?? 0,+ customHeaderCount: service.customHeaders.length,+ substitutionCount: service.substitutions.length}});@@ -464,17 +497,17 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodProparams: z.object({accessBundleId: z.string().uuid().describe(AGENT_VAULT.ACCESS_BUNDLE.accessBundleId)}),- response: { 200: z.object({ members: AgentVaultMemberSchema.array() }) }+ querystring: z.object(agentVaultListQuery(AGENT_VAULT.MEMBER)),+ response: { 200: z.object({ members: AgentVaultMemberSchema.array(), totalCount: z.number() }) }},- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),- handler: async (req) => {- const members = await server.services.agentVaultAccessBundle.listMembers({+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ handler: async (req) =>+ server.services.agentVaultAccessBundle.listMembers({projectId: req.internalAgentVaultProjectId,ctx: actorContext(req),- accessBundleId: req.params.accessBundleId- });- return { members };- }+ accessBundleId: req.params.accessBundleId,+ ...req.query+ })});server.route({@@ -492,7 +525,7 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodProresponse: {200: z.object({members: AgentVaultCreatedMemberSchema.array(),- skipped: z.string().uuid().array().describe(AGENT_VAULT.MEMBER.skipped)+ skipped: AgentVaultActorRefSchema.array().describe(AGENT_VAULT.MEMBER.skipped)})}},@@ -517,9 +550,7 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodProaccessBundleId: req.params.accessBundleId,accessBundleName,memberId: member.id,- ...(member.userId && { userId: member.userId }),- ...(member.identityId && { identityId: member.identityId }),- ...(member.groupId && { groupId: member.groupId })+ ...auditActorFields(member.actor)}}})@@ -529,7 +560,7 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodPromembers.forEach((member) =>emitAgentVaultTelemetry(server.services.telemetry, req, {event: PostHogEventTypes.AgentVaultAccessBundleMemberAdded,- properties: { accessBundleId: req.params.accessBundleId, memberType: memberTypeOf(member) }+ properties: { accessBundleId: req.params.accessBundleId, memberType: member.actor.type }}));@@ -538,48 +569,60 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodPro});server.route({- method: "DELETE",- url: "/:accessBundleId/members/:memberId",+ method: "POST",+ url: "/:accessBundleId/members/revoke",config: { rateLimit: writeLimit },schema: {- operationId: "removeAgentVaultAccessBundleMember",- description: "Revoke an Agent Vault access bundle from a user, machine identity or group",+ operationId: "revokeAgentVaultAccessBundleMembers",+ description: "Revoke an Agent Vault access bundle from users, machine identities or groups",tags: [ApiDocsTags.AgentVaultAccessBundles],params: z.object({- accessBundleId: z.string().uuid().describe(AGENT_VAULT.ACCESS_BUNDLE.accessBundleId),- memberId: z.string().uuid().describe(AGENT_VAULT.MEMBER.memberId)+ accessBundleId: z.string().uuid().describe(AGENT_VAULT.ACCESS_BUNDLE.accessBundleId)}),- response: { 200: z.object({ member: AgentVaultRemovedMemberSchema }) }+ body: AgentVaultMemberRevokeIdsSchema,+ response: {+ 200: z.object({+ members: AgentVaultRemovedMemberSchema.array(),+ skipped: AgentVaultActorRefSchema.array().describe(AGENT_VAULT.MEMBER.revokeSkipped)+ })+ }},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),handler: async (req) => {- const member = await server.services.agentVaultAccessBundle.removeMember({+ const { members, skipped, accessBundleName } = await server.services.agentVaultAccessBundle.revokeMembers({projectId: req.internalAgentVaultProjectId,ctx: actorContext(req),accessBundleId: req.params.accessBundleId,- memberId: req.params.memberId+ ...req.body});- await server.services.auditLog.createAuditLog({- ...req.auditLogInfo,- orgId: req.permission.orgId,- projectId: req.internalAgentVaultProjectId,- event: {- type: EventType.AGENT_VAULT_ACCESS_BUNDLE_MEMBER_REMOVE,- metadata: {- accessBundleId: req.params.accessBundleId,- accessBundleName: member.accessBundleName,- memberId: member.id- }- }- });+ await Promise.all(+ members.map((member) =>+ server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ orgId: req.permission.orgId,+ projectId: req.internalAgentVaultProjectId,+ event: {+ type: EventType.AGENT_VAULT_ACCESS_BUNDLE_MEMBER_REMOVE,+ metadata: {+ accessBundleId: req.params.accessBundleId,+ accessBundleName,+ memberId: member.id,+ ...auditActorFields(member.actor)+ }+ }+ })+ )+ );- emitAgentVaultTelemetry(server.services.telemetry, req, {- event: PostHogEventTypes.AgentVaultAccessBundleMemberRemoved,- properties: { accessBundleId: req.params.accessBundleId, memberType: memberTypeOf(member) }- });+ members.forEach((member) =>+ emitAgentVaultTelemetry(server.services.telemetry, req, {+ event: PostHogEventTypes.AgentVaultAccessBundleMemberRemoved,+ properties: { accessBundleId: req.params.accessBundleId, memberType: member.actor.type }+ })+ );- return { member };+ return { members, skipped };}});};diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-membership-router.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-membership-router.tsindex db1473db91..023b8d486f 100644--- a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-membership-router.ts+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-membership-router.ts@@ -1,8 +1,6 @@-import { FastifyRequest } from "fastify";import { z } from "zod";-import { ProjectMembershipRole } from "@app/db/schemas";-import { TAgentVaultActorContext } from "@app/ee/services/agent-vault/agent-vault-actor-types";+import { AgentVaultMemberType } from "@app/ee/services/agent-vault/agent-vault-enums";import { EventType } from "@app/ee/services/audit-log/audit-log-types";import { AGENT_VAULT } from "@app/lib/api-docs";import { ApiDocsTags } from "@app/lib/api-docs/constants";@@ -12,187 +10,131 @@ import { verifyAuth } from "@app/server/plugins/auth/verify-auth";import { AuthMode } from "@app/services/auth/auth-type";import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";-const actorContext = (req: FastifyRequest): TAgentVaultActorContext => ({- actorId: req.permission.id,- actor: req.permission.type,- actorOrgId: req.permission.orgId,- actorAuthMethod: req.permission.authMethod-});--const ProductRoleSchema = z- .enum([ProjectMembershipRole.Admin, ProjectMembershipRole.Member])- .describe(AGENT_VAULT.MEMBERSHIP.role);--const MemberSchema = z.object({- membershipId: z.string().uuid(),- userId: z.string().uuid().nullable(),- groupId: z.string().uuid().nullable(),- identityId: z.string().uuid().nullable(),- role: z.string().describe(AGENT_VAULT.MEMBERSHIP.role),- isActive: z.boolean(),- createdAt: z.date()-});+import { actorContext, auditActorFields } from "./agent-vault-router-fns";+import {+ agentVaultListQuery,+ AgentVaultProductMemberAddSchema,+ AgentVaultProductMemberIdsSchema,+ AgentVaultProductMemberRefSchema,+ AgentVaultProductMemberSchema,+ AgentVaultProductRoleSchema,+ AgentVaultSkippedActorSchema+} from "./agent-vault-schemas";++const ACTOR_TYPE_SEGMENTS = ["users", "groups", "machine-identities"] as const;++const ACTOR_TYPE_OF: Record<(typeof ACTOR_TYPE_SEGMENTS)[number], AgentVaultMemberType> = {+ users: AgentVaultMemberType.User,+ groups: AgentVaultMemberType.Group,+ "machine-identities": AgentVaultMemberType.MachineIdentity+};-// Mirrors PAM's MemberResultSchema so every membership write reports the row it touched.-const MemberResultSchema = z.object({- membershipId: z.string().uuid(),- userId: z.string().uuid().optional().describe(AGENT_VAULT.MEMBER.userId),- identityId: z.string().uuid().optional().describe(AGENT_VAULT.MEMBER.identityId),- groupId: z.string().uuid().optional().describe(AGENT_VAULT.MEMBER.groupId),- role: z.string().describe(AGENT_VAULT.MEMBERSHIP.role),- createdAt: z.date()+const auditActorNameFields = (actor: { type: AgentVaultMemberType }, actorName?: string) => ({+ ...(actor.type === AgentVaultMemberType.User && { userName: actorName }),+ ...(actor.type === AgentVaultMemberType.MachineIdentity && { machineIdentityName: actorName }),+ ...(actor.type === AgentVaultMemberType.Group && { groupName: actorName })});export const registerAgentVaultMembershipRouter = async (server: FastifyZodProvider) => {server.route({method: "GET",- url: "/users",+ url: "/",config: { rateLimit: readLimit },schema: {- operationId: "listAgentVaultProductUserMembers",- description: "List the users that are members of Agent Vault",- tags: [ApiDocsTags.AgentVaultMemberships],+ operationId: "listAgentVaultMembers",+ description: "List the users, groups and machine identities that are members of Agent Vault",+ tags: [ApiDocsTags.AgentVaultMembers],+ querystring: z.object({+ actorType: z.nativeEnum(AgentVaultMemberType).optional().describe(AGENT_VAULT.MEMBERSHIP.actorTypeFilter),+ ...agentVaultListQuery(AGENT_VAULT.MEMBERSHIP)+ }),response: {- 200: z.object({- members: MemberSchema.extend({- email: z.string().nullable(),- username: z.string(),- firstName: z.string().nullable(),- lastName: z.string().nullable(),- isOrgMembershipPending: z.boolean()- }).array()- })+ 200: z.object({ members: AgentVaultProductMemberSchema.array(), totalCount: z.number() })}},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),- handler: async (req) => ({- members: await server.services.agentVaultMembership.listProductUserMembers({- projectId: req.internalAgentVaultProjectId,- ctx: actorContext(req)- })- })- });- server.route({- method: "GET",- url: "/groups",- config: { rateLimit: readLimit },- schema: {- operationId: "listAgentVaultProductGroupMembers",- description: "List the groups that are members of Agent Vault",- tags: [ApiDocsTags.AgentVaultMemberships],- response: { 200: z.object({ members: MemberSchema.extend({ name: z.string() }).array() }) }- },- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),- handler: async (req) => ({- members: await server.services.agentVaultMembership.listProductGroupMembers({+ handler: async (req) =>+ server.services.agentVaultMembership.listProductMembers({projectId: req.internalAgentVaultProjectId,+ ...req.query,ctx: actorContext(req)})- })});+server.route({- method: "GET",- url: "/identities",- config: { rateLimit: readLimit },+ method: "POST",+ url: "/",+ config: { rateLimit: writeLimit },schema: {- operationId: "listAgentVaultProductIdentityMembers",- description: "List the machine identities that are members of Agent Vault",- tags: [ApiDocsTags.AgentVaultMemberships],+ operationId: "addAgentVaultMembers",+ description: "Give users, groups and machine identities access to Agent Vault, by id or by email",+ tags: [ApiDocsTags.AgentVaultMembers],+ body: AgentVaultProductMemberAddSchema,response: {200: z.object({- members: MemberSchema.extend({- name: z.string(),- identityProjectId: z.string().nullable(),- identityOrgId: z.string().nullable()- }).array()+ members: AgentVaultProductMemberRefSchema.array(),+ skipped: AgentVaultSkippedActorSchema.array().describe(AGENT_VAULT.MEMBERSHIP.addSkipped)})}},- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),- handler: async (req) => ({- members: await server.services.agentVaultMembership.listProductIdentityMembers({- projectId: req.internalAgentVaultProjectId,- ctx: actorContext(req)- })- })- });- server.route({- method: "POST",- url: "/users",- config: { rateLimit: writeLimit },- schema: {- operationId: "addAgentVaultProductUserMembers",- description: "Give one or more users access to Agent Vault, by id or by email",- tags: [ApiDocsTags.AgentVaultMemberships],- body: z- .object({- userIds: z.string().uuid().array().max(100).default([]),- // Usernames are stored lowercase and the lookup is an exact match, so a mixed-case address- // would come back as "not a member" rather than resolving.- emails: z- .string()- .email()- .array()- .max(100)- .default([])- .refine((val) => val.every((el) => el === el.toLowerCase()), "Email must be lowercase"),- role: ProductRoleSchema- })- .refine((val) => val.userIds.length + val.emails.length > 0, {- message: "Provide at least one user ID or email address."- }),- response: { 200: z.object({ members: MemberResultSchema.array(), skipped: z.string().array() }) }- },onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),handler: async (req) => {- const { memberships, skipped } = await server.services.agentVaultMembership.addProductUserMembers({+ const { members, skipped } = await server.services.agentVaultMembership.addProductMembers({projectId: req.internalAgentVaultProjectId,...req.body,ctx: actorContext(req)});await Promise.all(- memberships.map((membership) =>+ members.map((member) =>server.services.auditLog.createAuditLog({...req.auditLogInfo,orgId: req.permission.orgId,projectId: req.internalAgentVaultProjectId,event: {type: EventType.AGENT_VAULT_MEMBER_ADD,- metadata: { userId: membership.userId, userName: membership.userName, role: membership.role }+ metadata: {+ ...auditActorFields(member.actor),+ ...auditActorNameFields(member.actor, member.actorName),+ role: member.role+ }}})));- memberships.forEach((membership) =>+ members.forEach((member) =>emitAgentVaultTelemetry(server.services.telemetry, req, {event: PostHogEventTypes.AgentVaultProductMemberAdded,- properties: { memberType: "user", role: membership.role }+ properties: { memberType: member.actor.type, role: member.role }}));- return { members: memberships, skipped };+ return { members, skipped };}});server.route({method: "PATCH",- url: "/users/:userId",+ url: "/:actorType/:actorId",config: { rateLimit: writeLimit },schema: {- operationId: "updateAgentVaultProductUserMemberRole",- description: "Change a user's Agent Vault role",- tags: [ApiDocsTags.AgentVaultMemberships],- params: z.object({ userId: z.string().uuid().describe(AGENT_VAULT.MEMBER.userId) }),- body: z.object({ role: ProductRoleSchema }),- response: { 200: MemberResultSchema.omit({ createdAt: true }) }+ operationId: "updateAgentVaultMemberRole",+ description: "Change a member's Agent Vault role",+ tags: [ApiDocsTags.AgentVaultMembers],+ params: z.object({+ actorType: z.enum(ACTOR_TYPE_SEGMENTS).describe(AGENT_VAULT.MEMBER.actorType),+ actorId: z.string().uuid().describe(AGENT_VAULT.MEMBER.actorId)+ }),+ body: z.object({ role: AgentVaultProductRoleSchema }),+ response: { 200: z.object({ member: AgentVaultProductMemberRefSchema }) }},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),handler: async (req) => {- const member = await server.services.agentVaultMembership.updateProductMemberRole({+ const actor = { type: ACTOR_TYPE_OF[req.params.actorType], id: req.params.actorId };+ const { member } = await server.services.agentVaultMembership.updateProductMemberRole({projectId: req.internalAgentVaultProjectId,- userId: req.params.userId,+ actor,role: req.body.role,ctx: actorContext(req)});@@ -204,309 +146,72 @@ export const registerAgentVaultMembershipRouter = async (server: FastifyZodProvievent: {type: EventType.AGENT_VAULT_MEMBER_UPDATE,metadata: {- userId: req.params.userId,- userName: member.userName,- role: req.body.role+ ...auditActorFields(member.actor),+ ...auditActorNameFields(member.actor, member.actorName),+ role: member.role}}});emitAgentVaultTelemetry(server.services.telemetry, req, {event: PostHogEventTypes.AgentVaultProductMemberUpdated,- properties: { memberType: "user", role: req.body.role }- });-- return member;- }- });-- server.route({- method: "DELETE",- url: "/users/:userId",- config: { rateLimit: writeLimit },- schema: {- operationId: "removeAgentVaultProductUserMember",- description: "Remove a user from Agent Vault, and with it every bundle they hold",- tags: [ApiDocsTags.AgentVaultMemberships],- params: z.object({ userId: z.string().uuid().describe(AGENT_VAULT.MEMBER.userId) }),- response: { 200: MemberResultSchema.pick({ membershipId: true, userId: true }) }- },- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),- handler: async (req) => {- const removed = await server.services.agentVaultMembership.removeProductMember({- projectId: req.internalAgentVaultProjectId,- userId: req.params.userId,- ctx: actorContext(req)- });-- await server.services.auditLog.createAuditLog({- ...req.auditLogInfo,- orgId: req.permission.orgId,- projectId: req.internalAgentVaultProjectId,- event: {- type: EventType.AGENT_VAULT_MEMBER_REMOVE,- metadata: { userId: req.params.userId, userName: removed.userName }- }- });-- emitAgentVaultTelemetry(server.services.telemetry, req, {- event: PostHogEventTypes.AgentVaultProductMemberRemoved,- properties: { memberType: "user" }+ properties: { memberType: member.actor.type, role: member.role }});- return { membershipId: removed.membershipId, userId: req.params.userId };+ return { member };}});server.route({method: "POST",- url: "/groups/:groupId",- config: { rateLimit: writeLimit },- schema: {- operationId: "addAgentVaultProductGroupMember",- description: "Give a group access to Agent Vault",- tags: [ApiDocsTags.AgentVaultMemberships],- params: z.object({ groupId: z.string().uuid().describe(AGENT_VAULT.MEMBER.groupId) }),- body: z.object({ role: ProductRoleSchema }),- response: { 200: MemberResultSchema }- },- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),- handler: async (req) => {- const member = await server.services.agentVaultMembership.addProductMember({- projectId: req.internalAgentVaultProjectId,- groupId: req.params.groupId,- role: req.body.role,- ctx: actorContext(req)- });-- await server.services.auditLog.createAuditLog({- ...req.auditLogInfo,- orgId: req.permission.orgId,- projectId: req.internalAgentVaultProjectId,- event: {- type: EventType.AGENT_VAULT_MEMBER_ADD,- metadata: {- groupId: req.params.groupId,- groupName: member.groupName,- role: req.body.role- }- }- });-- emitAgentVaultTelemetry(server.services.telemetry, req, {- event: PostHogEventTypes.AgentVaultProductMemberAdded,- properties: { memberType: "group", role: req.body.role }- });-- return member;- }- });-- server.route({- method: "PATCH",- url: "/groups/:groupId",+ url: "/revoke",config: { rateLimit: writeLimit },schema: {- operationId: "updateAgentVaultProductGroupMemberRole",- description: "Change a group's Agent Vault role",- tags: [ApiDocsTags.AgentVaultMemberships],- params: z.object({ groupId: z.string().uuid().describe(AGENT_VAULT.MEMBER.groupId) }),- body: z.object({ role: ProductRoleSchema }),- response: { 200: MemberResultSchema.omit({ createdAt: true }) }- },- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),- handler: async (req) => {- const member = await server.services.agentVaultMembership.updateProductMemberRole({- projectId: req.internalAgentVaultProjectId,- groupId: req.params.groupId,- role: req.body.role,- ctx: actorContext(req)- });-- await server.services.auditLog.createAuditLog({- ...req.auditLogInfo,- orgId: req.permission.orgId,- projectId: req.internalAgentVaultProjectId,- event: {- type: EventType.AGENT_VAULT_MEMBER_UPDATE,- metadata: {- groupId: req.params.groupId,- groupName: member.groupName,- role: req.body.role- }- }- });-- emitAgentVaultTelemetry(server.services.telemetry, req, {- event: PostHogEventTypes.AgentVaultProductMemberUpdated,- properties: { memberType: "group", role: req.body.role }- });-- return member;- }- });-- server.route({- method: "DELETE",- url: "/groups/:groupId",- config: { rateLimit: writeLimit },- schema: {- operationId: "removeAgentVaultProductGroupMember",- description: "Remove a group from Agent Vault, and with it every bundle they hold",- tags: [ApiDocsTags.AgentVaultMemberships],- params: z.object({ groupId: z.string().uuid().describe(AGENT_VAULT.MEMBER.groupId) }),- response: { 200: MemberResultSchema.pick({ membershipId: true, groupId: true }) }- },- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),- handler: async (req) => {- const removed = await server.services.agentVaultMembership.removeProductMember({- projectId: req.internalAgentVaultProjectId,- groupId: req.params.groupId,- ctx: actorContext(req)- });-- await server.services.auditLog.createAuditLog({- ...req.auditLogInfo,- orgId: req.permission.orgId,- projectId: req.internalAgentVaultProjectId,- event: {- type: EventType.AGENT_VAULT_MEMBER_REMOVE,- metadata: { groupId: req.params.groupId, groupName: removed.groupName }- }- });-- emitAgentVaultTelemetry(server.services.telemetry, req, {- event: PostHogEventTypes.AgentVaultProductMemberRemoved,- properties: { memberType: "group" }- });-- return { membershipId: removed.membershipId, groupId: req.params.groupId };- }- });-- server.route({- method: "POST",- url: "/identities/:identityId",- config: { rateLimit: writeLimit },- schema: {- operationId: "addAgentVaultProductIdentityMember",- description: "Give a machine identity access to Agent Vault",- tags: [ApiDocsTags.AgentVaultMemberships],- params: z.object({ identityId: z.string().uuid().describe(AGENT_VAULT.MEMBER.identityId) }),- body: z.object({ role: ProductRoleSchema }),- response: { 200: MemberResultSchema }- },- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),- handler: async (req) => {- const member = await server.services.agentVaultMembership.addProductMember({- projectId: req.internalAgentVaultProjectId,- identityId: req.params.identityId,- role: req.body.role,- ctx: actorContext(req)- });-- await server.services.auditLog.createAuditLog({- ...req.auditLogInfo,- orgId: req.permission.orgId,- projectId: req.internalAgentVaultProjectId,- event: {- type: EventType.AGENT_VAULT_MEMBER_ADD,- metadata: {- identityId: req.params.identityId,- identityName: member.identityName,- role: req.body.role- }- }- });-- emitAgentVaultTelemetry(server.services.telemetry, req, {- event: PostHogEventTypes.AgentVaultProductMemberAdded,- properties: { memberType: "identity", role: req.body.role }- });-- return member;- }- });-- server.route({- method: "PATCH",- url: "/identities/:identityId",- config: { rateLimit: writeLimit },- schema: {- operationId: "updateAgentVaultProductIdentityMemberRole",- description: "Change a machine identity's Agent Vault role",- tags: [ApiDocsTags.AgentVaultMemberships],- params: z.object({ identityId: z.string().uuid().describe(AGENT_VAULT.MEMBER.identityId) }),- body: z.object({ role: ProductRoleSchema }),- response: { 200: MemberResultSchema.omit({ createdAt: true }) }- },- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),- handler: async (req) => {- const member = await server.services.agentVaultMembership.updateProductMemberRole({- projectId: req.internalAgentVaultProjectId,- identityId: req.params.identityId,- role: req.body.role,- ctx: actorContext(req)- });-- await server.services.auditLog.createAuditLog({- ...req.auditLogInfo,- orgId: req.permission.orgId,- projectId: req.internalAgentVaultProjectId,- event: {- type: EventType.AGENT_VAULT_MEMBER_UPDATE,- metadata: {- identityId: req.params.identityId,- identityName: member.identityName,- role: req.body.role- }- }- });-- emitAgentVaultTelemetry(server.services.telemetry, req, {- event: PostHogEventTypes.AgentVaultProductMemberUpdated,- properties: { memberType: "identity", role: req.body.role }- });-- return member;- }- });-- server.route({- method: "DELETE",- url: "/identities/:identityId",- config: { rateLimit: writeLimit },- schema: {- operationId: "removeAgentVaultProductIdentityMember",- description: "Remove a machine identity from Agent Vault, and with it every bundle they hold",- tags: [ApiDocsTags.AgentVaultMemberships],- params: z.object({ identityId: z.string().uuid().describe(AGENT_VAULT.MEMBER.identityId) }),- response: { 200: MemberResultSchema.pick({ membershipId: true, identityId: true }) }+ operationId: "revokeAgentVaultMembers",+ // A deliberate REST deviation: DELETE cannot carry a body reliably, so bulk removal is a named action.+ description: "Remove members from Agent Vault, and with them every bundle they hold",+ tags: [ApiDocsTags.AgentVaultMembers],+ body: AgentVaultProductMemberIdsSchema,+ response: {+ 200: z.object({+ members: AgentVaultProductMemberRefSchema.omit({ role: true }).array(),+ skipped: AgentVaultSkippedActorSchema.array().describe(AGENT_VAULT.MEMBERSHIP.revokeSkipped)+ })+ }},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),handler: async (req) => {- const removed = await server.services.agentVaultMembership.removeProductMember({+ const { members, skipped } = await server.services.agentVaultMembership.revokeProductMembers({projectId: req.internalAgentVaultProjectId,- identityId: req.params.identityId,+ ...req.body,ctx: actorContext(req)});- await server.services.auditLog.createAuditLog({- ...req.auditLogInfo,- orgId: req.permission.orgId,- projectId: req.internalAgentVaultProjectId,- event: {- type: EventType.AGENT_VAULT_MEMBER_REMOVE,- metadata: { identityId: req.params.identityId, identityName: removed.identityName }- }- });+ await Promise.all(+ members.map((member) =>+ server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ orgId: req.permission.orgId,+ projectId: req.internalAgentVaultProjectId,+ event: {+ type: EventType.AGENT_VAULT_MEMBER_REMOVE,+ metadata: {+ ...auditActorFields(member.actor),+ ...auditActorNameFields(member.actor, member.actorName)+ }+ }+ })+ )+ );- emitAgentVaultTelemetry(server.services.telemetry, req, {- event: PostHogEventTypes.AgentVaultProductMemberRemoved,- properties: { memberType: "identity" }- });+ members.forEach((member) =>+ emitAgentVaultTelemetry(server.services.telemetry, req, {+ event: PostHogEventTypes.AgentVaultProductMemberRemoved,+ properties: { memberType: member.actor.type }+ })+ );- return { membershipId: removed.membershipId, identityId: req.params.identityId };+ return { members, skipped };}});};diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-proxy-agent-router.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-proxy-agent-router.tsindex 341dd8c1da..0b92195ce1 100644--- a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-proxy-agent-router.ts+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-proxy-agent-router.ts@@ -144,16 +144,26 @@ export const registerAgentVaultProxyAgentRouter = async (server: FastifyZodProviname: z.string(),accessBundleName: z.string(),hostPattern: z.string(),+ allowedMethods: z.string().array().nullable(),+ allowedPathPrefixes: z.string().array().nullable(),credential: z.discriminatedUnion("type", [- z.object({- type: z.literal("bearer"),- headerName: z.string(),- headerPrefix: z.string(),- value: z.string()- }),- z.object({ type: z.literal("basic"), username: z.string(), password: z.string() }),- z.object({ type: z.literal("passthrough") })- ])+ z+ .object({+ type: z.literal("bearer"),+ headerName: z.string(),+ headerPrefix: z.string(),+ value: z.string()+ })+ .describe(JSON.stringify({ title: "Bearer" })),+ z+ .object({ type: z.literal("basic"), username: z.string(), password: z.string() })+ .describe(JSON.stringify({ title: "Basic Auth" })),+ z.object({ type: z.literal("passthrough") }).describe(JSON.stringify({ title: "Pass-through" }))+ ]),+ customHeaders: z.object({ name: z.string(), prefix: z.string(), value: z.string() }).array(),+ substitutions: z+ .object({ placeholder: z.string(), surfaces: z.string().array(), value: z.string() })+ .array()}).array()})diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-proxy-router.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-proxy-router.tsindex efa84aa6cd..509d138e16 100644--- a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-proxy-router.ts+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-proxy-router.ts@@ -1,7 +1,5 @@-import { FastifyRequest } from "fastify";import { z } from "zod";-import { TAgentVaultActorContext } from "@app/ee/services/agent-vault/agent-vault-actor-types";import { AgentVaultTrafficPolicy } from "@app/ee/services/agent-vault/agent-vault-enums";import { buildHostPatternSchema, parseHostPatterns } from "@app/ee/services/agent-vault/agent-vault-host-pattern";import { EventType } from "@app/ee/services/audit-log/audit-log-types";@@ -14,12 +12,8 @@ import { verifyAuth } from "@app/server/plugins/auth/verify-auth";import { AuthMode } from "@app/services/auth/auth-type";import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";-const actorContext = (req: FastifyRequest): TAgentVaultActorContext => ({- actorId: req.permission.id,- actor: req.permission.type,- actorOrgId: req.permission.orgId,- actorAuthMethod: req.permission.authMethod-});+import { actorContext } from "./agent-vault-router-fns";+import { agentVaultListQuery } from "./agent-vault-schemas";const ProxyMemberViewSchema = z.object({id: z.string().uuid().describe(AGENT_VAULT.PROXY.proxyId),@@ -34,8 +28,8 @@ const ProxyAdminViewSchema = ProxyMemberViewSchema.extend({trafficPolicy: z.nativeEnum(AgentVaultTrafficPolicy).describe(AGENT_VAULT.PROXY.trafficPolicy),allowedHosts: z.string().nullable().describe(AGENT_VAULT.PROXY.allowedHosts),pollInterval: z.number().describe(AGENT_VAULT.PROXY.pollInterval),- createdAt: z.date()-});+ createdAt: z.date().describe(AGENT_VAULT.PROXY.createdAt)+}).describe(JSON.stringify({ title: "Admin view" }));const EnrollmentSchema = z.object({token: z.string().describe(AGENT_VAULT.PROXY.enrollmentToken),@@ -57,16 +51,27 @@ export const registerAgentVaultProxyRouter = async (server: FastifyZodProvider)operationId: "listAgentVaultProxies",description: "List the organization's Agent Vault proxies",tags: [ApiDocsTags.AgentVaultProxies],- response: { 200: z.object({ proxies: z.union([ProxyAdminViewSchema, ProxyMemberViewSchema]).array() }) }+ querystring: z.object({+ orderBy: z.enum(["name", "createdAt"]).default("createdAt").describe(AGENT_VAULT.PROXY.orderBy),+ orderDirection: z.enum(["asc", "desc"]).default("desc").describe(AGENT_VAULT.PROXY.orderDirection),+ ...agentVaultListQuery(AGENT_VAULT.PROXY)+ }),+ response: {+ 200: z.object({+ proxies: z+ .union([ProxyAdminViewSchema, ProxyMemberViewSchema.describe(JSON.stringify({ title: "Member view" }))])+ .array(),+ totalCount: z.number()+ })+ }},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),- handler: async (req) => {- const proxies = await server.services.agentVaultProxy.listProxies({+ handler: async (req) =>+ server.services.agentVaultProxy.listProxies({projectId: req.internalAgentVaultProjectId,- ctx: actorContext(req)- });- return { proxies };- }+ ctx: actorContext(req),+ ...req.query+ })});server.route({@@ -215,7 +220,7 @@ export const registerAgentVaultProxyRouter = async (server: FastifyZodProvider)server.route({method: "POST",- url: "/:proxyId/token-auth/generate-enrollment-token",+ url: "/:proxyId/token-auth/enrollment-token",config: { rateLimit: writeLimit },schema: {operationId: "reissueAgentVaultProxyEnrollmentToken",diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-router-fns.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-router-fns.tsnew file mode 100644index 0000000000..4f8e2e43ed--- /dev/null+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-router-fns.ts@@ -0,0 +1,17 @@+import { FastifyRequest } from "fastify";++import { TAgentVaultActorContext } from "@app/ee/services/agent-vault/agent-vault-actor-types";+import { AgentVaultMemberType } from "@app/ee/services/agent-vault/agent-vault-enums";++export const actorContext = (req: FastifyRequest): TAgentVaultActorContext => ({+ actorId: req.permission.id,+ actor: req.permission.type,+ actorOrgId: req.permission.orgId,+ actorAuthMethod: req.permission.authMethod+});++export const auditActorFields = (actor: { type: AgentVaultMemberType; id: string }) => ({+ ...(actor.type === AgentVaultMemberType.User && { userId: actor.id }),+ ...(actor.type === AgentVaultMemberType.MachineIdentity && { machineIdentityId: actor.id }),+ ...(actor.type === AgentVaultMemberType.Group && { groupId: actor.id })+});diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-schemas.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-schemas.tsindex 971f63e6a4..698bc41079 100644--- a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-schemas.ts+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-schemas.ts@@ -1,13 +1,29 @@import { z } from "zod";+import { ProjectMembershipRole } from "@app/db/schemas";import {- AGENT_VAULT_HEADER_NAME_MESSAGE,- AGENT_VAULT_HEADER_NAME_RE,AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE,AGENT_VAULT_NO_CONTROL_CHARS_RE} from "@app/ee/services/agent-vault/agent-vault-credential-schemas";-import { AgentVaultCredentialType } from "@app/ee/services/agent-vault/agent-vault-enums";+import {+ AgentVaultCredentialType,+ AgentVaultHttpMethod,+ AgentVaultMemberType,+ AgentVaultSubstitutionSurface+} from "@app/ee/services/agent-vault/agent-vault-enums";import { hostPatternSchema } from "@app/ee/services/agent-vault/agent-vault-host-pattern";+import { agentVaultPathPrefixListSchema } from "@app/ee/services/agent-vault/agent-vault-path-prefix";+import {+ addDuplicateCustomHeaderNameIssues,+ addDuplicatePlaceholderIssues,+ AGENT_VAULT_MAX_CUSTOM_HEADERS,+ AGENT_VAULT_MAX_SUBSTITUTIONS,+ AgentVaultCustomHeaderInputSchema,+ AgentVaultCustomHeaderUpdateSchema,+ agentVaultHeaderNameSchema,+ AgentVaultSubstitutionInputSchema,+ AgentVaultSubstitutionUpdateSchema+} from "@app/ee/services/agent-vault/agent-vault-transformation-schemas";import { AGENT_VAULT_MAX_GRANTEES } from "@app/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service";import { AGENT_VAULT } from "@app/lib/api-docs";import { slugSchema } from "@app/server/lib/schemas";@@ -35,155 +51,389 @@ const basicHalvesAreNotBothEmpty = (export const AgentVaultCredentialInputSchema = z.discriminatedUnion("type", [- z.object({- type: z.literal(AgentVaultCredentialType.Bearer),- headerName: z- .string()- .trim()- .min(1)- .max(128)- .regex(AGENT_VAULT_HEADER_NAME_RE, AGENT_VAULT_HEADER_NAME_MESSAGE)- .optional()- .describe(AGENT_VAULT.SERVICE.headerName),- headerPrefix: z- .string()- .trim()- .max(64)- .regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)- .optional()- .describe(AGENT_VAULT.SERVICE.headerPrefix),- value: z- .string()- .min(1)- .max(8192)- .regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)- .describe(AGENT_VAULT.SERVICE.value)- }),- z.object({- type: z.literal(AgentVaultCredentialType.Basic),- username: z.string().trim().max(256).describe(AGENT_VAULT.SERVICE.username),- password: z- .string()- .max(8192)- .regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)- .describe(AGENT_VAULT.SERVICE.password)- }),- z.object({ type: z.literal(AgentVaultCredentialType.Passthrough) })+ z+ .object({+ type: z.literal(AgentVaultCredentialType.Bearer),+ headerName: agentVaultHeaderNameSchema.optional().describe(AGENT_VAULT.SERVICE.headerName),+ headerPrefix: z+ .string()+ .trim()+ .max(64)+ .regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)+ .optional()+ .describe(AGENT_VAULT.SERVICE.headerPrefix),+ value: z+ .string()+ .min(1)+ .max(8192)+ .regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)+ .describe(AGENT_VAULT.SERVICE.value)+ })+ .describe(JSON.stringify({ title: "Bearer" })),+ z+ .object({+ type: z.literal(AgentVaultCredentialType.Basic),+ username: z+ .string()+ .trim()+ .max(256)+ .regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)+ .describe(AGENT_VAULT.SERVICE.username),+ password: z+ .string()+ .max(8192)+ .regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)+ .describe(AGENT_VAULT.SERVICE.password)+ })+ .describe(JSON.stringify({ title: "Basic Auth" })),+ z+ .object({ type: z.literal(AgentVaultCredentialType.Passthrough) })+ .describe(JSON.stringify({ title: "Pass-through" }))]).superRefine(basicHalvesAreNotBothEmpty);// Not derived from the create schema: its `.default()`s would turn an omitted field into a reset on a PATCH.export const AgentVaultCredentialUpdateSchema = z.discriminatedUnion("type", [- z.object({- type: z.literal(AgentVaultCredentialType.Bearer),- headerName: z- .string()- .trim()- .min(1)- .max(128)- .regex(AGENT_VAULT_HEADER_NAME_RE, AGENT_VAULT_HEADER_NAME_MESSAGE)- .optional()- .describe(AGENT_VAULT.SERVICE.headerName),- headerPrefix: z- .string()- .trim()- .max(64)- .regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)- .optional()- .describe(AGENT_VAULT.SERVICE.headerPrefix),- value: z- .string()- .min(1)- .max(8192)- .regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)- .optional()- .describe(AGENT_VAULT.SERVICE.updateValue)- }),- z.object({- type: z.literal(AgentVaultCredentialType.Basic),- username: z.string().trim().max(256).optional().describe(AGENT_VAULT.SERVICE.updateUsername),- password: z- .string()- .max(8192)- .regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)- .optional()- .describe(AGENT_VAULT.SERVICE.updatePassword)- }),- z.object({ type: z.literal(AgentVaultCredentialType.Passthrough) })+ z+ .object({+ type: z.literal(AgentVaultCredentialType.Bearer),+ headerName: agentVaultHeaderNameSchema.optional().describe(AGENT_VAULT.SERVICE.headerName),+ headerPrefix: z+ .string()+ .trim()+ .max(64)+ .regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)+ .optional()+ .describe(AGENT_VAULT.SERVICE.headerPrefix),+ value: z+ .string()+ .min(1)+ .max(8192)+ .regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)+ .optional()+ .describe(AGENT_VAULT.SERVICE.updateValue)+ })+ .describe(JSON.stringify({ title: "Bearer" })),+ z+ .object({+ type: z.literal(AgentVaultCredentialType.Basic),+ username: z+ .string()+ .trim()+ .max(256)+ .regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)+ .optional()+ .describe(AGENT_VAULT.SERVICE.updateUsername),+ password: z+ .string()+ .max(8192)+ .regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)+ .optional()+ .describe(AGENT_VAULT.SERVICE.updatePassword)+ })+ .describe(JSON.stringify({ title: "Basic Auth" })),+ z+ .object({ type: z.literal(AgentVaultCredentialType.Passthrough) })+ .describe(JSON.stringify({ title: "Pass-through" }))]).superRefine(basicHalvesAreNotBothEmpty);export const AgentVaultCredentialSummarySchema = z.discriminatedUnion("type", [- z.object({- type: z.literal(AgentVaultCredentialType.Bearer),- headerName: z.string().describe(AGENT_VAULT.SERVICE.headerName),- headerPrefix: z.string().describe(AGENT_VAULT.SERVICE.headerPrefix)- }),- z.object({ type: z.literal(AgentVaultCredentialType.Basic) }),- z.object({ type: z.literal(AgentVaultCredentialType.Passthrough) })+ z+ .object({+ type: z.literal(AgentVaultCredentialType.Bearer),+ headerName: z.string().describe(AGENT_VAULT.SERVICE.headerName),+ headerPrefix: z.string().describe(AGENT_VAULT.SERVICE.headerPrefix)+ })+ .describe(JSON.stringify({ title: "Bearer" })),+ z.object({ type: z.literal(AgentVaultCredentialType.Basic) }).describe(JSON.stringify({ title: "Basic Auth" })),+ z+ .object({ type: z.literal(AgentVaultCredentialType.Passthrough) })+ .describe(JSON.stringify({ title: "Pass-through" }))]);+export const AgentVaultAllowedMethodsSchema = z+ .array(z.nativeEnum(AgentVaultHttpMethod))+ .min(1, "Pick at least one method, or leave this unset to allow every method.")+ .max(Object.keys(AgentVaultHttpMethod).length)+ .transform((methods) => [...new Set(methods)])+ .nullable()+ .describe(AGENT_VAULT.SERVICE.allowedMethods);++export const AgentVaultAllowedPathPrefixesSchema = agentVaultPathPrefixListSchema.describe(+ AGENT_VAULT.SERVICE.allowedPathPrefixes+);++export const AgentVaultCustomHeadersInputSchema = AgentVaultCustomHeaderInputSchema.array()+ .max(AGENT_VAULT_MAX_CUSTOM_HEADERS)+ .superRefine(addDuplicateCustomHeaderNameIssues)+ .describe(AGENT_VAULT.SERVICE.customHeaders);++export const AgentVaultCustomHeadersUpdateSchema = AgentVaultCustomHeaderUpdateSchema.array()+ .max(AGENT_VAULT_MAX_CUSTOM_HEADERS)+ .superRefine(addDuplicateCustomHeaderNameIssues)+ .describe(AGENT_VAULT.SERVICE.customHeaders);++export const AgentVaultSubstitutionsInputSchema = AgentVaultSubstitutionInputSchema.array()+ .max(AGENT_VAULT_MAX_SUBSTITUTIONS)+ .superRefine(addDuplicatePlaceholderIssues)+ .describe(AGENT_VAULT.SERVICE.substitutions);++export const AgentVaultSubstitutionsUpdateSchema = AgentVaultSubstitutionUpdateSchema.array()+ .max(AGENT_VAULT_MAX_SUBSTITUTIONS)+ .superRefine(addDuplicatePlaceholderIssues)+ .describe(AGENT_VAULT.SERVICE.substitutions);++// The sealed value is never in here. This schema is the last thing between the encrypted column and the+// wire on every service route: the serializer emits `result.data`, so anything absent here is dropped,+// and anything required here but missing from a projection is a 500 rather than a leak.export const AgentVaultServiceSchema = z.object({id: z.string().uuid().describe(AGENT_VAULT.SERVICE.serviceId),accessBundleId: z.string().uuid().describe(AGENT_VAULT.ACCESS_BUNDLE.accessBundleId),name: z.string().describe(AGENT_VAULT.SERVICE.name),hostPattern: z.string().describe(AGENT_VAULT.SERVICE.hostPattern),+ allowedMethods: z.nativeEnum(AgentVaultHttpMethod).array().nullable().describe(AGENT_VAULT.SERVICE.allowedMethods),+ allowedPathPrefixes: z.string().array().nullable().describe(AGENT_VAULT.SERVICE.allowedPathPrefixes),credential: AgentVaultCredentialSummarySchema,- createdAt: z.date().describe(AGENT_VAULT.SERVICE.createdAt)+ customHeaders: z+ .object({+ id: z.string().uuid().describe(AGENT_VAULT.SERVICE.customHeaderId),+ name: z.string().describe(AGENT_VAULT.SERVICE.customHeaderName),+ prefix: z.string().describe(AGENT_VAULT.SERVICE.customHeaderPrefix)+ })+ .array()+ .describe(AGENT_VAULT.SERVICE.customHeaders),+ substitutions: z+ .object({+ id: z.string().uuid().describe(AGENT_VAULT.SERVICE.substitutionId),+ placeholder: z.string().describe(AGENT_VAULT.SERVICE.placeholder),+ surfaces: z.nativeEnum(AgentVaultSubstitutionSurface).array().describe(AGENT_VAULT.SERVICE.surfaces)+ })+ .array()+ .describe(AGENT_VAULT.SERVICE.substitutions),+ createdAt: z.date().describe(AGENT_VAULT.SERVICE.createdAt),+ updatedAt: z.date().describe(AGENT_VAULT.SERVICE.updatedAt)});-// One list per actor type rather than a list of one-of-three objects: the field name carries the type,-// so nothing has to be validated after parsing, and the grant stays a single atomic request.+const memberIdsShape = (docs: { userIds: string; machineIdentityIds: string; groupIds: string }) => ({+ userIds: z.string().uuid().array().default([]).describe(docs.userIds),+ machineIdentityIds: z.string().uuid().array().default([]).describe(docs.machineIdentityIds),+ groupIds: z.string().uuid().array().default([]).describe(docs.groupIds)+});++const namedCount = (body: { userIds: string[]; machineIdentityIds: string[]; groupIds: string[]; emails?: string[] }) =>+ body.userIds.length + body.machineIdentityIds.length + body.groupIds.length + (body.emails?.length ?? 0);++export const AgentVaultProductRoleSchema = z+ .enum([ProjectMembershipRole.Admin, ProjectMembershipRole.Member])+ .describe(AGENT_VAULT.MEMBERSHIP.role);++const atLeastOne = "Name at least one user, machine identity, or group";++const atMost = (action: string) =>+ `${action} at most ${AGENT_VAULT_MAX_GRANTEES} users, machine identities, and groups at a time`;++// .refine returns a ZodEffects nothing can be extended after, so the bounds go on last and each schema+// repeats them rather than sharing a helper.export const AgentVaultMemberIdsSchema = z+ .object(+ memberIdsShape({+ userIds: AGENT_VAULT.MEMBER.userIds,+ machineIdentityIds: AGENT_VAULT.MEMBER.machineIdentityIds,+ groupIds: AGENT_VAULT.MEMBER.groupIds+ })+ )+ .refine((body) => namedCount(body) > 0, atLeastOne)+ .refine((body) => namedCount(body) <= AGENT_VAULT_MAX_GRANTEES, atMost("Grant an access bundle to"));++export const AgentVaultProductMemberIdsSchema = z+ .object(+ memberIdsShape({+ userIds: AGENT_VAULT.MEMBERSHIP.userIds,+ machineIdentityIds: AGENT_VAULT.MEMBERSHIP.machineIdentityIds,+ groupIds: AGENT_VAULT.MEMBERSHIP.groupIds+ })+ )+ .refine((body) => namedCount(body) > 0, atLeastOne)+ .refine((body) => namedCount(body) <= AGENT_VAULT_MAX_GRANTEES, atMost("Act on"));++// One object, not an intersection: zod parses each side on its own, so the id side would strip emails+// before the refines ran, failing an emails-only body and leaving the cap blind to them.+export const AgentVaultProductMemberAddSchema = z.object({- userIds: z.string().uuid().array().default([]).describe(AGENT_VAULT.MEMBER.userIds),- identityIds: z.string().uuid().array().default([]).describe(AGENT_VAULT.MEMBER.identityIds),- groupIds: z.string().uuid().array().default([]).describe(AGENT_VAULT.MEMBER.groupIds)+ ...memberIdsShape({+ userIds: AGENT_VAULT.MEMBERSHIP.userIds,+ machineIdentityIds: AGENT_VAULT.MEMBERSHIP.machineIdentityIds,+ groupIds: AGENT_VAULT.MEMBERSHIP.groupIds+ }),+ emails: z+ .string()+ .email()+ .array()+ .default([])+ .refine((val) => val.every((el) => el === el.toLowerCase()), "Email must be lowercase")+ .describe(AGENT_VAULT.MEMBERSHIP.emails),+ role: z.enum([ProjectMembershipRole.Admin, ProjectMembershipRole.Member]).describe(AGENT_VAULT.MEMBERSHIP.role)})- .refine(- (body) => body.userIds.length + body.identityIds.length + body.groupIds.length > 0,- "Name at least one user, machine identity, or group"+ .refine((body) => namedCount(body) > 0, atLeastOne)+ .refine((body) => namedCount(body) <= AGENT_VAULT_MAX_GRANTEES, atMost("Act on"));++export const AgentVaultMemberRevokeIdsSchema = z+ .object(+ memberIdsShape({+ userIds: AGENT_VAULT.MEMBER.revokeUserIds,+ machineIdentityIds: AGENT_VAULT.MEMBER.revokeMachineIdentityIds,+ groupIds: AGENT_VAULT.MEMBER.revokeGroupIds+ }))- .refine(- (body) => body.userIds.length + body.identityIds.length + body.groupIds.length <= AGENT_VAULT_MAX_GRANTEES,- `Grant an access bundle to at most ${AGENT_VAULT_MAX_GRANTEES} users, machine identities, and groups at a time`- );+ .refine((body) => namedCount(body) > 0, atLeastOne)+ .refine((body) => namedCount(body) <= AGENT_VAULT_MAX_GRANTEES, atMost("Revoke an access bundle from"));++const actorTypeSchema = <T extends AgentVaultMemberType>(type: T) =>+ z.literal(type).describe(AGENT_VAULT.MEMBER.actorType);++const actorIdSchema = z.string().uuid().describe(AGENT_VAULT.MEMBER.actorId);++export const AgentVaultActorRefSchema = z.discriminatedUnion("type", [+ z+ .object({ type: actorTypeSchema(AgentVaultMemberType.User), id: actorIdSchema })+ .describe(JSON.stringify({ title: "User" })),+ z+ .object({ type: actorTypeSchema(AgentVaultMemberType.MachineIdentity), id: actorIdSchema })+ .describe(JSON.stringify({ title: "Machine identity" })),+ z+ .object({ type: actorTypeSchema(AgentVaultMemberType.Group), id: actorIdSchema })+ .describe(JSON.stringify({ title: "Group" }))+]);++export const AgentVaultActorSchema = z.discriminatedUnion("type", [+ z+ .object({+ type: actorTypeSchema(AgentVaultMemberType.User),+ id: actorIdSchema,+ username: z.string().describe(AGENT_VAULT.MEMBER.username),+ email: z.string().nullable().describe(AGENT_VAULT.MEMBER.email),+ firstName: z.string().nullable().describe(AGENT_VAULT.MEMBER.firstName),+ lastName: z.string().nullable().describe(AGENT_VAULT.MEMBER.lastName)+ })+ .describe(JSON.stringify({ title: "User" })),+ z+ .object({+ type: actorTypeSchema(AgentVaultMemberType.MachineIdentity),+ id: actorIdSchema,+ name: z.string().describe(AGENT_VAULT.MEMBER.identityName)+ })+ .describe(JSON.stringify({ title: "Machine identity" })),+ z+ .object({+ type: actorTypeSchema(AgentVaultMemberType.Group),+ id: actorIdSchema,+ name: z.string().describe(AGENT_VAULT.MEMBER.groupName)+ })+ .describe(JSON.stringify({ title: "Group" }))+]);++// No .default().optional(): the optional wraps the default and the default never applies.+export const agentVaultListQuery = (docs: { search: string; limit: string; offset: string }) => ({+ search: z+ .string()+ .trim()+ .max(255)+ .regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)+ .optional()+ .describe(docs.search),+ limit: z.coerce.number().int().min(1).max(100).default(20).describe(docs.limit),+ offset: z.coerce.number().int().min(0).max(10000).default(0).describe(docs.offset)+});++export const AgentVaultProductActorSchema = z.discriminatedUnion("type", [+ z+ .object({+ type: actorTypeSchema(AgentVaultMemberType.User),+ id: actorIdSchema,+ username: z.string().describe(AGENT_VAULT.MEMBER.username),+ email: z.string().nullable().describe(AGENT_VAULT.MEMBER.email),+ firstName: z.string().nullable().describe(AGENT_VAULT.MEMBER.firstName),+ lastName: z.string().nullable().describe(AGENT_VAULT.MEMBER.lastName),+ isOrgMembershipPending: z.boolean().describe(AGENT_VAULT.MEMBER.isOrgMembershipPending)+ })+ .describe(JSON.stringify({ title: "User" })),+ z+ .object({+ type: actorTypeSchema(AgentVaultMemberType.MachineIdentity),+ id: actorIdSchema,+ name: z.string().describe(AGENT_VAULT.MEMBER.identityName),+ isManagedByAgentVault: z.boolean().describe(AGENT_VAULT.MEMBER.isManagedByAgentVault),+ orgId: z.string().uuid().nullable().describe(AGENT_VAULT.MEMBER.machineIdentityOrgId)+ })+ .describe(JSON.stringify({ title: "Machine identity" })),+ z+ .object({+ type: actorTypeSchema(AgentVaultMemberType.Group),+ id: actorIdSchema,+ name: z.string().describe(AGENT_VAULT.MEMBER.groupName)+ })+ .describe(JSON.stringify({ title: "Group" }))+]);++export const AgentVaultProductMemberSchema = z.object({+ id: z.string().uuid().describe(AGENT_VAULT.MEMBER.memberId),+ // Not the two-value input enum: the generic project membership routes reach these same rows, so one can+ // carry any role slug, and narrowing this would fail the whole list rather than render it.+ role: z.string().describe(AGENT_VAULT.MEMBERSHIP.role),+ isActive: z.boolean().describe(AGENT_VAULT.MEMBERSHIP.isActive),+ createdAt: z.date().describe(AGENT_VAULT.MEMBER.createdAt),+ actor: AgentVaultProductActorSchema+});++export const AgentVaultProductMemberRefSchema = z.object({+ id: z.string().uuid().describe(AGENT_VAULT.MEMBER.memberId),+ role: z.string().describe(AGENT_VAULT.MEMBERSHIP.role),+ createdAt: z.date().describe(AGENT_VAULT.MEMBER.createdAt),+ actor: AgentVaultActorRefSchema+});++export const AgentVaultSkippedActorSchema = z.discriminatedUnion("type", [+ z+ .object({+ type: actorTypeSchema(AgentVaultMemberType.User),+ id: actorIdSchema,+ identifier: z.string().describe(AGENT_VAULT.MEMBERSHIP.identifier)+ })+ .describe(JSON.stringify({ title: "User" })),+ z+ .object({+ type: actorTypeSchema(AgentVaultMemberType.MachineIdentity),+ id: actorIdSchema,+ identifier: z.string().describe(AGENT_VAULT.MEMBERSHIP.identifier)+ })+ .describe(JSON.stringify({ title: "Machine identity" })),+ z+ .object({+ type: actorTypeSchema(AgentVaultMemberType.Group),+ id: actorIdSchema,+ identifier: z.string().describe(AGENT_VAULT.MEMBERSHIP.identifier)+ })+ .describe(JSON.stringify({ title: "Group" }))+]);-// A removed grant is gone, so this reports the row's own columns rather than joining the actor's name,-// the way every other membership delete on the platform does.export const AgentVaultRemovedMemberSchema = z.object({id: z.string().uuid().describe(AGENT_VAULT.MEMBER.memberId),accessBundleId: z.string().uuid().describe(AGENT_VAULT.ACCESS_BUNDLE.accessBundleId),- userId: z.string().uuid().nullable().describe(AGENT_VAULT.MEMBER.userId),- identityId: z.string().uuid().nullable().describe(AGENT_VAULT.MEMBER.identityId),- groupId: z.string().uuid().nullable().describe(AGENT_VAULT.MEMBER.groupId),- createdAt: z.date()+ createdAt: z.date().describe(AGENT_VAULT.MEMBER.createdAt),+ actor: AgentVaultActorRefSchema});export const AgentVaultMemberSchema = z.object({id: z.string().uuid().describe(AGENT_VAULT.MEMBER.memberId),- userId: z.string().uuid().nullable().describe(AGENT_VAULT.MEMBER.userId),- identityId: z.string().uuid().nullable().describe(AGENT_VAULT.MEMBER.identityId),- groupId: z.string().uuid().nullable().describe(AGENT_VAULT.MEMBER.groupId),- createdAt: z.date(),- user: z- .object({- username: z.string(),- email: z.string().nullable(),- firstName: z.string().nullable(),- lastName: z.string().nullable()- })- .nullable(),- identity: z.object({ name: z.string() }).nullable(),- group: z.object({ name: z.string() }).nullable()+ createdAt: z.date().describe(AGENT_VAULT.MEMBER.createdAt),+ actor: AgentVaultActorSchema});export const AgentVaultCreatedMemberSchema = z.object({id: z.string().uuid().describe(AGENT_VAULT.MEMBER.memberId),accessBundleId: z.string().uuid().describe(AGENT_VAULT.ACCESS_BUNDLE.accessBundleId),- userId: z.string().uuid().nullable().describe(AGENT_VAULT.MEMBER.userId),- identityId: z.string().uuid().nullable().describe(AGENT_VAULT.MEMBER.identityId),- groupId: z.string().uuid().nullable().describe(AGENT_VAULT.MEMBER.groupId),- createdAt: z.date()+ createdAt: z.date().describe(AGENT_VAULT.MEMBER.createdAt),+ actor: AgentVaultActorRefSchema});diff --git a/backend/src/ee/routes/v1/agent-vault-routers/index.ts b/backend/src/ee/routes/v1/agent-vault-routers/index.tsindex dabe1544dc..fb892bd07d 100644--- a/backend/src/ee/routes/v1/agent-vault-routers/index.ts+++ b/backend/src/ee/routes/v1/agent-vault-routers/index.ts@@ -10,7 +10,7 @@ export const registerAgentVaultRouters = async (server: FastifyZodProvider) => {await server.register(registerAgentVaultAccessBundleRouter, { prefix: "/access-bundles" });await server.register(registerAgentVaultSessionRouter, { prefix: "/sessions" });await server.register(registerAgentVaultProxyRouter, { prefix: "/proxies" });- await server.register(registerAgentVaultMembershipRouter, { prefix: "/memberships" });+ await server.register(registerAgentVaultMembershipRouter, { prefix: "/members" });// Separate prefix so the preValidation project hook still matches while these routes authenticate as the proxy.await server.register(registerAgentVaultProxyAgentRouter, { prefix: "/proxy" });};diff --git a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-dal.ts b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-dal.tsindex f7acb98171..e653639375 100644--- a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-dal.ts+++ b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-dal.ts@@ -2,7 +2,9 @@ import { Knex } from "knex";import { TDbClient } from "@app/db";import { RESOURCE_SCOPE, ResourceType, TableName, TAgentVaultAccessBundles } from "@app/db/schemas";+import { AgentVaultMemberType } from "@app/ee/services/agent-vault/agent-vault-enums";import { DatabaseError } from "@app/lib/errors";+import { sanitizeSqlLikeString } from "@app/lib/fn/string";import { ormify } from "@app/lib/knex";export type TAgentVaultAccessBundleDALFactory = ReturnType<typeof agentVaultAccessBundleDALFactory>;@@ -12,21 +14,46 @@ export type TAgentVaultAccessBundleListRow = {name: string;description: string | null;createdAt: Date;+ updatedAt: Date;serviceCount: number;hostPatterns: string[];memberCount: number;};+export type TAgentVaultAccessBundleActorRef = {+ type: AgentVaultMemberType;+ id: string;+};++export type TAgentVaultAccessBundleActor =+ | {+ type: AgentVaultMemberType.User;+ id: string;+ username: string;+ email: string | null;+ firstName: string | null;+ lastName: string | null;+ }+ | { type: AgentVaultMemberType.MachineIdentity; id: string; name: string }+ | { type: AgentVaultMemberType.Group; id: string; name: string };+export type TAgentVaultAccessBundleMemberDetail = {id: string;accessBundleId: string;- userId: string | null;- identityId: string | null;- groupId: string | null;createdAt: Date;- user: { username: string; email: string | null; firstName: string | null; lastName: string | null } | null;- identity: { name: string } | null;- group: { name: string } | null;+ actor: TAgentVaultAccessBundleActor;+};++export type TAgentVaultAccessBundleOrderBy = "name" | "serviceCount" | "createdAt";++type TFindAccessBundlesDTO = {+ projectId: string;+ accessBundleIds: string[] | null;+ search?: string;+ orderBy: TAgentVaultAccessBundleOrderBy;+ orderDirection: "asc" | "desc";+ limit: number;+ offset: number;};const grantScope = (projectId: string, accessBundleId?: string) => ({@@ -39,15 +66,60 @@ const grantScope = (projectId: string, accessBundleId?: string) => ({export const agentVaultAccessBundleDALFactory = (db: TDbClient) => {const orm = ormify(db, TableName.AgentVaultAccessBundle);- const findWithCounts = async (- { projectId, accessBundleIds }: { projectId: string; accessBundleIds: string[] | null },+ const findForList = async (+ { projectId, accessBundleIds, search, orderBy, orderDirection, limit, offset }: TFindAccessBundlesDTO,tx?: Knex- ): Promise<TAgentVaultAccessBundleListRow[]> => {- if (accessBundleIds?.length === 0) return [];+ ): Promise<{ accessBundles: TAgentVaultAccessBundleListRow[]; totalCount: number }> => {+ if (accessBundleIds?.length === 0) return { accessBundles: [], totalCount: 0 };try {const conn = tx || db.replicaNode();+ // The page is chosen before the service join, which fans a bundle out per service: a LIMIT over that+ // would cut a bundle's services rather than the bundle list.+ const applyFilters = (query: Knex.QueryBuilder) => {+ void query.where(`${TableName.AgentVaultAccessBundle}.projectId`, projectId);+ if (accessBundleIds) void query.whereIn(`${TableName.AgentVaultAccessBundle}.id`, accessBundleIds);+ if (search) {+ const term = `%${sanitizeSqlLikeString(search)}%`;+ void query.where((qb) => {+ void qb+ .orWhereILike(`${TableName.AgentVaultAccessBundle}.name`, term)+ .orWhereILike(`${TableName.AgentVaultAccessBundle}.description`, term);+ });+ }+ return query;+ };++ const countResult = (await applyFilters(conn(TableName.AgentVaultAccessBundle))+ .count(`${TableName.AgentVaultAccessBundle}.id as count`)+ .first()) as { count: string } | undefined;+ const totalCount = parseInt(countResult?.count || "0", 10);++ const serviceCounts = conn(TableName.AgentVaultService)+ .select("accessBundleId")+ .count("* as count")+ .groupBy("accessBundleId")+ .as("sc");++ const pageQuery = applyFilters(conn(TableName.AgentVaultAccessBundle))+ .leftJoin(serviceCounts, function joinServiceCount() {+ this.on(db.raw(`sc."accessBundleId" = ??.id`, [TableName.AgentVaultAccessBundle]));+ })+ .limit(limit)+ .offset(offset)+ .select(db.ref("id").withSchema(TableName.AgentVaultAccessBundle));++ if (orderBy === "serviceCount") {+ void pageQuery.orderByRaw(`COALESCE(sc.count, 0) ${orderDirection === "desc" ? "DESC" : "ASC"}`);+ } else {+ void pageQuery.orderBy(`${TableName.AgentVaultAccessBundle}.${orderBy}`, orderDirection);+ }+ void pageQuery.orderBy(`${TableName.AgentVaultAccessBundle}.name`, "asc");++ const pageIds = ((await pageQuery) as { id: string }[]).map((row) => row.id);+ if (!pageIds.length) return { accessBundles: [], totalCount };+const memberCounts = conn(TableName.Membership).select("scopeResourceId").where({ ...grantScope(projectId), isActive: true })@@ -56,10 +128,7 @@ export const agentVaultAccessBundleDALFactory = (db: TDbClient) => {.as("mc");const rows = (await conn(TableName.AgentVaultAccessBundle)- .where(`${TableName.AgentVaultAccessBundle}.projectId`, projectId)- .where((qb) => {- if (accessBundleIds) void qb.whereIn(`${TableName.AgentVaultAccessBundle}.id`, accessBundleIds);- })+ .whereIn(`${TableName.AgentVaultAccessBundle}.id`, pageIds).leftJoin(TableName.AgentVaultService,`${TableName.AgentVaultService}.accessBundleId`,@@ -73,6 +142,7 @@ export const agentVaultAccessBundleDALFactory = (db: TDbClient) => {db.ref("name").withSchema(TableName.AgentVaultAccessBundle),db.ref("description").withSchema(TableName.AgentVaultAccessBundle),db.ref("createdAt").withSchema(TableName.AgentVaultAccessBundle),+ db.ref("updatedAt").withSchema(TableName.AgentVaultAccessBundle),db.ref("id").withSchema(TableName.AgentVaultService).as("serviceId"),db.ref("hostPattern").withSchema(TableName.AgentVaultService),db.raw('COALESCE(mc.count, 0)::int as "memberCount"')@@ -82,6 +152,7 @@ export const agentVaultAccessBundleDALFactory = (db: TDbClient) => {name: string;description: string | null;createdAt: Date;+ updatedAt: Date;serviceId: string | null;hostPattern: string | null;memberCount: number;@@ -96,6 +167,7 @@ export const agentVaultAccessBundleDALFactory = (db: TDbClient) => {name: row.name,description: row.description,createdAt: row.createdAt,+ updatedAt: row.updatedAt,serviceCount: 0,hostPatterns: [],memberCount: row.memberCount@@ -107,7 +179,12 @@ export const agentVaultAccessBundleDALFactory = (db: TDbClient) => {if (row.hostPattern) bundle.hostPatterns.push(...row.hostPattern.split(","));});- return [...byBundle.values()];+ // The fan-out query returns page rows in its own order, so the page order is reapplied here.+ const orderOfId = new Map(pageIds.map((id, index) => [id, index]));+ const accessBundles = [...byBundle.values()].sort(+ (a, b) => (orderOfId.get(a.id) ?? 0) - (orderOfId.get(b.id) ?? 0)+ );+ return { accessBundles, totalCount };} catch (error) {throw new DatabaseError({ error, name: "Find agent vault access bundles" });}@@ -138,15 +215,49 @@ export const agentVaultAccessBundleDALFactory = (db: TDbClient) => {};const findMembers = async (- { projectId, accessBundleId }: { projectId: string; accessBundleId: string },+ {+ projectId,+ accessBundleId,+ search,+ limit,+ offset+ }: { projectId: string; accessBundleId: string; search?: string; limit: number; offset: number },tx?: Knex- ): Promise<TAgentVaultAccessBundleMemberDetail[]> => {+ ): Promise<{ members: TAgentVaultAccessBundleMemberDetail[]; totalCount: number }> => {try {- const rows = (await (tx || db.replicaNode())(TableName.Membership)- .where({ ...grantScope(projectId, accessBundleId), isActive: true })- .leftJoin(TableName.Users, `${TableName.Membership}.actorUserId`, `${TableName.Users}.id`)- .leftJoin(TableName.Identity, `${TableName.Membership}.actorIdentityId`, `${TableName.Identity}.id`)- .leftJoin(TableName.Groups, `${TableName.Membership}.actorGroupId`, `${TableName.Groups}.id`)+ const conn = tx || db.replicaNode();++ const applyFilters = (query: Knex.QueryBuilder) => {+ void query+ .where({ ...grantScope(projectId, accessBundleId), isActive: true })+ .leftJoin(TableName.Users, `${TableName.Membership}.actorUserId`, `${TableName.Users}.id`)+ .leftJoin(TableName.Identity, `${TableName.Membership}.actorIdentityId`, `${TableName.Identity}.id`)+ .leftJoin(TableName.Groups, `${TableName.Membership}.actorGroupId`, `${TableName.Groups}.id`);++ if (search) {+ const term = `%${sanitizeSqlLikeString(search)}%`;+ void query.where((qb) => {+ void qb+ .orWhereILike(`${TableName.Users}.username`, term)+ .orWhereILike(`${TableName.Users}.email`, term)+ .orWhereRaw(`CONCAT_WS(' ', ??, ??) ILIKE ?`, [+ `${TableName.Users}.firstName`,+ `${TableName.Users}.lastName`,+ term+ ])+ .orWhereILike(`${TableName.Identity}.name`, term)+ .orWhereILike(`${TableName.Groups}.name`, term);+ });+ }+ return query;+ };++ const countResult = (await applyFilters(conn(TableName.Membership))+ .count(`${TableName.Membership}.id as count`)+ .first()) as { count: string } | undefined;+ const totalCount = parseInt(countResult?.count || "0", 10);++ const rows = (await applyFilters(conn(TableName.Membership)).select(db.ref("id").withSchema(TableName.Membership),db.ref("scopeResourceId").withSchema(TableName.Membership).as("accessBundleId"),@@ -161,7 +272,12 @@ export const agentVaultAccessBundleDALFactory = (db: TDbClient) => {db.ref("name").withSchema(TableName.Identity).as("identityName"),db.ref("name").withSchema(TableName.Groups).as("groupName"))- .orderBy(`${TableName.Membership}.createdAt`, "asc")) as {+ // The id breaks ties: createdAt is the transaction's start time, so a bulk grant leaves a hundred rows+ // sharing one, and offset paging would show some twice and others never.+ .orderBy(`${TableName.Membership}.createdAt`, "asc")+ .orderBy(`${TableName.Membership}.id`, "asc")+ .limit(limit)+ .offset(offset)) as {id: string;accessBundleId: string;userId: string | null;@@ -176,28 +292,36 @@ export const agentVaultAccessBundleDALFactory = (db: TDbClient) => {groupName: string | null;}[];- return rows.map((row) => ({- id: row.id,- accessBundleId: row.accessBundleId,- userId: row.userId,- identityId: row.identityId,- groupId: row.groupId,- createdAt: row.createdAt,- user: row.userId- ? {- username: row.userUsername ?? "",- email: row.userEmail,- firstName: row.userFirstName,- lastName: row.userLastName- }- : null,- identity: row.identityId ? { name: row.identityName ?? "" } : null,- group: row.groupId ? { name: row.groupName ?? "" } : null- }));+ const actorOf = (row: (typeof rows)[number]): TAgentVaultAccessBundleActor => {+ if (row.identityId) {+ return { type: AgentVaultMemberType.MachineIdentity, id: row.identityId, name: row.identityName ?? "" };+ }+ if (row.groupId) {+ return { type: AgentVaultMemberType.Group, id: row.groupId, name: row.groupName ?? "" };+ }+ return {+ type: AgentVaultMemberType.User,+ id: row.userId ?? "",+ username: row.userUsername ?? "",+ email: row.userEmail,+ firstName: row.userFirstName,+ lastName: row.userLastName+ };+ };++ return {+ members: rows.map((row) => ({+ id: row.id,+ accessBundleId: row.accessBundleId,+ createdAt: row.createdAt,+ actor: actorOf(row)+ })),+ totalCount+ };} catch (error) {throw new DatabaseError({ error, name: "Find agent vault access bundle members" });}};- return { ...orm, findWithCounts, findByIdInProject, lockByIdInProject, findMembers };+ return { ...orm, findForList, findByIdInProject, lockByIdInProject, findMembers };};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 2aa7712a78..b9a938323f 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@@ -1,7 +1,15 @@import { ForbiddenError } from "@casl/ability";import { Knex } from "knex";-import { AccessScope, RESOURCE_SCOPE, ResourceType, TAgentVaultServices, TMemberships } from "@app/db/schemas";+import {+ AccessScope,+ RESOURCE_SCOPE,+ ResourceType,+ TAgentVaultServiceCustomHeaders,+ TAgentVaultServices,+ TAgentVaultServiceSubstitutions,+ TMemberships+} from "@app/db/schemas";import { TIdentityGroupMembershipDALFactory } from "@app/ee/services/group/identity-group-membership-dal";import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";@@ -22,9 +30,15 @@ import {TAgentVaultCredentialConfig} from "../agent-vault/agent-vault-credential-schemas";import { isUniqueViolation } from "../agent-vault/agent-vault-db-error-fns";-import { AgentVaultCredentialType, AgentVaultResourceRole } from "../agent-vault/agent-vault-enums";+import {+ AgentVaultCredentialType,+ AgentVaultHttpMethod,+ AgentVaultMemberType,+ AgentVaultResourceRole,+ AgentVaultSubstitutionSurface+} from "../agent-vault/agent-vault-enums";import { getAgentVaultReachability } from "../agent-vault/agent-vault-permission";-import { TAgentVaultAccessBundleDALFactory } from "./agent-vault-access-bundle-dal";+import { TAgentVaultAccessBundleActorRef, TAgentVaultAccessBundleDALFactory } from "./agent-vault-access-bundle-dal";import {TAddMembersDTO,TAgentVaultCredentialInput,@@ -37,15 +51,20 @@ import {TGetAccessBundleDTO,TListAccessBundlesDTO,TListMembersDTO,- TRemoveMemberDTO,+ TRevokeMembersDTO,TUpdateAccessBundleDTO,TUpdateServiceDTO} from "./agent-vault-access-bundle-types";+import { TAgentVaultServiceCustomHeaderDALFactory } from "./agent-vault-service-custom-header-dal";import { TAgentVaultServiceDALFactory } from "./agent-vault-service-dal";+import { TAgentVaultServiceSubstitutionDALFactory } from "./agent-vault-service-substitution-dal";+import { planTransformationDiff, TTransformationWrite } from "./agent-vault-transformation-fns";type TAgentVaultAccessBundleServiceFactoryDep = {agentVaultAccessBundleDAL: TAgentVaultAccessBundleDALFactory;agentVaultServiceDAL: TAgentVaultServiceDALFactory;+ agentVaultServiceCustomHeaderDAL: TAgentVaultServiceCustomHeaderDALFactory;+ agentVaultServiceSubstitutionDAL: TAgentVaultServiceSubstitutionDALFactory;permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;membershipDAL: Pick<@@ -66,6 +85,8 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundconst {agentVaultAccessBundleDAL,agentVaultServiceDAL,+ agentVaultServiceCustomHeaderDAL,+ agentVaultServiceSubstitutionDAL,permissionService,kmsService,membershipDAL,@@ -81,13 +102,17 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundscopeResourceId: accessBundleId});+ const toActorRef = (row: TMemberships): TAgentVaultAccessBundleActorRef => {+ if (row.actorIdentityId) return { type: AgentVaultMemberType.MachineIdentity, id: row.actorIdentityId };+ if (row.actorGroupId) return { type: AgentVaultMemberType.Group, id: row.actorGroupId };+ return { type: AgentVaultMemberType.User, id: row.actorUserId ?? "" };+ };+const toMember = (row: TMemberships) => ({id: row.id,accessBundleId: row.scopeResourceId!,- userId: row.actorUserId ?? null,- identityId: row.actorIdentityId ?? null,- groupId: row.actorGroupId ?? null,- createdAt: row.createdAt+ createdAt: row.createdAt,+ actor: toActorRef(row)});type TGrantActorColumn = "actorUserId" | "actorIdentityId" | "actorGroupId";@@ -96,6 +121,17 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundconst actorKey = ({ actorColumn, actorId }: TGrantActor) => `${actorColumn}:${actorId}`;+ const ACTOR_TYPE_OF: Record<TGrantActorColumn, AgentVaultMemberType> = {+ actorUserId: AgentVaultMemberType.User,+ actorIdentityId: AgentVaultMemberType.MachineIdentity,+ actorGroupId: AgentVaultMemberType.Group+ };++ const toActorRefFromGrant = ({ actorColumn, actorId }: TGrantActor): TAgentVaultAccessBundleActorRef => ({+ type: ACTOR_TYPE_OF[actorColumn],+ id: actorId+ });+const ACTOR_FIELD_OF: Record<TGrantActorColumn, "userId" | "identityId" | "groupId"> = {actorUserId: "userId",actorIdentityId: "identityId",@@ -304,6 +340,71 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund}};+ // Built by hand rather than spread, so the sealed columns stay off the wire even if the response schema is+ // later loosened.+ const projectService = (+ service: TAgentVaultServices,+ customHeaders: TAgentVaultServiceCustomHeaders[],+ substitutions: TAgentVaultServiceSubstitutions[]+ ) => ({+ id: service.id,+ accessBundleId: service.accessBundleId,+ name: service.name,+ hostPattern: service.hostPattern,+ allowedMethods: (service.allowedMethods ?? null) as AgentVaultHttpMethod[] | null,+ allowedPathPrefixes: service.allowedPathPrefixes ?? null,+ credential: summarizeCredential(service),+ customHeaders: customHeaders.map((header) => ({ id: header.id, name: header.name, prefix: header.prefix })),+ substitutions: substitutions.map((substitution) => ({+ id: substitution.id,+ placeholder: substitution.placeholder,+ surfaces: substitution.surfaces as AgentVaultSubstitutionSurface[]+ })),+ createdAt: service.createdAt,+ updatedAt: service.updatedAt+ });++ const loadTransformations = async (serviceIds: string[], tx?: Knex) => {+ const [customHeaders, substitutions] = await Promise.all([+ agentVaultServiceCustomHeaderDAL.findByServiceIds(serviceIds, tx),+ agentVaultServiceSubstitutionDAL.findByServiceIds(serviceIds, tx)+ ]);+ return { customHeaders, substitutions };+ };++ // Basic has no header name in its config, but the proxy always writes Authorization.+ const credentialHeaderName = (credentialType: AgentVaultCredentialType, headerName?: string): string | null => {+ switch (credentialType) {+ case AgentVaultCredentialType.Bearer:+ return headerName || "Authorization";+ case AgentVaultCredentialType.Basic:+ return "Authorization";+ default:+ return null;+ }+ };++ // The proxy writes the credential last, so a collision costs the header rather than the token; refusing it+ // on write is what tells the author. Either half of a PATCH can introduce one, which is why both are read.+ const assertCustomHeadersDoNotShadowCredential = (+ config: TAgentVaultCredentialConfig,+ customHeaders: { name: string }[] | undefined+ ) => {+ if (!customHeaders?.length) return;+ const credentialHeader = credentialHeaderName(+ config.type,+ config.type === AgentVaultCredentialType.Bearer ? config.headerName : undefined+ );+ if (!credentialHeader) return;++ const clash = customHeaders.find((header) => header.name.toLowerCase() === credentialHeader.toLowerCase());+ if (clash) {+ throw new BadRequestError({+ message: `The ${credentialHeader} header is already set by the credential. Rename the custom header or change the credential.`+ });+ }+ };+// A bundle the caller cannot reach is a 404, never a 403, which would confirm the id exists.const resolveReachableBundle = async ({ projectId, ctx, accessBundleId }: TGetAccessBundleDTO) => {const reachability = await getAgentVaultReachability({ permissionService, membershipDAL }, { projectId, ctx });@@ -319,7 +420,7 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundreturn { bundle, ...reachability };};- const listAccessBundles = async ({ projectId, ctx }: TListAccessBundlesDTO) => {+ const listAccessBundles = async ({ projectId, ctx, ...page }: TListAccessBundlesDTO) => {const { permission, accessBundleIds } = await getAgentVaultReachability({ permissionService, membershipDAL },{ projectId, ctx }@@ -329,35 +430,32 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundProjectPermissionSub.AgentVaultAccessBundles);- return agentVaultAccessBundleDAL.findWithCounts({ projectId, accessBundleIds });+ return agentVaultAccessBundleDAL.findForList({ projectId, accessBundleIds, ...page });};const getAccessBundleById = async (dto: TGetAccessBundleDTO) => {- const { bundle, permission, isAdmin } = await resolveReachableBundle(dto);+ const { bundle, permission } = await resolveReachableBundle(dto);ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionAgentVaultAccessBundleActions.Read,ProjectPermissionSub.AgentVaultAccessBundles);const services = await agentVaultServiceDAL.findByAccessBundleId(bundle.id);- const members = isAdmin- ? await agentVaultAccessBundleDAL.findMembers({ projectId: dto.projectId, accessBundleId: bundle.id })- : undefined;+ const { customHeaders, substitutions } = await loadTransformations(services.map((service) => service.id));return {id: bundle.id,name: bundle.name,description: bundle.description ?? null,createdAt: bundle.createdAt,- services: services.map((service) => ({- id: service.id,- accessBundleId: service.accessBundleId,- name: service.name,- hostPattern: service.hostPattern,- credential: summarizeCredential(service),- createdAt: service.createdAt- })),- members+ updatedAt: bundle.updatedAt,+ services: services.map((service) =>+ projectService(+ service,+ customHeaders.filter((header) => header.serviceId === service.id),+ substitutions.filter((substitution) => substitution.serviceId === service.id)+ )+ )};};@@ -472,7 +570,17 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund}};- const createService = async ({ accessBundleId, name, hostPattern, credential, ...rest }: TCreateServiceDTO) => {+ const createService = async ({+ accessBundleId,+ name,+ hostPattern,+ allowedMethods,+ allowedPathPrefixes,+ credential,+ customHeaders,+ substitutions,+ ...rest+ }: TCreateServiceDTO) => {const { bundle, permission } = await resolveReachableBundle({ ...rest, accessBundleId });ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionAgentVaultAccessBundleActions.Edit,@@ -488,10 +596,26 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund// Encrypt before the lock: KMS is a network call and the transaction has to stay short.const { config, secret } = splitCredential(credential);+ assertCustomHeadersDoNotShadowCredential(config, customHeaders);+const { encryptor } = await getProjectCipher(rest.projectId);+ const seal = (value: string) => encryptor({ plainText: Buffer.from(JSON.stringify({ value })) }).cipherTextBlob;+const encryptedCredential = secret? encryptor({ plainText: Buffer.from(JSON.stringify(secret)) }).cipherTextBlob: null;+ const customHeaderRows = (customHeaders ?? []).map((header, position) => ({+ name: header.name,+ prefix: header.prefix ?? "",+ position,+ encryptedValue: seal(header.value)+ }));+ const substitutionRows = (substitutions ?? []).map((substitution, position) => ({+ placeholder: substitution.placeholder,+ surfaces: substitution.surfaces,+ position,+ encryptedValue: seal(substitution.value)+ }));// The pre-check above is only a fast failure. The authoritative one runs under the bundle row lock,// the same lock addMembers takes, because no database constraint can express host-pattern overlap.@@ -505,22 +629,39 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundawait checkHostPatternConflicts({ accessBundleId: bundle.id, hostPattern }, tx);- return agentVaultServiceDAL.create(+ const created = await agentVaultServiceDAL.create({accessBundleId: bundle.id,name,hostPattern,+ allowedMethods: allowedMethods ?? null,+ allowedPathPrefixes: allowedPathPrefixes ?? null,credentialType: credential.type,credentialConfig: config,encryptedCredential},tx);++ const insertedCustomHeaders = customHeaderRows.length+ ? await agentVaultServiceCustomHeaderDAL.insertMany(+ customHeaderRows.map((row) => ({ ...row, serviceId: created.id })),+ tx+ )+ : [];+ const insertedSubstitutions = substitutionRows.length+ ? await agentVaultServiceSubstitutionDAL.insertMany(+ substitutionRows.map((row) => ({ ...row, serviceId: created.id })),+ tx+ )+ : [];++ return { created, insertedCustomHeaders, insertedSubstitutions };});- let service;+ let result;try {- service = await write();+ result = await write();} catch (err) {if (isUniqueViolation(err)) {throw new BadRequestError({ message: `A service named '${name}' already exists in this access bundle` });@@ -528,7 +669,9 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundthrow err;}- return { service: { ...service, credential: summarizeCredential(service) } };+ return {+ service: projectService(result.created, result.insertedCustomHeaders, result.insertedSubstitutions)+ };};const updateService = async ({@@ -537,6 +680,10 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundname,hostPattern,credential,+ allowedMethods,+ allowedPathPrefixes,+ customHeaders,+ substitutions,...rest}: TUpdateServiceDTO) => {const { bundle, permission } = await resolveReachableBundle({ ...rest, accessBundleId });@@ -564,6 +711,7 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund}let credentialUpdate = {};+ let effectiveCredentialConfig = service.credentialConfig as TAgentVaultCredentialConfig;if (credential) {const needsStoredSecret =credential.type === AgentVaultCredentialType.Basic &&@@ -591,8 +739,36 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundcredentialConfig: config,...(encryptedCredential === undefined ? {} : { encryptedCredential })};+ effectiveCredentialConfig = config;}+ const cipherForTransformations =+ customHeaders?.length || substitutions?.length ? await getProjectCipher(rest.projectId) : null;+ const seal = (value: string) =>+ cipherForTransformations!.encryptor({ plainText: Buffer.from(JSON.stringify({ value })) }).cipherTextBlob;++ const customHeaderWrites: TTransformationWrite<{ name: string; prefix: string }>[] | undefined = customHeaders?.map(+ (header) => ({+ id: header.id,+ naturalKey: header.name.toLowerCase(),+ label: header.name,+ // An omitted prefix is cleared, not kept: it comes back in the response so a caller can resend it,+ // which is the thing a sealed value can never do.+ columns: { name: header.name, prefix: header.prefix ?? "" },+ encryptedValue: header.value === undefined ? undefined : seal(header.value)+ })+ );++ const substitutionWrites:+ | TTransformationWrite<{ placeholder: string; surfaces: AgentVaultSubstitutionSurface[] }>[]+ | undefined = substitutions?.map((substitution) => ({+ id: substitution.id,+ naturalKey: substitution.placeholder,+ label: substitution.placeholder,+ columns: { placeholder: substitution.placeholder, surfaces: substitution.surfaces },+ encryptedValue: substitution.value === undefined ? undefined : seal(substitution.value)+ }));+// Same lock as create, and below the credential work so no KMS call sits inside the transaction. The// re-check only earns its place when the pattern actually changes.const write = () =>@@ -607,20 +783,102 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundawait checkHostPatternConflicts({ accessBundleId: bundle.id, hostPattern, excludeServiceId: service.id }, tx);}- return agentVaultServiceDAL.updateById(- service.id,- {- name,- hostPattern,- ...credentialUpdate+ // Both halves read under the lock and on the primary. The service read above the transaction came off+ // a replica, and stale it would admit the very collision this check exists to stop.+ if (credential || customHeaders) {+ const effectiveCustomHeaders =+ customHeaders ??+ (await agentVaultServiceCustomHeaderDAL.findByServiceIds([service.id], tx)).map((row) => ({+ name: row.name+ }));+ if (!credential) {+ const current = await agentVaultServiceDAL.findById(service.id, tx);+ if (!current) throw new NotFoundError({ message: `Service with ID '${serviceId}' not found` });+ effectiveCredentialConfig = current.credentialConfig as TAgentVaultCredentialConfig;+ }+ assertCustomHeadersDoNotShadowCredential(effectiveCredentialConfig, effectiveCustomHeaders);+ }++ const hasColumnUpdate =+ name !== undefined ||+ hostPattern !== undefined ||+ allowedMethods !== undefined ||+ allowedPathPrefixes !== undefined ||+ Object.keys(credentialUpdate).length > 0;++ const updatedService = hasColumnUpdate+ ? await agentVaultServiceDAL.updateById(+ service.id,+ {+ name,+ hostPattern,+ // `null` clears the restriction, `undefined` leaves the column alone.+ ...(allowedMethods === undefined ? {} : { allowedMethods }),+ ...(allowedPathPrefixes === undefined ? {} : { allowedPathPrefixes }),+ ...credentialUpdate+ },+ tx+ )+ : service;++ // Outside the lock, two concurrent PATCHes both pass the ownership check and the loser's writes no-op.+ const applyDiff = async <TRow extends { id: string; encryptedValue: Buffer }, TColumns>(+ dal: {+ findByServiceIds: (ids: string[], tx?: Knex) => Promise<TRow[]>;+ insertMany: (rows: never[], tx?: Knex) => Promise<TRow[]>;+ updateById: (id: string, columns: never, tx?: Knex) => Promise<TRow>;+ delete: (filter: never, tx?: Knex) => Promise<TRow[]>;},- tx+ incoming: TTransformationWrite<TColumns>[] | undefined,+ naturalKeyOfRow: (row: TRow) => string,+ subject: string+ ): Promise<TRow[]> => {+ const existing = await dal.findByServiceIds([service.id], tx);+ if (!incoming) return existing;++ const plan = planTransformationDiff({ existing, incoming, naturalKeyOfRow, subject });++ // Sequential: these share the transaction's single connection, and the schema caps the list at 20.+ // eslint-disable-next-line no-restricted-syntax+ for (const update of plan.updates) {+ // eslint-disable-next-line no-await-in-loop+ await dal.updateById(update.id, update.columns as never, tx);+ }+ if (plan.deleteIds.length) await dal.delete({ $in: { id: plan.deleteIds } } as never, tx);++ const created = plan.creates.length+ ? await dal.insertMany(plan.creates.map((row) => ({ ...row, serviceId: service.id })) as never[], tx)+ : [];++ const updatedById = new Map(plan.updates.map((update) => [update.id, update.columns]));+ const survivors = existing+ .filter((row) => !plan.deleteIds.includes(row.id))+ .map((row) => ({ ...row, ...(updatedById.get(row.id) ?? {}) }) as TRow);++ return [...survivors, ...created].sort(+ (a, b) => (a as unknown as { position: number }).position - (b as unknown as { position: number }).position+ );+ };++ const updatedCustomHeaders = await applyDiff(+ agentVaultServiceCustomHeaderDAL,+ customHeaderWrites,+ (row) => row.name.toLowerCase(),+ "custom header"+ );+ const updatedSubstitutions = await applyDiff(+ agentVaultServiceSubstitutionDAL,+ substitutionWrites,+ (row) => row.placeholder,+ "substitution");++ return { updatedService, updatedCustomHeaders, updatedSubstitutions };});- let updated;+ let result;try {- updated = await write();+ result = await write();} catch (err) {if (isUniqueViolation(err)) {throw new BadRequestError({ message: `A service named '${name}' already exists in this access bundle` });@@ -628,7 +886,9 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundthrow err;}- return { service: { ...updated, credential: summarizeCredential(updated) } };+ return {+ service: projectService(result.updatedService, result.updatedCustomHeaders, result.updatedSubstitutions)+ };};const deleteService = async ({ accessBundleId, serviceId, ...rest }: TDeleteServiceDTO) => {@@ -641,20 +901,28 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundconst service = await agentVaultServiceDAL.findOne({ id: serviceId, accessBundleId: bundle.id });if (!service) throw new NotFoundError({ message: `Service with ID '${serviceId}' not found` });+ // Read before the delete, since CASCADE takes these rows with the service.+ const { customHeaders, substitutions } = await loadTransformations([service.id]);const deleted = await agentVaultServiceDAL.deleteById(service.id);- return { ...deleted, credential: summarizeCredential(deleted) };+ return projectService(deleted, customHeaders, substitutions);};- const listMembers = async ({ accessBundleId, ...rest }: TListMembersDTO) => {+ const listMembers = async ({ accessBundleId, search, limit, offset, ...rest }: TListMembersDTO) => {const { bundle, permission } = await resolveReachableBundle({ ...rest, accessBundleId });ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionAgentVaultAccessBundleActions.ManageMembers,ProjectPermissionSub.AgentVaultAccessBundles);- return agentVaultAccessBundleDAL.findMembers({ projectId: rest.projectId, accessBundleId: bundle.id });+ return agentVaultAccessBundleDAL.findMembers({+ projectId: rest.projectId,+ accessBundleId: bundle.id,+ search,+ limit,+ offset+ });};- const addMembers = async ({ accessBundleId, userIds, groupIds, identityIds, ...rest }: TAddMembersDTO) => {+ const addMembers = async ({ accessBundleId, userIds, groupIds, machineIdentityIds, ...rest }: TAddMembersDTO) => {const { bundle, permission } = await resolveReachableBundle({ ...rest, accessBundleId });ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionAgentVaultAccessBundleActions.ManageMembers,@@ -665,7 +933,7 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundconst byColumn: [TGrantActorColumn, string[]][] = [["actorUserId", userIds],["actorGroupId", groupIds],- ["actorIdentityId", identityIds]+ ["actorIdentityId", machineIdentityIds]];byColumn.forEach(([actorColumn, ids]) => {ids.forEach((actorId) => {@@ -699,7 +967,7 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund}));- const skipped = actors.filter((actor) => alreadyGranted.has(actorKey(actor))).map((actor) => actor.actorId);+ const skipped = actors.filter((actor) => alreadyGranted.has(actorKey(actor))).map(toActorRefFromGrant);const toGrant = actors.filter((actor) => !alreadyGranted.has(actorKey(actor)));if (!toGrant.length) return { created: [] as TMemberships[], skipped };@@ -710,7 +978,7 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundreturn { created, skipped };});- let outcome: { created: TMemberships[]; skipped: string[] };+ let outcome: { created: TMemberships[]; skipped: TAgentVaultAccessBundleActorRef[] };try {outcome = await grant();} catch (err) {@@ -727,24 +995,65 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund};};- const removeMember = async ({ accessBundleId, memberId, ...rest }: TRemoveMemberDTO) => {+ const revokeMembers = async ({+ accessBundleId,+ userIds,+ groupIds,+ machineIdentityIds,+ ...rest+ }: TRevokeMembersDTO) => {const { bundle, permission } = await resolveReachableBundle({ ...rest, accessBundleId });ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionAgentVaultAccessBundleActions.ManageMembers,ProjectPermissionSub.AgentVaultAccessBundles);- const member = await membershipDAL.findOne({ ...bundleScope(rest.projectId, bundle.id), id: memberId });- if (!member) throw new NotFoundError({ message: `Access bundle membership with ID '${memberId}' not found` });+ const requested = new Map<string, TGrantActor>();+ const byColumn: [TGrantActorColumn, string[]][] = [+ ["actorUserId", userIds],+ ["actorGroupId", groupIds],+ ["actorIdentityId", machineIdentityIds]+ ];+ byColumn.forEach(([actorColumn, ids]) => {+ ids.forEach((actorId) => requested.set(actorKey({ actorColumn, actorId }), { actorColumn, actorId }));+ });+ const actors = [...requested.values()];++ // The same row lock the grant path takes, so a revoke cannot race a grant or a bundle delete.+ const outcome = await membershipDAL.transaction(async (tx) => {+ const locked = await agentVaultAccessBundleDAL.lockByIdInProject(+ { id: bundle.id, projectId: rest.projectId },+ tx+ );+ if (!locked) throw new NotFoundError({ message: `Access bundle with ID '${accessBundleId}' not found` });++ const heldByKey = new Map<string, TMemberships>();+ await Promise.all(+ byColumn.map(async ([actorColumn, ids]) => {+ if (!ids.length) return;+ const rows = await membershipDAL.find(+ { ...bundleScope(rest.projectId, bundle.id), $in: { [actorColumn]: ids } },+ { tx }+ );+ rows.forEach((row) => {+ const actorId = row[actorColumn];+ if (actorId) heldByKey.set(actorKey({ actorColumn, actorId }), row);+ });+ })+ );++ const skipped = actors.filter((actor) => !heldByKey.has(actorKey(actor))).map(toActorRefFromGrant);+ const held = actors.filter((actor) => heldByKey.has(actorKey(actor)));+ if (!held.length) return { removed: [] as TMemberships[], skipped };++ const rows = held.map((actor) => heldByKey.get(actorKey(actor))!);+ await membershipDAL.delete({ $in: { id: rows.map((row) => row.id) } }, tx);+ return { removed: rows, skipped };+ });- await membershipDAL.deleteById(member.id);return {- id: member.id,- accessBundleId: bundle.id,- userId: member.actorUserId ?? null,- identityId: member.actorIdentityId ?? null,- groupId: member.actorGroupId ?? null,- createdAt: member.createdAt,+ members: outcome.removed.map(toMember),+ skipped: outcome.skipped,accessBundleName: bundle.name};};@@ -760,6 +1069,6 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBunddeleteService,listMembers,addMembers,- removeMember+ revokeMembers};};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 21974e4c80..eb2a61470e 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@@ -1,5 +1,10 @@import { TAgentVaultActorContext } from "../agent-vault/agent-vault-actor-types";-import { AgentVaultCredentialType } from "../agent-vault/agent-vault-enums";+import {+ AgentVaultCredentialType,+ AgentVaultHttpMethod,+ AgentVaultSubstitutionSurface+} from "../agent-vault/agent-vault-enums";+import { TAgentVaultAccessBundleOrderBy } from "./agent-vault-access-bundle-dal";export type TAgentVaultCredentialInput =| { type: AgentVaultCredentialType.Bearer; headerName?: string; headerPrefix?: string; value: string }@@ -18,7 +23,13 @@ export type TAgentVaultCredentialSummary =export type TAgentVaultProjectScoped = { projectId: string; ctx: TAgentVaultActorContext };-export type TListAccessBundlesDTO = TAgentVaultProjectScoped;+export type TListAccessBundlesDTO = TAgentVaultProjectScoped & {+ search?: string;+ orderBy: TAgentVaultAccessBundleOrderBy;+ orderDirection: "asc" | "desc";+ limit: number;+ offset: number;+};export type TGetAccessBundleDTO = TAgentVaultProjectScoped & { accessBundleId: string };@@ -35,11 +46,34 @@ export type TUpdateAccessBundleDTO = TAgentVaultProjectScoped & {export type TDeleteAccessBundleDTO = TAgentVaultProjectScoped & { accessBundleId: string };+export type TAgentVaultCustomHeaderInput = { name: string; prefix?: string; value: string };++// `id` is optional because a row is matched by its name when the caller did not send one, and `value` is+// optional because omitting it keeps whatever is sealed for the row that matched.+export type TAgentVaultCustomHeaderUpdate = { id?: string; name: string; prefix?: string; value?: string };++export type TAgentVaultSubstitutionInput = {+ placeholder: string;+ surfaces: AgentVaultSubstitutionSurface[];+ value: string;+};++export type TAgentVaultSubstitutionUpdate = {+ id?: string;+ placeholder: string;+ surfaces: AgentVaultSubstitutionSurface[];+ value?: string;+};+export type TCreateServiceDTO = TAgentVaultProjectScoped & {accessBundleId: string;name: string;hostPattern: string;+ allowedMethods?: AgentVaultHttpMethod[] | null;+ allowedPathPrefixes?: string[] | null;credential: TAgentVaultCredentialInput;+ customHeaders?: TAgentVaultCustomHeaderInput[];+ substitutions?: TAgentVaultSubstitutionInput[];};export type TUpdateServiceDTO = TAgentVaultProjectScoped & {@@ -47,7 +81,11 @@ export type TUpdateServiceDTO = TAgentVaultProjectScoped & {serviceId: string;name?: string;hostPattern?: string;+ allowedMethods?: AgentVaultHttpMethod[] | null;+ allowedPathPrefixes?: string[] | null;credential?: TAgentVaultCredentialUpdate;+ customHeaders?: TAgentVaultCustomHeaderUpdate[];+ substitutions?: TAgentVaultSubstitutionUpdate[];};export type TDeleteServiceDTO = TAgentVaultProjectScoped & {@@ -55,16 +93,23 @@ export type TDeleteServiceDTO = TAgentVaultProjectScoped & {serviceId: string;};-export type TListMembersDTO = TAgentVaultProjectScoped & { accessBundleId: string };+export type TListMembersDTO = TAgentVaultProjectScoped & {+ accessBundleId: string;+ search?: string;+ limit: number;+ offset: number;+};export type TAddMembersDTO = TAgentVaultProjectScoped & {accessBundleId: string;userIds: string[];groupIds: string[];- identityIds: string[];+ machineIdentityIds: string[];};-export type TRemoveMemberDTO = TAgentVaultProjectScoped & {+export type TRevokeMembersDTO = TAgentVaultProjectScoped & {accessBundleId: string;- memberId: string;+ userIds: string[];+ groupIds: string[];+ machineIdentityIds: string[];};diff --git a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-service-custom-header-dal.ts b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-service-custom-header-dal.tsnew file mode 100644index 0000000000..63ded2c199--- /dev/null+++ b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-service-custom-header-dal.ts@@ -0,0 +1,26 @@+import { Knex } from "knex";++import { TDbClient } from "@app/db";+import { TableName, TAgentVaultServiceCustomHeaders } from "@app/db/schemas";+import { DatabaseError } from "@app/lib/errors";+import { ormify, selectAllTableCols } from "@app/lib/knex";++export type TAgentVaultServiceCustomHeaderDALFactory = ReturnType<typeof agentVaultServiceCustomHeaderDALFactory>;++export const agentVaultServiceCustomHeaderDALFactory = (db: TDbClient) => {+ const orm = ormify(db, TableName.AgentVaultServiceCustomHeader);++ const findByServiceIds = async (serviceIds: string[], tx?: Knex): Promise<TAgentVaultServiceCustomHeaders[]> => {+ if (!serviceIds.length) return [];+ try {+ return (await (tx || db.replicaNode())(TableName.AgentVaultServiceCustomHeader)+ .whereIn("serviceId", serviceIds)+ .orderBy("position", "asc")+ .select(selectAllTableCols(TableName.AgentVaultServiceCustomHeader))) as TAgentVaultServiceCustomHeaders[];+ } catch (error) {+ throw new DatabaseError({ error, name: "Find agent vault service custom headers" });+ }+ };++ return { ...orm, findByServiceIds };+};diff --git a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-service-substitution-dal.ts b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-service-substitution-dal.tsnew file mode 100644index 0000000000..62245e9534--- /dev/null+++ b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-service-substitution-dal.ts@@ -0,0 +1,26 @@+import { Knex } from "knex";++import { TDbClient } from "@app/db";+import { TableName, TAgentVaultServiceSubstitutions } from "@app/db/schemas";+import { DatabaseError } from "@app/lib/errors";+import { ormify, selectAllTableCols } from "@app/lib/knex";++export type TAgentVaultServiceSubstitutionDALFactory = ReturnType<typeof agentVaultServiceSubstitutionDALFactory>;++export const agentVaultServiceSubstitutionDALFactory = (db: TDbClient) => {+ const orm = ormify(db, TableName.AgentVaultServiceSubstitution);++ const findByServiceIds = async (serviceIds: string[], tx?: Knex): Promise<TAgentVaultServiceSubstitutions[]> => {+ if (!serviceIds.length) return [];+ try {+ return (await (tx || db.replicaNode())(TableName.AgentVaultServiceSubstitution)+ .whereIn("serviceId", serviceIds)+ .orderBy("position", "asc")+ .select(selectAllTableCols(TableName.AgentVaultServiceSubstitution))) as TAgentVaultServiceSubstitutions[];+ } catch (error) {+ throw new DatabaseError({ error, name: "Find agent vault service substitutions" });+ }+ };++ return { ...orm, findByServiceIds };+};diff --git a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-transformation-fns.ts b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-transformation-fns.tsnew file mode 100644index 0000000000..3b05f52956--- /dev/null+++ b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-transformation-fns.ts@@ -0,0 +1,104 @@+import { BadRequestError } from "@app/lib/errors";++type TStoredRow = { id: string; encryptedValue: Buffer };++/** `encryptedValue` is undefined when the caller omitted the value, which means "keep whatever is stored". */+export type TTransformationWrite<TColumns> = {+ id?: string;+ naturalKey: string;+ /** The caller's own spelling, so an error quotes what they typed rather than the folded lookup key. */+ label: string;+ columns: TColumns;+ encryptedValue?: Buffer;+};++export type TTransformationPlan<TColumns> = {+ creates: (TColumns & { position: number; encryptedValue: Buffer })[];+ updates: { id: string; columns: TColumns & { position: number; encryptedValue?: Buffer } }[];+ deleteIds: string[];+};++// A re-seal of the same plaintext produces different bytes, so the presence of encryptedValue means changed.+const isUnchanged = (stored: Record<string, unknown>, columns: Record<string, unknown>) =>+ Object.entries(columns).every(([key, value]) => {+ if (key === "encryptedValue") return false;+ const current = stored[key];+ if (Array.isArray(value) && Array.isArray(current)) {+ return value.length === current.length && value.every((entry, i) => entry === current[i]);+ }+ return current === value;+ });++/**+ * Resolves each incoming row to a stored one by `id`, and otherwise by its natural key, which is what lets a+ * hand-written call edit one row without first fetching the service for its ids. Ids are claimed in a first+ * pass, or swapping two rows' names would let the second claim the row the first was already given.+ */+export const planTransformationDiff = <TRow extends TStoredRow, TColumns>({+ existing,+ incoming,+ naturalKeyOfRow,+ subject+}: {+ existing: TRow[];+ incoming: TTransformationWrite<TColumns>[];+ naturalKeyOfRow: (row: TRow) => string;+ subject: string;+}): TTransformationPlan<TColumns> => {+ const byId = new Map(existing.map((row) => [row.id, row]));+ const claimed = new Set<string>();+ const resolved = new Array<TRow | undefined>(incoming.length);++ incoming.forEach((row, index) => {+ if (!row.id) return;+ const stored = byId.get(row.id);+ if (!stored) {+ throw new BadRequestError({ message: `No ${subject} with ID '${row.id}' belongs to this service` });+ }+ // Without this, both rows resolve to the same stored row, the second update wins, and the first row the+ // caller asked for disappears. The list-level name check cannot catch it: the two rows differ by name.+ if (claimed.has(stored.id)) {+ throw new BadRequestError({ message: `The ${subject} with ID '${row.id}' is listed twice` });+ }+ claimed.add(stored.id);+ resolved[index] = stored;+ });++ const byKey = new Map(+ existing.filter((row) => !claimed.has(row.id)).map((row) => [naturalKeyOfRow(row), row] as const)+ );++ incoming.forEach((row, index) => {+ if (resolved[index]) return;+ const stored = byKey.get(row.naturalKey);+ if (!stored) return;+ byKey.delete(row.naturalKey);+ claimed.add(stored.id);+ resolved[index] = stored;+ });++ const plan: TTransformationPlan<TColumns> = { creates: [], updates: [], deleteIds: [] };++ incoming.forEach((row, index) => {+ const stored = resolved[index];+ if (stored) {+ const columns = {+ ...row.columns,+ position: index,+ ...(row.encryptedValue ? { encryptedValue: row.encryptedValue } : {})+ };+ if (!isUnchanged(stored, columns)) plan.updates.push({ id: stored.id, columns });+ return;+ }+ if (!row.encryptedValue) {+ throw new BadRequestError({+ message: `Adding the ${subject} '${row.label}' needs a value, because there is nothing stored for it yet`+ });+ }+ plan.creates.push({ ...row.columns, position: index, encryptedValue: row.encryptedValue });+ });++ plan.deleteIds = existing.filter((row) => !claimed.has(row.id)).map((row) => row.id);++ return plan;+};diff --git a/backend/src/ee/services/agent-vault-member/agent-vault-member-dal.ts b/backend/src/ee/services/agent-vault-member/agent-vault-member-dal.tsnew file mode 100644index 0000000000..9cfca02828--- /dev/null+++ b/backend/src/ee/services/agent-vault-member/agent-vault-member-dal.ts@@ -0,0 +1,196 @@+import { Knex } from "knex";++import { TDbClient } from "@app/db";+import { AccessScope, OrgMembershipStatus, ProjectMembershipRole, TableName } from "@app/db/schemas";+import { AgentVaultMemberType } from "@app/ee/services/agent-vault/agent-vault-enums";+import { DatabaseError } from "@app/lib/errors";+import { sanitizeSqlLikeString } from "@app/lib/fn/string";++export type TAgentVaultMemberDALFactory = ReturnType<typeof agentVaultMemberDALFactory>;++export type TAgentVaultProductActor =+ | {+ type: AgentVaultMemberType.User;+ id: string;+ username: string;+ email: string | null;+ firstName: string | null;+ lastName: string | null;+ isOrgMembershipPending: boolean;+ }+ | {+ type: AgentVaultMemberType.MachineIdentity;+ id: string;+ name: string;+ // An identity Agent Vault created cannot be detached, only deleted.+ isManagedByAgentVault: boolean;+ orgId: string | null;+ }+ | { type: AgentVaultMemberType.Group; id: string; name: string };++export type TAgentVaultProductMember = {+ id: string;+ role: string;+ isActive: boolean;+ createdAt: Date;+ actor: TAgentVaultProductActor;+};++const ACTOR_COLUMN: Record<AgentVaultMemberType, "actorUserId" | "actorIdentityId" | "actorGroupId"> = {+ [AgentVaultMemberType.User]: "actorUserId",+ [AgentVaultMemberType.MachineIdentity]: "actorIdentityId",+ [AgentVaultMemberType.Group]: "actorGroupId"+};++type TFindProductMembersDTO = {+ projectId: string;+ orgId: string;+ actorTypes: AgentVaultMemberType[];+ search?: string;+ limit: number;+ offset: number;+};++export const agentVaultMemberDALFactory = (db: TDbClient) => {+ const findProductMembers = async (+ { projectId, orgId, actorTypes, search, limit, offset }: TFindProductMembersDTO,+ tx?: Knex+ ): Promise<{ members: TAgentVaultProductMember[]; totalCount: number }> => {+ if (!actorTypes.length) return { members: [], totalCount: 0 };++ try {+ const conn = tx || db.replicaNode();++ const applyFilters = (query: Knex.QueryBuilder) => {+ void query+ .where(`${TableName.Membership}.scope`, AccessScope.Project)+ .where(`${TableName.Membership}.scopeProjectId`, projectId)+ // only_one_actor_type keeps at most one non-null, so these cannot multiply a row and the count can+ // carry them. Nothing else may be joined: membership_roles is one-to-many and would.+ .leftJoin(TableName.Users, `${TableName.Membership}.actorUserId`, `${TableName.Users}.id`)+ .leftJoin(TableName.Identity, `${TableName.Membership}.actorIdentityId`, `${TableName.Identity}.id`)+ .leftJoin(TableName.Groups, `${TableName.Membership}.actorGroupId`, `${TableName.Groups}.id`);++ void query.where((qb) => {+ actorTypes.forEach((type) => {+ void qb.orWhereNotNull(`${TableName.Membership}.${ACTOR_COLUMN[type]}`);+ });+ });++ if (search) {+ const term = `%${sanitizeSqlLikeString(search)}%`;+ void query.where((qb) => {+ void qb+ .orWhereILike(`${TableName.Users}.username`, term)+ .orWhereILike(`${TableName.Users}.email`, term)+ .orWhereRaw(`CONCAT_WS(' ', ??, ??) ILIKE ?`, [+ `${TableName.Users}.firstName`,+ `${TableName.Users}.lastName`,+ term+ ])+ .orWhereILike(`${TableName.Identity}.name`, term)+ .orWhereILike(`${TableName.Groups}.name`, term);+ });+ }+ return query;+ };++ const countResult = (await applyFilters(conn(TableName.Membership))+ .count(`${TableName.Membership}.id as count`)+ .first()) as { count: string } | undefined;+ const totalCount = parseInt(countResult?.count || "0", 10);++ const rows = (await applyFilters(conn(TableName.Membership))+ .select(+ db.ref("id").withSchema(TableName.Membership),+ db.ref("createdAt").withSchema(TableName.Membership),+ db.ref("isActive").withSchema(TableName.Membership),+ db.ref("actorUserId").withSchema(TableName.Membership).as("userId"),+ db.ref("actorIdentityId").withSchema(TableName.Membership).as("machineIdentityId"),+ db.ref("actorGroupId").withSchema(TableName.Membership).as("groupId"),+ db.ref("username").withSchema(TableName.Users).as("userUsername"),+ db.ref("email").withSchema(TableName.Users).as("userEmail"),+ db.ref("firstName").withSchema(TableName.Users).as("userFirstName"),+ db.ref("lastName").withSchema(TableName.Users).as("userLastName"),+ db.ref("name").withSchema(TableName.Identity).as("machineIdentityName"),+ db.ref("projectId").withSchema(TableName.Identity).as("machineIdentityProjectId"),+ db.ref("orgId").withSchema(TableName.Identity).as("machineIdentityOrgId"),+ db.ref("name").withSchema(TableName.Groups).as("groupName"),+ db.raw(+ `(SELECT mr."role" FROM ?? mr WHERE mr."membershipId" = ??."id" ORDER BY mr."createdAt" ASC LIMIT 1) as "role"`,+ [TableName.MembershipRole, TableName.Membership]+ ),+ // Pinned to this org: membership is unique per (org, actor), and a user can hold several in a sub-org family.+ db.raw(+ `EXISTS (SELECT 1 FROM ?? om WHERE om."scope" = ? AND om."scopeOrgId" = ?+ AND om."actorUserId" = ??."actorUserId" AND om."status" = ?) as "isOrgMembershipPending"`,+ [TableName.Membership, AccessScope.Organization, orgId, TableName.Membership, OrgMembershipStatus.Invited]+ )+ )+ .orderByRaw(`COALESCE(??, ??, ??, '') ASC`, [+ `${TableName.Users}.username`,+ `${TableName.Identity}.name`,+ `${TableName.Groups}.name`+ ])+ .orderBy(`${TableName.Membership}.id`, "asc")+ .limit(limit)+ .offset(offset)) as {+ id: string;+ createdAt: Date;+ isActive: boolean;+ userId: string | null;+ machineIdentityId: string | null;+ groupId: string | null;+ userUsername: string | null;+ userEmail: string | null;+ userFirstName: string | null;+ userLastName: string | null;+ machineIdentityName: string | null;+ machineIdentityProjectId: string | null;+ machineIdentityOrgId: string | null;+ groupName: string | null;+ role: string | null;+ isOrgMembershipPending: boolean;+ }[];++ const actorOf = (row: (typeof rows)[number]): TAgentVaultProductActor => {+ if (row.machineIdentityId) {+ return {+ type: AgentVaultMemberType.MachineIdentity,+ id: row.machineIdentityId,+ name: row.machineIdentityName ?? "",+ isManagedByAgentVault: row.machineIdentityProjectId === projectId,+ orgId: row.machineIdentityOrgId+ };+ }+ if (row.groupId) {+ return { type: AgentVaultMemberType.Group, id: row.groupId, name: row.groupName ?? "" };+ }+ return {+ type: AgentVaultMemberType.User,+ id: row.userId ?? "",+ username: row.userUsername ?? "",+ email: row.userEmail,+ firstName: row.userFirstName,+ lastName: row.userLastName,+ isOrgMembershipPending: row.isOrgMembershipPending+ };+ };++ return {+ members: rows.map((row) => ({+ id: row.id,+ role: row.role ?? ProjectMembershipRole.Member,+ isActive: row.isActive,+ createdAt: row.createdAt,+ actor: actorOf(row)+ })),+ totalCount+ };+ } catch (error) {+ throw new DatabaseError({ error, name: "Find agent vault product members" });+ }+ };++ return { findProductMembers };+};diff --git a/backend/src/ee/services/agent-vault-member/agent-vault-membership-service.test.ts b/backend/src/ee/services/agent-vault-member/agent-vault-membership-service.test.tsindex e7f1aa1175..17c55ae4de 100644--- a/backend/src/ee/services/agent-vault-member/agent-vault-membership-service.test.ts+++ b/backend/src/ee/services/agent-vault-member/agent-vault-membership-service.test.ts@@ -1,6 +1,7 @@import { describe, expect, test, vi } from "vitest";import { AccessScope, ProjectMembershipRole } from "@app/db/schemas";+import { AgentVaultMemberType } from "@app/ee/services/agent-vault/agent-vault-enums";import { ActorType } from "@app/services/auth/auth-type";import { agentVaultMembershipServiceFactory } from "./agent-vault-membership-service";@@ -11,12 +12,14 @@ const OTHER_PROJECT_ID = "project-2";const ACTOR_ID = "actor-1";const IDENTITY_ID = "identity-1";+const addIds = { userIds: [], groupIds: [], machineIdentityIds: [IDENTITY_ID], emails: [] };+const ctx = {actor: ActorType.USER,actorId: ACTOR_ID,actorOrgId: ORG_ID,actorAuthMethod: undefined-} as unknown as Parameters<ReturnType<typeof agentVaultMembershipServiceFactory>["addProductMember"]>[0]["ctx"];+} as unknown as Parameters<ReturnType<typeof agentVaultMembershipServiceFactory>["addProductMembers"]>[0]["ctx"];const buildTx = (adminCount: number) => {const chain: Record<string, unknown> = {};@@ -43,34 +46,49 @@ const buildService = ({const deps = {permissionService: { getProjectPermission: vi.fn().mockResolvedValue({ hasRole: () => true }) },identityDAL: {- find: vi.fn().mockResolvedValue([{ id: IDENTITY_ID, name: "agent", orgId: ORG_ID, projectId: identityProjectId }])+ // Honours a projectId filter, because the ownership check pushes it into the query rather than+ // comparing in JS: a mock that ignored it would report every identity as Agent Vault's own.+ find: vi.fn(({ projectId }: { projectId?: string }) =>+ Promise.resolve(+ projectId && projectId !== identityProjectId+ ? []+ : [{ id: IDENTITY_ID, name: "agent", orgId: ORG_ID, projectId: identityProjectId }]+ )+ )},groupDAL: { find: vi.fn().mockResolvedValue([]) },userDAL: { find: vi.fn().mockResolvedValue([]) },userAliasDAL: { findBySsoExternalIds: vi.fn().mockResolvedValue([]) },orgDAL: {findById: vi.fn().mockResolvedValue({ id: ORG_ID, rootOrgId: null }),- findEffectiveOrgMembership: vi.fn().mockResolvedValue({ isActive: true })+ findActiveEffectiveOrgMemberActorIds: vi.fn(({ actorIds }: { actorIds: string[] }) =>+ Promise.resolve(new Set(actorIds))+ )},membershipDAL: {find: vi.fn(({ scope }: { scope: string }) =>- Promise.resolve(scope === AccessScope.Project ? productMemberships : [])+ Promise.resolve(+ scope === AccessScope.Project+ ? productMemberships.map((row) => ({ ...row, actorIdentityId: IDENTITY_ID, createdAt: new Date() }))+ : []+ )),// assertWillRetainProjectAdmin takes an advisory lock through tx.raw, then counts live admins// with a query built off tx() itself. The chain answers with the fixture's admin count, so// adminMembershipIds still decides whether the guard lets the write through.transaction: vi.fn((cb: (tx: unknown) => unknown) => Promise.resolve(cb(buildTx(adminMembershipIds.length)))),- create: vi.fn().mockResolvedValue({ id: "mem-new", createdAt: new Date() }),- delete: vi.fn().mockResolvedValue(undefined),- deleteById: vi.fn().mockResolvedValue(undefined)+ insertMany: vi.fn((rows: Record<string, unknown>[]) =>+ Promise.resolve(rows.map((row) => ({ ...row, id: "mem-new", createdAt: new Date() })))+ ),+ delete: vi.fn().mockResolvedValue(undefined)},membershipRoleDAL: {find: vi.fn().mockResolvedValue(adminMembershipIds.map((id) => ({ membershipId: id, role: ProjectMembershipRole.Admin }))),create: vi.fn(({ role }: { role: string }) => Promise.resolve({ role })),- delete: vi.fn().mockResolvedValue(undefined),- update: vi.fn().mockResolvedValue(undefined)+ insertMany: vi.fn().mockResolvedValue(undefined),+ delete: vi.fn().mockResolvedValue(undefined)},projectAccessRequestDAL: { delete: vi.fn().mockResolvedValue(undefined) },usageMeteringService: { emitForProject: vi.fn() }@@ -89,41 +107,41 @@ describe("agentVaultMembership guards", () => {const { service, deps } = buildService({ identityProjectId: OTHER_PROJECT_ID });await expect(- service.addProductMember({+ service.addProductMembers({projectId: PROJECT_ID,- identityId: IDENTITY_ID,+ ...addIds,role: ProjectMembershipRole.Member,ctx})- ).rejects.toThrow("belongs to another project");+ ).rejects.toThrow("belong to another project");- expect(deps.membershipDAL.create).not.toHaveBeenCalled();+ expect(deps.membershipDAL.insertMany).not.toHaveBeenCalled();});test("accepts an identity that belongs to no project", async () => {const { service } = buildService({ identityProjectId: null });- const added = await service.addProductMember({+ const { members } = await service.addProductMembers({projectId: PROJECT_ID,- identityId: IDENTITY_ID,+ ...addIds,role: ProjectMembershipRole.Member,ctx});- expect(added.membershipId).toBe("mem-new");+ expect(members[0].id).toBe("mem-new");});test("accepts an identity created inside Agent Vault itself", async () => {const { service } = buildService({ identityProjectId: PROJECT_ID });- const added = await service.addProductMember({+ const { members } = await service.addProductMembers({projectId: PROJECT_ID,- identityId: IDENTITY_ID,+ ...addIds,role: ProjectMembershipRole.Member,ctx});- expect(added.membershipId).toBe("mem-new");+ expect(members[0].id).toBe("mem-new");});// Removing only the membership would leave the identity live but off every screen: this product's tab@@ -131,11 +149,11 @@ describe("agentVaultMembership guards", () => {test("refuses to detach an identity Agent Vault owns, pointing at delete instead", async () => {const { service, deps } = buildService({ identityProjectId: PROJECT_ID });- await expect(service.removeProductMember({ projectId: PROJECT_ID, identityId: IDENTITY_ID, ctx })).rejects.toThrow(+ await expect(service.revokeProductMembers({ projectId: PROJECT_ID, ...addIds, ctx })).rejects.toThrow("Delete the identity instead");- expect(deps.membershipDAL.deleteById).not.toHaveBeenCalled();+ expect(deps.membershipDAL.delete).not.toHaveBeenCalled();});test("still detaches an identity the organization owns", async () => {@@ -145,9 +163,9 @@ describe("agentVaultMembership guards", () => {adminMembershipIds: ["mem-other"]});- await service.removeProductMember({ projectId: PROJECT_ID, identityId: IDENTITY_ID, ctx });+ await service.revokeProductMembers({ projectId: PROJECT_ID, ...addIds, ctx });- expect(deps.membershipDAL.deleteById).toHaveBeenCalledWith("mem-1", expect.anything());+ expect(deps.membershipDAL.delete).toHaveBeenCalledWith({ $in: { id: ["mem-1"] } }, expect.anything());});test("refuses to change your own role", async () => {@@ -156,7 +174,7 @@ describe("agentVaultMembership guards", () => {await expect(service.updateProductMemberRole({projectId: PROJECT_ID,- userId: ACTOR_ID,+ actor: { type: AgentVaultMemberType.User, id: ACTOR_ID },role: ProjectMembershipRole.Member,ctx})@@ -171,13 +189,13 @@ describe("agentVaultMembership guards", () => {adminMembershipIds: ["mem-other"]});- const updated = await service.updateProductMemberRole({+ const { member } = await service.updateProductMemberRole({projectId: PROJECT_ID,- userId: "someone-else",+ actor: { type: AgentVaultMemberType.MachineIdentity, id: IDENTITY_ID },role: ProjectMembershipRole.Member,ctx});- expect(updated.role).toBe(ProjectMembershipRole.Member);+ expect(member.role).toBe(ProjectMembershipRole.Member);});});diff --git a/backend/src/ee/services/agent-vault-member/agent-vault-membership-service.ts b/backend/src/ee/services/agent-vault-member/agent-vault-membership-service.tsindex c2ecfea141..81eac9aac0 100644--- a/backend/src/ee/services/agent-vault-member/agent-vault-membership-service.ts+++ b/backend/src/ee/services/agent-vault-member/agent-vault-membership-service.ts@@ -1,11 +1,13 @@import { ForbiddenError } from "@casl/ability";+import { Knex } from "knex";import {AccessScope,ActionProjectType,- OrgMembershipStatus,ProjectMembershipRole,- RESOURCE_SCOPE+ RESOURCE_SCOPE,+ ResourceType,+ TMemberships} from "@app/db/schemas";import { TGroupDALFactory } from "@app/ee/services/group/group-dal";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";@@ -30,16 +32,19 @@ import { TUserAliasDALFactory } from "@app/services/user-alias/user-alias-dal";import { resolveUsersBySsoExternalId } from "@app/services/user-alias/user-alias-fns";import { TAgentVaultActorContext } from "../agent-vault/agent-vault-actor-types";+import { AgentVaultMemberType } from "../agent-vault/agent-vault-enums";+import { TAgentVaultMemberDALFactory } from "./agent-vault-member-dal";type TAgentVaultMembershipServiceFactoryDep = {- membershipDAL: Pick<TMembershipDALFactory, "create" | "find" | "transaction" | "delete" | "deleteById">;+ agentVaultMemberDAL: Pick<TAgentVaultMemberDALFactory, "findProductMembers">;+ membershipDAL: Pick<TMembershipDALFactory, "insertMany" | "find" | "transaction" | "delete">;identityDAL: Pick<TIdentityDALFactory, "find">;- membershipRoleDAL: Pick<TMembershipRoleDALFactory, "create" | "find" | "delete" | "update">;+ membershipRoleDAL: Pick<TMembershipRoleDALFactory, "create" | "insertMany" | "delete">;groupDAL: Pick<TGroupDALFactory, "find">;projectAccessRequestDAL: Pick<TProjectAccessRequestDALFactory, "delete">;userDAL: Pick<TUserDALFactory, "find">;userAliasDAL: Pick<TUserAliasDALFactory, "findBySsoExternalIds">;- orgDAL: Pick<TOrgDALFactory, "findById" | "findEffectiveOrgMembership">;+ orgDAL: Pick<TOrgDALFactory, "findById" | "findActiveEffectiveOrgMemberActorIds">;permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;usageMeteringService: Pick<TUsageMeteringServiceFactory, "emitForProject">;};@@ -51,36 +56,86 @@ export type TListAgentVaultProductMembersDTO = {ctx: TAgentVaultActorContext;};-type TAgentVaultProductActor = {- userId?: string;- groupId?: string;- identityId?: string;+export type TListAgentVaultMembersDTO = {+ projectId: string;+ actorType?: AgentVaultMemberType;+ search?: string;+ limit: number;+ offset: number;+ ctx: TAgentVaultActorContext;};-export type TAddAgentVaultProductMemberDTO = TAgentVaultProductActor & {+export type TAgentVaultActorRef = { type: AgentVaultMemberType; id: string };++type TAgentVaultNamedActor = TAgentVaultActorRef & { identifier: string };++export type TAgentVaultMemberIds = {+ userIds: string[];+ groupIds: string[];+ machineIdentityIds: string[];+};++export type TAddAgentVaultProductMembersDTO = TAgentVaultMemberIds & {projectId: string;- role: string;+ emails: string[];+ role: ProjectMembershipRole.Admin | ProjectMembershipRole.Member;ctx: TAgentVaultActorContext;};-export type TUpdateAgentVaultProductMemberDTO = TAddAgentVaultProductMemberDTO;--export type TRemoveAgentVaultProductMemberDTO = TAgentVaultProductActor & {+export type TUpdateAgentVaultProductMemberDTO = {projectId: string;+ actor: TAgentVaultActorRef;+ role: string;ctx: TAgentVaultActorContext;};-export type TAddAgentVaultProductUserMembersDTO = {+export type TRevokeAgentVaultProductMembersDTO = TAgentVaultMemberIds & {projectId: string;- userIds: string[];- emails: string[];- role: ProjectMembershipRole.Admin | ProjectMembershipRole.Member;ctx: TAgentVaultActorContext;};+// actorName is for the audit body; the response schemas do not select it.+type TAgentVaultWrittenMember = {+ id: string;+ role: string;+ createdAt: Date;+ actor: TAgentVaultActorRef;+ actorName?: string;+};++type TAgentVaultMemberWriteResult = Promise<{+ members: TAgentVaultWrittenMember[];+ skipped: TAgentVaultNamedActor[];+}>;+const VALID_PRODUCT_ROLES: string[] = [ProjectMembershipRole.Admin, ProjectMembershipRole.Member];+const ALL_ACTOR_TYPES = [AgentVaultMemberType.User, AgentVaultMemberType.Group, AgentVaultMemberType.MachineIdentity];++const ACTOR_COLUMN: Record<AgentVaultMemberType, "actorUserId" | "actorIdentityId" | "actorGroupId"> = {+ [AgentVaultMemberType.User]: "actorUserId",+ [AgentVaultMemberType.MachineIdentity]: "actorIdentityId",+ [AgentVaultMemberType.Group]: "actorGroupId"+};++const ACTOR_LABEL: Record<AgentVaultMemberType, string> = {+ [AgentVaultMemberType.User]: "User",+ [AgentVaultMemberType.MachineIdentity]: "Machine identity",+ [AgentVaultMemberType.Group]: "Group"+};++const actorToIds = (actor: TAgentVaultActorRef): TAgentVaultMemberIds => ({+ userIds: actor.type === AgentVaultMemberType.User ? [actor.id] : [],+ groupIds: actor.type === AgentVaultMemberType.Group ? [actor.id] : [],+ machineIdentityIds: actor.type === AgentVaultMemberType.MachineIdentity ? [actor.id] : []+});++const isSelf = (actor: TAgentVaultActorRef, ctx: TAgentVaultActorContext) =>+ (actor.type === AgentVaultMemberType.User && ctx.actor === ActorType.USER && actor.id === ctx.actorId) ||+ (actor.type === AgentVaultMemberType.MachineIdentity && ctx.actor === ActorType.IDENTITY && actor.id === ctx.actorId);+export const agentVaultMembershipServiceFactory = ({+ agentVaultMemberDAL,membershipDAL,identityDAL,membershipRoleDAL,@@ -109,349 +164,323 @@ export const agentVaultMembershipServiceFactory = ({}};- const addProductUserMembers = async ({- projectId,- userIds,- emails,- role,- ctx- }: TAddAgentVaultProductUserMembersDTO) => {- await checkProductAdmin(projectId, ctx);+ type TProjectPermission = Awaited<ReturnType<typeof getActorPermission>>["permission"];- if (!VALID_PRODUCT_ROLES.includes(role)) {- throw new BadRequestError({- message: `Invalid product role '${role}'. Expected: ${VALID_PRODUCT_ROLES.join(", ")}`- });+ const canReadActorType = (permission: TProjectPermission, type: AgentVaultMemberType) => {+ if (type === AgentVaultMemberType.User) {+ return permission.can(ProjectPermissionMemberActions.Read, ProjectPermissionSub.Member);}-- const usersByEmail = emails.length ? await userDAL.find({ $in: { username: emails } }) : [];- const userByEmail = new Map(usersByEmail.map((u) => [u.username, u]));-- // The invite this accompanies resolves IdP identifiers through SSO aliases, so this half has to as well.- const unmatched = emails.filter((e) => !userByEmail.has(e));- if (unmatched.length) {- const org = await orgDAL.findById(ctx.actorOrgId);- const { resolved, ambiguousIdentifiers } = await resolveUsersBySsoExternalId({- identifiers: unmatched,- orgId: ctx.actorOrgId,- rootOrgId: org?.rootOrgId,- userAliasDAL,- userDAL- });-- if (ambiguousIdentifiers.length) {- throw new BadRequestError({- message: `Identifier(s) ${ambiguousIdentifiers- .map((el) => `'${el}'`)- .join(- ", "- )} match more than one SSO account in this organization. Use the user's email address instead, or contact support to resolve the duplicate.`- });- }-- resolved.forEach((user, identifier) => userByEmail.set(identifier, user));+ if (type === AgentVaultMemberType.Group) {+ return permission.can(ProjectPermissionGroupActions.Read, ProjectPermissionSub.Groups);}+ return permission.can(ProjectPermissionIdentityActions.Read, ProjectPermissionSub.Identity);+ };- const unresolved = emails.filter((e) => !userByEmail.has(e));-- const candidates: { userId: string; label: string }[] = [];- const seen = new Set<string>();- for (const id of userIds) {- if (!seen.has(id)) {- seen.add(id);- candidates.push({ userId: id, label: id });- }+ const assertCanReadActorType = (permission: TProjectPermission, type: AgentVaultMemberType) => {+ const forbidden = ForbiddenError.from(permission);+ if (type === AgentVaultMemberType.User) {+ forbidden.throwUnlessCan(ProjectPermissionMemberActions.Read, ProjectPermissionSub.Member);+ return;}- for (const email of emails) {- const user = userByEmail.get(email);- if (user && !seen.has(user.id)) {- seen.add(user.id);- candidates.push({ userId: user.id, label: email });- }+ if (type === AgentVaultMemberType.Group) {+ forbidden.throwUnlessCan(ProjectPermissionGroupActions.Read, ProjectPermissionSub.Groups);+ return;}+ forbidden.throwUnlessCan(ProjectPermissionIdentityActions.Read, ProjectPermissionSub.Identity);+ };- const existing = await membershipDAL.find({ scope: AccessScope.Project, scopeProjectId: projectId });- const alreadyAttached = new Set(existing.map((m) => m.actorUserId).filter((v): v is string => Boolean(v)));- const skipped: string[] = [];+ const listProductMembers = async ({+ projectId,+ actorType,+ search,+ limit,+ offset,+ ctx+ }: TListAgentVaultMembersDTO) => {+ const { permission } = await getActorPermission(projectId, ctx);- const orgMemberships = candidates.length- ? await membershipDAL.find({- scope: AccessScope.Organization,- scopeOrgId: ctx.actorOrgId,- isActive: true,- $in: { actorUserId: candidates.map((c) => c.userId) }- })- : [];- const orgMemberIds = new Set(orgMemberships.map((m) => m.actorUserId));+ const asked = actorType ? [actorType] : ALL_ACTOR_TYPES;+ const readable = asked.filter((type) => canReadActorType(permission, type));+ if (!readable.length) assertCanReadActorType(permission, asked[0]);- const toCreate = candidates.filter((c) => {- if (!orgMemberIds.has(c.userId)) {- unresolved.push(c.label);- return false;- }- if (alreadyAttached.has(c.userId)) {- skipped.push(c.label);- return false;- }- return true;+ return agentVaultMemberDAL.findProductMembers({+ projectId,+ orgId: ctx.actorOrgId,+ actorTypes: readable,+ search,+ limit,+ offset});+ };- if (unresolved.length) {- const rejected = unresolved.map((el) => `'${el}'`).join(", ");+ const assertValidRole = (role: string) => {+ if (!VALID_PRODUCT_ROLES.includes(role)) {throw new BadRequestError({- message: `Cannot add ${rejected} to Agent Vault because they are not an active member of this organization. Invite them to the organization first.`+ message: `Invalid product role '${role}'. Expected: ${VALID_PRODUCT_ROLES.join(", ")}`});}-- const memberships = await membershipDAL.transaction(async (tx) => {- const results: { membershipId: string; userId: string; userName?: string; role: string; createdAt: Date }[] = [];- for (const { userId, label } of toCreate) {- // eslint-disable-next-line no-await-in-loop- const membership = await membershipDAL.create(- {- scope: AccessScope.Project,- scopeOrgId: ctx.actorOrgId,- scopeProjectId: projectId,- actorUserId: userId,- isActive: true- },- tx- );- // eslint-disable-next-line no-await-in-loop- const membershipRole = await membershipRoleDAL.create({ membershipId: membership.id, role }, tx);- // eslint-disable-next-line no-await-in-loop- await projectAccessRequestDAL.delete({ projectId, requesterUserId: userId }, tx);- results.push({- userName: label.includes("@") ? label : undefined,- membershipId: membership.id,- userId,- role: membershipRole.role,- createdAt: membership.createdAt- });- }- return results;- });-- if (memberships.length > 0) {- usageMeteringService.emitForProject(projectId, AgentVaultIdentities.key);- }-- return { memberships, skipped };};- const resolveMemberships = async (memberships: Awaited<ReturnType<typeof membershipDAL.find>>) => {- if (!memberships.length) return [];+ const actorKey = (actor: TAgentVaultActorRef) => `${actor.type}:${actor.id}`;- const roles = await membershipRoleDAL.find({ $in: { membershipId: memberships.map((m) => m.id) } });- const roleByMembership = new Map(roles.map((r) => [r.membershipId, r]));+ const named = (actors: { type: AgentVaultMemberType; id: string }[], type: AgentVaultMemberType) =>+ actors.filter((actor) => actor.type === type).map((actor) => actor.id);- return memberships.map((m) => {- const role = roleByMembership.get(m.id);- return {- membershipId: m.id,- userId: m.actorUserId ?? null,- identityId: m.actorIdentityId ?? null,- groupId: m.actorGroupId ?? null,- role: role?.role ?? ProjectMembershipRole.Member,- isActive: m.isActive,- createdAt: m.createdAt- };- });- };+ const resolveNamedActors = async (+ { userIds, groupIds, machineIdentityIds, emails }: TAgentVaultMemberIds & { emails?: string[] },+ orgId: string+ ) => {+ const byKey = new Map<string, TAgentVaultNamedActor>();+ const add = (type: AgentVaultMemberType, id: string, identifier: string) => {+ const key = `${type}:${id}`;+ if (!byKey.has(key)) byKey.set(key, { type, id, identifier });+ };++ userIds.forEach((id) => add(AgentVaultMemberType.User, id, id));+ groupIds.forEach((id) => add(AgentVaultMemberType.Group, id, id));+ machineIdentityIds.forEach((id) => add(AgentVaultMemberType.MachineIdentity, id, id));++ if (emails?.length) {+ const usersByEmail = await userDAL.find({ $in: { username: emails } });+ const userByEmail = new Map(usersByEmail.map((user) => [user.username, user]));++ // The invite this accompanies resolves IdP identifiers through SSO aliases, so this half has to as well.+ const unmatched = emails.filter((email) => !userByEmail.has(email));+ if (unmatched.length) {+ const org = await orgDAL.findById(orgId);+ const { resolved, ambiguousIdentifiers } = await resolveUsersBySsoExternalId({+ identifiers: unmatched,+ orgId,+ rootOrgId: org?.rootOrgId,+ userAliasDAL,+ userDAL+ });- const listProductUserMembers = async ({ projectId, ctx }: TListAgentVaultProductMembersDTO) => {- const { permission } = await getActorPermission(projectId, ctx);- ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionMemberActions.Read, ProjectPermissionSub.Member);+ if (ambiguousIdentifiers.length) {+ throw new BadRequestError({+ message: `Identifier(s) ${ambiguousIdentifiers+ .map((el) => `'${el}'`)+ .join(+ ", "+ )} match more than one SSO account in this organization. Use the user's email address instead, or contact support to resolve the duplicate.`+ });+ }++ resolved.forEach((user, identifier) => userByEmail.set(identifier, user));+ }- const memberships = await membershipDAL.find({ scope: AccessScope.Project, scopeProjectId: projectId });- const resolved = await resolveMemberships(memberships.filter((m) => m.actorUserId));+ const unresolved = emails.filter((email) => !userByEmail.has(email));+ if (unresolved.length) {+ throw new BadRequestError({+ message: `Cannot add ${unresolved+ .map((el) => `'${el}'`)+ .join(", ")} to Agent Vault because they are not a member of this organization. Invite them first.`+ });+ }- const userIds = resolved.map((m) => m.userId).filter((v): v is string => Boolean(v));- if (!userIds.length) return [];- const [users, orgMemberships] = await Promise.all([- userDAL.find({ $in: { id: userIds } }),- membershipDAL.find({ scope: AccessScope.Organization, scopeOrgId: ctx.actorOrgId, $in: { actorUserId: userIds } })- ]);- const userById = new Map(users.map((u) => [u.id, u]));- const orgStatusByUser = new Map(orgMemberships.map((m) => [m.actorUserId, m.status]));+ emails.forEach((email) => add(AgentVaultMemberType.User, userByEmail.get(email)!.id, email));+ }- return resolved.map((m) => {- const user = m.userId ? userById.get(m.userId) : undefined;- return {- ...m,- email: user?.email ?? null,- username: user?.username ?? "",- firstName: user?.firstName ?? null,- lastName: user?.lastName ?? null,- isOrgMembershipPending: orgStatusByUser.get(m.userId ?? "") === OrgMembershipStatus.Invited- };- });+ return [...byKey.values()];};- const listProductGroupMembers = async ({ projectId, ctx }: TListAgentVaultProductMembersDTO) => {- const { permission } = await getActorPermission(projectId, ctx);- ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionGroupActions.Read, ProjectPermissionSub.Groups);-- const memberships = await membershipDAL.find({ scope: AccessScope.Project, scopeProjectId: projectId });- const resolved = await resolveMemberships(memberships.filter((m) => m.actorGroupId));-- const groupIds = resolved.map((m) => m.groupId).filter((v): v is string => Boolean(v));- const groups = groupIds.length ? await groupDAL.find({ $in: { id: groupIds } }) : [];- const groupById = new Map(groups.map((g) => [g.id, g]));+ const resolveActorNames = async (actors: TAgentVaultNamedActor[]) => {+ const [users, groups, identities] = await Promise.all([+ named(actors, AgentVaultMemberType.User).length+ ? userDAL.find({ $in: { id: named(actors, AgentVaultMemberType.User) } })+ : [],+ named(actors, AgentVaultMemberType.Group).length+ ? groupDAL.find({ $in: { id: named(actors, AgentVaultMemberType.Group) } })+ : [],+ named(actors, AgentVaultMemberType.MachineIdentity).length+ ? identityDAL.find({ $in: { id: named(actors, AgentVaultMemberType.MachineIdentity) } })+ : []+ ]);- return resolved.map((m) => ({ ...m, name: (m.groupId && groupById.get(m.groupId)?.name) || "" }));+ const nameByKey = new Map<string, string>();+ users.forEach((user) => nameByKey.set(`${AgentVaultMemberType.User}:${user.id}`, user.username));+ groups.forEach((group) => nameByKey.set(`${AgentVaultMemberType.Group}:${group.id}`, group.name));+ identities.forEach((identity) =>+ nameByKey.set(`${AgentVaultMemberType.MachineIdentity}:${identity.id}`, identity.name)+ );+ return nameByKey;};- const listProductIdentityMembers = async ({ projectId, ctx }: TListAgentVaultProductMembersDTO) => {- const { permission } = await getActorPermission(projectId, ctx);- ForbiddenError.from(permission).throwUnlessCan(- ProjectPermissionIdentityActions.Read,- ProjectPermissionSub.Identity- );+ // resolveSession refuses an actor with no active org membership, so one added without it could never mint.+ const assertActorsAreAddable = async (actors: TAgentVaultNamedActor[], orgId: string, projectId: string) => {+ const groupIds = named(actors, AgentVaultMemberType.Group);+ const machineIdentityIds = named(actors, AgentVaultMemberType.MachineIdentity);+ const userIds = named(actors, AgentVaultMemberType.User);++ const [groups, identities, userMemberIds, identityMemberIds] = await Promise.all([+ groupIds.length ? groupDAL.find({ $in: { id: groupIds }, orgId }) : [],+ machineIdentityIds.length ? identityDAL.find({ $in: { id: machineIdentityIds }, orgId }) : [],+ orgDAL.findActiveEffectiveOrgMemberActorIds({ actorType: ActorType.USER, actorIds: userIds, orgId }),+ orgDAL.findActiveEffectiveOrgMemberActorIds({+ actorType: ActorType.IDENTITY,+ actorIds: machineIdentityIds,+ orgId+ })+ ]);- const memberships = await membershipDAL.find({ scope: AccessScope.Project, scopeProjectId: projectId });- const identityMemberships = memberships.filter((m) => m.actorIdentityId);- const resolved = await resolveMemberships(identityMemberships);+ const foundGroups = new Set(groups.map((group) => group.id));+ const missingGroups = groupIds.filter((id) => !foundGroups.has(id));+ if (missingGroups.length) {+ throw new NotFoundError({ message: `Group(s) ${missingGroups.map((el) => `'${el}'`).join(", ")} not found` });+ }- const identityIds = resolved.map((m) => m.identityId).filter((v): v is string => Boolean(v));- const identities = identityIds.length ? await identityDAL.find({ $in: { id: identityIds } }) : [];- const identityById = new Map(identities.map((i) => [i.id, i]));+ const identityById = new Map(identities.map((identity) => [identity.id, identity]));+ const missingIdentities = machineIdentityIds.filter((id) => !identityById.has(id));+ if (missingIdentities.length) {+ throw new NotFoundError({+ message: `Machine identity(s) ${missingIdentities.map((el) => `'${el}'`).join(", ")} not found`+ });+ }- return resolved.map((m) => {- const identity = m.identityId ? identityById.get(m.identityId) : undefined;- return {- ...m,- name: identity?.name ?? "",- identityProjectId: identity?.projectId ?? null,- identityOrgId: identity?.orgId ?? null- };+ // An identity created inside another product still carries an org-scope NoAccess membership, so the+ // org check below passes for it. Only Agent Vault's own identities and unscoped org ones belong here.+ const foreign = machineIdentityIds.filter((id) => {+ const projectOfIdentity = identityById.get(id)?.projectId;+ return projectOfIdentity && projectOfIdentity !== projectId;});- };-- const resolveActorColumn = (dto: { userId?: string; groupId?: string; identityId?: string }) => {- if (dto.userId) return { column: "actorUserId" as const, id: dto.userId, label: "User" };- if (dto.groupId) return { column: "actorGroupId" as const, id: dto.groupId, label: "Group" };- if (dto.identityId) return { column: "actorIdentityId" as const, id: dto.identityId, label: "Machine identity" };- throw new BadRequestError({ message: "Name exactly one user, group, or machine identity" });- };-- const assertValidRole = (role: string) => {- if (!VALID_PRODUCT_ROLES.includes(role)) {+ if (foreign.length) {throw new BadRequestError({- message: `Invalid product role '${role}'. Expected: ${VALID_PRODUCT_ROLES.join(", ")}`+ message: `Machine identity(s) ${foreign+ .map((el) => `'${el}'`)+ .join(", ")} belong to another project and cannot be given access to Agent Vault`});}- };- // resolveSession refuses an actor without an active org membership, so a member added without one could never mint.- const assertActorIsInOrg = async (- dto: { userId?: string; groupId?: string; identityId?: string },- orgId: string,- projectId: string,- label: string- ) => {- if (dto.groupId) {- const [group] = await groupDAL.find({ id: dto.groupId, orgId });- if (!group) throw new NotFoundError({ message: `Group with ID '${dto.groupId}' not found` });- return;- }- if (dto.identityId) {- const [identity] = await identityDAL.find({ id: dto.identityId, orgId });- if (!identity) throw new NotFoundError({ message: `Machine identity with ID '${dto.identityId}' not found` });- // An identity created inside another product still carries an org-scope NoAccess membership, so the- // org check below passes for it. Only Agent Vault's own identities and unscoped org ones belong here.- if (identity.projectId && identity.projectId !== projectId) {- throw new BadRequestError({- message: `Machine identity with ID '${dto.identityId}' belongs to another project and cannot be given access to Agent Vault`- });- }- }-- const actorId = dto.userId ?? dto.identityId!;// Status is not required: an org invite that has not been accepted still gets project access// everywhere else on the platform, and resolveSession refuses the actor until it is. isActive is the// real gate, so a deactivated member is still refused.- const membership = await orgDAL.findEffectiveOrgMembership({- actorType: dto.userId ? ActorType.USER : ActorType.IDENTITY,- actorId,- orgId,- acceptAnyStatus: true+ const outsiders = actors.filter((actor) => {+ if (actor.type === AgentVaultMemberType.User) return !userMemberIds.has(actor.id);+ if (actor.type === AgentVaultMemberType.MachineIdentity) return !identityMemberIds.has(actor.id);+ return false;});- if (!membership?.isActive) {+ if (outsiders.length) {throw new BadRequestError({- message: `Cannot add ${label.toLowerCase()} '${actorId}' to Agent Vault because they are not an active member of this organization. Invite them to the organization first.`+ message: `Cannot add ${outsiders+ .map((actor) => `'${actor.identifier}'`)+ .join(+ ", "+ )} to Agent Vault because they are not an active member of this organization. Invite them to the organization first.`});}};- const resolveActorLabel = async (dto: { userId?: string; groupId?: string; identityId?: string }) => {- if (dto.groupId) {- const [group] = await groupDAL.find({ id: dto.groupId });- return { groupName: group?.name };- }- if (dto.identityId) {- const [identity] = await identityDAL.find({ id: dto.identityId });- return { identityName: identity?.name };- }- const [user] = dto.userId ? await userDAL.find({ id: dto.userId }) : [];- return { userName: user?.username };+ const findMembershipsForActors = async (projectId: string, actors: TAgentVaultActorRef[], tx?: Knex) => {+ const byActor = new Map<string, TMemberships>();++ await Promise.all(+ ALL_ACTOR_TYPES.map(async (type) => {+ const ids = named(actors, type);+ if (!ids.length) return;+ const rows = await membershipDAL.find(+ {+ scope: AccessScope.Project,+ scopeProjectId: projectId,+ $in: { [ACTOR_COLUMN[type]]: ids }+ },+ { tx }+ );+ rows.forEach((row) => {+ const id = row[ACTOR_COLUMN[type]];+ if (id) byActor.set(`${type}:${id}`, row);+ });+ })+ );++ return byActor;};- const addProductMember = async ({ projectId, role, ctx, ...dto }: TAddAgentVaultProductMemberDTO) => {+ const addProductMembers = async ({+ projectId,+ role,+ ctx,+ emails,+ ...ids+ }: TAddAgentVaultProductMembersDTO): TAgentVaultMemberWriteResult => {await checkProductAdmin(projectId, ctx);assertValidRole(role);- const { column, id, label } = resolveActorColumn(dto);- await assertActorIsInOrg(dto, ctx.actorOrgId, projectId, label);+ const actors = await resolveNamedActors({ ...ids, emails }, ctx.actorOrgId);+ await assertActorsAreAddable(actors, ctx.actorOrgId, projectId);- const result = await membershipDAL.transaction(async (tx) => {- const existing = await membershipDAL.find(- { scope: AccessScope.Project, scopeProjectId: projectId, [column]: id },- { tx }- );- if (existing.length) {- throw new BadRequestError({ message: `${label} already has access to Agent Vault` });- }+ const nameByKey = await resolveActorNames(actors);++ const written = await membershipDAL.transaction(async (tx) => {+ const existing = await findMembershipsForActors(projectId, actors, tx);+ const skipped = actors.filter((actor) => existing.has(actorKey(actor)));+ const toCreate = actors.filter((actor) => !existing.has(actorKey(actor)));+ if (!toCreate.length) return { created: [], skipped };- const membership = await membershipDAL.create(- {+ const memberships = await membershipDAL.insertMany(+ toCreate.map((actor) => ({scope: AccessScope.Project,scopeOrgId: ctx.actorOrgId,scopeProjectId: projectId,- [column]: id,+ [ACTOR_COLUMN[actor.type]]: actor.id,isActive: true- },+ })),tx);- const membershipRole = await membershipRoleDAL.create({ membershipId: membership.id, role }, tx);- if (dto.userId) await projectAccessRequestDAL.delete({ projectId, requesterUserId: dto.userId }, tx);+ await membershipRoleDAL.insertMany(+ memberships.map((membership) => ({ membershipId: membership.id, role })),+ tx+ );++ const addedUserIds = named(toCreate, AgentVaultMemberType.User);+ if (addedUserIds.length) {+ await projectAccessRequestDAL.delete({ projectId, $in: { requesterUserId: addedUserIds } }, tx);+ }++ const membershipByActor = new Map(+ memberships.map((membership) => {+ const type = ALL_ACTOR_TYPES.find((el) => membership[ACTOR_COLUMN[el]])!;+ return [`${type}:${membership[ACTOR_COLUMN[type]]!}`, membership];+ })+ );- return { membershipId: membership.id, ...dto, role: membershipRole.role, createdAt: membership.createdAt };+ return {+ created: toCreate.map((actor) => {+ const membership = membershipByActor.get(actorKey(actor))!;+ return {+ id: membership.id,+ role,+ createdAt: membership.createdAt,+ actor: { type: actor.type, id: actor.id },+ actorName: nameByKey.get(actorKey(actor))+ };+ }),+ skipped+ };});- usageMeteringService.emitForProject(projectId, AgentVaultIdentities.key);- return { ...result, ...(await resolveActorLabel(dto)) };+ if (written.created.length) usageMeteringService.emitForProject(projectId, AgentVaultIdentities.key);+ return { members: written.created, skipped: written.skipped };};- const updateProductMemberRole = async ({ projectId, role, ctx, ...dto }: TUpdateAgentVaultProductMemberDTO) => {+ const updateProductMemberRole = async ({ projectId, actor, role, ctx }: TUpdateAgentVaultProductMemberDTO) => {await checkProductAdmin(projectId, ctx);assertValidRole(role);- if ((dto.userId && dto.userId === ctx.actorId) || (dto.identityId && dto.identityId === ctx.actorId)) {- throw new ForbiddenRequestError({ message: "You cannot change your own role" });- }+ if (isSelf(actor, ctx)) throw new ForbiddenRequestError({ message: "You cannot change your own role" });- const { column, id, label } = resolveActorColumn(dto);+ const [namedActor] = await resolveNamedActors({ ...actorToIds(actor), emails: [] }, ctx.actorOrgId);// The add paths check this; promoting did not, so a deactivated member could still be made an admin.- await assertActorIsInOrg(dto, ctx.actorOrgId, projectId, label);+ await assertActorsAreAddable([namedActor], ctx.actorOrgId, projectId);- const updated = await membershipDAL.transaction(async (tx) => {- const [membership] = await membershipDAL.find(- { scope: AccessScope.Project, scopeProjectId: projectId, [column]: id },- { tx }- );- if (!membership) throw new NotFoundError({ message: `${label} does not have access to Agent Vault` });+ const nameByKey = await resolveActorNames([namedActor]);++ return membershipDAL.transaction(async (tx) => {+ const memberships = await findMembershipsForActors(projectId, [actor], tx);+ const membership = memberships.get(actorKey(actor));+ if (!membership) {+ throw new NotFoundError({ message: `${ACTOR_LABEL[actor.type]} does not have access to Agent Vault` });+ }if (role !== ProjectMembershipRole.Admin) {await assertWillRetainProjectAdmin({@@ -465,65 +494,105 @@ export const agentVaultMembershipServiceFactory = ({await membershipRoleDAL.delete({ membershipId: membership.id }, tx);const membershipRole = await membershipRoleDAL.create({ membershipId: membership.id, role }, tx);- return { membershipId: membership.id, ...dto, role: membershipRole.role };+ return {+ member: {+ id: membership.id,+ role: membershipRole.role,+ createdAt: membership.createdAt,+ actor,+ actorName: nameByKey.get(actorKey(actor))+ }+ };});-- return { ...updated, ...(await resolveActorLabel(dto)) };};- const removeProductMember = async ({ projectId, ctx, ...dto }: TRemoveAgentVaultProductMemberDTO) => {+ const revokeProductMembers = async ({+ projectId,+ ctx,+ ...ids+ }: TRevokeAgentVaultProductMembersDTO): TAgentVaultMemberWriteResult => {await checkProductAdmin(projectId, ctx);- if ((dto.userId && dto.userId === ctx.actorId) || (dto.identityId && dto.identityId === ctx.actorId)) {+ const actors = await resolveNamedActors({ ...ids, emails: [] }, ctx.actorOrgId);++ // Naming yourself is a mistake, not a no-op: skipping it would let an admin believe they had left.+ if (actors.some((actor) => isSelf(actor, ctx))) {throw new ForbiddenRequestError({ message: "You cannot remove your own access" });}- const { column, id, label } = resolveActorColumn(dto);-// An identity scoped to this project exists only to be an Agent Vault member. Detaching it would leave// a live identity no screen can reach: this tab lists by membership, and the org list hides scoped ones.- if (dto.identityId) {- const [identity] = await identityDAL.find({ id: dto.identityId });- if (identity?.projectId === projectId) {+ const machineIdentityIds = named(actors, AgentVaultMemberType.MachineIdentity);+ if (machineIdentityIds.length) {+ const owned = (await identityDAL.find({ $in: { id: machineIdentityIds }, projectId })).map((el) => el.id);+ if (owned.length) {throw new BadRequestError({- message: `Machine identity with ID '${dto.identityId}' is managed by Agent Vault. Delete the identity instead of removing its access`+ message: `Machine identity(s) ${owned+ .map((el) => `'${el}'`)+ .join(", ")} are managed by Agent Vault. Delete the identity instead of removing its access`});}}- const membershipId = await membershipDAL.transaction(async (tx) => {- const [membership] = await membershipDAL.find(- { scope: AccessScope.Project, scopeProjectId: projectId, [column]: id },- { tx }- );- if (!membership) throw new NotFoundError({ message: `${label} does not have access to Agent Vault` });+ const nameByKey = await resolveActorNames(actors);++ const written = await membershipDAL.transaction(async (tx) => {+ const existing = await findMembershipsForActors(projectId, actors, tx);+ const skipped = actors.filter((actor) => !existing.has(actorKey(actor)));+ const held = actors.filter((actor) => existing.has(actorKey(actor)));+ if (!held.length) return { removed: [], skipped };+ const membershipIds = held.map((actor) => existing.get(actorKey(actor))!.id);++ // One check for the whole batch: per actor, two admins each pass on the other still standing.await assertWillRetainProjectAdmin({scopeProjectId: projectId,- excludeMembershipIds: [membership.id],+ excludeMembershipIds: membershipIds,productLabel: "Agent Vault",tx});- await membershipDAL.delete({ scope: RESOURCE_SCOPE, scopeProjectId: projectId, [column]: id }, tx);+ await Promise.all(+ ALL_ACTOR_TYPES.map(async (type) => {+ const typeIds = named(held, type);+ if (!typeIds.length) return;+ await membershipDAL.delete(+ {+ scope: RESOURCE_SCOPE,+ scopeProjectId: projectId,+ scopeResourceType: ResourceType.AgentVaultAccessBundle,+ $in: { [ACTOR_COLUMN[type]]: typeIds }+ },+ tx+ );+ })+ );- await membershipRoleDAL.delete({ membershipId: membership.id }, tx);- await membershipDAL.deleteById(membership.id, tx);+ // membership_roles cascades on the membership FK, so the roles go with these rows.+ await membershipDAL.delete({ $in: { id: membershipIds } }, tx);- return membership.id;+ return {+ removed: held.map((actor) => {+ const membership = existing.get(actorKey(actor))!;+ return {+ id: membership.id,+ role: "",+ createdAt: membership.createdAt,+ actor: { type: actor.type, id: actor.id },+ actorName: nameByKey.get(actorKey(actor))+ };+ }),+ skipped+ };});- usageMeteringService.emitForProject(projectId, AgentVaultIdentities.key);- return { membershipId, ...dto, ...(await resolveActorLabel(dto)) };+ if (written.removed.length) usageMeteringService.emitForProject(projectId, AgentVaultIdentities.key);+ return { members: written.removed, skipped: written.skipped };};-return {- addProductUserMembers,- listProductUserMembers,- listProductGroupMembers,- listProductIdentityMembers,- addProductMember,+ listProductMembers,+ addProductMembers,updateProductMemberRole,- removeProductMember+ revokeProductMembers};};diff --git a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-dal.ts b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-dal.tsindex 740df9786c..b8af7df385 100644--- a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-dal.ts+++ b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-dal.ts@@ -3,6 +3,7 @@ import { Knex } from "knex";import { TDbClient } from "@app/db";import { TableName, TAgentVaultProxies } from "@app/db/schemas";import { DatabaseError } from "@app/lib/errors";+import { sanitizeSqlLikeString } from "@app/lib/fn/string";import { ormify } from "@app/lib/knex";export type TAgentVaultProxyDALFactory = ReturnType<typeof agentVaultProxyDALFactory>;@@ -38,11 +39,44 @@ export const agentVaultProxyDALFactory = (db: TDbClient) => {}};- const findForProject = async (projectId: string, tx?: Knex): Promise<TAgentVaultProxies[]> => {+ const findForList = async (+ {+ projectId,+ search,+ orderBy,+ orderDirection,+ limit,+ offset+ }: {+ projectId: string;+ search?: string;+ orderBy: "name" | "createdAt";+ orderDirection: "asc" | "desc";+ limit: number;+ offset: number;+ },+ tx?: Knex+ ): Promise<{ proxies: TAgentVaultProxies[]; totalCount: number }> => {try {- return (await (tx || db.replicaNode())(TableName.AgentVaultProxy)- .where({ projectId })- .orderBy("name", "asc")) as TAgentVaultProxies[];+ const conn = tx || db.replicaNode();++ const applyFilters = (query: Knex.QueryBuilder) => {+ void query.where({ projectId });+ if (search) void query.whereILike("name", `%${sanitizeSqlLikeString(search)}%`);+ return query;+ };++ const countResult = (await applyFilters(conn(TableName.AgentVaultProxy)).count("id as count").first()) as+ | { count: string }+ | undefined;++ const proxies = (await applyFilters(conn(TableName.AgentVaultProxy))+ .orderBy(orderBy, orderDirection)+ .orderBy("name", "asc")+ .limit(limit)+ .offset(offset)) as TAgentVaultProxies[];++ return { proxies, totalCount: parseInt(countResult?.count || "0", 10) };} catch (error) {throw new DatabaseError({ error, name: "Find agent vault proxies" });}@@ -64,5 +98,5 @@ export const agentVaultProxyDALFactory = (db: TDbClient) => {}};- return { ...orm, findByIdWithOrg, findByIdInProject, findForProject, recordHeartbeat };+ return { ...orm, findByIdWithOrg, findByIdInProject, findForList, recordHeartbeat };};diff --git a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.ts b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.tsindex 17146f53da..d7e0c33369 100644--- a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.ts+++ b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.ts@@ -24,6 +24,8 @@ import { TOrgDALFactory } from "@app/services/org/org-dal";import { isUniqueViolation } from "../agent-vault/agent-vault-db-error-fns";import { AgentVaultCredentialType, AgentVaultTrafficPolicy } from "../agent-vault/agent-vault-enums";import { findReachableAccessBundleIds, liveGroupIdsFrom } from "../agent-vault/agent-vault-permission";+import { TAgentVaultServiceCustomHeaderDALFactory } from "../agent-vault-access-bundle/agent-vault-service-custom-header-dal";+import { TAgentVaultServiceSubstitutionDALFactory } from "../agent-vault-access-bundle/agent-vault-service-substitution-dal";import { TAgentVaultSessionDALFactory } from "../agent-vault-session/agent-vault-session-dal";import { hashSessionToken } from "../agent-vault-session/agent-vault-session-fns";import { RESOURCE_TYPE_AGENT_VAULT_PROXY } from "../resource-auth-method/resource-auth-method-fns";@@ -32,6 +34,7 @@ import { parseRootCaCertificate } from "./agent-vault-ca-fns";import { TAgentVaultProxyDALFactory } from "./agent-vault-proxy-dal";import {TAgentVaultProxyConfig,+ TAgentVaultProxyScoped,TCreateProxyDTO,TEnrollProxyDTO,THeartbeatDTO,@@ -49,6 +52,8 @@ const HEARTBEAT_MISSES_BEFORE_UNHEALTHY = 3;type TAgentVaultProxyServiceFactoryDep = {agentVaultProxyDAL: TAgentVaultProxyDALFactory;agentVaultResolveDAL: TAgentVaultResolveDALFactory;+ agentVaultServiceCustomHeaderDAL: Pick<TAgentVaultServiceCustomHeaderDALFactory, "findByServiceIds">;+ agentVaultServiceSubstitutionDAL: Pick<TAgentVaultServiceSubstitutionDALFactory, "findByServiceIds">;agentVaultSessionDAL: Pick<TAgentVaultSessionDALFactory, "findByTokenHash">;membershipDAL: Pick<TMembershipDALFactory, "findResourceMembershipsForActor">;orgDAL: Pick<TOrgDALFactory, "findEffectiveOrgMembership">;@@ -65,6 +70,8 @@ export type TAgentVaultProxyServiceFactory = ReturnType<typeof agentVaultProxySeexport const agentVaultProxyServiceFactory = ({agentVaultProxyDAL,agentVaultResolveDAL,+ agentVaultServiceCustomHeaderDAL,+ agentVaultServiceSubstitutionDAL,agentVaultSessionDAL,membershipDAL,orgDAL,@@ -102,7 +109,10 @@ export const agentVaultProxyServiceFactory = ({createdAt: proxy.createdAt});- const $authorize = async ({ projectId, ctx }: TListProxiesDTO, action: ProjectPermissionAgentVaultProxyActions) => {+ const $authorize = async (+ { projectId, ctx }: TAgentVaultProxyScoped,+ action: ProjectPermissionAgentVaultProxyActions+ ) => {const { permission, hasRole } = await permissionService.getProjectPermission({actor: ctx.actor,actorId: ctx.actorId,@@ -123,10 +133,17 @@ export const agentVaultProxyServiceFactory = ({const getProxyForAuth = (proxyId: string) => agentVaultProxyDAL.findByIdWithOrg(proxyId);- const listProxies = async (dto: TListProxiesDTO) => {+ const listProxies = async ({ search, orderBy, orderDirection, limit, offset, ...dto }: TListProxiesDTO) => {const { isAdmin } = await $authorize(dto, ProjectPermissionAgentVaultProxyActions.Read);- const proxies = await agentVaultProxyDAL.findForProject(dto.projectId);- return proxies.map((proxy) => (isAdmin ? toAdminView(proxy) : toMemberView(proxy)));+ const { proxies, totalCount } = await agentVaultProxyDAL.findForList({+ projectId: dto.projectId,+ search,+ orderBy,+ orderDirection,+ limit,+ offset+ });+ return { proxies: proxies.map((proxy) => (isAdmin ? toAdminView(proxy) : toMemberView(proxy))), totalCount };};const $resourceActor = (ctx: TCreateProxyDTO["ctx"]) => ({@@ -377,9 +394,16 @@ export const agentVaultProxyServiceFactory = ({accessBundleIds});+ const serviceIds = rows.map((row) => row.id);+ const [customHeaderRows, substitutionRows] = await Promise.all([+ agentVaultServiceCustomHeaderDAL.findByServiceIds(serviceIds),+ agentVaultServiceSubstitutionDAL.findByServiceIds(serviceIds)+ ]);+// A bundle of pass-through services has nothing sealed, so deriving the project data key would be- // a kms_keys read (or an external KMS round trip) per resolve for nothing.- const decryptor = rows.some((row) => row.encryptedCredential)+ const hasSealedValue =+ rows.some((row) => row.encryptedCredential) || customHeaderRows.length > 0 || substitutionRows.length > 0;+ const decryptor = hasSealedValue? (await kmsService.createCipherPairWithDataKey({type: KmsDataKey.SecretManager,@@ -388,12 +412,29 @@ export const agentVaultProxyServiceFactory = ({).decryptor: null;+ const $decryptValue = (encryptedValue: Buffer) => {+ if (!decryptor) throw new InternalServerError({ message: "Failed to resolve the session's credentials" });+ return (JSON.parse(decryptor({ cipherTextBlob: encryptedValue }).toString("utf-8")) as { value: string }).value;+ };+const services: TResolvedService[] = rows.map((row) => ({id: row.id,name: row.name,accessBundleName: row.accessBundleName,hostPattern: row.hostPattern,- credential: $decryptCredential(row, decryptor)+ allowedMethods: row.allowedMethods,+ allowedPathPrefixes: row.allowedPathPrefixes,+ credential: $decryptCredential(row, decryptor),+ customHeaders: customHeaderRows+ .filter((header) => header.serviceId === row.id)+ .map((header) => ({ name: header.name, prefix: header.prefix, value: $decryptValue(header.encryptedValue) })),+ substitutions: substitutionRows+ .filter((substitution) => substitution.serviceId === row.id)+ .map((substitution) => ({+ placeholder: substitution.placeholder,+ surfaces: substitution.surfaces,+ value: $decryptValue(substitution.encryptedValue)+ }))}));logger.info(diff --git a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-types.ts b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-types.tsindex d7f3f07d58..c2579600b4 100644--- a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-types.ts+++ b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-types.ts@@ -9,7 +9,13 @@ export type TAgentVaultProxyConfig = {pollInterval: number;};-export type TListProxiesDTO = TAgentVaultProxyScoped;+export type TListProxiesDTO = TAgentVaultProxyScoped & {+ search?: string;+ orderBy: "name" | "createdAt";+ orderDirection: "asc" | "desc";+ limit: number;+ offset: number;+};export type TCreateProxyDTO = TAgentVaultProxyScoped & {name: string;@@ -48,8 +54,12 @@ export type TResolvedService = {name: string;accessBundleName: string;hostPattern: string;+ allowedMethods: string[] | null;+ allowedPathPrefixes: string[] | null;credential:| { type: "bearer"; headerName: string; headerPrefix: string; value: string }| { type: "basic"; username: string; password: string }| { type: "passthrough" };+ customHeaders: { name: string; prefix: string; value: string }[];+ substitutions: { placeholder: string; surfaces: string[]; value: string }[];};diff --git a/backend/src/ee/services/agent-vault-proxy/agent-vault-resolve-dal.ts b/backend/src/ee/services/agent-vault-proxy/agent-vault-resolve-dal.tsindex b73fa28d02..9728fc4129 100644--- a/backend/src/ee/services/agent-vault-proxy/agent-vault-resolve-dal.ts+++ b/backend/src/ee/services/agent-vault-proxy/agent-vault-resolve-dal.ts@@ -14,6 +14,8 @@ export type TResolveServiceRow = {credentialType: string;credentialConfig: unknown;encryptedCredential: Buffer | null;+ allowedMethods: string[] | null;+ allowedPathPrefixes: string[] | null;position: number;};@@ -65,6 +67,8 @@ export const agentVaultResolveDALFactory = (db: TDbClient) => {db.ref("credentialType").withSchema(TableName.AgentVaultService),db.ref("credentialConfig").withSchema(TableName.AgentVaultService),db.ref("encryptedCredential").withSchema(TableName.AgentVaultService),+ db.ref("allowedMethods").withSchema(TableName.AgentVaultService),+ db.ref("allowedPathPrefixes").withSchema(TableName.AgentVaultService),// Resolve only reaches live bundles, so the current name is always the truthful one here.db.ref("name").withSchema(TableName.AgentVaultAccessBundle).as("accessBundleName"),db.ref("position").withSchema(TableName.AgentVaultSessionAccessBundle)diff --git a/backend/src/ee/services/agent-vault/CLAUDE.md b/backend/src/ee/services/agent-vault/CLAUDE.mdindex 9a6d27ab7f..64edb74115 100644--- a/backend/src/ee/services/agent-vault/CLAUDE.md+++ b/backend/src/ee/services/agent-vault/CLAUDE.md@@ -77,7 +77,9 @@ and `packages/agentvault/` in the CLI repo. Frontend: `frontend/src/pages/agent-`--access-bundle` and the single-select Create Session sheet. The mint body stays a list, the junction tablekeeps `position`, resolve orders by position then name, and the Go matcher breaks ties by slice order, solifting the cap is those three places plus the copy that says one (the api-docs string, the service's cap- message, the sheet and sessions page, the CLI help and the docs), not a migration.+ message, the sheet and sessions page, the CLI help and the docs), not a migration. It also needs a+ decision `bestMatch` does not make: it picks by host specificity alone, so a restricted winner would 403+ a request the other bundle's unrestricted service would have served.- The bundle on a session is a ceiling fixed at mint and intersected with live reachability on every resolve.It can shrink and grow back, never past what was minted.- Grants are read fresh on every resolve. The actor's role comes through the platform's permission cache@@ -110,20 +112,50 @@ and `packages/agentvault/` in the CLI repo. Frontend: `frontend/src/pages/agent-token is burned too.- Resolve is not audited: once per poll per session would swamp the audit table.-## Host grammar+## Host and path grammar`agent-vault-host-pattern.ts` is the grammar of record. The CLI matcher (`packages/agentvault/match.go`) doesthe matching at runtime and reimplements the same rules, so a change here needs the same change there.-- Paths are rejected: the matcher would compare the decoded path while the upstream gets the escaped one.-- A portless pattern means 443. An explicit port is allowed, `:80` included, so the proxy must also refuse- to inject over plaintext, and it does.+- Paths are rejected *in a host pattern*; `allowedPathPrefixes` is a separate filter that never decodes.+ A filter is judged by what it *allows*, so the refusals are the load-bearing half. The grammar is an+ allowlist because a prefix is compared against the escaped path: one carrying anything Go's encoder+ rewrites could never match. `agent-vault-path-prefix.ts` is the grammar of record, `policy.go` the match.+- Methods and path prefixes are filters on a service that already matched, **not** part of the match key,+ so the same-bundle host conflict rule stays host-only. Two services on one host differing only by method+ is still a hard reject.+- A violation is a 403 from the proxy, not a withheld credential. `NULL` is the only "unrestricted"; an+ empty array is never stored.+- There is no version negotiation with the proxy. A binary predating this drops the new resolve fields and+ enforces nothing while the UI shows the rules. Settled: accepted while the product is in preview.+- A portless pattern means 443, and that is the whole of what keeps a credential off a plaintext wire:+ injection in the proxy is scheme-blind, so naming a port (`:80` included) is how an admin opts a service+ into brokering over http.- A wildcard is the leftmost label only and matches exactly one label. This is what makes every pattern pairidentical, contained or disjoint, which is what makes conflict detection exact. Do not loosen it.- Conflict detection is an intersection over individual patterns, because `hostPattern` is a comma-separatedset. Same bundle: hard reject. Across bundles: allowed, since a session carries one bundle they never meet.- Patterns are stored as typed and normalised at match time. `*.com` is accepted; settled as not a bug.+## Transformations++Two child tables, `agent_vault_service_custom_headers` and `agent_vault_service_substitutions`. "Custom+header" is the name in every layer; unqualified "header" means the credential's own.++- **There is no unique index on name or placeholder, and there must not be.** A rename that swaps two rows+ emits the two UPDATEs in sequence, so `UNIQUE (serviceId, lower(name))` fails the first against the+ second row's current value. Uniqueness is the list-level refine plus the bundle lock. Adding an index+ needs deferred constraints or delete-then-insert.+- The proxy writes substitutions, then custom headers, then **the credential last**, so nothing can+ overwrite the credential. A path substitution rewrites the path after the policy check, so a restricted+ service re-checks it.+- Stored rows **and the credential** are read inside the transaction, after the bundle lock. Outside it two+ concurrent PATCHes both pass the ownership check and the loser's writes no-op.+- A refusal after substitution must never quote the path: by then it carries the real credential, and the+ error text is both the 403 body and the log line.+- A PATCH replaces the whole list. Omitting a row's `value` keeps what is sealed; every other field+ replaces.+## Credentials at rest- The KMS cipher pair is project-scoped (`KmsDataKey.SecretManager`) and built once per resolve.diff --git a/backend/src/ee/services/agent-vault/agent-vault-credential-schemas.ts b/backend/src/ee/services/agent-vault/agent-vault-credential-schemas.tsindex f3aaaa91cf..9f0bf11ea2 100644--- a/backend/src/ee/services/agent-vault/agent-vault-credential-schemas.ts+++ b/backend/src/ee/services/agent-vault/agent-vault-credential-schemas.ts@@ -1,3 +1,4 @@+import RE2 from "re2";import { z } from "zod";import { AgentVaultCredentialType } from "./agent-vault-enums";@@ -8,7 +9,7 @@ import { AgentVaultCredentialType } from "./agent-vault-enums";// The characters RFC 7230 allows. Go's HTTP client refuses to send anything else, so a name saved// without this check 502s every request through the service.-export const AGENT_VAULT_HEADER_NAME_RE = /^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/;+export const AGENT_VAULT_HEADER_NAME_RE = new RE2(/^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/);export const AGENT_VAULT_HEADER_NAME_MESSAGE ="A header name can't contain spaces or colons. Use letters, digits and dashes, as in X-API-Key.";@@ -16,7 +17,7 @@ export const AGENT_VAULT_HEADER_NAME_MESSAGE =// A NUL is rejected by the jsonb write and 500s; a CR or LF saves fine and then makes Go refuse to send// the header, so the credential silently never goes out. Both usually arrive by pasting.// eslint-disable-next-line no-control-regex-export const AGENT_VAULT_NO_CONTROL_CHARS_RE = /^[^\x00-\x1f\x7f]*$/;+export const AGENT_VAULT_NO_CONTROL_CHARS_RE = new RE2(/^[^\x00-\x1f\x7f]*$/);export const AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE ="This can't contain line breaks or other control characters. Check for a stray newline if you pasted it.";diff --git a/backend/src/ee/services/agent-vault/agent-vault-enums.ts b/backend/src/ee/services/agent-vault/agent-vault-enums.tsindex b17f1a58c7..f227a5c8aa 100644--- a/backend/src/ee/services/agent-vault/agent-vault-enums.ts+++ b/backend/src/ee/services/agent-vault/agent-vault-enums.ts@@ -4,10 +4,33 @@ export enum AgentVaultCredentialType {Passthrough = "passthrough"}+export enum AgentVaultMemberType {+ User = "user",+ MachineIdentity = "machineIdentity",+ Group = "group"+}+export enum AgentVaultResourceRole {Consumer = "consumer"}+export enum AgentVaultHttpMethod {+ Get = "GET",+ Head = "HEAD",+ Post = "POST",+ Put = "PUT",+ Patch = "PATCH",+ Delete = "DELETE",+ Options = "OPTIONS"+}++export enum AgentVaultSubstitutionSurface {+ Path = "path",+ Query = "query",+ Header = "header",+ Body = "body"+}+export enum AgentVaultTrafficPolicy {AnyHost = "any-host",BundleHosts = "bundle-hosts"diff --git a/backend/src/ee/services/agent-vault/agent-vault-path-prefix.test.ts b/backend/src/ee/services/agent-vault/agent-vault-path-prefix.test.tsnew file mode 100644index 0000000000..42365e2837--- /dev/null+++ b/backend/src/ee/services/agent-vault/agent-vault-path-prefix.test.ts@@ -0,0 +1,67 @@+import { describe, expect, it } from "vitest";++import { agentVaultPathPrefixListSchema, normalizePathPrefix } from "./agent-vault-path-prefix";++describe("agent vault path prefixes", () => {+ describe("grammar", () => {+ it.each([+ ["/repos"],+ ["/repos/octo"],+ ["/"],+ ["/v1/chat/completions"],+ ["/repos-and-more"],+ ["/a+b"],+ ["/tenants/acme:v2@edge"],+ ["/~user/$data"]+ ])("accepts %s", (prefix) => {+ expect(agentVaultPathPrefixListSchema.safeParse([prefix]).success).toBe(true);+ });++ it.each([+ ["repos", "must start with a /"],+ ["/repos/../admin", ".. segment"],+ ["/repos/./x", ". segment"],+ ["//repos", "empty segment"],+ ["/repos%2fadmin", "% is rejected so the byte comparison stays exact"],+ ["/repos;x", "; is stripped by some servers"],+ ["/repos\\x", "\\ is read as / by some servers"],+ ["/repos?x=1", "? ends the path"],+ ["/repos#x", "# ends the path"],+ ["/repos x", "a space would have to be escaped"],+ ["/a,b", "a comma separates one prefix from the next"],+ ["/caf\u00e9", "a non-ASCII prefix is compared against /caf%C3%A9 and could never match"],+ ["/repos/{owner}", "braces are encoded in the request URL, so this would match nothing"],+ ["/a[b]", "brackets survive or not depending on the rest of the path"],+ ["/products(1)", "parentheses are encoded by the path encoder"]+ ])("rejects %s (%s)", (prefix) => {+ expect(agentVaultPathPrefixListSchema.safeParse([prefix]).success).toBe(false);+ });++ it("rejects an empty list, because NULL is how every path is expressed", () => {+ expect(agentVaultPathPrefixListSchema.safeParse([]).success).toBe(false);+ });++ it("accepts null", () => {+ expect(agentVaultPathPrefixListSchema.safeParse(null).success).toBe(true);+ });++ it("rejects duplicates once normalised", () => {+ expect(agentVaultPathPrefixListSchema.safeParse(["/repos", "/repos/"]).success).toBe(false);+ });++ it("caps the list", () => {+ const many = Array.from({ length: 21 }, (_, i) => `/p${i}`);+ expect(agentVaultPathPrefixListSchema.safeParse(many).success).toBe(false);+ });+ });++ describe("normalisation", () => {+ it("strips a trailing slash so /repos and /repos/ are one prefix", () => {+ expect(normalizePathPrefix("/repos/")).toBe("/repos");+ });++ it("leaves a bare / alone, since stripping it would empty the prefix", () => {+ expect(normalizePathPrefix("/")).toBe("/");+ });+ });+});diff --git a/backend/src/ee/services/agent-vault/agent-vault-path-prefix.ts b/backend/src/ee/services/agent-vault/agent-vault-path-prefix.tsnew file mode 100644index 0000000000..9f6486ba14--- /dev/null+++ b/backend/src/ee/services/agent-vault/agent-vault-path-prefix.ts@@ -0,0 +1,60 @@+import RE2 from "re2";+import { z } from "zod";++export const AGENT_VAULT_MAX_PATH_PREFIX_LENGTH = 512;+export const AGENT_VAULT_MAX_PATH_PREFIXES = 20;++// A prefix is compared against the escaped path, so anything the encoder rewrites could never match:+// `/café` would be judged against `/caf%C3%A9`. Deliberate exclusions on top of that: '%' keeps the+// comparison exact, ';' and '\' are what isAmbiguousPath refuses, '?' and '#' end the path, ',' commits a+// chip in the UI. Anything else left out, '(' say, survives the wire but is useless in a prefix anyway,+// since matching is by whole segment and `/Products` never covers `/Products(1)`.+const PATH_PREFIX_RE = new RE2(/^\/[A-Za-z0-9\-._~$&+/:=@]*$/);++const hasTraversalSegment = (value: string) => value.split("/").some((segment) => segment === "." || segment === "..");++// '/' keeps its trailing slash: stripping it would leave an empty string, which means nothing.+export const normalizePathPrefix = (value: string) => {+ const trimmed = value.trim();+ if (trimmed === "/") return trimmed;+ return trimmed.replace(/\/+$/, "");+};++const pathPrefixError = (raw: string) => {+ const value = raw.trim();+ if (!value) return "A path prefix can't be empty.";+ if (value.length > AGENT_VAULT_MAX_PATH_PREFIX_LENGTH)+ return `"${value.slice(0, 40)}…" is longer than ${AGENT_VAULT_MAX_PATH_PREFIX_LENGTH} characters.`;+ if (!value.startsWith("/")) return `"${value}" must start with a /.`;+ if (value.includes("//")) return `"${value}" can't contain an empty path segment.`;+ if (hasTraversalSegment(value)) return `"${value}" can't contain a . or .. segment.`;+ if (!PATH_PREFIX_RE.test(value)) return `"${value}" can only contain letters, digits and - . _ ~ $ & + : = @.`;+ return null;+};++// No `.max()`: pathPrefixError measures the length itself, and Zod's check would fire alongside it.+export const pathPrefixSchema = z+ .string()+ .trim()+ .superRefine((raw, ctx) => {+ const message = pathPrefixError(raw);+ if (message) ctx.addIssue({ code: z.ZodIssueCode.custom, message });+ })+ .transform(normalizePathPrefix);++// NULL is the only "every path", so the proxy never has two representations to treat alike. `.nullable()`+// without `.optional()`, so a PATCH omitting the field leaves the column alone and an explicit null clears it.+export const agentVaultPathPrefixListSchema = z+ .array(pathPrefixSchema)+ .min(1, "Add at least one path prefix, or leave this unset to allow every path.")+ .max(AGENT_VAULT_MAX_PATH_PREFIXES)+ .superRefine((prefixes, ctx) => {+ const seen = new Set<string>();+ prefixes.forEach((prefix, index) => {+ if (seen.has(prefix)) {+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: `"${prefix}" is listed twice.`, path: [index] });+ }+ seen.add(prefix);+ });+ })+ .nullable();diff --git a/backend/src/ee/services/agent-vault/agent-vault-transformation-schemas.ts b/backend/src/ee/services/agent-vault/agent-vault-transformation-schemas.tsnew file mode 100644index 0000000000..495154b463--- /dev/null+++ b/backend/src/ee/services/agent-vault/agent-vault-transformation-schemas.ts@@ -0,0 +1,129 @@+import { z } from "zod";++import { AGENT_VAULT } from "@app/lib/api-docs";++import {+ AGENT_VAULT_HEADER_NAME_MESSAGE,+ AGENT_VAULT_HEADER_NAME_RE,+ AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE,+ AGENT_VAULT_NO_CONTROL_CHARS_RE+} from "./agent-vault-credential-schemas";+import { AgentVaultSubstitutionSurface } from "./agent-vault-enums";++export const AGENT_VAULT_MAX_CUSTOM_HEADERS = 20;+export const AGENT_VAULT_MAX_SUBSTITUTIONS = 20;++// Set by the proxy or stripped as hop-by-hop, so naming one is silently dropped or corrupts the request.+const RESERVED_HEADER_NAMES = new Set([+ "host",+ "content-length",+ "transfer-encoding",+ "connection",+ "proxy-connection",+ "upgrade",+ "te",+ "trailer",+ "keep-alive",+ "proxy-authenticate",+ "proxy-authorization"+]);++export const AGENT_VAULT_RESERVED_HEADER_MESSAGE = "This header is set by the proxy and can't be overridden.";++// Shared with the bearer credential's own header name: both end up on the request the same way, so both+// have the same reserved names.+export const agentVaultHeaderNameSchema = z+ .string()+ .trim()+ .min(1)+ .max(128)+ .regex(AGENT_VAULT_HEADER_NAME_RE, AGENT_VAULT_HEADER_NAME_MESSAGE)+ .refine((name) => !RESERVED_HEADER_NAMES.has(name.toLowerCase()), AGENT_VAULT_RESERVED_HEADER_MESSAGE);++const headerPrefixSchema = z+ .string()+ .trim()+ .max(64)+ .regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE);++const secretValueSchema = z+ .string()+ .min(1)+ .max(8192)+ .regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE);++// No minimum length: a short placeholder over-matches, but that is the author's own doing.+const placeholderSchema = z+ .string()+ .trim()+ .min(1)+ .max(255)+ .regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE);++const surfacesSchema = z+ .array(z.nativeEnum(AgentVaultSubstitutionSurface))+ .min(1, "Pick at least one place to look for the placeholder.")+ .max(Object.keys(AgentVaultSubstitutionSurface).length)+ .transform((surfaces) => [...new Set(surfaces)]);++// Rows resolve by `id` and otherwise by name or placeholder, so a hand-written call can edit one without+// fetching the service first. `value` is optional on update because omitting it keeps what is sealed.+export const AgentVaultCustomHeaderInputSchema = z.object({+ name: agentVaultHeaderNameSchema.describe(AGENT_VAULT.SERVICE.customHeaderName),+ prefix: headerPrefixSchema.optional().describe(AGENT_VAULT.SERVICE.customHeaderPrefix),+ value: secretValueSchema.describe(AGENT_VAULT.SERVICE.customHeaderValue)+});++export const AgentVaultCustomHeaderUpdateSchema = z.object({+ id: z.string().uuid().optional().describe(AGENT_VAULT.SERVICE.customHeaderId),+ name: agentVaultHeaderNameSchema.describe(AGENT_VAULT.SERVICE.customHeaderName),+ prefix: headerPrefixSchema.optional().describe(AGENT_VAULT.SERVICE.updateCustomHeaderPrefix),+ value: secretValueSchema.optional().describe(AGENT_VAULT.SERVICE.updateCustomHeaderValue)+});++export const AgentVaultSubstitutionInputSchema = z.object({+ placeholder: placeholderSchema.describe(AGENT_VAULT.SERVICE.placeholder),+ surfaces: surfacesSchema.describe(AGENT_VAULT.SERVICE.surfaces),+ value: secretValueSchema.describe(AGENT_VAULT.SERVICE.substitutionValue)+});++export const AgentVaultSubstitutionUpdateSchema = z.object({+ id: z.string().uuid().optional().describe(AGENT_VAULT.SERVICE.substitutionId),+ placeholder: placeholderSchema.describe(AGENT_VAULT.SERVICE.placeholder),+ surfaces: surfacesSchema.describe(AGENT_VAULT.SERVICE.surfaces),+ value: secretValueSchema.optional().describe(AGENT_VAULT.SERVICE.updateSubstitutionValue)+});++type TNamed = { name: string };+type TPlaceheld = { placeholder: string };++// Header names collide case-insensitively, placeholders exactly, matching how each is used. A duplicate+// would make "which stored row did the caller mean" unanswerable.+export const addDuplicateCustomHeaderNameIssues = (headers: TNamed[], ctx: z.RefinementCtx) => {+ const seen = new Set<string>();+ headers.forEach((header, index) => {+ const key = header.name.toLowerCase();+ if (seen.has(key)) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: `The custom header "${header.name}" is listed twice.`,+ path: [index, "name"]+ });+ }+ seen.add(key);+ });+};++export const addDuplicatePlaceholderIssues = (substitutions: TPlaceheld[], ctx: z.RefinementCtx) => {+ const seen = new Set<string>();+ substitutions.forEach((substitution, index) => {+ if (seen.has(substitution.placeholder)) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: `The placeholder "${substitution.placeholder}" is listed twice.`,+ path: [index, "placeholder"]+ });+ }+ seen.add(substitution.placeholder);+ });+};diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex 190a0d4d43..4255a9f7f8 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -6324,6 +6324,11 @@ interface AgentVaultServiceCreateEvent {credentialType: string;headerName?: string;headerPrefix?: string;+ allowedMethods?: string[] | null;+ allowedPathPrefixes?: string[] | null;+ // Names and placeholders only. A sealed value must never reach an audit row.+ customHeaderNames?: string[];+ substitutionPlaceholders?: string[];};}@@ -6337,6 +6342,12 @@ interface AgentVaultServiceUpdateEvent {credentialType?: string;headerName?: string;headerPrefix?: string;+ allowedMethods?: string[] | null;+ allowedPathPrefixes?: string[] | null;+ customHeaderNames?: string[];+ customHeadersReplaced?: string[];+ substitutionPlaceholders?: string[];+ substitutionsReplaced?: string[];credentialReplaced: boolean;};}@@ -6357,8 +6368,8 @@ interface AgentVaultProductMemberAddEvent {userName?: string;groupId?: string;groupName?: string;- identityId?: string;- identityName?: string;+ machineIdentityId?: string;+ machineIdentityName?: string;role: string;};}@@ -6370,8 +6381,8 @@ interface AgentVaultProductMemberUpdateEvent {userName?: string;groupId?: string;groupName?: string;- identityId?: string;- identityName?: string;+ machineIdentityId?: string;+ machineIdentityName?: string;role: string;};}@@ -6383,8 +6394,8 @@ interface AgentVaultProductMemberRemoveEvent {userName?: string;groupId?: string;groupName?: string;- identityId?: string;- identityName?: string;+ machineIdentityId?: string;+ machineIdentityName?: string;};}@@ -6395,7 +6406,7 @@ interface AgentVaultAccessBundleMemberAddEvent {accessBundleName: string;memberId: string;userId?: string;- identityId?: string;+ machineIdentityId?: string;groupId?: string;};}@@ -6406,6 +6417,9 @@ interface AgentVaultAccessBundleMemberRemoveEvent {accessBundleId: string;accessBundleName: string;memberId: string;+ userId?: string;+ machineIdentityId?: string;+ groupId?: string;};}diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex 7724626682..5bb96903ae 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -105,7 +105,7 @@ export enum ApiDocsTags {AgentVaultAccessBundles = "Agent Vault Access Bundles",AgentVaultSessions = "Agent Vault Sessions",AgentVaultProxies = "Agent Vault Proxies",- AgentVaultMemberships = "Agent Vault Memberships",+ AgentVaultMembers = "Agent Vault Members",KmipServers = "KMIP Servers"}@@ -4225,15 +4225,19 @@ export const AGENT_VAULT = {description: "A description of what this access bundle is for.",serviceCount: "How many services the access bundle holds.",memberCount: "How many users, machine identities and groups can reach the access bundle.",+ orderBy: "What to sort access bundles by: name, serviceCount or createdAt.",+ orderDirection: "Which way to sort: asc or desc.",+ search: "Match access bundles by name or description.",+ limit: "The maximum number of access bundles to return.",+ offset: "How many access bundles to skip.",hostPatterns: "Every host pattern the access bundle's services cover."},SERVICE: {serviceId: "The ID of the service.",name: "The name of the service.",hostPattern:- "A comma-separated set of hosts this service covers, each optionally with a port (defaults to 443). A leading '*.' wildcard matches exactly one label. Paths are not supported.",- credentialType: "How the credential is attached to the request: bearer, basic or passthrough.",- headerName: "The header the credential is written to. Defaults to Authorization.",+ "A comma-separated set of hosts this service covers, each optionally with a port (defaults to `443`). A leading `*.` wildcard matches exactly one label. Paths are not supported.",+ headerName: "The header the credential is written to. Defaults to `Authorization`.",headerPrefix:"Written before the credential value, separated by one space. Leave empty for a header that carries the value alone, such as DD-API-KEY. On update a field left out keeps its stored value, so send an empty string to clear the prefix when changing the header.",username:@@ -4244,27 +4248,87 @@ export const AGENT_VAULT = {updatePassword:"The password half of the basic credential. Omit to keep the stored password; send an empty string to remove it, which requires a username.",createdAt: "When the service was added to the access bundle.",+ updatedAt: "When the service was last changed.",value: "The secret. Never returned once saved.",password:- "The password half of the basic credential. May be empty if a username is set, for APIs that carry the whole key in the username. Never returned once saved."+ "The password half of the basic credential. May be empty if a username is set, for APIs that carry the whole key in the username. Never returned once saved.",+ allowedMethods:+ "The HTTP methods this service allows. Null allows every method. Anything else is refused by the proxy with a 403.",+ allowedPathPrefixes:+ "The path prefixes this service allows, matched on whole segments, so `/repos` covers `/repos/octo` but not `/repositories`. `null` allows every path. A path-restricted service also refuses any request whose path would have to be normalised to judge.",+ customHeaders:+ "Additional headers the proxy attaches to every request to this service, on top of the credential. Send the full list. A header you leave out is deleted. Send a header's `id` to change it in place and keep its stored value. Without an `id`, a header is matched by name.",+ customHeaderId: "The ID of the custom header. Send it to change that header in place. Omit it to match by name.",+ customHeaderName: "The name of the header, which must not be the credential's own header.",+ customHeaderPrefix: "Written before the header value, separated by one space. Leave empty to send the value alone.",+ updateCustomHeaderPrefix:+ "Written before the header value, separated by one space. Unlike the value, an omitted prefix is cleared rather than kept, since the stored prefix is returned and can be resent.",+ customHeaderValue: "The header value. Never returned once saved.",+ updateCustomHeaderValue: "The header value. Omit to keep the value already stored for this header.",+ substitutions:+ "Placeholders the proxy swaps for a real secret before forwarding. Send the full list. A substitution you leave out is deleted. Send a substitution's `id` to change it in place and keep its stored value. Without an `id`, it is matched by its placeholder.",+ substitutionId:+ "The ID of the substitution. Send it to change that substitution in place. Omit it to match by placeholder.",+ placeholder:+ "The fake value your agent already sends. The proxy replaces it with the real secret. Matched as a plain string, so a distinctive placeholder is worth choosing.",+ surfaces: "Where in the request to look for the placeholder: path, query, header or body.",+ substitutionValue: "The real value the placeholder is replaced with. Never returned once saved.",+ updateSubstitutionValue: "The real value the placeholder is replaced with. Omit to keep the value already stored."},MEMBER: {memberId: "The ID of the access bundle membership.",- userId: "The ID of the user to grant the access bundle to.",- identityId: "The ID of the machine identity to grant the access bundle to.",- groupId: "The ID of the group to grant the access bundle to.",+ createdAt: "When the access bundle was granted.",+ userId: "The ID of the user whose Agent Vault membership this is.",+ identityId: "The ID of the machine identity whose Agent Vault membership this is.",+ groupId: "The ID of the group whose Agent Vault membership this is.",userIds: "The IDs of the users to grant the access bundle to.",- identityIds: "The IDs of the machine identities to grant the access bundle to.",+ machineIdentityIds: "The IDs of the machine identities to grant the access bundle to.",groupIds: "The IDs of the groups to grant the access bundle to.",- skipped: "The IDs of the requested grantees who already had the access bundle and were left as they were."+ actorType: "Whether this member is a user, a machine identity or a group.",+ actorId: "The ID of the user, machine identity or group.",+ username: "The username of the user.",+ email: "The email address of the user.",+ firstName: "The first name of the user.",+ lastName: "The last name of the user.",+ identityName: "The name of the machine identity.",+ groupName: "The name of the group.",+ isOrgMembershipPending: "Whether the user still has an unaccepted invitation to the organization.",+ isManagedByAgentVault:+ "Whether Agent Vault created the machine identity. One it owns is deleted rather than removed.",+ machineIdentityOrgId: "The ID of the organization the machine identity belongs to.",+ revokeUserIds: "The IDs of the users to revoke the access bundle from.",+ revokeMachineIdentityIds: "The IDs of the machine identities to revoke the access bundle from.",+ revokeGroupIds: "The IDs of the groups to revoke the access bundle from.",+ skipped: "The requested grantees who already had the access bundle and were left as they were.",+ revokeSkipped: "The requested grantees who did not have the access bundle, so nothing was revoked.",+ search: "Match members by name, username or email address.",+ limit: "The maximum number of members to return.",+ offset: "How many members to skip."},MEMBERSHIP: {- role: "The Agent Vault role: admin or member."+ role: "The Agent Vault role: admin or member.",+ isActive: "Whether the member can currently reach Agent Vault.",+ userIds: "The IDs of the users to act on.",+ machineIdentityIds: "The IDs of the machine identities to act on.",+ groupIds: "The IDs of the groups to act on.",+ emails: "The email addresses of the users to give access to. Each must already be in the organization.",+ identifier: "The ID or email address the request named, echoed back so a reply can be matched to it.",+ addSkipped: "The requested members who already had access to Agent Vault and were left as they were.",+ revokeSkipped: "The requested members who did not have access to Agent Vault, so nothing was removed.",+ actorTypeFilter: "List only users, only groups or only machine identities.",+ search: "Match members by name, username or email address.",+ limit: "The maximum number of members to return.",+ offset: "How many members to skip."},PROXY: {proxyId: "The ID of the proxy.",name: "The name of the proxy.",- heartbeat: "When the proxy last checked in, or null if it never has.",+ orderBy: "What to sort proxies by: name or createdAt.",+ orderDirection: "Which way to sort: asc or desc.",+ search: "Match proxies by name.",+ limit: "The maximum number of proxies to return.",+ offset: "How many proxies to skip.",+ heartbeat: "When the proxy last checked in, or `null` if it never has.",isHealthy: "Whether the proxy has checked in recently enough to be considered up.",enrollmentToken: "A one-time token the proxy enrolls with. Shown once, and valid for one hour.",rootCaCertificate:@@ -4273,11 +4337,12 @@ export const AGENT_VAULT = {"The SHA-256 fingerprint of the proxy's certificate authority. Pin this if you want to verify the proxy an agent connects to.",rootCaExpiresAt: "When the proxy's certificate authority expires.",trafficPolicy:- "Which hosts an agent may reach through this proxy. 'any-host' lets every request out; 'bundle-hosts' allows only hosts an access bundle covers, plus anything in allowedHosts, and refuses the rest with a 403.",+ "Which hosts an agent may reach through this proxy. `any-host` lets every request out; `bundle-hosts` allows only hosts an access bundle covers, plus anything in `allowedHosts`, and refuses the rest with a 403.",allowedHosts:- "Hosts that stay reachable under the 'bundle-hosts' traffic policy even though no access bundle covers them. Still intercepted, and given no credential.",+ "Hosts that stay reachable under the `bundle-hosts` traffic policy even though no access bundle covers them. Still intercepted, and given no credential.",pollInterval: "How often, in seconds, the proxy refreshes its sessions and settings. Between 10 and 300.",- sessionToken: "The session an agent is running with. A selector, not a second credential."+ sessionToken: "The session an agent is running with. A selector, not a second credential.",+ createdAt: "When the proxy was registered."},SESSION: {sessionId: "The ID of the session.",diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 17cddfaf32..662b5b1b7e 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -27,7 +27,10 @@ import { agentProxyCaServiceFactory } from "@app/ee/services/agent-proxy-ca/agenimport { orgAgentProxyConfigDALFactory } from "@app/ee/services/agent-proxy-ca/org-agent-proxy-config-dal";import { agentVaultAccessBundleDALFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-dal";import { agentVaultAccessBundleServiceFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service";+import { agentVaultServiceCustomHeaderDALFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-service-custom-header-dal";import { agentVaultServiceDALFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-service-dal";+import { agentVaultServiceSubstitutionDALFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-service-substitution-dal";+import { agentVaultMemberDALFactory } from "@app/ee/services/agent-vault-member/agent-vault-member-dal";import { agentVaultMembershipServiceFactory } from "@app/ee/services/agent-vault-member/agent-vault-membership-service";import { agentVaultProjectResolverFactory } from "@app/ee/services/agent-vault-project/agent-vault-project-resolver";import { agentVaultProxyDALFactory } from "@app/ee/services/agent-vault-proxy/agent-vault-proxy-dal";@@ -1809,8 +1812,11 @@ export const registerRoutes = async (projectDAL});+ const agentVaultMemberDAL = agentVaultMemberDALFactory(db);const agentVaultAccessBundleDAL = agentVaultAccessBundleDALFactory(db);const agentVaultServiceDAL = agentVaultServiceDALFactory(db);+ const agentVaultServiceCustomHeaderDAL = agentVaultServiceCustomHeaderDALFactory(db);+ const agentVaultServiceSubstitutionDAL = agentVaultServiceSubstitutionDALFactory(db);const agentVaultSessionDAL = agentVaultSessionDALFactory(db);const agentVaultSessionAccessBundleDAL = agentVaultSessionAccessBundleDALFactory(db);const agentVaultProxyDAL = agentVaultProxyDALFactory(db);@@ -1819,6 +1825,8 @@ export const registerRoutes = async (const agentVaultAccessBundleService = agentVaultAccessBundleServiceFactory({agentVaultAccessBundleDAL,agentVaultServiceDAL,+ agentVaultServiceCustomHeaderDAL,+ agentVaultServiceSubstitutionDAL,permissionService,kmsService,membershipDAL,@@ -1844,6 +1852,7 @@ export const registerRoutes = async (});const agentVaultMembershipService = agentVaultMembershipServiceFactory({+ agentVaultMemberDAL,membershipDAL,identityDAL,membershipRoleDAL,@@ -1936,6 +1945,8 @@ export const registerRoutes = async (const agentVaultProxyService = agentVaultProxyServiceFactory({agentVaultProxyDAL,agentVaultResolveDAL,+ agentVaultServiceCustomHeaderDAL,+ agentVaultServiceSubstitutionDAL,agentVaultSessionDAL,membershipDAL,orgDAL,diff --git a/backend/src/server/routes/v1/invite-org-router.ts b/backend/src/server/routes/v1/invite-org-router.tsindex 20ca21d992..5e729fa486 100644--- a/backend/src/server/routes/v1/invite-org-router.ts+++ b/backend/src/server/routes/v1/invite-org-router.ts@@ -1,6 +1,7 @@import { z } from "zod";import { AccessScope, ActionProjectType, OrgMembershipRole, ProjectMembershipRole } from "@app/db/schemas";+import { AgentVaultMemberType } from "@app/ee/services/agent-vault/agent-vault-enums";import { EventType } from "@app/ee/services/audit-log/audit-log-types";import { PamProductRole } from "@app/ee/services/pam/pam-enums";import { ForbiddenRequestError } from "@app/lib/errors";@@ -206,7 +207,7 @@ export const registerInviteOrgRouter = async (server: FastifyZodProvider) => {}}- const { memberships } = await server.services.agentVaultMembership.addProductUserMembers({+ const { members } = await server.services.agentVaultMembership.addProductMembers({projectId: agentVaultProjectId,ctx: {actorId: req.permission.id,@@ -215,23 +216,25 @@ export const registerInviteOrgRouter = async (server: FastifyZodProvider) => {actorAuthMethod: req.permission.authMethod},userIds: [],+ groupIds: [],+ machineIdentityIds: [],emails: req.body.inviteeEmails,role: ProjectMembershipRole.Member});- for await (const membership of memberships) {+ for await (const member of members) {await server.services.auditLog.createAuditLog({...req.auditLogInfo,orgId: req.permission.orgId,projectId: agentVaultProjectId,event: {type: EventType.AGENT_VAULT_MEMBER_ADD,- metadata: { userId: membership.userId, userName: membership.userName, role: membership.role }+ metadata: { userId: member.actor.id, userName: member.actorName, role: member.role }}});emitAgentVaultTelemetry(server.services.telemetry, req, {event: PostHogEventTypes.AgentVaultProductMemberAdded,- properties: { memberType: "user", role: membership.role }+ properties: { memberType: AgentVaultMemberType.User, role: member.role }});}} catch (err) {diff --git a/backend/src/services/org/org-dal.ts b/backend/src/services/org/org-dal.tsindex 80053f10a5..94e7df66ce 100644--- a/backend/src/services/org/org-dal.ts+++ b/backend/src/services/org/org-dal.ts@@ -863,6 +863,53 @@ export const orgDALFactory = (db: TDbClient) => {}};+ /**+ * The batched form of findEffectiveOrgMembership. A direct row is authoritative, as there: deactivating+ * someone's own membership suspends them even while a group they belong to stays active. Unlike the+ * singular helper it applies no status filter, so an invited member counts as active.+ */+ const findActiveEffectiveOrgMemberActorIds = async (+ dto: { actorType: ActorType; actorIds: string[]; orgId: string },+ tx?: Knex+ ): Promise<Set<string>> => {+ if (!dto.actorIds.length) return new Set();++ try {+ const conn = tx ?? db.replicaNode();+ const isUser = dto.actorType === ActorType.USER;+ const groupTable = isUser ? TableName.UserGroupMembership : TableName.IdentityGroupMembership;+ const groupActorColumn = `${groupTable}.${isUser ? "userId" : "identityId"}`;+ const directColumn = `${TableName.Membership}.${isUser ? "actorUserId" : "actorIdentityId"}`;++ const directRows = (await conn(TableName.Membership)+ .where(`${TableName.Membership}.scope`, AccessScope.Organization)+ .where(`${TableName.Membership}.scopeOrgId`, dto.orgId)+ .whereIn(directColumn, dto.actorIds)+ .select(conn.raw(`?? as "actorId"`, [directColumn]), `${TableName.Membership}.isActive`)) as {+ actorId: string;+ isActive: boolean;+ }[];++ const active = new Set(directRows.filter((row) => row.isActive).map((row) => row.actorId));+ const hasDirectRow = new Set(directRows.map((row) => row.actorId));+ const withoutDirect = dto.actorIds.filter((id) => !hasDirectRow.has(id));+ if (!withoutDirect.length) return active;++ const groupRows = (await conn(TableName.Membership)+ .where(`${TableName.Membership}.scope`, AccessScope.Organization)+ .where(`${TableName.Membership}.scopeOrgId`, dto.orgId)+ .where(`${TableName.Membership}.isActive`, true)+ .join(groupTable, `${groupTable}.groupId`, `${TableName.Membership}.actorGroupId`)+ .whereIn(groupActorColumn, withoutDirect)+ .distinct(conn.raw(`?? as "actorId"`, [groupActorColumn]))) as { actorId: string }[];++ groupRows.forEach((row) => active.add(row.actorId));+ return active;+ } catch (error) {+ throw new DatabaseError({ error, name: "Find active effective org member actor ids" });+ }+ };+const findActiveEffectiveOrgMembershipsByUserId = async (userId: string, tx?: Knex): Promise<TMemberships[]> => {try {const conn = tx ?? db.replicaNode();@@ -1103,6 +1150,7 @@ export const orgDALFactory = (db: TDbClient) => {findMembership,findEffectiveOrgMembership,findEffectiveOrgMemberships,+ findActiveEffectiveOrgMemberActorIds,findActiveEffectiveOrgMembershipsByUserId,findMembershipWithScimFilter,createMembership,diff --git a/backend/src/services/telemetry/telemetry-types.ts b/backend/src/services/telemetry/telemetry-types.tsindex cdb14caee7..0502e3e1f4 100644--- a/backend/src/services/telemetry/telemetry-types.ts+++ b/backend/src/services/telemetry/telemetry-types.ts@@ -1,5 +1,9 @@import { IdentityAuthMethod, ProjectType } from "@app/db/schemas";-import { AgentVaultCredentialType, AgentVaultTrafficPolicy } from "@app/ee/services/agent-vault/agent-vault-enums";+import {+ AgentVaultCredentialType,+ AgentVaultMemberType,+ AgentVaultTrafficPolicy+} from "@app/ee/services/agent-vault/agent-vault-enums";import {AcmeAccountActor,AcmeProfileActor,@@ -2395,8 +2399,6 @@ type TAgentVaultEventBase = {actorType: string;};-type TAgentVaultMemberType = "user" | "group" | "identity";-export type TAgentVaultAccessBundleCreatedEvent = {event: PostHogEventTypes.AgentVaultAccessBundleCreated;properties: TAgentVaultEventBase & { accessBundleId: string };@@ -2419,6 +2421,10 @@ export type TAgentVaultServiceCreatedEvent = {serviceId: string;credentialType: AgentVaultCredentialType;hostPatternCount: number;+ allowedMethodCount: number;+ allowedPathPrefixCount: number;+ customHeaderCount: number;+ substitutionCount: number;};};@@ -2429,6 +2435,10 @@ export type TAgentVaultServiceUpdatedEvent = {serviceId: string;credentialType: AgentVaultCredentialType;hostPatternCount: number;+ allowedMethodCount: number;+ allowedPathPrefixCount: number;+ customHeaderCount: number;+ substitutionCount: number;};};@@ -2439,12 +2449,12 @@ export type TAgentVaultServiceDeletedEvent = {export type TAgentVaultAccessBundleMemberAddedEvent = {event: PostHogEventTypes.AgentVaultAccessBundleMemberAdded;- properties: TAgentVaultEventBase & { accessBundleId: string; memberType: TAgentVaultMemberType };+ properties: TAgentVaultEventBase & { accessBundleId: string; memberType: AgentVaultMemberType };};export type TAgentVaultAccessBundleMemberRemovedEvent = {event: PostHogEventTypes.AgentVaultAccessBundleMemberRemoved;- properties: TAgentVaultEventBase & { accessBundleId: string; memberType: TAgentVaultMemberType };+ properties: TAgentVaultEventBase & { accessBundleId: string; memberType: AgentVaultMemberType };};export type TAgentVaultSessionCreatedEvent = {@@ -2506,17 +2516,17 @@ export type TAgentVaultProxyEnrolledEvent = {export type TAgentVaultProductMemberAddedEvent = {event: PostHogEventTypes.AgentVaultProductMemberAdded;- properties: TAgentVaultEventBase & { memberType: TAgentVaultMemberType; role: string };+ properties: TAgentVaultEventBase & { memberType: AgentVaultMemberType; role: string };};export type TAgentVaultProductMemberUpdatedEvent = {event: PostHogEventTypes.AgentVaultProductMemberUpdated;- properties: TAgentVaultEventBase & { memberType: TAgentVaultMemberType; role: string };+ properties: TAgentVaultEventBase & { memberType: AgentVaultMemberType; role: string };};export type TAgentVaultProductMemberRemovedEvent = {event: PostHogEventTypes.AgentVaultProductMemberRemoved;- properties: TAgentVaultEventBase & { memberType: TAgentVaultMemberType };+ properties: TAgentVaultEventBase & { memberType: AgentVaultMemberType };};export type TAgentVaultPostHogEvent =diff --git a/docs/api-reference/endpoints/agent-vault-access-bundle-members/add.mdx b/docs/api-reference/endpoints/agent-vault-access-bundle-members/add.mdxnew file mode 100644index 0000000000..34743f592b--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-access-bundle-members/add.mdx@@ -0,0 +1,4 @@+---+title: "Add bundle members"+openapi: "POST /api/v1/agent-vault/access-bundles/{accessBundleId}/members"+---diff --git a/docs/api-reference/endpoints/agent-vault-access-bundle-members/list.mdx b/docs/api-reference/endpoints/agent-vault-access-bundle-members/list.mdxnew file mode 100644index 0000000000..9f22e28d4c--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-access-bundle-members/list.mdx@@ -0,0 +1,4 @@+---+title: "List bundle members"+openapi: "GET /api/v1/agent-vault/access-bundles/{accessBundleId}/members"+---diff --git a/docs/api-reference/endpoints/agent-vault-access-bundle-members/revoke.mdx b/docs/api-reference/endpoints/agent-vault-access-bundle-members/revoke.mdxnew file mode 100644index 0000000000..112cf7b63b--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-access-bundle-members/revoke.mdx@@ -0,0 +1,4 @@+---+title: "Revoke bundle members"+openapi: "POST /api/v1/agent-vault/access-bundles/{accessBundleId}/members/revoke"+---diff --git a/docs/api-reference/endpoints/agent-vault-access-bundles/create.mdx b/docs/api-reference/endpoints/agent-vault-access-bundles/create.mdxnew file mode 100644index 0000000000..3fdd9c6f6b--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-access-bundles/create.mdx@@ -0,0 +1,4 @@+---+title: "Create access bundle"+openapi: "POST /api/v1/agent-vault/access-bundles"+---diff --git a/docs/api-reference/endpoints/agent-vault-access-bundles/delete.mdx b/docs/api-reference/endpoints/agent-vault-access-bundles/delete.mdxnew file mode 100644index 0000000000..514d21bc16--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-access-bundles/delete.mdx@@ -0,0 +1,4 @@+---+title: "Delete access bundle"+openapi: "DELETE /api/v1/agent-vault/access-bundles/{accessBundleId}"+---diff --git a/docs/api-reference/endpoints/agent-vault-access-bundles/get.mdx b/docs/api-reference/endpoints/agent-vault-access-bundles/get.mdxnew file mode 100644index 0000000000..c28b0bb048--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-access-bundles/get.mdx@@ -0,0 +1,4 @@+---+title: "Get access bundle"+openapi: "GET /api/v1/agent-vault/access-bundles/{accessBundleId}"+---diff --git a/docs/api-reference/endpoints/agent-vault-access-bundles/list.mdx b/docs/api-reference/endpoints/agent-vault-access-bundles/list.mdxnew file mode 100644index 0000000000..f0719b0dff--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-access-bundles/list.mdx@@ -0,0 +1,4 @@+---+title: "List access bundles"+openapi: "GET /api/v1/agent-vault/access-bundles"+---diff --git a/docs/api-reference/endpoints/agent-vault-access-bundles/update.mdx b/docs/api-reference/endpoints/agent-vault-access-bundles/update.mdxnew file mode 100644index 0000000000..79b6045610--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-access-bundles/update.mdx@@ -0,0 +1,4 @@+---+title: "Update access bundle"+openapi: "PATCH /api/v1/agent-vault/access-bundles/{accessBundleId}"+---diff --git a/docs/api-reference/endpoints/agent-vault-members/add.mdx b/docs/api-reference/endpoints/agent-vault-members/add.mdxnew file mode 100644index 0000000000..891cf834c5--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-members/add.mdx@@ -0,0 +1,4 @@+---+title: "Add members"+openapi: "POST /api/v1/agent-vault/members"+---diff --git a/docs/api-reference/endpoints/agent-vault-members/list.mdx b/docs/api-reference/endpoints/agent-vault-members/list.mdxnew file mode 100644index 0000000000..18f04a8975--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-members/list.mdx@@ -0,0 +1,4 @@+---+title: "List members"+openapi: "GET /api/v1/agent-vault/members"+---diff --git a/docs/api-reference/endpoints/agent-vault-members/revoke.mdx b/docs/api-reference/endpoints/agent-vault-members/revoke.mdxnew file mode 100644index 0000000000..9cd98908c5--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-members/revoke.mdx@@ -0,0 +1,4 @@+---+title: "Revoke members"+openapi: "POST /api/v1/agent-vault/members/revoke"+---diff --git a/docs/api-reference/endpoints/agent-vault-members/update-role.mdx b/docs/api-reference/endpoints/agent-vault-members/update-role.mdxnew file mode 100644index 0000000000..b553506135--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-members/update-role.mdx@@ -0,0 +1,4 @@+---+title: "Update member role"+openapi: "PATCH /api/v1/agent-vault/members/{actorType}/{actorId}"+---diff --git a/docs/api-reference/endpoints/agent-vault-proxies/create.mdx b/docs/api-reference/endpoints/agent-vault-proxies/create.mdxnew file mode 100644index 0000000000..e3ad47dd01--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-proxies/create.mdx@@ -0,0 +1,4 @@+---+title: "Create proxy"+openapi: "POST /api/v1/agent-vault/proxies"+---diff --git a/docs/api-reference/endpoints/agent-vault-proxies/delete.mdx b/docs/api-reference/endpoints/agent-vault-proxies/delete.mdxnew file mode 100644index 0000000000..ad9e2a1775--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-proxies/delete.mdx@@ -0,0 +1,4 @@+---+title: "Delete proxy"+openapi: "DELETE /api/v1/agent-vault/proxies/{proxyId}"+---diff --git a/docs/api-reference/endpoints/agent-vault-proxies/enrollment-token.mdx b/docs/api-reference/endpoints/agent-vault-proxies/enrollment-token.mdxnew file mode 100644index 0000000000..3adf747645--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-proxies/enrollment-token.mdx@@ -0,0 +1,4 @@+---+title: "Reissue enrollment token"+openapi: "POST /api/v1/agent-vault/proxies/{proxyId}/token-auth/enrollment-token"+---diff --git a/docs/api-reference/endpoints/agent-vault-proxies/list.mdx b/docs/api-reference/endpoints/agent-vault-proxies/list.mdxnew file mode 100644index 0000000000..0b62290a49--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-proxies/list.mdx@@ -0,0 +1,4 @@+---+title: "List proxies"+openapi: "GET /api/v1/agent-vault/proxies"+---diff --git a/docs/api-reference/endpoints/agent-vault-proxies/revoke.mdx b/docs/api-reference/endpoints/agent-vault-proxies/revoke.mdxnew file mode 100644index 0000000000..a001399bcb--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-proxies/revoke.mdx@@ -0,0 +1,4 @@+---+title: "Revoke proxy access"+openapi: "POST /api/v1/agent-vault/proxies/{proxyId}/revoke"+---diff --git a/docs/api-reference/endpoints/agent-vault-proxies/update.mdx b/docs/api-reference/endpoints/agent-vault-proxies/update.mdxnew file mode 100644index 0000000000..fcc2719347--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-proxies/update.mdx@@ -0,0 +1,4 @@+---+title: "Update proxy"+openapi: "PATCH /api/v1/agent-vault/proxies/{proxyId}"+---diff --git a/docs/api-reference/endpoints/agent-vault-services/create.mdx b/docs/api-reference/endpoints/agent-vault-services/create.mdxnew file mode 100644index 0000000000..985c897b68--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-services/create.mdx@@ -0,0 +1,4 @@+---+title: "Create service"+openapi: "POST /api/v1/agent-vault/access-bundles/{accessBundleId}/services"+---diff --git a/docs/api-reference/endpoints/agent-vault-services/delete.mdx b/docs/api-reference/endpoints/agent-vault-services/delete.mdxnew file mode 100644index 0000000000..a59ce7c31b--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-services/delete.mdx@@ -0,0 +1,4 @@+---+title: "Delete service"+openapi: "DELETE /api/v1/agent-vault/access-bundles/{accessBundleId}/services/{serviceId}"+---diff --git a/docs/api-reference/endpoints/agent-vault-services/update.mdx b/docs/api-reference/endpoints/agent-vault-services/update.mdxnew file mode 100644index 0000000000..a52cc9932c--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-services/update.mdx@@ -0,0 +1,4 @@+---+title: "Update service"+openapi: "PATCH /api/v1/agent-vault/access-bundles/{accessBundleId}/services/{serviceId}"+---diff --git a/docs/api-reference/endpoints/agent-vault-sessions/create.mdx b/docs/api-reference/endpoints/agent-vault-sessions/create.mdxnew file mode 100644index 0000000000..bfad4706ad--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-sessions/create.mdx@@ -0,0 +1,4 @@+---+title: "Create session"+openapi: "POST /api/v1/agent-vault/sessions"+---diff --git a/docs/api-reference/endpoints/agent-vault-sessions/list.mdx b/docs/api-reference/endpoints/agent-vault-sessions/list.mdxnew file mode 100644index 0000000000..e688b4a058--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-sessions/list.mdx@@ -0,0 +1,4 @@+---+title: "List sessions"+openapi: "GET /api/v1/agent-vault/sessions"+---diff --git a/docs/api-reference/endpoints/agent-vault-sessions/revoke.mdx b/docs/api-reference/endpoints/agent-vault-sessions/revoke.mdxnew file mode 100644index 0000000000..a4b1f3dc5d--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-sessions/revoke.mdx@@ -0,0 +1,4 @@+---+title: "Revoke session"+openapi: "POST /api/v1/agent-vault/sessions/{sessionId}/revoke"+---diff --git a/docs/cli/commands/agent-vault.mdx b/docs/cli/commands/agent-vault.mdxindex 2f7c628b8b..c90dab8558 100644--- a/docs/cli/commands/agent-vault.mdx+++ b/docs/cli/commands/agent-vault.mdx@@ -149,7 +149,7 @@ infisical agent-vault run --session-token <session-token> --proxy 10.0.1.5:17323#### `--access-bundle`-Create a session with this access bundle, by name. Pass it once. Creates it as the machine identity from `--client-id` and `--client-secret`, or as your login. The identity has to be an Agent Vault member with a grant on the access bundle. Can't be combined with `--session-token`.+Create a session with this access bundle, by name. Pass it once. Creates it as the machine identity from `--client-id` and `--client-secret`, or as your login. The machine identity has to be an Agent Vault member with a grant on the access bundle. Can't be combined with `--session-token`.```bash# Examplediff --git a/docs/docs.json b/docs/docs.jsonindex 1e979bfdca..20e8e16cbb 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -4423,6 +4423,65 @@}]},+ {+ "group": "Agent Vault",+ "pages": [+ {+ "group": "Access bundles",+ "pages": [+ "api-reference/endpoints/agent-vault-access-bundles/list",+ "api-reference/endpoints/agent-vault-access-bundles/get",+ "api-reference/endpoints/agent-vault-access-bundles/create",+ "api-reference/endpoints/agent-vault-access-bundles/update",+ "api-reference/endpoints/agent-vault-access-bundles/delete"+ ]+ },+ {+ "group": "Services",+ "pages": [+ "api-reference/endpoints/agent-vault-services/create",+ "api-reference/endpoints/agent-vault-services/update",+ "api-reference/endpoints/agent-vault-services/delete"+ ]+ },+ {+ "group": "Access bundle members",+ "pages": [+ "api-reference/endpoints/agent-vault-access-bundle-members/list",+ "api-reference/endpoints/agent-vault-access-bundle-members/add",+ "api-reference/endpoints/agent-vault-access-bundle-members/revoke"+ ]+ },+ {+ "group": "Members",+ "pages": [+ "api-reference/endpoints/agent-vault-members/list",+ "api-reference/endpoints/agent-vault-members/add",+ "api-reference/endpoints/agent-vault-members/update-role",+ "api-reference/endpoints/agent-vault-members/revoke"+ ]+ },+ {+ "group": "Proxies",+ "pages": [+ "api-reference/endpoints/agent-vault-proxies/list",+ "api-reference/endpoints/agent-vault-proxies/create",+ "api-reference/endpoints/agent-vault-proxies/update",+ "api-reference/endpoints/agent-vault-proxies/delete",+ "api-reference/endpoints/agent-vault-proxies/enrollment-token",+ "api-reference/endpoints/agent-vault-proxies/revoke"+ ]+ },+ {+ "group": "Sessions",+ "pages": [+ "api-reference/endpoints/agent-vault-sessions/list",+ "api-reference/endpoints/agent-vault-sessions/create",+ "api-reference/endpoints/agent-vault-sessions/revoke"+ ]+ }+ ]+ },{"group": "KMIP servers","boost": 0.25,@@ -4723,6 +4782,66 @@}},"redirects": [+ {+ "source": "/api-reference/endpoints/agent-vault-memberships/list-users",+ "destination": "/api-reference/endpoints/agent-vault-members/list"+ },+ {+ "source": "/api-reference/endpoints/agent-vault-memberships/list-groups",+ "destination": "/api-reference/endpoints/agent-vault-members/list"+ },+ {+ "source": "/api-reference/endpoints/agent-vault-memberships/list-identities",+ "destination": "/api-reference/endpoints/agent-vault-members/list"+ },+ {+ "source": "/api-reference/endpoints/agent-vault-memberships/add-users",+ "destination": "/api-reference/endpoints/agent-vault-members/add"+ },+ {+ "source": "/api-reference/endpoints/agent-vault-memberships/add-group",+ "destination": "/api-reference/endpoints/agent-vault-members/add"+ },+ {+ "source": "/api-reference/endpoints/agent-vault-memberships/add-identity",+ "destination": "/api-reference/endpoints/agent-vault-members/add"+ },+ {+ "source": "/api-reference/endpoints/agent-vault-memberships/update-user-role",+ "destination": "/api-reference/endpoints/agent-vault-members/update-role"+ },+ {+ "source": "/api-reference/endpoints/agent-vault-memberships/update-group-role",+ "destination": "/api-reference/endpoints/agent-vault-members/update-role"+ },+ {+ "source": "/api-reference/endpoints/agent-vault-memberships/update-identity-role",+ "destination": "/api-reference/endpoints/agent-vault-members/update-role"+ },+ {+ "source": "/api-reference/endpoints/agent-vault-memberships/remove-user",+ "destination": "/api-reference/endpoints/agent-vault-members/revoke"+ },+ {+ "source": "/api-reference/endpoints/agent-vault-memberships/remove-group",+ "destination": "/api-reference/endpoints/agent-vault-members/revoke"+ },+ {+ "source": "/api-reference/endpoints/agent-vault-memberships/remove-identity",+ "destination": "/api-reference/endpoints/agent-vault-members/revoke"+ },+ {+ "source": "/api-reference/endpoints/agent-vault-access-bundle-members/remove-user",+ "destination": "/api-reference/endpoints/agent-vault-access-bundle-members/revoke"+ },+ {+ "source": "/api-reference/endpoints/agent-vault-access-bundle-members/remove-group",+ "destination": "/api-reference/endpoints/agent-vault-access-bundle-members/revoke"+ },+ {+ "source": "/api-reference/endpoints/agent-vault-access-bundle-members/remove-identity",+ "destination": "/api-reference/endpoints/agent-vault-access-bundle-members/revoke"+ },{"source": "/ai/model-context-protocol","destination": "/documentation/getting-started/set-up-with-ai"diff --git a/docs/documentation/platform/agent-vault/access-bundles.mdx b/docs/documentation/platform/agent-vault/access-bundles.mdxindex 529a0f1726..db2ede3c9f 100644--- a/docs/documentation/platform/agent-vault/access-bundles.mdx+++ b/docs/documentation/platform/agent-vault/access-bundles.mdx@@ -55,4 +55,4 @@ To allow a user, group, or machine identity to create sessions for a given acces### Revoke access-To revoke access from a user, group, or machine identity, open the bundle and select **Options** > **Manage Access**. Open the member's actions menu and select **Revoke Access**. Any of their running agents lose the bundle's credentials within one poll interval of the proxy.\ No newline at end of file+To revoke access from a user, group, or machine identity, open the bundle and select **Options** > **Manage Access**. Find them with the search box, open their actions menu, and select **Revoke Access**. Any of their running agents lose the bundle's credentials within one poll interval of the proxy.\ No newline at end of filediff --git a/docs/documentation/platform/agent-vault/access-control.mdx b/docs/documentation/platform/agent-vault/access-control.mdxindex cce43679b0..432d788036 100644--- a/docs/documentation/platform/agent-vault/access-control.mdx+++ b/docs/documentation/platform/agent-vault/access-control.mdx@@ -32,6 +32,8 @@ An admin reaches every access bundle without being granted one. A member reaches3. Select **Add Users**, **Add Machine Identity**, or **Add Group**4. Choose who to add, and give them **Admin** or **Member**+Each tab searches the whole membership rather than the rows on screen. A search matches a user's name, username, or email address, and a group or machine identity's name.+Whoever you add has to be an active member of the organization first. Invite them to the organization before adding them here.You can't change your own role or remove your own access. Ask another admin to do either.@@ -40,7 +42,7 @@ You can't change your own role or remove your own access. Ask another admin to dProduct membership is the entry ticket. Reaching a host still takes a grant on the [access bundle](/documentation/platform/agent-vault/access-bundles) that holds the service covering it.-Open an access bundle and select **Manage Access** to grant it to a user, machine identity, or group. The grantee has to be an Agent Vault member already.+Open an access bundle and select **Manage Access** to grant it to a user, machine identity, or group. The grantee has to be an Agent Vault member already. That list is paged and searchable, so finding one member of a bundle granted to hundreds doesn't mean scrolling through all of them.Granting a group grants everyone in it, and each member creates sessions as themselves. Someone who joins the group later picks the grant up, and someone who leaves loses it.@@ -48,4 +50,4 @@ Granting a group grants everyone in it, and each member creates sessions as themA change to membership or a grant reaches a running agent within one proxy poll, 60 seconds by default. Nothing on the agent's machine needs restarting.-Removing someone from Agent Vault also takes away their access bundle grants, so adding them back leaves their sessions without credentials until you grant those again. See [what a running agent can reach](/documentation/platform/agent-vault/sessions#what-a-running-agent-can-reach) for what happens to each kind of change mid-run.+Removing someone from Agent Vault also takes away their access bundle grants, so adding them back leaves their sessions without credentials until you grant those again. See [what a running agent can reach](/documentation/platform/agent-vault/sessions#access-changes) for what happens to each kind of change mid-run.diff --git a/docs/documentation/platform/agent-vault/how-it-works.mdx b/docs/documentation/platform/agent-vault/how-it-works.mdxindex 2a3375e884..8b52c9903c 100644--- a/docs/documentation/platform/agent-vault/how-it-works.mdx+++ b/docs/documentation/platform/agent-vault/how-it-works.mdx@@ -113,11 +113,12 @@ Here's a breakdown of each primitive that Agent Vault relies on.### Services-A service represents one external API, such as GitHub's REST API, Slack's Web API, or Anthropic's messages endpoint. Each service holds three things:+A service represents one external API, such as GitHub's REST API, Slack's Web API, or Anthropic's messages endpoint. Each service holds:- **Hosts.** The host or hosts the service applies to, like `api.github.com`- **Authentication scheme.** How the API authenticates: bearer, basic, or pass-through- **Credential.** The real API token or username and password the proxy attaches to matching requests+- **Rules.** The HTTP methods and paths the service allows, if you want to narrow it furtherYou don't hand services to an agent directly—they're defined within access bundles.@@ -129,7 +130,7 @@ You don't hand services to an agent directly—they're defined within access bunAn access bundle groups a set of services under one name. A **code-review** bundle might hold services for GitHub, Slack, and Anthropic. An **on-call** bundle might hold services for PagerDuty, Datadog, and Slack.-You grant access to a bundle for a user, group, or machine identity. Anyone with access to that bundle can create sessions that reference it.+You grant a bundle to a user, group, or machine identity. Anyone holding that grant can create sessions that reference it.<Card title="Access bundles" icon="box" href="/documentation/platform/agent-vault/access-bundles">Lists of services that AI agents can access during a session.@@ -141,7 +142,7 @@ A session is a time-bound access grant that's scoped to one access bundle. InfisWhen you create a session, you pick one access bundle and set an expiry. The agent never sees the real credentials inside the bundle. All it has is the session token, which only works when the proxy can authorize it against a live session.-Even if an attacker stole the session token, they could only reach hosts that are defined by the access bundle's services, and only until the session expires or you revoke it.+Even if an attacker stole the session token, they could only reach the hosts, methods, and paths that the access bundle's services allow, and only until the session expires or you revoke it.<Card title="Sessions" icon="monitor" href="/documentation/platform/agent-vault/sessions">Time-bound grants that let AI agents access services without holding real credentials.@@ -149,7 +150,7 @@ Even if an attacker stole the session token, they could only reach hosts that ar### Proxies-A proxy runs where your agent's traffic leaves your network. It intercepts every outbound HTTPS request, authorizes the request against the session's access bundle, attaches the matching service's credential as a header, and forwards the request to the upstream host.+A proxy runs where your agent's traffic leaves your network. It intercepts every outbound request, authorizes the request against the session's access bundle, attaches the matching service's credential as a header, and forwards the request to the upstream host. A request that breaks the service's rules is refused instead.<Card title="Proxies" icon="route" href="/documentation/platform/agent-vault/proxies">Forward proxies that intercept an AI agent's requests and attach real credentials on the way out.@@ -161,7 +162,7 @@ Here's what happens when an agent calls `api.github.com` through an Agent Vault1. The agent's HTTPS client routes the request through the [proxy](#proxies) (because the `HTTPS_PROXY` environment variable points at it), including the [session](#sessions) token as the proxy credential.2. The proxy looks up the session with Infisical, checking if it's still live and which [access bundle](#access-bundles) it carries.-3. The proxy looks inside the session's access bundle and finds a [service](#services) whose host pattern covers `api.github.com`. The proxy reads the real GitHub token from that service.+3. The proxy looks inside the session's access bundle and finds a [service](#services) whose host pattern covers `api.github.com`. If that service allows only certain methods or paths, the request is checked against them first. The proxy reads the real GitHub token from that service.4. The proxy opens a new HTTPS connection to `api.github.com`, attaches the real token in the authorization header, and forwards the request.5. GitHub responds. The proxy pipes the response back to the agent.diff --git a/docs/documentation/platform/agent-vault/proxies.mdx b/docs/documentation/platform/agent-vault/proxies.mdxindex fb9c60606a..dcbe219081 100644--- a/docs/documentation/platform/agent-vault/proxies.mdx+++ b/docs/documentation/platform/agent-vault/proxies.mdx@@ -84,6 +84,8 @@ no service covers host "internal.example.com": host blocked by policyPorts are part of the match. A [service's host pattern](/documentation/platform/agent-vault/services#host-patterns) that names no port covers port 443 only, so a service on `example.com` doesn't cover `example.com:8443`, and under this policy a request to the second is refused. Name the port in the pattern to cover it.+The proxy returns a 403 the same way for a request that breaks a service's own [method or path rules](/documentation/platform/agent-vault/services#methods-and-paths), whichever traffic policy it runs.+<Frame><img src="/images/platform/agent-vault/proxy-create.png" alt="The Create Proxy dialog with the two traffic policy options and the poll interval" /></Frame>@@ -92,7 +94,7 @@ Ports are part of the match. A [service's host pattern](/documentation/platform/A comma-separated list of hosts that stay reachable under **Only allow requests to reach hosts specified in access bundles**, with no credential attached. Use it for hosts every agent needs, such as a package registry or a documentation site. Under **Allow requests to reach any host** the list changes nothing.-An exception written without a port matches that host on every port, unlike a service pattern, which means port 443 when it names none.+An exception written without a port matches that host on every port, unlike a [service pattern](/documentation/platform/agent-vault/services#default-port), which means port 443 when it names none. An exception never carries a credential, so the wider match attaches nothing extra.An exception isn't exempt from interception. Every HTTPS host is TLS-terminated by the proxy before any policy applies, so an exception is a host the proxy doesn't block, not a host it leaves alone. To open a host for one access bundle rather than for every agent on the proxy, add a pass-through service to that bundle instead.diff --git a/docs/documentation/platform/agent-vault/services.mdx b/docs/documentation/platform/agent-vault/services.mdxindex 33974c1486..d0cf060dd2 100644--- a/docs/documentation/platform/agent-vault/services.mdx+++ b/docs/documentation/platform/agent-vault/services.mdx@@ -56,7 +56,7 @@ Basic is the right choice for APIs behind HTTP basic authentication, including o### Pass-through-The proxy attaches nothing, and forwards the agent's request to the API unchanged.+The proxy attaches no credential. Unless the service adds [custom headers](#custom-headers) or [substitutions](#substitutions), it forwards the agent's request to the API unchanged.Pass-through is the right choice when the proxy's strict [traffic policy](/documentation/platform/agent-vault/proxies#traffic-policy) would otherwise block the host. It lets the request reach the API without attaching a credential.@@ -98,6 +98,18 @@ To match a port other than `443`, include it in the host:internal-api.example.com:8443```+### Plaintext hosts++A service behaves the same way over plain `http://` as it does over HTTPS. The proxy attaches the credential, the custom headers, and the substitutions either way. Use a plaintext host for an API on your own network that terminates TLS at the edge, or one that serves no HTTPS at all.++Since a host without a port means `443`, a plaintext service has to name its port:++```text+internal-api.example.com:8080+```++The credential crosses that hop unencrypted, so anyone who can read traffic between the proxy and the API can read it. Keep plaintext hosts to a network you trust.+### WildcardsWildcards match exactly one label. The pattern below matches `api.atlassian.net`, but not `a.b.atlassian.net` or `atlassian.net`.@@ -106,9 +118,33 @@ Wildcards match exactly one label. The pattern below matches `api.atlassian.net`*.atlassian.net```-### Paths/routes+## Methods and paths++By default, a service allows every HTTP method and every path on its hosts. When configuring a service, you have the option to narrow it to only the methods and routes your agent needs.++<Frame>+ <img src="/images/platform/agent-vault/service-details.png" alt="The Details step of a GitHub service, allowing GET and POST on the path prefixes /repos and /search" />+</Frame>++### Methods++Select the HTTP methods the service allows. A read-only service might allow only `GET` and `HEAD`, so a request that tries to write is stopped before it leaves your network.++### Path prefixes-You can't configure a specific path/route on a host. Patterns like `api.github.com/repos` aren't supported.+List the routes the service allows. A path prefix matches whole segments, so `/repos` covers `/repos/octo/hello` but not `/repositories`. Write the path exactly as it appears in the URL.++The proxy blocks a request that breaks either rule with a 403:++```text+HTTP/1.1 403 Forbidden++service "github" does not allow POST: blocked by service policy+```++<Note>+A service with path prefixes set also refuses any path that different servers would resolve differently, such as one containing `..` or an encoded slash. Ordinary paths still work, including ones carrying a space or a non-ASCII character such as `/repos/owner/repo/contents/café.md`.+</Note>## Host conflicts@@ -119,8 +155,43 @@ However, two services can match the same host if they define the host pattern di- One service defines its host as `api.github.com`- Another service defines it as `*.github.com`-In the above example, requests to `api.github.com` would get the credential from the first service.+In the above example, requests to `api.github.com` are handled by the first service.++The more specific service handles the request outright, so its [methods and paths](#methods-and-paths) are the ones that apply. If it allows only GET, a POST to `api.github.com` is refused even though the wildcard service allows every method. A wildcard covers the hosts its sibling doesn't name, not the requests its sibling refuses.<Note>Different access bundles can cover the same host with different credentials, since an agent only gets the credential from the access bundle its session is scoped to.-</Note>\ No newline at end of file+</Note>+++## Custom headers++Some APIs need a header alongside the credential, such as an organization ID or an API version. On the **Credential** step, under **Advanced Options**, add one with a name, an optional prefix, and a value. The proxy attaches it to every request to that service, whatever credential type the service uses.++<Frame>+ <img src="/images/platform/agent-vault/service-advanced-options.png" alt="The Credential step with an API version custom header and a substitution that swaps the agent's placeholder for the real token, matched in the header" />+</Frame>++A custom header can't reuse the credential's own header name, because the credential would win and the custom header would do nothing. Infisical rejects the save. Headers the proxy sets itself, such as `Host`, `Content-Length`, and `Connection`, are rejected for the same reason.++A header value can carry a substitution placeholder, which the proxy resolves before it goes out, so one substitution can stand in for a value reused across several headers.++## Substitutions++When an agent already sends a fake value, a substitution swaps it for the real one on the way out. It works with any credential type, including pass-through, which is what makes a host reachable without attaching a credential of its own.++On the **Credential** step, under **Advanced Options**, give the placeholder your agent sends and the real value, then use **Replace In** to select the parts of the request where you want it replaced: the URL path, the query string, the headers, or the body.++For example, an agent configured with `__GITHUB_PAT__` as its GitHub token sends:++```text+Authorization: Bearer __GITHUB_PAT__+```++GitHub receives the real token, and the agent never holds it.++The swap is a plain find-and-replace, so pick a placeholder distinctive enough that it can't appear anywhere else in the request.++A value containing a `/` stays inside one path segment rather than adding another, so a GitLab project reaches the API as `group%2Fproject` and a path prefix still accepts it.++The proxy doesn't rewrite a body over 10 MB, or one sent compressed with `Content-Encoding`. The placeholder goes out unchanged, and the proxy logs a warning naming the service.diff --git a/docs/documentation/platform/agent-vault/sessions.mdx b/docs/documentation/platform/agent-vault/sessions.mdxindex 74723aaf65..de4c812bda 100644--- a/docs/documentation/platform/agent-vault/sessions.mdx+++ b/docs/documentation/platform/agent-vault/sessions.mdx@@ -68,7 +68,7 @@ The **Sessions** page shows each session as **Active**, **Revoked**, or **ExpireThe access bundle is chosen when you create the session and can't be changed afterwards. However, the proxy re-checks whether the agent still gets credentials on every poll (60 seconds by default). Here are a few situations where a session's access might be revoked:-- If a user, group, or machine identity is removed from an access bundle, every session that user or identity created with that bundle stops getting credentials+- If an access bundle is revoked from a user, group, or machine identity, every session they created with that bundle stops getting credentials- If an access bundle is deleted, every session scoped to it stops getting credentials. The session still lists the bundle's name so you can see what it was- If a user is removed from Agent Vault, the proxy refuses every request on their sessionsdiff --git a/docs/images/platform/agent-vault/service-advanced-options.png b/docs/images/platform/agent-vault/service-advanced-options.pngnew file mode 100644index 0000000000..0c36d6f3f7Binary files /dev/null and b/docs/images/platform/agent-vault/service-advanced-options.png differdiff --git a/docs/images/platform/agent-vault/service-details.png b/docs/images/platform/agent-vault/service-details.pngnew file mode 100644index 0000000000..4cb679853bBinary files /dev/null and b/docs/images/platform/agent-vault/service-details.png differdiff --git a/docs/snippets/agent-vault/QuickstartBody.mdx b/docs/snippets/agent-vault/QuickstartBody.mdxindex 1d3c376721..0a7a0d652c 100644--- a/docs/snippets/agent-vault/QuickstartBody.mdx+++ b/docs/snippets/agent-vault/QuickstartBody.mdx@@ -159,10 +159,11 @@ The CLI adds the proxy's certificate authority to the agent process' trusted CAsThe session token was missing from the request. Confirm you passed `--session-token`, or that the token appears as the userinfo in your `HTTPS_PROXY` URL (like `http://x-agent-vault:<session-token>@<proxy-address>`).</Accordion><Accordion title="403 from the proxy">- This could be for two reasons:+ This could be for a few reasons:- The session was revoked or has expired. Check the Sessions page in Infisical, and create a new one if needed.- Under the proxy's [strict traffic policy](/documentation/platform/agent-vault/proxies#traffic-policy), no service in the bundle covers the host you called. Add a service that does, or use a pass-through service.+ - The service covers the host, but the request uses a method or a path it doesn't allow. The message names the service and the method. Check the service's [methods and paths](/documentation/platform/agent-vault/services#methods-and-paths).</Accordion></AccordionGroup>diff --git a/frontend/src/components/agent-vault/AddMemberDialog.tsx b/frontend/src/components/agent-vault/GrantAccessDialog.tsxsimilarity index 57%rename from frontend/src/components/agent-vault/AddMemberDialog.tsxrename to frontend/src/components/agent-vault/GrantAccessDialog.tsxindex 6255b634ba..922b2c21cb 100644--- a/frontend/src/components/agent-vault/AddMemberDialog.tsx+++ b/frontend/src/components/agent-vault/GrantAccessDialog.tsx@@ -1,5 +1,4 @@import { useEffect, useMemo, useState } from "react";-import { BotIcon, UserIcon, UsersIcon } from "lucide-react";import { createNotification } from "@app/components/notifications";import {@@ -15,113 +14,68 @@ import {FieldContent,FieldLabel} from "@app/components/v3";+import { actorIdsPayload } from "@app/helpers/agentVaultMembers";+import { useDebounce } from "@app/hooks";import {useAddAgentVaultAccessBundleMembers,- useListAgentVaultProductGroupMembers,- useListAgentVaultProductIdentityMembers,- useListAgentVaultProductUserMembers+ useListAgentVaultMembers} from "@app/hooks/api/agentVault";-import { TAgentVaultMember } from "@app/hooks/api/agentVault/types";+import { AgentVaultMemberType } from "@app/hooks/api/agentVault/enums";+import { TAgentVaultProductActor } from "@app/hooks/api/agentVault/types";+import { MEMBER_KIND, memberDisplayName, memberSubtitle } from "./MemberName";import { PendingInvitationBadge } from "./PendingInvitationBadge";-enum MemberKind {- User = "user",- Identity = "identity",- Group = "group"-}--const KIND_ICON: Record<MemberKind, typeof UserIcon> = {- [MemberKind.User]: UserIcon,- [MemberKind.Identity]: BotIcon,- [MemberKind.Group]: UsersIcon-};+const PICKER_LIMIT = 50;type Option = {- kind: MemberKind;- id: string;+ actor: TAgentVaultProductActor;label: string;subtitle: string;- isPendingInvitation?: boolean;};type Props = {isOpen: boolean;onOpenChange: (isOpen: boolean) => void;accessBundleId: string;- members: TAgentVaultMember[];};-export const AddMemberDialog = ({ isOpen, onOpenChange, accessBundleId, members }: Props) => {+export const GrantAccessDialog = ({ isOpen, onOpenChange, accessBundleId }: Props) => {const addMembers = useAddAgentVaultAccessBundleMembers();const [selected, setSelected] = useState<Option[]>([]);+ const [search, setSearch] = useState("");+ const [debouncedSearch] = useDebounce(search);useEffect(() => {- if (isOpen) setSelected([]);+ if (isOpen) {+ setSelected([]);+ setSearch("");+ }}, [isOpen]);- const { data: users } = useListAgentVaultProductUserMembers(isOpen);- const { data: groupMemberships } = useListAgentVaultProductGroupMembers(isOpen);- const { data: identities } = useListAgentVaultProductIdentityMembers(isOpen);+ const { data, isFetching } = useListAgentVaultMembers(+ { search: debouncedSearch.trim() || undefined, limit: PICKER_LIMIT },+ isOpen+ );- const grantedIds = useMemo(+ const options = useMemo<Option[]>(() =>- new Set(members.map((member) => member.userId ?? member.identityId ?? member.groupId ?? "")),- [members]+ (data?.members ?? []).map((member) => ({+ actor: member.actor,+ label: memberDisplayName(member.actor),+ subtitle: memberSubtitle(member.actor)+ })),+ [data]);- const options = useMemo<Option[]>(() => {- const userOptions = (users ?? [])- .filter((member) => member.userId)- .map((member) => {- const fullName = [member.firstName, member.lastName].filter(Boolean).join(" ");- return {- kind: MemberKind.User,- id: member.userId as string,- label: fullName || member.username || member.email || "",- subtitle: member.email || member.username,- isPendingInvitation: member.isOrgMembershipPending- };- })- .filter((option) => !grantedIds.has(option.id));-- const groupOptions = (groupMemberships ?? [])- .filter((member) => member.groupId)- .map((member) => ({- kind: MemberKind.Group,- id: member.groupId as string,- label: member.name,- subtitle: "Group"- }))- .filter((option) => !grantedIds.has(option.id));-- const identityOptions = (identities ?? [])- .filter((member) => member.identityId)- .map((member) => ({- kind: MemberKind.Identity,- id: member.identityId as string,- label: member.name,- subtitle: "Machine Identity"- }))- .filter((option) => !grantedIds.has(option.id))- .sort((a, b) => a.label.localeCompare(b.label));-- return [...userOptions, ...groupOptions, ...identityOptions];- }, [users, groupMemberships, identities, grantedIds]);-const handleAdd = async () => {try {if (!selected.length) return;- const idsOfKind = (kind: MemberKind) =>- selected.filter((option) => option.kind === kind).map((option) => option.id);-const { members: granted, skipped } = await addMembers.mutateAsync({accessBundleId,- userIds: idsOfKind(MemberKind.User),- identityIds: idsOfKind(MemberKind.Identity),- groupIds: idsOfKind(MemberKind.Group)+ ...actorIdsPayload(selected.map((option) => option.actor))});if (!granted.length) {@@ -167,22 +121,25 @@ export const AddMemberDialog = ({ isOpen, onOpenChange, accessBundleId, membersmultipleoptions={options}value={selected}- getOptionValue={(option) => `${option.kind}:${option.id}`}+ shouldFilter={false}+ isLoading={isFetching}+ // Without this a chip already picked vanishes when the next search returns a page it is not on.+ includeMissingSelectedOptions+ onInputValueChange={setSearch}+ getOptionValue={(option) => `${option.actor.type}:${option.actor.id}`}getOptionLabel={(option) => option.label}getOptionKeywords={(option) => [option.subtitle]}placeholder="Pick users, groups, or machine identities..."searchPlaceholder="Pick users, groups, or machine identities..."searchAriaLabel="Search users, groups, and machine identities"- emptyMessage={- options.length- ? "No matches."- : "No one left to add. Add them under Access Control first."+ emptyMessage={(inputValue) =>+ inputValue ? "No matches." : "No members yet. Add them under Access Control first."}clearAriaLabel="Clear all grantees"modalonValueChange={(next) => setSelected([...next])}renderValue={(option) => {- const Icon = KIND_ICON[option.kind];+ const { icon: Icon } = MEMBER_KIND[option.actor.type];return (<span className="flex min-w-0 items-center gap-1.5"><Icon className="size-3.5 shrink-0 text-muted" />@@ -191,7 +148,7 @@ export const AddMemberDialog = ({ isOpen, onOpenChange, accessBundleId, members);}}renderOption={(option) => {- const Icon = KIND_ICON[option.kind];+ const { icon: Icon } = MEMBER_KIND[option.actor.type];return (<span className="flex min-w-0 items-center gap-2.5"><Icon className="size-4 shrink-0 text-muted" />@@ -201,7 +158,12 @@ export const AddMemberDialog = ({ isOpen, onOpenChange, accessBundleId, members{option.subtitle}</span></span>- <PendingInvitationBadge isPending={Boolean(option.isPendingInvitation)} />+ <PendingInvitationBadge+ isPending={+ option.actor.type === AgentVaultMemberType.User &&+ option.actor.isOrgMembershipPending+ }+ /></span>);}}diff --git a/frontend/src/components/agent-vault/ManageAccessSheet.tsx b/frontend/src/components/agent-vault/ManageAccessSheet.tsxindex f4357b2f3f..b8e9a740f0 100644--- a/frontend/src/components/agent-vault/ManageAccessSheet.tsx+++ b/frontend/src/components/agent-vault/ManageAccessSheet.tsx@@ -1,6 +1,6 @@-import { useState } from "react";+import { useEffect, useState } from "react";import { format } from "date-fns";-import { BanIcon, MoreHorizontalIcon, UserPlusIcon } from "lucide-react";+import { BanIcon, MoreHorizontalIcon, SearchIcon, UserPlusIcon } from "lucide-react";import { createNotification } from "@app/components/notifications";import {@@ -22,6 +22,10 @@ import {EmptyHeader,EmptyTitle,IconButton,+ InputGroup,+ InputGroupAddon,+ InputGroupInput,+ Pagination,Sheet,SheetContent,SheetDescription,@@ -35,13 +39,20 @@ import {TableHeader,TableRow} from "@app/components/v3";+import { actorIdsPayload } from "@app/helpers/agentVaultMembers";import {- useGetAgentVaultAccessBundle,- useRemoveAgentVaultAccessBundleMember+ getUserTablePreference,+ PreferenceKey,+ setUserTablePreference+} from "@app/helpers/userTablePreferences";+import { useDebounce, useResetPageHelper } from "@app/hooks";+import {+ useListAgentVaultAccessBundleMembers,+ useRevokeAgentVaultAccessBundleMembers} from "@app/hooks/api/agentVault";import { TAgentVaultMember } from "@app/hooks/api/agentVault/types";-import { AddMemberDialog } from "./AddMemberDialog";+import { GrantAccessDialog } from "./GrantAccessDialog";import { memberDisplayName, MemberName } from "./MemberName";type Props = {@@ -53,19 +64,40 @@ export const ManageAccessSheet = ({ accessBundle, onOpenChange }: Props) => {const [isAddOpen, setIsAddOpen] = useState(false);const [memberToRemove, setMemberToRemove] = useState<TAgentVaultMember | null>(null);- const { data: bundleDetails, isPending } = useGetAgentVaultAccessBundle(accessBundle?.id ?? "");- const removeMember = useRemoveAgentVaultAccessBundleMember();+ const [search, setSearch] = useState("");+ const [debouncedSearch] = useDebounce(search);+ const [page, setPage] = useState(1);+ const [perPage, setPerPage] = useState(() =>+ getUserTablePreference("agentVaultAccessBundleMembersTable", PreferenceKey.PerPage, 10)+ );++ // The sheet stays mounted between opens, so a second bundle would inherit the first one's filter.+ useEffect(() => {+ setSearch("");+ setPage(1);+ }, [accessBundle?.id]);++ const { data, isPending } = useListAgentVaultAccessBundleMembers(accessBundle?.id ?? "", {+ search: debouncedSearch.trim() || undefined,+ limit: perPage,+ offset: (page - 1) * perPage+ });+ const revokeMembers = useRevokeAgentVaultAccessBundleMembers();- const members = bundleDetails?.members ?? [];- const memberToRemoveName = memberToRemove ? memberDisplayName(memberToRemove) : "";+ const members = data?.members ?? [];+ const totalCount = data?.totalCount ?? 0;+ useResetPageHelper({ totalCount, offset: (page - 1) * perPage, setPage });++ const isFiltered = Boolean(debouncedSearch.trim());+ const memberToRemoveName = memberToRemove ? memberDisplayName(memberToRemove.actor) : "";const handleRemove = async () => {try {if (!accessBundle || !memberToRemove) return;- await removeMember.mutateAsync({+ await revokeMembers.mutateAsync({accessBundleId: accessBundle.id,- memberId: memberToRemove.id+ ...actorIdsPayload([memberToRemove.actor])});createNotification({text: `Access bundle revoked from "${memberToRemoveName}"`,@@ -88,7 +120,20 @@ export const ManageAccessSheet = ({ accessBundle, onOpenChange }: Props) => {</SheetHeader><div className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto p-4">- <div className="flex items-center justify-end">+ <div className="flex items-center gap-2">+ <InputGroup className="flex-1">+ <InputGroupAddon>+ <SearchIcon />+ </InputGroupAddon>+ <InputGroupInput+ value={search}+ onChange={(e) => {+ setSearch(e.target.value);+ setPage(1);+ }}+ placeholder="Search members..."+ />+ </InputGroup><Button size="sm" variant="av" onClick={() => setIsAddOpen(true)}><UserPlusIcon />Grant Access@@ -100,9 +145,13 @@ export const ManageAccessSheet = ({ accessBundle, onOpenChange }: Props) => {{!isPending && members.length === 0 && (<Empty className="flex-none border"><EmptyHeader>- <EmptyTitle>No members yet</EmptyTitle>+ <EmptyTitle>+ {isFiltered ? "No members match your search" : "No members yet"}+ </EmptyTitle><EmptyDescription>- Grant this bundle to a user, machine identity, or group.+ {isFiltered+ ? "Try a different search term."+ : "Grant this bundle to a user, machine identity, or group."}</EmptyDescription></EmptyHeader></Empty>@@ -130,7 +179,7 @@ export const ManageAccessSheet = ({ accessBundle, onOpenChange }: Props) => {<IconButtonvariant="ghost"size="xs"- aria-label={`Actions for ${memberDisplayName(member)}`}+ aria-label={`Actions for ${memberDisplayName(member.actor)}`}><MoreHorizontalIcon /></IconButton>@@ -151,21 +200,38 @@ export const ManageAccessSheet = ({ accessBundle, onOpenChange }: Props) => {</TableBody></Table>)}++ {totalCount > 0 && (+ <Pagination+ count={totalCount}+ page={page}+ perPage={perPage}+ onChangePage={setPage}+ onChangePerPage={(newPerPage) => {+ setPerPage(newPerPage);+ setPage(1);+ setUserTablePreference(+ "agentVaultAccessBundleMembersTable",+ PreferenceKey.PerPage,+ newPerPage+ );+ }}+ />+ )}</div>{accessBundle && (- <AddMemberDialog+ <GrantAccessDialogisOpen={isAddOpen}onOpenChange={setIsAddOpen}accessBundleId={accessBundle.id}- members={members}/>)}<AlertDialogopen={Boolean(memberToRemove)}onOpenChange={(isOpen) => {- if (!isOpen && !removeMember.isPending) setMemberToRemove(null);+ if (!isOpen && !revokeMembers.isPending) setMemberToRemove(null);}}><AlertDialogContent>@@ -179,10 +245,10 @@ export const ManageAccessSheet = ({ accessBundle, onOpenChange }: Props) => {</AlertDialogDescription></AlertDialogHeader><AlertDialogFooter>- <AlertDialogCancel isDisabled={removeMember.isPending}>Cancel</AlertDialogCancel>+ <AlertDialogCancel isDisabled={revokeMembers.isPending}>Cancel</AlertDialogCancel><AlertDialogActionvariant="danger"- isPending={removeMember.isPending}+ isPending={revokeMembers.isPending}onClick={async (event) => {event.preventDefault();await handleRemove();diff --git a/frontend/src/components/agent-vault/MemberName.tsx b/frontend/src/components/agent-vault/MemberName.tsxindex dbffba19c2..9b09624e16 100644--- a/frontend/src/components/agent-vault/MemberName.tsx+++ b/frontend/src/components/agent-vault/MemberName.tsx@@ -1,37 +1,36 @@import { BotIcon, UserIcon, UsersIcon } from "lucide-react";-import { TAgentVaultMember } from "@app/hooks/api/agentVault/types";+import { AgentVaultMemberType } from "@app/hooks/api/agentVault/enums";+import { TAgentVaultActor, TAgentVaultMember } from "@app/hooks/api/agentVault/types";-export const memberDisplayName = (member: TAgentVaultMember) => {- if (member.group) return member.group.name;- if (member.identity) return member.identity.name;- if (!member.user) return "Unknown";-- const fullName = [member.user.firstName, member.user.lastName].filter(Boolean).join(" ");- return fullName || member.user.username || member.user.email || "Unknown";+export const MEMBER_KIND: Record<AgentVaultMemberType, { label: string; icon: typeof UserIcon }> = {+ [AgentVaultMemberType.User]: { label: "User", icon: UserIcon },+ [AgentVaultMemberType.MachineIdentity]: { label: "Machine Identity", icon: BotIcon },+ [AgentVaultMemberType.Group]: { label: "Group", icon: UsersIcon }};-const memberKind = (member: TAgentVaultMember) => {- if (member.groupId) return { label: "Group", icon: UsersIcon };- if (member.identityId) return { label: "Machine Identity", icon: BotIcon };- return { label: "User", icon: UserIcon };+export const memberDisplayName = (actor: TAgentVaultActor) => {+ if (actor.type !== AgentVaultMemberType.User) return actor.name;++ const fullName = [actor.firstName, actor.lastName].filter(Boolean).join(" ");+ return fullName || actor.username || actor.email || "Unknown";};-const memberSubtitle = (member: TAgentVaultMember, kindLabel: string) => {- if (member.user) return member.user.email || member.user.username;- return kindLabel;+export const memberSubtitle = (actor: TAgentVaultActor) => {+ if (actor.type !== AgentVaultMemberType.User) return MEMBER_KIND[actor.type].label;+ return actor.email || actor.username;};export const MemberName = ({ member }: { member: TAgentVaultMember }) => {- const { label, icon: Icon } = memberKind(member);+ const { label, icon: Icon } = MEMBER_KIND[member.actor.type];return (<div className="flex min-w-0 items-center gap-2.5"><Icon className="size-4 shrink-0 text-muted" /><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, label)}</div>+ <div className="truncate">{memberDisplayName(member.actor)}</div>+ <div className="truncate text-xs leading-4 text-muted">{memberSubtitle(member.actor)}</div></div></div>);diff --git a/frontend/src/components/agent-vault/service-sheet/CredentialFields.tsx b/frontend/src/components/agent-vault/service-sheet/CredentialFields.tsxindex ee8717f2c8..10171e6f44 100644--- a/frontend/src/components/agent-vault/service-sheet/CredentialFields.tsx+++ b/frontend/src/components/agent-vault/service-sheet/CredentialFields.tsx@@ -1,6 +1,6 @@import { useEffect, useState } from "react";import { Controller, ControllerRenderProps, useFormContext } from "react-hook-form";-import { EyeIcon, EyeOffIcon } from "lucide-react";+import { EyeIcon, EyeOffIcon, XIcon } from "lucide-react";import {Alert,@@ -41,40 +41,86 @@ export const credentialPreview = (return `${form.headerName || "Authorization"}: ${prefix}${secret}`;};-type SecretName = "secret" | "username";+type SecretName =+ | "secret"+ | "username"+ | `customHeaders.${number}.value`+ | `substitutions.${number}.value`;-const SecretInput = <TName extends SecretName>({+export const SecretInput = <TName extends SecretName>({field,label,+ ariaLabel,placeholder,isError,- isUntouched+ isUntouched,+ hasStoredSecret,+ canBeCleared}: {field: ControllerRenderProps<TServiceForm, TName>;label: string;+ /** Needed where the visible label renders on the first row only, as the repeating lists do. */+ ariaLabel?: string;placeholder: string;isError: boolean;isUntouched: boolean;+ /** Whether a stored secret stands behind the sentinel. False on create, and once the credential+ * type moves away from the stored one, where there is nothing to restore or clear. */+ hasStoredSecret: boolean;+ /** Whether empty is a value this field can hold. Only such a field offers the clear button. */+ canBeCleared: boolean;}) => {+ const { setFocus } = useFormContext<TServiceForm>();const [isVisible, setIsVisible] = useState(false);+ const [isCleared, setIsCleared] = useState(false);++ // The sheet is not unmounted between opens, so the flag has to follow the value back to the sentinel.+ useEffect(() => {+ if (isUntouched) setIsCleared(false);+ }, [isUntouched]);++ const lowerLabel = label.toLowerCase();return (<InputGroup><InputGroupInput{...field}+ aria-label={ariaLabel}type={isVisible ? "text" : "password"}- // Selected rather than cleared, so focusing the field and moving on cannot remove a credential.- onFocus={(event) => {- if (isUntouched) event.target.select();+ onChange={(event) => {+ setIsCleared(false);+ field.onChange(event);+ }}+ onFocus={() => {+ if (isUntouched) field.onChange("");+ }}+ // Empty reads the same whether the secret was meant to go or the field was only clicked into,+ // so the clear button is made the one way to say it and passing through loses nothing.+ onBlur={() => {+ if (hasStoredSecret && !field.value && !isCleared) field.onChange(UNCHANGED_SECRET);+ field.onBlur();}}placeholder={placeholder}isError={isError}/><InputGroupAddon align="inline-end">+ {canBeCleared && hasStoredSecret && (+ <InputGroupButton+ isDisabled={isCleared}+ aria-label={`Clear ${lowerLabel}`}+ onClick={() => {+ setIsCleared(true);+ field.onChange("");+ setFocus(field.name);+ }}+ >+ <XIcon />+ </InputGroupButton>+ )}<InputGroupButton// A stored credential is never returned, so until it is replaced there is nothing to reveal.- isDisabled={isUntouched}- aria-label={`${isVisible ? "Hide" : "Show"} ${label.toLowerCase()}`}+ isDisabled={isUntouched || !field.value}+ aria-label={`${isVisible ? "Hide" : "Show"} ${lowerLabel}`}onClick={() => setIsVisible((prev) => !prev)}>{isVisible ? <EyeOffIcon /> : <EyeIcon />}@@ -99,6 +145,8 @@ export const CredentialFields = ({ storedType }: Props) => {const isBasic = credentialType === AgentVaultCredentialType.Basic;const isUntouched = secret === UNCHANGED_SECRET;const isUsernameUntouched = username === UNCHANGED_SECRET;+ // A stored secret belongs to the type it was saved under, so switching type leaves nothing behind it.+ const hasStoredSecret = Boolean(storedType) && credentialType === storedType;useEffect(() => {if (!storedType || credentialType === storedType) return;@@ -106,6 +154,30 @@ export const CredentialFields = ({ storedType }: Props) => {if (isUsernameUntouched) setValue("username", "");}, [isUntouched, isUsernameUntouched, credentialType, storedType, setValue]);+ const secretField = (+ <Controller+ control={control}+ name="secret"+ render={({ field, fieldState }) => (+ <Field className="flex-1">+ <FieldLabel>{isBasic ? "Password" : "Token"}</FieldLabel>+ <FieldContent>+ <SecretInput+ field={field}+ label={isBasic ? "Password" : "Token"}+ placeholder={isBasic ? "Enter the password" : "Enter the token"}+ isError={Boolean(fieldState.error)}+ isUntouched={isUntouched}+ hasStoredSecret={hasStoredSecret}+ canBeCleared={isBasic}+ />+ <FieldError>{fieldState.error?.message}</FieldError>+ </FieldContent>+ </Field>+ )}+ />+ );+return (<div className="flex flex-col gap-5"><Controller@@ -133,12 +205,12 @@ export const CredentialFields = ({ storedType }: Props) => {/>{credentialType === AgentVaultCredentialType.Bearer && (- <>+ <div className="flex items-start gap-3"><Controllercontrol={control}name="headerName"render={({ field, fieldState }) => (- <Field>+ <Field className="w-56"><FieldLabel>Header Name</FieldLabel><FieldContent><Input@@ -155,7 +227,7 @@ export const CredentialFields = ({ storedType }: Props) => {control={control}name="headerPrefix"render={({ field, fieldState }) => (- <Field>+ <Field className="w-28"><FieldLabel>Prefix</FieldLabel><FieldContent><Input {...field} placeholder="Bearer" isError={Boolean(fieldState.error)} />@@ -164,51 +236,35 @@ export const CredentialFields = ({ storedType }: Props) => {</Field>)}/>- </>+ {secretField}+ </div>)}{credentialType === AgentVaultCredentialType.Basic && (- <Controller- control={control}- name="username"- render={({ field, fieldState }) => (- <Field>- <FieldLabel>Username</FieldLabel>- <FieldContent>- <SecretInput- field={field}- label="Username"- placeholder="Enter the username"- isError={Boolean(fieldState.error)}- isUntouched={isUsernameUntouched}- />- <FieldError>{fieldState.error?.message}</FieldError>- </FieldContent>- </Field>- )}- />- )}-- {credentialType !== AgentVaultCredentialType.Passthrough && (- <Controller- control={control}- name="secret"- render={({ field, fieldState }) => (- <Field>- <FieldLabel>{isBasic ? "Password" : "Token"}</FieldLabel>- <FieldContent>- <SecretInput- field={field}- label={isBasic ? "Password" : "Token"}- placeholder={isBasic ? "Enter the password" : "Enter the token"}- isError={Boolean(fieldState.error)}- isUntouched={isUntouched}- />- <FieldError>{fieldState.error?.message}</FieldError>- </FieldContent>- </Field>- )}- />+ <div className="flex items-start gap-3">+ <Controller+ control={control}+ name="username"+ render={({ field, fieldState }) => (+ <Field className="flex-1">+ <FieldLabel>Username</FieldLabel>+ <FieldContent>+ <SecretInput+ field={field}+ label="Username"+ placeholder="Enter the username"+ isError={Boolean(fieldState.error)}+ isUntouched={isUsernameUntouched}+ hasStoredSecret={hasStoredSecret}+ canBeCleared+ />+ <FieldError>{fieldState.error?.message}</FieldError>+ </FieldContent>+ </Field>+ )}+ />+ {secretField}+ </div>)}{credentialType !== AgentVaultCredentialType.Passthrough && (diff --git a/frontend/src/components/agent-vault/service-sheet/DetailsFields.tsx b/frontend/src/components/agent-vault/service-sheet/DetailsFields.tsxindex d35b9602fe..9d8e6c24b6 100644--- a/frontend/src/components/agent-vault/service-sheet/DetailsFields.tsx+++ b/frontend/src/components/agent-vault/service-sheet/DetailsFields.tsx@@ -1,19 +1,26 @@import { Controller, useFormContext } from "react-hook-form";+import { InfoIcon } from "lucide-react";import {+ Checkbox,Field,FieldContent,FieldDescription,FieldError,FieldLabel,Input,- TextArea+ TagsInput,+ Tooltip,+ TooltipContent,+ TooltipTrigger} from "@app/components/v3";+import { hostError } from "@app/helpers/agentVaultHostPattern";+import { pathPrefixError } from "@app/helpers/agentVaultPathPrefix";-import { TServiceForm } from "./serviceSchema";+import { HTTP_METHODS, isAllMethods, TServiceForm } from "./serviceSchema";export const DetailsFields = () => {- const { control } = useFormContext<TServiceForm>();+ const { control, trigger, clearErrors } = useFormContext<TServiceForm>();return (<div className="flex flex-col gap-5">@@ -34,25 +41,143 @@ export const DetailsFields = () => {<Controllercontrol={control}- name="hostPattern"+ name="hosts"render={({ field, fieldState }) => (<Field><FieldLabel>Hosts</FieldLabel><FieldContent>- <TextArea- {...field}- rows={3}- placeholder="api.datadoghq.com"- isError={Boolean(fieldState.error)}+ <Controller+ control={control}+ name="hostDraft"+ render={({ field: draft }) => (+ <TagsInput+ value={field.value}+ onValueChange={field.onChange}+ inputValue={draft.value}+ onInputValueChange={(next) => {+ draft.onChange(next);+ if (fieldState.error) clearErrors("hosts");+ }}+ validateTag={hostError}+ onValidationError={(reason) =>+ reason ? trigger("hosts") : clearErrors("hosts")+ }+ isError={Boolean(fieldState.error)}+ aria-label="Hosts"+ placeholder="api.datadoghq.com"+ />+ )}/><FieldDescription>- Separate multiple hosts with commas. Wildcards like *.example.com are allowed.+ The credential is only sent to these hosts. Wildcards like *.example.com are+ allowed.</FieldDescription>+ <FieldError+ errors={Array.isArray(fieldState.error) ? fieldState.error : [fieldState.error]}+ />+ </FieldContent>+ </Field>+ )}+ />++ <Controller+ control={control}+ name="methods"+ render={({ field, fieldState }) => (+ <Field>+ <FieldLabel>Methods</FieldLabel>+ <FieldContent>+ <Field orientation="horizontal">+ <Checkbox+ id="all-methods"+ isChecked={isAllMethods(field.value)}+ onCheckedChange={(checked) =>+ field.onChange(checked === true ? [...HTTP_METHODS] : [])+ }+ />+ <FieldLabel htmlFor="all-methods">All Methods</FieldLabel>+ </Field>++ <div+ role="group"+ aria-label="Methods"+ className="mt-2 ml-6 grid w-fit grid-cols-4 gap-x-8 gap-y-2"+ >+ {HTTP_METHODS.map((method) => (+ <Field key={method} orientation="horizontal" className="w-auto">+ <Checkbox+ id={`method-${method}`}+ isChecked={field.value.includes(method)}+ onCheckedChange={(checked) =>+ // Rebuilt from the canonical list so a rechecked method lands back in its+ // old slot rather than at the end.+ field.onChange(+ HTTP_METHODS.filter((candidate) =>+ candidate === method+ ? checked === true+ : field.value.includes(candidate)+ )+ )+ }+ />+ <FieldLabel htmlFor={`method-${method}`}>{method}</FieldLabel>+ </Field>+ ))}+ </div><FieldError>{fieldState.error?.message}</FieldError></FieldContent></Field>)}/>++ <Controller+ control={control}+ name="pathPrefixes"+ render={({ field, fieldState }) => (+ <Field>+ <FieldLabel>+ Paths+ <Tooltip>+ <TooltipTrigger asChild>+ <InfoIcon />+ </TooltipTrigger>+ <TooltipContent className="max-w-xs">+ The routes this service allows on its hosts. A prefix matches whole segments, so+ /api/v1 covers /api/v1/users but not /api/v10.+ </TooltipContent>+ </Tooltip>+ </FieldLabel>+ <FieldContent>+ <Controller+ control={control}+ name="pathDraft"+ render={({ field: draft }) => (+ <TagsInput+ value={field.value}+ onValueChange={field.onChange}+ inputValue={draft.value}+ onInputValueChange={(next) => {+ draft.onChange(next);+ if (fieldState.error) clearErrors("pathPrefixes");+ }}+ validateTag={pathPrefixError}+ onValidationError={(reason) =>+ reason ? trigger("pathPrefixes") : clearErrors("pathPrefixes")+ }+ isError={Boolean(fieldState.error)}+ aria-label="Path prefixes"+ placeholder="/api/v1"+ />+ )}+ />+ <FieldDescription>Leave empty to allow every path.</FieldDescription>+ <FieldError+ errors={Array.isArray(fieldState.error) ? fieldState.error : [fieldState.error]}+ />+ </FieldContent>+ </Field>+ )}+ /></div>);};diff --git a/frontend/src/components/agent-vault/service-sheet/ReviewFields.tsx b/frontend/src/components/agent-vault/service-sheet/ReviewFields.tsxindex ac738e1bc9..922a641d9f 100644--- a/frontend/src/components/agent-vault/service-sheet/ReviewFields.tsx+++ b/frontend/src/components/agent-vault/service-sheet/ReviewFields.tsx@@ -1,6 +1,7 @@import { useFormContext } from "react-hook-form";import {+ CodeBlock,Detail,DetailGroup,DetailGroupHeader,@@ -10,7 +11,27 @@ import {import { AgentVaultCredentialType } from "@app/hooks/api/agentVault";import { credentialPreview } from "./CredentialFields";-import { CREDENTIAL_LABELS, TServiceForm, UNCHANGED_SECRET } from "./serviceSchema";+import {+ CREDENTIAL_LABELS,+ isAllMethods,+ SURFACE_LABELS,+ TServiceForm,+ UNCHANGED_SECRET+} from "./serviceSchema";++const MASK = "\u2022".repeat(8);++const alignColumns = (rows: string[][]) => {+ const widths = rows[0].map((_, column) => Math.max(...rows.map((row) => row[column].length)));+ return rows+ .map((row) =>+ row+ .map((cell, column) => (column === row.length - 1 ? cell : cell.padEnd(widths[column])))+ .join(" ")+ .trimEnd()+ )+ .join("\n");+};type Props = {isUpdate: boolean;@@ -24,6 +45,20 @@ export const ReviewFields = ({ isUpdate }: Props) => {const secretLabel = isBasic ? "Password" : "Token";const sends = credentialPreview(form);+ const headerRows = form.customHeaders+ .filter((header) => header.name)+ .map((header) => [`${header.name}:`, header.prefix ? `${header.prefix} ${MASK}` : MASK]);++ const substitutionRows = form.substitutions+ .filter((substitution) => substitution.placeholder)+ .map((substitution) => [+ substitution.placeholder,+ `\u2192 ${MASK}`,+ substitution.surfaces.length+ ? `in ${substitution.surfaces.map((surface) => SURFACE_LABELS[surface]).join(", ")}`+ : ""+ ]);+const outcome = (value: string | undefined, canClear: boolean) => {if (!isUpdate) return value ? "Set" : "None";if (value === UNCHANGED_SECRET) return "Unchanged";@@ -42,7 +77,19 @@ export const ReviewFields = ({ isUpdate }: Props) => {</Detail><Detail><DetailLabel>Hosts</DetailLabel>- <DetailValue className="font-mono">{form.hostPattern}</DetailValue>+ <DetailValue>{form.hosts.join(", ")}</DetailValue>+ </Detail>+ <Detail>+ <DetailLabel>Methods</DetailLabel>+ <DetailValue>+ {isAllMethods(form.methods) ? "All" : form.methods.join(", ")}+ </DetailValue>+ </Detail>+ <Detail>+ <DetailLabel>Paths</DetailLabel>+ <DetailValue>+ {form.pathPrefixes.length ? form.pathPrefixes.join(", ") : "All"}+ </DetailValue></Detail></div></DetailGroup>@@ -57,7 +104,7 @@ export const ReviewFields = ({ isUpdate }: Props) => {{sends && (<Detail><DetailLabel>Sends</DetailLabel>- <DetailValue className="font-mono">{sends}</DetailValue>+ <DetailValue>{sends}</DetailValue></Detail>)}{isBasic && (@@ -73,6 +120,24 @@ export const ReviewFields = ({ isUpdate }: Props) => {</Detail>)}</div>+ {(headerRows.length > 0 || substitutionRows.length > 0) && (+ <div className="flex flex-col gap-3">+ {headerRows.length > 0 && (+ <CodeBlock+ label="Custom headers"+ isCopyable={false}+ value={alignColumns(headerRows)}+ />+ )}+ {substitutionRows.length > 0 && (+ <CodeBlock+ label="Substitutions"+ isCopyable={false}+ value={alignColumns(substitutionRows)}+ />+ )}+ </div>+ )}</DetailGroup></div>);diff --git a/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx b/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsxindex c9a71fc581..b35dde7082 100644--- a/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx+++ b/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx@@ -1,4 +1,4 @@-import { useEffect, useMemo, useState } from "react";+import { useEffect, useMemo, useRef, useState } from "react";import { FormProvider, useForm } from "react-hook-form";import { zodResolver } from "@hookform/resolvers/zod";import axios from "axios";@@ -19,6 +19,7 @@ import {StepperStep} from "@app/components/v3";import { ProviderIcon } from "@app/components/v3/platform/ProviderIcon";+import { hostError } from "@app/helpers/agentVaultHostPattern";import { AgentVaultTemplate } from "@app/helpers/agentVaultTemplates";import { useDiscardChangesGuard, useWizardSteps } from "@app/hooks";import {@@ -37,21 +38,30 @@ import { ReviewFields } from "./ReviewFields";import {buildServiceSchema,displayHostPattern,+ HTTP_METHODS,+ isAllMethods,SERVICE_STEP_FIELDS,ServiceStep,TServiceForm,UNCHANGED_SECRET} from "./serviceSchema";import { SERVICE_DOCS_URL, SERVICE_STEPS } from "./stepMeta";+import { ADVANCED_ITEM, TransformationsFields } from "./TransformationsFields";const BLANK_SERVICE_FORM: TServiceForm = {name: "",- hostPattern: "",- credentialType: AgentVaultCredentialType.Bearer,+ hosts: [],+ hostDraft: "",+ pathDraft: "",+ credentialType: AgentVaultCredentialType.Passthrough,headerName: "Authorization",headerPrefix: "Bearer",username: "",- secret: ""+ secret: "",+ methods: [...HTTP_METHODS],+ pathPrefixes: [],+ customHeaders: [],+ substitutions: []};type Props = {@@ -61,6 +71,11 @@ type Props = {service?: TAgentVaultService | null;};+// Long enough for the advanced section to open and settle. There is no event to wait on: the section+// is a Radix accordion, whose content is unmounted while closed, so the control cannot be measured+// until after it mounts and takes its height.+const SECTION_OPEN_MS = 250;+export const ServiceSheet = ({ isOpen, onOpenChange, accessBundleId, service }: Props) => {const isUpdate = Boolean(service);const createService = useCreateAgentVaultService();@@ -70,13 +85,16 @@ export const ServiceSheet = ({ isOpen, onOpenChange, accessBundleId, service }:const schema = useMemo(() => buildServiceSchema(service), [service]);- const formMethods = useForm<TServiceForm>({ resolver: zodResolver(schema) });+ const formMethods = useForm<TServiceForm>({+ defaultValues: BLANK_SERVICE_FORM,+ resolver: zodResolver(schema)+ });const {handleSubmit,reset,setError,trigger,- formState: { isDirty, isSubmitting }+ formState: { errors, isDirty, isSubmitting }} = formMethods;const { confirmDiscard, isDiscardDialogOpen, requestDiscard, setIsDiscardDialogOpen } =@@ -89,13 +107,42 @@ export const ServiceSheet = ({ isOpen, onOpenChange, accessBundleId, service }:);const stepKeys = useMemo(() => steps.map((meta) => meta.step), [steps]);+ const panelRef = useRef<HTMLDivElement>(null);+ const [openItem, setOpenItem] = useState(ADVANCED_ITEM);+ // The stand-in for formState.submitCount, which only counts handleSubmit and so never moves for a+ // wizard that gates its steps with trigger. Without it a second Continue reveals nothing, because+ // the errors it finds are the ones already there.+ const [blockedAttempt, setBlockedAttempt] = useState(0);+const { step, isLastStep, goBack, goNext, onFormInvalid, setStep } = useWizardSteps<ServiceStep>({stepKeys,stepFields: SERVICE_STEP_FIELDS,invalidMessage: "Fix the errors before saving.",- validateStep: (fields) => trigger(fields as (keyof TServiceForm)[])+ validateStep: async (fields) => {+ const isValid = await trigger(fields as (keyof TServiceForm)[]);+ if (!isValid) setBlockedAttempt((count) => count + 1);+ return isValid;+ }});+ const hasAdvancedError = Boolean(errors.customHeaders || errors.substitutions);++ useEffect(() => {+ if (hasAdvancedError) setOpenItem(ADVANCED_ITEM);+ }, [hasAdvancedError, blockedAttempt]);++ useEffect(() => {+ if (!blockedAttempt) return undefined;+ // Once the accordion has finished opening: a control inside it is neither mounted nor at its final+ // offset before then, so anything sooner scrolls to the wrong place or to nothing. The control+ // rather than its message, which arrives a render later and keeps its text once the error clears.+ const id = window.setTimeout(() => {+ const invalid = panelRef.current?.querySelector<HTMLElement>('[aria-invalid="true"]');+ (invalid?.closest('[data-slot="field"]') ?? invalid)?.scrollIntoView({ block: "nearest" });+ }, SECTION_OPEN_MS);+ return () => window.clearTimeout(id);+ }, [blockedAttempt]);+useEffect(() => {if (!isOpen) return;@@ -105,8 +152,9 @@ export const ServiceSheet = ({ isOpen, onOpenChange, accessBundleId, service }:if (service) {const { credential } = service;reset({+ ...BLANK_SERVICE_FORM,name: service.name,- hostPattern: displayHostPattern(service.hostPattern),+ hosts: displayHostPattern(service.hostPattern).split(", "),credentialType: credential.type,// Seeded even for a credential that has no header, so switching the type to Bearer starts from// the same defaults a new service gets. Left undefined, the submit would send an empty@@ -118,7 +166,22 @@ export const ServiceSheet = ({ isOpen, onOpenChange, accessBundleId, service }:headerPrefix:credential.type === AgentVaultCredentialType.Bearer ? credential.headerPrefix : "Bearer",username: credential.type === AgentVaultCredentialType.Basic ? UNCHANGED_SECRET : undefined,- secret: credential.type === AgentVaultCredentialType.Passthrough ? "" : UNCHANGED_SECRET+ secret: credential.type === AgentVaultCredentialType.Passthrough ? "" : UNCHANGED_SECRET,+ methods: service.allowedMethods ?? [...HTTP_METHODS],+ pathPrefixes: service.allowedPathPrefixes ?? [],+ // The stored values never come back, so each row carries the sentinel until it is retyped.+ customHeaders: service.customHeaders.map((header) => ({+ id: header.id,+ name: header.name,+ prefix: header.prefix,+ value: UNCHANGED_SECRET+ })),+ substitutions: service.substitutions.map((substitution) => ({+ id: substitution.id,+ placeholder: substitution.placeholder,+ surfaces: substitution.surfaces,+ value: UNCHANGED_SECRET+ }))});} else {reset(BLANK_SERVICE_FORM);@@ -130,10 +193,14 @@ export const ServiceSheet = ({ isOpen, onOpenChange, accessBundleId, service }:if (picked) {const cred = picked.credential;+ // A template placeholder like <your-tenant>.atlassian.net is not a host, so it goes into the draft.+ const parts = picked.hostPattern.split(",").map((host) => host.trim());+reset({...BLANK_SERVICE_FORM,name: picked.key,- hostPattern: picked.hostPattern,+ hosts: parts.filter((host) => !hostError(host, [])),+ hostDraft: parts.find((host) => Boolean(hostError(host, []))) ?? "",credentialType: cred.type,...(cred.type === AgentVaultCredentialType.Bearer && {headerName: cred.headerName ?? "Authorization",@@ -186,6 +253,26 @@ export const ServiceSheet = ({ isOpen, onOpenChange, accessBundleId, service }:};};+ const buildPolicy = (data: TServiceForm) => ({+ allowedMethods: isAllMethods(data.methods) ? null : data.methods,+ allowedPathPrefixes: data.pathPrefixes.length ? data.pathPrefixes : null+ });++ const buildTransformations = (data: TServiceForm) => ({+ customHeaders: data.customHeaders.map((header) => ({+ ...(header.id ? { id: header.id } : {}),+ name: header.name,+ prefix: header.prefix,+ ...(header.value === UNCHANGED_SECRET ? {} : { value: header.value })+ })),+ substitutions: data.substitutions.map((substitution) => ({+ ...(substitution.id ? { id: substitution.id } : {}),+ placeholder: substitution.placeholder,+ surfaces: substitution.surfaces,+ ...(substitution.value === UNCHANGED_SECRET ? {} : { value: substitution.value })+ }))+ });+const onSubmit = async (data: TServiceForm) => {try {if (service) {@@ -193,15 +280,19 @@ export const ServiceSheet = ({ isOpen, onOpenChange, accessBundleId, service }:accessBundleId,serviceId: service.id,name: data.name,- hostPattern: data.hostPattern,- credential: buildCredentialPatch(data)+ hostPattern: data.hosts.join(","),+ ...buildPolicy(data),+ credential: buildCredentialPatch(data),+ ...buildTransformations(data)});} else {await createService.mutateAsync({accessBundleId,name: data.name,- hostPattern: data.hostPattern,- credential: buildCredential(data)+ hostPattern: data.hosts.join(","),+ ...buildPolicy(data),+ credential: buildCredential(data),+ ...buildTransformations(data)});}@@ -220,23 +311,63 @@ export const ServiceSheet = ({ isOpen, onOpenChange, accessBundleId, service }:serverResponse?.error === ApiErrorTypes.BadRequestError &&serverResponse.message.includes("already covers")) {- setError("hostPattern", { type: "server", message: serverResponse.message });+ setError("hosts", { type: "server", message: serverResponse.message });setStep(stepKeys.indexOf(ServiceStep.Details));return;}+ // Thrown after the stored halves are merged in, so the form cannot have known: it is told which+ // halves exist only as "unchanged", never whether one of them is empty.+ if (+ serverResponse?.error === ApiErrorTypes.BadRequestError &&+ serverResponse.message.includes("needs a username")+ ) {+ setError("username", { type: "server", message: serverResponse.message });+ setStep(stepKeys.indexOf(ServiceStep.Credential));+ return;+ }+if (serverResponse?.error === ApiErrorTypes.ValidationError) {- const hostIssues = serverResponse.message.filter(- (issue) => issue.path[0] === "hostPattern"- );- if (hostIssues.length > 0) {- setError("hostPattern", {- type: "server",- message: hostIssues.map((issue) => issue.message).join(" ")- });- setStep(stepKeys.indexOf(ServiceStep.Details));- }- if (hostIssues.length < serverResponse.message.length) onRequestError(error);+ const STEP_OF_FIELD: Record<string, ServiceStep> = {+ name: ServiceStep.Details,+ hostPattern: ServiceStep.Details,+ allowedMethods: ServiceStep.Details,+ allowedPathPrefixes: ServiceStep.Details,+ credential: ServiceStep.Credential,+ customHeaders: ServiceStep.Credential,+ substitutions: ServiceStep.Credential+ };++ const FORM_FIELD_OF: Record<string, keyof TServiceForm> = {+ hostPattern: "hosts",+ allowedMethods: "methods",+ allowedPathPrefixes: "pathPrefixes",+ credential: "secret"+ };++ let earliestStep: number | null = null;+ let unmapped = false;++ serverResponse.message.forEach((issue) => {+ const root = String(issue.path[0]);+ const issueStep = STEP_OF_FIELD[root];+ if (!issueStep) {+ unmapped = true;+ return;+ }++ const target =+ issue.path.length > 1 && (root === "customHeaders" || root === "substitutions")+ ? (issue.path.join(".") as keyof TServiceForm)+ : (FORM_FIELD_OF[root] ?? (root as keyof TServiceForm));++ setError(target, { type: "server", message: issue.message });+ const index = stepKeys.indexOf(issueStep);+ if (index !== -1 && (earliestStep === null || index < earliestStep)) earliestStep = index;+ });++ if (earliestStep !== null) setStep(earliestStep);+ if (unmapped) onRequestError(error);return;}@@ -290,7 +421,7 @@ export const ServiceSheet = ({ isOpen, onOpenChange, accessBundleId, service }:requestDiscard();}}>- <SheetContent className="sm:max-w-6xl">+ <SheetContent className="flex h-full max-h-full w-screen flex-col gap-y-0 sm:max-w-[90vw] xl:max-w-7xl"><SheetHeader>{isTemplateStep ? (<>@@ -327,7 +458,12 @@ export const ServiceSheet = ({ isOpen, onOpenChange, accessBundleId, service }:<p className="mb-5 text-[11px] font-medium tracking-wider text-muted uppercase">Setup steps</p>- <Stepper activeStep={step} orientation="vertical" onStepChange={handleStepChange}>+ <Stepper+ activeStep={step}+ orientation="vertical"+ nonLinear={isUpdate}+ onStepChange={handleStepChange}+ ><StepperList>{steps.map((meta, index) => (<StepperStep@@ -341,7 +477,10 @@ export const ServiceSheet = ({ isOpen, onOpenChange, accessBundleId, service }:</Stepper></aside>- <div className="flex min-w-0 flex-1 flex-col overflow-y-auto px-8 py-6">+ <div+ ref={panelRef}+ className="flex min-w-0 flex-1 flex-col overflow-y-auto px-8 py-6"+ ><div className="mb-6"><h2 className="text-lg font-semibold text-foreground">{current.title}</h2><p className="mt-1 text-sm text-muted">{current.subtitle}</p>@@ -349,7 +488,10 @@ export const ServiceSheet = ({ isOpen, onOpenChange, accessBundleId, service }:{current.step === ServiceStep.Details && <DetailsFields />}{current.step === ServiceStep.Credential && (- <CredentialFields storedType={service?.credential.type} />+ <div className="flex flex-col gap-5">+ <CredentialFields storedType={service?.credential.type} />+ <TransformationsFields openItem={openItem} onOpenChange={setOpenItem} />+ </div>)}{current.step === ServiceStep.Review && <ReviewFields isUpdate={isUpdate} />}</div>diff --git a/frontend/src/components/agent-vault/service-sheet/SubstitutionExample.tsx b/frontend/src/components/agent-vault/service-sheet/SubstitutionExample.tsxnew file mode 100644index 0000000000..6b066fddc3--- /dev/null+++ b/frontend/src/components/agent-vault/service-sheet/SubstitutionExample.tsx@@ -0,0 +1,57 @@+import { ArrowDownIcon } from "lucide-react";++const PLACEHOLDER = "__API_TOKEN__";+const REAL_VALUE = "sk_live_••••4f2a";++const Token = ({ children, isResolved }: { children: string; isResolved?: boolean }) => (+ <span+ className={`rounded-xs px-1 ${+ isResolved ? "bg-success/10 text-success" : "bg-foreground/10 text-foreground"+ }`}+ >+ {children}+ </span>+);++const Wire = ({+ title,+ isResolved,+ token+}: {+ title: string;+ isResolved?: boolean;+ token: string;+}) => (+ <div className="overflow-hidden rounded-md border border-border">+ <div className="flex items-center gap-1.5 border-b border-border bg-container px-2.5 py-1.5 font-mono text-[10px] text-muted">+ {title}+ </div>+ <div className="flex flex-col gap-1 px-2.5 py-2 font-mono text-[11px] break-all text-foreground">+ <p>+ GET /v1/keys/+ <Token isResolved={isResolved}>{token}</Token>+ </p>+ <p>+ Authorization: Bearer <Token isResolved={isResolved}>{token}</Token>+ </p>+ </div>+ </div>+);++export const SubstitutionExample = () => (+ <div className="flex flex-col gap-2">+ <p className="text-xs text-foreground">+ Where should the placeholder be swapped for the real value?+ </p>+ <Wire title="Agent sends" token={PLACEHOLDER} />+ <p className="flex items-center gap-1.5 text-[11px] text-muted">+ <ArrowDownIcon className="size-3 shrink-0" />+ Infisical substitutes in the parts you select+ </p>+ <Wire title="Service receives" token={REAL_VALUE} isResolved />+ <p className="text-[11px] text-muted">+ This example needs <span className="text-foreground">URL Path</span> and{" "}+ <span className="text-foreground">Headers</span>.+ </p>+ </div>+);diff --git a/frontend/src/components/agent-vault/service-sheet/TransformationsFields.tsx b/frontend/src/components/agent-vault/service-sheet/TransformationsFields.tsxnew file mode 100644index 0000000000..cb6f061d3c--- /dev/null+++ b/frontend/src/components/agent-vault/service-sheet/TransformationsFields.tsx@@ -0,0 +1,339 @@+import { Controller, useFieldArray, useFormContext } from "react-hook-form";+import { InfoIcon, PlusIcon, TrashIcon } from "lucide-react";++import {+ Accordion,+ AccordionContent,+ AccordionItem,+ AccordionTrigger,+ Button,+ Checkbox,+ CopyButton,+ Field,+ FieldContent,+ FieldError,+ FieldLabel,+ HoverCard,+ HoverCardContent,+ HoverCardTrigger,+ IconButton,+ Input,+ InputGroup,+ InputGroupAddon,+ InputGroupInput+} from "@app/components/v3";+import { AgentVaultSubstitutionSurface } from "@app/hooks/api/agentVault";++import { SecretInput } from "./CredentialFields";+import {+ MAX_CUSTOM_HEADERS,+ MAX_SUBSTITUTIONS,+ SURFACE_LABELS,+ TServiceForm,+ UNCHANGED_SECRET+} from "./serviceSchema";+import { SubstitutionExample } from "./SubstitutionExample";++export const ADVANCED_ITEM = "advanced-options";++const SURFACES = Object.values(AgentVaultSubstitutionSurface);++const RemoveRowButton = ({+ ariaLabel,+ hasLabelRow,+ onClick+}: {+ ariaLabel: string;+ hasLabelRow: boolean;+ onClick: () => void;+}) => (+ <div className="flex flex-col gap-0.5">+ {hasLabelRow && (+ <FieldLabel className="pointer-events-none invisible text-xs select-none" aria-hidden>+ + </FieldLabel>+ )}+ <div className="flex h-9 items-center">+ <IconButton+ aria-label={ariaLabel}+ variant="ghost"+ size="xs"+ className="hover:text-danger"+ onClick={onClick}+ >+ <TrashIcon className="size-4" />+ </IconButton>+ </div>+ </div>+);++export const TransformationsFields = ({+ openItem,+ onOpenChange+}: {+ openItem: string;+ onOpenChange: (item: string) => void;+}) => {+ const { control, getValues } = useFormContext<TServiceForm>();+ const customHeaders = useFieldArray({ control, name: "customHeaders" });+ const substitutions = useFieldArray({ control, name: "substitutions" });++ return (+ <Accordion+ type="single"+ collapsible+ variant="ghost"+ value={openItem}+ onValueChange={onOpenChange}+ >+ <AccordionItem value={ADVANCED_ITEM}>+ <AccordionTrigger>Advanced Options</AccordionTrigger>+ <AccordionContent>+ <div className="flex flex-col gap-5">+ <div className="flex flex-col gap-3">+ <div>+ <p className="text-sm font-medium">Custom headers</p>+ <p className="mt-1 text-xs text-muted">+ Added to every request to this service, on top of the credential.+ </p>+ </div>+ {customHeaders.fields.length > 0 && (+ <div className="flex flex-col gap-3 rounded-md border border-border bg-container/50 p-4">+ {customHeaders.fields.map((row, index) => (+ <div key={row.id} className="flex items-start gap-3">+ <Controller+ control={control}+ name={`customHeaders.${index}.name`}+ render={({ field, fieldState }) => (+ <Field className="flex-1">+ <FieldContent>+ {index === 0 && <FieldLabel className="text-xs">Name</FieldLabel>}+ <Input+ {...field}+ aria-label="Header name"+ placeholder="X-Org-Id"+ isError={Boolean(fieldState.error)}+ />+ <FieldError>{fieldState.error?.message}</FieldError>+ </FieldContent>+ </Field>+ )}+ />+ <Controller+ control={control}+ name={`customHeaders.${index}.prefix`}+ render={({ field, fieldState }) => (+ <Field className="w-28">+ <FieldContent>+ {index === 0 && <FieldLabel className="text-xs">Prefix</FieldLabel>}+ <Input+ {...field}+ aria-label="Header prefix"+ placeholder="Token"+ isError={Boolean(fieldState.error)}+ />+ <FieldError>{fieldState.error?.message}</FieldError>+ </FieldContent>+ </Field>+ )}+ />+ <Controller+ control={control}+ name={`customHeaders.${index}.value`}+ render={({ field, fieldState }) => (+ <Field className="flex-1">+ <FieldContent>+ {index === 0 && <FieldLabel className="text-xs">Value</FieldLabel>}+ <SecretInput+ field={field}+ label="Header value"+ ariaLabel="Header value"+ placeholder="Enter the value"+ isError={Boolean(fieldState.error)}+ isUntouched={field.value === UNCHANGED_SECRET}+ hasStoredSecret={Boolean(getValues(`customHeaders.${index}.id`))}+ canBeCleared={false}+ />+ <FieldError>{fieldState.error?.message}</FieldError>+ </FieldContent>+ </Field>+ )}+ />+ <RemoveRowButton+ ariaLabel={`Remove header ${index + 1}`}+ hasLabelRow={index === 0}+ onClick={() => customHeaders.remove(index)}+ />+ </div>+ ))}+ </div>+ )}++ {customHeaders.fields.length < MAX_CUSTOM_HEADERS && (+ <Button+ variant="ghost"+ size="xs"+ className="self-start"+ onClick={() => customHeaders.append({ name: "", prefix: "", value: "" })}+ >+ <PlusIcon className="mr-1 size-4" />+ Add Custom Header+ </Button>+ )}++ <Controller+ control={control}+ name="customHeaders"+ render={({ fieldState }) => <FieldError>{fieldState.error?.message}</FieldError>}+ />+ </div>++ <div className="flex flex-col gap-3">+ <div>+ <p className="text-sm font-medium">Substitutions</p>+ <p className="mt-1 text-xs text-muted">+ Your agent sends a placeholder. The proxy swaps it for the real value before+ forwarding.+ </p>+ </div>+ <div className="flex flex-col gap-3">+ {substitutions.fields.map((row, index) => (+ <div+ key={row.id}+ className="flex flex-col gap-3 rounded-md border border-border bg-container/50 p-4"+ >+ <div className="flex items-start gap-2">+ <Controller+ control={control}+ name={`substitutions.${index}.placeholder`}+ render={({ field, fieldState }) => (+ <Field className="flex-1">+ <FieldContent>+ <FieldLabel className="text-xs">Replace</FieldLabel>+ <InputGroup>+ <InputGroupInput+ {...field}+ aria-label="Placeholder"+ placeholder="__API_TOKEN__"+ isError={Boolean(fieldState.error)}+ />+ {Boolean(field.value) && (+ <InputGroupAddon align="inline-end">+ <CopyButton+ value={field.value}+ ariaLabel="Copy placeholder"+ size="xs"+ />+ </InputGroupAddon>+ )}+ </InputGroup>+ <FieldError>{fieldState.error?.message}</FieldError>+ </FieldContent>+ </Field>+ )}+ />+ <Controller+ control={control}+ name={`substitutions.${index}.value`}+ render={({ field, fieldState }) => (+ <Field className="flex-1">+ <FieldContent>+ <FieldLabel className="text-xs">With</FieldLabel>+ <SecretInput+ field={field}+ label="Substitution value"+ ariaLabel="Substitution value"+ placeholder="Enter the real value"+ isError={Boolean(fieldState.error)}+ isUntouched={field.value === UNCHANGED_SECRET}+ hasStoredSecret={Boolean(getValues(`substitutions.${index}.id`))}+ canBeCleared={false}+ />+ <FieldError>{fieldState.error?.message}</FieldError>+ </FieldContent>+ </Field>+ )}+ />+ <RemoveRowButton+ ariaLabel={`Remove substitution ${index + 1}`}+ hasLabelRow+ onClick={() => substitutions.remove(index)}+ />+ </div>++ <Controller+ control={control}+ name={`substitutions.${index}.surfaces`}+ render={({ field, fieldState }) => (+ <Field>+ <FieldContent>+ <FieldLabel className="text-xs">+ Replace In+ <HoverCard openDelay={200} closeDelay={150}>+ <HoverCardTrigger asChild>+ <InfoIcon />+ </HoverCardTrigger>+ <HoverCardContent className="w-96" side="top" align="start">+ <SubstitutionExample />+ </HoverCardContent>+ </HoverCard>+ </FieldLabel>+ <div className="mt-2 flex flex-wrap gap-x-5 gap-y-2">+ {SURFACES.map((surface) => (+ <Field key={surface} orientation="horizontal" className="w-auto">+ <Checkbox+ id={`surface-${index}-${surface}`}+ isChecked={field.value.includes(surface)}+ onCheckedChange={(checked) =>+ field.onChange(+ checked === true+ ? [...field.value, surface]+ : field.value.filter((value) => value !== surface)+ )+ }+ />+ <FieldLabel htmlFor={`surface-${index}-${surface}`}>+ {SURFACE_LABELS[surface]}+ </FieldLabel>+ </Field>+ ))}+ </div>+ <FieldError>{fieldState.error?.message}</FieldError>+ </FieldContent>+ </Field>+ )}+ />+ </div>+ ))}++ {substitutions.fields.length < MAX_SUBSTITUTIONS && (+ <Button+ variant="ghost"+ size="xs"+ className="self-start"+ onClick={() =>+ substitutions.append({+ placeholder: "",+ value: "",+ surfaces: [AgentVaultSubstitutionSurface.Header]+ })+ }+ >+ <PlusIcon className="mr-1 size-4" />+ Add Substitution+ </Button>+ )}++ <Controller+ control={control}+ name="substitutions"+ render={({ fieldState }) => <FieldError>{fieldState.error?.message}</FieldError>}+ />+ </div>+ </div>+ </div>+ </AccordionContent>+ </AccordionItem>+ </Accordion>+ );+};diff --git a/frontend/src/components/agent-vault/service-sheet/serviceSchema.ts b/frontend/src/components/agent-vault/service-sheet/serviceSchema.tsindex 9b1d81a906..4c2e525bb6 100644--- a/frontend/src/components/agent-vault/service-sheet/serviceSchema.ts+++ b/frontend/src/components/agent-vault/service-sheet/serviceSchema.ts@@ -1,7 +1,12 @@import { z } from "zod";-import { addHostListIssues } from "@app/helpers/agentVaultHostPattern";-import { AgentVaultCredentialType } from "@app/hooks/api/agentVault";+import { addHostIssues, hostError } from "@app/helpers/agentVaultHostPattern";+import { addPathPrefixIssues, pathPrefixError } from "@app/helpers/agentVaultPathPrefix";+import {+ AgentVaultCredentialType,+ AgentVaultHttpMethod,+ AgentVaultSubstitutionSurface+} from "@app/hooks/api/agentVault";import { TAgentVaultService } from "@app/hooks/api/agentVault/types";import { slugSchema } from "@app/lib/schemas";@@ -24,6 +29,52 @@ export const CREDENTIAL_LABELS: Record<AgentVaultCredentialType, string> = {[AgentVaultCredentialType.Passthrough]: "Pass-through"};+export const HTTP_METHODS = Object.values(AgentVaultHttpMethod);++/** Every method selected is stored as allowedMethods: null, so "All" is a view of the list, not a flag beside it. */+export const isAllMethods = (methods: AgentVaultHttpMethod[]) =>+ methods.length === HTTP_METHODS.length;++// Mirrors AGENT_VAULT_MAX_CUSTOM_HEADERS / AGENT_VAULT_MAX_SUBSTITUTIONS / AGENT_VAULT_MAX_PATH_PREFIXES on the+// backend. Without these the only thing enforcing the cap is the server, and its rejection names an array+// root that no field renders.+export const MAX_CUSTOM_HEADERS = 20;+export const MAX_SUBSTITUTIONS = 20;+export const MAX_PATH_PREFIXES = 20;++// The column holds every host as one comma-joined string, so this caps the join, not any single host.+const AGENT_VAULT_MAX_HOST_PATTERN_LENGTH = 1024;++export const SURFACE_LABELS: Record<AgentVaultSubstitutionSurface, string> = {+ [AgentVaultSubstitutionSurface.Path]: "URL Path",+ [AgentVaultSubstitutionSurface.Query]: "Query String",+ [AgentVaultSubstitutionSurface.Header]: "Headers",+ [AgentVaultSubstitutionSurface.Body]: "Body"+};++// Mirrors AGENT_VAULT_NO_CONTROL_CHARS_RE on the backend. A pasted key with a trailing newline is the+// common case, and it saves fine but then makes Go refuse to send the header.+// eslint-disable-next-line no-control-regex+const NO_CONTROL_CHARS_RE = /^[^\x00-\x1f\x7f]*$/;++const CONTROL_CHARS_MESSAGE =+ "This can't contain line breaks or other control characters. Check for a stray newline if you pasted it.";++// Set by the proxy on every request, so naming one here would either be dropped or corrupt the request.+const RESERVED_HEADER_NAMES = new Set([+ "host",+ "content-length",+ "transfer-encoding",+ "connection",+ "proxy-connection",+ "upgrade",+ "te",+ "trailer",+ "keep-alive",+ "proxy-authenticate",+ "proxy-authorization"+]);+export enum ServiceStep {Template = "template",Details = "details",@@ -33,8 +84,16 @@ export enum ServiceStep {export const SERVICE_STEP_FIELDS: Record<ServiceStep, string[]> = {[ServiceStep.Template]: [],- [ServiceStep.Details]: ["name", "hostPattern"],- [ServiceStep.Credential]: ["credentialType", "headerName", "headerPrefix", "username", "secret"],+ [ServiceStep.Details]: ["name", "hosts", "hostDraft", "methods", "pathPrefixes", "pathDraft"],+ [ServiceStep.Credential]: [+ "credentialType",+ "headerName",+ "headerPrefix",+ "username",+ "secret",+ "customHeaders",+ "substitutions"+ ],[ServiceStep.Review]: []};@@ -42,7 +101,11 @@ export const buildServiceSchema = (service?: TAgentVaultService | null) =>z.object({name: slugSchema({ max: 64, field: "Name" }),- hostPattern: z.string().trim().min(1, "Required").max(1024).superRefine(addHostListIssues),+ hosts: z.array(z.string()),+ // In the form rather than component state so the resolver sees it: trigger() wipes anything set with+ // setError, so a refusal held outside the form would let the step advance.+ hostDraft: z.string(),+ pathDraft: z.string(),credentialType: z.nativeEnum(AgentVaultCredentialType),headerName: z.string()@@ -55,9 +118,157 @@ export const buildServiceSchema = (service?: TAgentVaultService | null) =>.optional(),headerPrefix: z.string().trim().max(64).optional(),username: z.string().trim().max(256).optional(),- secret: z.string().max(8192).optional()+ secret: z.string().max(8192).optional(),+ methods: z.array(z.nativeEnum(AgentVaultHttpMethod)),+ pathPrefixes: z+ .array(z.string())+ .max(MAX_PATH_PREFIXES, `You can add at most ${MAX_PATH_PREFIXES} path prefixes.`),+ customHeaders: z+ .array(+ z.object({+ id: z.string().optional(),+ name: z.string().trim().max(128),+ prefix: z.string().trim().max(64),+ value: z.string().max(8192)+ })+ )+ .max(MAX_CUSTOM_HEADERS, `You can add at most ${MAX_CUSTOM_HEADERS} custom headers.`),+ substitutions: z+ .array(+ z.object({+ id: z.string().optional(),+ placeholder: z.string().trim().max(255),+ value: z.string().max(8192),+ surfaces: z.array(z.nativeEnum(AgentVaultSubstitutionSurface))+ })+ )+ .max(MAX_SUBSTITUTIONS, `You can add at most ${MAX_SUBSTITUTIONS} substitutions.`)}).superRefine((data, ctx) => {+ addHostIssues(data.hosts, ctx, ["hosts"]);+ const hostDraft = data.hostDraft.trim();+ if (hostDraft) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["hosts"],+ message: hostError(hostDraft, data.hosts) ?? `Add "${hostDraft}" or clear it.`+ });+ } else if (data.hosts.length === 0) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["hosts"],+ message: "Add at least one host."+ });+ }++ const pathDraft = data.pathDraft.trim();+ if (pathDraft) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["pathPrefixes"],+ message:+ pathPrefixError(pathDraft, data.pathPrefixes) ?? `Add "${pathDraft}" or clear it.`+ });+ }+ if (data.hosts.join(",").length > AGENT_VAULT_MAX_HOST_PATTERN_LENGTH) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["hosts"],+ message: `These hosts come to more than ${AGENT_VAULT_MAX_HOST_PATTERN_LENGTH} characters together. Remove a few.`+ });+ }++ if (data.methods.length === 0) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["methods"],+ message: "Select at least one method."+ });+ }++ addPathPrefixIssues(data.pathPrefixes, ctx, ["pathPrefixes"]);++ let credentialHeader: string | null = null;+ if (data.credentialType === AgentVaultCredentialType.Bearer) {+ credentialHeader = data.headerName || "Authorization";+ } else if (data.credentialType === AgentVaultCredentialType.Basic) {+ credentialHeader = "Authorization";+ }++ // Basic always writes Authorization, which is not reserved, so only bearer can name one.+ if (+ data.credentialType === AgentVaultCredentialType.Bearer &&+ data.headerName &&+ RESERVED_HEADER_NAMES.has(data.headerName.toLowerCase())+ ) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["headerName"],+ message: "This header is set by the proxy and can't be overridden."+ });+ }++ const seenHeaders = new Set<string>();+ data.customHeaders.forEach((header, index) => {+ const at = (field: string, message: string) =>+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["customHeaders", index, field],+ message+ });++ if (!header.name) {+ at("name", "Required");+ } else if (!/^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/.test(header.name)) {+ at(+ "name",+ "A header name can't contain spaces or colons. Use letters, digits and dashes."+ );+ } else if (RESERVED_HEADER_NAMES.has(header.name.toLowerCase())) {+ at("name", "This header is set by the proxy and can't be overridden.");+ } else if (+ credentialHeader &&+ header.name.toLowerCase() === credentialHeader.toLowerCase()+ ) {+ at("name", `The ${credentialHeader} header is already set by the credential.`);+ } else if (seenHeaders.has(header.name.toLowerCase())) {+ at("name", "This header is listed twice.");+ }+ seenHeaders.add(header.name.toLowerCase());++ if (!header.value) at("value", "Required");+ else if (!NO_CONTROL_CHARS_RE.test(header.value)) at("value", CONTROL_CHARS_MESSAGE);++ if (header.prefix && !NO_CONTROL_CHARS_RE.test(header.prefix)) {+ at("prefix", CONTROL_CHARS_MESSAGE);+ }+ });++ const seenPlaceholders = new Set<string>();+ data.substitutions.forEach((substitution, index) => {+ const at = (field: string, message: string) =>+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["substitutions", index, field],+ message+ });++ if (!substitution.placeholder) {+ at("placeholder", "Required");+ } else if (!NO_CONTROL_CHARS_RE.test(substitution.placeholder)) {+ at("placeholder", CONTROL_CHARS_MESSAGE);+ } else if (seenPlaceholders.has(substitution.placeholder)) {+ at("placeholder", "This placeholder is listed twice.");+ }+ seenPlaceholders.add(substitution.placeholder);++ if (!substitution.value) at("value", "Required");+ else if (!NO_CONTROL_CHARS_RE.test(substitution.value)) at("value", CONTROL_CHARS_MESSAGE);+ if (substitution.surfaces.length === 0) {+ at("surfaces", "Pick at least one place to look for the placeholder.");+ }+ });+if (data.credentialType === AgentVaultCredentialType.Passthrough) return;const isUnchanged = data.secret === UNCHANGED_SECRET;diff --git a/frontend/src/components/agent-vault/service-sheet/stepMeta.ts b/frontend/src/components/agent-vault/service-sheet/stepMeta.tsindex 568b2f7534..db193c5f55 100644--- a/frontend/src/components/agent-vault/service-sheet/stepMeta.ts+++ b/frontend/src/components/agent-vault/service-sheet/stepMeta.ts@@ -2,7 +2,7 @@ import { AgentVaultDocsUrls } from "@app/pages/agent-vault/agent-vault-docs-urlsimport { ServiceStep } from "./serviceSchema";-export const SERVICE_DOCS_URL = AgentVaultDocsUrls.accessBundles;+export const SERVICE_DOCS_URL = AgentVaultDocsUrls.services;type StepMeta = {step: ServiceStep;@@ -22,21 +22,22 @@ export const SERVICE_STEPS: StepMeta[] = [{step: ServiceStep.Details,name: "Details",- shortDescription: "Name and hosts",+ shortDescription: "Name, hosts and rules",title: "Details",- subtitle: "What this service is called, and the hosts it covers.",+ subtitle: "What this service is called, the hosts it covers, and the requests it allows.",rightLabel: "DETAILS",rightDescription:- "The proxy only attaches the credential to requests that reach the hosts you list here."+ "The proxy only attaches the credential to requests that reach the hosts you list here. Every path is allowed unless you name the ones you want."},{step: ServiceStep.Credential,name: "Credential",shortDescription: "How to authenticate",title: "Credential",- subtitle: "How requests to this service are authenticated.",+ subtitle: "How requests to this service are authenticated, and anything else to add to them.",rightLabel: "CREDENTIAL",- rightDescription: "Agents reach this service without ever holding the credential themselves."+ rightDescription:+ "Agents reach this service without ever holding the credential themselves. Custom headers go out on top of it, and a substitution swaps a placeholder your agent already sends for the real value."},{step: ServiceStep.Review,diff --git a/frontend/src/components/v3/generic/Combobox/Combobox.tsx b/frontend/src/components/v3/generic/Combobox/Combobox.tsxindex 19426cc0fa..972f6423b8 100644--- a/frontend/src/components/v3/generic/Combobox/Combobox.tsx+++ b/frontend/src/components/v3/generic/Combobox/Combobox.tsx@@ -5,6 +5,14 @@ import { CheckIcon, ChevronDownIcon, Loader2Icon, XIcon } from "lucide-react";import { cn } from "../../utils";import { useScrollEdges } from "../../utils/useScrollEdges";import { getComboboxInputAriaLabel } from "./combobox-accessibility";+import {+ COMBOBOX_CHIP_CLASS,+ COMBOBOX_CHIP_LABEL_CLASS,+ COMBOBOX_CHIP_REMOVE_CLASS,+ COMBOBOX_CHIPS_CLASS,+ COMBOBOX_CHIPS_INPUT_CLASS,+ comboboxChipsViewportClass+} from "./combobox-chips";import { mergeComboboxItems } from "./combobox-items";import "../../utils/ScrollEdgeFade.css";@@ -755,19 +763,14 @@ const MultipleCombobox = <TOption,>({data-disabled={isDisabled ? "" : undefined}data-invalid={isError}className={cn(- "flex min-h-9 w-full gap-1 rounded-md border border-border bg-transparent text-sm text-foreground transition-[color,box-shadow] outline-none",+ COMBOBOX_CHIPS_CLASS,singleLine ? "items-center" : "items-start",- "focus-within:border-ring focus-within:ring-[3px] focus-within:ring-ring/50 hover:border-foreground/20",- "data-[disabled]:pointer-events-none data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50 data-[invalid=true]:border-danger data-[invalid=true]:ring-danger/40",value.length > 0 ? "p-1" : "py-1 pr-2 pl-2.5",className)}><div- className={cn(- "scroll-edge-fade flex thin-scrollbar min-w-0 flex-1 items-center gap-1",- singleLine ? "overflow-x-auto" : "max-h-24 flex-wrap overflow-y-auto"- )}+ className={comboboxChipsViewportClass(singleLine)}ref={setViewportRef}data-scroll-edge-axis={singleLine ? "horizontal" : "vertical"}data-scrollable-start={scrollEdges.start}@@ -781,13 +784,15 @@ const MultipleCombobox = <TOption,>({return (<ComboboxPrimitive.Chipkey={getOptionValue(option)}- className="flex h-6.5 max-w-full items-center gap-1 rounded-sm bg-foreground/10 px-1.5 text-xs text-foreground outline-none focus:ring-2 focus:ring-ring"+ className={COMBOBOX_CHIP_CLASS}>- <span className="max-w-48 truncate">{renderValue?.(option) ?? label}</span>+ <span className={COMBOBOX_CHIP_LABEL_CLASS}>+ {renderValue?.(option) ?? label}+ </span>{!isDisabled && (<ComboboxPrimitive.ChipRemovearia-label={`Remove ${label}`}- className="flex size-4 shrink-0 items-center justify-center rounded-xs text-muted outline-none hover:bg-foreground/10 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"+ className={COMBOBOX_CHIP_REMOVE_CLASS}><XIcon className="size-3" /></ComboboxPrimitive.ChipRemove>@@ -815,7 +820,7 @@ const MultipleCombobox = <TOption,>({onKeyDown?.(event);preventComboboxFormSubmit(event);}}- className="h-6 min-w-24 flex-1 bg-transparent px-0.5 text-sm text-foreground outline-none placeholder:text-muted"+ className={COMBOBOX_CHIPS_INPUT_CLASS}{...inputProps}/></div>diff --git a/frontend/src/components/v3/generic/Combobox/combobox-chips.ts b/frontend/src/components/v3/generic/Combobox/combobox-chips.tsnew file mode 100644index 0000000000..fb9d960b13--- /dev/null+++ b/frontend/src/components/v3/generic/Combobox/combobox-chips.ts@@ -0,0 +1,29 @@+/**+ * The chips-field shell, shared by `Combobox`'s multiple mode and `TagsInput`. Both are built from the same+ * Base UI parts, so the two drift apart the moment these strings live in two files. Per-consumer layout, the+ * container padding, stays at the call site.+ */++export const COMBOBOX_CHIPS_CLASS = [+ "flex min-h-9 w-full gap-1 rounded-md border border-border bg-transparent text-sm text-foreground transition-[color,box-shadow] outline-none",+ "focus-within:border-ring focus-within:ring-[3px] focus-within:ring-ring/50 hover:border-foreground/20",+ "data-[disabled]:pointer-events-none data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50 data-[invalid=true]:border-danger data-[invalid=true]:ring-danger/40"+].join(" ");++/** Scrolls sideways when the chips stay on one line, and wraps to a capped height otherwise. */+export const comboboxChipsViewportClass = (singleLine?: boolean) =>+ [+ "scroll-edge-fade flex thin-scrollbar min-w-0 flex-1 items-center gap-1",+ singleLine ? "overflow-x-auto" : "max-h-24 flex-wrap overflow-y-auto"+ ].join(" ");++export const COMBOBOX_CHIP_CLASS =+ "flex h-6.5 max-w-full items-center gap-1 rounded-sm bg-foreground/10 px-1.5 text-xs text-foreground outline-none focus:ring-2 focus:ring-ring";++export const COMBOBOX_CHIP_LABEL_CLASS = "max-w-48 truncate";++export const COMBOBOX_CHIP_REMOVE_CLASS =+ "flex size-4 shrink-0 items-center justify-center rounded-xs text-muted outline-none hover:bg-foreground/10 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring";++export const COMBOBOX_CHIPS_INPUT_CLASS =+ "h-6 min-w-24 flex-1 bg-transparent px-0.5 text-sm text-foreground outline-none placeholder:text-muted";diff --git a/frontend/src/components/v3/generic/TagsInput/TagsInput.stories.tsx b/frontend/src/components/v3/generic/TagsInput/TagsInput.stories.tsxnew file mode 100644index 0000000000..ebc816ac6b--- /dev/null+++ b/frontend/src/components/v3/generic/TagsInput/TagsInput.stories.tsx@@ -0,0 +1,321 @@+import { useState } from "react";+import type { Meta, StoryObj } from "@storybook/react-vite";+import { expect, userEvent, within } from "storybook/test";++import { Field, FieldDescription, FieldError, FieldLabel } from "../Field";+import { TagsInput, type TagsInputProps } from "./TagsInput";++const LANGUAGES = ["typescript", "go", "rust"];++/**+ * `TagsInput` collects a list of free-text values as removable chips. It reuses the+ * `Combobox` chip styling so a tag looks the same wherever it appears, but renders no+ * popup: there is nothing to pick from, only what the user types.+ *+ * Enter, a comma or a space commits the draft, and pasting splits on any of those plus+ * newlines, so a list copied from somewhere else arrives as separate tags. Blur commits+ * whatever is left in the box, so a value typed and never confirmed is not lost.+ *+ * Tags are keyed by their text, which means `validateTag` has to refuse duplicates or the+ * list cannot render. Compose with `Field` / `FieldLabel` / `FieldError` for labels and+ * validation text rather than laying that out here.+ */+const meta = {+ title: "Generic/TagsInput",+ component: TagsInput,+ parameters: {+ layout: "centered"+ },+ tags: ["autodocs"],+ argTypes: {+ isError: { control: "boolean" },+ isDisabled: { control: "boolean" },+ placeholder: { control: "text" },+ value: { table: { disable: true } },+ className: { table: { disable: true } }+ },+ args: {+ onValueChange: () => undefined+ },+ decorators: [+ (Story) => (+ <div className="w-80">+ <Story />+ </div>+ )+ ],+ globals: {+ backgrounds: { value: "card" }+ }+} satisfies Meta<typeof TagsInput>;++export default meta;+type Story = StoryObj;++const DefaultRender = ({ isDisabled, isError, placeholder }: Partial<TagsInputProps>) => {+ const [value, setValue] = useState<string[]>(LANGUAGES);++ return (+ <Field+ data-disabled={isDisabled ? "true" : undefined}+ data-invalid={isError ? "true" : undefined}+ >+ <FieldLabel htmlFor="tags-input-default">Languages</FieldLabel>+ <TagsInput+ id="tags-input-default"+ value={value}+ onValueChange={setValue}+ isDisabled={isDisabled}+ isError={isError}+ placeholder={placeholder}+ />+ <FieldDescription>Press Enter, comma or space to add one.</FieldDescription>+ </Field>+ );+};++/** The Controls panel drives this one, so `isDisabled`, `isError` and the placeholder are live. */+export const Default: Story = {+ args: {+ isDisabled: false,+ isError: false,+ placeholder: "Add a language"+ },+ render: (args) => <DefaultRender {...args} />+};++const EmptyRender = () => {+ const [value, setValue] = useState<string[]>([]);++ return (+ <Field>+ <FieldLabel htmlFor="tags-input-empty">Labels</FieldLabel>+ <TagsInput+ id="tags-input-empty"+ value={value}+ onValueChange={setValue}+ placeholder="Add a label"+ />+ </Field>+ );+};++/**+ * With no tags the control is a plain text box and the placeholder shows. It only starts+ * looking like a chip field once something has been committed.+ */+export const Empty: Story = {+ render: () => <EmptyRender />+};++const PasteRender = () => {+ const [value, setValue] = useState<string[]>([]);++ return (+ <Field>+ <FieldLabel htmlFor="tags-input-paste">Ingredients</FieldLabel>+ <TagsInput+ id="tags-input-paste"+ value={value}+ onValueChange={setValue}+ placeholder="Paste a list"+ />+ </Field>+ );+};++/**+ * A pasted list is split on commas, spaces and newlines, so a column copied out of a+ * spreadsheet and a comma separated line both arrive as separate tags.+ */+export const Paste: Story = {+ name: "Example: Paste a List",+ render: () => <PasteRender />,+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const input = canvas.getByRole("combobox");++ await userEvent.click(input);+ await userEvent.paste("flour, sugar butter");++ await expect(canvas.getByText("flour")).toBeVisible();+ await expect(canvas.getByText("sugar")).toBeVisible();+ await expect(canvas.getByText("butter")).toBeVisible();+ }+};++const ControlledDraftRender = () => {+ const [value, setValue] = useState<string[]>(["typescript"]);+ const [draft, setDraft] = useState("go");++ return (+ <div className="flex flex-col gap-3">+ <Field>+ <FieldLabel htmlFor="tags-input-controlled">Languages</FieldLabel>+ <TagsInput+ id="tags-input-controlled"+ value={value}+ onValueChange={setValue}+ inputValue={draft}+ onInputValueChange={setDraft}+ placeholder="Add a language"+ />+ </Field>+ <p className="text-xs text-muted">+ Uncommitted draft: <span className="font-mono">{draft || "(empty)"}</span>+ </p>+ </div>+ );+};++/**+ * Pass `inputValue` and `onInputValueChange` to own the half-typed text. The component+ * keeps its own draft otherwise, so this is only needed when something outside has to see+ * it — a form library holding it so an unconfirmed value survives a re-render, or a+ * validation message that should clear as soon as the text changes.+ */+export const ControlledDraft: Story = {+ name: "Example: Controlled Draft",+ parameters: {+ docs: {+ description: {+ story:+ "The draft starts as `go` and is mirrored below the field. Press Enter to commit it and watch the mirror clear, or keep typing to watch it track."+ }+ }+ },+ render: () => <ControlledDraftRender />,+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const input = canvas.getByRole("combobox");++ await expect(input).toHaveValue("go");+ await userEvent.type(input, "{Enter}");+ await expect(canvas.getByText("(empty)")).toBeVisible();+ }+};++const ValidationRender = () => {+ const [value, setValue] = useState<string[]>(["api.github.com"]);+ const [error, setError] = useState<string | null>(null);++ const validateTag = (tag: string, existing: string[]) => {+ if (existing.includes(tag)) return `"${tag}" is already in the list.`;+ if (tag.includes("/")) return `"${tag}" is a host, so it can't contain a path.`;+ return null;+ };++ return (+ <Field data-invalid={error ? "true" : undefined}>+ <FieldLabel htmlFor="tags-input-validated">Hosts</FieldLabel>+ <TagsInput+ id="tags-input-validated"+ value={value}+ onValueChange={setValue}+ validateTag={validateTag}+ onValidationError={setError}+ isError={Boolean(error)}+ placeholder="api.datadoghq.com"+ />+ {error ? <FieldError>{error}</FieldError> : null}+ </Field>+ );+};++/**+ * `validateTag` runs before a tag is committed. Returning a reason refuses it, leaves the+ * text in the box so it can be corrected, and hands the reason to `onValidationError`.+ * `existing` never contains the value being checked, so a duplicate check is a plain+ * `includes`.+ */+export const Validation: Story = {+ name: "Example: Validation",+ parameters: {+ docs: {+ description: {+ story:+ "Hostnames are the case that needs a rule, so this one is not generic. Type a value already in the list, or one containing a `/`, then press Enter: the tag is refused and the draft is kept rather than cleared."+ }+ }+ },+ render: () => <ValidationRender />,+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const input = canvas.getByRole("combobox");++ await userEvent.type(input, "api.github.com{Enter}");+ await expect(await canvas.findByText(/already in the list/)).toBeVisible();+ await expect(input).toHaveValue("api.github.com");+ }+};++export const States: Story = {+ render: () => (+ <div className="flex flex-col gap-5">+ <Field data-invalid="true">+ <FieldLabel htmlFor="tags-input-error">Languages</FieldLabel>+ <TagsInput+ id="tags-input-error"+ value={LANGUAGES}+ onValueChange={() => undefined}+ isError+ />+ <FieldError>Add at least one language.</FieldError>+ </Field>+ <Field data-disabled="true">+ <FieldLabel htmlFor="tags-input-disabled">Languages</FieldLabel>+ <TagsInput+ id="tags-input-disabled"+ value={LANGUAGES}+ onValueChange={() => undefined}+ isDisabled+ />+ </Field>+ <Field data-disabled="true">+ <FieldLabel htmlFor="tags-input-disabled-empty">Labels</FieldLabel>+ <TagsInput+ id="tags-input-disabled-empty"+ value={[]}+ onValueChange={() => undefined}+ placeholder="Add a label"+ isDisabled+ />+ </Field>+ </div>+ )+};++const OverflowRender = () => {+ const [value, setValue] = useState<string[]>([+ "typescript",+ "javascript",+ "go",+ "rust",+ "python",+ "ruby",+ "elixir",+ "kotlin",+ "swift",+ "scala",+ "haskell",+ "clojure",+ "erlang",+ "zig"+ ]);++ return (+ <Field>+ <FieldLabel htmlFor="tags-input-overflow">Languages</FieldLabel>+ <TagsInput id="tags-input-overflow" value={value} onValueChange={setValue} />+ </Field>+ );+};++/**+ * A long list wraps into a bounded, internally scrollable area so the form cannot grow+ * without limit, with a fade at whichever edge has more to show.+ */+export const Overflow: Story = {+ name: "Example: Many Tags",+ render: () => <OverflowRender />+};diff --git a/frontend/src/components/v3/generic/TagsInput/TagsInput.tsx b/frontend/src/components/v3/generic/TagsInput/TagsInput.tsxnew file mode 100644index 0000000000..6da0681423--- /dev/null+++ b/frontend/src/components/v3/generic/TagsInput/TagsInput.tsx@@ -0,0 +1,200 @@+import * as React from "react";+import { Combobox as ComboboxPrimitive } from "@base-ui/react/combobox";+import { XIcon } from "lucide-react";++import { cn } from "../../utils";+import { useScrollEdges } from "../../utils/useScrollEdges";+import {+ COMBOBOX_CHIP_CLASS,+ COMBOBOX_CHIP_LABEL_CLASS,+ COMBOBOX_CHIP_REMOVE_CLASS,+ COMBOBOX_CHIPS_CLASS,+ COMBOBOX_CHIPS_INPUT_CLASS,+ comboboxChipsViewportClass+} from "../Combobox/combobox-chips";++import "../../utils/ScrollEdgeFade.css";++const NO_ITEMS: string[] = [];++type TagsInputProps = Omit<+ React.ComponentPropsWithoutRef<"input">,+ "children" | "disabled" | "onChange" | "type" | "value"+> & {+ /** Tags are keyed by their text, so `validateTag` has to refuse a duplicate for the list to render. */+ value?: readonly string[];+ onValueChange: (next: string[]) => void;+ isDisabled?: boolean;+ isError?: boolean;+ /** Returning a reason refuses the commit. `existing` never contains the value being checked. */+ validateTag?: (tag: string, existing: string[]) => string | null;+ onValidationError?: (reason: string | null) => void;+ inputValue?: string;+ onInputValueChange?: (draft: string) => void;+ className?: string;+};++const TagsInput = React.forwardRef<HTMLInputElement, TagsInputProps>(+ (+ {+ value = NO_ITEMS,+ onValueChange,+ isDisabled,+ isError,+ validateTag,+ onValidationError,+ inputValue,+ onInputValueChange,+ className,+ placeholder,+ ...inputProps+ },+ forwardedRef+ ) => {+ const [uncontrolledDraft, setUncontrolledDraft] = React.useState("");+ const draft = inputValue ?? uncontrolledDraft;++ const { scrollEdges, setViewportRef } = useScrollEdges<HTMLDivElement>("vertical");++ const setDraft = (next: string) => {+ if (inputValue === undefined) setUncontrolledDraft(next);+ onInputValueChange?.(next);+ };++ const tags = React.useMemo(() => [...value], [value]);++ const commit = (raw: string) => {+ const tag = raw.trim();+ if (!tag) {+ setDraft("");+ return true;+ }++ const reason = validateTag?.(tag, tags) ?? null;+ if (reason) {+ onValidationError?.(reason);+ return false;+ }++ onValidationError?.(null);+ onValueChange([...tags, tag]);+ setDraft("");+ return true;+ };++ const handleKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {+ if (event.key === "Enter") {+ event.preventDefault();+ commit(draft);+ return;+ }++ if (event.key === "," || event.key === " ") {+ event.preventDefault();+ commit(draft);+ }+ };++ const handlePaste = (event: React.ClipboardEvent<HTMLInputElement>) => {+ const pasted = event.clipboardData.getData("text");+ const splitOn = /[\n\r, ]/;+ if (!splitOn.test(pasted)) return;++ event.preventDefault();++ const parts = pasted+ .split(splitOn)+ .map((part) => part.trim())+ .filter(Boolean);++ const accepted: string[] = [];+ let refusedFrom = -1;++ for (let index = 0; index < parts.length; index += 1) {+ const reason = validateTag?.(parts[index], [...tags, ...accepted]) ?? null;+ if (reason) {+ onValidationError?.(reason);+ refusedFrom = index;+ break;+ }+ accepted.push(parts[index]);+ }++ if (accepted.length) onValueChange([...tags, ...accepted]);+ if (refusedFrom === -1) {+ onValidationError?.(null);+ setDraft("");+ return;+ }++ setDraft(parts.slice(refusedFrom).join(","));+ };++ return (+ <ComboboxPrimitive.Root+ multiple+ items={NO_ITEMS}+ value={tags}+ onValueChange={onValueChange}+ // No popup is rendered, but the open state still drives aria-expanded and makes Base UI swallow Enter.+ open={false}+ onOpenChange={() => {}}+ openOnInputClick={false}+ inputValue={draft}+ onInputValueChange={setDraft}+ disabled={isDisabled}+ >+ <ComboboxPrimitive.Chips+ data-slot="tags-input"+ data-disabled={isDisabled ? "" : undefined}+ data-invalid={isError}+ className={cn(+ COMBOBOX_CHIPS_CLASS,+ "items-start",+ tags.length > 0 ? "p-1" : "px-2.5 py-1",+ className+ )}+ >+ <div+ ref={setViewportRef}+ className={comboboxChipsViewportClass()}+ data-scroll-edge-axis="vertical"+ data-scrollable-start={scrollEdges.start}+ data-scrollable-end={scrollEdges.end}+ >+ {tags.map((tag) => (+ <ComboboxPrimitive.Chip key={tag} className={COMBOBOX_CHIP_CLASS}>+ <span className={COMBOBOX_CHIP_LABEL_CLASS}>{tag}</span>+ {!isDisabled && (+ <ComboboxPrimitive.ChipRemove+ aria-label={`Remove ${tag}`}+ // Removal is Base UI's, through the controlled Root. Doing it here too would fire the+ // caller's handler twice. Adding is ours, in `commit`, since there is no options list.+ onClick={() => onValidationError?.(null)}+ className={COMBOBOX_CHIP_REMOVE_CLASS}+ >+ <XIcon className="size-3" />+ </ComboboxPrimitive.ChipRemove>+ )}+ </ComboboxPrimitive.Chip>+ ))}+ <ComboboxPrimitive.Input+ ref={forwardedRef}+ aria-invalid={isError || undefined}+ placeholder={tags.length === 0 ? placeholder : undefined}+ onKeyDown={handleKeyDown}+ onPaste={handlePaste}+ onBlur={() => commit(draft)}+ className={COMBOBOX_CHIPS_INPUT_CLASS}+ {...inputProps}+ />+ </div>+ </ComboboxPrimitive.Chips>+ </ComboboxPrimitive.Root>+ );+ }+);++TagsInput.displayName = "TagsInput";++export { TagsInput, type TagsInputProps };diff --git a/frontend/src/components/v3/generic/TagsInput/index.ts b/frontend/src/components/v3/generic/TagsInput/index.tsnew file mode 100644index 0000000000..697ade8c3b--- /dev/null+++ b/frontend/src/components/v3/generic/TagsInput/index.ts@@ -0,0 +1 @@+export { TagsInput, type TagsInputProps } from "./TagsInput";diff --git a/frontend/src/components/v3/generic/index.ts b/frontend/src/components/v3/generic/index.tsindex 73d5137c9a..ff998862fd 100644--- a/frontend/src/components/v3/generic/index.ts+++ b/frontend/src/components/v3/generic/index.ts@@ -47,6 +47,7 @@ export * from "./Spinner";export * from "./Stepper";export * from "./Table";export * from "./Tabs";+export * from "./TagsInput";export * from "./TextArea";export * from "./Toast";export * from "./Toggle";diff --git a/frontend/src/helpers/agentVaultHostPattern.ts b/frontend/src/helpers/agentVaultHostPattern.tsindex 1a9ad0d671..d426963a1e 100644--- a/frontend/src/helpers/agentVaultHostPattern.ts+++ b/frontend/src/helpers/agentVaultHostPattern.ts@@ -3,39 +3,63 @@ import { z } from "zod";const HOST_LABELS_RE =/^(?:\*\.)?[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*$/i;+/** The key the server dedupes on, so `API.Foo.com.` and `api.foo.com:443` collide here too. */+const hostKey = (raw: string): string | null => {+ const trimmed = raw.trim();+ if (trimmed.startsWith("[")) return trimmed.toLowerCase();++ let host = trimmed;+ let port = "443";+ const colonIdx = trimmed.lastIndexOf(":");+ if (colonIdx !== -1) {+ host = trimmed.slice(0, colonIdx);+ port = trimmed.slice(colonIdx + 1);+ }++ return `${host.replace(/\.$/, "").toLowerCase()}:${port}`;+};+/*** A partial pre-check, so a malformed host is caught on the field that holds it rather than bounced* back from a submit. agent-vault-host-pattern.ts stays the grammar of record.+ *+ * `existing` must never contain the value being checked: the duplicate is reported on the second+ * occurrence, matching the server.*/-const hostSegmentError = (segment: string, seen: Set<string>): string | null => {+export const hostError = (segment: string, existing: string[] = []): string | null => {const raw = segment.trim();if (!raw) return "Remove the empty entry";if (raw.includes("://")) return "Remove the scheme, for example https://";if (raw.includes("/"))return "A host pattern covers a whole host, so remove everything from the first /";- if (raw.startsWith("[")) return null;- let host = raw;- let port = "443";- const colonIdx = raw.lastIndexOf(":");- if (colonIdx !== -1) {- host = raw.slice(0, colonIdx);- port = raw.slice(colonIdx + 1);- const parsed = Number(port);- if (!/^\d+$/.test(port) || parsed < 1 || parsed > 65535) return `"${raw}" has an invalid port`;- }+ if (!raw.startsWith("[")) {+ let host = raw;+ const colonIdx = raw.lastIndexOf(":");+ if (colonIdx !== -1) {+ host = raw.slice(0, colonIdx);+ const port = raw.slice(colonIdx + 1);+ const parsed = Number(port);+ if (!/^\d+$/.test(port) || parsed < 1 || parsed > 65535)+ return `"${raw}" has an invalid port`;+ }- host = host.replace(/\.$/, "").toLowerCase();- if (host === "*" || host === "*.") return "Name specific hosts. A bare wildcard is too broad.";- if (!HOST_LABELS_RE.test(host)) return `"${raw}" is not a valid host`;+ host = host.replace(/\.$/, "").toLowerCase();+ if (host === "*" || host === "*.") return "Name specific hosts. A bare wildcard is too broad.";+ if (!HOST_LABELS_RE.test(host)) return `"${raw}" is not a valid host`;+ }- const key = `${host}:${port}`;- if (seen.has(key)) return `"${raw}" is listed more than once`;- seen.add(key);+ const key = hostKey(raw);+ if (key && existing.some((other) => hostKey(other) === key))+ return `"${raw}" is listed more than once`;return null;};+/** One error slot per host. Each is judged against the hosts before it, never against itself. */+const hostErrors = (hosts: string[]): (string | null)[] =>+ hosts.map((host, index) => hostError(host, hosts.slice(0, index)));+export const addHostListIssues = (value: string | undefined,ctx: z.RefinementCtx,@@ -43,9 +67,18 @@ export const addHostListIssues = () => {if (!value) return;- const seen = new Set<string>();- value.split(",").forEach((segment) => {- const error = hostSegmentError(segment, seen);+ hostErrors(value.split(",")).forEach((error) => {if (error) ctx.addIssue({ code: z.ZodIssueCode.custom, message: error, ...(path && { path }) });});};++export const addHostIssues = (+ hosts: string[],+ ctx: z.RefinementCtx,+ path: (string | number)[] = []+) => {+ hostErrors(hosts).forEach((error, index) => {+ if (error)+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: error, path: [...path, index] });+ });+};diff --git a/frontend/src/helpers/agentVaultMembers.ts b/frontend/src/helpers/agentVaultMembers.tsnew file mode 100644index 0000000000..787a00889d--- /dev/null+++ b/frontend/src/helpers/agentVaultMembers.ts@@ -0,0 +1,14 @@+import { AgentVaultMemberType } from "@app/hooks/api/agentVault/enums";+import { TAgentVaultActorIdsDTO, TAgentVaultActorRef } from "@app/hooks/api/agentVault/types";++export const actorIdsPayload = (actors: TAgentVaultActorRef[]): TAgentVaultActorIdsDTO => ({+ userIds: actors+ .filter((actor) => actor.type === AgentVaultMemberType.User)+ .map((actor) => actor.id),+ groupIds: actors+ .filter((actor) => actor.type === AgentVaultMemberType.Group)+ .map((actor) => actor.id),+ machineIdentityIds: actors+ .filter((actor) => actor.type === AgentVaultMemberType.MachineIdentity)+ .map((actor) => actor.id)+});diff --git a/frontend/src/helpers/agentVaultPathPrefix.ts b/frontend/src/helpers/agentVaultPathPrefix.tsnew file mode 100644index 0000000000..1c46b51756--- /dev/null+++ b/frontend/src/helpers/agentVaultPathPrefix.ts@@ -0,0 +1,45 @@+import { z } from "zod";++// Mirrors backend/src/ee/services/agent-vault/agent-vault-path-prefix.ts, which stays the grammar of record.+// Kept here so a bad prefix is caught before the request rather than coming back as a server error.++const PATH_PREFIX_RE = /^\/[A-Za-z0-9\-._~$&+/:=@]*$/;++export const normalizePathPrefix = (value: string) => {+ const trimmed = value.trim();+ if (trimmed === "/") return trimmed;+ return trimmed.replace(/\/+$/, "");+};++/** `existing` must never contain the value being checked, so a duplicate is reported on the second one. */+export const pathPrefixError = (raw: string, existing: string[] = []): string | null => {+ const value = raw.trim();+ if (!value) return "A path prefix can't be empty.";+ if (value.length > 512) return "A path prefix can be at most 512 characters.";+ if (!value.startsWith("/")) return "A path prefix must start with a /.";+ if (value.includes("//")) return "A path prefix can't contain an empty segment.";+ if (value.split("/").some((segment) => segment === "." || segment === ".."))+ return "A path prefix can't contain a . or .. segment.";+ if (!PATH_PREFIX_RE.test(value))+ return "A path prefix can only contain letters, digits and - . _ ~ $ & + : = @.";++ const normalized = normalizePathPrefix(value);+ if (existing.some((other) => normalizePathPrefix(other) === normalized))+ return `"${normalized}" is listed twice.`;++ return null;+};++/** One error slot per prefix. Each is judged against the prefixes before it, never against itself. */+const pathPrefixErrors = (prefixes: string[]): (string | null)[] =>+ prefixes.map((prefix, index) => pathPrefixError(prefix, prefixes.slice(0, index)));++export const addPathPrefixIssues = (+ prefixes: string[],+ ctx: z.RefinementCtx,+ path: (string | number)[] = []+) => {+ pathPrefixErrors(prefixes).forEach((message, index) => {+ if (message) ctx.addIssue({ code: z.ZodIssueCode.custom, message, path: [...path, index] });+ });+};diff --git a/frontend/src/helpers/agentVaultTemplates.ts b/frontend/src/helpers/agentVaultTemplates.tsindex 2346d2c212..1049e5b92c 100644--- a/frontend/src/helpers/agentVaultTemplates.ts+++ b/frontend/src/helpers/agentVaultTemplates.ts@@ -389,9 +389,14 @@ export const POPULAR_AGENT_VAULT_TEMPLATES = [const stripPort = (pattern: string) => pattern.split(":")[0];+// A template whose host starts with a placeholder label, such as <your-tenant>.atlassian.net, is+// saved with that label replaced. Treat it exactly like a "*." wildcard, or the icon is lost the+// moment someone fills their tenant in.+const ONE_LABEL_PREFIX_RE = /^(?:\*|<[^>]+>)\./;+const hostMatchesTemplateHost = (host: string, templateHost: string) => {- if (!templateHost.startsWith("*.")) return host === templateHost;- const suffix = templateHost.slice(2);+ if (!ONE_LABEL_PREFIX_RE.test(templateHost)) return host === templateHost;+ const suffix = templateHost.replace(ONE_LABEL_PREFIX_RE, "");if (!host.endsWith(`.${suffix}`)) return false;return !host.slice(0, host.length - suffix.length - 1).includes(".");};diff --git a/frontend/src/hooks/api/agentVault/enums.ts b/frontend/src/hooks/api/agentVault/enums.tsindex e8d04d4114..c4e620051d 100644--- a/frontend/src/hooks/api/agentVault/enums.ts+++ b/frontend/src/hooks/api/agentVault/enums.ts@@ -1,9 +1,32 @@+export enum AgentVaultHttpMethod {+ Get = "GET",+ Head = "HEAD",+ Post = "POST",+ Put = "PUT",+ Patch = "PATCH",+ Delete = "DELETE",+ Options = "OPTIONS"+}++export enum AgentVaultSubstitutionSurface {+ Path = "path",+ Query = "query",+ Header = "header",+ Body = "body"+}+export enum AgentVaultCredentialType {Bearer = "bearer",Basic = "basic",Passthrough = "passthrough"}+export enum AgentVaultMemberType {+ User = "user",+ MachineIdentity = "machineIdentity",+ Group = "group"+}+export enum AgentVaultTrafficPolicy {AnyHost = "any-host",BundleHosts = "bundle-hosts"diff --git a/frontend/src/hooks/api/agentVault/mutations.tsx b/frontend/src/hooks/api/agentVault/mutations.tsxindex 6011553a52..16e96f524b 100644--- a/frontend/src/hooks/api/agentVault/mutations.tsx+++ b/frontend/src/hooks/api/agentVault/mutations.tsx@@ -4,16 +4,21 @@ import { apiRequest } from "@app/config/request";import { useOrganization } from "@app/context";import { ApiErrorTypes } from "../types";+import { AgentVaultMemberType } from "./enums";import { agentVaultKeys } from "./queries";import {TAddAgentVaultMembersDTO,+ TAddAgentVaultProductMembersDTO,TAgentVaultAccessBundle,+ TAgentVaultActorIdsDTO,+ TAgentVaultActorRef,TAgentVaultEnrollment,+ TAgentVaultMemberWriteResult,TAgentVaultMintedSession,- TAgentVaultProductMemberActor,TAgentVaultProxy,TAgentVaultProxySettingsDTO,TAgentVaultService,+ TAgentVaultWrittenMember,TCreateAgentVaultAccessBundleDTO,TCreateAgentVaultServiceDTO,TCreateAgentVaultSessionDTO,@@ -146,6 +151,12 @@ export const useDeleteAgentVaultService = () => {});};+const ACTOR_PATH: Record<AgentVaultMemberType, string> = {+ [AgentVaultMemberType.User]: "users",+ [AgentVaultMemberType.Group]: "groups",+ [AgentVaultMemberType.MachineIdentity]: "machine-identities"+};+export const useAddAgentVaultAccessBundleMembers = () => {const { currentOrg } = useOrganization();const queryClient = useQueryClient();@@ -153,7 +164,7 @@ export const useAddAgentVaultAccessBundleMembers = () => {mutationFn: async ({ accessBundleId, ...params }: TAddAgentVaultMembersDTO) => {const { data } = await apiRequest.post<{members: { id: string }[];- skipped: string[];+ skipped: { type: AgentVaultMemberType; id: string }[];}>(`/api/v1/agent-vault/access-bundles/${accessBundleId}/members`, params);return data;},@@ -166,21 +177,15 @@ export const useAddAgentVaultAccessBundleMembers = () => {});};-export const useRemoveAgentVaultAccessBundleMember = () => {+export const useRevokeAgentVaultAccessBundleMembers = () => {const { currentOrg } = useOrganization();const queryClient = useQueryClient();return useMutation({- mutationFn: async ({- accessBundleId,- memberId- }: {- accessBundleId: string;- memberId: string;- }) => {- const { data } = await apiRequest.delete<{ member: { id: string } }>(- `/api/v1/agent-vault/access-bundles/${accessBundleId}/members/${memberId}`- );- return data.member;+ mutationFn: async ({ accessBundleId, ...params }: TAddAgentVaultMembersDTO) => {+ const { data } = await apiRequest.post<+ TAgentVaultMemberWriteResult<{ id: string; actor: TAgentVaultActorRef }>+ >(`/api/v1/agent-vault/access-bundles/${accessBundleId}/members/revoke`, params);+ return data;},onSuccess: (_, { accessBundleId }) => {queryClient.invalidateQueries({@@ -282,7 +287,7 @@ export const useReissueAgentVaultProxyEnrollmentToken = () =>useMutation({mutationFn: async (proxyId: string) => {const { data } = await apiRequest.post<TAgentVaultEnrollment>(- `/api/v1/agent-vault/proxies/${proxyId}/token-auth/generate-enrollment-token`+ `/api/v1/agent-vault/proxies/${proxyId}/token-auth/enrollment-token`);return data;}@@ -306,81 +311,51 @@ export const useRevokeAgentVaultProxyAccess = () => {// The member is named in the URL, so a call with no actor has nowhere to go. The role dialogs pass an// empty actor while closed, which cannot reach a mutation, so this only fires on a genuine mistake.-const agentVaultMemberPath = ({- userId,- groupId,- identityId-}: TAgentVaultProductMemberActor): string => {- if (userId) return `users/${userId}`;- if (groupId) return `groups/${groupId}`;- if (identityId) return `identities/${identityId}`;- throw new Error("Name a user, group or machine identity");-};--const invalidateProductMembers = (- queryClient: ReturnType<typeof useQueryClient>,- orgId: string-) => {- queryClient.invalidateQueries({ queryKey: agentVaultKeys.productMembers(orgId) });+// Removing a product member strips their bundle grants, so the bundle queries go too.+const invalidateMembers = (queryClient: ReturnType<typeof useQueryClient>, orgId: string) => {+ queryClient.invalidateQueries({ queryKey: agentVaultKeys.members(orgId) });queryClient.invalidateQueries({ queryKey: agentVaultKeys.accessBundles(orgId) });};-export const useAddAgentVaultProductUserMembers = () => {+export const useAddAgentVaultMembers = () => {const { currentOrg } = useOrganization();const queryClient = useQueryClient();return useMutation({- mutationFn: async (dto: { userIds: string[]; emails: string[]; role: string }) => {- const { data } = await apiRequest.post<{- members: { membershipId: string; userId?: string; role: string; createdAt: string }[];- skipped: string[];- }>("/api/v1/agent-vault/memberships/users", dto);+ mutationFn: async (dto: TAddAgentVaultProductMembersDTO) => {+ const { data } = await apiRequest.post<+ TAgentVaultMemberWriteResult<TAgentVaultWrittenMember>+ >("/api/v1/agent-vault/members", dto);return data;},- onSuccess: () => invalidateProductMembers(queryClient, currentOrg.id)+ onSuccess: () => invalidateMembers(queryClient, currentOrg.id)});};-// Users are added through the batch route, so this covers groups and machine identities only.-export const useAddAgentVaultProductMember = () => {+export const useUpdateAgentVaultMemberRole = () => {const { currentOrg } = useOrganization();const queryClient = useQueryClient();return useMutation({- mutationFn: async ({ role, ...actor }: TAgentVaultProductMemberActor & { role: string }) => {- const { data } = await apiRequest.post(- `/api/v1/agent-vault/memberships/${agentVaultMemberPath(actor)}`,+ mutationFn: async ({ actor, role }: { actor: TAgentVaultActorRef; role: string }) => {+ const { data } = await apiRequest.patch<{ member: TAgentVaultWrittenMember }>(+ `/api/v1/agent-vault/members/${ACTOR_PATH[actor.type]}/${actor.id}`,{ role });- return data;- },- onSuccess: () => invalidateProductMembers(queryClient, currentOrg.id)- });-};--export const useUpdateAgentVaultProductMemberRole = () => {- const { currentOrg } = useOrganization();- const queryClient = useQueryClient();- return useMutation({- mutationFn: async ({ role, ...actor }: TAgentVaultProductMemberActor & { role: string }) => {- const { data } = await apiRequest.patch(- `/api/v1/agent-vault/memberships/${agentVaultMemberPath(actor)}`,- { role }- );- return data;+ return data.member;},- onSuccess: () => invalidateProductMembers(queryClient, currentOrg.id)+ onSuccess: () => invalidateMembers(queryClient, currentOrg.id)});};-export const useRemoveAgentVaultProductMember = () => {+export const useRevokeAgentVaultMembers = () => {const { currentOrg } = useOrganization();const queryClient = useQueryClient();return useMutation({- mutationFn: async (actor: TAgentVaultProductMemberActor) => {- const { data } = await apiRequest.delete(- `/api/v1/agent-vault/memberships/${agentVaultMemberPath(actor)}`- );+ mutationFn: async (dto: TAgentVaultActorIdsDTO) => {+ const { data } = await apiRequest.post<+ TAgentVaultMemberWriteResult<TAgentVaultWrittenMember>+ >("/api/v1/agent-vault/members/revoke", dto);return data;},- onSuccess: () => invalidateProductMembers(queryClient, currentOrg.id)+ onSuccess: () => invalidateMembers(queryClient, currentOrg.id)});};diff --git a/frontend/src/hooks/api/agentVault/queries.tsx b/frontend/src/hooks/api/agentVault/queries.tsxindex 610c7c05ad..6d9579fad3 100644--- a/frontend/src/hooks/api/agentVault/queries.tsx+++ b/frontend/src/hooks/api/agentVault/queries.tsx@@ -3,14 +3,17 @@ import { useQuery } from "@tanstack/react-query";import { apiRequest } from "@app/config/request";import { useOrganization } from "@app/context";+import { AgentVaultMemberType } from "./enums";import {TAgentVaultAccessBundleDetails,TAgentVaultAccessBundleListItem,- TAgentVaultProductGroupMember,- TAgentVaultProductIdentityMember,- TAgentVaultProductUserMember,+ TAgentVaultMember,+ TAgentVaultProductMemberOf,TAgentVaultProxy,TAgentVaultSession,+ TListAgentVaultAccessBundlesDTO,+ TListAgentVaultMembersDTO,+ TListAgentVaultProxiesDTO,TListAgentVaultSessionsDTO} from "./types";@@ -31,64 +34,76 @@ export const agentVaultKeys = {sessions: (orgId: string) => [...agentVaultKeys.all(orgId), "sessions"] as const,sessionList: (orgId: string, params?: TListAgentVaultSessionsDTO) =>[...agentVaultKeys.sessions(orgId), params] as const,+ accessBundleList: (orgId: string, params?: TListAgentVaultAccessBundlesDTO) =>+ [...agentVaultKeys.accessBundles(orgId), "list", params] as const,proxies: (orgId: string) => [...agentVaultKeys.all(orgId), "proxies"] as const,- productMembers: (orgId: string) => [...agentVaultKeys.all(orgId), "product-members"] as const,- productUserMembers: (orgId: string) =>- [...agentVaultKeys.productMembers(orgId), "users"] as const,- productGroupMembers: (orgId: string) =>- [...agentVaultKeys.productMembers(orgId), "groups"] as const,- productIdentityMembers: (orgId: string) =>- [...agentVaultKeys.productMembers(orgId), "identities"] as const+ proxyList: (orgId: string, params?: TListAgentVaultProxiesDTO) =>+ [...agentVaultKeys.proxies(orgId), params] as const,+ accessBundleMembers: (orgId: string, accessBundleId: string) =>+ [...agentVaultKeys.accessBundle(orgId, accessBundleId), "members"] as const,+ accessBundleMemberList: (+ orgId: string,+ accessBundleId: string,+ params?: Omit<TListAgentVaultMembersDTO, "actorType">+ ) => [...agentVaultKeys.accessBundleMembers(orgId, accessBundleId), params] as const,+ members: (orgId: string) => [...agentVaultKeys.all(orgId), "members"] as const,+ memberList: (orgId: string, params?: TListAgentVaultMembersDTO) =>+ [...agentVaultKeys.members(orgId), params] as const};-const fetchProductMembers = async <T,>(path: string) => {- const { data } = await apiRequest.get<{ members: T[] }>(- `/api/v1/agent-vault/memberships/${path}`- );- return data.members;-};--export const useListAgentVaultProductUserMembers = (enabled = true) => {+export const useListAgentVaultMembers = <T extends AgentVaultMemberType = AgentVaultMemberType>(+ params: TListAgentVaultMembersDTO & { actorType?: T } = {},+ enabled = true+) => {const { currentOrg } = useOrganization();return useQuery({- queryKey: agentVaultKeys.productUserMembers(currentOrg.id),- queryFn: () => fetchProductMembers<TAgentVaultProductUserMember>("users"),- enabled- });-};--export const useListAgentVaultProductGroupMembers = (enabled = true) => {- const { currentOrg } = useOrganization();-- return useQuery({- queryKey: agentVaultKeys.productGroupMembers(currentOrg.id),- queryFn: () => fetchProductMembers<TAgentVaultProductGroupMember>("groups"),- enabled+ queryKey: agentVaultKeys.memberList(currentOrg.id, params),+ queryFn: async () => {+ const { data } = await apiRequest.get<{+ members: TAgentVaultProductMemberOf<T>[];+ totalCount: number;+ }>("/api/v1/agent-vault/members", { params });+ return data;+ },+ enabled,+ placeholderData: (prev) => prev});};-export const useListAgentVaultProductIdentityMembers = (enabled = true) => {+export const useListAgentVaultAccessBundleMembers = (+ accessBundleId: string,+ params: Omit<TListAgentVaultMembersDTO, "actorType"> = {}+) => {const { currentOrg } = useOrganization();return useQuery({- queryKey: agentVaultKeys.productIdentityMembers(currentOrg.id),- queryFn: () => fetchProductMembers<TAgentVaultProductIdentityMember>("identities"),- enabled+ queryKey: agentVaultKeys.accessBundleMemberList(currentOrg.id, accessBundleId, params),+ queryFn: async () => {+ const { data } = await apiRequest.get<{ members: TAgentVaultMember[]; totalCount: number }>(+ `/api/v1/agent-vault/access-bundles/${accessBundleId}/members`,+ { params }+ );+ return data;+ },+ enabled: Boolean(accessBundleId),+ placeholderData: (prev) => prev});};-export const useListAgentVaultAccessBundles = () => {+export const useListAgentVaultAccessBundles = (params: TListAgentVaultAccessBundlesDTO = {}) => {const { currentOrg } = useOrganization();return useQuery({- queryKey: agentVaultKeys.accessBundles(currentOrg.id),+ queryKey: agentVaultKeys.accessBundleList(currentOrg.id, params),queryFn: async () => {const { data } = await apiRequest.get<{accessBundles: TAgentVaultAccessBundleListItem[];- }>("/api/v1/agent-vault/access-bundles");- return data.accessBundles;- }+ totalCount: number;+ }>("/api/v1/agent-vault/access-bundles", { params });+ return data;+ },+ placeholderData: (prev) => prev});};@@ -124,17 +139,19 @@ export const useListAgentVaultSessions = (params?: TListAgentVaultSessionsDTO) =});};-export const useListAgentVaultProxies = () => {+export const useListAgentVaultProxies = (params: TListAgentVaultProxiesDTO = {}) => {const { currentOrg } = useOrganization();return useQuery({- queryKey: agentVaultKeys.proxies(currentOrg.id),+ queryKey: agentVaultKeys.proxyList(currentOrg.id, params),queryFn: async () => {- const { data } = await apiRequest.get<{ proxies: TAgentVaultProxy[] }>(- "/api/v1/agent-vault/proxies"+ const { data } = await apiRequest.get<{ proxies: TAgentVaultProxy[]; totalCount: number }>(+ "/api/v1/agent-vault/proxies",+ { params });- return data.proxies;+ return data;},- refetchInterval: 30_000+ refetchInterval: 30_000,+ placeholderData: (prev) => prev});};diff --git a/frontend/src/hooks/api/agentVault/types.ts b/frontend/src/hooks/api/agentVault/types.tsindex 277839be56..b9815e5a44 100644--- a/frontend/src/hooks/api/agentVault/types.ts+++ b/frontend/src/hooks/api/agentVault/types.ts@@ -1,7 +1,10 @@import {AgentVaultCredentialType,+ AgentVaultHttpMethod,+ AgentVaultMemberType,AgentVaultSessionScope,AgentVaultSessionStatus,+ AgentVaultSubstitutionSurface,AgentVaultTrafficPolicy} from "./enums";@@ -30,29 +33,130 @@ export type TAgentVaultCredentialUpdate =| { type: AgentVaultCredentialType.Basic; username?: string; password?: string }| { type: AgentVaultCredentialType.Passthrough };+export type TAgentVaultCustomHeaderSummary = { id: string; name: string; prefix: string };++export type TAgentVaultSubstitutionSummary = {+ id: string;+ placeholder: string;+ surfaces: AgentVaultSubstitutionSurface[];+};++/** `id` is optional because the API matches a row by name (or placeholder) when one is not sent, and+ * `value` is optional because omitting it keeps whatever is already stored for that row. */+export type TAgentVaultCustomHeaderInput = {+ id?: string;+ name: string;+ prefix?: string;+ value?: string;+};++export type TAgentVaultSubstitutionInput = {+ id?: string;+ placeholder: string;+ surfaces: AgentVaultSubstitutionSurface[];+ value?: string;+};+export type TAgentVaultService = {id: string;accessBundleId: string;name: string;hostPattern: string;+ // null means unrestricted.+ allowedMethods: AgentVaultHttpMethod[] | null;+ allowedPathPrefixes: string[] | null;credential: TAgentVaultCredentialSummary;+ customHeaders: TAgentVaultCustomHeaderSummary[];+ substitutions: TAgentVaultSubstitutionSummary[];createdAt: string;+ updatedAt: string;};+export type TAgentVaultActor =+ | {+ type: AgentVaultMemberType.User;+ id: string;+ username: string;+ email: string | null;+ firstName: string | null;+ lastName: string | null;+ }+ | { type: AgentVaultMemberType.MachineIdentity; id: string; name: string }+ | { type: AgentVaultMemberType.Group; id: string; name: string };++export type TAgentVaultActorRef = { type: AgentVaultMemberType; id: string };+export type TAgentVaultMember = {id: string;- userId: string | null;- identityId: string | null;- groupId: string | null;createdAt: string;- user: {- username: string;- email: string | null;- firstName: string | null;- lastName: string | null;- } | null;- identity: { name: string } | null;- group: { name: string } | null;+ actor: TAgentVaultActor;+};++export type TAgentVaultProductActor =+ | (Extract<TAgentVaultActor, { type: AgentVaultMemberType.User }> & {+ isOrgMembershipPending: boolean;+ })+ | (Extract<TAgentVaultActor, { type: AgentVaultMemberType.MachineIdentity }> & {+ isManagedByAgentVault: boolean;+ orgId: string | null;+ })+ | Extract<TAgentVaultActor, { type: AgentVaultMemberType.Group }>;++export type TAgentVaultProductMember = {+ id: string;+ role: string;+ isActive: boolean;+ createdAt: string;+ actor: TAgentVaultProductActor;+};++export type TAgentVaultProductMemberOf<T extends AgentVaultMemberType> = Omit<+ TAgentVaultProductMember,+ "actor"+> & {+ actor: Extract<TAgentVaultProductActor, { type: T }>;+};++export type TListAgentVaultProxiesDTO = {+ search?: string;+ orderBy?: "name" | "createdAt";+ orderDirection?: "asc" | "desc";+ limit?: number;+ offset?: number;+};++export type TListAgentVaultAccessBundlesDTO = Omit<TListAgentVaultProxiesDTO, "orderBy"> & {+ orderBy?: "name" | "serviceCount" | "createdAt";+};++export type TListAgentVaultMembersDTO = {+ actorType?: AgentVaultMemberType;+ search?: string;+ limit?: number;+ offset?: number;+};++export type TAgentVaultActorIdsDTO = {+ userIds?: string[];+ groupIds?: string[];+ machineIdentityIds?: string[];+};++export type TAddAgentVaultProductMembersDTO = TAgentVaultActorIdsDTO & {+ emails?: string[];+ role: string;+};++export type TAgentVaultWrittenMember = {+ id: string;+ role: string;+ createdAt: string;+ actor: TAgentVaultActorRef;+};++export type TAgentVaultMemberWriteResult<T> = {+ members: T[];+ skipped: (TAgentVaultActorRef & { identifier: string })[];};export type TAgentVaultAccessBundle = {@@ -60,6 +164,7 @@ export type TAgentVaultAccessBundle = {name: string;description?: string | null;createdAt: string;+ updatedAt: string;};export type TAgentVaultAccessBundleListItem = TAgentVaultAccessBundle & {@@ -70,7 +175,6 @@ export type TAgentVaultAccessBundleListItem = TAgentVaultAccessBundle & {export type TAgentVaultAccessBundleDetails = TAgentVaultAccessBundle & {services: TAgentVaultService[];- members?: TAgentVaultMember[];};export type TAgentVaultSessionAccessBundle = {@@ -141,7 +245,11 @@ export type TCreateAgentVaultServiceDTO = {accessBundleId: string;name: string;hostPattern: string;+ allowedMethods?: AgentVaultHttpMethod[] | null;+ allowedPathPrefixes?: string[] | null;credential: TAgentVaultCredentialInput;+ customHeaders?: TAgentVaultCustomHeaderInput[];+ substitutions?: TAgentVaultSubstitutionInput[];};export type TUpdateAgentVaultServiceDTO = {@@ -149,14 +257,15 @@ export type TUpdateAgentVaultServiceDTO = {serviceId: string;name?: string;hostPattern?: string;+ allowedMethods?: AgentVaultHttpMethod[] | null;+ allowedPathPrefixes?: string[] | null;credential?: TAgentVaultCredentialUpdate;+ customHeaders?: TAgentVaultCustomHeaderInput[];+ substitutions?: TAgentVaultSubstitutionInput[];};-export type TAddAgentVaultMembersDTO = {+export type TAddAgentVaultMembersDTO = TAgentVaultActorIdsDTO & {accessBundleId: string;- userIds: string[];- identityIds: string[];- groupIds: string[];};export type TCreateAgentVaultSessionDTO = {@@ -170,37 +279,3 @@ export type TAgentVaultProxySettingsDTO = {allowedHosts?: string | null;pollInterval?: number;};--export type TAgentVaultProductMember = {- membershipId: string;- userId: string | null;- groupId: string | null;- identityId: string | null;- role: string;- isActive: boolean;- createdAt: string;-};--export type TAgentVaultProductUserMember = TAgentVaultProductMember & {- email: string | null;- username: string;- firstName: string | null;- lastName: string | null;- isOrgMembershipPending: boolean;-};--export type TAgentVaultProductGroupMember = TAgentVaultProductMember & {- name: string;-};--export type TAgentVaultProductIdentityMember = TAgentVaultProductMember & {- name: string;- identityProjectId: string | null;- identityOrgId: string | null;-};--export type TAgentVaultProductMemberActor = {- userId?: string;- groupId?: string;- identityId?: string;-};diff --git a/frontend/src/hooks/index.ts b/frontend/src/hooks/index.tsindex fa9e8d630e..c7a3961cab 100644--- a/frontend/src/hooks/index.ts+++ b/frontend/src/hooks/index.ts@@ -15,6 +15,7 @@ export { usePagination } from "./usePagination";export { usePersistentState } from "./usePersistentState";export { usePopUp } from "./usePopUp";export { useResetPageHelper } from "./useResetPageHelper";+export { useResetPageOnSearch } from "./useResetPageOnSearch";export * from "./useResizableHeaderHeight";export { useScopeVariant } from "./useScopeVariant";export { useSecretsActivationNudge } from "./useSecretsActivationNudge";diff --git a/frontend/src/hooks/useResetPageOnSearch.ts b/frontend/src/hooks/useResetPageOnSearch.tsnew file mode 100644index 0000000000..224f570bdb--- /dev/null+++ b/frontend/src/hooks/useResetPageOnSearch.ts@@ -0,0 +1,20 @@+import { Dispatch, SetStateAction, useEffect, useRef } from "react";++// Resetting the page from the search input's onChange instead would move the+// query to an unfiltered page one a full debounce interval before the search+// term lands, flashing a cached page of unfiltered rows in between.+export const useResetPageOnSearch = ({+ debouncedSearch,+ setPage+}: {+ debouncedSearch: string;+ setPage: Dispatch<SetStateAction<number>>;+}) => {+ const lastSearch = useRef(debouncedSearch);++ useEffect(() => {+ if (lastSearch.current === debouncedSearch) return;+ lastSearch.current = debouncedSearch;+ setPage(1);+ }, [debouncedSearch]);+};diff --git a/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/ServicesCard.tsx b/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/ServicesCard.tsxindex 9056e6e453..11b6ed89b2 100644--- a/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/ServicesCard.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/ServicesCard.tsx@@ -160,7 +160,7 @@ export const ServicesCard = ({ accessBundleId, services, canManage, onAdd, onEdi<CardHeader><CardTitle>Services- <DocumentationLinkBadge href={AgentVaultDocsUrls.accessBundles} />+ <DocumentationLinkBadge href={AgentVaultDocsUrls.services} /></CardTitle><CardDescription>A service defines one API the agent can reach, the hosts the API answers on, and thediff --git a/frontend/src/pages/agent-vault/AgentVaultAccessBundlesPage/AgentVaultAccessBundlesPage.tsx b/frontend/src/pages/agent-vault/AgentVaultAccessBundlesPage/AgentVaultAccessBundlesPage.tsxindex 1bd4259e14..875574bcf8 100644--- a/frontend/src/pages/agent-vault/AgentVaultAccessBundlesPage/AgentVaultAccessBundlesPage.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultAccessBundlesPage/AgentVaultAccessBundlesPage.tsx@@ -1,4 +1,4 @@-import { useMemo, useState } from "react";+import { useState } from "react";import { Helmet } from "react-helmet";import { useTranslation } from "react-i18next";import { useNavigate } from "@tanstack/react-router";@@ -40,6 +40,7 @@ import {InputGroupAddon,InputGroupInput,PageHeader,+ Pagination,Skeleton,Table,TableBody,@@ -52,6 +53,12 @@ import {TooltipTrigger} from "@app/components/v3";import { useOrganization, useProjectPermission } from "@app/context";+import {+ getUserTablePreference,+ PreferenceKey,+ setUserTablePreference+} from "@app/helpers/userTablePreferences";+import { useDebounce, useResetPageHelper } from "@app/hooks";import { useListAgentVaultAccessBundles } from "@app/hooks/api/agentVault";import { TAgentVaultAccessBundleListItem } from "@app/hooks/api/agentVault/types";import { ProjectType } from "@app/hooks/api/projects/types";@@ -62,19 +69,10 @@ import { DeleteAccessBundleDialog } from "./components/DeleteAccessBundleDialog"enum SortColumn {Name = "name",- Services = "services",- Created = "created"+ Services = "serviceCount",+ Created = "createdAt"}-const SORT_COMPARATORS: Record<- SortColumn,- (a: TAgentVaultAccessBundleListItem, b: TAgentVaultAccessBundleListItem) => number-> = {- [SortColumn.Name]: (a, b) => a.name.localeCompare(b.name),- [SortColumn.Services]: (a, b) => a.serviceCount - b.serviceCount,- [SortColumn.Created]: (a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime()-};-export const AgentVaultAccessBundlesPage = () => {const { t } = useTranslation();const navigate = useNavigate();@@ -83,8 +81,13 @@ export const AgentVaultAccessBundlesPage = () => {const isAdmin = hasProjectRole(ProjectMembershipRole.Admin);const [search, setSearch] = useState("");+ const [debouncedSearch] = useDebounce(search);const [sortColumn, setSortColumn] = useState(SortColumn.Created);const [sortDirection, setSortDirection] = useState<"ascending" | "descending">("descending");+ const [page, setPage] = useState(1);+ const [perPage, setPerPage] = useState(() =>+ getUserTablePreference("agentVaultAccessBundlesTable", PreferenceKey.PerPage, 20)+ );const [isCreateOpen, setIsCreateOpen] = useState(false);const [bundleToEdit, setBundleToEdit] = useState<TAgentVaultAccessBundleListItem | null>(null);const [bundleToDelete, setBundleToDelete] = useState<TAgentVaultAccessBundleListItem | null>(@@ -94,22 +97,20 @@ export const AgentVaultAccessBundlesPage = () => {null);- const { data: accessBundles, isPending } = useListAgentVaultAccessBundles();-- const displayedBundles = useMemo(() => {- const term = search.trim().toLowerCase();- const filtered = (accessBundles ?? []).filter(- (bundle) =>- bundle.name.toLowerCase().includes(term) ||- (bundle.description ?? "").toLowerCase().includes(term)- );+ const { data, isPending } = useListAgentVaultAccessBundles({+ search: debouncedSearch.trim() || undefined,+ orderBy: sortColumn,+ orderDirection: sortDirection === "ascending" ? "asc" : "desc",+ limit: perPage,+ offset: (page - 1) * perPage+ });- const ordered = [...filtered].sort(SORT_COMPARATORS[sortColumn]);-- return sortDirection === "ascending" ? ordered : ordered.reverse();- }, [accessBundles, search, sortColumn, sortDirection]);+ const displayedBundles = data?.accessBundles ?? [];+ const totalCount = data?.totalCount ?? 0;+ useResetPageHelper({ totalCount, offset: (page - 1) * perPage, setPage });const handleSort = (column: SortColumn, direction: "ascending" | "descending" | "none") => {+ setPage(1);if (direction === "none") {setSortColumn(SortColumn.Created);setSortDirection("descending");@@ -127,7 +128,7 @@ export const AgentVaultAccessBundlesPage = () => {sortColumn !== column && "opacity-30");- const isFiltered = Boolean(search.trim());+ const isFiltered = Boolean(debouncedSearch.trim());let emptyTitle: string;let emptyDescription: string;@@ -180,7 +181,10 @@ export const AgentVaultAccessBundlesPage = () => {</InputGroupAddon><InputGroupInputvalue={search}- onChange={(e) => setSearch(e.target.value)}+ onChange={(e) => {+ setSearch(e.target.value);+ setPage(1);+ }}placeholder="Search access bundles..."/></InputGroup>@@ -349,6 +353,26 @@ export const AgentVaultAccessBundlesPage = () => {</TableBody></Table>)}++ {totalCount > 0 && (+ <CardContent className="-mt-5 pt-0">+ <Pagination+ count={totalCount}+ page={page}+ perPage={perPage}+ onChangePage={setPage}+ onChangePerPage={(newPerPage) => {+ setPerPage(newPerPage);+ setPage(1);+ setUserTablePreference(+ "agentVaultAccessBundlesTable",+ PreferenceKey.PerPage,+ newPerPage+ );+ }}+ />+ </CardContent>+ )}</Card><AccessBundleFormDialog isOpen={isCreateOpen} onOpenChange={setIsCreateOpen} />diff --git a/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/AddGroupDialog.tsx b/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/AddGroupDialog.tsxindex 14e9695a7f..8f6d5c812a 100644--- a/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/AddGroupDialog.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/AddGroupDialog.tsx@@ -16,10 +16,7 @@ import {} from "@app/components/v3";import { useOrganization } from "@app/context";import { useGetOrganizationGroups } from "@app/hooks/api";-import {- useAddAgentVaultProductMember,- useListAgentVaultProductGroupMembers-} from "@app/hooks/api/agentVault";+import { useAddAgentVaultMembers } from "@app/hooks/api/agentVault";import { ProjectMembershipRole } from "@app/hooks/api/roles/types";import { ProductRoleField } from "./ProductRoleField";@@ -34,24 +31,26 @@ type Props = {export const AddGroupDialog = ({ isOpen, onOpenChange }: Props) => {const { currentOrg } = useOrganization();const { data: orgGroups = [] } = useGetOrganizationGroups(currentOrg.id);- const { data: projectGroups = [] } = useListAgentVaultProductGroupMembers();- const addMember = useAddAgentVaultProductMember();+ const addMembers = useAddAgentVaultMembers();const [group, setGroup] = useState<TOption | null>(null);const [role, setRole] = useState<string>(ProjectMembershipRole.Member);- const options = useMemo(() => {- const attached = new Set(projectGroups.map((membership) => membership.groupId));- return orgGroups- .filter((orgGroup) => !attached.has(orgGroup.id))- .map((orgGroup) => ({ value: orgGroup.id, label: orgGroup.name }));- }, [orgGroups, projectGroups]);+ const options = useMemo(+ () => orgGroups.map((orgGroup) => ({ value: orgGroup.id, label: orgGroup.name })),+ [orgGroups]+ );const handleAdd = async () => {try {if (!group) return;- await addMember.mutateAsync({ groupId: group.value, role });- createNotification({ text: `"${group.label}" added`, type: "success" });+ const { skipped } = await addMembers.mutateAsync({ groupIds: [group.value], role });+ createNotification({+ text: skipped.length+ ? `"${group.label}" already has access to Agent Vault`+ : `"${group.label}" added`,+ type: skipped.length ? "info" : "success"+ });setGroup(null);onOpenChange(false);} catch {@@ -96,7 +95,7 @@ export const AddGroupDialog = ({ isOpen, onOpenChange }: Props) => {</Button><Buttonvariant="av"- isPending={addMember.isPending}+ isPending={addMembers.isPending}isDisabled={!group}onClick={handleAdd}>diff --git a/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/GroupsTab.tsx b/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/GroupsTab.tsxindex de38ab4f6e..ea5ce37b5a 100644--- a/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/GroupsTab.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/GroupsTab.tsx@@ -1,4 +1,4 @@-import { useMemo, useState } from "react";+import { useState } from "react";import { MoreHorizontalIcon, PencilIcon, PlusIcon, SearchIcon, Trash2Icon } from "lucide-react";import { ProductRoleBadge } from "@app/components/agent-vault/ProductRoleBadge";@@ -22,6 +22,7 @@ import {InputGroup,InputGroupAddon,InputGroupInput,+ Pagination,Skeleton,Table,TableBody,@@ -32,43 +33,53 @@ import {} from "@app/components/v3";import { ProjectPermissionActions, ProjectPermissionSub } from "@app/context";import {- useListAgentVaultProductGroupMembers,- useRemoveAgentVaultProductMember-} from "@app/hooks/api/agentVault";-import { ProjectMembershipRole } from "@app/hooks/api/roles/types";+ getUserTablePreference,+ PreferenceKey,+ setUserTablePreference+} from "@app/helpers/userTablePreferences";+import { useDebounce, useResetPageHelper, useResetPageOnSearch } from "@app/hooks";+import { useListAgentVaultMembers, useRevokeAgentVaultMembers } from "@app/hooks/api/agentVault";+import { AgentVaultMemberType } from "@app/hooks/api/agentVault/enums";+import { TAgentVaultProductMemberOf } from "@app/hooks/api/agentVault/types";import { AddGroupDialog } from "./AddGroupDialog";import { ProductRoleDialog } from "./ProductRoleDialog";-type TGroupRow = { id: string; name: string; role: string };+type TGroupMember = TAgentVaultProductMemberOf<AgentVaultMemberType.Group>;export const GroupsTab = () => {- const { data: groups = [], isPending } = useListAgentVaultProductGroupMembers();- const removeMember = useRemoveAgentVaultProductMember();-const [search, setSearch] = useState("");- const [isAddOpen, setIsAddOpen] = useState(false);- const [groupToEdit, setGroupToEdit] = useState<TGroupRow | null>(null);- const [groupToRemove, setGroupToRemove] = useState<TGroupRow | null>(null);+ const [debouncedSearch] = useDebounce(search);+ const [page, setPage] = useState(1);+ const [perPage, setPerPage] = useState(() =>+ getUserTablePreference("agentVaultAccessControlTable", PreferenceKey.PerPage, 20)+ );- const rows = useMemo<TGroupRow[]>(() => {- const term = search.trim().toLowerCase();- return groups- .filter((membership) => membership.groupId)- .map((membership) => ({- id: membership.groupId as string,- name: membership.name,- role: membership.role- }))- .filter((row) => row.name.toLowerCase().includes(term));- }, [groups, search]);+ const { data, isPending } = useListAgentVaultMembers({+ actorType: AgentVaultMemberType.Group,+ search: debouncedSearch.trim() || undefined,+ limit: perPage,+ offset: (page - 1) * perPage+ });+ const revokeMembers = useRevokeAgentVaultMembers();++ const rows = data?.members ?? [];+ const totalCount = data?.totalCount ?? 0;+ useResetPageHelper({ totalCount, offset: (page - 1) * perPage, setPage });+ useResetPageOnSearch({ debouncedSearch, setPage });++ const isFiltered = Boolean(debouncedSearch.trim());++ const [isAddOpen, setIsAddOpen] = useState(false);+ const [groupToEdit, setGroupToEdit] = useState<TGroupMember | null>(null);+ const [groupToRemove, setGroupToRemove] = useState<TGroupMember | null>(null);const handleRemove = async () => {try {if (!groupToRemove) return;- await removeMember.mutateAsync({ groupId: groupToRemove.id });+ await revokeMembers.mutateAsync({ groupIds: [groupToRemove.actor.id] });createNotification({- text: `"${groupToRemove.name}" removed`,+ text: `"${groupToRemove.actor.name}" removed`,type: "success"});setGroupToRemove(null);@@ -104,9 +115,11 @@ export const GroupsTab = () => {<CardContent><Empty className="border"><EmptyHeader>- <EmptyTitle>{search ? "No groups match your search" : "No groups yet"}</EmptyTitle>+ <EmptyTitle>+ {isFiltered ? "No groups match your search" : "No groups yet"}+ </EmptyTitle><EmptyDescription>- {search+ {isFiltered? "Try a different search term.": "Add a group to give everyone in it access."}</EmptyDescription>@@ -140,8 +153,8 @@ export const GroupsTab = () => {{!isPending &&rows.map((row) => (<TableRow key={row.id}>- <TableCell isTruncatable className="min-w-32" title={row.name}>- <HighlightText text={row.name} highlight={search} />+ <TableCell isTruncatable className="min-w-32" title={row.actor.name}>+ <HighlightText text={row.actor.name} highlight={debouncedSearch} /></TableCell><TableCell><ProductRoleBadge role={row.role} />@@ -171,14 +184,32 @@ export const GroupsTab = () => {</Table>)}+ {totalCount > 0 && (+ <CardContent className="-mt-5 pt-0">+ <Pagination+ count={totalCount}+ page={page}+ perPage={perPage}+ onChangePage={setPage}+ onChangePerPage={(newPerPage) => {+ setPerPage(newPerPage);+ setPage(1);+ setUserTablePreference(+ "agentVaultAccessControlTable",+ PreferenceKey.PerPage,+ newPerPage+ );+ }}+ />+ </CardContent>+ )}+<AddGroupDialog isOpen={isAddOpen} onOpenChange={setIsAddOpen} /><ProductRoleDialog- isOpen={Boolean(groupToEdit)}+ member={groupToEdit}onOpenChange={() => setGroupToEdit(null)}- subject={groupToEdit?.name ?? ""}- currentRole={groupToEdit?.role ?? ProjectMembershipRole.Member}- actor={groupToEdit ? { groupId: groupToEdit.id } : {}}+ subject={groupToEdit?.actor.name ?? ""}/><DeleteConfirmDialog@@ -186,11 +217,11 @@ export const GroupsTab = () => {onOpenChange={(isOpen) => {if (!isOpen) setGroupToRemove(null);}}- title={`Remove "${groupToRemove?.name ?? ""}"`}+ title={`Remove "${groupToRemove?.actor.name ?? ""}"`}description="Everyone in the group loses Agent Vault access, along with every access bundle granted to the group."- confirmKey={groupToRemove?.name ?? ""}+ confirmKey={groupToRemove?.actor.name ?? ""}confirmLabel="Remove"- isPending={removeMember.isPending}+ isPending={revokeMembers.isPending}onConfirm={handleRemove}/></Card>diff --git a/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/IdentitiesTab.tsx b/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/IdentitiesTab.tsxindex b19aade8e0..2d67e40168 100644--- a/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/IdentitiesTab.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/IdentitiesTab.tsx@@ -1,4 +1,4 @@-import { useMemo, useState } from "react";+import { useState } from "react";import { useQueryClient } from "@tanstack/react-query";import { useNavigate } from "@tanstack/react-router";import {@@ -33,6 +33,7 @@ import {InputGroupAddon,InputGroupInput,OrgIcon,+ Pagination,Skeleton,SubOrgIcon,Table,@@ -48,44 +49,64 @@ import {useOrganization,useProject} from "@app/context";+import {+ getUserTablePreference,+ PreferenceKey,+ setUserTablePreference+} from "@app/helpers/userTablePreferences";+import { useDebounce, useResetPageHelper, useResetPageOnSearch } from "@app/hooks";import {agentVaultKeys,- useListAgentVaultProductIdentityMembers,- useRemoveAgentVaultProductMember+ useListAgentVaultMembers,+ useRevokeAgentVaultMembers} from "@app/hooks/api/agentVault";-import { TAgentVaultProductIdentityMember } from "@app/hooks/api/agentVault/types";+import { AgentVaultMemberType } from "@app/hooks/api/agentVault/enums";+import { TAgentVaultProductMemberOf } from "@app/hooks/api/agentVault/types";import { useDeleteProjectIdentity, useUpdateProjectIdentity } from "@app/hooks/api/projectIdentity";-import { ProjectMembershipRole } from "@app/hooks/api/roles/types";import { CreateProjectIdentitySheet } from "@app/pages/project/AccessControlPage/components/IdentityTab/components/CreateProjectIdentity/CreateProjectIdentitySheet";import { ProductRoleDialog } from "./ProductRoleDialog";+type TMachineIdentityMember = TAgentVaultProductMemberOf<AgentVaultMemberType.MachineIdentity>;+export const IdentitiesTab = () => {const { currentProject } = useProject();const { currentOrg, isSubOrganization } = useOrganization();const navigate = useNavigate();const queryClient = useQueryClient();- const { data: identities = [], isPending } = useListAgentVaultProductIdentityMembers();- const removeMember = useRemoveAgentVaultProductMember();+ const [search, setSearch] = useState("");+ const [debouncedSearch] = useDebounce(search);+ const [page, setPage] = useState(1);+ const [perPage, setPerPage] = useState(() =>+ getUserTablePreference("agentVaultAccessControlTable", PreferenceKey.PerPage, 20)+ );++ const { data, isPending } = useListAgentVaultMembers({+ actorType: AgentVaultMemberType.MachineIdentity,+ search: debouncedSearch.trim() || undefined,+ limit: perPage,+ offset: (page - 1) * perPage+ });+ const revokeMembers = useRevokeAgentVaultMembers();const deleteIdentity = useDeleteProjectIdentity();const updateIdentity = useUpdateProjectIdentity();- const [search, setSearch] = useState("");- const [isAddOpen, setIsAddOpen] = useState(false);- const [toEdit, setToEdit] = useState<TAgentVaultProductIdentityMember | null>(null);- const [toRemove, setToRemove] = useState<TAgentVaultProductIdentityMember | null>(null);+ const filtered = data?.members ?? [];+ const totalCount = data?.totalCount ?? 0;+ useResetPageHelper({ totalCount, offset: (page - 1) * perPage, setPage });+ useResetPageOnSearch({ debouncedSearch, setPage });- const filtered = useMemo(() => {- const term = search.trim().toLowerCase();- return identities.filter((identity) => identity.name.toLowerCase().includes(term));- }, [identities, search]);+ const isFiltered = Boolean(debouncedSearch.trim());++ const [isAddOpen, setIsAddOpen] = useState(false);+ const [toEdit, setToEdit] = useState<TMachineIdentityMember | null>(null);+ const [toRemove, setToRemove] = useState<TMachineIdentityMember | null>(null);// An identity created here is scoped to the Agent Vault project, so detaching it would orphan it.- // Those are deleted outright.- const isAgentVaultManaged = (identity: TAgentVaultProductIdentityMember) =>- identity.identityProjectId === currentProject.id;+ const isAgentVaultManaged = (member: TMachineIdentityMember) =>+ member.actor.isManagedByAgentVault;- const renderManagedByBadge = (identity: TAgentVaultProductIdentityMember) => {+ const renderManagedByBadge = (identity: TMachineIdentityMember) => {if (isAgentVaultManaged(identity)) {return (<Badge variant="av">@@ -94,7 +115,7 @@ export const IdentitiesTab = () => {</Badge>);}- if (isSubOrganization && currentOrg.id === identity.identityOrgId) {+ if (isSubOrganization && currentOrg.id === identity.actor.orgId) {return (<Badge variant="sub-org"><SubOrgIcon />@@ -112,24 +133,24 @@ export const IdentitiesTab = () => {const handleRemove = async () => {try {- if (!toRemove?.identityId) return;+ if (!toRemove) return;if (isAgentVaultManaged(toRemove)) {// Identities are created here with delete protection on, which the delete endpoint refuses.await updateIdentity.mutateAsync({- identityId: toRemove.identityId,+ identityId: toRemove.actor.id,projectId: currentProject.id,hasDeleteProtection: false});await deleteIdentity.mutateAsync({- identityId: toRemove.identityId,+ identityId: toRemove.actor.id,projectId: currentProject.id});- queryClient.invalidateQueries({ queryKey: agentVaultKeys.productMembers(currentOrg.id) });- createNotification({ text: `"${toRemove.name}" deleted`, type: "success" });+ queryClient.invalidateQueries({ queryKey: agentVaultKeys.members(currentOrg.id) });+ createNotification({ text: `"${toRemove.actor.name}" deleted`, type: "success" });} else {- await removeMember.mutateAsync({ identityId: toRemove.identityId });- createNotification({ text: `"${toRemove.name}" removed`, type: "success" });+ await revokeMembers.mutateAsync({ machineIdentityIds: [toRemove.actor.id] });+ createNotification({ text: `"${toRemove.actor.name}" removed`, type: "success" });}setToRemove(null);@@ -169,10 +190,12 @@ export const IdentitiesTab = () => {<Empty className="border"><EmptyHeader><EmptyTitle>- {search ? "No machine identities match your search" : "No machine identities yet"}+ {isFiltered+ ? "No machine identities match your search"+ : "No machine identities yet"}</EmptyTitle><EmptyDescription>- {search+ {isFiltered? "Try a different search term.": "Add a machine identity to give it access."}</EmptyDescription>@@ -207,18 +230,17 @@ export const IdentitiesTab = () => {{!isPending &&filtered.map((identity) => (<TableRow- key={identity.membershipId}- className={identity.identityId ? "cursor-pointer" : undefined}+ key={identity.id}+ className="cursor-pointer"onClick={() => {- if (!identity.identityId) return;navigate({to: "/organizations/$orgId/agent-vault/identities/$identityId",- params: { orgId: currentOrg.id, identityId: identity.identityId }+ params: { orgId: currentOrg.id, identityId: identity.actor.id }});}}>- <TableCell isTruncatable className="min-w-32" title={identity.name}>- <HighlightText text={identity.name} highlight={search} />+ <TableCell isTruncatable className="min-w-32" title={identity.actor.name}>+ <HighlightText text={identity.actor.name} highlight={debouncedSearch} /></TableCell><TableCell><ProductRoleBadge role={identity.role} />@@ -249,14 +271,32 @@ export const IdentitiesTab = () => {</Table>)}+ {totalCount > 0 && (+ <CardContent className="-mt-5 pt-0">+ <Pagination+ count={totalCount}+ page={page}+ perPage={perPage}+ onChangePage={setPage}+ onChangePerPage={(newPerPage) => {+ setPerPage(newPerPage);+ setPage(1);+ setUserTablePreference(+ "agentVaultAccessControlTable",+ PreferenceKey.PerPage,+ newPerPage+ );+ }}+ />+ </CardContent>+ )}+<CreateProjectIdentitySheet isOpen={isAddOpen} onOpenChange={setIsAddOpen} /><ProductRoleDialog- isOpen={Boolean(toEdit)}+ member={toEdit}onOpenChange={() => setToEdit(null)}- subject={toEdit?.name ?? ""}- currentRole={toEdit?.role ?? ProjectMembershipRole.Member}- actor={toEdit?.identityId ? { identityId: toEdit.identityId } : {}}+ subject={toEdit?.actor.name ?? ""}/><DeleteConfirmDialog@@ -266,17 +306,17 @@ export const IdentitiesTab = () => {}}title={toRemove && isAgentVaultManaged(toRemove)- ? `Delete "${toRemove.name}"`- : `Remove "${toRemove?.name ?? ""}"`+ ? `Delete "${toRemove.actor.name}"`+ : `Remove "${toRemove?.actor.name ?? ""}"`}description={toRemove && isAgentVaultManaged(toRemove)? "This machine identity is managed by Agent Vault. Deleting it removes the identity along with its access. This cannot be undone.": "It loses Agent Vault access, along with every access bundle granted to it. The machine identity won't be deleted because it isn't managed by Agent Vault."}- confirmKey={toRemove?.name ?? ""}+ confirmKey={toRemove?.actor.name ?? ""}confirmLabel={toRemove && isAgentVaultManaged(toRemove) ? "Delete" : "Remove"}- isPending={removeMember.isPending || updateIdentity.isPending || deleteIdentity.isPending}+ isPending={revokeMembers.isPending || updateIdentity.isPending || deleteIdentity.isPending}onConfirm={handleRemove}/></Card>diff --git a/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/InviteMembersDialog.tsx b/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/InviteMembersDialog.tsxindex 6cd0e573bb..2337ac153b 100644--- a/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/InviteMembersDialog.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/InviteMembersDialog.tsx@@ -19,10 +19,8 @@ import {} from "@app/components/v3";import { useOrganization } from "@app/context";import { useGetOrgUsers } from "@app/hooks/api";-import {- useAddAgentVaultProductUserMembers,- useListAgentVaultProductUserMembers-} from "@app/hooks/api/agentVault";+import { useAddAgentVaultMembers, useListAgentVaultMembers } from "@app/hooks/api/agentVault";+import { AgentVaultMemberType } from "@app/hooks/api/agentVault/enums";import { ProjectMembershipRole } from "@app/hooks/api/roles/types";import { getRequesterStatus } from "@app/lib/fn/requesterStatus";@@ -38,31 +36,34 @@ type Props = {export const InviteMembersDialog = ({ isOpen, onOpenChange }: Props) => {const { currentOrg } = useOrganization();const { data: orgUsers = [] } = useGetOrgUsers(currentOrg.id);- const { data: projectUsers = [] } = useListAgentVaultProductUserMembers();- const addMembers = useAddAgentVaultProductUserMembers();+ const addMembers = useAddAgentVaultMembers();const navigate = useNavigate({ from: "" });const requesterEmail = useSearch({strict: false,select: (el) => (el as { requesterEmail?: string })?.requesterEmail});+ // A page, not one row: the search is a substring match, so another member can outrank the requester.+ // One buried under twenty still falls through, costing an add the server reports as already a member.+ const { data: requesterMatch } = useListAgentVaultMembers(+ { actorType: AgentVaultMemberType.User, search: requesterEmail, limit: 20 },+ Boolean(requesterEmail)+ );+const [selected, setSelected] = useState<TCandidate[]>([]);const [role, setRole] = useState<string>(ProjectMembershipRole.Member);const candidates = useMemo(() => {- const attached = new Set(projectUsers.map((member) => member.userId));- return orgUsers- .filter((orgUser) => !attached.has(orgUser.user.id))- .map((orgUser) => {- const name = `${orgUser.user.firstName ?? ""} ${orgUser.user.lastName ?? ""}`.trim();- const email = orgUser.user.email || orgUser.user.username || "";- return { value: orgUser.user.id, label: name || email, email };- });- }, [orgUsers, projectUsers]);+ return orgUsers.map((orgUser) => {+ const name = `${orgUser.user.firstName ?? ""} ${orgUser.user.lastName ?? ""}`.trim();+ const email = orgUser.user.email || orgUser.user.username || "";+ return { value: orgUser.user.id, label: name || email, email };+ });+ }, [orgUsers]);const memberUsernames = useMemo(- () => new Set(projectUsers.map((member) => member.username)),- [projectUsers]+ () => new Set((requesterMatch?.members ?? []).map((member) => member.actor.username)),+ [requesterMatch]);const requesterStatus = useMemo(@@ -107,14 +108,16 @@ export const InviteMembersDialog = ({ isOpen, onOpenChange }: Props) => {addMembers.mutate({userIds: selected.map((candidate) => candidate.value),- emails: [],role},{- onSuccess: ({ members }) => {+ onSuccess: ({ members, skipped }) => {+ const addedText = `${members.length} user${members.length === 1 ? "" : "s"} added`;createNotification({- text: `${members.length} user${members.length === 1 ? "" : "s"} added`,- type: "success"+ text: members.length+ ? `${addedText}${skipped.length ? `. ${skipped.length} already had access.` : ""}`+ : `${skipped.length === 1 ? "That user already has" : `All ${skipped.length} already have`} access to Agent Vault`,+ type: members.length ? "success" : "info"});handleClose();}diff --git a/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/MembersTab.tsx b/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/MembersTab.tsxindex 7afecc82dd..eb961a51da 100644--- a/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/MembersTab.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/MembersTab.tsx@@ -1,7 +1,8 @@-import { useEffect, useMemo, useState } from "react";+import { useEffect, useState } from "react";import { useSearch } from "@tanstack/react-router";import { MoreHorizontalIcon, PencilIcon, PlusIcon, SearchIcon, Trash2Icon } from "lucide-react";+import { memberDisplayName } from "@app/components/agent-vault/MemberName";import { PendingInvitationBadge } from "@app/components/agent-vault/PendingInvitationBadge";import { ProductRoleBadge } from "@app/components/agent-vault/ProductRoleBadge";import { createNotification } from "@app/components/notifications";@@ -24,6 +25,7 @@ import {InputGroup,InputGroupAddon,InputGroupInput,+ Pagination,Skeleton,Table,TableBody,@@ -40,30 +42,48 @@ import {useUser} from "@app/context";import {- useListAgentVaultProductUserMembers,- useRemoveAgentVaultProductMember-} from "@app/hooks/api/agentVault";-import { TAgentVaultProductUserMember } from "@app/hooks/api/agentVault/types";-import { ProjectMembershipRole } from "@app/hooks/api/roles/types";+ getUserTablePreference,+ PreferenceKey,+ setUserTablePreference+} from "@app/helpers/userTablePreferences";+import { useDebounce, useResetPageHelper, useResetPageOnSearch } from "@app/hooks";+import { useListAgentVaultMembers, useRevokeAgentVaultMembers } from "@app/hooks/api/agentVault";+import { AgentVaultMemberType } from "@app/hooks/api/agentVault/enums";+import { TAgentVaultProductMemberOf } from "@app/hooks/api/agentVault/types";import { InviteMembersDialog } from "./InviteMembersDialog";import { ProductRoleDialog } from "./ProductRoleDialog";-const fullName = (member: TAgentVaultProductUserMember) =>- `${member.firstName ?? ""} ${member.lastName ?? ""}`.trim();--const displayName = (member: TAgentVaultProductUserMember) =>- fullName(member) || member.username || member.email || "";+type TUserMember = TAgentVaultProductMemberOf<AgentVaultMemberType.User>;export const MembersTab = () => {const { user } = useUser();- const { data: members = [], isPending } = useListAgentVaultProductUserMembers();- const removeMember = useRemoveAgentVaultProductMember();const [search, setSearch] = useState("");+ const [debouncedSearch] = useDebounce(search);+ const [page, setPage] = useState(1);+ const [perPage, setPerPage] = useState(() =>+ getUserTablePreference("agentVaultAccessControlTable", PreferenceKey.PerPage, 20)+ );++ const { data, isPending } = useListAgentVaultMembers({+ actorType: AgentVaultMemberType.User,+ search: debouncedSearch.trim() || undefined,+ limit: perPage,+ offset: (page - 1) * perPage+ });+ const revokeMembers = useRevokeAgentVaultMembers();++ const filtered = data?.members ?? [];+ const totalCount = data?.totalCount ?? 0;+ useResetPageHelper({ totalCount, offset: (page - 1) * perPage, setPage });+ useResetPageOnSearch({ debouncedSearch, setPage });++ const isFiltered = Boolean(debouncedSearch.trim());+const [isInviteOpen, setIsInviteOpen] = useState(false);- const [memberToEdit, setMemberToEdit] = useState<TAgentVaultProductUserMember | null>(null);- const [memberToRemove, setMemberToRemove] = useState<TAgentVaultProductUserMember | null>(null);+ const [memberToEdit, setMemberToEdit] = useState<TUserMember | null>(null);+ const [memberToRemove, setMemberToRemove] = useState<TUserMember | null>(null);const { permission } = useProjectPermission();const canAddMembers = permission.can(@@ -80,22 +100,12 @@ export const MembersTab = () => {if (requesterEmail && canAddMembers) setIsInviteOpen(true);}, [requesterEmail, canAddMembers]);- const filtered = useMemo(() => {- const term = search.trim().toLowerCase();- if (!term) return members;- return members.filter(- (member) =>- displayName(member).toLowerCase().includes(term) ||- (member.email ?? "").toLowerCase().includes(term)- );- }, [members, search]);-const handleRemove = async () => {try {- if (!memberToRemove?.userId) return;- await removeMember.mutateAsync({ userId: memberToRemove.userId });+ if (!memberToRemove) return;+ await revokeMembers.mutateAsync({ userIds: [memberToRemove.actor.id] });createNotification({- text: `${displayName(memberToRemove)} removed`,+ text: `${memberDisplayName(memberToRemove.actor)} removed`,type: "success"});setMemberToRemove(null);@@ -131,9 +141,9 @@ export const MembersTab = () => {<CardContent><Empty className="border"><EmptyHeader>- <EmptyTitle>{search ? "No users match your search" : "No users yet"}</EmptyTitle>+ <EmptyTitle>{isFiltered ? "No users match your search" : "No users yet"}</EmptyTitle><EmptyDescription>- {search ? "Try a different search term." : "Add users to give them access."}+ {isFiltered ? "Try a different search term." : "Add users to give them access."}</EmptyDescription></EmptyHeader></Empty>@@ -167,14 +177,16 @@ export const MembersTab = () => {))}{!isPending &&filtered.map((member) => {- const isSelf = member.userId === user?.id;- const name = fullName(member);+ const isSelf = member.actor.id === user?.id;+ const name = [member.actor.firstName, member.actor.lastName]+ .filter(Boolean)+ .join(" ");return (- <TableRow key={member.membershipId}>+ <TableRow key={member.id}><TableCell isTruncatable className="min-w-32" title={name || undefined}>{name ? (- <HighlightText text={name} highlight={search} />+ <HighlightText text={name} highlight={debouncedSearch} />) : (<span className="text-muted">—</span>)}@@ -182,16 +194,19 @@ export const MembersTab = () => {<TableCellisTruncatableclassName="min-w-32 text-sm"- title={member.email || member.username}+ title={member.actor.email || member.actor.username}>- <HighlightText text={member.email || member.username} highlight={search} />+ <HighlightText+ text={member.actor.email || member.actor.username}+ highlight={debouncedSearch}+ /></TableCell><TableCell><ProductRoleBadge role={member.role} /></TableCell><TableCell variant="action"><div className="flex items-center justify-end gap-2">- <PendingInvitationBadge isPending={member.isOrgMembershipPending} />+ <PendingInvitationBadge isPending={member.actor.isOrgMembershipPending} />{!isSelf && (<DropdownMenu><DropdownMenuTrigger asChild>@@ -223,14 +238,32 @@ export const MembersTab = () => {</Table>)}+ {totalCount > 0 && (+ <CardContent className="-mt-5 pt-0">+ <Pagination+ count={totalCount}+ page={page}+ perPage={perPage}+ onChangePage={setPage}+ onChangePerPage={(newPerPage) => {+ setPerPage(newPerPage);+ setPage(1);+ setUserTablePreference(+ "agentVaultAccessControlTable",+ PreferenceKey.PerPage,+ newPerPage+ );+ }}+ />+ </CardContent>+ )}+<InviteMembersDialog isOpen={isInviteOpen} onOpenChange={setIsInviteOpen} /><ProductRoleDialog- isOpen={Boolean(memberToEdit)}+ member={memberToEdit}onOpenChange={() => setMemberToEdit(null)}- subject={memberToEdit ? displayName(memberToEdit) : ""}- currentRole={memberToEdit?.role ?? ProjectMembershipRole.Member}- actor={memberToEdit?.userId ? { userId: memberToEdit.userId } : {}}+ subject={memberToEdit ? memberDisplayName(memberToEdit.actor) : ""}/><DeleteConfirmDialog@@ -238,11 +271,11 @@ export const MembersTab = () => {onOpenChange={(isOpen) => {if (!isOpen) setMemberToRemove(null);}}- title={`Remove "${memberToRemove ? displayName(memberToRemove) : ""}"`}+ title={`Remove "${memberToRemove ? memberDisplayName(memberToRemove.actor) : ""}"`}description="They lose every access bundle granted to them. Any active session they hold stops reaching its hosts at the next proxy poll."- confirmKey={memberToRemove ? displayName(memberToRemove) : ""}+ confirmKey={memberToRemove ? memberDisplayName(memberToRemove.actor) : ""}confirmLabel="Remove"- isPending={removeMember.isPending}+ isPending={revokeMembers.isPending}onConfirm={handleRemove}/></Card>diff --git a/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/ProductRoleDialog.tsx b/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/ProductRoleDialog.tsxindex 9257726c58..3c7398509c 100644--- a/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/ProductRoleDialog.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/ProductRoleDialog.tsx@@ -13,30 +13,32 @@ import {FieldContent,FieldLabel} from "@app/components/v3";-import { useUpdateAgentVaultProductMemberRole } from "@app/hooks/api/agentVault";-import { TAgentVaultProductMemberActor } from "@app/hooks/api/agentVault/types";+import { useUpdateAgentVaultMemberRole } from "@app/hooks/api/agentVault";+import { TAgentVaultProductMember } from "@app/hooks/api/agentVault/types";+import { ProjectMembershipRole } from "@app/hooks/api/roles/types";import { ProductRoleField } from "./ProductRoleField";type Props = {- isOpen: boolean;+ member: Pick<TAgentVaultProductMember, "role" | "actor"> | null;onOpenChange: (isOpen: boolean) => void;subject: string;- currentRole: string;- actor: TAgentVaultProductMemberActor;};-export const ProductRoleDialog = ({ isOpen, onOpenChange, subject, currentRole, actor }: Props) => {- const updateRole = useUpdateAgentVaultProductMemberRole();+export const ProductRoleDialog = ({ member, onOpenChange, subject }: Props) => {+ const updateRole = useUpdateAgentVaultMemberRole();+ const currentRole = member?.role ?? ProjectMembershipRole.Member;const [role, setRole] = useState(currentRole);useEffect(() => {- if (isOpen) setRole(currentRole);- }, [isOpen, currentRole]);+ if (member) setRole(member.role);+ }, [member]);const handleSave = async () => {try {- await updateRole.mutateAsync({ ...actor, role });+ // Guarded here, not by returning null, so the exit animation still runs.+ if (!member) return;+ await updateRole.mutateAsync({ actor: member.actor, role });createNotification({text: `${subject} is now ${role === "admin" ? "an Admin" : "a Member"}`,type: "success"@@ -48,7 +50,7 @@ export const ProductRoleDialog = ({ isOpen, onOpenChange, subject, currentRole,};return (- <Dialog open={isOpen} onOpenChange={onOpenChange}>+ <Dialog open={Boolean(member)} onOpenChange={onOpenChange}><DialogContent><DialogHeader><DialogTitle>Change Role</DialogTitle>diff --git a/frontend/src/pages/agent-vault/AgentVaultProxiesPage/AgentVaultProxiesPage.tsx b/frontend/src/pages/agent-vault/AgentVaultProxiesPage/AgentVaultProxiesPage.tsxindex cc56e8507c..fd2bcca0b7 100644--- a/frontend/src/pages/agent-vault/AgentVaultProxiesPage/AgentVaultProxiesPage.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultProxiesPage/AgentVaultProxiesPage.tsx@@ -1,4 +1,4 @@-import { ReactNode, useMemo, useState } from "react";+import { ReactNode, useState } from "react";import { Helmet } from "react-helmet";import { useTranslation } from "react-i18next";import { format } from "date-fns";@@ -46,6 +46,7 @@ import {EmptyTitle,IconButton,PageHeader,+ Pagination,Skeleton,Table,TableBody,@@ -58,6 +59,12 @@ import {TooltipTrigger} from "@app/components/v3";import { useProjectPermission } from "@app/context";+import {+ getUserTablePreference,+ PreferenceKey,+ setUserTablePreference+} from "@app/helpers/userTablePreferences";+import { useResetPageHelper } from "@app/hooks";import {AgentVaultTrafficPolicy,useDeleteAgentVaultProxy,@@ -123,15 +130,9 @@ const HeadWithHint = ({ hint, children }: { hint: string; children: ReactNode })enum SortColumn {Name = "name",- Created = "created"+ Created = "createdAt"}-const SORT_COMPARATORS: Record<SortColumn, (a: TAgentVaultProxy, b: TAgentVaultProxy) => number> = {- [SortColumn.Name]: (a, b) => a.name.localeCompare(b.name),- [SortColumn.Created]: (a, b) =>- new Date(a.createdAt ?? 0).getTime() - new Date(b.createdAt ?? 0).getTime()-};-const truncateFingerprint = (fingerprint: string) =>`${fingerprint.split(":").slice(0, 5).join(":")}…`;@@ -140,7 +141,23 @@ export const AgentVaultProxiesPage = () => {const { hasProjectRole } = useProjectPermission();const isAdmin = hasProjectRole(ProjectMembershipRole.Admin);- const { data: proxies, isPending } = useListAgentVaultProxies();+ const [sortColumn, setSortColumn] = useState(SortColumn.Created);+ const [sortDirection, setSortDirection] = useState<"ascending" | "descending">("descending");+ const [page, setPage] = useState(1);+ const [perPage, setPerPage] = useState(() =>+ getUserTablePreference("agentVaultProxiesTable", PreferenceKey.PerPage, 20)+ );++ const { data, isPending } = useListAgentVaultProxies({+ orderBy: sortColumn,+ orderDirection: sortDirection === "ascending" ? "asc" : "desc",+ limit: perPage,+ offset: (page - 1) * perPage+ });++ const displayed = data?.proxies ?? [];+ const totalCount = data?.totalCount ?? 0;+ useResetPageHelper({ totalCount, offset: (page - 1) * perPage, setPage });const deleteProxy = useDeleteAgentVaultProxy();const revokeProxy = useRevokeAgentVaultProxyAccess();const reissueToken = useReissueAgentVaultProxyEnrollmentToken();@@ -151,15 +168,9 @@ export const AgentVaultProxiesPage = () => {const [proxyToRevoke, setProxyToRevoke] = useState<TAgentVaultProxy | null>(null);const [proxyToReissue, setProxyToReissue] = useState<TAgentVaultProxy | null>(null);const [enrollment, setEnrollment] = useState<TAgentVaultEnrollment | null>(null);- const [sortColumn, setSortColumn] = useState(SortColumn.Created);- const [sortDirection, setSortDirection] = useState<"ascending" | "descending">("descending");-- const displayed = useMemo(() => {- const ordered = [...(proxies ?? [])].sort(SORT_COMPARATORS[sortColumn]);- return sortDirection === "ascending" ? ordered : ordered.reverse();- }, [proxies, sortColumn, sortDirection]);const handleSort = (column: SortColumn, direction: "ascending" | "descending" | "none") => {+ setPage(1);if (direction === "none") {setSortColumn(SortColumn.Created);setSortDirection("descending");@@ -240,7 +251,7 @@ export const AgentVaultProxiesPage = () => {)}</CardHeader>- {!isPending && (proxies?.length ?? 0) === 0 ? (+ {!isPending && totalCount === 0 ? (<CardContent><Empty className="border"><EmptyHeader>@@ -392,6 +403,22 @@ export const AgentVaultProxiesPage = () => {</TableBody></Table>)}++ {totalCount > 0 && (+ <CardContent className="-mt-5 pt-0">+ <Pagination+ count={totalCount}+ page={page}+ perPage={perPage}+ onChangePage={setPage}+ onChangePerPage={(newPerPage) => {+ setPerPage(newPerPage);+ setPage(1);+ setUserTablePreference("agentVaultProxiesTable", PreferenceKey.PerPage, newPerPage);+ }}+ />+ </CardContent>+ )}</Card><ProxyFormDialogdiff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/AgentVaultSessionsPage.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/AgentVaultSessionsPage.tsxindex 835fbac681..8d0fd0ed13 100644--- a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/AgentVaultSessionsPage.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/AgentVaultSessionsPage.tsx@@ -107,7 +107,7 @@ export const AgentVaultSessionsPage = () => {limit: perPage,offset: (page - 1) * perPage});- const { data: accessBundles } = useListAgentVaultAccessBundles();+ const { data: accessBundles } = useListAgentVaultAccessBundles({ limit: 1 });const sessions = data?.sessions ?? [];const totalCount = data?.totalCount ?? 0;@@ -117,7 +117,7 @@ export const AgentVaultSessionsPage = () => {// The debounced term, not the typed one: the rows on screen were fetched with this, so keying the copy// off the live input would caption a stale result set.const isFiltered = Boolean(debouncedSearch.trim()) || statusFilter !== ALL_STATUSES;- const hasReachableBundles = (accessBundles?.length ?? 0) > 0;+ const hasReachableBundles = (accessBundles?.totalCount ?? 0) > 0;let emptyTitle: string;let emptyDescription: string;@@ -352,7 +352,6 @@ export const AgentVaultSessionsPage = () => {)}{totalCount > 0 && (- // The card lays its children out with gap-5, which reads as a gap under the table.<CardContent className="-mt-5 pt-0"><Paginationcount={totalCount}diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/CreateSessionDialog.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/CreateSessionDialog.tsxindex 82674bc5f6..ac02cd7a15 100644--- a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/CreateSessionDialog.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/CreateSessionDialog.tsx@@ -25,7 +25,7 @@ import {SelectTrigger,SelectValue} from "@app/components/v3";-import { useDiscardChangesGuard } from "@app/hooks";+import { useDebounce, useDiscardChangesGuard } from "@app/hooks";import {useCreateAgentVaultSession,useListAgentVaultAccessBundles@@ -73,7 +73,14 @@ type Props = {};export const CreateSessionDialog = ({ isOpen, onOpenChange, onCreated }: Props) => {- const { data: accessBundles } = useListAgentVaultAccessBundles();+ const [bundleSearch, setBundleSearch] = useState("");+ const [debouncedBundleSearch] = useDebounce(bundleSearch);+ const { data: accessBundles, isFetching: isSearchingBundles } = useListAgentVaultAccessBundles({+ search: debouncedBundleSearch.trim() || undefined,+ orderBy: "name",+ orderDirection: "asc",+ limit: 50+ });const createSession = useCreateAgentVaultSession();const [selectedBundle, setSelectedBundle] = useState<TAgentVaultAccessBundleListItem | null>(@@ -144,8 +151,12 @@ export const CreateSessionDialog = ({ isOpen, onOpenChange, onCreated }: Props)<FieldContent><Comboboxid="agent-vault-session-bundle"- options={accessBundles ?? []}+ options={accessBundles?.accessBundles ?? []}value={selectedBundle}+ shouldFilter={false}+ isLoading={isSearchingBundles}+ includeMissingSelectedOptions+ onInputValueChange={setBundleSearch}getOptionValue={(bundle) => bundle.id}getOptionLabel={(bundle) => bundle.name}placeholder="Pick an access bundle"diff --git a/frontend/src/pages/agent-vault/agent-vault-docs-urls.ts b/frontend/src/pages/agent-vault/agent-vault-docs-urls.tsindex b6f685faaa..5fecdac389 100644--- a/frontend/src/pages/agent-vault/agent-vault-docs-urls.ts+++ b/frontend/src/pages/agent-vault/agent-vault-docs-urls.ts@@ -4,6 +4,7 @@ export const AgentVaultDocsUrls = {overview: `${AGENT_VAULT_DOCS_BASE_URL}/overview`,quickstart: `${AGENT_VAULT_DOCS_BASE_URL}/quickstart`,accessBundles: `${AGENT_VAULT_DOCS_BASE_URL}/access-bundles`,+ services: `${AGENT_VAULT_DOCS_BASE_URL}/services`,sessions: `${AGENT_VAULT_DOCS_BASE_URL}/sessions`,proxies: `${AGENT_VAULT_DOCS_BASE_URL}/proxies`} as const;diff --git a/frontend/src/pages/project/AccessControlPage/components/IdentityTab/components/CreateProjectIdentity/CreateProjectIdentityForm.tsx b/frontend/src/pages/project/AccessControlPage/components/IdentityTab/components/CreateProjectIdentity/CreateProjectIdentityForm.tsxindex 5ca54067ff..4630c1882c 100644--- a/frontend/src/pages/project/AccessControlPage/components/IdentityTab/components/CreateProjectIdentity/CreateProjectIdentityForm.tsx+++ b/frontend/src/pages/project/AccessControlPage/components/IdentityTab/components/CreateProjectIdentity/CreateProjectIdentityForm.tsx@@ -31,7 +31,7 @@ import {useListProjectIdentityMemberships,useUpdateProjectIdentityMembership} from "@app/hooks/api";-import { agentVaultKeys, useAddAgentVaultProductMember } from "@app/hooks/api/agentVault";+import { agentVaultKeys, useAddAgentVaultMembers } from "@app/hooks/api/agentVault";import { UNIVERSAL_AUTH_DEFAULTS, useAddIdentityUniversalAuth } from "@app/hooks/api/identities";import { pamKeys, useAddPamProductIdentityMember } from "@app/hooks/api/pam";import { ProjectType } from "@app/hooks/api/projects/types";@@ -162,7 +162,7 @@ export const CreateProjectIdentityForm = ({const { mutateAsync: updateMembership } = useUpdateProjectIdentityMembership();const { mutateAsync: createMembership } = useCreateProjectIdentityMembership();const { mutateAsync: addPamProductIdentityMember } = useAddPamProductIdentityMember();- const { mutateAsync: addAgentVaultProductMember } = useAddAgentVaultProductMember();+ const { mutateAsync: addAgentVaultMembers } = useAddAgentVaultMembers();const { mutateAsync: addUniversalAuth } = useAddIdentityUniversalAuth();const { mutateAsync: createAdditionalPrivilege } = useCreateIdentityProjectAdditionalPrivilege();@@ -209,7 +209,7 @@ export const CreateProjectIdentityForm = ({role: data.role.slug});} else if (isAgentVault) {- await addAgentVaultProductMember({ identityId, role: data.role.slug });+ await addAgentVaultMembers({ machineIdentityIds: [identityId], role: data.role.slug });} else {await createMembership({projectId,@@ -224,7 +224,7 @@ export const CreateProjectIdentityForm = ({queryClient.invalidateQueries({ queryKey: pamKeys.productIdentities() });}if (isAgentVault) {- queryClient.invalidateQueries({ queryKey: agentVaultKeys.productMembers(currentOrg.id) });+ queryClient.invalidateQueries({ queryKey: agentVaultKeys.members(currentOrg.id) });}const hasTemplateGrants = data.templateIds.length > 0;diff --git a/frontend/src/pages/project/IdentityDetailsByIDPage/IdentityDetailsByIDPage.tsx b/frontend/src/pages/project/IdentityDetailsByIDPage/IdentityDetailsByIDPage.tsxindex cc318f3096..196cc17ea2 100644--- a/frontend/src/pages/project/IdentityDetailsByIDPage/IdentityDetailsByIDPage.tsx+++ b/frontend/src/pages/project/IdentityDetailsByIDPage/IdentityDetailsByIDPage.tsx@@ -60,7 +60,7 @@ import {useDeleteProjectIdentityMembership,useGetProjectIdentityMembershipV2} from "@app/hooks/api";-import { useRemoveAgentVaultProductMember } from "@app/hooks/api/agentVault";+import { useRevokeAgentVaultMembers } from "@app/hooks/api/agentVault";import { ActorType } from "@app/hooks/api/auditLogs/enums";import { useRemovePamProductIdentityMember } from "@app/hooks/api/pam";import { projectIdentityQuery, useDeleteProjectIdentity } from "@app/hooks/api/projectIdentity";@@ -91,7 +91,7 @@ const Page = () => {const { mutateAsync: removeIdentityMutateAsync } = useDeleteProjectIdentityMembership();const { mutateAsync: removePamIdentityMutateAsync } = useRemovePamProductIdentityMember();- const { mutateAsync: removeAgentVaultIdentityMutateAsync } = useRemoveAgentVaultProductMember();+ const { mutateAsync: revokeAgentVaultMembers } = useRevokeAgentVaultMembers();const isProjectIdentity = Boolean(identityMembershipDetails?.identity.projectId);const isCertManager = currentProject?.type === ProjectType.CertificateManager;@@ -154,7 +154,7 @@ const Page = () => {} else if (isAgentVault) {// Same reason as PAM: the product route keeps the last-admin guard, emits the Agent Vault event// and reaps the identity's bundle grants, none of which the generic route does.- await removeAgentVaultIdentityMutateAsync({ identityId });+ await revokeAgentVaultMembers({ machineIdentityIds: [identityId] });} else {await removeIdentityMutateAsync({identityId,