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
Merge remote-tracking branch 'origin/main' into agent-vault-personal-values
Scott Wilson356cfc0c54e6
diff --cc backend/e2e-test/routes/v1/agent-vault.spec.tsindex 0c99225686,ca98f90fa9..6145feda0c--- a/backend/e2e-test/routes/v1/agent-vault.spec.ts+++ b/backend/e2e-test/routes/v1/agent-vault.spec.ts@@@ -242,41 -239,6 +241,21 @@@ const createMemberIdentity = async (nam};};+// Resolves once a backend waits on a lock the given one holds: by then a request has done everything it+// does before the lock and is queued behind it.+const waitUntilBlockedBy = async (pid: number, attemptsLeft = 200): Promise<void> => {+ const { rows } = await testDb.raw(+ "select count(*)::int as waiting from pg_stat_activity where ? = any(pg_blocking_pids(pid))",+ [pid]+ );+ if (rows[0].waiting > 0) return;+ if (attemptsLeft === 0) throw new Error(`No request queued behind the lock held by backend ${pid}`);+ await new Promise((resolve) => {+ setTimeout(resolve, 25);+ });+ await waitUntilBlockedBy(pid, attemptsLeft - 1);+};+- // Enrollment only checks that it is a live CA. ECDSA P-256, because the FIPS image refuses Ed25519.- const createProxyCaPem = async () => {- const algorithm = { name: "ECDSA", namedCurve: "P-256", hash: "SHA-256" };- const keys = await globalThis.crypto.subtle.generateKey(algorithm, true, ["sign", "verify"]);- const certificate = await x509.X509CertificateGenerator.createSelfSigned({- name: "CN=Agent Vault Variables Test CA",- serialNumber: "01",- notBefore: new Date(Date.now() - 60_000),- notAfter: new Date(Date.now() + 24 * 60 * 60 * 1000),- signingAlgorithm: algorithm,- keys,- extensions: [- new x509.BasicConstraintsExtension(true, undefined, true),- // eslint-disable-next-line no-bitwise- new x509.KeyUsagesExtension(x509.KeyUsageFlags.keyCertSign | x509.KeyUsageFlags.cRLSign, true)- ]- });- return certificate.toString("pem");- };-const createAccessBundle = async (name: string) => {const res = await inject("POST", "/api/v1/agent-vault/access-bundles", { name });expect(res.statusCode).toBe(200);@@@ -1795,712 -1739,6 +1767,705 @@@ describe("Agent Vault V1 Router", asyn});});+ describe("member-provided values", async () => {+ const servicesUrl = (accessBundleId: string) => `/api/v1/agent-vault/access-bundles/${accessBundleId}/services`;+ const membersUrl = (accessBundleId: string) => `/api/v1/agent-vault/access-bundles/${accessBundleId}/members`;+ const personalValuesUrl = (accessBundleId: string, serviceId: string) =>+ `${servicesUrl(accessBundleId)}/${serviceId}/personal-values`;+ const variablesUrl = "/api/v1/agent-vault/variables";+ const personalVariablesUrl = `${variablesUrl}?scope=personal`;++ // Personal variable keys are unique per owner, and the seeded admin owns them across every test here.+ beforeEach(async () => {+ const project = await testDb("projects")+ .where({ orgId: seedData1.organization.id, type: ProjectType.AgentVault })+ .first();+ if (!project) return;+ const variableIds = testDb("agent_vault_variables")+ .where({ projectId: project.id })+ .where((owned) => {+ void owned.whereNotNull("userId").orWhereNotNull("identityId");+ })+ .select("id");+ await testDb("agent_vault_personal_value_references").whereIn("variableId", variableIds).del();+ await testDb("agent_vault_variables").whereIn("id", variableIds).del();+ });++ type TResolvedService = {+ name: string;+ credential: Record<string, string>;+ personalValuesMissing: boolean;+ };++ type TPersonalValues = {+ isConfigured: boolean;+ fields: { field: string; isSet: boolean; variableReferences: { variableId: string; key: string }[] }[];+ };++ const enrollProxy = async (name: string) => {+ const created = await inject("POST", "/api/v1/agent-vault/proxies", { name });+ expect(created.statusCode).toBe(200);- const { token } = JSON.parse(created.payload) as { token: string };- const login = await testServer.inject({- method: "POST",- url: "/api/v1/agent-vault/proxy/login",- body: { method: ResourceAuthMethodType.Token, token, rootCaCertificate: await createProxyCaPem() }- });- expect(login.statusCode).toBe(200);- const { accessToken } = JSON.parse(login.payload) as { accessToken: string };++ const { proxyToken: accessToken } = JSON.parse(created.payload) as { proxyToken: string };++ return async (sessionToken: string, serviceName: string) => {+ const resolved = await testServer.inject({+ method: "POST",+ url: "/api/v1/agent-vault/proxy/resolve",+ headers: { authorization: `Bearer ${accessToken}`, "x-infisical-agent-session": sessionToken }+ });+ expect(resolved.statusCode).toBe(200);+ const { services } = JSON.parse(resolved.payload) as { services: TResolvedService[] };+ return services.find((service) => service.name === serviceName)!;+ };+ };++ const mintSession = async (+ as: (method: "POST", url: string, body: Record<string, unknown>) => ReturnType<typeof inject>,+ accessBundleName: string+ ) => {+ const mint = await as("POST", "/api/v1/agent-vault/sessions", { accessBundles: [accessBundleName], ttl: "1h" });+ expect(mint.statusCode).toBe(200);+ return (JSON.parse(mint.payload) as { session: { token: string } }).session.token;+ };++ const createService = async (accessBundleId: string, body: Record<string, unknown>) => {+ const res = await inject("POST", servicesUrl(accessBundleId), body);+ expect(res.statusCode).toBe(200);+ return (+ JSON.parse(res.payload) as {+ service: { id: string; name: string; credential: { type: string; memberProvidedFields?: string[] } };+ }+ ).service;+ };++ // The caller's status for each service, as the bundle read returns it.+ const statusesOf = async (+ as: (method: "GET", url: string) => ReturnType<typeof inject>,+ accessBundleId: string+ ) => {+ const res = await as("GET", `/api/v1/agent-vault/access-bundles/${accessBundleId}`);+ expect(res.statusCode).toBe(200);+ const { accessBundle } = JSON.parse(res.payload) as {+ accessBundle: { services: { id: string; personalValues: TPersonalValues | null }[] };+ };+ return new Map(accessBundle.services.map((service) => [service.id, service.personalValues]));+ };++ // The bundles granted to the caller that still require their values, with the services that do.+ const pendingOf = async (as: (method: "GET", url: string) => ReturnType<typeof inject>) => {+ 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: { id: string; name: string }[] }[];+ };+ return new Map(+ accessBundles.map((bundle) => [bundle.id, bundle.servicesRequiringSetup.map((service) => service.name)])+ );+ };++ const setValues = (+ as: (method: "PATCH", url: string, body: Record<string, unknown>) => ReturnType<typeof inject>,+ accessBundleId: string,+ serviceId: string,+ values: Record<string, string>+ ) =>+ as("PATCH", personalValuesUrl(accessBundleId, serviceId), {+ values: Object.entries(values).map(([field, value]) => ({ field, value }))+ });++ test("a member-provided token comes from whoever the session belongs to", async () => {+ const bundle = await createAccessBundle("mp-bearer");+ const service = await createService(bundle.id, {+ name: "datadog",+ hostPattern: "api.datadoghq.com",+ credential: { type: "bearer", headerName: "DD-API-KEY", memberProvidedFields: ["credential-value"] }+ });+ expect(service.credential.memberProvidedFields).toEqual(["credential-value"]);++ const both = await inject("POST", servicesUrl(bundle.id), {+ name: "datadog-both",+ hostPattern: "api.us5.datadoghq.com",+ credential: { type: "bearer", value: "admin_value", memberProvidedFields: ["credential-value"] }+ });+ expect(both.statusCode).toBe(422);++ // A PATCH that leaves the list out keeps it, so a token sent alongside is refused rather than dropped.+ const dropped = await inject("PATCH", `${servicesUrl(bundle.id)}/${service.id}`, {+ credential: { type: "bearer", value: "admin_value" }+ });+ expect(dropped.statusCode).toBe(400);+ expect(JSON.parse(dropped.payload).message).toContain("'credential-value' is member provided");++ const member = await createMemberIdentity(`mp-bearer-member-${Date.now()}`);+ try {+ expect((await inject("POST", membersUrl(bundle.id), { machineIdentityIds: [member.id] })).statusCode).toBe(200);++ expect((await statusesOf(member.as, bundle.id)).get(service.id)).toEqual({+ isConfigured: false,+ 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"]);++ const resolve = await enrollProxy("mp-bearer");+ const adminSession = await mintSession(inject, bundle.name);+ const memberSession = await mintSession(member.as, bundle.name);++ const unset = await resolve(adminSession, "datadog");+ expect(unset.personalValuesMissing).toBe(true);+ expect(unset.credential).toEqual({ type: "passthrough" });++ // UUIDs are case-insensitive, so an upper-case bundle id in the path names the same bundle.+ const set = await setValues(member.as, bundle.id.toUpperCase(), service.id, {+ "credential-value": "member_token"+ });+ expect(set.statusCode).toBe(200);+ expect(JSON.parse(set.payload).personalValues).toMatchObject({ isConfigured: true });+ expect(set.payload).not.toContain("member_token");++ expect(await resolve(memberSession, "datadog")).toMatchObject({+ personalValuesMissing: false,+ credential: { type: "bearer", headerName: "DD-API-KEY", headerPrefix: "", value: "member_token" }+ });+ expect((await resolve(adminSession, "datadog")).personalValuesMissing).toBe(true);++ expect((await setValues(inject, bundle.id, service.id, { "credential-value": "admin_token" })).statusCode).toBe(+ 200+ );+ expect((await resolve(adminSession, "datadog")).credential.value).toBe("admin_token");+ expect((await resolve(memberSession, "datadog")).credential.value).toBe("member_token");++ const wrongField = await setValues(member.as, bundle.id, service.id, { "credential-username": "x" });+ expect(wrongField.statusCode).toBe(400);+ expect((await member.as("PATCH", personalValuesUrl(bundle.id, service.id), { values: [] })).statusCode).toBe(+ 422+ );+ 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);+ expect(JSON.parse(removed.payload).personalValues.isConfigured).toBe(false);+ expect((await resolve(memberSession, "datadog")).personalValuesMissing).toBe(true);+ expect((await member.as("DELETE", personalValuesUrl(bundle.id, service.id))).statusCode).toBe(404);+ } finally {+ await member.cleanup();+ }+ });++ test("a member's own variables fill their values, and nobody else's do", async () => {+ const bundle = await createAccessBundle("mp-variables");+ const service = await createService(bundle.id, {+ name: "github",+ hostPattern: "api.github.com",+ credential: { type: "bearer", memberProvidedFields: ["credential-value"] }+ });++ const member = await createMemberIdentity(`mp-variables-member-${Date.now()}`);+ try {+ expect((await inject("POST", membersUrl(bundle.id), { machineIdentityIds: [member.id] })).statusCode).toBe(200);++ const adminVariable = await inject("POST", variablesUrl, {+ scope: "personal",+ key: "MY_TOKEN",+ value: "admin_secret"+ });+ expect(adminVariable.statusCode).toBe(200);+ const adminVariableId = (JSON.parse(adminVariable.payload) as { variable: { id: string } }).variable.id;++ // The same key, owned by someone else, is a different variable.+ const created = await member.as("POST", variablesUrl, {+ scope: "personal",+ key: "MY_TOKEN",+ value: "member_secret"+ });+ expect(created.statusCode).toBe(200);+ const memberVariableId = (JSON.parse(created.payload) as { variable: { id: string } }).variable.id;+ expect(+ (await member.as("POST", variablesUrl, { scope: "personal", key: "MY_TOKEN", value: "again" })).statusCode+ ).toBe(400);++ const unknown = await setValues(member.as, bundle.id, service.id, { "credential-value": "{{NOPE}}" });+ expect(unknown.statusCode).toBe(400);+ expect(JSON.parse(unknown.payload).message).toContain("no personal variable named 'NOPE'");++ const set = await setValues(member.as, bundle.id, service.id, { "credential-value": "token {{MY_TOKEN}}" });+ expect(set.statusCode).toBe(200);+ expect(JSON.parse(set.payload).personalValues.fields).toEqual([+ expect.objectContaining({+ field: "credential-value",+ isSet: true,+ variableReferences: [{ variableId: memberVariableId, key: "MY_TOKEN" }]+ })+ ]);++ const resolve = await enrollProxy("mp-variables");+ const memberSession = await mintSession(member.as, bundle.name);+ expect((await resolve(memberSession, "github")).credential.value).toBe("token member_secret");++ const memberList = await member.as("GET", personalVariablesUrl);+ expect(JSON.parse(memberList.payload).variables).toEqual([+ expect.objectContaining({+ key: "MY_TOKEN",+ usedByServices: [expect.objectContaining({ id: service.id, accessBundleName: bundle.name })]+ })+ ]);+ expect(memberList.payload).not.toContain("member_secret");+ const adminList = await inject("GET", personalVariablesUrl);+ expect(JSON.parse(adminList.payload).variables).toEqual([+ 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}?scope=global&limit=100`);+ expect(globalList.statusCode).toBe(200);+ 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.+ expect((await member.as("GET", `${variablesUrl}/${adminVariableId}/value`)).statusCode).toBe(404);+ expect((await inject("GET", `${variablesUrl}/${memberVariableId}/value`)).statusCode).toBe(404);+ const revealed = await member.as("GET", `${variablesUrl}/${memberVariableId}/value`);+ expect(JSON.parse(revealed.payload).value).toBe("member_secret");++ const inUse = await member.as("DELETE", `${variablesUrl}/${memberVariableId}`);+ expect(inUse.statusCode).toBe(409);+ expect(JSON.parse(inUse.payload).message).toContain("'github'");++ expect((await member.as("PATCH", `${variablesUrl}/${memberVariableId}`, { value: "rotated" })).statusCode).toBe(+ 200+ );+ expect((await resolve(memberSession, "github")).credential.value).toBe("token rotated");+ } finally {+ await member.cleanup();+ }+ });++ test("changing which fields are member provided keeps the values that still apply", async () => {+ const bundle = await createAccessBundle("mp-basic");+ const service = await createService(bundle.id, {+ name: "pagerduty",+ hostPattern: "api.pagerduty.com",+ credential: { type: "basic", password: "admin_pw", memberProvidedFields: ["credential-username"] }+ });+ expect(service.credential.memberProvidedFields).toEqual(["credential-username"]);+ const patchService = (credential: Record<string, unknown>) =>+ inject("PATCH", `${servicesUrl(bundle.id)}/${service.id}`, { credential });+ // Which fields a member has saved for the service, read directly since no response lists them all at once.+ const storedFields = async () =>+ (await testDb("agent_vault_personal_values").where({ serviceId: service.id }).select("field"))+ .map((row: { field: string }) => row.field)+ .sort();++ expect((await setValues(inject, bundle.id, service.id, { "credential-username": "admin_user" })).statusCode).toBe(+ 200+ );+ const resolve = await enrollProxy("mp-basic");+ const session = await mintSession(inject, bundle.name);+ expect((await resolve(session, "pagerduty")).credential).toEqual({+ type: "basic",+ username: "admin_user",+ password: "admin_pw"+ });++ // Handing the password over too keeps the saved username, and the member only adds the new field.+ expect(+ (await patchService({ type: "basic", memberProvidedFields: ["credential-username", "credential-value"] }))+ .statusCode+ ).toBe(200);+ expect(await storedFields()).toEqual(["credential-username"]);+ expect((await resolve(session, "pagerduty")).personalValuesMissing).toBe(true);+ const onlyPassword = await setValues(inject, bundle.id, service.id, { "credential-value": "member_pw" });+ expect(onlyPassword.statusCode).toBe(200);+ expect(JSON.parse(onlyPassword.payload).personalValues.isConfigured).toBe(true);+ expect((await resolve(session, "pagerduty")).credential).toEqual({+ type: "basic",+ username: "admin_user",+ password: "member_pw"+ });++ // Taking the username back drops only the saved username. The admin's half starts empty.+ expect((await patchService({ type: "basic", memberProvidedFields: ["credential-value"] })).statusCode).toBe(200);+ expect(await storedFields()).toEqual(["credential-value"]);+ expect(await resolve(session, "pagerduty")).toMatchObject({+ personalValuesMissing: false,+ credential: { type: "basic", username: "", password: "member_pw" }+ });++ // A new credential type drops every saved value, even for a field members still provide.+ expect((await patchService({ type: "bearer", memberProvidedFields: ["credential-value"] })).statusCode).toBe(200);+ expect(await storedFields()).toEqual([]);+ expect((await resolve(session, "pagerduty")).personalValuesMissing).toBe(true);++ // With nothing saved, a save has to send every field.+ expect(+ (await patchService({ type: "basic", memberProvidedFields: ["credential-username", "credential-value"] }))+ .statusCode+ ).toBe(200);+ const half = await setValues(inject, bundle.id, service.id, { "credential-username": "only_user" });+ expect(half.statusCode).toBe(400);+ expect(JSON.parse(half.payload).message).toContain("password");++ // A bearer service with no token and nothing left to members is not a credential at all.+ expect((await patchService({ type: "bearer" })).statusCode).toBe(400);+ });++ test("losing a bundle clears the values a member saved for it, and keeps their variables", async () => {+ const bundle = await createAccessBundle("mp-revoke");+ const service = await createService(bundle.id, {+ name: "slack",+ hostPattern: "slack.com",+ credential: { type: "bearer", memberProvidedFields: ["credential-value"] }+ });++ const member = await createMemberIdentity(`mp-revoke-member-${Date.now()}`);+ try {+ expect((await inject("POST", membersUrl(bundle.id), { machineIdentityIds: [member.id] })).statusCode).toBe(200);+ expect(+ (await member.as("POST", variablesUrl, { scope: "personal", key: "SLACK_TOKEN", value: "xoxb" })).statusCode+ ).toBe(200);+ expect(+ (await setValues(member.as, bundle.id, service.id, { "credential-value": "{{SLACK_TOKEN}}" })).statusCode+ ).toBe(200);+ // The admin's own values are not the revoked member's to lose.+ expect((await setValues(inject, bundle.id, service.id, { "credential-value": "admin" })).statusCode).toBe(200);++ expect((await inject("DELETE", membersUrl(bundle.id), { machineIdentityIds: [member.id] })).statusCode).toBe(+ 200+ );+ expect(+ await testDb("agent_vault_personal_values").where({ serviceId: service.id, identityId: member.id })+ ).toHaveLength(0);+ expect(+ await testDb("agent_vault_personal_values").where({ serviceId: service.id, userId: seedData1.id })+ ).toHaveLength(1);+ expect(await testDb("agent_vault_variables").where({ identityId: member.id })).toHaveLength(1);++ expect((await inject("POST", membersUrl(bundle.id), { machineIdentityIds: [member.id] })).statusCode).toBe(200);+ expect((await statusesOf(member.as, bundle.id)).get(service.id)?.isConfigured).toBe(false);++ // Leaving Agent Vault clears them too.+ expect((await setValues(member.as, bundle.id, service.id, { "credential-value": "again" })).statusCode).toBe(+ 200+ );+ expect(+ (await inject("DELETE", "/api/v1/agent-vault/members", { machineIdentityIds: [member.id] })).statusCode+ ).toBe(200);+ expect(await testDb("agent_vault_personal_values").where({ identityId: member.id })).toHaveLength(0);+ } finally {+ await member.cleanup();+ }+ });++ test("an admin keeps their values through a revoke, and a demotion clears the ones they hold no grant for", async () => {+ const granted = await createAccessBundle("mp-admin-granted");+ const ungranted = await createAccessBundle("mp-admin-ungranted");+ const credential = { type: "bearer", memberProvidedFields: ["credential-value"] };+ const grantedService = await createService(granted.id, {+ name: "linear",+ hostPattern: "api.linear.app",+ credential+ });+ const ungrantedService = await createService(ungranted.id, {+ name: "notion",+ hostPattern: "api.notion.com",+ credential+ });++ const admin = await createMemberIdentity(`mp-admin-${Date.now()}`);+ const valuesOf = async () =>+ (await testDb("agent_vault_personal_values").where({ identityId: admin.id }).select("serviceId"))+ .map((row: { serviceId: string }) => row.serviceId)+ .sort();+ try {+ const promote = await inject("PATCH", "/api/v1/agent-vault/members", {+ machineIdentityIds: [admin.id],+ role: "admin"+ });+ expect(promote.statusCode).toBe(200);+ expect((await inject("POST", membersUrl(granted.id), { machineIdentityIds: [admin.id] })).statusCode).toBe(200);+ expect((await setValues(admin.as, granted.id, grantedService.id, { "credential-value": "a" })).statusCode).toBe(+ 200+ );+ expect(+ (await setValues(admin.as, ungranted.id, ungrantedService.id, { "credential-value": "b" })).statusCode+ ).toBe(200);++ // Still an admin, so the bundle is still theirs to use.+ expect((await inject("DELETE", membersUrl(granted.id), { machineIdentityIds: [admin.id] })).statusCode).toBe(+ 200+ );+ expect(await valuesOf()).toEqual([grantedService.id, ungrantedService.id].sort());++ expect((await inject("POST", membersUrl(granted.id), { machineIdentityIds: [admin.id] })).statusCode).toBe(200);+ const demote = await inject("PATCH", "/api/v1/agent-vault/members", {+ machineIdentityIds: [admin.id],+ role: "member"+ });+ expect(demote.statusCode).toBe(200);+ expect(await valuesOf()).toEqual([grantedService.id]);+ } finally {+ await admin.cleanup();+ }+ });++ test("a personal variable on a bundle the member lost drops out of Used By and can be deleted", async () => {+ const bundle = await createAccessBundle("mp-lost-reach");+ const service = await createService(bundle.id, {+ name: "sentry",+ hostPattern: "sentry.io",+ credential: { type: "bearer", memberProvidedFields: ["credential-value"] }+ });++ const member = await createMemberIdentity(`mp-lost-reach-${Date.now()}`);+ try {+ expect((await inject("POST", membersUrl(bundle.id), { machineIdentityIds: [member.id] })).statusCode).toBe(200);+ const created = await member.as("POST", variablesUrl, { scope: "personal", key: "SENTRY", value: "s" });+ expect(created.statusCode).toBe(200);+ const variableId = (JSON.parse(created.payload) as { variable: { id: string } }).variable.id;+ expect(+ (await setValues(member.as, bundle.id, service.id, { "credential-value": "{{SENTRY}}" })).statusCode+ ).toBe(200);+ expect((await member.as("DELETE", `${variablesUrl}/${variableId}`)).statusCode).toBe(409);++ // Paths outside Agent Vault (a group removal, a lapsed role) drop the grant without clearing values, and the+ // API has no way to stage that here.+ await testDb("memberships").where({ scopeResourceId: bundle.id, actorIdentityId: member.id }).del();++ const listed = await member.as("GET", personalVariablesUrl);+ expect(listed.statusCode).toBe(200);+ expect(JSON.parse(listed.payload).variables).toEqual([+ expect.objectContaining({ id: variableId, usedByServices: [] })+ ]);+ expect((await member.as("DELETE", `${variablesUrl}/${variableId}`)).statusCode).toBe(200);+ expect(await testDb("agent_vault_personal_values").where({ identityId: member.id })).toHaveLength(0);+ } finally {+ await member.cleanup();+ }+ });++ test("an admin's save on a bundle they hold no grant on waits for a demotion, then 404s", async () => {+ const bundle = await createAccessBundle("mp-admin-race");+ const service = await createService(bundle.id, {+ name: "vercel",+ hostPattern: "api.vercel.com",+ credential: { type: "bearer", memberProvidedFields: ["credential-value"] }+ });++ const admin = await createMemberIdentity(`mp-admin-race-${Date.now()}`);+ try {+ expect(+ (await inject("PATCH", "/api/v1/agent-vault/members", { machineIdentityIds: [admin.id], role: "admin" }))+ .statusCode+ ).toBe(200);+ const membership = await testDb("memberships").where({ scope: "project", actorIdentityId: admin.id }).first();++ // What a demotion does: replace the admin role, and hold it until it commits.+ const trx = await testDb.transaction();+ let pending: ReturnType<typeof setValues> | undefined;+ try {+ const { rows } = await trx.raw("select pg_backend_pid() as pid");+ await trx("membership_roles").where({ membershipId: membership.id }).delete();+ await trx("membership_roles").insert({ membershipId: membership.id, role: "member" });++ pending = setValues(admin.as, bundle.id, service.id, { "credential-value": "raced" });+ await waitUntilBlockedBy(rows[0].pid);+ await trx.commit();++ expect((await pending).statusCode).toBe(404);+ } catch (err) {+ if (!trx.isCompleted()) await trx.rollback();+ // Let the save finish before cleanup, so a failure here doesn't leave state for the tests after it.+ await pending?.catch(() => undefined);+ throw err;+ }+ expect(await testDb("agent_vault_personal_values").where({ identityId: admin.id })).toHaveLength(0);+ } finally {+ await admin.cleanup();+ }+ });++ 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, {+ name: "openai",+ hostPattern: "api.openai.com",+ credential: { type: "bearer", memberProvidedFields: ["credential-value"] }+ });+ expect((await inject("DELETE", membersUrl(ungranted.id), { userIds: [seedData1.id] })).statusCode).toBe(200);++ const listed = await inject("GET", "/api/v1/agent-vault/access-bundles?search=mp-mine&limit=100");+ expect(JSON.parse(listed.payload).accessBundles).toEqual([+ expect.objectContaining({ id: ungranted.id, servicesRequiringSetup: [] })+ ]);+ expect((await pendingOf(inject)).has(ungranted.id)).toBe(false);+ expect((await inject("GET", "/api/v1/agent-vault/access-bundles?requiresSetup=maybe")).statusCode).toBe(422);+ // Opening the bundle still shows what a session from it would need.+ expect((await statusesOf(inject, ungranted.id)).get(service.id)?.isConfigured).toBe(false);+ });++ test("a service out of reach is a 404, and one without member-provided fields takes no values", async () => {+ const bundle = await createAccessBundle("mp-reach");+ const memberService = await createService(bundle.id, {+ name: "anthropic",+ hostPattern: "api.anthropic.com",+ credential: { type: "bearer", memberProvidedFields: ["credential-value"] }+ });+ const adminService = await createService(bundle.id, {+ name: "mistral",+ hostPattern: "api.mistral.ai",+ credential: { type: "bearer", value: "admin_only" }+ });++ const member = await createMemberIdentity(`mp-reach-member-${Date.now()}`);+ try {+ expect((await setValues(member.as, bundle.id, memberService.id, { "credential-value": "x" })).statusCode).toBe(+ 404+ );+ expect((await member.as("GET", `/api/v1/agent-vault/access-bundles/${bundle.id}`)).statusCode).toBe(404);+ expect((await pendingOf(member.as)).size).toBe(0);+ // A service named under another bundle reads as missing too.+ const other = await createAccessBundle("mp-reach-other");+ expect((await setValues(inject, other.id, memberService.id, { "credential-value": "x" })).statusCode).toBe(404);+ } finally {+ await member.cleanup();+ }++ const refused = await setValues(inject, bundle.id, adminService.id, { "credential-value": "x" });+ expect(refused.statusCode).toBe(400);+ expect(JSON.parse(refused.payload).message).toContain("doesn't take any values from its members");+ expect((await statusesOf(inject, bundle.id)).get(adminService.id)).toBeNull();+ });+ });+describe("product membership", async () => {const membersUrl = "/api/v1/agent-vault/members";diff --cc backend/src/ee/services/agent-vault/CLAUDE.mdindex 403f0a906c,bc6d5847cb..57427accb2--- a/backend/src/ee/services/agent-vault/CLAUDE.md+++ b/backend/src/ee/services/agent-vault/CLAUDE.md@@@ -18,12 -18,11 +18,12 @@@ never in anything the agent holds```agent-vault/ shared: enums, host grammar, conflict detection, reachabilityagent-vault-access-bundle/ bundles, services, credential encryption, grants-agent-vault-variable/ product-wide variables and the reads behind Used By+agent-vault-variable/ global and personal variables and the reads behind Used Byagent-vault-member/ product membership (list, add, role, remove)+agent-vault-personal-value/ each actor's own values for the fields a service leaves to membersagent-vault-session/ mint, revoke, list, getagent-vault-project/ the per-org project's lazy bootstrap and resolver- agent-vault-proxy/ login (enrollment), heartbeat, resolve+ agent-vault-proxy/ create/rotate (proxy token + CA), bootstrap, heartbeat, resolveagent-vault-session-log/ storage settings, chunk ingest, playback```diff --cc frontend/src/hooks/api/agentVault/mutations.tsxindex d459a7478a,71f11582cc..dd47ced47d--- a/frontend/src/hooks/api/agentVault/mutations.tsx+++ b/frontend/src/hooks/api/agentVault/mutations.tsx@@@ -14,10 -14,9 +14,10 @@@ importTAgentVaultGrantedMember,TAgentVaultMemberWriteResult,TAgentVaultMintedSession,+ TAgentVaultPersonalValues,TAgentVaultProxy,TAgentVaultProxySettingsDTO,+ TAgentVaultProxyWithToken,TAgentVaultService,TAgentVaultSessionLogSettings,TAgentVaultVariable,