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
fix(agent-vault): address Saif's review on personal values
Scott Wilsonb7fce24e2138
diff --git a/backend/e2e-test/routes/v1/agent-vault.spec.ts b/backend/e2e-test/routes/v1/agent-vault.spec.tsindex 86009b140e..a65bebbd15 100644--- a/backend/e2e-test/routes/v1/agent-vault.spec.ts+++ b/backend/e2e-test/routes/v1/agent-vault.spec.ts@@ -3,6 +3,7 @@ import crypto from "node:crypto";import * as x509 from "@peculiar/x509";import { createAwsAppConnection, deleteAwsAppConnection } from "e2e-test/testUtils/app-connections";import { pollUntil } from "e2e-test/testUtils/poll";+import { addUserMembership, createUser, createUserAccessToken, deleteUsers } from "e2e-test/testUtils/users";import { AccessScope, ActionProjectType, OrgMembershipRole, ProjectMembershipRole, ProjectType } from "@app/db/schemas";import { seedData1 } from "@app/db/seed-data";@@ -53,7 +54,7 @@ initLogger();const authHeader = { authorization: `Bearer ${jwtAuthToken}` };-const inject = (method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE", url: string, body?: Record<string, unknown>) =>+const inject = (method: "GET" | "POST" | "PATCH" | "DELETE", url: string, body?: Record<string, unknown>) =>testServer.inject({ method, url, headers: authHeader, ...(body ? { body } : {}) });const createOrgIdentity = async (name: string) => {@@ -235,7 +236,7 @@ const createMemberIdentity = async (name: string) => {return {id: identity.id,- as: (method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE", url: string, body?: Record<string, unknown>) =>+ as: (method: "GET" | "POST" | "PATCH" | "DELETE", url: string, body?: Record<string, unknown>) =>testServer.inject({ method, url, headers: { authorization: `Bearer ${token}` }, ...(body ? { body } : {}) }),cleanup: () => inject("DELETE", `/api/v1/identities/${identity.id}`)};@@ -846,7 +847,7 @@ describe("Agent Vault V1 Router", async () => {};const createVariable = async (body: { key: string; value: string }) => {- const res = await inject("POST", variablesUrl, body);+ const res = await inject("POST", variablesUrl, { scope: "global", ...body });expect(res.statusCode).toBe(200);return (JSON.parse(res.payload) as { variable: { id: string; key: string } }).variable;};@@ -1250,6 +1251,7 @@ describe("Agent Vault V1 Router", async () => {test("no response but the value route carries a value, and that route returns it uncached", async () => {// A client from before every value was secret may still send isSecret: false. It is stripped, not honoured.const createdRes = await inject("POST", variablesUrl, {+ scope: "global",key: "HIDDEN",value: "hidden_value",isSecret: false@@ -1258,7 +1260,7 @@ describe("Agent Vault V1 Router", async () => {expect(createdRes.payload).not.toContain("hidden_value");const hidden = (JSON.parse(createdRes.payload) as { variable: { id: string } }).variable;- const listed = await inject("GET", variablesUrl);+ const listed = await inject("GET", `${variablesUrl}?scope=global`);expect(listed.statusCode).toBe(200);expect(listed.payload).not.toContain("hidden_value");const [listedVariable] = JSON.parse(listed.payload).variables;@@ -1285,7 +1287,7 @@ describe("Agent Vault V1 Router", async () => {});test("a value can't be only spaces, and one with spaces around it is kept as typed", async () => {- const blank = await inject("POST", variablesUrl, { key: "BLANK", value: " " });+ const blank = await inject("POST", variablesUrl, { scope: "global", key: "BLANK", value: " " });expect(blank.statusCode).toBe(422);expect(blank.payload).toContain("A value can't be only spaces.");@@ -1298,10 +1300,14 @@ describe("Agent Vault V1 Router", async () => {test("a key is unique across Agent Vault and has to be upper snake case", async () => {const first = await createVariable({ key: "TOKEN", value: "one" });- const duplicate = await inject("POST", variablesUrl, { key: "TOKEN", value: "two" });+ const duplicate = await inject("POST", variablesUrl, { scope: "global", key: "TOKEN", value: "two" });expect(duplicate.statusCode).toBe(400);expect(JSON.parse(duplicate.payload).message).toBe("A variable named 'TOKEN' already exists.");- expect((await inject("POST", variablesUrl, { key: "lower_case", value: "x" })).statusCode).toBe(422);+ // The variable form puts the message on the Key field by this, not by its wording.+ expect(JSON.parse(duplicate.payload).details).toEqual({ field: "key" });+ expect((await inject("POST", variablesUrl, { scope: "global", key: "lower_case", value: "x" })).statusCode).toBe(+ 422+ );const second = await createVariable({ key: "OTHER", value: "three" });const renamedOnto = await inject("PATCH", `${variablesUrl}/${second.id}`, { key: "TOKEN" });@@ -1398,7 +1404,7 @@ describe("Agent Vault V1 Router", async () => {await expectReferencesMatchSealedText(first.id);await expectReferencesMatchSealedText(second.id);- const listed = JSON.parse((await inject("GET", variablesUrl)).payload) as {+ const listed = JSON.parse((await inject("GET", `${variablesUrl}?scope=global`)).payload) as {variables: { id: string; usedByServices: Record<string, string>[] }[];};expect(listed.variables.find((entry) => entry.id === variable.id)?.usedByServices).toEqual([@@ -1709,7 +1715,7 @@ describe("Agent Vault V1 Router", async () => {0);- const listed = JSON.parse((await inject("GET", variablesUrl)).payload) as {+ const listed = JSON.parse((await inject("GET", `${variablesUrl}?scope=global`)).payload) as {variables: { id: string; usedByServices: unknown[] }[];};expect(listed.variables).toEqual([@@ -1762,14 +1768,21 @@ describe("Agent Vault V1 Router", async () => {{ variableId: variable.id, key: "TOKEN", field: "credential-value" }]);- const listed = await member.asIdentity("GET", variablesUrl);+ const listed = await member.asIdentity("GET", `${variablesUrl}?scope=global`);expect(listed.statusCode).toBe(403);expect(listed.payload).not.toContain("admin_only_value");expect(listed.payload).not.toContain("TOKEN");+ // Without a scope a member gets what they can see, which is only their own.+ const everything = await member.asIdentity("GET", variablesUrl);+ expect(everything.statusCode).toBe(200);+ expect(JSON.parse(everything.payload)).toEqual({ variables: [], totalCount: 0 });// By id, a global variable reads to a member like one that does not exist, as another member's personal one does.expect((await member.asIdentity("GET", `${variablesUrl}/${variable.id}/value`)).statusCode).toBe(404);expect((await member.asIdentity("DELETE", `${variablesUrl}/${variable.id}`)).statusCode).toBe(404);- expect((await member.asIdentity("POST", variablesUrl, { key: "MINE", value: "x" })).statusCode).toBe(403);+ expect(+ (await member.asIdentity("POST", variablesUrl, { scope: "global", key: "MINE", value: "x" })).statusCode+ ).toBe(403);+ expect((await member.asIdentity("POST", variablesUrl, { key: "MINE", value: "x" })).statusCode).toBe(422);} finally {await deleteUaIdentity(member.id);}@@ -1872,9 +1885,11 @@ describe("Agent Vault V1 Router", async () => {const res = await as("GET", "/api/v1/agent-vault/access-bundles?requiresSetup=true&limit=100");expect(res.statusCode).toBe(200);const { accessBundles } = JSON.parse(res.payload) as {- accessBundles: { id: string; servicesRequiringSetup: string[] }[];+ accessBundles: { id: string; servicesRequiringSetup: { id: string; name: string }[] }[];};- return new Map(accessBundles.map((bundle) => [bundle.id, bundle.servicesRequiringSetup]));+ return new Map(+ accessBundles.map((bundle) => [bundle.id, bundle.servicesRequiringSetup.map((service) => service.name)])+ );};const setValues = (@@ -1919,6 +1934,18 @@ describe("Agent Vault V1 Router", async () => {fields: [expect.objectContaining({ field: "credential-value", isSet: false })]});expect((await pendingOf(member.as)).get(bundle.id)).toEqual(["datadog"]);+ // Each entry carries the service id, which is what saving the values needs.+ const pending = await member.as("GET", "/api/v1/agent-vault/access-bundles?requiresSetup=true");+ expect(+ (+ JSON.parse(pending.payload) as { accessBundles: { id: string; servicesRequiringSetup: unknown[] }[] }+ ).accessBundles.find((listed) => listed.id === bundle.id)?.servicesRequiringSetup+ ).toEqual([{ id: service.id, name: "datadog" }]);+ // false is the rest of what the caller reaches, so the two filters split the list between them.+ const setUp = await member.as("GET", "/api/v1/agent-vault/access-bundles?requiresSetup=false&limit=100");+ expect(+ (JSON.parse(setUp.payload) as { accessBundles: { id: string }[] }).accessBundles.map((listed) => listed.id)+ ).not.toContain(bundle.id);// The creator is granted the bundle, so it is one of the admin's own too.expect((await statusesOf(inject, bundle.id)).get(service.id)?.isConfigured).toBe(false);expect((await pendingOf(inject)).get(bundle.id)).toEqual(["datadog"]);@@ -1958,6 +1985,10 @@ describe("Agent Vault V1 Router", async () => {);expect((await statusesOf(member.as, bundle.id)).get(service.id)?.isConfigured).toBe(true);expect((await pendingOf(member.as)).has(bundle.id)).toBe(false);+ const nowSetUp = await member.as("GET", "/api/v1/agent-vault/access-bundles?requiresSetup=false&limit=100");+ expect(+ (JSON.parse(nowSetUp.payload) as { accessBundles: { id: string }[] }).accessBundles.map((listed) => listed.id)+ ).toContain(bundle.id);const removed = await member.as("DELETE", personalValuesUrl(bundle.id, service.id));expect(removed.statusCode).toBe(200);@@ -2032,13 +2063,22 @@ describe("Agent Vault V1 Router", async () => {expect.objectContaining({ id: adminVariableId, usedByServices: [] })]);+ const idsIn = (res: { payload: string }) =>+ (JSON.parse(res.payload) as { variables: { id: string }[] }).variables.map((variable) => variable.id);+// Personal variables never show among the global ones, and a member can't list those.- const globalList = await inject("GET", variablesUrl);+ const globalList = await inject("GET", `${variablesUrl}?scope=global&limit=100`);expect(globalList.statusCode).toBe(200);- expect(- (JSON.parse(globalList.payload) as { variables: { id: string }[] }).variables.map((variable) => variable.id)- ).not.toContain(adminVariableId);- expect((await member.as("GET", variablesUrl)).statusCode).toBe(403);+ expect(idsIn(globalList)).not.toContain(adminVariableId);+ expect(idsIn(globalList)).not.toContain(memberVariableId);+ expect((await member.as("GET", `${variablesUrl}?scope=global`)).statusCode).toBe(403);++ // Without a scope, each caller gets everything they can see: an admin the global ones and their own, a+ // member only their own. Nobody gets another's.+ const adminEverything = await inject("GET", `${variablesUrl}?limit=100`);+ expect(idsIn(adminEverything)).toEqual(expect.arrayContaining([adminVariableId, ...idsIn(globalList)]));+ expect(idsIn(adminEverything)).not.toContain(memberVariableId);+ expect(idsIn(await member.as("GET", variablesUrl))).toEqual([memberVariableId]);expect(JSON.parse(created.payload).variable.scope).toBe("personal");// Another actor's variable reads exactly like one that does not exist, an admin's included.@@ -2304,6 +2344,104 @@ describe("Agent Vault V1 Router", async () => {}});+ test("sorting personal variables by use counts only the services the member still reaches", async () => {+ const lost = await createAccessBundle("mp-sort-lost");+ const kept = await createAccessBundle("mp-sort-kept");+ const credential = { type: "bearer", memberProvidedFields: ["credential-value"] };+ const lostServices = [+ await createService(lost.id, { name: "lost-one", hostPattern: "lost-one.example.com", credential }),+ await createService(lost.id, { name: "lost-two", hostPattern: "lost-two.example.com", credential })+ ];+ const keptService = await createService(kept.id, { name: "kept", hostPattern: "kept.example.com", credential });++ const member = await createMemberIdentity(`mp-sort-${Date.now()}`);+ try {+ const grant = (bundleId: string) => inject("POST", membersUrl(bundleId), { machineIdentityIds: [member.id] });+ expect((await grant(lost.id)).statusCode).toBe(200);+ expect((await grant(kept.id)).statusCode).toBe(200);+ const addVariable = (key: string) => member.as("POST", variablesUrl, { scope: "personal", key, value: "v" });+ expect((await addVariable("A_LOST")).statusCode).toBe(200);+ expect((await addVariable("B_KEPT")).statusCode).toBe(200);+ const save = (bundleId: string, serviceId: string, key: string) =>+ setValues(member.as, bundleId, serviceId, { "credential-value": `{{${key}}}` });+ expect((await save(lost.id, lostServices[0].id, "A_LOST")).statusCode).toBe(200);+ expect((await save(lost.id, lostServices[1].id, "A_LOST")).statusCode).toBe(200);+ expect((await save(kept.id, keptService.id, "B_KEPT")).statusCode).toBe(200);++ // A path outside Agent Vault drops the grant and leaves the values, as in the Used By test above.+ await testDb("memberships").where({ scopeResourceId: lost.id, actorIdentityId: member.id }).del();++ const sorted = await member.as("GET", `${personalVariablesUrl}&orderBy=serviceCount&orderDirection=desc`);+ expect(sorted.statusCode).toBe(200);+ expect(+ (JSON.parse(sorted.payload) as { variables: { key: string; usedByServices: unknown[] }[] }).variables.map(+ (variable) => `${variable.key}:${variable.usedByServices.length}`+ )+ ).toEqual(["B_KEPT:1", "A_LOST:0"]);+ } finally {+ await member.cleanup();+ }+ });++ test("revoking a group's grant clears the values its members saved", async () => {+ const bundle = await createAccessBundle("mp-group-revoke");+ const service = await createService(bundle.id, {+ name: "pagerduty",+ hostPattern: "api.pagerduty.com",+ credential: { type: "bearer", memberProvidedFields: ["credential-value"] }+ });+ const group = await createProjectGroup(await getProjectId(), "mp-group-revoke", ProjectMembershipRole.Member);+ const member = await createMemberIdentity(`mp-group-revoke-${Date.now()}`);+ try {+ await testDb("identity_group_membership").insert({ groupId: group.id, identityId: member.id });+ expect((await inject("POST", membersUrl(bundle.id), { groupIds: [group.id] })).statusCode).toBe(200);+ expect((await setValues(member.as, bundle.id, service.id, { "credential-value": "pd" })).statusCode).toBe(200);++ expect((await inject("DELETE", membersUrl(bundle.id), { groupIds: [group.id] })).statusCode).toBe(200);+ expect(await testDb("agent_vault_personal_values").where({ identityId: member.id })).toHaveLength(0);+ } finally {+ await member.cleanup();+ await group.cleanup();+ }+ });++ test("a user member's own token is what their session sends", async () => {+ const bundle = await createAccessBundle("mp-user");+ const service = await createService(bundle.id, {+ name: "openai",+ hostPattern: "api.openai.com",+ credential: { type: "bearer", memberProvidedFields: ["credential-value"] }+ });++ const { userId } = await createUser("mp-user");+ try {+ await addUserMembership({ userId, orgId: seedData1.organization.id, role: OrgMembershipRole.Member });+ expect(+ (await inject("POST", "/api/v1/agent-vault/members", { userIds: [userId], role: "member" })).statusCode+ ).toBe(200);+ expect((await inject("POST", membersUrl(bundle.id), { userIds: [userId] })).statusCode).toBe(200);+ const token = await createUserAccessToken({ userId, orgId: seedData1.organization.id });+ const asUser = (method: "GET" | "POST" | "PATCH" | "DELETE", url: string, body?: Record<string, unknown>) =>+ testServer.inject({ method, url, headers: { authorization: `Bearer ${token}` }, ...(body ? { body } : {}) });++ expect((await pendingOf(asUser)).get(bundle.id)).toEqual(["openai"]);+ expect(+ (await asUser("POST", variablesUrl, { scope: "personal", key: "OPENAI_KEY", value: "sk-user" })).statusCode+ ).toBe(200);+ expect(+ (await setValues(asUser, bundle.id, service.id, { "credential-value": "{{OPENAI_KEY}}" })).statusCode+ ).toBe(200);+ expect((await statusesOf(asUser, bundle.id)).get(service.id)?.isConfigured).toBe(true);++ const resolve = await enrollProxy("mp-user");+ const resolved = await resolve(await mintSession(asUser, bundle.name), "openai");+ expect(resolved.personalValuesMissing).toBe(false);+ expect(resolved.credential).toMatchObject({ value: "sk-user" });+ } finally {+ await deleteUsers([userId]);+ }+ });+test("an admin is asked for values only on the bundles granted to them", async () => {const ungranted = await createAccessBundle("mp-mine-ungranted");const service = await createService(ungranted.id, {diff --git a/backend/e2e-test/testUtils/users.ts b/backend/e2e-test/testUtils/users.tsindex 7d4f98f039..fb99c8083c 100644--- a/backend/e2e-test/testUtils/users.ts+++ b/backend/e2e-test/testUtils/users.ts@@ -1,6 +1,9 @@import crypto from "node:crypto";+import jwt from "jsonwebtoken";+import { AccessScope, OrgMembershipRole, OrgMembershipStatus, ProjectMembershipRole, TableName } from "@app/db/schemas";+import { AuthMethod, AuthTokenType } from "@app/services/auth/auth-type";// Writes the rows directly rather than going through signup, which needs SRP. The user can be named// in memberships and reminders but cannot log in.@@ -42,3 +45,31 @@ export const addUserMembership = async (dto: {await testDb(TableName.MembershipRole).insert({ membershipId, role: dto.role });return membershipId;};++// A user from createUser has no password, so this signs the access token a login would have issued, against a+// session row of its own. The row goes with the user in deleteUsers.+export const createUserAccessToken = async ({ userId, orgId }: { userId: string; orgId: string }) => {+ const [session] = await testDb(TableName.AuthTokenSession)+ .insert({+ userId,+ ip: "127.0.0.1",+ userAgent: "e2e-test-user",+ accessVersion: 1,+ refreshVersion: 1,+ lastUsed: new Date()+ } as never)+ .returning("id");++ return jwt.sign(+ {+ authTokenType: AuthTokenType.ACCESS_TOKEN,+ userId,+ tokenVersionId: (session as { id: string }).id,+ authMethod: AuthMethod.EMAIL,+ organizationId: orgId,+ accessVersion: 1+ },+ process.env.AUTH_SECRET as string,+ { expiresIn: "1h" }+ );+};diff --git a/backend/src/db/migrations/20261013120000_agent-vault-personal-values.ts b/backend/src/db/migrations/20261017120000_agent-vault-personal-values.tssimilarity index 100%rename from backend/src/db/migrations/20261013120000_agent-vault-personal-values.tsrename to backend/src/db/migrations/20261017120000_agent-vault-personal-values.tsdiff --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 99fe18e16c..a764e6f958 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@@ -89,7 +89,13 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodProserviceCount: 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),- servicesRequiringSetup: z.string().array().describe(AGENT_VAULT.ACCESS_BUNDLE.servicesRequiringSetup)+ servicesRequiringSetup: z+ .object({+ id: z.string().uuid().describe(AGENT_VAULT.ACCESS_BUNDLE.servicesRequiringSetupId),+ name: z.string().describe(AGENT_VAULT.ACCESS_BUNDLE.servicesRequiringSetupName)+ })+ .array()+ .describe(AGENT_VAULT.ACCESS_BUNDLE.servicesRequiringSetup)}).array(),totalCount: z.number()})@@ -542,7 +548,7 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodPro},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),handler: async (req) => {- const { personalValues, replaced } = await server.services.agentVaultPersonalValue.setPersonalValues({+ const { personalValues } = await server.services.agentVaultPersonalValue.setPersonalValues({projectId: req.internalAgentVaultProjectId,ctx: actorContext(req),accessBundleId: req.params.accessBundleId,@@ -562,7 +568,6 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodProserviceId: personalValues.serviceId,serviceName: personalValues.serviceName,fields: req.body.values.map((value) => value.field),- replaced,variableKeys: [...new Set(personalValues.fieldsdiff --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 e46266af89..537987b266 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@@ -6,6 +6,7 @@ import {AGENT_VAULT_NO_CONTROL_CHARS_RE} from "@app/ee/services/agent-vault/agent-vault-credential-schemas";import {+ AGENT_VAULT_MEMBER_PROVIDED_FIELDS,AgentVaultCredentialType,AgentVaultHttpMethod,AgentVaultMemberType,@@ -50,7 +51,7 @@ const bearerMemberProvidedFieldsSchema = z.describe(AGENT_VAULT.SERVICE.bearerMemberProvidedFields);const basicMemberProvidedFieldsSchema = z- .enum([AgentVaultVariableReferenceField.CredentialUsername, AgentVaultVariableReferenceField.CredentialValue])+ .enum(AGENT_VAULT_MEMBER_PROVIDED_FIELDS).array().max(2).describe(AGENT_VAULT.SERVICE.basicMemberProvidedFields);@@ -220,7 +221,7 @@ export const AgentVaultCredentialSummarySchema = z.discriminatedUnion("type", [.object({type: z.literal(AgentVaultCredentialType.Basic),memberProvidedFields: z- .enum([AgentVaultVariableReferenceField.CredentialUsername, AgentVaultVariableReferenceField.CredentialValue])+ .enum(AGENT_VAULT_MEMBER_PROVIDED_FIELDS).array().describe(AGENT_VAULT.SERVICE.memberProvidedFields)})@@ -271,9 +272,7 @@ export const AgentVaultVariableReferenceSchema = z.discriminatedUnion("field", [z.object({...variableReferenceBase,- field: z- .enum([AgentVaultVariableReferenceField.CredentialValue, AgentVaultVariableReferenceField.CredentialUsername])- .describe(AGENT_VAULT.SERVICE.referenceField)+ field: z.enum(AGENT_VAULT_MEMBER_PROVIDED_FIELDS).describe(AGENT_VAULT.SERVICE.referenceField)}).describe(JSON.stringify({ title: "Credential" })),z@@ -359,9 +358,7 @@ export const AgentVaultVariableSchema = z.object({updatedAt: z.date().describe(AGENT_VAULT.VARIABLE.updatedAt)});-const personalValueFieldSchema = z- .enum([AgentVaultVariableReferenceField.CredentialValue, AgentVaultVariableReferenceField.CredentialUsername])- .describe(AGENT_VAULT.PERSONAL_VALUE.field);+const personalValueFieldSchema = z.enum(AGENT_VAULT_MEMBER_PROVIDED_FIELDS).describe(AGENT_VAULT.PERSONAL_VALUE.field);// The caller's own values for one service. Fields are listed as descriptors, so a custom header or substitution left// to members can join them with its id and no change to this shape.@@ -386,12 +383,21 @@ export const AgentVaultPersonalValuesSchema = z}).describe(AGENT_VAULT.PERSONAL_VALUE.personalValues);-export const AgentVaultPersonalValueInputSchema = z.object({- field: personalValueFieldSchema,- value: acceptsVariableReferences(- z.string().min(1).max(8192).regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)- ).describe(AGENT_VAULT.PERSONAL_VALUE.value)-});+// A username follows the admin's rule for one, a token or password the admin's rule for those.+export const AgentVaultPersonalValueInputSchema = z.discriminatedUnion("field", [+ z.object({+ field: z.literal(AgentVaultVariableReferenceField.CredentialUsername).describe(AGENT_VAULT.PERSONAL_VALUE.field),+ value: acceptsVariableReferences(+ z.string().trim().min(1).max(256).regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)+ ).describe(AGENT_VAULT.PERSONAL_VALUE.value)+ }),+ z.object({+ field: z.literal(AgentVaultVariableReferenceField.CredentialValue).describe(AGENT_VAULT.PERSONAL_VALUE.field),+ value: acceptsVariableReferences(+ z.string().min(1).max(8192).regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)+ ).describe(AGENT_VAULT.PERSONAL_VALUE.value)+ })+]);const memberIdsShape = (docs: { userIds: string; machineIdentityIds: string; groupIds: string }) => ({userIds: z.string().uuid().array().default([]).describe(docs.userIds),diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-variable-router.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-variable-router.tsindex 82c84c371f..cb96802525 100644--- a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-variable-router.ts+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-variable-router.ts@@ -30,13 +30,11 @@ export const registerAgentVaultVariableRouter = async (server: FastifyZodProvideschema: {hide: false,operationId: "listAgentVaultVariables",- description: "List Agent Vault's global variables, or your own personal ones",+ description:+ "List the Agent Vault variables you can see: your own personal ones, and the global ones if you're an admin",tags: [ApiDocsTags.AgentVaultVariables],querystring: z.object({- scope: z- .nativeEnum(AgentVaultVariableScope)- .default(AgentVaultVariableScope.Global)- .describe(AGENT_VAULT.VARIABLE.listScope),+ scope: z.nativeEnum(AgentVaultVariableScope).optional().describe(AGENT_VAULT.VARIABLE.listScope),orderBy: z.enum(["key", "serviceCount"]).default("key").describe(AGENT_VAULT.VARIABLE.orderBy),orderDirection: z.enum(["asc", "desc"]).default("asc").describe(AGENT_VAULT.VARIABLE.orderDirection),keys: z@@ -77,10 +75,7 @@ export const registerAgentVaultVariableRouter = async (server: FastifyZodProvidedescription: "Create a global variable, or a personal one of your own",tags: [ApiDocsTags.AgentVaultVariables],body: z.object({- scope: z- .nativeEnum(AgentVaultVariableScope)- .default(AgentVaultVariableScope.Global)- .describe(AGENT_VAULT.VARIABLE.createScope),+ scope: z.nativeEnum(AgentVaultVariableScope).describe(AGENT_VAULT.VARIABLE.createScope),key: AgentVaultVariableKeySchema.describe(AGENT_VAULT.VARIABLE.key),value: AgentVaultVariableValueSchema.describe(AGENT_VAULT.VARIABLE.value)}),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 dd2166b888..2f9997c350 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@@ -44,6 +44,7 @@ export type TAgentVaultAccessBundleOrderBy = "name" | "serviceCount" | "createdAtype TFindAccessBundlesDTO = {projectId: string;accessBundleIds: string[] | null;+ excludeAccessBundleIds?: string[];search?: string;orderBy: TAgentVaultAccessBundleOrderBy;orderDirection: "asc" | "desc";@@ -62,7 +63,16 @@ export const agentVaultAccessBundleDALFactory = (db: TDbClient) => {const orm = ormify(db, TableName.AgentVaultAccessBundle);const findForList = async (- { projectId, accessBundleIds, search, orderBy, orderDirection, limit, offset }: TFindAccessBundlesDTO,+ {+ projectId,+ accessBundleIds,+ excludeAccessBundleIds,+ search,+ orderBy,+ orderDirection,+ limit,+ offset+ }: TFindAccessBundlesDTO,tx?: Knex): Promise<{ accessBundles: TAgentVaultAccessBundleListRow[]; totalCount: number }> => {if (accessBundleIds?.length === 0) return { accessBundles: [], totalCount: 0 };@@ -75,6 +85,9 @@ export const agentVaultAccessBundleDALFactory = (db: TDbClient) => {const applyFilters = (query: Knex.QueryBuilder) => {void query.where(`${TableName.AgentVaultAccessBundle}.projectId`, projectId);if (accessBundleIds) void query.whereIn(`${TableName.AgentVaultAccessBundle}.id`, accessBundleIds);+ if (excludeAccessBundleIds?.length) {+ void query.whereNotIn(`${TableName.AgentVaultAccessBundle}.id`, excludeAccessBundleIds);+ }if (search) {const term = `%${sanitizeSqlLikeString(search)}%`;void query.where((qb) => {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 3ea733a8ae..58c71d8caa 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@@ -34,10 +34,7 @@ import {TAgentVaultActorNameDALs} from "../agent-vault/agent-vault-actor-name-fns";import { describeConflict, findHostPatternConflicts } from "../agent-vault/agent-vault-conflict-fns";-import {- AgentVaultBearerConfigSchema,- TAgentVaultCredentialConfig-} from "../agent-vault/agent-vault-credential-schemas";+import { TAgentVaultCredentialConfig } from "../agent-vault/agent-vault-credential-schemas";import { isUniqueViolation } from "../agent-vault/agent-vault-db-error-fns";import {AgentVaultCredentialType,@@ -69,7 +66,6 @@ import {TAddMembersDTO,TAgentVaultBasicMemberField,TAgentVaultBearerMemberField,- TAgentVaultCredentialInput,TAgentVaultCredentialSummary,TAgentVaultCredentialUpdate,TAgentVaultVariableReferenceSummary,@@ -84,6 +80,14 @@ import {TUpdateAccessBundleDTO,TUpdateServiceDTO} from "./agent-vault-access-bundle-types";+import {+ isStoredSecretReplaced,+ mergeCredential,+ needsStoredSecretFor,+ nextMemberFieldsOf,+ splitCredential,+ TCredentialWrite+} from "./agent-vault-credential-write-fns";import { TAgentVaultServiceCustomHeaderDALFactory } from "./agent-vault-service-custom-header-dal";import { TAgentVaultServiceDALFactory } from "./agent-vault-service-dal";import { TAgentVaultServiceSubstitutionDALFactory } from "./agent-vault-service-substitution-dal";@@ -314,201 +318,6 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundconst getProjectCipher = (projectId: string) =>kmsService.createCipherPairWithDataKey({ type: KmsDataKey.SecretManager, projectId });- // `null` clears the sealed column, `undefined` leaves it alone. $decryptCredential reads a NULL secret- // as passthrough, so the two are not interchangeable. The secret holds only the fields the admin sets, so a- // credential every member supplies in full stores none.- type TCredentialWrite = {- config: TAgentVaultCredentialConfig;- secret: Record<string, string> | null | undefined;- memberProvidedFields: TAgentVaultMemberProvidedField[] | null;- };-- // Sending a value replaces the stored secret, and so does a write that drops a field the admin held: handing it to- // members, or changing the type over a secret that was stored.- const isStoredSecretReplaced = (- credential: TAgentVaultCredentialUpdate,- stored: TAgentVaultServices,- written: TCredentialWrite["secret"]- ) => {- if (written === undefined) return false;- if (credential.type !== stored.credentialType) return Boolean(stored.encryptedCredential) || written !== null;- if (credential.type === AgentVaultCredentialType.Passthrough) return false;-- const previousMemberFields = (stored.memberProvidedFields ?? []) as TAgentVaultMemberProvidedField[];- const keyOfField: [TAgentVaultMemberProvidedField, string][] =- credential.type === AgentVaultCredentialType.Bearer- ? [[AgentVaultVariableReferenceField.CredentialValue, "value"]]- : [- [AgentVaultVariableReferenceField.CredentialUsername, "username"],- [AgentVaultVariableReferenceField.CredentialValue, "password"]- ];- return keyOfField.some(- ([field, key]) =>- (credential as Record<string, unknown>)[key] !== undefined ||- (!previousMemberFields.includes(field) && written?.[key] === undefined)- );- };-- const BASIC_NEEDS_A_HALF_MESSAGE =- "A basic credential needs a username, a password, or both. Set one, or leave one to each member.";-- // NULL, never an empty list, is what the column stores for a credential the admin sets in full.- const memberFieldsOf = (credential: TAgentVaultCredentialInput): TAgentVaultMemberProvidedField[] | null => {- if (credential.type === AgentVaultCredentialType.Passthrough) return null;- const fields = [...new Set<TAgentVaultMemberProvidedField>(credential.memberProvidedFields ?? [])];- return fields.length ? fields : null;- };-- const splitCredential = (credential: TAgentVaultCredentialInput): TCredentialWrite => {- const memberProvidedFields = memberFieldsOf(credential);- const isMemberProvided = (field: TAgentVaultMemberProvidedField) => Boolean(memberProvidedFields?.includes(field));-- switch (credential.type) {- case AgentVaultCredentialType.Bearer: {- const config = AgentVaultBearerConfigSchema.parse({- headerName: credential.headerName,- headerPrefix: credential.headerPrefix- });- if (isMemberProvided(AgentVaultVariableReferenceField.CredentialValue)) {- return { config: { type: credential.type, ...config }, secret: null, memberProvidedFields };- }- if (credential.value === undefined) {- throw new BadRequestError({- message: "A bearer credential needs a token. Set one, or leave the token to each member."- });- }- return {- config: { type: credential.type, ...config },- secret: { value: credential.value },- memberProvidedFields- };- }- case AgentVaultCredentialType.Basic: {- const secret = Object.fromEntries(- (- [- [AgentVaultVariableReferenceField.CredentialUsername, "username", credential.username],- [AgentVaultVariableReferenceField.CredentialValue, "password", credential.password]- ] as const- ).flatMap(([field, key, value]) => (isMemberProvided(field) ? [] : [[key, value ?? ""]]))- ) as Record<string, string>;- if (!memberProvidedFields && !Object.values(secret).some(Boolean)) {- throw new BadRequestError({ message: BASIC_NEEDS_A_HALF_MESSAGE });- }- return {- config: { type: credential.type },- secret: Object.keys(secret).length ? secret : null,- memberProvidedFields- };- }- default:- return { config: { type: AgentVaultCredentialType.Passthrough }, secret: null, memberProvidedFields: null };- }- };-- // The member-provided fields a PATCH ends with: an omitted list keeps the stored one.- const nextMemberFieldsOf = (credential: TAgentVaultCredentialUpdate, stored: TAgentVaultServices) => {- if (credential.type !== stored.credentialType || credential.type === AgentVaultCredentialType.Passthrough) {- return memberFieldsOf(credential);- }- if (credential.memberProvidedFields === undefined) {- return (stored.memberProvidedFields as TAgentVaultMemberProvidedField[] | null | undefined) ?? null;- }- return memberFieldsOf(credential);- };-- const mergeCredential = (- credential: TAgentVaultCredentialUpdate,- stored: TAgentVaultServices,- storedSecret: Record<string, string> | null- ): TCredentialWrite => {- if (credential.type !== stored.credentialType) {- if (- credential.type === AgentVaultCredentialType.Bearer &&- credential.value === undefined &&- !memberFieldsOf(credential)?.includes(AgentVaultVariableReferenceField.CredentialValue)- ) {- throw new BadRequestError({- message:- "Provide a new token when changing the credential type to bearer, or leave the token to each member. The stored secret belongs to the previous type"- });- }- return splitCredential(credential);- }-- const prev = (stored.credentialConfig ?? {}) as { headerName?: string; headerPrefix?: string };- const previousMemberFields = (stored.memberProvidedFields ?? []) as TAgentVaultMemberProvidedField[];- const memberProvidedFields = nextMemberFieldsOf(credential, stored);- const memberFieldsChanged = !sameMemberProvidedFields(memberProvidedFields, previousMemberFields);- const isMemberProvided = (field: TAgentVaultMemberProvidedField) => Boolean(memberProvidedFields?.includes(field));-- // The schema only sees the member-provided list a request sends. One that leaves the list out keeps the stored- // one, so a value for a field that list hands to members is refused here rather than dropped.- const memberFieldOfKey: Record<string, TAgentVaultMemberProvidedField> =- credential.type === AgentVaultCredentialType.Bearer- ? { value: AgentVaultVariableReferenceField.CredentialValue }- : {- username: AgentVaultVariableReferenceField.CredentialUsername,- password: AgentVaultVariableReferenceField.CredentialValue- };- const sentToMemberField = Object.entries(memberFieldOfKey).find(- ([key, field]) => (credential as Record<string, unknown>)[key] !== undefined && isMemberProvided(field)- );- if (sentToMemberField) {- throw new BadRequestError({- message: `Leave '${sentToMemberField[0]}' out: '${sentToMemberField[1]}' is member provided, so each member sets it. To set it yourself, send memberProvidedFields without '${sentToMemberField[1]}'.`- });- }-- switch (credential.type) {- case AgentVaultCredentialType.Bearer: {- const config = {- type: credential.type,- headerName: credential.headerName ?? prev.headerName ?? "Authorization",- headerPrefix: credential.headerPrefix ?? prev.headerPrefix ?? ""- };- if (isMemberProvided(AgentVaultVariableReferenceField.CredentialValue)) {- return { config, secret: memberFieldsChanged ? null : undefined, memberProvidedFields };- }- if (credential.value !== undefined) {- return { config, secret: { value: credential.value }, memberProvidedFields };- }- if (memberFieldsChanged) {- throw new BadRequestError({- message: "Provide a token when you stop leaving it to each member. Nothing is stored for it yet."- });- }- return { config, secret: undefined, memberProvidedFields };- }- case AgentVaultCredentialType.Basic: {- if (credential.username === undefined && credential.password === undefined && !memberFieldsChanged) {- return { config: { type: credential.type }, secret: undefined, memberProvidedFields };- }- // A half that was member-provided has nothing stored to keep, so taking it back starts it empty.- const adminHalf = (field: TAgentVaultMemberProvidedField, key: "username" | "password") => {- if (isMemberProvided(field)) return [];- const sent = credential[key];- if (sent !== undefined) return [[key, sent]];- return [[key, previousMemberFields.includes(field) ? "" : (storedSecret?.[key] ?? "")]];- };- const secret = Object.fromEntries([- ...adminHalf(AgentVaultVariableReferenceField.CredentialUsername, "username"),- ...adminHalf(AgentVaultVariableReferenceField.CredentialValue, "password")- ]) as Record<string, string>;- if (!memberProvidedFields && !Object.values(secret).some(Boolean)) {- throw new BadRequestError({ message: BASIC_NEEDS_A_HALF_MESSAGE });- }- return {- config: { type: credential.type },- secret: Object.keys(secret).length ? secret : null,- memberProvidedFields- };- }- default:- return { config: { type: AgentVaultCredentialType.Passthrough }, secret: null, memberProvidedFields: null };- }- };-const summarizeCredential = (service: TAgentVaultServices): TAgentVaultCredentialSummary => {const config = service.credentialConfig as Record<string, string>;const memberProvidedFields = service.memberProvidedFields ?? [];@@ -791,7 +600,7 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundconst owner = ownerOrNullOf(ctx);const pendingByBundleOf = async (bundleIds: string[]) => {- const byBundle = new Map<string, string[]>();+ const byBundle = new Map<string, { id: string; name: string }[]>();if (!owner || !bundleIds.length) return byBundle;const statuses = await agentVaultPersonalValueService.findStatusesForOwner({projectId,@@ -802,17 +611,21 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundstatuses.filter((status) => !status.isConfigured).forEach((status) =>- byBundle.set(status.accessBundleId, [...(byBundle.get(status.accessBundleId) ?? []), status.serviceName])+ byBundle.set(status.accessBundleId, [+ ...(byBundle.get(status.accessBundleId) ?? []),+ { id: status.serviceId, name: status.serviceName }+ ]));return byBundle;};- // The filter needs every granted bundle's status before it can page; the plain list only needs the page's.- if (requiresSetup) {+ // Either filter needs every granted bundle's status before it can page; the plain list only needs the page's.+ if (requiresSetup !== undefined) {const pendingByBundle = await pendingByBundleOf(grantedAccessBundleIds);+ const pendingIds = [...pendingByBundle.keys()];const { accessBundles, totalCount } = await agentVaultAccessBundleDAL.findForList({projectId,- accessBundleIds: [...pendingByBundle.keys()],+ ...(requiresSetup ? { accessBundleIds: pendingIds } : { accessBundleIds, excludeAccessBundleIds: pendingIds }),...page});return {@@ -1207,20 +1020,7 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundconst memberFieldsChanged =credentialTypeChanged ||(Boolean(credential) && !sameMemberProvidedFields(nextMemberFields, previousMemberFields));- const needsStoredSecret =- credential?.type === AgentVaultCredentialType.Basic &&- service.credentialType === AgentVaultCredentialType.Basic &&- Boolean(service.encryptedCredential) &&- (credential.username !== undefined || credential.password !== undefined || memberFieldsChanged) &&- (- [- [AgentVaultVariableReferenceField.CredentialUsername, "username"],- [AgentVaultVariableReferenceField.CredentialValue, "password"]- ] as const- ).some(- ([field, key]) =>- credential[key] === undefined && !nextMemberFields?.includes(field) && !previousMemberFields.includes(field)- );+ const needsStoredSecret = Boolean(credential) && needsStoredSecretFor(credential!, service);const storedSecretCipher = needsStoredSecret ? await getProjectCipher(rest.projectId) : null;const storedSecret = storedSecretCipher? (JSON.parse(diff --git a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-credential-write-fns.test.ts b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-credential-write-fns.test.tsnew file mode 100644index 0000000000..9683a1e5c3--- /dev/null+++ b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-credential-write-fns.test.ts@@ -0,0 +1,260 @@+import { TAgentVaultServices } from "@app/db/schemas";++import { AgentVaultCredentialType } from "../agent-vault/agent-vault-enums";+import { TAgentVaultCredentialUpdate } from "./agent-vault-access-bundle-types";+import {+ isStoredSecretReplaced,+ mergeCredential,+ needsStoredSecretFor,+ splitCredential+} from "./agent-vault-credential-write-fns";++const VALUE = "credential-value";+const USERNAME = "credential-username";++const BEARER = AgentVaultCredentialType.Bearer;+const BASIC = AgentVaultCredentialType.Basic;+const PASSTHROUGH = AgentVaultCredentialType.Passthrough;++// Only the columns the helpers read. A sealed secret is any non-empty buffer: the helpers check for one, not its contents.+const storedService = ({+ type,+ memberProvidedFields = null,+ sealed = true+}: {+ type: AgentVaultCredentialType;+ memberProvidedFields?: string[] | null;+ sealed?: boolean;+}) =>+ ({+ credentialType: type,+ credentialConfig: type === BEARER ? { type, headerName: "Authorization", headerPrefix: "Bearer " } : { type },+ memberProvidedFields,+ encryptedCredential: sealed ? Buffer.from("sealed") : null+ }) as unknown as TAgentVaultServices;++const credential = (value: Record<string, unknown>) => value as unknown as TAgentVaultCredentialUpdate;++describe("splitCredential", () => {+ test.each([+ ["bearer with a token", { type: BEARER, value: "t" }, { value: "t" }, null],+ ["bearer left to members", { type: BEARER, memberProvidedFields: [VALUE] }, null, [VALUE]],+ ["basic with both halves", { type: BASIC, username: "u", password: "p" }, { username: "u", password: "p" }, null],+ ["basic with a username only", { type: BASIC, username: "u" }, { username: "u", password: "" }, null],+ [+ "basic with the password left to members",+ { type: BASIC, username: "u", memberProvidedFields: [VALUE] },+ { username: "u" },+ [VALUE]+ ],+ ["basic left wholly to members", { type: BASIC, memberProvidedFields: [USERNAME, VALUE] }, null, [USERNAME, VALUE]],+ ["passthrough", { type: PASSTHROUGH }, null, null]+ ])("%s", (_, input, secret, memberProvidedFields) => {+ const written = splitCredential(credential(input));+ expect(written.secret).toEqual(secret);+ expect(written.memberProvidedFields).toEqual(memberProvidedFields);+ });++ test.each([+ ["bearer with no token and nothing left to members", { type: BEARER }, "needs a token"],+ ["basic with neither half", { type: BASIC }, "needs a username, a password, or both"]+ ])("refuses %s", (_, input, message) => {+ expect(() => splitCredential(credential(input))).toThrow(message);+ });+});++describe("mergeCredential", () => {+ const STORED_BASIC = { username: "stored-u", password: "stored-p" };++ test.each([+ // [case, stored service, update, sealed secret read for it, expected secret, expected member fields]+ ["bearer token rotated", { type: BEARER }, { type: BEARER, value: "new" }, null, { value: "new" }, null],+ ["bearer header renamed only", { type: BEARER }, { type: BEARER, headerName: "X-Key" }, null, undefined, null],+ [+ "bearer token handed to members",+ { type: BEARER },+ { type: BEARER, memberProvidedFields: [VALUE] },+ null,+ null,+ [VALUE]+ ],+ [+ "bearer still member provided, list left out",+ { type: BEARER, memberProvidedFields: [VALUE], sealed: false },+ { type: BEARER, headerName: "X-Key" },+ null,+ undefined,+ [VALUE]+ ],+ [+ "bearer taken back with a token",+ { type: BEARER, memberProvidedFields: [VALUE], sealed: false },+ { type: BEARER, memberProvidedFields: [], value: "admin" },+ null,+ { value: "admin" },+ null+ ],+ [+ "basic password rotated",+ { type: BASIC },+ { type: BASIC, password: "new-p" },+ STORED_BASIC,+ { username: "stored-u", password: "new-p" },+ null+ ],+ [+ "basic password handed to members",+ { type: BASIC },+ { type: BASIC, memberProvidedFields: [VALUE] },+ STORED_BASIC,+ { username: "stored-u" },+ [VALUE]+ ],+ [+ "basic password taken back with a value",+ { type: BASIC, memberProvidedFields: [VALUE] },+ { type: BASIC, memberProvidedFields: [], password: "admin-p" },+ { username: "stored-u" },+ { username: "stored-u", password: "admin-p" },+ null+ ],+ [+ "basic password taken back without one starts it empty",+ { type: BASIC, memberProvidedFields: [VALUE] },+ { type: BASIC, memberProvidedFields: [] },+ { username: "stored-u" },+ { username: "stored-u", password: "" },+ null+ ],+ [+ "basic username taken back from a fully member-provided credential",+ { type: BASIC, memberProvidedFields: [USERNAME, VALUE], sealed: false },+ { type: BASIC, memberProvidedFields: [VALUE] },+ null,+ { username: "" },+ [VALUE]+ ],+ [+ "basic username handed over as well",+ { type: BASIC, memberProvidedFields: [VALUE] },+ { type: BASIC, memberProvidedFields: [USERNAME, VALUE] },+ { username: "stored-u" },+ null,+ [USERNAME, VALUE]+ ],+ ["basic unchanged", { type: BASIC }, { type: BASIC }, null, undefined, null],+ [+ "type changed to a member-provided bearer",+ { type: BASIC },+ { type: BEARER, memberProvidedFields: [VALUE] },+ null,+ null,+ [VALUE]+ ],+ ["type changed to passthrough", { type: BEARER }, { type: PASSTHROUGH }, null, null, null]+ ])("%s", (_, stored, update, sealedSecret, secret, memberProvidedFields) => {+ const written = mergeCredential(+ credential(update),+ storedService(stored as Parameters<typeof storedService>[0]),+ sealedSecret+ );+ expect(written.secret).toEqual(secret);+ expect(written.memberProvidedFields).toEqual(memberProvidedFields);+ });++ test.each([+ [+ "a token sent for a member-provided field",+ { type: BEARER, memberProvidedFields: [VALUE], sealed: false },+ { type: BEARER, value: "x" },+ "is member provided"+ ],+ [+ "a bearer taken back with no token",+ { type: BEARER, memberProvidedFields: [VALUE], sealed: false },+ { type: BEARER, memberProvidedFields: [] },+ "Provide a token when you stop leaving it to each member"+ ],+ [+ "a type change to bearer with no token",+ { type: BASIC },+ { type: BEARER },+ "Provide a new token when changing the credential type to bearer"+ ],+ [+ "a basic left with neither half",+ { type: BASIC, memberProvidedFields: [USERNAME, VALUE], sealed: false },+ { type: BASIC, memberProvidedFields: [] },+ "needs a username, a password, or both"+ ]+ ])("refuses %s", (_, stored, update, message) => {+ expect(() =>+ mergeCredential(credential(update), storedService(stored as Parameters<typeof storedService>[0]), null)+ ).toThrow(message);+ });+});++describe("isStoredSecretReplaced", () => {+ test.each([+ ["a token sent", { type: BEARER }, { type: BEARER, value: "new" }, { value: "new" }, true],+ ["nothing written", { type: BEARER }, { type: BEARER, headerName: "X" }, undefined, false],+ ["a stored token handed to members", { type: BEARER }, { type: BEARER, memberProvidedFields: [VALUE] }, null, true],+ [+ "a stored password handed to members",+ { type: BASIC },+ { type: BASIC, memberProvidedFields: [VALUE] },+ { username: "u" },+ true+ ],+ [+ "a member-provided password taken back empty",+ { type: BASIC, memberProvidedFields: [VALUE] },+ { type: BASIC, memberProvidedFields: [] },+ { username: "u", password: "" },+ false+ ],+ ["a type change over a stored secret", { type: BEARER }, { type: PASSTHROUGH }, null, true],+ [+ "a type change with nothing stored before or after",+ { type: PASSTHROUGH, sealed: false },+ { type: BEARER, memberProvidedFields: [VALUE] },+ null,+ false+ ]+ ])("%s", (_, stored, update, written, replaced) => {+ expect(+ isStoredSecretReplaced(+ credential(update),+ storedService(stored as Parameters<typeof storedService>[0]),+ written as Record<string, string> | null | undefined+ )+ ).toBe(replaced);+ });+});++describe("needsStoredSecretFor", () => {+ test.each([+ ["a basic password rotated keeps the stored username", { type: BASIC }, { type: BASIC, password: "p" }, true],+ ["a basic with both halves sent", { type: BASIC }, { type: BASIC, username: "u", password: "p" }, false],+ ["a basic left unchanged", { type: BASIC }, { type: BASIC }, false],+ [+ "a basic password handed to members keeps the stored username",+ { type: BASIC },+ { type: BASIC, memberProvidedFields: [VALUE] },+ true+ ],+ [+ "a basic half taken back has nothing stored to keep",+ { type: BASIC, memberProvidedFields: [USERNAME, VALUE] },+ { type: BASIC, memberProvidedFields: [VALUE] },+ false+ ],+ ["a basic with nothing sealed", { type: BASIC, sealed: false }, { type: BASIC, password: "p" }, false],+ ["a bearer", { type: BEARER }, { type: BEARER, value: "t" }, false],+ ["a type change", { type: BEARER }, { type: BASIC, password: "p" }, false]+ ])("%s", (_, stored, update, needed) => {+ expect(needsStoredSecretFor(credential(update), storedService(stored as Parameters<typeof storedService>[0]))).toBe(+ needed+ );+ });+});diff --git a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-credential-write-fns.ts b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-credential-write-fns.tsnew file mode 100644index 0000000000..6edfb5efc6--- /dev/null+++ b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-credential-write-fns.ts@@ -0,0 +1,241 @@+import { TAgentVaultServices } from "@app/db/schemas";+import { BadRequestError } from "@app/lib/errors";++import {+ AgentVaultBearerConfigSchema,+ TAgentVaultCredentialConfig+} from "../agent-vault/agent-vault-credential-schemas";+import {+ AgentVaultCredentialType,+ AgentVaultVariableReferenceField,+ TAgentVaultMemberProvidedField+} from "../agent-vault/agent-vault-enums";+import { sameMemberProvidedFields } from "../agent-vault-personal-value/agent-vault-personal-value-fns";+import { TAgentVaultCredentialInput, TAgentVaultCredentialUpdate } from "./agent-vault-access-bundle-types";++// `null` clears the sealed column, `undefined` leaves it alone. $decryptCredential reads a NULL secret+// as passthrough, so the two are not interchangeable. The secret holds only the fields the admin sets, so a+// credential every member supplies in full stores none.+export type TCredentialWrite = {+ config: TAgentVaultCredentialConfig;+ secret: Record<string, string> | null | undefined;+ memberProvidedFields: TAgentVaultMemberProvidedField[] | null;+};++const BASIC_HALVES = [+ [AgentVaultVariableReferenceField.CredentialUsername, "username"],+ [AgentVaultVariableReferenceField.CredentialValue, "password"]+] as const;++type TBasicUpdate = Extract<TAgentVaultCredentialUpdate, { type: AgentVaultCredentialType.Basic }>;++// A basic update rewrites the sealed secret when it sends a half or changes which halves are left to members.+const rewritesBasicSecret = (credential: TBasicUpdate, memberFieldsChanged: boolean) =>+ credential.username !== undefined || credential.password !== undefined || memberFieldsChanged;++// The admin halves a rewrite keeps from the sealed secret: not sent, and the admin's both before and after. A half+// that was left to members has nothing sealed to keep.+const keptBasicHalves = (+ credential: TBasicUpdate,+ nextMemberFields: readonly TAgentVaultMemberProvidedField[] | null,+ previousMemberFields: readonly TAgentVaultMemberProvidedField[]+) =>+ BASIC_HALVES.filter(+ ([field, key]) =>+ credential[key] === undefined && !nextMemberFields?.includes(field) && !previousMemberFields.includes(field)+ ).map(([, key]) => key);++// Sending a value replaces the stored secret, and so does a write that drops a field the admin held: handing it to+// members, or changing the type over a secret that was stored.+export const isStoredSecretReplaced = (+ credential: TAgentVaultCredentialUpdate,+ stored: TAgentVaultServices,+ written: TCredentialWrite["secret"]+) => {+ if (written === undefined) return false;+ if (credential.type !== stored.credentialType) return Boolean(stored.encryptedCredential) || written !== null;+ if (credential.type === AgentVaultCredentialType.Passthrough) return false;++ const previousMemberFields = (stored.memberProvidedFields ?? []) as TAgentVaultMemberProvidedField[];+ const keyOfField: readonly (readonly [TAgentVaultMemberProvidedField, string])[] =+ credential.type === AgentVaultCredentialType.Bearer+ ? [[AgentVaultVariableReferenceField.CredentialValue, "value"]]+ : BASIC_HALVES;+ return keyOfField.some(+ ([field, key]) =>+ (credential as Record<string, unknown>)[key] !== undefined ||+ (!previousMemberFields.includes(field) && written?.[key] === undefined)+ );+};++export const BASIC_NEEDS_A_HALF_MESSAGE =+ "A basic credential needs a username, a password, or both. Set one, or leave one to each member.";++// NULL, never an empty list, is what the column stores for a credential the admin sets in full.+export const memberFieldsOf = (credential: TAgentVaultCredentialInput): TAgentVaultMemberProvidedField[] | null => {+ if (credential.type === AgentVaultCredentialType.Passthrough) return null;+ const fields = [...new Set<TAgentVaultMemberProvidedField>(credential.memberProvidedFields ?? [])];+ return fields.length ? fields : null;+};++export const splitCredential = (credential: TAgentVaultCredentialInput): TCredentialWrite => {+ const memberProvidedFields = memberFieldsOf(credential);+ const isMemberProvided = (field: TAgentVaultMemberProvidedField) => Boolean(memberProvidedFields?.includes(field));++ switch (credential.type) {+ case AgentVaultCredentialType.Bearer: {+ const config = AgentVaultBearerConfigSchema.parse({+ headerName: credential.headerName,+ headerPrefix: credential.headerPrefix+ });+ if (isMemberProvided(AgentVaultVariableReferenceField.CredentialValue)) {+ return { config: { type: credential.type, ...config }, secret: null, memberProvidedFields };+ }+ if (credential.value === undefined) {+ throw new BadRequestError({+ message: "A bearer credential needs a token. Set one, or leave the token to each member."+ });+ }+ return {+ config: { type: credential.type, ...config },+ secret: { value: credential.value },+ memberProvidedFields+ };+ }+ case AgentVaultCredentialType.Basic: {+ const secret = Object.fromEntries(+ (+ [+ [AgentVaultVariableReferenceField.CredentialUsername, "username", credential.username],+ [AgentVaultVariableReferenceField.CredentialValue, "password", credential.password]+ ] as const+ ).flatMap(([field, key, value]) => (isMemberProvided(field) ? [] : [[key, value ?? ""]]))+ ) as Record<string, string>;+ if (!memberProvidedFields && !Object.values(secret).some(Boolean)) {+ throw new BadRequestError({ message: BASIC_NEEDS_A_HALF_MESSAGE });+ }+ return {+ config: { type: credential.type },+ secret: Object.keys(secret).length ? secret : null,+ memberProvidedFields+ };+ }+ default:+ return { config: { type: AgentVaultCredentialType.Passthrough }, secret: null, memberProvidedFields: null };+ }+};++// The member-provided fields a PATCH ends with: an omitted list keeps the stored one.+export const nextMemberFieldsOf = (credential: TAgentVaultCredentialUpdate, stored: TAgentVaultServices) => {+ if (credential.type !== stored.credentialType || credential.type === AgentVaultCredentialType.Passthrough) {+ return memberFieldsOf(credential);+ }+ if (credential.memberProvidedFields === undefined) {+ return (stored.memberProvidedFields as TAgentVaultMemberProvidedField[] | null | undefined) ?? null;+ }+ return memberFieldsOf(credential);+};++export const mergeCredential = (+ credential: TAgentVaultCredentialUpdate,+ stored: TAgentVaultServices,+ storedSecret: Record<string, string> | null+): TCredentialWrite => {+ if (credential.type !== stored.credentialType) {+ if (+ credential.type === AgentVaultCredentialType.Bearer &&+ credential.value === undefined &&+ !memberFieldsOf(credential)?.includes(AgentVaultVariableReferenceField.CredentialValue)+ ) {+ throw new BadRequestError({+ message:+ "Provide a new token when changing the credential type to bearer, or leave the token to each member. The stored secret belongs to the previous type"+ });+ }+ return splitCredential(credential);+ }++ const prev = (stored.credentialConfig ?? {}) as { headerName?: string; headerPrefix?: string };+ const previousMemberFields = (stored.memberProvidedFields ?? []) as TAgentVaultMemberProvidedField[];+ const memberProvidedFields = nextMemberFieldsOf(credential, stored);+ const memberFieldsChanged = !sameMemberProvidedFields(memberProvidedFields, previousMemberFields);+ const isMemberProvided = (field: TAgentVaultMemberProvidedField) => Boolean(memberProvidedFields?.includes(field));++ // The schema only sees the member-provided list a request sends. One that leaves the list out keeps the stored+ // one, so a value for a field that list hands to members is refused here rather than dropped.+ const memberFieldOfKey: Record<string, TAgentVaultMemberProvidedField> =+ credential.type === AgentVaultCredentialType.Bearer+ ? { value: AgentVaultVariableReferenceField.CredentialValue }+ : {+ username: AgentVaultVariableReferenceField.CredentialUsername,+ password: AgentVaultVariableReferenceField.CredentialValue+ };+ const sentToMemberField = Object.entries(memberFieldOfKey).find(+ ([key, field]) => (credential as Record<string, unknown>)[key] !== undefined && isMemberProvided(field)+ );+ if (sentToMemberField) {+ throw new BadRequestError({+ message: `Leave '${sentToMemberField[0]}' out: '${sentToMemberField[1]}' is member provided, so each member sets it. To set it yourself, send memberProvidedFields without '${sentToMemberField[1]}'.`+ });+ }++ switch (credential.type) {+ case AgentVaultCredentialType.Bearer: {+ const config = {+ type: credential.type,+ headerName: credential.headerName ?? prev.headerName ?? "Authorization",+ headerPrefix: credential.headerPrefix ?? prev.headerPrefix ?? ""+ };+ if (isMemberProvided(AgentVaultVariableReferenceField.CredentialValue)) {+ return { config, secret: memberFieldsChanged ? null : undefined, memberProvidedFields };+ }+ if (credential.value !== undefined) {+ return { config, secret: { value: credential.value }, memberProvidedFields };+ }+ if (memberFieldsChanged) {+ throw new BadRequestError({+ message: "Provide a token when you stop leaving it to each member. Nothing is stored for it yet."+ });+ }+ return { config, secret: undefined, memberProvidedFields };+ }+ case AgentVaultCredentialType.Basic: {+ if (!rewritesBasicSecret(credential, memberFieldsChanged)) {+ return { config: { type: credential.type }, secret: undefined, memberProvidedFields };+ }+ // A half taken back from members has nothing sealed to keep, so it starts empty.+ const kept = new Set<string>(keptBasicHalves(credential, memberProvidedFields, previousMemberFields));+ const secret = Object.fromEntries(+ BASIC_HALVES.flatMap(([field, key]) => {+ if (isMemberProvided(field)) return [];+ const sent = credential[key];+ if (sent !== undefined) return [[key, sent]];+ return [[key, kept.has(key) ? (storedSecret?.[key] ?? "") : ""]];+ })+ ) as Record<string, string>;+ if (!memberProvidedFields && !Object.values(secret).some(Boolean)) {+ throw new BadRequestError({ message: BASIC_NEEDS_A_HALF_MESSAGE });+ }+ return {+ config: { type: credential.type },+ secret: Object.keys(secret).length ? secret : null,+ memberProvidedFields+ };+ }+ default:+ return { config: { type: AgentVaultCredentialType.Passthrough }, secret: null, memberProvidedFields: null };+ }+};++// Whether an update's write keeps an admin half it left out, which it can only read from the sealed secret.+export const needsStoredSecretFor = (credential: TAgentVaultCredentialUpdate, service: TAgentVaultServices) => {+ if (credential.type !== AgentVaultCredentialType.Basic) return false;+ if (service.credentialType !== AgentVaultCredentialType.Basic || !service.encryptedCredential) return false;+ const previousMemberFields = (service.memberProvidedFields ?? []) as TAgentVaultMemberProvidedField[];+ const nextMemberFields = nextMemberFieldsOf(credential, service);+ const memberFieldsChanged = !sameMemberProvidedFields(nextMemberFields, previousMemberFields);+ return (+ rewritesBasicSecret(credential, memberFieldsChanged) &&+ keptBasicHalves(credential, nextMemberFields, previousMemberFields).length > 0+ );+};diff --git a/backend/src/ee/services/agent-vault-personal-value/agent-vault-personal-value-service.ts b/backend/src/ee/services/agent-vault-personal-value/agent-vault-personal-value-service.tsindex f4e421ad8a..29831ff6c8 100644--- a/backend/src/ee/services/agent-vault-personal-value/agent-vault-personal-value-service.ts+++ b/backend/src/ee/services/agent-vault-personal-value/agent-vault-personal-value-service.ts@@ -300,7 +300,7 @@ export const agentVaultPersonalValueServiceFactory = ({{ projectId: dto.projectId, owner, accessBundleIds: [service.accessBundleId], serviceId: service.id },tx);- return { personalValues: projected, replaced: existing.length > 0 };+ return { personalValues: projected };});try {diff --git a/backend/src/ee/services/agent-vault-variable/agent-vault-variable-dal.ts b/backend/src/ee/services/agent-vault-variable/agent-vault-variable-dal.tsindex 0476ccc8f1..1dcad53a00 100644--- a/backend/src/ee/services/agent-vault-variable/agent-vault-variable-dal.ts+++ b/backend/src/ee/services/agent-vault-variable/agent-vault-variable-dal.ts@@ -19,9 +19,12 @@ export type TAgentVaultVariableOrderBy = "key" | "serviceCount";// names one, so a global lookup never matches a personal key and the other way round.export type TAgentVaultVariableOwnerScope = { projectId: string; owner: TAgentVaultOwner | null };-export type TFindAgentVaultVariablesDTO = TAgentVaultVariableOwnerScope & {+// Each owner is one scope to list, null the global one: a list can span both for an admin.+export type TFindAgentVaultVariablesDTO = { projectId: string; owners: (TAgentVaultOwner | null)[] } & {search?: string;keys?: string[];+ // Counts only the services in these bundles toward serviceCount. Omit to count every one.+ accessBundleIds?: string[];orderBy: TAgentVaultVariableOrderBy;orderDirection: "asc" | "desc";limit: number;@@ -51,7 +54,7 @@ const VARIABLE_COLUMNS = [] as const;// Each (variable, service) pair a reference row records: a service's own fields, or a member's value for one.-const referencingServices = (conn: Knex, variableIds?: string[]) => {+const referencingServices = (conn: Knex, variableIds?: string[] | Knex.QueryBuilder) => {const serviceRefs = conn(TableName.AgentVaultServiceVariableReference).select(`${TableName.AgentVaultServiceVariableReference}.variableId`,`${TableName.AgentVaultServiceVariableReference}.serviceId`@@ -88,11 +91,32 @@ export const agentVaultVariableDALFactory = (db: TDbClient) => {// Reads the primary even without a tx, so a variable created a moment ago is always listed. serviceCount counts// the services that use a variable, each once however many of its fields do.const findForList = async (- { projectId, owner, search, keys, orderBy, orderDirection, limit, offset }: TFindAgentVaultVariablesDTO,+ {+ projectId,+ owners,+ search,+ keys,+ accessBundleIds,+ orderBy,+ orderDirection,+ limit,+ offset+ }: TFindAgentVaultVariablesDTO,tx?: Knex): Promise<{ variables: TAgentVaultVariable[]; totalCount: number }> => {try {const conn = tx || db;+ if (!owners.length) return { variables: [], totalCount: 0 };+ const listed = () =>+ conn(TableName.AgentVaultVariable)+ .where(`${TableName.AgentVaultVariable}.projectId`, projectId)+ .where((anyOwner) => {+ owners.forEach((owner) => {+ void anyOwner.orWhere((one) => {+ void whereOwner(one, TableName.AgentVaultVariable, owner);+ });+ });+ });const applyFilters = (query: Knex.QueryBuilder) => {if (search) {@@ -102,24 +126,27 @@ export const agentVaultVariableDALFactory = (db: TDbClient) => {return query;};- const countResult = (await applyFilters(scoped(conn, { projectId, owner }))+ const countResult = (await applyFilters(listed()).count(`${TableName.AgentVaultVariable}.id as count`).first()) as { count: string } | undefined;const totalCount = parseInt(countResult?.count || "0", 10);- const pageQuery = applyFilters(scoped(conn, { projectId, owner })).limit(limit).offset(offset).select(columns);+ const pageQuery = applyFilters(listed()).limit(limit).offset(offset).select(columns);if (orderBy === "serviceCount") {// Counted over this list's variables only; the references tables hold every org's.const usageCounts = conn- .from(referencingServices(conn).as("refs"))- .whereIn("refs.variableId", scoped(conn, { projectId, owner }).select(`${TableName.AgentVaultVariable}.id`))+ .from(referencingServices(conn, listed().select(`${TableName.AgentVaultVariable}.id`)).as("refs")).select("refs.variableId").countDistinct("refs.serviceId as count")- .groupBy("refs.variableId")- .as("uc");+ .groupBy("refs.variableId");+ if (accessBundleIds) {+ void usageCounts+ .join(TableName.AgentVaultService, "refs.serviceId", `${TableName.AgentVaultService}.id`)+ .whereIn(`${TableName.AgentVaultService}.accessBundleId`, accessBundleIds);+ }- void pageQuery.leftJoin(usageCounts, function joinUsageCount() {+ void pageQuery.leftJoin(usageCounts.as("uc"), function joinUsageCount() {this.on(db.raw(`uc."variableId" = ??.id`, [TableName.AgentVaultVariable]));});void pageQuery.orderByRaw(`COALESCE(uc.count, 0) ${orderDirection === "desc" ? "DESC" : "ASC"}`);diff --git a/backend/src/ee/services/agent-vault-variable/agent-vault-variable-service.ts b/backend/src/ee/services/agent-vault-variable/agent-vault-variable-service.tsindex cbe7d762a2..12d9cead4f 100644--- a/backend/src/ee/services/agent-vault-variable/agent-vault-variable-service.ts+++ b/backend/src/ee/services/agent-vault-variable/agent-vault-variable-service.ts@@ -16,7 +16,7 @@ import { TMembershipDALFactory } from "@app/services/membership/membership-dal";import { isUniqueViolation } from "../agent-vault/agent-vault-db-error-fns";import { AgentVaultVariableScope } from "../agent-vault/agent-vault-enums";-import { ownerOf, TAgentVaultOwner } from "../agent-vault/agent-vault-owner-fns";+import { ownerOf, ownerOrNullOf, TAgentVaultOwner } from "../agent-vault/agent-vault-owner-fns";import { getAgentVaultPermission, getAgentVaultReachability } from "../agent-vault/agent-vault-permission";import { AGENT_VAULT_MAX_PERSONAL_VARIABLES, AGENT_VAULT_MAX_VARIABLES } from "../agent-vault/agent-vault-variable-fns";import { TAgentVaultPersonalValueDALFactory } from "../agent-vault-personal-value/agent-vault-personal-value-dal";@@ -86,6 +86,34 @@ export const agentVaultVariableServiceFactory = ({return { projectId, owner: ownerOf(ctx) };};+ const resolveListOwners = async (+ { projectId, ctx }: TAgentVaultVariableScoped,+ scope?: AgentVaultVariableScope+ ): Promise<(TAgentVaultOwner | null)[]> => {+ if (scope) return [(await resolveScope({ projectId, ctx }, scope)).owner];++ const { permission } = await getAgentVaultPermission({ permissionService }, { projectId, ctx });+ ForbiddenError.from(permission).throwUnlessCan(+ ProjectPermissionAgentVaultAccessBundleActions.Read,+ ProjectPermissionSub.AgentVaultAccessBundles+ );+ const owners: (TAgentVaultOwner | null)[] = [];+ if (+ permission.can(ProjectPermissionAgentVaultAccessBundleActions.Edit, ProjectPermissionSub.AgentVaultAccessBundles)+ ) {+ owners.push(null);+ }+ const owner = ownerOrNullOf(ctx);+ if (owner) owners.push(owner);+ if (!owners.length) {+ ForbiddenError.from(permission).throwUnlessCan(+ ProjectPermissionAgentVaultAccessBundleActions.Edit,+ ProjectPermissionSub.AgentVaultAccessBundles+ );+ }+ return owners;+ };+const notFound = (variableId: string) => new NotFoundError({ message: `Variable with ID '${variableId}' not found` });// A variable the caller may not act on reads exactly like one that does not exist, so an id never confirms that@@ -116,16 +144,30 @@ export const agentVaultVariableServiceFactory = ({};// A member who lost a bundle keeps their personal variables, but not a view into the bundle: its services drop out- // of what they see. Global variables are admin-only, and an admin reaches every bundle.- const splitByReach = async (- { projectId, ctx, owner }: { projectId: string; ctx: TGenericPermission; owner: TAgentVaultOwner | null },- services: TAgentVaultServiceUsingVariable[]- ) => {- if (!owner || !services.length) return { reachable: services, unreachable: [] };+ // of what they see. Global variables are admin-only, and an admin reaches every bundle, so both get null.+ const reachableBundleIdsOf = async ({+ projectId,+ ctx,+ owner+ }: {+ projectId: string;+ ctx: TGenericPermission;+ owner: TAgentVaultOwner | null;+ }) => {+ if (!owner) return null;const { accessBundleIds } = await getAgentVaultReachability({ permissionService, membershipDAL },{ projectId, ctx });+ return accessBundleIds;+ };++ const splitByReach = async (+ args: { projectId: string; ctx: TGenericPermission; owner: TAgentVaultOwner | null },+ services: TAgentVaultServiceUsingVariable[]+ ) => {+ if (!services.length) return { reachable: services, unreachable: [] };+ const accessBundleIds = await reachableBundleIdsOf(args);if (!accessBundleIds) return { reachable: services, unreachable: [] };const reach = new Set(accessBundleIds);return {@@ -157,6 +199,10 @@ export const agentVaultVariableServiceFactory = ({const duplicateKeyMessage = (key: string, { owner }: TAgentVaultVariableOwnerScope) =>owner ? `You already have a variable named '${key}'.` : `A variable named '${key}' already exists.`;+ // `details.field` names the input at fault, so a form can show the message there without matching its text.+ const duplicateKeyError = (key: string, scope: TAgentVaultVariableOwnerScope) =>+ new BadRequestError({ message: duplicateKeyMessage(key, scope), details: { field: "key" } });+const inUseMessage = (key: string,services: TAgentVaultServiceUsingVariable[],@@ -179,19 +225,23 @@ export const agentVaultVariableServiceFactory = ({(await getProjectCipher(projectId)).encryptor({ plainText: Buffer.from(JSON.stringify({ value })) }).cipherTextBlob;const listVariables = async ({ projectId, ctx, scope: scopeName, limit, ...query }: TListVariablesDTO) => {- const scope = await resolveScope({ projectId, ctx }, scopeName);+ const owners = await resolveListOwners({ projectId, ctx }, scopeName);+ const personalOwner = owners.find((owner) => owner !== null) ?? null;// A lookup by keys returns every key that exists unless the caller caps it, so a missing entry always means// the key doesn't exist.+ // The Used By sort counts only what the page will show.+ const accessBundleIds = await reachableBundleIdsOf({ projectId, ctx, owner: personalOwner });const { variables, totalCount } = await agentVaultVariableDAL.findForList({- ...scope,+ projectId,+ owners,...query,+ accessBundleIds: accessBundleIds ?? undefined,limit: limit ?? query.keys?.length ?? AGENT_VAULT_VARIABLE_LIST_DEFAULT_LIMIT});- const { reachable } = await splitByReach(- { projectId, ctx, owner: scope.owner },- await agentVaultVariableDAL.findServicesUsing(variables.map((variable) => variable.id))- );+ const services = await agentVaultVariableDAL.findServicesUsing(variables.map((variable) => variable.id));+ const reach = accessBundleIds ? new Set(accessBundleIds) : null;+ const reachable = reach ? services.filter((service) => reach.has(service.accessBundleId)) : services;return { variables: variables.map((variable) => projectVariable(variable, reachable)), totalCount };};@@ -215,7 +265,7 @@ export const agentVaultVariableServiceFactory = ({const existing = await agentVaultVariableDAL.findKeys(scope, tx);if (existing.some((variable) => variable.key === key)) {- throw new BadRequestError({ message: duplicateKeyMessage(key, scope) });+ throw duplicateKeyError(key, scope);}if (existing.length >= cap) {throw new BadRequestError({@@ -240,7 +290,7 @@ export const agentVaultVariableServiceFactory = ({try {return { variable: projectVariable(await write(), []) };} catch (err) {- if (isUniqueViolation(err)) throw new BadRequestError({ message: duplicateKeyMessage(key, scope) });+ if (isUniqueViolation(err)) throw duplicateKeyError(key, scope);throw err;}};@@ -260,7 +310,7 @@ export const agentVaultVariableServiceFactory = ({if (key !== undefined && key !== current.key) {const clash = await agentVaultVariableDAL.findByKey({ key, ...scope }, tx);- if (clash) throw new BadRequestError({ message: duplicateKeyMessage(key, scope) });+ if (clash) throw duplicateKeyError(key, scope);}// A rename is this row alone. Sealed text names the variable by id, so nothing that uses it changes.@@ -278,7 +328,7 @@ export const agentVaultVariableServiceFactory = ({result = await write();} catch (err) {if (isUniqueViolation(err)) {- throw new BadRequestError({ message: duplicateKeyMessage(key ?? variable.key, scope) });+ throw duplicateKeyError(key ?? variable.key, scope);}throw err;}diff --git a/backend/src/ee/services/agent-vault-variable/agent-vault-variable-types.ts b/backend/src/ee/services/agent-vault-variable/agent-vault-variable-types.tsindex 3fe09bf0aa..4d19c06fb6 100644--- a/backend/src/ee/services/agent-vault-variable/agent-vault-variable-types.ts+++ b/backend/src/ee/services/agent-vault-variable/agent-vault-variable-types.ts@@ -6,9 +6,10 @@ import { TFindAgentVaultVariablesDTO } from "./agent-vault-variable-dal";export type TAgentVaultVariableScoped = { projectId: string; ctx: TGenericPermission };export type TListVariablesDTO = TAgentVaultVariableScoped &- Omit<TFindAgentVaultVariablesDTO, "projectId" | "owner" | "limit"> & {+ Omit<TFindAgentVaultVariablesDTO, "projectId" | "owners" | "limit" | "accessBundleIds"> & {limit?: number;- scope: AgentVaultVariableScope;+ // Omitted lists everything the caller can see: their own, and the global ones too for an admin.+ scope?: AgentVaultVariableScope;};export type TCreateVariableDTO = TAgentVaultVariableScoped & {diff --git a/backend/src/ee/services/agent-vault/CLAUDE.md b/backend/src/ee/services/agent-vault/CLAUDE.mdindex cc33f34708..fab877e21b 100644--- a/backend/src/ee/services/agent-vault/CLAUDE.md+++ b/backend/src/ee/services/agent-vault/CLAUDE.md@@ -8,12 +8,12 @@ would get something wrong from the code alone; cut anything the code already staattaches the real credential on the way out. What an agent may reach lives in a **session** row on our side,never in anything the agent holds.-| Noun | What it is |-| ----------------- | ------------------------------------------------------------------------------------------------ |-| **Access bundle** | A named set of services. The unit you grant |-| **Service** | One host pattern set plus its credential |-| **Session** | A minted token naming one actor, one of their bundles, and an expiry. The token _is_ the session |-| **Proxy** | One deployed egress node with its own CA. One row per box |+| Noun | What it is |+| --- | --- |+| **Access bundle** | A named set of services. The unit you grant |+| **Service** | One host pattern set plus its credential |+| **Session** | A minted token naming one actor, one of their bundles, and an expiry. The token *is* the session |+| **Proxy** | One deployed egress node with its own CA. One row per box |```agent-vault/ shared: enums, host grammar, conflict detection, reachability@@ -129,8 +129,8 @@ and `packages/agentvault/` in the CLI repo. Frontend: `frontend/src/pages/agent-`agent-vault-host-pattern-fns.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 _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+- 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 anallowlist because a prefix is compared against the escaped path: one carrying anything Go's encoderrewrites could never match. `agent-vault-path-prefix-schemas.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,@@ -248,10 +248,11 @@ variables**, rows of `agent_vault_variables` with an owner, that only their ownservice's sealed secret holds only the admin's fields, so a bearer token left to members stores no secret atall and the column is NULL. Code that reads `encryptedCredential` NULL as passthrough has to check`memberProvidedFields` first.-- **One variables resource, two scopes.** `scope` on `/agent-vault/variables` (`global`, the default, or- `personal`) picks the list and the owner of a new one; every variable read and lock in the DAL takes an owner- (`null` for global) so a global lookup never matches a personal key, and resolve expands each kind only against- its own. By id, a variable the caller may not act on is a 404, never a 403: someone else's personal one, and a+- **One variables resource, two scopes.** `scope` on `/agent-vault/variables` (`global` or `personal`) picks the+ list and is required for a new one; a list without it returns everything the caller can see (their own, plus+ the global ones for an admin), and the service sheet's picker asks for `global` explicitly. Every variable read+ and lock in the DAL takes an owner (`null` for global) so a global lookup never matches a personal key, and+ resolve expands each kind only against its own. By id, a variable the caller may not act on is a 404, never a 403: someone else's personal one, and aglobal one for a member. Global keys are unique per project (500 cap), personal ones per owner (100 cap), eachenforced by a partial unique index plus an advisory lock per project or per owner.- **Everything personal is scoped to the caller, never to an id the caller sends.** No route names another actor,@@ -262,7 +263,8 @@ variables**, rows of `agent_vault_variables` with an owner, that only their ownpersonal value against the session actor's personal variables only, so neither is ever expanded twice and apersonal `{{KEY}}` can't reach a global variable. A service whose actor hasn't set every member-provided fieldgoes out with `personalValuesMissing: true` and a passthrough credential. The proxy refuses it with a 403 (CLI- change); an older proxy that ignores the flag forwards the request without a credential, never with the admin's.+ change); an older proxy that ignores the flag forwards it with the service's custom headers and substitutions+ but no credential, never the admin's.- **A save is a PATCH**: a field sent replaces that field's saved value, a field left out keeps it, and everymember-provided field must be set once it's applied. The save takes the service row `FOR SHARE` and re-checksthe fields it validated against, so an admin changing them either waits for it or makes it 409. It also takes@@ -287,11 +289,12 @@ variables**, rows of `agent_vault_variables` with an owner, that only their ownrow `FOR UPDATE` and a personal values save takes the rows it references `FOR SHARE`. Used By on a variable readsboth reference tables; any one variable only ever appears in one of them.- **The API calls them personal values**, the UI's word: a sub-resource of the service- (`PATCH`/`DELETE .../services/:serviceId/personal-values`), always the caller's own, with no collection route. Reads- ride along: the bundle read puts the caller's status on each- service (`personalValues`, null when nothing is member-provided), and the bundle list gives `servicesRequiringSetup` per bundle- plus a `requiresSetup=true` filter for the sidebar and banners. Both count only the bundles granted to the caller,- so an admin isn't nagged about bundles they reach only by role; the bundle read still shows them.+ (`PATCH`/`DELETE .../services/:serviceId/personal-values`), always the caller's own, with no collection route.+ Reads ride along: the bundle read puts the caller's status on each service (`personalValues`, null when nothing+ is member-provided), and the bundle list gives `servicesRequiringSetup` (`{ id, name }`) per bundle plus a+ `requiresSetup` filter for the sidebar and banners (`false` is the rest of what the caller reaches). Both count+ only the bundles granted to the caller, so an admin isn't nagged about bundles they reach only by role; the+ bundle read still shows them.## Credentials at restdiff --git a/backend/src/ee/services/agent-vault/agent-vault-enums.ts b/backend/src/ee/services/agent-vault/agent-vault-enums.tsindex 9987913248..c8debd63b7 100644--- a/backend/src/ee/services/agent-vault/agent-vault-enums.ts+++ b/backend/src/ee/services/agent-vault/agent-vault-enums.ts@@ -64,11 +64,9 @@ export enum AgentVaultVariableScope {* The fields an admin can leave to each member, named as variable references name them: `credential-value` is a* bearer token or a basic password, `credential-username` a basic username.*/-export type TAgentVaultMemberProvidedField =- | AgentVaultVariableReferenceField.CredentialValue- | AgentVaultVariableReferenceField.CredentialUsername;--export const AGENT_VAULT_MEMBER_PROVIDED_FIELDS: readonly TAgentVaultMemberProvidedField[] = [+export const AGENT_VAULT_MEMBER_PROVIDED_FIELDS = [AgentVaultVariableReferenceField.CredentialValue,AgentVaultVariableReferenceField.CredentialUsername-];+] as const;++export type TAgentVaultMemberProvidedField = (typeof AGENT_VAULT_MEMBER_PROVIDED_FIELDS)[number];diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex 5242ca3bb4..07468b94af 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -6640,8 +6640,6 @@ interface AgentVaultPersonalValuesSetEvent {serviceName: string;// The fields this update set. A field it left out kept its saved value.fields: string[];- // False the first time the actor sets up their personal values for this service.- replaced: boolean;variableKeys: string[];};}diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex 2be65c84b9..0abb09f591 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -4484,9 +4484,11 @@ export const AGENT_VAULT = {offset: "How many access bundles to skip.",hostPatterns: "Every host pattern the access bundle's services cover.",requiresSetup:- "true lists only the access bundles granted to you, directly or through a group, that have services still requiring your personal values.",+ "true lists only the access bundles granted to you, directly or through a group, that have services still requiring your personal values. false lists the rest of the access bundles you can reach. Omit to list them all.",servicesRequiringSetup:- "The names of the services in this access bundle that still require your personal values. Counted only for access bundles granted to you, so empty for one you reach only as an admin."+ "The services in this access bundle that still require your personal values. Counted only for access bundles granted to you, so empty for one you reach only as an admin.",+ servicesRequiringSetupId: "The ID of the service, for setting your personal values on it.",+ servicesRequiringSetupName: "The name of the service."},SERVICE: {serviceId: "The ID of the service.",@@ -4560,9 +4562,9 @@ export const AGENT_VAULT = {scope:"global for a variable admins set up for services, or personal for one of your own, which only your personal values can use and only you can see. Personal keys are unique among your own variables.",listScope:- "Which variables to list: global (the default), which needs the admin role, or personal for your own. Nobody can list another member's personal variables.",+ "Which variables to list: global, which needs the admin role, or personal for your own. Omit to list everything you can see: your own personal variables, plus the global ones if you're an admin. Nobody can list another member's personal variables.",createScope:- "global (the default) creates a variable services can use, which needs the admin role. personal creates one of your own, which only your personal values can use.",+ "global creates a variable services can use, which needs the admin role. personal creates one of your own, which only your personal values can use.",key: "The name values use to refer to the variable, as `{{KEY}}`. Starts with a letter and uses only upper case letters, numbers and underscores.",value: "The value the proxy puts in place of each `{{KEY}}`.",updateValue: "The value the proxy puts in place of each `{{KEY}}`. Omit to keep the stored value.",diff --git a/docs/documentation/platform/agent-vault/access-bundles.mdx b/docs/documentation/platform/agent-vault/access-bundles.mdxindex ac246a16b4..5ba8d3902c 100644--- a/docs/documentation/platform/agent-vault/access-bundles.mdx+++ b/docs/documentation/platform/agent-vault/access-bundles.mdx@@ -12,10 +12,7 @@ You can reuse access bundles across as many sessions as you like. This makes the- A **marketing** bundle that grants access to Twilio and Google Docs<Frame>- <img- src="/images/platform/agent-vault/access-bundles-list.png"- alt="The Access Bundles page listing four access bundles with their services and member counts"- />+ <img src="/images/platform/agent-vault/access-bundles-list.png" alt="The Access Bundles page listing four access bundles with their services and member counts" /></Frame>## Create an access bundle@@ -24,14 +21,14 @@ To create a new access bundle:<Steps><Step>- In Agent Vault, go to **Access Bundles** and select **Create Access- Bundle**.+ In Agent Vault, go to **Access Bundles** and select **Create Access Bundle**.</Step><Step>- Give the bundle a name that says what job it's for, like **code-review** or- **marketing**.+ Give the bundle a name that says what job it's for, like **code-review** or **marketing**.+ </Step>+ <Step>+ Select **Create**. The access bundle will appear in the list.</Step>- <Step>Select **Create**. The access bundle will appear in the list.</Step></Steps>Now you can [add services](/documentation/platform/agent-vault/services#add-a-service) to the access bundle so agents using it can make authenticated requests.@@ -81,9 +78,11 @@ To set up your personal values:</Step></Steps>-Only you can read your personal values, so admins can't see them either.+Infisical never shows your personal values to anyone else, admins included.- To change your personal values, open the service's actions menu, select **Update My Personal Values**, and enter the values you want to change (a field you leave blank keeps its saved value)- To delete your personal values, select **Remove** in the same dialog, then select **Remove Personal Values**If an admin removes you from the access bundle or from Agent Vault, Infisical deletes the personal values you set up for its services.++Machine identities can set up personal values too, through the [API](/api-reference/endpoints/agent-vault-services/set-personal-values). An identity keeps its own [personal variables](/documentation/platform/agent-vault/variables#personal-variables) the same way.diff --git a/docs/documentation/platform/agent-vault/access-control.mdx b/docs/documentation/platform/agent-vault/access-control.mdxindex 7d5762b240..04329d197d 100644--- a/docs/documentation/platform/agent-vault/access-control.mdx+++ b/docs/documentation/platform/agent-vault/access-control.mdx@@ -26,7 +26,7 @@ Agent Vault has one member list for your whole organization, instead of one per| Role | What they can do ||------|------------------|| **Admin** | <ul><li>Create and manage access bundles, services, variables, and proxies</li><li>Grant access bundles</li><li>Manage membership</li><li>Read audit logs</li></ul> |-| **Member** | <ul><li>Create sessions with the access bundles granted to them</li><li>Revoke their own sessions</li></ul> |+| **Member** | <ul><li>Create sessions with the access bundles granted to them</li><li>Revoke their own sessions</li><li>Set up their [personal values](/documentation/platform/agent-vault/access-bundles#set-up-your-personal-values) and keep [personal variables](/documentation/platform/agent-vault/variables#personal-variables)</li></ul> |An admin can use every access bundle without a grant. A member can't use an access bundle until an admin grants it, and only sees the bundles granted to them. On the **Sessions** page, members see their own sessions, and admins can switch between **All Sessions** and **My Sessions**.diff --git a/docs/documentation/platform/agent-vault/proxies.mdx b/docs/documentation/platform/agent-vault/proxies.mdxindex f57616b99a..12f4684764 100644--- a/docs/documentation/platform/agent-vault/proxies.mdx+++ b/docs/documentation/platform/agent-vault/proxies.mdx@@ -145,6 +145,7 @@ The proxy also returns a 403 for:- A request to a port the service's [host pattern](/documentation/platform/agent-vault/services#host-patterns) doesn't name, such as `example.com:8443` for a service on `example.com`, which only covers port `443`- A request that breaks the service's [method or path rules](/documentation/platform/agent-vault/services#methods-and-paths), under either traffic policy+- A request to a service that needs [your personal values](/documentation/platform/agent-vault/access-bundles#set-up-your-personal-values), before you set them up### Exceptionsdiff --git a/docs/documentation/platform/agent-vault/services.mdx b/docs/documentation/platform/agent-vault/services.mdxindex cde0a92047..86ea15281a 100644--- a/docs/documentation/platform/agent-vault/services.mdx+++ b/docs/documentation/platform/agent-vault/services.mdx@@ -6,18 +6,13 @@ description: "External APIs that an AI agent can securely call during a session.A service represents one external API that an agent can access during a [session](/documentation/platform/agent-vault/sessions). Each service defines the external API’s [host URL](#host-patterns), its [authentication method](#credential-types), and a real credential to attach when forwarding requests from the agent.<Tip>- A service can also limit which [HTTP methods and paths](#methods-and-paths)- the agent can use, [add custom headers](#custom-headers) to each request, and- [replace placeholder values](#substitutions) the agent sends with real ones.+A service can also limit which [HTTP methods and paths](#methods-and-paths) the agent can use, [add custom headers](#custom-headers) to each request, and [replace placeholder values](#substitutions) the agent sends with real ones.</Tip>You can configure services within an [access bundle](/documentation/platform/agent-vault/access-bundles). For example, you might create a **code-review** access bundle and add services for Slack, GitHub, and Anthropic:<Frame>- <img- src="/images/platform/agent-vault/access-bundle-services.png"- alt="The code-review access bundle's Services table listing its GitHub, Slack, and Anthropic services with their credentials and hosts"- />+ <img src="/images/platform/agent-vault/access-bundle-services.png" alt="The code-review access bundle's Services table listing its GitHub, Slack, and Anthropic services with their credentials and hosts" /></Frame>## Add a service@@ -34,13 +29,11 @@ To add a service to an access bundle:<Frame><img src="/images/platform/agent-vault/service-template-picker.png" alt="The Choose a template panel with Custom, OpenAI, Anthropic, Slack, GitHub, and Google Workspace" /></Frame>-</Step><Step>Follow the steps and paste your credentials in the **Credential** section.To use a value that several services share, type `{{` in a [field that accepts variables](/documentation/platform/agent-vault/variables#use-a-variable-in-a-service) and select a variable from the list that opens.-</Step><Step>Select **Add Service**. The service appears in the bundle's list.@@ -52,8 +45,7 @@ To add a service to an access bundle:When configuring a service, you have the option to set its credential type. This determines what the proxy attaches to outbound requests.<Tip>- If you're configuring a service with a template, you can usually leave the- credential type set to the default.+If you're configuring a service with a template, you can usually leave the credential type set to the default.</Tip>### Bearer@@ -75,9 +67,7 @@ The proxy attaches no credential. Unless the service adds [custom headers](#custPass-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.<Note>- For **Bearer** and **Basic** services, if the agent's request already carries- a header with the same name as the one the service sends, the proxy replaces- it with the service's credential.+For **Bearer** and **Basic** services, if the agent's request already carries a header with the same name as the one the service sends, the proxy replaces it with the service's credential.</Note>## Member-provided values@@ -93,12 +83,14 @@ To make a field member provided:<Steps><Step>- In Agent Vault, go to **Access Bundles** and select the access bundle. Open- the service's actions menu and select **Edit**, then go to the- **Credential** step.+ In Agent Vault, go to **Access Bundles** and select the access bundle. Open the service's actions menu and select **Edit**, then go to the **Credential** step.+ </Step>+ <Step>+ Next to the field, turn on **Member provided**.+ </Step>+ <Step>+ Select **Continue**, then select **Save**.</Step>- <Step>Next to the field, turn on **Member provided**.</Step>- <Step>Select **Continue**, then select **Save**.</Step></Steps>When you change which fields are member provided, members keep the values that still apply:@@ -107,8 +99,7 @@ When you change which fields are member provided, members keep the values that s- If you stop leaving a field to members, Infisical deletes their values for that field only<Warning>- If you change the credential type, Infisical deletes every member's personal- values for the service, and each member has to set them up again.+If you change the credential type, Infisical deletes every member's personal values for the service, and each member has to set them up again.</Warning>Until a member [sets up their personal values](/documentation/platform/agent-vault/access-bundles#set-up-your-personal-values), the proxy refuses their sessions' requests to the service with a `403` response. Requests to the bundle's other services still go through.@@ -118,9 +109,7 @@ Until a member [sets up their personal values](/documentation/platform/agent-vauWhen configuring a service, you have the option to set which host patterns it matches. A host pattern controls which outbound requests get the service's credential attached.<Tip>- For security reasons, we recommend keeping host patterns as narrow as the API- allows. If you're configuring a service with a template, you can usually leave- the host set to the default.+For security reasons, we recommend keeping host patterns as narrow as the API allows. If you're configuring a service with a template, you can usually leave the host set to the default.</Tip>### Multiple hosts@@ -162,9 +151,7 @@ internal-api.example.com:8080If you don't name the port, the host will only match [port `443`](#default-port):<Warning>- The proxy sends the credential to a plaintext host unencrypted, so anyone who- can read traffic between the proxy and the API can read the credential. Only- use plaintext hosts on a network you trust.+The proxy sends the credential to a plaintext host unencrypted, so anyone who can read traffic between the proxy and the API can read the credential. Only use plaintext hosts on a network you trust.</Warning>### Wildcards@@ -187,16 +174,11 @@ However, two services can match the same host if they define the host pattern diIn the above example, requests to `api.github.com` are handled by the first service.<Warning>- The proxy applies only the more specific service's [methods and- paths](#methods-and-paths). This means that if the `api.github.com` service- allows only `GET`, the proxy refuses a `POST` to `api.github.com`, even if- that same `POST` request would succeed through `*.github.com`.+The proxy applies only the more specific service's [methods and paths](#methods-and-paths). This means that if the `api.github.com` service allows only `GET`, the proxy refuses a `POST` to `api.github.com`, even if that same `POST` request would succeed through `*.github.com`.</Warning><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.+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>## Methods and paths@@ -204,10 +186,7 @@ In the above example, requests to `api.github.com` are handled by the first servBy 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 paths 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"- />+ <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@@ -219,10 +198,7 @@ On the **Details** step, clear **All Methods** and select the HTTP methods the sOn the **Details** step's **Paths** field, enter each path prefix 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.<Note>- If a service has path prefixes, the proxy also refuses any path that different- servers would resolve differently, such as one containing `..` or an encoded- slash. Ordinary paths still work, including ones with a space or a non-ASCII- character such as `/repos/owner/repo/contents/café.md`.+If a service has path prefixes, the proxy also refuses any path that different servers would resolve differently, such as one containing `..` or an encoded slash. Ordinary paths still work, including ones with a space or a non-ASCII character such as `/repos/owner/repo/contents/café.md`.</Note>### Refused requests@@ -246,19 +222,13 @@ service "github" does not allow path "/admin": blocked by service policySome APIs need a header alongside the credential, such as an organization ID or an API version. On the **Credential** step, under **Advanced Options**, select **Add Custom Header** and enter 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"- />+ <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>Infisical won't save a custom header with the same name as the credential's header, because the proxy would overwrite it with the credential. Infisical also won't save a custom header that the proxy sets itself, such as `Host`, `Content-Length`, or `Connection`.<Tip>- A custom header's value can include a [substitution](#substitutions)- placeholder. If that substitution has **Headers** selected under **Replace- In**, the proxy replaces the placeholder with the real value, so several- headers can reuse one secret.+A custom header's value can include a [substitution](#substitutions) placeholder. If that substitution has **Headers** selected under **Replace In**, the proxy replaces the placeholder with the real value, so several headers can reuse one secret.</Tip>## Substitutions@@ -276,7 +246,7 @@ GitHub receives the real token, and the agent never holds it.We recommend using substitutions when your agent's tool won't run without a token of its own, or when the API expects the credential outside a header, such as in the URL path or the query string.<Info>- Substitutions work with every credential type, including pass-through.+Substitutions work with every credential type, including pass-through.</Info>### Add a substitution@@ -291,7 +261,6 @@ We recommend using substitutions when your agent's tool won't run without a toke<Tip>The proxy replaces every occurrence of the placeholder, so pick one that won't appear anywhere else in the request.</Tip>-</Step><Step>Under **Replace In**, select where the proxy looks for the placeholder: **URL Path**, **Query String**, **Headers**, or **Body**.@@ -302,7 +271,6 @@ We recommend using substitutions when your agent's tool won't run without a toke<Tip>Some tools check a token's format before they send it. If the agent's tool does, make the placeholder match the format of the real key, such as `ghp_` followed by 36 characters for a GitHub token.</Tip>-</Step></Steps>diff --git a/docs/documentation/platform/agent-vault/sessions-cli.mdx b/docs/documentation/platform/agent-vault/sessions-cli.mdxindex a2051b3ab0..1e4afcdbb4 100644--- a/docs/documentation/platform/agent-vault/sessions-cli.mdx+++ b/docs/documentation/platform/agent-vault/sessions-cli.mdx@@ -179,6 +179,9 @@ If you've [set up session logs](/documentation/platform/agent-vault/session-logs<Accordion title="The agent loses access to APIs partway through a run">If the agent's requests start failing with a 403 from the proxy, such as `CONNECT tunnel failed, response 403`, the session expired before the agent finished. Set a longer `--ttl`.</Accordion>+ <Accordion title="Requests to a service fail with "needs your personal values"">+ The service is [member provided](/documentation/platform/agent-vault/services#member-provided-values), and whoever the session belongs to hasn't set up their personal values for it yet. A user sets them up under **Access Bundles**: select the bundle named in the message, then [set up the personal values](/documentation/platform/agent-vault/access-bundles#set-up-your-personal-values). A machine identity sets them up through the [API](/api-reference/endpoints/agent-vault-services/set-personal-values). Once they're saved, the proxy picks them up within one [poll interval](/documentation/platform/agent-vault/proxies#poll-interval).+ </Accordion><Accordion title="A session stays Active after the agent stopped">The CLI couldn't revoke the session, for example because the machine shut down or the process was killed with `SIGKILL`. [Revoke the session](/documentation/platform/agent-vault/sessions#revoke-a-session) on the **Sessions** page, or let it expire at the end of its `--ttl`.</Accordion>diff --git a/docs/documentation/platform/agent-vault/variables.mdx b/docs/documentation/platform/agent-vault/variables.mdxindex eed94b11f2..8d68c1bd25 100644--- a/docs/documentation/platform/agent-vault/variables.mdx+++ b/docs/documentation/platform/agent-vault/variables.mdx@@ -36,7 +36,7 @@ To add a variable:Enter a **Key** and a **Value**. To view the value later, select the eye icon next to it. Each time someone views or copies a value, Infisical adds an event to the audit log.<Note>- A key can be up to 64 characters long. It must start with a letter and use only uppercase letters, numbers, and underscores. No two variables can have the same key.+ A key can be up to 64 characters long. It must start with a letter and use only uppercase letters, numbers, and underscores. No two global variables can have the same key.</Note></Step>@@ -51,7 +51,7 @@ To add a variable:</Steps><Note>-Agent Vault can hold up to 500 variables.+Agent Vault can hold up to 500 global variables.</Note>## Use a variable in a service@@ -157,4 +157,5 @@ To see your personal variables, go to **Variables** in Agent Vault. If you're anYou add, update, and delete personal variables the same way as [global variables](#add-a-variable), with these limits:- You can keep up to 100 personal variables+- Your personal variable keys need to be unique among your own variables only, so one can share a key with a global variable or with another member's personal variable- If your personal values for a service use a variable, you can't delete the variable until you change those valuesdiff --git a/frontend/src/components/agent-vault/PersonalValuesDialog.tsx b/frontend/src/components/agent-vault/PersonalValuesDialog.tsxindex f7fb79808a..26a46964e7 100644--- a/frontend/src/components/agent-vault/PersonalValuesDialog.tsx+++ b/frontend/src/components/agent-vault/PersonalValuesDialog.tsx@@ -276,7 +276,9 @@ export const PersonalValuesDialog = ({ target, onOpenChange }: Props) => {<Dialog open={isOpen} onOpenChange={onOpenChange}><DialogContent><DialogHeader>- <DialogTitle>Set up {service?.name}</DialogTitle>+ <DialogTitle>+ {personalValues?.isConfigured ? "Update" : "Set Up"} Personal Values for {service?.name}+ </DialogTitle><DialogDescription>{personalValues?.isConfigured && lastSetAt? `You set these up on ${format(new Date(lastSetAt), "MMM d, yyyy")}. Sessions you start with ${target?.accessBundleName} use them. A field you leave blank keeps its saved value.`diff --git a/frontend/src/components/agent-vault/VariableFormDialog.tsx b/frontend/src/components/agent-vault/VariableFormDialog.tsxindex d922dbac0f..aa07bfca7d 100644--- a/frontend/src/components/agent-vault/VariableFormDialog.tsx+++ b/frontend/src/components/agent-vault/VariableFormDialog.tsx@@ -209,8 +209,7 @@ const VariableForm = ({: undefined;if (serverResponse?.error === ApiErrorTypes.BadRequestError &&- (serverResponse.message.endsWith("already exists.") ||- serverResponse.message.startsWith("You already have a variable named"))+ (serverResponse.details as { field?: string } | undefined)?.field === "key") {setError("key", { type: TAKEN_KEY_ERROR_TYPE, message: serverResponse.message });}diff --git a/frontend/src/components/agent-vault/nameList.test.ts b/frontend/src/components/agent-vault/nameList.test.tsnew file mode 100644index 0000000000..833d8c6e4c--- /dev/null+++ b/frontend/src/components/agent-vault/nameList.test.ts@@ -0,0 +1,15 @@+import { describe, expect, test } from "vitest";++import { nameList } from "./nameList";++describe("nameList", () => {+ test.each([+ [["a"], undefined, "a"],+ [["a", "b"], undefined, "a and b"],+ [["a", "b", "c"], undefined, "a, b and c"],+ [["a", "b", "c", "d"], undefined, "a, b, c and 1 more"],+ [["a", "b", "c"], 17, "a, b, c and 14 more"]+ ])("%j of %s", (names, total, expected) => {+ expect(nameList(names, total)).toBe(expected);+ });+});diff --git a/frontend/src/components/agent-vault/nameList.ts b/frontend/src/components/agent-vault/nameList.tsnew file mode 100644index 0000000000..5a4e6a433d--- /dev/null+++ b/frontend/src/components/agent-vault/nameList.ts@@ -0,0 +1,13 @@+const NAMES_SHOWN = 3;++/**+ * Names a list for a sentence: "a", "a and b", "a, b and c", and past three, "a, b, c and 4 more". `total` counts+ * names a page didn't load, so a capped list still reports how many there are.+ */+export const nameList = (names: string[], total = names.length) => {+ const shown = names.slice(0, NAMES_SHOWN);+ const more = total - shown.length;+ if (more > 0) return `${shown.join(", ")} and ${more} more`;+ if (shown.length <= 2) return shown.join(" and ");+ return `${shown.slice(0, -1).join(", ")} and ${shown[shown.length - 1]}`;+};diff --git a/frontend/src/components/agent-vault/service-sheet/CredentialFields.tsx b/frontend/src/components/agent-vault/service-sheet/CredentialFields.tsxindex c760aa4831..012963eea1 100644--- a/frontend/src/components/agent-vault/service-sheet/CredentialFields.tsx+++ b/frontend/src/components/agent-vault/service-sheet/CredentialFields.tsx@@ -363,6 +363,18 @@ export const CredentialFields = ({ storedType, storedMemberFields = [] }: Props)// A bearer token and a basic password are both credential-value.const secretCredentialField = AgentVaultVariableReferenceField.CredentialValue;+ // Saving deletes what members set: all of it on a type change, or one field's when it's taken back.+ const isDeletingAllMemberValues =+ Boolean(storedType) && storedMemberFields.length > 0 && credentialType !== storedType;+ const memberValuesNote = (field: TAgentVaultMemberProvidedField, label: string) =>+ storedType === credentialType &&+ storedMemberFields.includes(field) &&+ !isMemberProvided(field) && (+ <FieldDescription>+ Members' saved {label.toLowerCase()}s are deleted when you save.+ </FieldDescription>+ );+useEffect(() => {if (!storedType || credentialType === storedType) return;if (isUntouched) setValue("secret", "");@@ -429,6 +441,7 @@ export const CredentialFields = ({ storedType, storedMemberFields = [] }: Props)storedKeys={hasStoredValue(secretCredentialField) ? storedKeys.secret : undefined}/>)}+ {memberValuesNote(secretCredentialField, secretLabel)}<FieldError>{fieldState.error?.message}</FieldError></FieldContent></Field>@@ -457,6 +470,11 @@ export const CredentialFields = ({ storedType, storedMemberFields = [] }: Props)))}</SelectContent></Select>+ {isDeletingAllMemberValues && (+ <FieldDescription>+ Members' saved values for this service are deleted when you save.+ </FieldDescription>+ )}</FieldContent></Field>)}@@ -527,6 +545,10 @@ export const CredentialFields = ({ storedType, storedMemberFields = [] }: Props)}/>)}+ {memberValuesNote(+ AgentVaultVariableReferenceField.CredentialUsername,+ "Username"+ )}<FieldError>{fieldState.error?.message}</FieldError></FieldContent></Field>diff --git a/frontend/src/components/agent-vault/service-sheet/ReviewFields.tsx b/frontend/src/components/agent-vault/service-sheet/ReviewFields.tsxindex 23dc8ff5ea..03119afab2 100644--- a/frontend/src/components/agent-vault/service-sheet/ReviewFields.tsx+++ b/frontend/src/components/agent-vault/service-sheet/ReviewFields.tsx@@ -53,9 +53,11 @@ const alignColumns = (rows: string[][]) => {type Props = {isUpdate: boolean;+ /** The fields that were member-provided when the sheet opened, which have no stored value behind them. */+ storedMemberFields?: TAgentVaultMemberProvidedField[];};-export const ReviewFields = ({ isUpdate }: Props) => {+export const ReviewFields = ({ isUpdate, storedMemberFields = [] }: Props) => {const { watch } = useFormContext<TServiceForm>();const form = watch();@@ -83,7 +85,8 @@ export const ReviewFields = ({ isUpdate }: Props) => {field: TAgentVaultMemberProvidedField) => {if (form.memberProvidedFields.includes(field)) return "Set by each member";- if (!isUpdate) return value ? "Set" : "None";+ // A field taken back from members had no value of the admin's to replace or clear.+ if (!isUpdate || storedMemberFields.includes(field)) return value ? "Set" : "None";if (value === UNCHANGED_SECRET) return "Unchanged";if (value) return "Replaced";return canClear ? "Cleared" : "Unchanged";diff --git a/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx b/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsxindex 703967b67b..c9e808b95c 100644--- a/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx+++ b/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx@@ -702,7 +702,12 @@ export const ServiceSheet = ({</div></ServiceVariablesContext.Provider>)}- {current.step === ServiceStep.Review && <ReviewFields isUpdate={isUpdate} />}+ {current.step === ServiceStep.Review && (+ <ReviewFields+ isUpdate={isUpdate}+ storedMemberFields={service ? storedMemberFields(service) : undefined}+ />+ )}</div><aside className="hidden w-80 shrink-0 flex-col gap-4 overflow-y-auto border-l border-border px-6 py-6 lg:flex">diff --git a/frontend/src/components/agent-vault/service-sheet/VariableSuggestions.tsx b/frontend/src/components/agent-vault/service-sheet/VariableSuggestions.tsxindex b1a99f90cf..0f5d94962c 100644--- a/frontend/src/components/agent-vault/service-sheet/VariableSuggestions.tsx+++ b/frontend/src/components/agent-vault/service-sheet/VariableSuggestions.tsx@@ -11,6 +11,7 @@ import {} from "@app/helpers/agentVaultVariables";import { useDebounce } from "@app/hooks";import {+ AgentVaultVariableScope,useAgentVaultVariableKeyStatus,useListAgentVaultVariables} from "@app/hooks/api/agentVault";@@ -43,7 +44,11 @@ export const useVariableAutocomplete = ({// Searched on the server, so the list never has to hold every variable. The last page stays up while the next// loads, filtered to the new text, which a longer query only narrows.const { data: searched, isPlaceholderData } = useListAgentVaultVariables(- { search: debouncedQuery || undefined, limit: SUGGESTION_LIMIT },+ {+ scope: AgentVaultVariableScope.Global,+ search: debouncedQuery || undefined,+ limit: SUGGESTION_LIMIT+ },{ enabled: isOpen && !isLocal });// A search can show only so many, and the exact key may not be among them, so whether to offer to create it is@@ -346,11 +351,18 @@ export const VariableSuggestions = ({</>) : (<p className="px-2 py-1.5 text-xs text-muted">- {isLoading ? "Loading variables..." : "No variables yet. Type a key to create one."}+ {isLoading && "Loading variables..."}+ {!isLoading && isPicker && (+ <>+ No variables yet. Type <code className="font-mono">{"{{"}</code> in the field to+ create one.+ </>+ )}+ {!isLoading && !isPicker && "No variables yet. Type a key to create one."}</p>)}- {/* Only when the list was opened from the button: someone who typed {{ already knows. */}- {isPicker && (+ {/* Only when the button opened a list there is something to pick from: someone who typed {{ already knows. */}+ {isPicker && suggestions.length > 0 && (<><div className="-mx-1 my-1 h-px bg-border" /><p className="px-2 py-1.5 text-xs text-muted">diff --git a/frontend/src/hooks/api/agentVault/types.ts b/frontend/src/hooks/api/agentVault/types.tsindex 71a191d409..b6ba96ff08 100644--- a/frontend/src/hooks/api/agentVault/types.ts+++ b/frontend/src/hooks/api/agentVault/types.ts@@ -208,7 +208,7 @@ export type TAgentVaultAccessBundleListItem = TAgentVaultAccessBundle & {memberCount: number;hostPatterns: string[];// Counted over the bundles granted to the caller, so empty on one an admin reaches only by role.- servicesRequiringSetup: string[];+ servicesRequiringSetup: { id: string; name: string }[];};export type TAgentVaultAccessBundleDetails = TAgentVaultAccessBundle & {@@ -446,7 +446,7 @@ export type TAgentVaultVariable = {};export type TCreateAgentVaultVariableDTO = {- scope?: AgentVaultVariableScope;+ scope: AgentVaultVariableScope;key: string;value: string;};diff --git a/frontend/src/hooks/api/types.ts b/frontend/src/hooks/api/types.tsindex f82520cb65..1142441cec 100644--- a/frontend/src/hooks/api/types.ts+++ b/frontend/src/hooks/api/types.ts@@ -78,6 +78,7 @@ export type TApiErrors =statusCode: 400;message: string;error: ApiErrorTypes.BadRequestError;+ details?: unknown;}| {reqId: string;diff --git a/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/AgentVaultAccessBundleDetailPage.tsx b/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/AgentVaultAccessBundleDetailPage.tsxindex c4ebeca866..7df7b96e15 100644--- a/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/AgentVaultAccessBundleDetailPage.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/AgentVaultAccessBundleDetailPage.tsx@@ -14,6 +14,7 @@ import {import { AccessBundleFormDialog } from "@app/components/agent-vault/AccessBundleFormDialog";import { ManageAccessSheet } from "@app/components/agent-vault/ManageAccessSheet";+import { nameList } from "@app/components/agent-vault/nameList";import { PersonalValuesDialog } from "@app/components/agent-vault/PersonalValuesDialog";import { ServiceSheet } from "@app/components/agent-vault/service-sheet";import {@@ -141,7 +142,7 @@ export const AgentVaultAccessBundleDetailPage = () => {<p>{needsSetup.length === 1? `${needsSetup[0].name} requires your personal values.`- : `${needsSetup.length} services require your personal values: ${needsSetup.map((service) => service.name).join(", ")}.`}{" "}+ : `${needsSetup.length} services require your personal values: ${nameList(needsSetup.map((service) => service.name))}.`}{" "}Sessions from this bundle can't reach {needsSetup.length === 1 ? "it" : "them"}{" "}until you set {needsSetup.length === 1 ? "it" : "them"} up.</p>diff --git a/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/ServicesCard.tsx b/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/ServicesCard.tsxindex b247b87ddd..2e9b89c3d4 100644--- a/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/ServicesCard.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/ServicesCard.tsx@@ -242,92 +242,87 @@ export const ServicesCard = ({</TableRow></TableHeader><TableBody>- {displayed.map((service) => {- const serviceValues = service.personalValues;- return (- <TableRow key={service.id}>- <TableCell>- <div className="flex items-center gap-2">- <ServiceIcon hostPattern={service.hostPattern} />- {service.name}- </div>- </TableCell>- <TableCell>- <HostsCell hostPattern={service.hostPattern} />- </TableCell>- <TableCell>- <Tooltip>- <TooltipTrigger asChild>- <span className="text-sm">- {format(new Date(service.createdAt), "MMM d, yyyy")}- </span>- </TooltipTrigger>- <TooltipContent>- {format(new Date(service.createdAt), "MMM d, yyyy h:mm a")}- </TooltipContent>- </Tooltip>- </TableCell>- <TableCell>- <div className="flex justify-center">- {serviceValues &&- (serviceValues.isConfigured ? (- <Badge variant="neutral" asChild>- <button type="button" onClick={() => onSetUp(service)}>- <CircleCheckIcon />- Configured- </button>- </Badge>- ) : (- <Badge variant="warning" asChild>- <button type="button" onClick={() => onSetUp(service)}>- <TriangleAlertIcon />- Requires Setup- </button>- </Badge>- ))}- </div>- </TableCell>- <TableCell variant="action">- <div className="flex items-center justify-end gap-1.5">- {(canManage || serviceValues) && (- <DropdownMenu>- <DropdownMenuTrigger asChild>- <IconButton variant="ghost" size="xs" aria-label="Open service actions">- <MoreHorizontalIcon />- </IconButton>- </DropdownMenuTrigger>- <DropdownMenuContent sideOffset={2} align="end">- {serviceValues && (- <DropdownMenuItem onClick={() => onSetUp(service)}>- <KeyIcon />- {serviceValues.isConfigured- ? "Update My Personal Values"- : "Set Up My Personal Values"}- </DropdownMenuItem>- )}- {canManage && (- <>- <DropdownMenuItem onClick={() => onEdit(service)}>- <PencilIcon />- Edit- </DropdownMenuItem>- <DropdownMenuItem- variant="danger"- onClick={() => setServiceToDelete(service)}- >- <TrashIcon />- Delete- </DropdownMenuItem>- </>- )}- </DropdownMenuContent>- </DropdownMenu>- )}- </div>- </TableCell>- </TableRow>- );- })}+ {displayed.map((service) => (+ <TableRow key={service.id}>+ <TableCell>+ <div className="flex items-center gap-2">+ <ServiceIcon hostPattern={service.hostPattern} />+ {service.name}+ </div>+ </TableCell>+ <TableCell>+ <HostsCell hostPattern={service.hostPattern} />+ </TableCell>+ <TableCell>+ <Tooltip>+ <TooltipTrigger asChild>+ <span className="text-sm">+ {format(new Date(service.createdAt), "MMM d, yyyy")}+ </span>+ </TooltipTrigger>+ <TooltipContent>+ {format(new Date(service.createdAt), "MMM d, yyyy h:mm a")}+ </TooltipContent>+ </Tooltip>+ </TableCell>+ <TableCell>+ <div className="flex justify-center">+ {service.personalValues &&+ (service.personalValues.isConfigured ? (+ <Badge variant="neutral" asChild>+ <button type="button" onClick={() => onSetUp(service)}>+ <CircleCheckIcon />+ Configured+ </button>+ </Badge>+ ) : (+ <Badge variant="warning" asChild>+ <button type="button" onClick={() => onSetUp(service)}>+ <TriangleAlertIcon />+ Requires Setup+ </button>+ </Badge>+ ))}+ </div>+ </TableCell>+ <TableCell variant="action">+ {(canManage || service.personalValues) && (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <IconButton variant="ghost" size="xs" aria-label="Open service actions">+ <MoreHorizontalIcon />+ </IconButton>+ </DropdownMenuTrigger>+ <DropdownMenuContent sideOffset={2} align="end">+ {service.personalValues && (+ <DropdownMenuItem onClick={() => onSetUp(service)}>+ <KeyIcon />+ {service.personalValues.isConfigured+ ? "Update My Personal Values"+ : "Set Up My Personal Values"}+ </DropdownMenuItem>+ )}+ {canManage && (+ <>+ <DropdownMenuItem onClick={() => onEdit(service)}>+ <PencilIcon />+ Edit+ </DropdownMenuItem>+ <DropdownMenuItem+ variant="danger"+ onClick={() => setServiceToDelete(service)}+ >+ <TrashIcon />+ Delete+ </DropdownMenuItem>+ </>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ )}+ </TableCell>+ </TableRow>+ ))}</TableBody></Table>)}diff --git a/frontend/src/pages/agent-vault/AgentVaultAccessBundlesPage/AgentVaultAccessBundlesPage.tsx b/frontend/src/pages/agent-vault/AgentVaultAccessBundlesPage/AgentVaultAccessBundlesPage.tsxindex f56cad81df..d7984e7525 100644--- a/frontend/src/pages/agent-vault/AgentVaultAccessBundlesPage/AgentVaultAccessBundlesPage.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultAccessBundlesPage/AgentVaultAccessBundlesPage.tsx@@ -18,6 +18,7 @@ import { twMerge } from "tailwind-merge";import { AccessBundleFormDialog } from "@app/components/agent-vault/AccessBundleFormDialog";import { ManageAccessSheet } from "@app/components/agent-vault/ManageAccessSheet";+import { nameList } from "@app/components/agent-vault/nameList";import { ServiceIconStack } from "@app/components/agent-vault/ServiceIconStack";import {Alert,@@ -118,6 +119,8 @@ export const AgentVaultAccessBundlesPage = () => {// From its own query rather than the page shown, so a bundle on a later page is still called out.const { data: requiringSetup } = useListAgentVaultAccessBundlesRequiringSetup();const bundlesNeedingSetup = requiringSetup?.accessBundles ?? [];+ // The query loads at most a page of them; the count comes from the server.+ const bundlesNeedingSetupCount = requiringSetup?.totalCount ?? 0;const totalCount = data?.totalCount ?? 0;useResetPageHelper({ totalCount, offset: (page - 1) * perPage, setPage });@@ -172,9 +175,12 @@ export const AgentVaultAccessBundlesPage = () => {<TriangleAlertIcon /><AlertDescription><p>- {bundlesNeedingSetup.length === 1+ {bundlesNeedingSetupCount === 1? `${bundlesNeedingSetup[0].name} has services that require your personal values.`- : `${bundlesNeedingSetup.length} access bundles have services that require your personal values: ${bundlesNeedingSetup.map((bundle) => bundle.name).join(", ")}.`}{" "}+ : `${bundlesNeedingSetupCount} access bundles have services that require your personal values: ${nameList(+ bundlesNeedingSetup.map((bundle) => bundle.name),+ bundlesNeedingSetupCount+ )}.`}{" "}Sessions can't reach those services until you set them up.</p><AlertAction>@@ -214,8 +220,8 @@ export const AgentVaultAccessBundlesPage = () => {</CardAction>)}</CardHeader>- <CardContent className="flex items-center gap-2">- <InputGroup className="flex-1">+ <CardContent>+ <InputGroup><InputGroupAddon><SearchIcon /></InputGroupAddon>@@ -355,59 +361,60 @@ export const AgentVaultAccessBundlesPage = () => {</TooltipTrigger><TooltipContent className="max-w-xs">Your personal values are missing for{" "}- {bundle.servicesRequiringSetup.join(", ")}.+ {nameList(+ bundle.servicesRequiringSetup.map((service) => service.name)+ )}+ .</TooltipContent></Tooltip>)}</div></TableCell><TableCell variant="action">- <div className="flex items-center justify-end gap-1.5">- {isAdmin && (- <DropdownMenu>- <DropdownMenuTrigger asChild>- <IconButton- variant="ghost"- size="xs"- aria-label="Open access bundle actions"- onClick={(event) => event.stopPropagation()}- >- <MoreHorizontalIcon />- </IconButton>- </DropdownMenuTrigger>- <DropdownMenuContent sideOffset={2} align="end">- <DropdownMenuItem- onClick={(event) => {- event.stopPropagation();- setBundleToManage(bundle);- }}- >- <UsersIcon />- Manage Access- </DropdownMenuItem>- <DropdownMenuItem- onClick={(event) => {- event.stopPropagation();- setBundleToEdit(bundle);- }}- >- <PencilIcon />- Edit- </DropdownMenuItem>- <DropdownMenuItem- variant="danger"- onClick={(event) => {- event.stopPropagation();- setBundleToDelete(bundle);- }}- >- <TrashIcon />- Delete- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- )}- </div>+ {isAdmin && (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <IconButton+ variant="ghost"+ size="xs"+ aria-label="Open access bundle actions"+ onClick={(event) => event.stopPropagation()}+ >+ <MoreHorizontalIcon />+ </IconButton>+ </DropdownMenuTrigger>+ <DropdownMenuContent sideOffset={2} align="end">+ <DropdownMenuItem+ onClick={(event) => {+ event.stopPropagation();+ setBundleToManage(bundle);+ }}+ >+ <UsersIcon />+ Manage Access+ </DropdownMenuItem>+ <DropdownMenuItem+ onClick={(event) => {+ event.stopPropagation();+ setBundleToEdit(bundle);+ }}+ >+ <PencilIcon />+ Edit+ </DropdownMenuItem>+ <DropdownMenuItem+ variant="danger"+ onClick={(event) => {+ event.stopPropagation();+ setBundleToDelete(bundle);+ }}+ >+ <TrashIcon />+ Delete+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ )}</TableCell></TableRow>))}