Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat(agent-vault): move variables from access bundles to Agent Vault as a whole
Scott Wilson8ce4a4f8eb50
diff --git a/backend/e2e-test/routes/v1/agent-vault.spec.ts b/backend/e2e-test/routes/v1/agent-vault.spec.tsindex fa96f8d28a..c58a9cdf5f 100644--- a/backend/e2e-test/routes/v1/agent-vault.spec.ts+++ b/backend/e2e-test/routes/v1/agent-vault.spec.ts@@ -8,7 +8,6 @@ import { AccessScope, ActionProjectType, OrgMembershipRole, ProjectMembershipRolimport { seedData1 } from "@app/db/seed-data";import { agentVaultServiceCustomHeaderDALFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-service-custom-header-dal";import { agentVaultServiceSubstitutionDALFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-service-substitution-dal";-import { agentVaultVariableDALFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-variable-dal";import { agentVaultProxyDALFactory } from "@app/ee/services/agent-vault-proxy/agent-vault-proxy-dal";import {AGENT_VAULT_MAX_PROXIES_PER_ORG,@@ -17,6 +16,7 @@ import {import { agentVaultResolveDALFactory } from "@app/ee/services/agent-vault-proxy/agent-vault-resolve-dal";import { agentVaultSessionDALFactory } from "@app/ee/services/agent-vault-session/agent-vault-session-dal";import { agentVaultSessionLogConfigDALFactory } from "@app/ee/services/agent-vault-session-log/agent-vault-session-log-config-dal";+import { agentVaultVariableDALFactory } from "@app/ee/services/agent-vault-variable/agent-vault-variable-dal";import { groupDALFactory } from "@app/ee/services/group/group-dal";import { isHsmActiveAndEnabled } from "@app/ee/services/hsm/hsm-fns";import { permissionDALFactory } from "@app/ee/services/permission/permission-dal";@@ -780,9 +780,21 @@ describe("Agent Vault V1 Router", async () => {});describe("variables", async () => {- const variablesUrl = (accessBundleId: string) => `/api/v1/agent-vault/access-bundles/${accessBundleId}/variables`;+ const variablesUrl = "/api/v1/agent-vault/variables";const servicesUrl = (accessBundleId: string) => `/api/v1/agent-vault/access-bundles/${accessBundleId}/services`;+ // Keys are unique across the org's Agent Vault, and every test here shares it. A variable still referenced can't+ // be deleted through the API, so the rows go straight from the database.+ 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 }).select("id");+ await testDb("agent_vault_service_variable_references").whereIn("variableId", variableIds).del();+ await testDb("agent_vault_variables").where({ projectId: project.id }).del();+ });+type TReference = {variableId: string;key: string;@@ -791,8 +803,8 @@ describe("Agent Vault V1 Router", async () => {substitutionId?: string;};- const createVariable = async (accessBundleId: string, body: { key: string; value: string }) => {- const res = await inject("POST", variablesUrl(accessBundleId), body);+ const createVariable = async (body: { key: string; value: string }) => {+ const res = await inject("POST", variablesUrl, body);expect(res.statusCode).toBe(200);return (JSON.parse(res.payload) as { variable: { id: string; key: string } }).variable;};@@ -898,13 +910,16 @@ describe("Agent Vault V1 Router", async () => {const STORED_REFERENCE = /\{\{([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\}\}/g;// What the delete refusal rests on: every field's rows name exactly the ids in its sealed text that resolve- // expands, which are those of the bundle's own variables. Read off the sealed text, not through the service.+ // expands, which are those of the project's variables. Read off the sealed text, not through the service.const expectReferencesMatchSealedText = async (accessBundleId: string) => {const { decryptor } = await cipherFor(accessBundleId);const open = (sealed: Buffer) =>JSON.parse(decryptor({ cipherTextBlob: sealed }).toString("utf-8")) as Record<string, string>;+ const { projectId } = (await testDb("agent_vault_access_bundles").where({ id: accessBundleId }).first()) as {+ projectId: string;+ };const variableIds = new Set(- ((await testDb("agent_vault_variables").where({ accessBundleId }).select("id")) as { id: string }[]).map(+ ((await testDb("agent_vault_variables").where({ projectId }).select("id")) as { id: string }[]).map((row) => row.id));@@ -974,8 +989,8 @@ describe("Agent Vault V1 Router", async () => {test("a service uses a variable by key, and resolve puts the value in its place", async () => {const bundle = await createAccessBundle("variables-resolve");- const token = await createVariable(bundle.id, { key: "GITHUB_TOKEN", value: "ghp_from_variable" });- const org = await createVariable(bundle.id, { key: "ORG_ID", value: "org-42" });+ const token = await createVariable({ key: "GITHUB_TOKEN", value: "ghp_from_variable" });+ const org = await createVariable({ key: "ORG_ID", value: "org-42" });const created = await inject("POST", servicesUrl(bundle.id), {name: "github",@@ -1029,7 +1044,7 @@ describe("Agent Vault V1 Router", async () => {test("a field at the reference limit reaches the host whole with its variables at their longest, from either save", async () => {const bundle = await createAccessBundle("variables-longest");- const long = await createVariable(bundle.id, { key: "LONG", value: "x" });+ const long = await createVariable({ key: "LONG", value: "x" });const created = await inject("POST", servicesUrl(bundle.id), {name: "longest",@@ -1039,7 +1054,7 @@ describe("Agent Vault V1 Router", async () => {expect(created.statusCode).toBe(200);// Nothing measures a field filled in, so a value change can't be refused on a service's behalf.- const grown = await inject("PATCH", `${variablesUrl(bundle.id)}/${long.id}`, { value: "y".repeat(8192) });+ const grown = await inject("PATCH", `${variablesUrl}/${long.id}`, { value: "y".repeat(8192) });expect(grown.statusCode).toBe(200);const resolve = await resolverFor(bundle, "variables-longest");@@ -1048,7 +1063,7 @@ describe("Agent Vault V1 Router", async () => {test("a username a variable fills in is trimmed like a typed one, and the password keeps its spaces", async () => {const bundle = await createAccessBundle("variables-username-trim");- await createVariable(bundle.id, { key: "PADDED", value: " padded " });+ await createVariable({ key: "PADDED", value: " padded " });const created = await inject("POST", servicesUrl(bundle.id), {name: "padded",hostPattern: "padded.example.com",@@ -1066,7 +1081,7 @@ describe("Agent Vault V1 Router", async () => {test("a stored id with no variable behind it is sent as stored, and its service keeps its restrictions", async () => {const bundle = await createAccessBundle("variables-missing");- const gone = await createVariable(bundle.id, { key: "GONE", value: "x" });+ const gone = await createVariable({ key: "GONE", value: "x" });const created = await inject("POST", servicesUrl(bundle.id), {name: "missing",hostPattern: "api.example.com",@@ -1089,7 +1104,7 @@ describe("Agent Vault V1 Router", async () => {test("renaming a variable keeps its services working, and a new value reaches the next resolve", async () => {const bundle = await createAccessBundle("variables-rename");- const variable = await createVariable(bundle.id, { key: "OLD_NAME", value: "first" });+ const variable = await createVariable({ key: "OLD_NAME", value: "first" });const created = await inject("POST", servicesUrl(bundle.id), {name: "echo",hostPattern: "echo.example.com",@@ -1099,9 +1114,12 @@ describe("Agent Vault V1 Router", async () => {const serviceId = (JSON.parse(created.payload) as { service: { id: string } }).service.id;const resolve = await resolverFor(bundle, "variables-rename");- const renamed = await inject("PATCH", `${variablesUrl(bundle.id)}/${variable.id}`, { key: "NEW_NAME" });+ const renamed = await inject("PATCH", `${variablesUrl}/${variable.id}`, { key: "NEW_NAME" });expect(renamed.statusCode).toBe(200);- expect(JSON.parse(renamed.payload).variable).toMatchObject({ key: "NEW_NAME", serviceIds: [serviceId] });+ expect(JSON.parse(renamed.payload).variable).toMatchObject({+ key: "NEW_NAME",+ usedBy: [{ id: serviceId, name: "echo", accessBundleId: bundle.id, accessBundleName: bundle.name }]+ });const detail = JSON.parse((await inject("GET", `/api/v1/agent-vault/access-bundles/${bundle.id}`)).payload) as {accessBundle: { services: { variableReferences: TReference[] }[] };@@ -1112,9 +1130,7 @@ describe("Agent Vault V1 Router", async () => {await expectReferencesMatchSealedText(bundle.id);expect((await resolve()).services[0].credential).toMatchObject({ value: "first" });- expect((await inject("PATCH", `${variablesUrl(bundle.id)}/${variable.id}`, { value: "second" })).statusCode).toBe(- 200- );+ expect((await inject("PATCH", `${variablesUrl}/${variable.id}`, { value: "second" })).statusCode).toBe(200);expect((await resolve()).services[0].credential).toMatchObject({ value: "second" });const stale = await inject("POST", servicesUrl(bundle.id), {@@ -1128,7 +1144,7 @@ describe("Agent Vault V1 Router", async () => {test("a variable a service uses can't be deleted, and the refusal names the service", async () => {const bundle = await createAccessBundle("variables-in-use");- const variable = await createVariable(bundle.id, { key: "API_KEY", value: "key_value" });+ const variable = await createVariable({ key: "API_KEY", value: "key_value" });const created = await inject("POST", servicesUrl(bundle.id), {name: "datadog",hostPattern: "api.datadoghq.com",@@ -1137,9 +1153,9 @@ describe("Agent Vault V1 Router", async () => {expect(created.statusCode).toBe(200);const { service } = JSON.parse(created.payload) as { service: { id: string } };- const refused = await inject("DELETE", `${variablesUrl(bundle.id)}/${variable.id}`);+ const refused = await inject("DELETE", `${variablesUrl}/${variable.id}`);expect(refused.statusCode).toBe(409);- expect(JSON.parse(refused.payload).message).toContain("'datadog'");+ expect(JSON.parse(refused.payload).message).toContain(`'datadog' (access bundle '${bundle.name}')`);const detached = await inject("PATCH", `${servicesUrl(bundle.id)}/${service.id}`, {credential: { type: "bearer", value: "literal_value" }@@ -1148,7 +1164,7 @@ describe("Agent Vault V1 Router", async () => {expect(JSON.parse(detached.payload).service.variableReferences).toEqual([]);await expectReferencesMatchSealedText(bundle.id);- const removed = await inject("DELETE", `${variablesUrl(bundle.id)}/${variable.id}`);+ const removed = await inject("DELETE", `${variablesUrl}/${variable.id}`);expect(removed.statusCode).toBe(200);expect(JSON.parse(removed.payload).variable).toMatchObject({ id: variable.id, key: "API_KEY" });});@@ -1201,7 +1217,7 @@ describe("Agent Vault V1 Router", async () => {test("a value takes three variable references, a repeat counted each time, and a fourth fails validation", async () => {const bundle = await createAccessBundle("variables-reference-limit");- await createVariable(bundle.id, { key: "TOKEN", value: "t" });+ await createVariable({ key: "TOKEN", value: "t" });const atLimit = await inject("POST", servicesUrl(bundle.id), {name: "at-limit",@@ -1225,9 +1241,8 @@ describe("Agent Vault V1 Router", async () => {});test("no response but the value route carries a value, and that route returns it uncached", async () => {- const bundle = await createAccessBundle("variables-visibility");// A client from before every value was secret may still send isSecret: false. It is stripped, not honoured.- const createdRes = await inject("POST", variablesUrl(bundle.id), {+ const createdRes = await inject("POST", variablesUrl, {key: "HIDDEN",value: "hidden_value",isSecret: false@@ -1236,19 +1251,20 @@ 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(bundle.id));+ const listed = await inject("GET", variablesUrl);expect(listed.statusCode).toBe(200);expect(listed.payload).not.toContain("hidden_value");const [listedVariable] = JSON.parse(listed.payload).variables;- expect(listedVariable).toMatchObject({ key: "HIDDEN", serviceIds: [] });+ expect(listedVariable).toMatchObject({ key: "HIDDEN", usedBy: [] });+ expect(listedVariable).not.toHaveProperty("accessBundleId");expect(listedVariable).not.toHaveProperty("value");expect(listedVariable).not.toHaveProperty("isSecret");- const updated = await inject("PATCH", `${variablesUrl(bundle.id)}/${hidden.id}`, { value: "new_hidden_value" });+ const updated = await inject("PATCH", `${variablesUrl}/${hidden.id}`, { value: "new_hidden_value" });expect(updated.statusCode).toBe(200);expect(updated.payload).not.toContain("new_hidden_value");- const revealed = await inject("GET", `${variablesUrl(bundle.id)}/${hidden.id}/value`);+ const revealed = await inject("GET", `${variablesUrl}/${hidden.id}/value`);expect(revealed.statusCode).toBe(200);expect(JSON.parse(revealed.payload)).toEqual({ value: "new_hidden_value" });expect(revealed.headers["cache-control"]).toContain("no-store");@@ -1256,41 +1272,165 @@ describe("Agent Vault V1 Router", async () => {const row = await testDb("agent_vault_variables").where({ id: hidden.id }).first();expect(row.encryptedValue.toString("utf-8")).not.toContain("new_hidden_value");- const removed = await inject("DELETE", `${variablesUrl(bundle.id)}/${hidden.id}`);+ const removed = await inject("DELETE", `${variablesUrl}/${hidden.id}`);expect(removed.statusCode).toBe(200);expect(removed.payload).not.toContain("new_hidden_value");});test("a value can't be only spaces, and one with spaces around it is kept as typed", async () => {- const bundle = await createAccessBundle("variables-blank-value");- const blank = await inject("POST", variablesUrl(bundle.id), { key: "BLANK", value: " " });+ const blank = await inject("POST", variablesUrl, { key: "BLANK", value: " " });expect(blank.statusCode).toBe(422);expect(blank.payload).toContain("A value can't be only spaces.");- const padded = await createVariable(bundle.id, { key: "PADDED", value: " kept " });- const revealed = await inject("GET", `${variablesUrl(bundle.id)}/${padded.id}/value`);+ const padded = await createVariable({ key: "PADDED", value: " kept " });+ const revealed = await inject("GET", `${variablesUrl}/${padded.id}/value`);expect(JSON.parse(revealed.payload)).toEqual({ value: " kept " });- expect((await inject("PATCH", `${variablesUrl(bundle.id)}/${padded.id}`, { value: " " })).statusCode).toBe(422);+ expect((await inject("PATCH", `${variablesUrl}/${padded.id}`, { value: " " })).statusCode).toBe(422);});- test("a key is unique in its bundle and has to be upper snake case", async () => {- const bundle = await createAccessBundle("variables-keys");- await createVariable(bundle.id, { key: "TOKEN", value: "one" });+ 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(bundle.id), { key: "TOKEN", value: "two" });+ const duplicate = await inject("POST", variablesUrl, { key: "TOKEN", value: "two" });expect(duplicate.statusCode).toBe(400);- expect(JSON.parse(duplicate.payload).message).toContain("'TOKEN'");- expect((await inject("POST", variablesUrl(bundle.id), { key: "lower_case", value: "x" })).statusCode).toBe(422);+ 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);++ const second = await createVariable({ key: "OTHER", value: "three" });+ const renamedOnto = await inject("PATCH", `${variablesUrl}/${second.id}`, { key: "TOKEN" });+ expect(renamedOnto.statusCode).toBe(400);+ expect(JSON.parse(renamedOnto.payload).message).toBe("A variable named 'TOKEN' already exists.");++ // Renaming a variable to its own key is no clash.+ expect((await inject("PATCH", `${variablesUrl}/${first.id}`, { key: "TOKEN" })).statusCode).toBe(200);+ });++ test("services in different bundles share a variable, and each resolves it", async () => {+ const first = await createAccessBundle("variables-shared-first");+ const second = await createAccessBundle("variables-shared-second");+ const variable = await createVariable({ key: "SHARED_TOKEN", value: "shared_value" });++ const createdIn = async (bundle: { id: string }, name: string) => {+ const res = await inject("POST", servicesUrl(bundle.id), {+ name,+ hostPattern: `${name}.example.com`,+ credential: { type: "bearer", value: "{{SHARED_TOKEN}}" }+ });+ expect(res.statusCode).toBe(200);+ return (JSON.parse(res.payload) as { service: { id: string } }).service;+ };+ const firstService = await createdIn(first, "shared-one");+ const secondService = await createdIn(second, "shared-two");+ await expectReferencesMatchSealedText(first.id);+ await expectReferencesMatchSealedText(second.id);++ const listed = JSON.parse((await inject("GET", variablesUrl)).payload) as {+ variables: { id: string; usedBy: Record<string, string>[] }[];+ };+ expect(listed.variables.find((entry) => entry.id === variable.id)?.usedBy).toEqual([+ {+ id: firstService.id,+ name: "shared-one",+ hostPattern: "shared-one.example.com",+ accessBundleId: first.id,+ accessBundleName: first.name+ },+ {+ id: secondService.id,+ name: "shared-two",+ hostPattern: "shared-two.example.com",+ accessBundleId: second.id,+ accessBundleName: second.name+ }+ ]);++ const refused = await inject("DELETE", `${variablesUrl}/${variable.id}`);+ expect(refused.statusCode).toBe(409);+ expect(JSON.parse(refused.payload).message).toBe(+ `The variable 'SHARED_TOKEN' is used by the services 'shared-one' (access bundle '${first.name}'), 'shared-two' (access bundle '${second.name}'). Remove it from those services before deleting it.`+ );++ const resolveFirst = await resolverFor(first, "variables-shared-first");+ expect((await resolveFirst()).services[0].credential).toMatchObject({ value: "shared_value" });+ const resolveSecond = await resolverFor(second, "variables-shared-second");+ expect((await resolveSecond()).services[0].credential).toMatchObject({ value: "shared_value" });+ });++ test("a delete waits for a service save that is adding a reference, and then refuses", async () => {+ const bundle = await createAccessBundle("variables-delete-race");+ const variable = await createVariable({ key: "RACED", value: "raced_value" });+ const created = await inject("POST", servicesUrl(bundle.id), {+ name: "raced",+ hostPattern: "raced.example.com",+ credential: { type: "passthrough" }+ });+ expect(created.statusCode).toBe(200);+ const { service } = JSON.parse(created.payload) as { service: { id: string } };++ // What a save does once it holds the bundle: take the variable FOR SHARE, then add its reference row.+ const trx = await testDb.transaction();+ try {+ const { rows } = await trx.raw("select pg_backend_pid() as pid");+ await trx("agent_vault_variables").where({ id: variable.id }).forShare().first();++ const pending = inject("DELETE", `${variablesUrl}/${variable.id}`);+ await waitUntilBlockedBy(rows[0].pid);++ await trx("agent_vault_service_variable_references").insert({+ serviceId: service.id,+ variableId: variable.id,+ field: "credential-value"+ });+ await trx.commit();- const other = await createAccessBundle("variables-keys-other");- expect((await inject("POST", variablesUrl(other.id), { key: "TOKEN", value: "three" })).statusCode).toBe(200);+ const refused = await pending;+ expect(refused.statusCode).toBe(409);+ expect(JSON.parse(refused.payload).message).toContain("'raced'");+ } catch (err) {+ if (!trx.isCompleted()) await trx.rollback();+ throw err;+ }+ expect(await testDb("agent_vault_variables").where({ id: variable.id })).toHaveLength(1);+ });++ test("a service save waiting on a variable that is then deleted fails without leaving a reference", async () => {+ const bundle = await createAccessBundle("variables-save-race");+ const variable = await createVariable({ key: "DOOMED", value: "doomed_value" });++ // What a delete does: lock the variable, find no references, delete it. The save looks the key up first and+ // then queues behind the lock. Its share lock and the deferred foreign key each give this answer on their own.+ const trx = await testDb.transaction();+ try {+ const { rows } = await trx.raw("select pg_backend_pid() as pid");+ await trx("agent_vault_variables").where({ id: variable.id }).forUpdate().first();++ const pending = inject("POST", servicesUrl(bundle.id), {+ name: "doomed",+ hostPattern: "doomed.example.com",+ credential: { type: "bearer", value: "{{DOOMED}}" }+ });+ await waitUntilBlockedBy(rows[0].pid);++ await trx("agent_vault_variables").where({ id: variable.id }).del();+ await trx.commit();++ const refused = await pending;+ expect(refused.statusCode).toBe(400);+ expect(JSON.parse(refused.payload).message).toBe(+ "A variable this service uses was deleted while it was being saved. Check its variable references and save again."+ );+ } catch (err) {+ if (!trx.isCompleted()) await trx.rollback();+ throw err;+ }+ expect(await testDb("agent_vault_services").where({ accessBundleId: bundle.id })).toHaveLength(0);});test("an update rebuilds the references of only the values it wrote", async () => {const bundle = await createAccessBundle("variables-partial");- await createVariable(bundle.id, { key: "USER", value: "the-user" });- await createVariable(bundle.id, { key: "PASS", value: "the-pass" });- await createVariable(bundle.id, { key: "HEADER", value: "the-header" });+ await createVariable({ key: "USER", value: "the-user" });+ await createVariable({ key: "PASS", value: "the-pass" });+ await createVariable({ key: "HEADER", value: "the-header" });const created = await inject("POST", servicesUrl(bundle.id), {name: "basic",@@ -1334,8 +1474,8 @@ describe("Agent Vault V1 Router", async () => {test("a basic credential's kept half is stored text, so one saved before variables existed stays as it was", async () => {const bundle = await createAccessBundle("variables-legacy-half");- await createVariable(bundle.id, { key: "FOO", value: "foo-value" });- await createVariable(bundle.id, { key: "USER", value: "the-user" });+ await createVariable({ key: "FOO", value: "foo-value" });+ await createVariable({ key: "USER", value: "the-user" });const created = await inject("POST", servicesUrl(bundle.id), {name: "legacy",@@ -1376,9 +1516,9 @@ describe("Agent Vault V1 Router", async () => {test("a partial basic update refuses to write over a credential another save changed while it waited", async () => {const bundle = await createAccessBundle("variables-stale-half");- await createVariable(bundle.id, { key: "FIRST_USER", value: "first-user" });- await createVariable(bundle.id, { key: "SECOND_USER", value: "second-user" });- await createVariable(bundle.id, { key: "PASS", value: "the-pass" });+ await createVariable({ key: "FIRST_USER", value: "first-user" });+ await createVariable({ key: "SECOND_USER", value: "second-user" });+ await createVariable({ key: "PASS", value: "the-pass" });const created = await inject("POST", servicesUrl(bundle.id), {name: "stale",@@ -1478,9 +1618,9 @@ describe("Agent Vault V1 Router", async () => {}});- test("deleting a bundle takes its variables and every reference to them", async () => {+ test("deleting a bundle keeps the variables its services used, and drops their references", async () => {const bundle = await createAccessBundle("variables-bundle-delete");- const variable = await createVariable(bundle.id, { key: "TOKEN", value: "t" });+ const variable = await createVariable({ key: "TOKEN", value: "t" });const created = await inject("POST", servicesUrl(bundle.id), {name: "one",hostPattern: "one.example.com",@@ -1491,15 +1631,20 @@ describe("Agent Vault V1 Router", async () => {const removed = await inject("DELETE", `/api/v1/agent-vault/access-bundles/${bundle.id}`);expect(removed.statusCode).toBe(200);- expect(await testDb("agent_vault_variables").where({ id: variable.id })).toHaveLength(0);expect(await testDb("agent_vault_service_variable_references").where({ variableId: variable.id })).toHaveLength(0);++ const listed = JSON.parse((await inject("GET", variablesUrl)).payload) as {+ variables: { id: string; usedBy: unknown[] }[];+ };+ expect(listed.variables).toEqual([expect.objectContaining({ id: variable.id, key: "TOKEN", usedBy: [] })]);+ expect((await inject("DELETE", `${variablesUrl}/${variable.id}`)).statusCode).toBe(200);});test("variables are admin only, reads included", async () => {const bundle = await createAccessBundle("variables-admin-only");- const variable = await createVariable(bundle.id, { key: "TOKEN", value: "admin_only_value" });+ const variable = await createVariable({ key: "TOKEN", value: "admin_only_value" });const created = await inject("POST", servicesUrl(bundle.id), {name: "uses-token",hostPattern: "api.example.com",@@ -1541,16 +1686,12 @@ describe("Agent Vault V1 Router", async () => {{ variableId: variable.id, key: "TOKEN", field: "credential-value" }]);- const listed = await member.asIdentity("GET", variablesUrl(bundle.id));+ const listed = await member.asIdentity("GET", variablesUrl);expect(listed.statusCode).toBe(403);- expect(JSON.parse(listed.payload).message).toBe("Only Agent Vault admins can view or change variables");expect(listed.payload).not.toContain("admin_only_value");- expect((await member.asIdentity("GET", `${variablesUrl(bundle.id)}/${variable.id}/value`)).statusCode).toBe(- 403- );- expect((await member.asIdentity("POST", variablesUrl(bundle.id), { key: "MINE", value: "x" })).statusCode).toBe(- 403- );+ expect(listed.payload).not.toContain("TOKEN");+ expect((await member.asIdentity("GET", `${variablesUrl}/${variable.id}/value`)).statusCode).toBe(403);+ expect((await member.asIdentity("POST", variablesUrl, { key: "MINE", value: "x" })).statusCode).toBe(403);} finally {await deleteUaIdentity(member.id);}diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.tsindex 8d2ce22d5e..c5a8fa7d20 100644--- a/backend/src/@types/fastify.d.ts+++ b/backend/src/@types/fastify.d.ts@@ -12,6 +12,7 @@ import { TAgentVaultProjectResolverFactory } from "@app/ee/services/agent-vault-import { TAgentVaultProxyServiceFactory } from "@app/ee/services/agent-vault-proxy/agent-vault-proxy-service";import { TAgentVaultSessionServiceFactory } from "@app/ee/services/agent-vault-session/agent-vault-session-service";import { TAgentVaultSessionLogServiceFactory } from "@app/ee/services/agent-vault-session-log/agent-vault-session-log-service";+import { TAgentVaultVariableServiceFactory } from "@app/ee/services/agent-vault-variable/agent-vault-variable-service";import { TAssumePrivilegeServiceFactory } from "@app/ee/services/assume-privilege/assume-privilege-types";import { TAuditLogSettingsServiceFactory } from "@app/ee/services/audit-log/audit-log-settings-service";import { TAuditLogServiceFactory, TCreateAuditLogDTO } from "@app/ee/services/audit-log/audit-log-types";@@ -385,6 +386,7 @@ declare module "fastify" {secretScanningV2ProjectResolver: TSecretScanningV2ProjectResolverFactory;agentVaultProjectResolver: TAgentVaultProjectResolverFactory;agentVaultAccessBundle: TAgentVaultAccessBundleServiceFactory;+ agentVaultVariable: TAgentVaultVariableServiceFactory;agentVaultProxy: TAgentVaultProxyServiceFactory;agentVaultSession: TAgentVaultSessionServiceFactory;agentVaultSessionLog: TAgentVaultSessionLogServiceFactory;diff --git a/backend/src/db/migrations/20261012120000_agent-vault-variables-product-scope.ts b/backend/src/db/migrations/20261012120000_agent-vault-variables-product-scope.tsnew file mode 100644index 0000000000..ba093aa6d4--- /dev/null+++ b/backend/src/db/migrations/20261012120000_agent-vault-variables-product-scope.ts@@ -0,0 +1,85 @@+import { Knex } from "knex";++import { TableName } from "../schemas";+import { findVariableKeyRenames, TVariableKeyRow } from "./utils/agent-vault-variable-key-dedupe";++const PROJECT_KEY_UNIQUE = "agent_vault_variables_projectid_key_unique";+const RENAME_BATCH_SIZE = 500;++// accessBundleId stays, nullable and no longer cascading, for one release: a pod still on the previous release+// resolves variables by it while this one rolls out. Nothing in this release reads or writes it.+export async function up(knex: Knex): Promise<void> {+ if (await knex.schema.hasColumn(TableName.AgentVaultVariable, "projectId")) return;++ await knex.schema.alterTable(TableName.AgentVaultVariable, (t) => {+ t.string("projectId", 36);+ t.foreign("projectId").references("id").inTable(TableName.Project).onDelete("CASCADE");+ });++ await knex.raw(`UPDATE ?? AS v SET "projectId" = b."projectId" FROM ?? AS b WHERE b.id = v."accessBundleId"`, [+ TableName.AgentVaultVariable,+ TableName.AgentVaultAccessBundle+ ]);++ const rows = (await knex(TableName.AgentVaultVariable).select(+ "id",+ "projectId",+ "key",+ "createdAt"+ )) as TVariableKeyRow[];++ const renames = [...findVariableKeyRenames(rows)];+ for (let i = 0; i < renames.length; i += RENAME_BATCH_SIZE) {+ const batch = renames.slice(i, i + RENAME_BATCH_SIZE);+ // eslint-disable-next-line no-await-in-loop+ await knex.raw(+ `UPDATE ?? AS v SET "key" = r."key" FROM (VALUES ${batch.map(() => "(?::uuid, ?)").join(", ")}) AS r("id", "key") WHERE v.id = r."id"`,+ [TableName.AgentVaultVariable, ...batch.flat()]+ );+ }++ await knex.schema.alterTable(TableName.AgentVaultVariable, (t) => {+ t.dropNullable("projectId");+ // Also the index the projectId foreign key needs, as its leftmost column.+ t.unique(["projectId", "key"], { indexName: PROJECT_KEY_UNIQUE });++ t.dropForeign(["accessBundleId"]);+ t.setNullable("accessBundleId");+ t.foreign("accessBundleId").references("id").inTable(TableName.AgentVaultAccessBundle).onDelete("SET NULL");+ });+}++// Best effort. A variable goes back to the bundle of a service that uses it, or to the project's oldest bundle,+// and one with neither is deleted. Services in any other bundle that use it stop resolving it.+export async function down(knex: Knex): Promise<void> {+ if (!(await knex.schema.hasColumn(TableName.AgentVaultVariable, "projectId"))) return;++ await knex.raw(+ `UPDATE ?? AS v SET "accessBundleId" = (+ SELECT s."accessBundleId" FROM ?? AS r JOIN ?? AS s ON s.id = r."serviceId"+ WHERE r."variableId" = v.id ORDER BY s."createdAt" LIMIT 1+ ) WHERE v."accessBundleId" IS NULL`,+ [TableName.AgentVaultVariable, TableName.AgentVaultServiceVariableReference, TableName.AgentVaultService]+ );+ await knex.raw(+ `UPDATE ?? AS v SET "accessBundleId" = (+ SELECT b.id FROM ?? AS b WHERE b."projectId" = v."projectId" ORDER BY b."createdAt" LIMIT 1+ ) WHERE v."accessBundleId" IS NULL`,+ [TableName.AgentVaultVariable, TableName.AgentVaultAccessBundle]+ );+ await knex(TableName.AgentVaultVariable).whereNull("accessBundleId").delete();++ // The analytics view selects these columns, and Postgres won't drop a column a view uses. The next+ // regeneration recreates it.+ await knex.raw(`DROP VIEW IF EXISTS analytics.??`, [TableName.AgentVaultVariable]);++ await knex.schema.alterTable(TableName.AgentVaultVariable, (t) => {+ t.dropForeign(["accessBundleId"]);+ t.dropNullable("accessBundleId");+ t.foreign("accessBundleId").references("id").inTable(TableName.AgentVaultAccessBundle).onDelete("CASCADE");++ t.dropUnique(["projectId", "key"], PROJECT_KEY_UNIQUE);+ t.dropForeign(["projectId"]);+ t.dropColumn("projectId");+ });+}diff --git a/backend/src/db/migrations/utils/agent-vault-variable-key-dedupe.test.ts b/backend/src/db/migrations/utils/agent-vault-variable-key-dedupe.test.tsnew file mode 100644index 0000000000..725a77d69f--- /dev/null+++ b/backend/src/db/migrations/utils/agent-vault-variable-key-dedupe.test.ts@@ -0,0 +1,74 @@+import { findVariableKeyRenames, TVariableKeyRow } from "./agent-vault-variable-key-dedupe";++const PROJECT = "project-a";++const at = (minute: number) => new Date(Date.UTC(2026, 9, 1, 0, minute));++const row = (id: string, key: string, minute: number, projectId = PROJECT): TVariableKeyRow => ({+ id,+ key,+ projectId,+ createdAt: at(minute)+});++describe("findVariableKeyRenames", () => {+ test("distinct keys are left alone", () => {+ expect(findVariableKeyRenames([row("a", "GITHUB_TOKEN", 0), row("b", "SLACK_TOKEN", 1)]).size).toBe(0);+ });++ test("the oldest keeps a shared key and the rest are numbered in creation order", () => {+ const renames = findVariableKeyRenames([+ row("third", "API_KEY", 3),+ row("first", "API_KEY", 1),+ row("second", "API_KEY", 2)+ ]);++ expect(Object.fromEntries(renames)).toEqual({ second: "API_KEY_1", third: "API_KEY_2" });+ });++ test("a suffix another variable already holds is skipped, and that variable keeps it", () => {+ const renames = findVariableKeyRenames([+ row("first", "API_KEY", 1),+ row("second", "API_KEY", 2),+ row("holder", "API_KEY_1", 0)+ ]);++ expect(Object.fromEntries(renames)).toEqual({ second: "API_KEY_2" });+ });++ test("two renamed variables never land on the same key", () => {+ const renames = findVariableKeyRenames([+ row("a1", "A", 1),+ row("a2", "A", 2),+ row("a1dup", "A_1", 3),+ row("a1dup2", "A_1", 4)+ ]);++ const finalKeys = ["a1", "a2", "a1dup", "a1dup2"].map((id) => renames.get(id) ?? { a1: "A", a1dup: "A_1" }[id]);+ expect(new Set(finalKeys).size).toBe(4);+ });++ test("projects are deduplicated separately", () => {+ const renames = findVariableKeyRenames([row("a", "TOKEN", 1, "project-a"), row("b", "TOKEN", 2, "project-b")]);++ expect(renames.size).toBe(0);+ });++ test("a key at the length limit is shortened to fit its suffix", () => {+ const longKey = `K${"X".repeat(63)}`;+ const renames = findVariableKeyRenames([row("first", longKey, 1), row("second", longKey, 2)]);++ const renamed = renames.get("second")!;+ expect(renamed).toHaveLength(64);+ expect(renamed.endsWith("_1")).toBe(true);+ expect(renamed).toMatch(/^[A-Z][A-Z0-9_]*$/);+ });++ test("a creation-time tie is broken by id, so the outcome never depends on row order", () => {+ const forward = findVariableKeyRenames([row("b", "TOKEN", 1), row("a", "TOKEN", 1)]);+ const reversed = findVariableKeyRenames([row("a", "TOKEN", 1), row("b", "TOKEN", 1)]);++ expect(Object.fromEntries(forward)).toEqual({ b: "TOKEN_1" });+ expect(Object.fromEntries(reversed)).toEqual({ b: "TOKEN_1" });+ });+});diff --git a/backend/src/db/migrations/utils/agent-vault-variable-key-dedupe.ts b/backend/src/db/migrations/utils/agent-vault-variable-key-dedupe.tsnew file mode 100644index 0000000000..f4ac8ffde9--- /dev/null+++ b/backend/src/db/migrations/utils/agent-vault-variable-key-dedupe.ts@@ -0,0 +1,48 @@+// Frozen copy of the key limit at the time variables moved to product scope, so a later change to the app's limit+// can't change what this migration did.+const KEY_MAX_LENGTH = 64;++export type TVariableKeyRow = { id: string; projectId: string; key: string; createdAt: Date };++const withSuffix = (key: string, n: number) => {+ const suffix = `_${n}`;+ return `${key.slice(0, KEY_MAX_LENGTH - suffix.length)}${suffix}`;+};++/**+ * Keys were unique per access bundle and are now unique per project. In each project the oldest variable keeps a+ * shared key and every later one takes the first free `KEY_1`, `KEY_2`, ... A renamed key never takes one any+ * variable already holds, so no variable that keeps its key is ever touched. Services seal variables by id, not+ * key, so a rename changes nothing a service sends.+ */+export const findVariableKeyRenames = (rows: TVariableKeyRow[]): Map<string, string> => {+ const renames = new Map<string, string>();++ const byProject = new Map<string, TVariableKeyRow[]>();+ rows.forEach((row) => {+ const projectRows = byProject.get(row.projectId) ?? [];+ projectRows.push(row);+ byProject.set(row.projectId, projectRows);+ });++ byProject.forEach((projectRows) => {+ const taken = new Set(projectRows.map((row) => row.key));+ const seen = new Set<string>();++ [...projectRows]+ .sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime() || a.id.localeCompare(b.id))+ .forEach((row) => {+ if (!seen.has(row.key)) {+ seen.add(row.key);+ return;+ }+ let n = 1;+ while (taken.has(withSuffix(row.key, n))) n += 1;+ const renamed = withSuffix(row.key, n);+ taken.add(renamed);+ renames.set(row.id, renamed);+ });+ });++ return renames;+};diff --git a/backend/src/db/sanitized-schema.yaml b/backend/src/db/sanitized-schema.yamlindex 41dbbe9f8e..7b660a9c24 100644--- a/backend/src/db/sanitized-schema.yaml+++ b/backend/src/db/sanitized-schema.yaml@@ -115,6 +115,7 @@ tables:source: public.agent_vault_variablescolumns:- id+ - projectId- accessBundleId- createdAt- updatedAtdiff --git a/backend/src/db/schemas/agent-vault-variables.ts b/backend/src/db/schemas/agent-vault-variables.tsindex 96662c432d..214c1bdd81 100644--- a/backend/src/db/schemas/agent-vault-variables.ts+++ b/backend/src/db/schemas/agent-vault-variables.ts@@ -11,11 +11,12 @@ import { TImmutableDBKeys } from "./models";export const AgentVaultVariablesSchema = z.object({id: z.string().uuid(),- accessBundleId: z.string().uuid(),+ accessBundleId: z.string().uuid().nullable().optional(),key: z.string(),encryptedValue: zodBuffer,createdAt: z.date(),- updatedAt: z.date()+ updatedAt: z.date(),+ projectId: z.string()});export type TAgentVaultVariables = z.infer<typeof AgentVaultVariablesSchema>;diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-access-bundle-router.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-access-bundle-router.tsindex 580a8bfbf3..f6780f89eb 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@@ -11,8 +11,7 @@ import { parseHostPatterns } from "@app/ee/services/agent-vault/agent-vault-hostimport { EventType } from "@app/ee/services/audit-log/audit-log-types";import { AGENT_VAULT } from "@app/lib/api-docs";import { ApiDocsTags } from "@app/lib/api-docs/constants";-import { readLimit, secretsLimit, writeLimit } from "@app/server/config/rateLimiter";-import { addNoCacheHeaders } from "@app/server/lib/caching";+import { readLimit, writeLimit } from "@app/server/config/rateLimiter";import { emitAgentVaultTelemetry } from "@app/server/lib/telemetry";import { verifyAuth } from "@app/server/plugins/auth/verify-auth";import { AuthMode } from "@app/services/auth/auth-type";@@ -37,10 +36,7 @@ import {AgentVaultProductMemberSchema,AgentVaultServiceSchema,AgentVaultSubstitutionsInputSchema,- AgentVaultSubstitutionsUpdateSchema,- AgentVaultVariableKeySchema,- AgentVaultVariableSchema,- AgentVaultVariableValueSchema+ AgentVaultSubstitutionsUpdateSchema} from "./agent-vault-schemas";const AccessBundleDescriptionSchema = z@@ -515,236 +511,6 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodPro}});- server.route({- method: "GET",- url: "/:accessBundleId/variables",- config: { rateLimit: readLimit },- schema: {- hide: false,- operationId: "listAgentVaultVariables",- description: "List the variables in an Agent Vault access bundle",- tags: [ApiDocsTags.AgentVaultAccessBundles],- params: z.object({- accessBundleId: z.string().uuid().describe(AGENT_VAULT.ACCESS_BUNDLE.accessBundleId)- }),- response: { 200: z.object({ variables: AgentVaultVariableSchema.array() }) }- },- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),- handler: async (req) => {- const variables = await server.services.agentVaultAccessBundle.listVariables({- projectId: req.internalAgentVaultProjectId,- ctx: actorContext(req),- accessBundleId: req.params.accessBundleId- });- return { variables };- }- });-- server.route({- method: "POST",- url: "/:accessBundleId/variables",- config: { rateLimit: writeLimit },- schema: {- hide: false,- operationId: "createAgentVaultVariable",- description: "Create a variable in an Agent Vault access bundle",- tags: [ApiDocsTags.AgentVaultAccessBundles],- params: z.object({- accessBundleId: z.string().uuid().describe(AGENT_VAULT.ACCESS_BUNDLE.accessBundleId)- }),- body: z.object({- key: AgentVaultVariableKeySchema.describe(AGENT_VAULT.VARIABLE.key),- value: AgentVaultVariableValueSchema.describe(AGENT_VAULT.VARIABLE.value)- }),- response: { 200: z.object({ variable: AgentVaultVariableSchema }) }- },- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),- handler: async (req) => {- const { variable, accessBundleName } = await server.services.agentVaultAccessBundle.createVariable({- projectId: req.internalAgentVaultProjectId,- ctx: actorContext(req),- accessBundleId: req.params.accessBundleId,- ...req.body- });-- await server.services.auditLog.createAuditLog({- ...req.auditLogInfo,- orgId: req.permission.orgId,- projectId: req.internalAgentVaultProjectId,- event: {- type: EventType.AGENT_VAULT_VARIABLE_CREATE,- metadata: {- accessBundleId: req.params.accessBundleId,- accessBundleName,- variableId: variable.id,- key: variable.key- }- }- });-- emitAgentVaultTelemetry(server.services.telemetry, req, {- event: PostHogEventTypes.AgentVaultVariableCreated,- properties: { accessBundleId: req.params.accessBundleId, variableId: variable.id }- });-- return { variable };- }- });-- server.route({- method: "PATCH",- url: "/:accessBundleId/variables/:variableId",- config: { rateLimit: writeLimit },- schema: {- hide: false,- operationId: "updateAgentVaultVariable",- description: "Update a variable in an Agent Vault access bundle",- tags: [ApiDocsTags.AgentVaultAccessBundles],- params: z.object({- accessBundleId: z.string().uuid().describe(AGENT_VAULT.ACCESS_BUNDLE.accessBundleId),- variableId: z.string().uuid().describe(AGENT_VAULT.VARIABLE.variableId)- }),- body: z- .object({- key: AgentVaultVariableKeySchema.optional().describe(AGENT_VAULT.VARIABLE.key),- value: AgentVaultVariableValueSchema.optional().describe(AGENT_VAULT.VARIABLE.updateValue)- })- .refine(- (body) => Object.values(body).some((value) => value !== undefined),- "Provide 'key', 'value' or both to update"- ),- response: { 200: z.object({ variable: AgentVaultVariableSchema }) }- },- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),- handler: async (req) => {- const { variable, previousKey, accessBundleName } = await server.services.agentVaultAccessBundle.updateVariable({- projectId: req.internalAgentVaultProjectId,- ctx: actorContext(req),- accessBundleId: req.params.accessBundleId,- variableId: req.params.variableId,- ...req.body- });-- await server.services.auditLog.createAuditLog({- ...req.auditLogInfo,- orgId: req.permission.orgId,- projectId: req.internalAgentVaultProjectId,- event: {- type: EventType.AGENT_VAULT_VARIABLE_UPDATE,- metadata: {- accessBundleId: req.params.accessBundleId,- accessBundleName,- variableId: variable.id,- key: variable.key,- previousKey: previousKey === variable.key ? undefined : previousKey,- valueReplaced: req.body.value !== undefined- }- }- });-- emitAgentVaultTelemetry(server.services.telemetry, req, {- event: PostHogEventTypes.AgentVaultVariableUpdated,- properties: {- accessBundleId: req.params.accessBundleId,- variableId: variable.id,- keyChanged: previousKey !== variable.key,- valueReplaced: req.body.value !== undefined,- usedByServiceCount: variable.serviceIds.length- }- });-- return { variable };- }- });-- server.route({- method: "DELETE",- url: "/:accessBundleId/variables/:variableId",- config: { rateLimit: writeLimit },- schema: {- hide: false,- operationId: "deleteAgentVaultVariable",- description: "Delete a variable from an Agent Vault access bundle. A variable a service uses can't be deleted.",- tags: [ApiDocsTags.AgentVaultAccessBundles],- params: z.object({- accessBundleId: z.string().uuid().describe(AGENT_VAULT.ACCESS_BUNDLE.accessBundleId),- variableId: z.string().uuid().describe(AGENT_VAULT.VARIABLE.variableId)- }),- response: { 200: z.object({ variable: AgentVaultVariableSchema }) }- },- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),- handler: async (req) => {- const { variable, accessBundleName } = await server.services.agentVaultAccessBundle.deleteVariable({- projectId: req.internalAgentVaultProjectId,- ctx: actorContext(req),- accessBundleId: req.params.accessBundleId,- variableId: req.params.variableId- });-- await server.services.auditLog.createAuditLog({- ...req.auditLogInfo,- orgId: req.permission.orgId,- projectId: req.internalAgentVaultProjectId,- event: {- type: EventType.AGENT_VAULT_VARIABLE_DELETE,- metadata: {- accessBundleId: req.params.accessBundleId,- accessBundleName,- variableId: variable.id,- key: variable.key- }- }- });-- emitAgentVaultTelemetry(server.services.telemetry, req, {- event: PostHogEventTypes.AgentVaultVariableDeleted,- properties: { accessBundleId: req.params.accessBundleId, variableId: variable.id }- });-- return { variable };- }- });-- server.route({- method: "GET",- url: "/:accessBundleId/variables/:variableId/value",- config: { rateLimit: secretsLimit },- schema: {- hide: false,- operationId: "getAgentVaultVariableValue",- description: "Get the value of a variable in an Agent Vault access bundle",- tags: [ApiDocsTags.AgentVaultAccessBundles],- params: z.object({- accessBundleId: z.string().uuid().describe(AGENT_VAULT.ACCESS_BUNDLE.accessBundleId),- variableId: z.string().uuid().describe(AGENT_VAULT.VARIABLE.variableId)- }),- response: { 200: z.object({ value: z.string().describe(AGENT_VAULT.VARIABLE.revealedValue) }) }- },- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),- handler: async (req, reply) => {- const { variableId, key, value, accessBundleName } =- await server.services.agentVaultAccessBundle.getVariableValue({- projectId: req.internalAgentVaultProjectId,- ctx: actorContext(req),- accessBundleId: req.params.accessBundleId,- variableId: req.params.variableId- });-- await server.services.auditLog.createAuditLog({- ...req.auditLogInfo,- orgId: req.permission.orgId,- projectId: req.internalAgentVaultProjectId,- event: {- type: EventType.AGENT_VAULT_VARIABLE_VALUE_VIEW,- metadata: { accessBundleId: req.params.accessBundleId, accessBundleName, variableId, key }- }- });-- addNoCacheHeaders(reply);- return { value };- }- });-server.route({method: "GET",url: "/:accessBundleId/members",diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-schemas.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-schemas.tsindex c4870898e0..08c56fa56f 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@@ -250,9 +250,17 @@ export const AgentVaultVariableValueSchema = zexport const AgentVaultVariableSchema = z.object({id: z.string().uuid().describe(AGENT_VAULT.VARIABLE.variableId),- accessBundleId: z.string().uuid().describe(AGENT_VAULT.ACCESS_BUNDLE.accessBundleId),key: z.string().describe(AGENT_VAULT.VARIABLE.key),- serviceIds: z.string().uuid().array().describe(AGENT_VAULT.VARIABLE.serviceIds),+ usedBy: z+ .object({+ id: z.string().uuid().describe(AGENT_VAULT.VARIABLE.usedById),+ name: z.string().describe(AGENT_VAULT.VARIABLE.usedByName),+ hostPattern: z.string().describe(AGENT_VAULT.VARIABLE.usedByHostPattern),+ accessBundleId: z.string().uuid().describe(AGENT_VAULT.VARIABLE.usedByAccessBundleId),+ accessBundleName: z.string().describe(AGENT_VAULT.VARIABLE.usedByAccessBundleName)+ })+ .array()+ .describe(AGENT_VAULT.VARIABLE.usedBy),createdAt: z.date().describe(AGENT_VAULT.VARIABLE.createdAt),updatedAt: z.date().describe(AGENT_VAULT.VARIABLE.updatedAt)});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.tsnew file mode 100644index 0000000000..92ae2a0782--- /dev/null+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-variable-router.ts@@ -0,0 +1,222 @@+import { z } from "zod";++import { EventType } from "@app/ee/services/audit-log/audit-log-types";+import { AGENT_VAULT } from "@app/lib/api-docs";+import { ApiDocsTags } from "@app/lib/api-docs/constants";+import { readLimit, secretsLimit, writeLimit } from "@app/server/config/rateLimiter";+import { addNoCacheHeaders } from "@app/server/lib/caching";+import { emitAgentVaultTelemetry } from "@app/server/lib/telemetry";+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";+import { AuthMode } from "@app/services/auth/auth-type";+import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";++import { actorContext } from "./agent-vault-router-fns";+import {+ AgentVaultVariableKeySchema,+ AgentVaultVariableSchema,+ AgentVaultVariableValueSchema+} from "./agent-vault-schemas";++export const registerAgentVaultVariableRouter = async (server: FastifyZodProvider) => {+ server.route({+ method: "GET",+ url: "/",+ config: { rateLimit: readLimit },+ schema: {+ hide: false,+ operationId: "listAgentVaultVariables",+ description: "List the variables in Agent Vault",+ tags: [ApiDocsTags.AgentVaultVariables],+ response: { 200: z.object({ variables: AgentVaultVariableSchema.array() }) }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ handler: async (req) => {+ const variables = await server.services.agentVaultVariable.listVariables({+ projectId: req.internalAgentVaultProjectId,+ ctx: actorContext(req)+ });+ return { variables };+ }+ });++ server.route({+ method: "POST",+ url: "/",+ config: { rateLimit: writeLimit },+ schema: {+ hide: false,+ operationId: "createAgentVaultVariable",+ description: "Create a variable in Agent Vault",+ tags: [ApiDocsTags.AgentVaultVariables],+ body: z.object({+ key: AgentVaultVariableKeySchema.describe(AGENT_VAULT.VARIABLE.key),+ value: AgentVaultVariableValueSchema.describe(AGENT_VAULT.VARIABLE.value)+ }),+ response: { 200: z.object({ variable: AgentVaultVariableSchema }) }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ handler: async (req) => {+ const { variable } = await server.services.agentVaultVariable.createVariable({+ projectId: req.internalAgentVaultProjectId,+ ctx: actorContext(req),+ ...req.body+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ orgId: req.permission.orgId,+ projectId: req.internalAgentVaultProjectId,+ event: {+ type: EventType.AGENT_VAULT_VARIABLE_CREATE,+ metadata: { variableId: variable.id, key: variable.key }+ }+ });++ emitAgentVaultTelemetry(server.services.telemetry, req, {+ event: PostHogEventTypes.AgentVaultVariableCreated,+ properties: { variableId: variable.id }+ });++ return { variable };+ }+ });++ server.route({+ method: "PATCH",+ url: "/:variableId",+ config: { rateLimit: writeLimit },+ schema: {+ hide: false,+ operationId: "updateAgentVaultVariable",+ description: "Update a variable in Agent Vault",+ tags: [ApiDocsTags.AgentVaultVariables],+ params: z.object({+ variableId: z.string().uuid().describe(AGENT_VAULT.VARIABLE.variableId)+ }),+ body: z+ .object({+ key: AgentVaultVariableKeySchema.optional().describe(AGENT_VAULT.VARIABLE.key),+ value: AgentVaultVariableValueSchema.optional().describe(AGENT_VAULT.VARIABLE.updateValue)+ })+ .refine(+ (body) => Object.values(body).some((value) => value !== undefined),+ "Provide 'key', 'value' or both to update"+ ),+ response: { 200: z.object({ variable: AgentVaultVariableSchema }) }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ handler: async (req) => {+ const { variable, previousKey } = await server.services.agentVaultVariable.updateVariable({+ projectId: req.internalAgentVaultProjectId,+ ctx: actorContext(req),+ variableId: req.params.variableId,+ ...req.body+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ orgId: req.permission.orgId,+ projectId: req.internalAgentVaultProjectId,+ event: {+ type: EventType.AGENT_VAULT_VARIABLE_UPDATE,+ metadata: {+ variableId: variable.id,+ key: variable.key,+ previousKey: previousKey === variable.key ? undefined : previousKey,+ valueReplaced: req.body.value !== undefined+ }+ }+ });++ emitAgentVaultTelemetry(server.services.telemetry, req, {+ event: PostHogEventTypes.AgentVaultVariableUpdated,+ properties: {+ variableId: variable.id,+ keyChanged: previousKey !== variable.key,+ valueReplaced: req.body.value !== undefined,+ usedByServiceCount: variable.usedBy.length+ }+ });++ return { variable };+ }+ });++ server.route({+ method: "DELETE",+ url: "/:variableId",+ config: { rateLimit: writeLimit },+ schema: {+ hide: false,+ operationId: "deleteAgentVaultVariable",+ description: "Delete a variable from Agent Vault. A variable a service uses can't be deleted.",+ tags: [ApiDocsTags.AgentVaultVariables],+ params: z.object({+ variableId: z.string().uuid().describe(AGENT_VAULT.VARIABLE.variableId)+ }),+ response: { 200: z.object({ variable: AgentVaultVariableSchema }) }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ handler: async (req) => {+ const { variable } = await server.services.agentVaultVariable.deleteVariable({+ projectId: req.internalAgentVaultProjectId,+ ctx: actorContext(req),+ variableId: req.params.variableId+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ orgId: req.permission.orgId,+ projectId: req.internalAgentVaultProjectId,+ event: {+ type: EventType.AGENT_VAULT_VARIABLE_DELETE,+ metadata: { variableId: variable.id, key: variable.key }+ }+ });++ emitAgentVaultTelemetry(server.services.telemetry, req, {+ event: PostHogEventTypes.AgentVaultVariableDeleted,+ properties: { variableId: variable.id }+ });++ return { variable };+ }+ });++ server.route({+ method: "GET",+ url: "/:variableId/value",+ config: { rateLimit: secretsLimit },+ schema: {+ hide: false,+ operationId: "getAgentVaultVariableValue",+ description: "Get the value of a variable in Agent Vault",+ tags: [ApiDocsTags.AgentVaultVariables],+ params: z.object({+ variableId: z.string().uuid().describe(AGENT_VAULT.VARIABLE.variableId)+ }),+ response: { 200: z.object({ value: z.string().describe(AGENT_VAULT.VARIABLE.revealedValue) }) }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ handler: async (req, reply) => {+ const { variableId, key, value } = await server.services.agentVaultVariable.getVariableValue({+ projectId: req.internalAgentVaultProjectId,+ ctx: actorContext(req),+ variableId: req.params.variableId+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ orgId: req.permission.orgId,+ projectId: req.internalAgentVaultProjectId,+ event: {+ type: EventType.AGENT_VAULT_VARIABLE_VALUE_VIEW,+ metadata: { variableId, key }+ }+ });++ addNoCacheHeaders(reply);+ return { value };+ }+ });+};diff --git a/backend/src/ee/routes/v1/agent-vault-routers/index.ts b/backend/src/ee/routes/v1/agent-vault-routers/index.tsindex 047d94d09b..21ead9ad82 100644--- a/backend/src/ee/routes/v1/agent-vault-routers/index.ts+++ b/backend/src/ee/routes/v1/agent-vault-routers/index.ts@@ -7,10 +7,12 @@ import { registerAgentVaultProxyRouter } from "./agent-vault-proxy-router";import { registerAgentVaultSessionLogRouter } from "./agent-vault-session-log-router";import { registerAgentVaultSessionRouter } from "./agent-vault-session-router";import { registerAgentVaultSettingsRouter } from "./agent-vault-settings-router";+import { registerAgentVaultVariableRouter } from "./agent-vault-variable-router";export const registerAgentVaultRouters = async (server: FastifyZodProvider) => {await server.register(registerAgentVaultProjectRouter, { prefix: "/project" });await server.register(registerAgentVaultAccessBundleRouter, { prefix: "/access-bundles" });+ await server.register(registerAgentVaultVariableRouter, { prefix: "/variables" });await server.register(async (sessionServer) => {await sessionServer.register(registerAgentVaultSessionRouter);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 bb8a17beaf..8bdc58b750 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@@ -9,7 +9,6 @@ import {TAgentVaultServices,TAgentVaultServiceSubstitutions,TAgentVaultServiceVariableReferencesInsert,- TAgentVaultVariables,TMemberships} from "@app/db/schemas";import { TIdentityGroupMembershipDALFactory } from "@app/ee/services/group/identity-group-membership-dal";@@ -20,7 +19,7 @@ import {ProjectPermissionSub} from "@app/ee/services/permission/project-permission";import { DatabaseErrorCode } from "@app/lib/error-codes";-import { BadRequestError, ConflictError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";+import { BadRequestError, ConflictError, NotFoundError } from "@app/lib/errors";import { hasPostgresConstraintViolation, hasPostgresErrorCode } from "@app/lib/errors/postgres";import { ActorType } from "@app/services/auth/auth-type";import { TKmsServiceFactory } from "@app/services/kms/kms-service";@@ -50,13 +49,13 @@ import {} from "../agent-vault/agent-vault-enums";import { getAgentVaultReachability } from "../agent-vault/agent-vault-permission";import {- AGENT_VAULT_MAX_VARIABLES,findStoredVariableIds,findVariableKeys,toStoredVariableReferences,toVariableReference} from "../agent-vault/agent-vault-variable-fns";import { TAgentVaultMemberDALFactory } from "../agent-vault-member/agent-vault-member-dal";+import { TAgentVaultVariableDALFactory } from "../agent-vault-variable/agent-vault-variable-dal";import { TAgentVaultAccessBundleActorRef, TAgentVaultAccessBundleDALFactory } from "./agent-vault-access-bundle-dal";import {TAddMembersDTO,@@ -66,18 +65,14 @@ import {TAgentVaultVariableReferenceSummary,TCreateAccessBundleDTO,TCreateServiceDTO,- TCreateVariableDTO,TDeleteAccessBundleDTO,TDeleteServiceDTO,TGetAccessBundleDTO,TListAccessBundlesDTO,TListMembersDTO,- TListVariablesDTO,TRevokeMembersDTO,TUpdateAccessBundleDTO,- TUpdateServiceDTO,- TUpdateVariableDTO,- TVariableByIdDTO+ TUpdateServiceDTO} from "./agent-vault-access-bundle-types";import { TAgentVaultServiceCustomHeaderDALFactory } from "./agent-vault-service-custom-header-dal";import { TAgentVaultServiceDALFactory } from "./agent-vault-service-dal";@@ -87,14 +82,13 @@ import {TAgentVaultVariableReferenceWithKey} from "./agent-vault-service-variable-reference-dal";import { planTransformationDiff, TTransformationWrite } from "./agent-vault-transformation-fns";-import { TAgentVaultVariableDALFactory } from "./agent-vault-variable-dal";type TAgentVaultAccessBundleServiceFactoryDep = {agentVaultAccessBundleDAL: TAgentVaultAccessBundleDALFactory;agentVaultServiceDAL: TAgentVaultServiceDALFactory;agentVaultServiceCustomHeaderDAL: TAgentVaultServiceCustomHeaderDALFactory;agentVaultServiceSubstitutionDAL: TAgentVaultServiceSubstitutionDALFactory;- agentVaultVariableDAL: TAgentVaultVariableDALFactory;+ agentVaultVariableDAL: Pick<TAgentVaultVariableDALFactory, "findKeysByProjectId" | "lockForReference">;agentVaultServiceVariableReferenceDAL: TAgentVaultServiceVariableReferenceDALFactory;permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;@@ -303,14 +297,6 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundconst getProjectCipher = (projectId: string) =>kmsService.createCipherPairWithDataKey({ type: KmsDataKey.SecretManager, projectId });- type TProjectCipher = Awaited<ReturnType<typeof getProjectCipher>>;-- const sealVariableValue = (encryptor: TProjectCipher["encryptor"], value: string) =>- encryptor({ plainText: Buffer.from(JSON.stringify({ value })) }).cipherTextBlob;-- const openVariableValue = (decryptor: TProjectCipher["decryptor"], encryptedValue: Buffer) =>- (JSON.parse(decryptor({ cipherTextBlob: encryptedValue }).toString("utf-8")) as { value: string }).value;-// `null` clears the sealed column, `undefined` leaves it alone. $decryptCredential reads a NULL secret// as passthrough, so the two are not interchangeable.type TCredentialWrite = { config: TAgentVaultCredentialConfig; secret: Record<string, string> | null | undefined };@@ -488,9 +474,9 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund}};- // A key the bundle does not define would reach the host as literal braces, so it fails the save instead.+ // A key Agent Vault does not define would reach the host as literal braces, so it fails the save instead.// Stored text that a save keeps rather than writes needs the lookup only for the ids it holds.- const loadBundleVariables = async (accessBundleId: string, texts: TReferencingText[], storedTexts: string[] = []) => {+ const loadProjectVariables = async (projectId: string, texts: TReferencingText[], storedTexts: string[] = []) => {if (!texts.some(({ text }) => findVariableKeys(text).length) &&!storedTexts.some((text) => findStoredVariableIds(text).length)@@ -498,14 +484,14 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundreturn { idOfKey: new Map<string, string>(), variableIds: new Set<string>() };}- const variables = await agentVaultVariableDAL.findKeysByAccessBundleId(accessBundleId);+ const variables = await agentVaultVariableDAL.findKeysByProjectId(projectId);const idOfKey = new Map(variables.map((variable) => [variable.key, variable.id]));texts.forEach(({ label, text }) => {const missing = findVariableKeys(text).find((key) => !idOfKey.has(key));if (missing) {throw new BadRequestError({- message: `${label} uses ${toVariableReference(missing)}, but this access bundle has no variable named '${missing}'. Add it under Variables, or correct the name.`+ message: `${label} uses ${toVariableReference(missing)}, but Agent Vault has no variable named '${missing}'. Add it under Variables, or correct the name.`});}});@@ -543,7 +529,7 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundvariableIds: ReadonlySet<string>): TAgentVaultServiceVariableReferencesInsert[] =>findStoredVariableIds(storedText)- // Resolve leaves an id that names no variable of this bundle as text, so it gets no row either.+ // Resolve leaves an id that names no variable of this project as text, so it gets no row either..filter((variableId) => variableIds.has(variableId)).map((variableId) => ({serviceId,@@ -581,6 +567,22 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund// a delete removes without taking the bundle lock. So only this one means a variable went away.const VARIABLE_REFERENCE_VARIABLE_FOREIGN_KEY = "agent_vault_service_variable_references_variableid_foreign";+ // A variable is deleted under its own row lock, not a bundle's, so a save holds the rows it references until it+ // commits. A delete then waits for the save and sees its references, and an id already gone fails the save here.+ const insertReferenceRows = async (+ projectId: string,+ rows: TAgentVaultServiceVariableReferencesInsert[],+ tx: Knex+ ) => {+ if (!rows.length) return;+ const variableIds = [...new Set(rows.map((row) => row.variableId))];+ const present = await agentVaultVariableDAL.lockForReference({ projectId, variableIds }, tx);+ if (present.length !== variableIds.length) {+ throw new BadRequestError({ message: VARIABLE_DELETED_DURING_SAVE_MESSAGE });+ }+ await agentVaultServiceVariableReferenceDAL.insertMany(rows, tx);+ };+const CREDENTIAL_CHANGED_DURING_SAVE_MESSAGE ="This service's credential was changed by another save while this one was in progress. Reload the service and save again.";@@ -818,7 +820,7 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundawait checkHostPatternConflicts({ accessBundleId: bundle.id, hostPattern });- const { idOfKey, variableIds } = await loadBundleVariables(bundle.id, [+ const { idOfKey, variableIds } = await loadProjectVariables(rest.projectId, [...credentialReferenceTexts(credential),...(customHeaders ?? []).map((header) => ({ label: `The custom header '${header.name}'`, text: header.value })),...(substitutions ?? []).map((substitution) => ({@@ -914,7 +916,7 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund))];- if (referenceRows.length) await agentVaultServiceVariableReferenceDAL.insertMany(referenceRows, tx);+ await insertReferenceRows(rest.projectId, referenceRows, tx);const variableReferences = referenceRows.length? await agentVaultServiceVariableReferenceDAL.findByServiceIds([created.id], tx): [];@@ -1003,8 +1005,8 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund: null;// Only the values that arrived. One left out keeps what is sealed, and so keeps its references.- const { idOfKey, variableIds } = await loadBundleVariables(- bundle.id,+ const { idOfKey, variableIds } = await loadProjectVariables(+ rest.projectId,[...(credential ? credentialReferenceTexts(credential) : []),...(customHeaders ?? []).flatMap((header) =>@@ -1255,7 +1257,7 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund))];- if (referenceRows.length) await agentVaultServiceVariableReferenceDAL.insertMany(referenceRows, tx);+ await insertReferenceRows(rest.projectId, referenceRows, tx);const variableReferences = await agentVaultServiceVariableReferenceDAL.findByServiceIds([service.id], tx);return { updatedService, updatedCustomHeaders, updatedSubstitutions, variableReferences };@@ -1313,210 +1315,6 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund};};- // Values never leave through this projection; only the audited value endpoint returns one.- const projectVariable = (variable: TAgentVaultVariables, serviceIds: string[]) => ({- id: variable.id,- accessBundleId: variable.accessBundleId,- key: variable.key,- serviceIds,- createdAt: variable.createdAt,- updatedAt: variable.updatedAt- });-- const serviceIdsUsing = (references: { variableId: string; serviceId: string }[], variableId: string) => [- ...new Set(- references.filter((reference) => reference.variableId === variableId).map((reference) => reference.serviceId)- )- ];-- // Variables are admin only, reads included: a member can reach a bundle without seeing what it is built- // from, and Edit is the action only an admin holds.- const resolveVariableBundle = async (dto: TGetAccessBundleDTO) => {- const { bundle, permission } = await resolveReachableBundle(dto);- if (- permission.cannot(- ProjectPermissionAgentVaultAccessBundleActions.Edit,- ProjectPermissionSub.AgentVaultAccessBundles- )- ) {- throw new ForbiddenRequestError({ message: "Only Agent Vault admins can view or change variables" });- }- return bundle;- };-- const duplicateVariableKeyMessage = (key: string) => `A variable named '${key}' already exists in this access bundle`;-- const variableInUseMessage = (key: string, serviceNames: string[]) => {- const names = serviceNames.map((serviceName) => `'${serviceName}'`).join(", ");- return serviceNames.length === 1- ? `The variable '${key}' is used by the service ${names}. Remove it from that service before deleting it.`- : `The variable '${key}' is used by the services ${names}. Remove it from those services before deleting it.`;- };-- const listVariables = async (dto: TListVariablesDTO) => {- const bundle = await resolveVariableBundle(dto);-- const variables = await agentVaultVariableDAL.findByAccessBundleId(bundle.id);- const references = await agentVaultServiceVariableReferenceDAL.findByVariableIds(- variables.map((variable) => variable.id)- );-- return variables.map((variable) => projectVariable(variable, serviceIdsUsing(references, variable.id)));- };-- const createVariable = async ({ accessBundleId, key, value, ...rest }: TCreateVariableDTO) => {- const bundle = await resolveVariableBundle({ ...rest, accessBundleId });-- const { encryptor } = await getProjectCipher(rest.projectId);- const encryptedValue = sealVariableValue(encryptor, value);-- // Under the bundle lock the count and the key check are authoritative. The unique index is the backstop.- const write = () =>- agentVaultVariableDAL.transaction(async (tx) => {- const locked = await agentVaultAccessBundleDAL.lockByIdInProject(- { id: bundle.id, projectId: rest.projectId },- tx- );- if (!locked) throw new NotFoundError({ message: `Access bundle with ID '${accessBundleId}' not found` });-- const existing = await agentVaultVariableDAL.findKeysByAccessBundleId(bundle.id, tx);- if (existing.some((variable) => variable.key === key)) {- throw new BadRequestError({ message: duplicateVariableKeyMessage(key) });- }- if (existing.length >= AGENT_VAULT_MAX_VARIABLES) {- throw new BadRequestError({- message: `An access bundle can hold at most ${AGENT_VAULT_MAX_VARIABLES} variables. Delete one it no longer uses first.`- });- }-- return agentVaultVariableDAL.create({ accessBundleId: bundle.id, key, encryptedValue }, tx);- });-- try {- return { variable: projectVariable(await write(), []), accessBundleName: bundle.name };- } catch (err) {- if (isUniqueViolation(err)) throw new BadRequestError({ message: duplicateVariableKeyMessage(key) });- throw err;- }- };-- const updateVariable = async ({ accessBundleId, variableId, key, value, ...rest }: TUpdateVariableDTO) => {- const bundle = await resolveVariableBundle({ ...rest, accessBundleId });-- const variable = await agentVaultVariableDAL.findOne({ id: variableId, accessBundleId: bundle.id });- if (!variable) throw new NotFoundError({ message: `Variable with ID '${variableId}' not found` });-- const encryptedValue =- value === undefined ? undefined : sealVariableValue((await getProjectCipher(rest.projectId)).encryptor, value);-- const write = () =>- agentVaultVariableDAL.transaction(async (tx) => {- const locked = await agentVaultAccessBundleDAL.lockByIdInProject(- { id: bundle.id, projectId: rest.projectId },- tx- );- if (!locked) throw new NotFoundError({ message: `Access bundle with ID '${accessBundleId}' not found` });-- const current = await agentVaultVariableDAL.findOne({ id: variable.id, accessBundleId: bundle.id }, tx);- if (!current) throw new NotFoundError({ message: `Variable with ID '${variableId}' not found` });-- if (key !== undefined && key !== current.key) {- const clash = await agentVaultVariableDAL.findOne({ accessBundleId: bundle.id, key }, tx);- if (clash) throw new BadRequestError({ message: duplicateVariableKeyMessage(key) });- }-- // A rename is this row alone. Sealed fields name the variable by id, so nothing that uses it changes.- const updated = await agentVaultVariableDAL.updateById(- current.id,- { key, ...(encryptedValue ? { encryptedValue } : {}) },- tx- );- const references = await agentVaultServiceVariableReferenceDAL.findByVariableIds([current.id], tx);- return { previous: current, updated, references };- });-- let result;- try {- result = await write();- } catch (err) {- if (isUniqueViolation(err)) {- throw new BadRequestError({ message: duplicateVariableKeyMessage(key ?? variable.key) });- }- throw err;- }-- const { previous, updated, references } = result;- return {- variable: projectVariable(updated, serviceIdsUsing(references, updated.id)),- previousKey: previous.key,- accessBundleName: bundle.name- };- };-- const deleteVariable = async ({ accessBundleId, variableId, ...rest }: TVariableByIdDTO) => {- const bundle = await resolveVariableBundle({ ...rest, accessBundleId });-- // The refusal here is the real check, under the lock every service write takes. The deferred foreign key- // only backs it up, and only raises at commit.- const remove = () =>- agentVaultVariableDAL.transaction(async (tx) => {- const locked = await agentVaultAccessBundleDAL.lockByIdInProject(- { id: bundle.id, projectId: rest.projectId },- tx- );- if (!locked) throw new NotFoundError({ message: `Access bundle with ID '${accessBundleId}' not found` });-- const variable = await agentVaultVariableDAL.findOne({ id: variableId, accessBundleId: bundle.id }, tx);- if (!variable) throw new NotFoundError({ message: `Variable with ID '${variableId}' not found` });-- const references = await agentVaultServiceVariableReferenceDAL.findByVariableIds([variable.id], tx);- if (references.length) {- const services = await agentVaultServiceDAL.find(- { $in: { id: serviceIdsUsing(references, variable.id) } },- { tx }- );- throw new ConflictError({- message: variableInUseMessage(- variable.key,- services.map((service) => service.name)- )- });- }-- return agentVaultVariableDAL.deleteById(variable.id, tx);- });-- let deleted: TAgentVaultVariables;- try {- deleted = await remove();- } catch (err) {- if (hasPostgresErrorCode(err, DatabaseErrorCode.ForeignKeyViolation)) {- throw new ConflictError({- message:- "This variable is still used by a service. Remove it from every service that uses it, then delete it."- });- }- throw err;- }-- return { variable: projectVariable(deleted, []), accessBundleName: bundle.name };- };-- const getVariableValue = async ({ accessBundleId, variableId, ...rest }: TVariableByIdDTO) => {- const bundle = await resolveVariableBundle({ ...rest, accessBundleId });-- const variable = await agentVaultVariableDAL.findOne({ id: variableId, accessBundleId: bundle.id });- if (!variable) throw new NotFoundError({ message: `Variable with ID '${variableId}' not found` });-- const { decryptor } = await getProjectCipher(rest.projectId);- return {- variableId: variable.id,- key: variable.key,- value: openVariableValue(decryptor, variable.encryptedValue),- accessBundleName: bundle.name- };- };-const listMembers = async ({ accessBundleId, search, limit, offset, ...rest }: TListMembersDTO) => {const { bundle, permission } = await resolveReachableBundle({ ...rest, accessBundleId });ForbiddenError.from(permission).throwUnlessCan(@@ -1699,11 +1497,6 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundcreateService,updateService,deleteService,- listVariables,- createVariable,- updateVariable,- deleteVariable,- getVariableValue,listMembers,listAvailableMembers,addMembers,diff --git a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-types.ts b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-types.tsindex 07d14ea100..052012abea 100644--- a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-types.ts+++ b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-types.ts@@ -101,23 +101,6 @@ export type TDeleteServiceDTO = TAgentVaultProjectScoped & {serviceId: string;};-export type TListVariablesDTO = TAgentVaultProjectScoped & { accessBundleId: string };--export type TCreateVariableDTO = TAgentVaultProjectScoped & {- accessBundleId: string;- key: string;- value: string;-};--export type TUpdateVariableDTO = TAgentVaultProjectScoped & {- accessBundleId: string;- variableId: string;- key?: string;- value?: string;-};--export type TVariableByIdDTO = TAgentVaultProjectScoped & { accessBundleId: string; variableId: string };-export type TListMembersDTO = TAgentVaultProjectScoped & {accessBundleId: string;search?: string;diff --git a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-variable-dal.ts b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-variable-dal.tsdeleted file mode 100644index d30517a3b3..0000000000--- a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-variable-dal.ts+++ /dev/null@@ -1,66 +0,0 @@-import { Knex } from "knex";--import { TDbClient } from "@app/db";-import { TableName, TAgentVaultVariables } from "@app/db/schemas";-import { DatabaseError } from "@app/lib/errors";-import { ormify, selectAllTableCols } from "@app/lib/knex";--export type TAgentVaultVariableDALFactory = ReturnType<typeof agentVaultVariableDALFactory>;--export type TAgentVaultVariableValueRow = Pick<TAgentVaultVariables, "id" | "accessBundleId" | "encryptedValue">;--export const agentVaultVariableDALFactory = (db: TDbClient) => {- const orm = ormify(db, TableName.AgentVaultVariable);-- // Reads the primary even without a tx, so a variable created a moment ago is always listed.- const findByAccessBundleId = async (accessBundleId: string, tx?: Knex): Promise<TAgentVaultVariables[]> => {- try {- return (await (tx || db)(TableName.AgentVaultVariable)- .where({ accessBundleId })- .orderBy("key", "asc")- .select(selectAllTableCols(TableName.AgentVaultVariable))) as TAgentVaultVariables[];- } catch (error) {- throw new DatabaseError({ error, name: "Find agent vault variables" });- }- };-- // Reads the primary even without a tx, so a key created a moment ago is always found.- const findKeysByAccessBundleId = async (- accessBundleId: string,- tx?: Knex- ): Promise<Pick<TAgentVaultVariables, "id" | "key">[]> => {- try {- return await (tx || db)(TableName.AgentVaultVariable).where({ accessBundleId }).select("id", "key");- } catch (error) {- throw new DatabaseError({ error, name: "Find agent vault variable keys" });- }- };-- // Resolve is the hot path, so it reads a replica. A variable is always saved before any service that uses it,- // but each query picks its own replica, and the one serving this read can trail the one that served the- // service. So an id the replica does not have is asked of the primary before resolve gives up on it.- const findValuesForResolve = async ({- variableIds,- accessBundleIds- }: {- variableIds: string[];- accessBundleIds: string[];- }): Promise<TAgentVaultVariableValueRow[]> => {- if (!variableIds.length || !accessBundleIds.length) return [];- const read = async (conn: Knex, ids: string[]): Promise<TAgentVaultVariableValueRow[]> =>- conn(TableName.AgentVaultVariable)- .whereIn("id", ids)- .whereIn("accessBundleId", accessBundleIds)- .select("id", "accessBundleId", "encryptedValue");- try {- const rows = await read(db.replicaNode(), variableIds);- const found = new Set(rows.map((row) => row.id));- const missing = variableIds.filter((id) => !found.has(id));- return missing.length ? [...rows, ...(await read(db, missing))] : rows;- } catch (error) {- throw new DatabaseError({ error, name: "Find agent vault variable values" });- }- };-- return { ...orm, findByAccessBundleId, findKeysByAccessBundleId, findValuesForResolve };-};diff --git a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.ts b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.tsindex 46cc6e2ee0..367fe1ca56 100644--- a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.ts+++ b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.ts@@ -28,7 +28,6 @@ import { findReachableAccessBundleIds, liveGroupIdsFrom } from "../agent-vault/aimport { expandStoredVariableReferences, findStoredVariableIds } from "../agent-vault/agent-vault-variable-fns";import { TAgentVaultServiceCustomHeaderDALFactory } from "../agent-vault-access-bundle/agent-vault-service-custom-header-dal";import { TAgentVaultServiceSubstitutionDALFactory } from "../agent-vault-access-bundle/agent-vault-service-substitution-dal";-import { TAgentVaultVariableDALFactory } from "../agent-vault-access-bundle/agent-vault-variable-dal";import { TAgentVaultSessionDALFactory } from "../agent-vault-session/agent-vault-session-dal";import { hashSessionToken } from "../agent-vault-session/agent-vault-session-fns";import { TAgentVaultSessionLogConfigDALFactory } from "../agent-vault-session-log/agent-vault-session-log-config-dal";@@ -38,6 +37,7 @@ import {TSessionLogLicenseService} from "../agent-vault-session-log/agent-vault-session-log-fns";import { openSessionLogKey } from "../agent-vault-session-log/agent-vault-session-log-secrets";+import { TAgentVaultVariableDALFactory } from "../agent-vault-variable/agent-vault-variable-dal";import { RESOURCE_TYPE_AGENT_VAULT_PROXY } from "../resource-auth-method/resource-auth-method-fns";import { TResourceAuthMethodServiceFactory } from "../resource-auth-method/resource-auth-method-service";import { parseRootCaCertificate } from "./agent-vault-ca-fns";@@ -345,13 +345,13 @@ export const agentVaultProxyServiceFactory = ({// dropping the service instead would also drop its method and path restrictions.const $expandVariableReferences = async ({sessionId,+ projectId,services,- accessBundleIdOf,decryptValue}: {sessionId: string;+ projectId: string;services: TResolvedService[];- accessBundleIdOf: Map<string, string>;decryptValue: (encryptedValue: Buffer) => string;}): Promise<TResolvedService[]> => {const sealedTextsOf = ({ credential, customHeaders, substitutions }: TResolvedService) => [@@ -367,12 +367,10 @@ export const agentVaultProxyServiceFactory = ({if (!variableIds.length) return services;const variables = new Map(- (- await agentVaultVariableDAL.findValuesForResolve({- variableIds,- accessBundleIds: [...new Set(accessBundleIdOf.values())]- })- ).map((variable) => [variable.id, variable])+ (await agentVaultVariableDAL.findValuesForResolve({ variableIds, projectId })).map((variable) => [+ variable.id,+ variable+ ]));const opened = new Map<string, string>();@@ -380,9 +378,9 @@ export const agentVaultProxyServiceFactory = ({const expanded = services.map((service) => {const valueOf = (variableId: string) => {+ // The lookup is scoped to the session's project, so a stored id never reaches another org's variable.const variable = variables.get(variableId);- // A stored id only ever names a variable of the service's own bundle.- if (!variable || variable.accessBundleId !== accessBundleIdOf.get(service.id)) {+ if (!variable) {unresolvedServiceIds.add(service.id);return undefined;}@@ -567,8 +565,8 @@ export const agentVaultProxyServiceFactory = ({const services = await $expandVariableReferences({sessionId: session.id,+ projectId: session.projectId,services: decryptedServices,- accessBundleIdOf: new Map(rows.map((row) => [row.id, row.accessBundleId])),decryptValue: $decryptValue});diff --git a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-variable-dal.test.ts b/backend/src/ee/services/agent-vault-variable/agent-vault-variable-dal.test.tssimilarity index 62%rename from backend/src/ee/services/agent-vault-access-bundle/agent-vault-variable-dal.test.tsrename to backend/src/ee/services/agent-vault-variable/agent-vault-variable-dal.test.tsindex 00b36838aa..edb5508b7d 100644--- a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-variable-dal.test.ts+++ b/backend/src/ee/services/agent-vault-variable/agent-vault-variable-dal.test.ts@@ -2,30 +2,33 @@ import { TableName } from "@app/db/schemas";import { agentVaultVariableDALFactory } from "./agent-vault-variable-dal";-type TRow = { id: string; accessBundleId: string; encryptedValue: Buffer };+type TRow = { id: string; projectId: string; encryptedValue: Buffer };-const BUNDLE_ID = "0b6f6c1e-5a8d-4c2b-9e7f-3d1a2b4c5d6e";+const PROJECT_ID = "0b6f6c1e-5a8d-4c2b-9e7f-3d1a2b4c5d6e";const FIRST_ID = "4f1e2d3c-6b5a-4978-8a6b-5c4d3e2f1a0b";const SECOND_ID = "9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d";-const row = (id: string): TRow => ({ id, accessBundleId: BUNDLE_ID, encryptedValue: Buffer.from(id) });+const row = (id: string): TRow => ({ id, projectId: PROJECT_ID, encryptedValue: Buffer.from(id) });// One database node: it answers with the rows it holds among the ids asked for, and records each lookup,// so a test can tell which node was asked for what.const buildNode = (rows: TRow[]) => {- const lookups: { table: string; ids: string[]; accessBundleIds: string[] }[] = [];+ const lookups: { table: string; ids: string[]; projectId?: string }[] = [];const node = (table: string) => {- const lookup = { table, ids: [] as string[], accessBundleIds: [] as string[] };+ const lookup = { table, ids: [] as string[], projectId: undefined as string | undefined };const chain = {whereIn: (column: string, values: string[]) => {if (column === "id") lookup.ids = values;- if (column === "accessBundleId") lookup.accessBundleIds = values;+ return chain;+ },+ where: (column: string, value: string) => {+ if (column === "projectId") lookup.projectId = value;return chain;},select: async () => {lookups.push(lookup);return rows.filter(- (candidate) => lookup.ids.includes(candidate.id) && lookup.accessBundleIds.includes(candidate.accessBundleId)+ (candidate) => lookup.ids.includes(candidate.id) && candidate.projectId === lookup.projectId);}};@@ -48,33 +51,40 @@ describe("findValuesForResolve", () => {replicaRows: [row(FIRST_ID), row(SECOND_ID)]});- const values = await dal.findValuesForResolve({ variableIds: [FIRST_ID, SECOND_ID], accessBundleIds: [BUNDLE_ID] });+ const values = await dal.findValuesForResolve({ variableIds: [FIRST_ID, SECOND_ID], projectId: PROJECT_ID });expect(values.map((value) => value.id)).toEqual([FIRST_ID, SECOND_ID]);expect(replica.lookups).toHaveLength(1);expect(primary.lookups).toEqual([]);});- test("an id the replica has not caught up on is asked of the primary, alone and still scoped to the bundle", async () => {+ test("an id the replica has not caught up on is asked of the primary, alone and still scoped to the project", async () => {const { dal, primary } = buildDAL({primaryRows: [row(FIRST_ID), row(SECOND_ID)],replicaRows: [row(FIRST_ID)]});- const values = await dal.findValuesForResolve({ variableIds: [FIRST_ID, SECOND_ID], accessBundleIds: [BUNDLE_ID] });+ const values = await dal.findValuesForResolve({ variableIds: [FIRST_ID, SECOND_ID], projectId: PROJECT_ID });expect(values.map((value) => value.id)).toEqual([FIRST_ID, SECOND_ID]);- expect(primary.lookups).toEqual([- { table: TableName.AgentVaultVariable, ids: [SECOND_ID], accessBundleIds: [BUNDLE_ID] }- ]);+ expect(primary.lookups).toEqual([{ table: TableName.AgentVaultVariable, ids: [SECOND_ID], projectId: PROJECT_ID }]);});test("an id neither node has is left out, for resolve to report", async () => {const { dal, primary } = buildDAL({ primaryRows: [row(FIRST_ID)], replicaRows: [row(FIRST_ID)] });- const values = await dal.findValuesForResolve({ variableIds: [FIRST_ID, SECOND_ID], accessBundleIds: [BUNDLE_ID] });+ const values = await dal.findValuesForResolve({ variableIds: [FIRST_ID, SECOND_ID], projectId: PROJECT_ID });expect(values.map((value) => value.id)).toEqual([FIRST_ID]);expect(primary.lookups).toHaveLength(1);});++ test("a variable of another project is never returned", async () => {+ const foreign = { ...row(SECOND_ID), projectId: "another-project" };+ const { dal } = buildDAL({ primaryRows: [row(FIRST_ID), foreign], replicaRows: [row(FIRST_ID), foreign] });++ const values = await dal.findValuesForResolve({ variableIds: [FIRST_ID, SECOND_ID], projectId: PROJECT_ID });++ expect(values.map((value) => value.id)).toEqual([FIRST_ID]);+ });});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.tsnew file mode 100644index 0000000000..73894c93b0--- /dev/null+++ b/backend/src/ee/services/agent-vault-variable/agent-vault-variable-dal.ts@@ -0,0 +1,185 @@+import { Knex } from "knex";++import { TDbClient } from "@app/db";+import { TableName, TAgentVaultVariables } from "@app/db/schemas";+import { DatabaseError } from "@app/lib/errors";+import { ormify } from "@app/lib/knex";++export type TAgentVaultVariableDALFactory = ReturnType<typeof agentVaultVariableDALFactory>;++// accessBundleId is left over from bundle-scoped variables and no longer read, so it stays off every row.+export type TAgentVaultVariable = Omit<TAgentVaultVariables, "accessBundleId">;++export type TAgentVaultVariableValueRow = Pick<TAgentVaultVariables, "id" | "encryptedValue">;++export type TAgentVaultVariableUser = {+ variableId: string;+ serviceId: string;+ serviceName: string;+ hostPattern: string;+ accessBundleId: string;+ accessBundleName: string;+};++const VARIABLE_COLUMNS = ["id", "projectId", "key", "encryptedValue", "createdAt", "updatedAt"] as const;++export const agentVaultVariableDALFactory = (db: TDbClient) => {+ const orm = ormify(db, TableName.AgentVaultVariable);++ const columns = VARIABLE_COLUMNS.map((column) => `${TableName.AgentVaultVariable}.${column}`);++ // Reads the primary even without a tx, so a variable created a moment ago is always listed.+ const findByProjectId = async (projectId: string, tx?: Knex): Promise<TAgentVaultVariable[]> => {+ try {+ return (await (tx || db)(TableName.AgentVaultVariable)+ .where({ projectId })+ .orderBy("key", "asc")+ .select(columns)) as TAgentVaultVariable[];+ } catch (error) {+ throw new DatabaseError({ error, name: "Find agent vault variables" });+ }+ };++ // Reads the primary even without a tx, so a key created a moment ago is always found.+ const findKeysByProjectId = async (+ projectId: string,+ tx?: Knex+ ): Promise<Pick<TAgentVaultVariables, "id" | "key">[]> => {+ try {+ return await (tx || db)(TableName.AgentVaultVariable).where({ projectId }).select("id", "key");+ } catch (error) {+ throw new DatabaseError({ error, name: "Find agent vault variable keys" });+ }+ };++ const findByIdInProject = async (+ { id, projectId }: { id: string; projectId: string },+ tx?: Knex+ ): Promise<TAgentVaultVariable | undefined> => {+ try {+ return (await (tx || db)(TableName.AgentVaultVariable).where({ id, projectId }).first(columns)) as+ | TAgentVaultVariable+ | undefined;+ } catch (error) {+ throw new DatabaseError({ error, name: "Find agent vault variable" });+ }+ };++ const findByKeyInProject = async (+ { key, projectId }: { key: string; projectId: string },+ tx?: Knex+ ): Promise<TAgentVaultVariable | undefined> => {+ try {+ return (await (tx || db)(TableName.AgentVaultVariable).where({ key, projectId }).first(columns)) as+ | TAgentVaultVariable+ | undefined;+ } catch (error) {+ throw new DatabaseError({ error, name: "Find agent vault variable by key" });+ }+ };++ // Taken by a variable delete, update or rename. A service save takes the same rows FOR SHARE, so a delete waits for+ // a save that is adding a reference, then sees it.+ const lockByIdInProject = async (+ { id, projectId }: { id: string; projectId: string },+ tx: Knex+ ): Promise<TAgentVaultVariable | undefined> => {+ try {+ return (await tx(TableName.AgentVaultVariable).where({ id, projectId }).forUpdate().first(columns)) as+ | TAgentVaultVariable+ | undefined;+ } catch (error) {+ throw new DatabaseError({ error, name: "Lock agent vault variable" });+ }+ };++ // Returns the ids that still exist. One missing was deleted after the save looked its key up.+ const lockForReference = async (+ { variableIds, projectId }: { variableIds: string[]; projectId: string },+ tx: Knex+ ): Promise<string[]> => {+ if (!variableIds.length) return [];+ try {+ const rows = await tx(TableName.AgentVaultVariable)+ .where({ projectId })+ .whereIn("id", variableIds)+ .orderBy("id")+ .forShare()+ .select("id");+ return rows.map((row) => row.id);+ } catch (error) {+ throw new DatabaseError({ error, name: "Lock agent vault variables for reference" });+ }+ };++ // Reads the primary even without a tx, so a service saved a moment ago shows as using its variables.+ const findUsers = async (variableIds: string[], tx?: Knex): Promise<TAgentVaultVariableUser[]> => {+ if (!variableIds.length) return [];+ try {+ return (await (tx || db)(TableName.AgentVaultServiceVariableReference)+ .join(+ TableName.AgentVaultService,+ `${TableName.AgentVaultServiceVariableReference}.serviceId`,+ `${TableName.AgentVaultService}.id`+ )+ .join(+ TableName.AgentVaultAccessBundle,+ `${TableName.AgentVaultService}.accessBundleId`,+ `${TableName.AgentVaultAccessBundle}.id`+ )+ .whereIn(`${TableName.AgentVaultServiceVariableReference}.variableId`, variableIds)+ .distinct(+ db.ref("variableId").withSchema(TableName.AgentVaultServiceVariableReference),+ db.ref("id").withSchema(TableName.AgentVaultService).as("serviceId"),+ db.ref("name").withSchema(TableName.AgentVaultService).as("serviceName"),+ db.ref("hostPattern").withSchema(TableName.AgentVaultService),+ db.ref("id").withSchema(TableName.AgentVaultAccessBundle).as("accessBundleId"),+ db.ref("name").withSchema(TableName.AgentVaultAccessBundle).as("accessBundleName")+ )+ .orderBy([+ { column: "accessBundleName", order: "asc" },+ { column: "serviceName", order: "asc" }+ ])) as TAgentVaultVariableUser[];+ } catch (error) {+ throw new DatabaseError({ error, name: "Find agent vault variable users" });+ }+ };++ // Resolve is the hot path, so it reads a replica. A variable is always saved before any service that uses it,+ // but each query picks its own replica, and the one serving this read can trail the one that served the+ // service. So an id the replica does not have is asked of the primary before resolve gives up on it.+ const findValuesForResolve = async ({+ variableIds,+ projectId+ }: {+ variableIds: string[];+ projectId: string;+ }): Promise<TAgentVaultVariableValueRow[]> => {+ if (!variableIds.length) return [];+ const read = async (conn: Knex, ids: string[]): Promise<TAgentVaultVariableValueRow[]> =>+ conn(TableName.AgentVaultVariable)+ .whereIn("id", ids)+ .where("projectId", projectId)+ .select("id", "encryptedValue");+ try {+ const rows = await read(db.replicaNode(), variableIds);+ const found = new Set(rows.map((row) => row.id));+ const missing = variableIds.filter((id) => !found.has(id));+ return missing.length ? [...rows, ...(await read(db, missing))] : rows;+ } catch (error) {+ throw new DatabaseError({ error, name: "Find agent vault variable values" });+ }+ };++ return {+ ...orm,+ findByProjectId,+ findKeysByProjectId,+ findByIdInProject,+ findByKeyInProject,+ lockByIdInProject,+ lockForReference,+ findUsers,+ findValuesForResolve+ };+};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.tsnew file mode 100644index 0000000000..d38b7dce67--- /dev/null+++ b/backend/src/ee/services/agent-vault-variable/agent-vault-variable-service.ts@@ -0,0 +1,222 @@+import { ForbiddenError } from "@casl/ability";++import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";+import {+ ProjectPermissionAgentVaultAccessBundleActions,+ ProjectPermissionSub+} from "@app/ee/services/permission/project-permission";+import { PgSqlLock } from "@app/keystore/keystore";+import { DatabaseErrorCode } from "@app/lib/error-codes";+import { BadRequestError, ConflictError, NotFoundError } from "@app/lib/errors";+import { hasPostgresErrorCode } from "@app/lib/errors/postgres";+import { TKmsServiceFactory } from "@app/services/kms/kms-service";+import { KmsDataKey } from "@app/services/kms/kms-types";++import { isUniqueViolation } from "../agent-vault/agent-vault-db-error-fns";+import { getAgentVaultPermission } from "../agent-vault/agent-vault-permission";+import { AGENT_VAULT_MAX_VARIABLES } from "../agent-vault/agent-vault-variable-fns";+import { TAgentVaultProjectScoped } from "../agent-vault-access-bundle/agent-vault-access-bundle-types";+import {+ TAgentVaultVariable,+ TAgentVaultVariableDALFactory,+ TAgentVaultVariableUser+} from "./agent-vault-variable-dal";+import {+ TAgentVaultVariableUsedBy,+ TCreateVariableDTO,+ TUpdateVariableDTO,+ TVariableByIdDTO+} from "./agent-vault-variable-types";++type TAgentVaultVariableServiceFactoryDep = {+ agentVaultVariableDAL: TAgentVaultVariableDALFactory;+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;+};++export type TAgentVaultVariableServiceFactory = ReturnType<typeof agentVaultVariableServiceFactory>;++export const agentVaultVariableServiceFactory = ({+ agentVaultVariableDAL,+ permissionService,+ kmsService+}: TAgentVaultVariableServiceFactoryDep) => {+ const getProjectCipher = (projectId: string) =>+ kmsService.createCipherPairWithDataKey({ type: KmsDataKey.SecretManager, projectId });++ // Variables are admin only, reads included: a member can use a service without seeing what it is built from, and+ // Edit on access bundles is the action only an admin holds.+ const assertCanManageVariables = async ({ projectId, ctx }: TAgentVaultProjectScoped) => {+ const { permission } = await getAgentVaultPermission({ permissionService }, { projectId, ctx });+ ForbiddenError.from(permission).throwUnlessCan(+ ProjectPermissionAgentVaultAccessBundleActions.Edit,+ ProjectPermissionSub.AgentVaultAccessBundles+ );+ };++ // Values never leave through this projection; only the audited value endpoint returns one.+ const projectVariable = (variable: TAgentVaultVariable, users: TAgentVaultVariableUser[]) => ({+ id: variable.id,+ key: variable.key,+ usedBy: users+ .filter((user) => user.variableId === variable.id)+ .map(+ (user): TAgentVaultVariableUsedBy => ({+ id: user.serviceId,+ name: user.serviceName,+ hostPattern: user.hostPattern,+ accessBundleId: user.accessBundleId,+ accessBundleName: user.accessBundleName+ })+ ),+ createdAt: variable.createdAt,+ updatedAt: variable.updatedAt+ });++ const notFound = (variableId: string) => new NotFoundError({ message: `Variable with ID '${variableId}' not found` });++ const duplicateKeyMessage = (key: string) => `A variable named '${key}' already exists.`;++ const inUseMessage = (key: string, users: TAgentVaultVariableUser[]) => {+ const names = users.map((user) => `'${user.serviceName}' (access bundle '${user.accessBundleName}')`).join(", ");+ return users.length === 1+ ? `The variable '${key}' is used by the service ${names}. Remove it from that service before deleting it.`+ : `The variable '${key}' is used by the services ${names}. Remove it from those services before deleting it.`;+ };++ const listVariables = async (dto: TAgentVaultProjectScoped) => {+ await assertCanManageVariables(dto);++ const variables = await agentVaultVariableDAL.findByProjectId(dto.projectId);+ const users = await agentVaultVariableDAL.findUsers(variables.map((variable) => variable.id));++ return variables.map((variable) => projectVariable(variable, users));+ };++ const createVariable = async ({ key, value, ...rest }: TCreateVariableDTO) => {+ await assertCanManageVariables(rest);++ const { encryptor } = await getProjectCipher(rest.projectId);+ const encryptedValue = encryptor({ plainText: Buffer.from(JSON.stringify({ value })) }).cipherTextBlob;++ // Serialised per project so the count and the key check are authoritative. The unique index is the backstop.+ const write = () =>+ agentVaultVariableDAL.transaction(async (tx) => {+ // eslint-disable-next-line @typescript-eslint/no-unsafe-call+ await tx.raw("SELECT pg_advisory_xact_lock(?)", [PgSqlLock.CreateAgentVaultVariable(rest.projectId)]);++ const existing = await agentVaultVariableDAL.findKeysByProjectId(rest.projectId, tx);+ if (existing.some((variable) => variable.key === key)) {+ throw new BadRequestError({ message: duplicateKeyMessage(key) });+ }+ if (existing.length >= AGENT_VAULT_MAX_VARIABLES) {+ throw new BadRequestError({+ message: `Agent Vault can hold at most ${AGENT_VAULT_MAX_VARIABLES} variables. Delete one that no service uses first.`+ });+ }++ return agentVaultVariableDAL.create({ projectId: rest.projectId, key, encryptedValue }, tx);+ });++ try {+ return { variable: projectVariable(await write(), []) };+ } catch (err) {+ if (isUniqueViolation(err)) throw new BadRequestError({ message: duplicateKeyMessage(key) });+ throw err;+ }+ };++ const updateVariable = async ({ variableId, key, value, ...rest }: TUpdateVariableDTO) => {+ await assertCanManageVariables(rest);++ const variable = await agentVaultVariableDAL.findByIdInProject({ id: variableId, projectId: rest.projectId });+ if (!variable) throw notFound(variableId);++ const encryptedValue =+ value === undefined+ ? undefined+ : (await getProjectCipher(rest.projectId)).encryptor({ plainText: Buffer.from(JSON.stringify({ value })) })+ .cipherTextBlob;++ const write = () =>+ agentVaultVariableDAL.transaction(async (tx) => {+ const current = await agentVaultVariableDAL.lockByIdInProject(+ { id: variable.id, projectId: rest.projectId },+ tx+ );+ if (!current) throw notFound(variableId);++ if (key !== undefined && key !== current.key) {+ const clash = await agentVaultVariableDAL.findByKeyInProject({ key, projectId: rest.projectId }, tx);+ if (clash) throw new BadRequestError({ message: duplicateKeyMessage(key) });+ }++ // A rename is this row alone. Sealed fields name the variable by id, so nothing that uses it changes.+ await agentVaultVariableDAL.updateById(current.id, { key, ...(encryptedValue ? { encryptedValue } : {}) }, tx);+ const updated = await agentVaultVariableDAL.findByIdInProject(+ { id: current.id, projectId: rest.projectId },+ tx+ );+ const users = await agentVaultVariableDAL.findUsers([current.id], tx);+ return { previous: current, updated: updated!, users };+ });++ let result;+ try {+ result = await write();+ } catch (err) {+ if (isUniqueViolation(err)) throw new BadRequestError({ message: duplicateKeyMessage(key ?? variable.key) });+ throw err;+ }++ return { variable: projectVariable(result.updated, result.users), previousKey: result.previous.key };+ };++ const deleteVariable = async ({ variableId, ...rest }: TVariableByIdDTO) => {+ await assertCanManageVariables(rest);++ // The refusal here is the real check. The row lock waits for any service save adding a reference to this+ // variable, since those take it FOR SHARE. The deferred foreign key only backs it up, and only raises at commit.+ const remove = () =>+ agentVaultVariableDAL.transaction(async (tx) => {+ const variable = await agentVaultVariableDAL.lockByIdInProject(+ { id: variableId, projectId: rest.projectId },+ tx+ );+ if (!variable) throw notFound(variableId);++ const users = await agentVaultVariableDAL.findUsers([variable.id], tx);+ if (users.length) throw new ConflictError({ message: inUseMessage(variable.key, users) });++ await agentVaultVariableDAL.deleteById(variable.id, tx);+ return variable;+ });++ try {+ return { variable: projectVariable(await remove(), []) };+ } catch (err) {+ if (hasPostgresErrorCode(err, DatabaseErrorCode.ForeignKeyViolation)) {+ throw new ConflictError({+ message:+ "This variable is still used by a service. Remove it from every service that uses it, then delete it."+ });+ }+ throw err;+ }+ };++ const getVariableValue = async ({ variableId, ...rest }: TVariableByIdDTO) => {+ await assertCanManageVariables(rest);++ const variable = await agentVaultVariableDAL.findByIdInProject({ id: variableId, projectId: rest.projectId });+ if (!variable) throw notFound(variableId);++ const { decryptor } = await getProjectCipher(rest.projectId);+ const { value } = JSON.parse(decryptor({ cipherTextBlob: variable.encryptedValue }).toString("utf-8")) as {+ value: string;+ };+ return { variableId: variable.id, key: variable.key, value };+ };++ return { listVariables, createVariable, updateVariable, deleteVariable, getVariableValue };+};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.tsnew file mode 100644index 0000000000..b7e65ee749--- /dev/null+++ b/backend/src/ee/services/agent-vault-variable/agent-vault-variable-types.ts@@ -0,0 +1,15 @@+import { TAgentVaultProjectScoped } from "../agent-vault-access-bundle/agent-vault-access-bundle-types";++export type TCreateVariableDTO = TAgentVaultProjectScoped & { key: string; value: string };++export type TUpdateVariableDTO = TAgentVaultProjectScoped & { variableId: string; key?: string; value?: string };++export type TVariableByIdDTO = TAgentVaultProjectScoped & { variableId: string };++export type TAgentVaultVariableUsedBy = {+ id: string;+ name: string;+ hostPattern: string;+ accessBundleId: string;+ accessBundleName: string;+};diff --git a/backend/src/ee/services/agent-vault/CLAUDE.md b/backend/src/ee/services/agent-vault/CLAUDE.mdindex 4b21f40d9d..e34c10ea79 100644--- a/backend/src/ee/services/agent-vault/CLAUDE.md+++ b/backend/src/ee/services/agent-vault/CLAUDE.md@@ -17,7 +17,8 @@ never in anything the agent holds.```agent-vault/ shared: enums, host grammar, conflict detection, reachability-agent-vault-access-bundle/ bundles, services, variables, credential encryption, grants+agent-vault-access-bundle/ bundles, services, credential encryption, grants+agent-vault-variable/ product-wide variables and the reads behind Used Byagent-vault-member/ product membership (list, add, role, remove)agent-vault-session/ mint, revoke, list, getagent-vault-project/ the per-org project's lazy bootstrap and resolver@@ -168,8 +169,9 @@ header" is the name in every layer; unqualified "header" means the credential's## Variables-A variable is a key and a sealed value on one bundle. A service uses one as `{{KEY}}` in its token, username,-password, a custom header value or a substitution value. Nothing else takes one: a host pattern, method or+A variable is a key and a sealed value on the Agent Vault project, so every bundle's services share one set and keys+are unique per project. A service uses one as `{{KEY}}` in its token, username, password, a custom header value or a+substitution value. Nothing else takes one: a host pattern, method orpath decides what a service can reach, so it stays literal.- **Sealed text names a variable by id, `{{<uuid>}}`, never by key.** The key form exists only at the API@@ -183,10 +185,15 @@ path decides what a service can reach, so it stays literal.the ids out of the decrypted fields, so a service saved mid-poll can never leave the two describingdifferent versions of a field.- **The rows are read off the stored text, never off the request**: `findStoredVariableIds`, kept to the- bundle's own variables, which is exactly what resolve expands. Nothing in the database can compare the+ project's own variables, which is exactly what resolve expands. Nothing in the database can compare therows with sealed text, and an id with no row is a variable the delete refusal lets go while a service still- sends it. Any new path that seals a service field derives its rows the same way, and moving a service to- another bundle would have to remap its ids, since resolve expands only its own bundle's.+ sends it. Any new path that seals a service field derives its rows the same way. Resolve expands only the+ session project's variables, so a service can move between bundles without remapping its ids.+- **A variable delete and a service save meet on the variable row, not the bundle.** The delete takes it `FOR+ UPDATE` and then reads the references; a save takes the rows it is about to reference `FOR SHARE` right before+ inserting them (`insertReferenceRows`). So the delete waits for an in-flight save and refuses with a 409 naming+ each service and its bundle, and a save whose variable went first fails with a 400. Create serialises on a+ per-project advisory lock for the cap and the key check; the `(projectId, key)` unique index is the backstop.- A stored value never comes back in any form, a lone `{{KEY}}` included. The sheet lists the keys a storedfield uses under the field and keeps the field masked until it is retyped. Settled: putting a lonereference back in its field made it the one stored field that shows, and left a field mixing text with a@@ -201,10 +208,15 @@ path decides what a service can reach, so it stays literal.and returns a 409 if the type changed, or, for a partial basic update, the sealed secret did. Otherwise thehalf left out is written back stale, and its rows describe text that is no longer sealed. That first read ison the primary (`findByIdInAccessBundle`): a replica still behind the previous save would 409 the next one.-- The `variableId` key is `DEFERRABLE INITIALLY DEFERRED`. A bundle delete cascades to its services and its- variables in one statement, and an immediate check can fire before the service cascade has removed the- rows, depending on which constraint was created first. The refusal that matters is the check under the- bundle lock (a 409 naming the services); the deferred key is the backstop and only raises at commit.+- The `variableId` key is `DEFERRABLE INITIALLY DEFERRED`. A project delete cascades to its bundles' services and+ to its variables in one statement, and an immediate check can fire before the service cascade has removed the+ rows, depending on which constraint was created first. The refusal that matters is the one under the variable+ row lock; the deferred key is the backstop and only raises at commit. Deleting a bundle keeps its variables.+- **Variables were per bundle until AGE2-130.** The migration gave each its bundle's project and, where two+ bundles shared a key, kept it on the oldest and renamed the rest `KEY_1`, `KEY_2`, ... (skipping any key already+ taken). That was safe only because sealed text names ids. `accessBundleId` survives, nullable and `SET NULL`,+ so a pod on the previous release keeps resolving during the rollout; nothing reads or writes it, and a follow-up+ migration drops it. Audit events from before the move still carry `accessBundleId` and `accessBundleName`.- Every `{{...}}` in a value must be an existing, well-formed key, or the save fails. A malformed one isrefused without quoting it, because the text was cut from a secret. Placeholders and header prefixes (thebearer prefix and custom header prefixes) can't contain double braces, which would read as a reference the@@ -223,7 +235,7 @@ path decides what a service can reach, so it stays literal.query can land on a different replica. An id with no variable behind it on either stays as text and islogged rather than dropping the service, which would also drop the service's method and path restrictions.Values saved before variables existed hold no id tokens, so they pass through untouched.-- Admin only, reads included: every variable route checks `Edit` on access bundles, which a member lacks,+- Admin only, reads included: every `/agent-vault/variables` route checks `Edit` on access bundles, which a member lacks,and the bundle read gives a member its services without `variableReferences` (left out, not empty, sincean empty list would claim they use none). Every value is sealed and no response but the value route returnsone. That route is a GET with no-store headers and one audit event per read.diff --git a/backend/src/ee/services/agent-vault/agent-vault-variable-fns.ts b/backend/src/ee/services/agent-vault/agent-vault-variable-fns.tsindex 3c9a64b08d..9422cf69e6 100644--- a/backend/src/ee/services/agent-vault/agent-vault-variable-fns.ts+++ b/backend/src/ee/services/agent-vault/agent-vault-variable-fns.ts@@ -2,7 +2,7 @@ import RE2 from "re2";export const AGENT_VAULT_VARIABLE_KEY_MAX_LENGTH = 64;export const AGENT_VAULT_VARIABLE_VALUE_MAX_LENGTH = 8192;-export const AGENT_VAULT_MAX_VARIABLES = 100;+export const AGENT_VAULT_MAX_VARIABLES = 500;// Counts every {{...}}, a repeat included: repeating one short reference is what would let a field fill in to// millions of characters. With the value limit this is the whole bound on a filled-in field, the text as typed// plus three values, so no save reads another row to hold a field to it and none can race another past it.diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex 30faead9fb..8cefb2b4d0 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -6518,12 +6518,13 @@ interface AgentVaultServiceDeleteEvent {};}-// Keys only. A variable's value never reaches an audit row.+// Keys only. A variable's value never reaches an audit row. Variables belonged to an access bundle until they moved to+// Agent Vault as a whole, so accessBundleId and accessBundleName are present only on events recorded before that.interface AgentVaultVariableCreateEvent {type: EventType.AGENT_VAULT_VARIABLE_CREATE;metadata: {- accessBundleId: string;- accessBundleName: string;+ accessBundleId?: string;+ accessBundleName?: string;variableId: string;key: string;};@@ -6532,8 +6533,8 @@ interface AgentVaultVariableCreateEvent {interface AgentVaultVariableUpdateEvent {type: EventType.AGENT_VAULT_VARIABLE_UPDATE;metadata: {- accessBundleId: string;- accessBundleName: string;+ accessBundleId?: string;+ accessBundleName?: string;variableId: string;key: string;// Present only when the update changed the key.@@ -6545,8 +6546,8 @@ interface AgentVaultVariableUpdateEvent {interface AgentVaultVariableDeleteEvent {type: EventType.AGENT_VAULT_VARIABLE_DELETE;metadata: {- accessBundleId: string;- accessBundleName: string;+ accessBundleId?: string;+ accessBundleName?: string;variableId: string;key: string;};@@ -6555,8 +6556,8 @@ interface AgentVaultVariableDeleteEvent {interface AgentVaultVariableValueViewEvent {type: EventType.AGENT_VAULT_VARIABLE_VALUE_VIEW;metadata: {- accessBundleId: string;- accessBundleName: string;+ accessBundleId?: string;+ accessBundleName?: string;variableId: string;key: string;};diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.tsindex fea95718eb..7f7d6c0031 100644--- a/backend/src/keystore/keystore.ts+++ b/backend/src/keystore/keystore.ts@@ -31,6 +31,7 @@ export const PgSqlLock = {CreateIdentity: (orgId: string) => pgAdvisoryLockHashText(`create-identity:${orgId}`),CreateGateway: (orgId: string) => pgAdvisoryLockHashText(`create-gateway:${orgId}`),CreateAgentVaultProxy: (projectId: string) => pgAdvisoryLockHashText(`create-agent-vault-proxy:${projectId}`),+ CreateAgentVaultVariable: (projectId: string) => pgAdvisoryLockHashText(`create-agent-vault-variable:${projectId}`),AccessSharedSecret: (sharedSecretId: string) => pgAdvisoryLockHashText(`access-shared-secret:${sharedSecretId}`),KmsOrgKeyCreation: (orgId: string) => pgAdvisoryLockHashText(`kms-org-key:${orgId}`),KmsOrgDataKeyCreation: (orgId: string) => pgAdvisoryLockHashText(`kms-org-data-key:${orgId}`),diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex bcdb98917f..c7ff5ea825 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -104,6 +104,7 @@ export enum ApiDocsTags {PamDiscovery = "PAM Discovery",AgentVault = "Agent Vault",AgentVaultAccessBundles = "Agent Vault Access Bundles",+ AgentVaultVariables = "Agent Vault Variables",AgentVaultSessions = "Agent Vault Sessions",AgentVaultProxies = "Agent Vault Proxies",AgentVaultMembers = "Agent Vault Members",@@ -4391,7 +4392,7 @@ export const ENCRYPTION_KEY_ROTATION = {}};-const AGENT_VAULT_VARIABLE_REFERENCES = `Can use up to ${AGENT_VAULT_MAX_REFERENCES_PER_FIELD} references to the access bundle's variables, written as \`{{KEY}}\`. A reference that repeats counts each time.`;+const AGENT_VAULT_VARIABLE_REFERENCES = `Can use up to ${AGENT_VAULT_MAX_REFERENCES_PER_FIELD} references to Agent Vault's variables, written as \`{{KEY}}\`. A reference that repeats counts each time.`;export const AGENT_VAULT = {ACCESS_BUNDLE: {@@ -4459,9 +4460,14 @@ export const AGENT_VAULT = {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.",revealedValue: "The variable's value.",- serviceIds:- "The IDs of the services in the access bundle that use this variable. A variable in use can't be deleted.",- createdAt: "When the variable was added to the access bundle.",+ usedBy:+ "The services that use this variable, across every access bundle, ordered by access bundle name and then service name. A variable in use can't be deleted.",+ usedById: "The ID of a service that uses this variable.",+ usedByName: "The name of the service.",+ usedByHostPattern: "The host pattern of the service.",+ usedByAccessBundleId: "The ID of the access bundle the service belongs to.",+ usedByAccessBundleName: "The name of the access bundle the service belongs to.",+ createdAt: "When the variable was added.",updatedAt: "When the variable was last changed."},MEMBER: {diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 6cd06bb06e..1cb4e1f926 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -30,7 +30,6 @@ import { agentVaultServiceCustomHeaderDALFactory } from "@app/ee/services/agent-import { agentVaultServiceDALFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-service-dal";import { agentVaultServiceSubstitutionDALFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-service-substitution-dal";import { agentVaultServiceVariableReferenceDALFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-service-variable-reference-dal";-import { agentVaultVariableDALFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-variable-dal";import { agentVaultMemberDALFactory } from "@app/ee/services/agent-vault-member/agent-vault-member-dal";import { agentVaultMembershipServiceFactory } from "@app/ee/services/agent-vault-member/agent-vault-membership-service";import { agentVaultProjectResolverFactory } from "@app/ee/services/agent-vault-project/agent-vault-project-resolver";@@ -42,6 +41,8 @@ import { agentVaultSessionDALFactory } from "@app/ee/services/agent-vault-sessioimport { agentVaultSessionServiceFactory } from "@app/ee/services/agent-vault-session/agent-vault-session-service";import { agentVaultSessionLogConfigDALFactory } from "@app/ee/services/agent-vault-session-log/agent-vault-session-log-config-dal";import { agentVaultSessionLogServiceFactory } from "@app/ee/services/agent-vault-session-log/agent-vault-session-log-service";+import { agentVaultVariableDALFactory } from "@app/ee/services/agent-vault-variable/agent-vault-variable-dal";+import { agentVaultVariableServiceFactory } from "@app/ee/services/agent-vault-variable/agent-vault-variable-service";import { assumePrivilegeServiceFactory } from "@app/ee/services/assume-privilege/assume-privilege-service";import { clickhouseAuditLogDALFactory } from "@app/ee/services/audit-log/audit-log-clickhouse-dal";import { auditLogDALFactory } from "@app/ee/services/audit-log/audit-log-dal";@@ -1989,6 +1990,12 @@ export const registerRoutes = async (const agentVaultResolveDAL = agentVaultResolveDALFactory(db);const agentVaultSessionLogConfigDAL = agentVaultSessionLogConfigDALFactory(db);+ const agentVaultVariableService = agentVaultVariableServiceFactory({+ agentVaultVariableDAL,+ permissionService,+ kmsService+ });+const agentVaultAccessBundleService = agentVaultAccessBundleServiceFactory({agentVaultAccessBundleDAL,agentVaultServiceDAL,@@ -4668,6 +4675,7 @@ export const registerRoutes = async (pamProjectResolver,agentVaultProjectResolver,agentVaultAccessBundle: agentVaultAccessBundleService,+ agentVaultVariable: agentVaultVariableService,agentVaultProxy: agentVaultProxyService,agentVaultSession: agentVaultSessionService,agentVaultSessionLog: agentVaultSessionLogService,diff --git a/backend/src/services/telemetry/telemetry-types.ts b/backend/src/services/telemetry/telemetry-types.tsindex 1277e34dc1..8cf3c68a0e 100644--- a/backend/src/services/telemetry/telemetry-types.ts+++ b/backend/src/services/telemetry/telemetry-types.ts@@ -2480,13 +2480,12 @@ export type TAgentVaultServiceDeletedEvent = {export type TAgentVaultVariableCreatedEvent = {event: PostHogEventTypes.AgentVaultVariableCreated;- properties: TAgentVaultEventBase & { accessBundleId: string; variableId: string };+ properties: TAgentVaultEventBase & { variableId: string };};export type TAgentVaultVariableUpdatedEvent = {event: PostHogEventTypes.AgentVaultVariableUpdated;properties: TAgentVaultEventBase & {- accessBundleId: string;variableId: string;keyChanged: boolean;valueReplaced: boolean;@@ -2496,7 +2495,7 @@ export type TAgentVaultVariableUpdatedEvent = {export type TAgentVaultVariableDeletedEvent = {event: PostHogEventTypes.AgentVaultVariableDeleted;- properties: TAgentVaultEventBase & { accessBundleId: string; variableId: string };+ properties: TAgentVaultEventBase & { variableId: string };};export type TAgentVaultAccessBundleMemberAddedEvent = {diff --git a/docs/images/platform/agent-vault/access-bundle-variables-empty.png b/docs/images/platform/agent-vault/access-bundle-variables-empty.pngdeleted file mode 100644index 97ba83d14e..0000000000Binary files a/docs/images/platform/agent-vault/access-bundle-variables-empty.png and /dev/null differdiff --git a/docs/images/platform/agent-vault/access-bundle-variables.png b/docs/images/platform/agent-vault/access-bundle-variables.pngdeleted file mode 100644index d8480dc035..0000000000Binary files a/docs/images/platform/agent-vault/access-bundle-variables.png and /dev/null differdiff --git a/frontend/src/components/agent-vault/VariableFormDialog.tsx b/frontend/src/components/agent-vault/VariableFormDialog.tsxindex 6bcc70c4c1..cc8cc81566 100644--- a/frontend/src/components/agent-vault/VariableFormDialog.tsx+++ b/frontend/src/components/agent-vault/VariableFormDialog.tsx@@ -51,7 +51,7 @@ const buildSchema = (takenKeys: string[], isValueRequired: boolean) =>.regex(VARIABLE_KEY_RE, VARIABLE_KEY_MESSAGE).refine((key) => !takenKeys.includes(key),- "This bundle already has a variable with this key."+ (key) => ({ message: `A variable named '${key}' already exists.` })),value: z.string()@@ -72,11 +72,8 @@ type FormData = z.infer<ReturnType<typeof buildSchema>>;type Props = {isOpen: boolean;onOpenChange: (isOpen: boolean) => void;- accessBundleId: string;variable?: TAgentVaultVariable | null;existingKeys: string[];- /** How many services use the variable being edited, so a rename can say they keep working. */- usedByCount?: number;/** A key to start a new variable from, as when it was named in a service before it existed. */initialKey?: string;onCreated?: (variable: TAgentVaultVariable) => void;@@ -86,10 +83,8 @@ type Props = {export const VariableFormDialog = ({isOpen,onOpenChange,- accessBundleId,variable,existingKeys,- usedByCount = 0,initialKey,onCreated,onCloseAutoFocus@@ -97,6 +92,7 @@ export const VariableFormDialog = ({const createVariable = useCreateAgentVaultVariable();const updateVariable = useUpdateAgentVaultVariable();const isUpdate = Boolean(variable);+ const usedByCount = variable?.usedBy.length ?? 0;const [isValueVisible, setIsValueVisible] = useState(false);const schema = useMemo(@@ -132,7 +128,6 @@ export const VariableFormDialog = ({try {if (variable) {await updateVariable.mutateAsync({- accessBundleId,variableId: variable.id,key: data.key === variable.key ? undefined : data.key,value: data.value.length > 0 ? data.value : undefined@@ -140,7 +135,6 @@ export const VariableFormDialog = ({createNotification({ text: `Variable "${data.key}" updated`, type: "success" });} else {const created = await createVariable.mutateAsync({- accessBundleId,key: data.key,value: data.value});@@ -167,7 +161,7 @@ export const VariableFormDialog = ({<DialogHeader><DialogTitle>{isUpdate ? "Edit Variable" : "Add Variable"}</DialogTitle><DialogDescription>- Store a value once and use it from any service in this bundle.+ Store a value once and use it from any service in any access bundle.</DialogDescription></DialogHeader>diff --git a/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx b/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsxindex 5e98236b9e..af08da9397 100644--- a/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx+++ b/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx@@ -156,7 +156,7 @@ export const ServiceSheet = ({const createService = useCreateAgentVaultService();const updateService = useUpdateAgentVaultService();- const { data: variables } = useListAgentVaultVariables(accessBundleId, isOpen);+ const { data: variables } = useListAgentVaultVariables(isOpen);const variableKeys = useMemo(() => variables?.map((variable) => variable.key), [variables]);const storedKeys = useMemo(() => storedVariableKeys(service), [service]);// One dialog for every field. The request settles once the dialog has closed, not when the variable is@@ -651,7 +651,6 @@ export const ServiceSheet = ({onOpenChange={(open) => {if (!open) setNewVariableKey(null);}}- accessBundleId={accessBundleId}initialKey={newVariableKey ?? undefined}existingKeys={variableKeys ?? []}onCreated={(variable) => {diff --git a/frontend/src/components/agent-vault/service-sheet/VariableSuggestions.tsx b/frontend/src/components/agent-vault/service-sheet/VariableSuggestions.tsxindex 8bc4ed2225..ec0b7cddac 100644--- a/frontend/src/components/agent-vault/service-sheet/VariableSuggestions.tsx+++ b/frontend/src/components/agent-vault/service-sheet/VariableSuggestions.tsx@@ -247,8 +247,8 @@ export const VariableSuggestions = ({) : (<p className="px-2 py-1.5 text-xs text-muted">{variables?.length- ? "No variable in this bundle matches that name."- : "This bundle has no variables yet. Add one under Variables."}+ ? "No variable matches that name."+ : "No variables yet. Add one under Variables."}</p>)}</PopoverContent>diff --git a/frontend/src/components/agent-vault/service-sheet/stepMeta.ts b/frontend/src/components/agent-vault/service-sheet/stepMeta.tsindex 86b2644984..948a31dfa5 100644--- a/frontend/src/components/agent-vault/service-sheet/stepMeta.ts+++ b/frontend/src/components/agent-vault/service-sheet/stepMeta.ts@@ -40,7 +40,7 @@ export const SERVICE_STEPS: StepMeta[] = [rightDescription:"Agents reach this service without ever holding the credential themselves. Custom headers go out on top of it, and a substitution swaps a placeholder your agent already sends for the real value.",rightTip:- "To use one of this bundle's variables, type {{ in any value and pick it from the list. The proxy puts the variable's value in its place."+ "To use a variable, type {{ in any value and pick it from the list. The proxy puts the variable's value in its place."},{step: ServiceStep.Review,diff --git a/frontend/src/helpers/agentVaultVariables.test.ts b/frontend/src/helpers/agentVaultVariables.test.tsindex d0343471c7..c4f47384eb 100644--- a/frontend/src/helpers/agentVaultVariables.test.ts+++ b/frontend/src/helpers/agentVaultVariables.test.ts@@ -49,7 +49,13 @@ describe("variableReferenceError", () => {});- it("passes a well-formed reference to a key the bundle has", () => {+ it("passes a well-formed reference to a key Agent Vault has", () => {expect(variableReferenceError("Bearer {{GITHUB_TOKEN}}", new Set(["GITHUB_TOKEN"]))).toBeNull();});++ it("names a key Agent Vault does not have, in the API's words", () => {+ expect(variableReferenceError("Bearer {{GITHUB_TOKEN}}", new Set(["OTHER"]))).toBe(+ "Agent Vault has no variable named 'GITHUB_TOKEN'. Add it under Variables, or correct the name."+ );+ });});diff --git a/frontend/src/helpers/agentVaultVariables.ts b/frontend/src/helpers/agentVaultVariables.tsindex 39e6d98f04..a004796c08 100644--- a/frontend/src/helpers/agentVaultVariables.ts+++ b/frontend/src/helpers/agentVaultVariables.ts@@ -1,6 +1,7 @@export const VARIABLE_KEY_MAX_LENGTH = 64;export const VARIABLE_VALUE_MAX_LENGTH = 8192;export const MAX_REFERENCES_PER_FIELD = 3;+export const MAX_VARIABLES = 500;export const VARIABLE_KEY_RE = /^[A-Z][A-Z0-9_]*$/;@@ -86,7 +87,9 @@ export const variableReferenceError = (text: string, keys?: ReadonlySet<string>)}const missing = keys ? refs.find((ref) => !keys.has(ref)) : undefined;- if (missing) return `This bundle has no variable named ${missing}. Add it under Variables first.`;+ if (missing) {+ return `Agent Vault has no variable named '${missing}'. Add it under Variables, or correct the name.`;+ }return null;};diff --git a/frontend/src/helpers/organizationSwitch.ts b/frontend/src/helpers/organizationSwitch.tsindex b989afc86c..be025d60c6 100644--- a/frontend/src/helpers/organizationSwitch.ts+++ b/frontend/src/helpers/organizationSwitch.ts@@ -27,6 +27,7 @@ const organizationSwitchSections = ["pam/access-management","agent-vault/sessions","agent-vault/access-bundles",+ "agent-vault/variables","agent-vault/proxies","agent-vault/settings","agent-vault/audit-logs",diff --git a/frontend/src/hooks/api/agentVault/mutations.tsx b/frontend/src/hooks/api/agentVault/mutations.tsxindex 5f3c6062ee..3814a0f389 100644--- a/frontend/src/hooks/api/agentVault/mutations.tsx+++ b/frontend/src/hooks/api/agentVault/mutations.tsx@@ -20,7 +20,6 @@ import {TAgentVaultService,TAgentVaultSessionLogSettings,TAgentVaultVariable,- TAgentVaultVariableRef,TAgentVaultWrittenMember,TCreateAgentVaultAccessBundleDTO,TCreateAgentVaultServiceDTO,@@ -66,6 +65,8 @@ export const useUpdateAgentVaultAccessBundle = () => {queryClient.invalidateQueries({queryKey: agentVaultKeys.accessBundle(currentOrg.id, accessBundleId)});+ // A variable's usedBy names each service's bundle.+ queryClient.invalidateQueries({ queryKey: agentVaultKeys.variables(currentOrg.id) });}});};@@ -83,6 +84,7 @@ export const useDeleteAgentVaultAccessBundle = () => {onSuccess: () => {queryClient.invalidateQueries({ queryKey: agentVaultKeys.accessBundles(currentOrg.id) });queryClient.invalidateQueries({ queryKey: agentVaultKeys.sessions(currentOrg.id) });+ queryClient.invalidateQueries({ queryKey: agentVaultKeys.variables(currentOrg.id) });}});};@@ -106,6 +108,7 @@ export const useCreateAgentVaultService = () => {queryKey: agentVaultKeys.accessBundle(currentOrg.id, accessBundleId)});queryClient.invalidateQueries({ queryKey: agentVaultKeys.accessBundles(currentOrg.id) });+ queryClient.invalidateQueries({ queryKey: agentVaultKeys.variables(currentOrg.id) });}});};@@ -129,6 +132,7 @@ export const useUpdateAgentVaultService = () => {queryKey: agentVaultKeys.accessBundle(currentOrg.id, accessBundleId)});queryClient.invalidateQueries({ queryKey: agentVaultKeys.accessBundles(currentOrg.id) });+ queryClient.invalidateQueries({ queryKey: agentVaultKeys.variables(currentOrg.id) });}});};@@ -154,6 +158,7 @@ export const useDeleteAgentVaultService = () => {queryKey: agentVaultKeys.accessBundle(currentOrg.id, accessBundleId)});queryClient.invalidateQueries({ queryKey: agentVaultKeys.accessBundles(currentOrg.id) });+ queryClient.invalidateQueries({ queryKey: agentVaultKeys.variables(currentOrg.id) });}});};@@ -388,32 +393,31 @@ export const useUpdateAgentVaultSessionLogSettings = () => {});};-// The bundle key covers its variables too, and a rename changes the keys each service reports.-const invalidateVariables = (- queryClient: ReturnType<typeof useQueryClient>,- orgId: string,- accessBundleId: string-) =>- queryClient.invalidateQueries({ queryKey: agentVaultKeys.accessBundle(orgId, accessBundleId) });+// A rename changes the keys each service's variableReferences reports, so the bundles refresh too.+const invalidateVariables = (queryClient: ReturnType<typeof useQueryClient>, orgId: string) =>+ Promise.all([+ queryClient.invalidateQueries({ queryKey: agentVaultKeys.variables(orgId) }),+ queryClient.invalidateQueries({ queryKey: agentVaultKeys.accessBundles(orgId) })+ ]);export const useCreateAgentVaultVariable = () => {const { currentOrg } = useOrganization();const queryClient = useQueryClient();return useMutation({- mutationFn: async ({ accessBundleId, ...params }: TCreateAgentVaultVariableDTO) => {+ mutationFn: async (params: TCreateAgentVaultVariableDTO) => {const { data } = await apiRequest.post<{ variable: TAgentVaultVariable }>(- `/api/v1/agent-vault/access-bundles/${accessBundleId}/variables`,+ "/api/v1/agent-vault/variables",params);return data.variable;},- onSuccess: (variable, { accessBundleId }) => {+ onSuccess: (variable) => {// Listed before the refetch lands, so a reference to it that was just inserted reads as known.queryClient.setQueryData<TAgentVaultVariable[]>(- agentVaultKeys.accessBundleVariables(currentOrg.id, accessBundleId),+ agentVaultKeys.variables(currentOrg.id),(prev) => (prev ? [...prev, variable].sort((a, b) => a.key.localeCompare(b.key)) : prev));- return invalidateVariables(queryClient, currentOrg.id, accessBundleId);+ return invalidateVariables(queryClient, currentOrg.id);}});};@@ -422,15 +426,14 @@ export const useUpdateAgentVaultVariable = () => {const { currentOrg } = useOrganization();const queryClient = useQueryClient();return useMutation({- mutationFn: async ({ accessBundleId, variableId, ...params }: TUpdateAgentVaultVariableDTO) => {+ mutationFn: async ({ variableId, ...params }: TUpdateAgentVaultVariableDTO) => {const { data } = await apiRequest.patch<{ variable: TAgentVaultVariable }>(- `/api/v1/agent-vault/access-bundles/${accessBundleId}/variables/${variableId}`,+ `/api/v1/agent-vault/variables/${variableId}`,params);return data.variable;},- onSuccess: (_, { accessBundleId }) =>- invalidateVariables(queryClient, currentOrg.id, accessBundleId)+ onSuccess: () => invalidateVariables(queryClient, currentOrg.id)});};@@ -438,23 +441,22 @@ export const useDeleteAgentVaultVariable = () => {const { currentOrg } = useOrganization();const queryClient = useQueryClient();return useMutation({- mutationFn: async ({ accessBundleId, variableId }: TAgentVaultVariableRef) => {+ mutationFn: async (variableId: string) => {const { data } = await apiRequest.delete<{ variable: TAgentVaultVariable }>(- `/api/v1/agent-vault/access-bundles/${accessBundleId}/variables/${variableId}`+ `/api/v1/agent-vault/variables/${variableId}`);return data.variable;},- onSuccess: (_, { accessBundleId }) =>- invalidateVariables(queryClient, currentOrg.id, accessBundleId)+ onSuccess: () => invalidateVariables(queryClient, currentOrg.id)});};// A mutation rather than a query, so a revealed value never enters the query cache.export const useRevealAgentVaultVariableValue = () =>useMutation({- mutationFn: async ({ accessBundleId, variableId }: TAgentVaultVariableRef) => {+ mutationFn: async (variableId: string) => {const { data } = await apiRequest.get<{ value: string }>(- `/api/v1/agent-vault/access-bundles/${accessBundleId}/variables/${variableId}/value`+ `/api/v1/agent-vault/variables/${variableId}/value`);return data.value;}diff --git a/frontend/src/hooks/api/agentVault/queries.tsx b/frontend/src/hooks/api/agentVault/queries.tsxindex 8a02265057..1339b2db77 100644--- a/frontend/src/hooks/api/agentVault/queries.tsx+++ b/frontend/src/hooks/api/agentVault/queries.tsx@@ -88,8 +88,7 @@ export const agentVaultKeys = {accessBundleId: string,params?: Omit<TListAgentVaultMembersDTO, "actorType">) => [...agentVaultKeys.accessBundleMembers(orgId, accessBundleId), "available", params] as const,- accessBundleVariables: (orgId: string, accessBundleId: string) =>- [...agentVaultKeys.accessBundle(orgId, accessBundleId), "variables"] as const,+ variables: (orgId: string) => [...agentVaultKeys.all(orgId), "variables"] as const,members: (orgId: string) => [...agentVaultKeys.all(orgId), "members"] as const,memberList: (orgId: string, params?: TListAgentVaultMembersDTO) =>[...agentVaultKeys.members(orgId), params] as const,@@ -528,17 +527,17 @@ export const useGetAgentVaultSessionLogs = (};};-export const useListAgentVaultVariables = (accessBundleId: string, enabled = true) => {+export const useListAgentVaultVariables = (enabled = true) => {const { currentOrg } = useOrganization();return useQuery({- queryKey: agentVaultKeys.accessBundleVariables(currentOrg.id, accessBundleId),+ queryKey: agentVaultKeys.variables(currentOrg.id),queryFn: async () => {const { data } = await apiRequest.get<{ variables: TAgentVaultVariable[] }>(- `/api/v1/agent-vault/access-bundles/${accessBundleId}/variables`+ "/api/v1/agent-vault/variables");return data.variables;},- enabled: enabled && Boolean(accessBundleId)+ enabled});};diff --git a/frontend/src/hooks/api/agentVault/types.ts b/frontend/src/hooks/api/agentVault/types.tsindex 7f1fc2a772..a789c26c9e 100644--- a/frontend/src/hooks/api/agentVault/types.ts+++ b/frontend/src/hooks/api/agentVault/types.ts@@ -396,27 +396,30 @@ export type TAgentVaultDecryptedSessionLogPage<decrypted: Record<string, TAgentVaultDecryptedChunk>;};-export type TAgentVaultVariable = {+export type TAgentVaultVariableUsage = {id: string;+ name: string;+ hostPattern: string;accessBundleId: string;+ accessBundleName: string;+};++export type TAgentVaultVariable = {+ id: string;key: string;- serviceIds: string[];+ // Every service that references the variable, across all access bundles.+ usedBy: TAgentVaultVariableUsage[];createdAt: string;updatedAt: string;};-export type TAgentVaultVariableRef = {- accessBundleId: string;- variableId: string;-};-export type TCreateAgentVaultVariableDTO = {- accessBundleId: string;key: string;value: string;};-export type TUpdateAgentVaultVariableDTO = TAgentVaultVariableRef & {+export type TUpdateAgentVaultVariableDTO = {+ variableId: string;key?: string;value?: string;};diff --git a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/AgentVaultNav.tsx b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/AgentVaultNav.tsxindex 1b23039e78..ed64de560d 100644--- a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/AgentVaultNav.tsx+++ b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/AgentVaultNav.tsx@@ -1,4 +1,4 @@-import { FileText, IdCard, Info, Package, Server, Settings, Shield } from "lucide-react";+import { Braces, FileText, IdCard, Info, Package, Server, Settings, Shield } from "lucide-react";import { useAgentVaultIntro } from "@app/components/agent-vault/AgentVaultIntro";import {@@ -31,7 +31,8 @@ export const AgentVaultNav = ({ onSubmenuOpen }: { onSubmenuOpen: (submenu: Submconst accessItems: NavItem[] = [{ label: "Sessions", icon: IdCard, pathSuffix: "sessions" },- { label: "Access Bundles", icon: Package, pathSuffix: "access-bundles" }+ { label: "Access Bundles", icon: Package, pathSuffix: "access-bundles" },+ { label: "Variables", icon: Braces, pathSuffix: "variables", hidden: !isAdmin }];const infrastructureItems: NavItem[] = [diff --git a/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/AgentVaultAccessBundleDetailPage.tsx b/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/AgentVaultAccessBundleDetailPage.tsxindex f247d48453..9fe5248afe 100644--- a/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/AgentVaultAccessBundleDetailPage.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/AgentVaultAccessBundleDetailPage.tsx@@ -35,7 +35,6 @@ import { ProjectMembershipRole } from "@app/hooks/api/roles/types";import { DeleteAccessBundleDialog } from "@app/pages/agent-vault/AgentVaultAccessBundlesPage/components/DeleteAccessBundleDialog";import { ServicesCard } from "./components/ServicesCard";-import { VariablesCard } from "./components/VariablesCard";export const AgentVaultAccessBundleDetailPage = () => {const { t } = useTranslation();@@ -126,26 +125,19 @@ export const AgentVaultAccessBundleDetailPage = () => {)}</PageHeader>- <div className="flex flex-col gap-8">- <ServicesCard- accessBundleId={accessBundle.id}- services={accessBundle.services}- canManage={isAdmin}- onAdd={() => {- setServiceToEdit(null);- setIsServiceSheetOpen(true);- }}- onEdit={(service) => {- setServiceToEdit(service);- setIsServiceSheetOpen(true);- }}- />-- {/* The variables routes are admin only. */}- {isAdmin && (- <VariablesCard accessBundleId={accessBundle.id} services={accessBundle.services} />- )}- </div>+ <ServicesCard+ accessBundleId={accessBundle.id}+ services={accessBundle.services}+ canManage={isAdmin}+ onAdd={() => {+ setServiceToEdit(null);+ setIsServiceSheetOpen(true);+ }}+ onEdit={(service) => {+ setServiceToEdit(service);+ setIsServiceSheetOpen(true);+ }}+ /><ManageAccessSheetaccessBundle={isManageAccessOpen ? accessBundle : null}diff --git a/frontend/src/pages/agent-vault/AgentVaultVariablesPage/AgentVaultVariablesPage.tsx b/frontend/src/pages/agent-vault/AgentVaultVariablesPage/AgentVaultVariablesPage.tsxnew file mode 100644index 0000000000..7c37d60503--- /dev/null+++ b/frontend/src/pages/agent-vault/AgentVaultVariablesPage/AgentVaultVariablesPage.tsx@@ -0,0 +1,33 @@+import { Helmet } from "react-helmet";+import { useTranslation } from "react-i18next";+import { BracesIcon } from "lucide-react";++import { AccessRestrictedDialog, PageHeader } from "@app/components/v3";+import { useProjectPermission } from "@app/context";+import { ProjectType } from "@app/hooks/api/projects/types";+import { ProjectMembershipRole } from "@app/hooks/api/roles/types";++import { VariablesCard } from "./components/VariablesCard";++export const AgentVaultVariablesPage = () => {+ const { t } = useTranslation();+ const { hasProjectRole } = useProjectPermission();+ const isAdmin = hasProjectRole(ProjectMembershipRole.Admin);++ return (+ <div className="mx-auto mb-6 flex w-full max-w-8xl flex-col">+ <Helmet>+ <title>{t("common.head-title", { title: "Variables" })}</title>+ </Helmet>++ <PageHeader+ scope={ProjectType.AgentVault}+ icon={BracesIcon}+ title="Variables"+ description="Store values once and reference them from services in any access bundle."+ />+ {/* The variables routes are admin only. */}+ {isAdmin ? <VariablesCard /> : <AccessRestrictedDialog />}+ </div>+ );+};diff --git a/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/DeleteVariableDialog.tsx b/frontend/src/pages/agent-vault/AgentVaultVariablesPage/components/DeleteVariableDialog.tsxsimilarity index 72%rename from frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/DeleteVariableDialog.tsxrename to frontend/src/pages/agent-vault/AgentVaultVariablesPage/components/DeleteVariableDialog.tsxindex e4913165a8..74fdc8015c 100644--- a/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/DeleteVariableDialog.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultVariablesPage/components/DeleteVariableDialog.tsx@@ -1,3 +1,5 @@+import { Link } from "@tanstack/react-router";+import { ServiceIcon } from "@app/components/agent-vault/ServiceIconStack";import { createNotification } from "@app/components/notifications";import {@@ -10,26 +12,25 @@ import {AlertDialogTitle,Button} from "@app/components/v3";+import { useOrganization } from "@app/context";import { useDeleteAgentVaultVariable } from "@app/hooks/api/agentVault";-import { TAgentVaultService, TAgentVaultVariable } from "@app/hooks/api/agentVault/types";+import { TAgentVaultVariable } from "@app/hooks/api/agentVault/types";type Props = {variable: TAgentVaultVariable | null;- usedBy: TAgentVaultService[];onOpenChange: (isOpen: boolean) => void;};-export const DeleteVariableDialog = ({ variable, usedBy, onOpenChange }: Props) => {+export const DeleteVariableDialog = ({ variable, onOpenChange }: Props) => {+ const { currentOrg } = useOrganization();const deleteVariable = useDeleteAgentVaultVariable();+ const usedBy = variable?.usedBy ?? [];const isInUse = usedBy.length > 0;const handleDelete = async () => {if (!variable) return;try {- await deleteVariable.mutateAsync({- accessBundleId: variable.accessBundleId,- variableId: variable.id- });+ await deleteVariable.mutateAsync(variable.id);createNotification({ text: `Variable "${variable.key}" deleted`, type: "success" });onOpenChange(false);} catch {@@ -52,9 +53,18 @@ export const DeleteVariableDialog = ({ variable, usedBy, onOpenChange }: Props){isInUse && (<ul className="flex max-h-48 flex-col gap-2 overflow-y-auto rounded-md border border-border bg-container/50 p-3">{usedBy.map((service) => (- <li key={service.id} className="flex items-center gap-2 text-sm">+ <li key={service.id} className="flex items-center gap-2"><ServiceIcon hostPattern={service.hostPattern} />- {service.name}+ <div className="flex min-w-0 flex-col">+ <span className="truncate text-sm">{service.name}</span>+ <Link+ to="/organizations/$orgId/agent-vault/access-bundles/$accessBundleId"+ params={{ orgId: currentOrg.id, accessBundleId: service.accessBundleId }}+ className="truncate text-xs text-muted underline-offset-4 hover:text-foreground hover:underline"+ >+ {service.accessBundleName}+ </Link>+ </div></li>))}</ul>diff --git a/frontend/src/pages/agent-vault/AgentVaultVariablesPage/components/UsedByBundleBadges.tsx b/frontend/src/pages/agent-vault/AgentVaultVariablesPage/components/UsedByBundleBadges.tsxnew file mode 100644index 0000000000..29c07a8341--- /dev/null+++ b/frontend/src/pages/agent-vault/AgentVaultVariablesPage/components/UsedByBundleBadges.tsx@@ -0,0 +1,108 @@+import { Link } from "@tanstack/react-router";+import { PackageIcon } from "lucide-react";++import { ServiceIcon } from "@app/components/agent-vault/ServiceIconStack";+import {+ Badge,+ Popover,+ PopoverContent,+ PopoverTrigger,+ Tooltip,+ TooltipContent,+ TooltipTrigger+} from "@app/components/v3";+import { useOrganization } from "@app/context";+import { TAgentVaultVariable } from "@app/hooks/api/agentVault/types";++type TUsage = TAgentVaultVariable["usedBy"][number];++type TBundleUsage = {+ accessBundleId: string;+ accessBundleName: string;+ services: TUsage[];+};++const DEFAULT_MAX_VISIBLE = 2;++const groupByBundle = (usedBy: TUsage[]): TBundleUsage[] => {+ const byBundle = new Map<string, TBundleUsage>();+ usedBy.forEach((usage) => {+ const bundle = byBundle.get(usage.accessBundleId) ?? {+ accessBundleId: usage.accessBundleId,+ accessBundleName: usage.accessBundleName,+ services: []+ };+ bundle.services.push(usage);+ byBundle.set(usage.accessBundleId, bundle);+ });+ return [...byBundle.values()].sort((a, b) =>+ a.accessBundleName.localeCompare(b.accessBundleName)+ );+};++const BundleBadge = ({ bundle }: { bundle: TBundleUsage }) => {+ const { currentOrg } = useOrganization();++ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <Badge variant="neutral" isTruncatable className="max-w-[10rem]" asChild>+ <Link+ to="/organizations/$orgId/agent-vault/access-bundles/$accessBundleId"+ params={{ orgId: currentOrg.id, accessBundleId: bundle.accessBundleId }}+ >+ <PackageIcon />+ <span>{bundle.accessBundleName}</span>+ </Link>+ </Badge>+ </TooltipTrigger>+ <TooltipContent className="max-w-xs">+ <p className="mb-2 break-all text-muted">{bundle.accessBundleName}</p>+ <ul className="flex flex-col gap-1.5">+ {bundle.services.map((service) => (+ <li key={service.id} className="flex items-center gap-2">+ <ServiceIcon hostPattern={service.hostPattern} className="size-5" />+ <span className="truncate">{service.name}</span>+ </li>+ ))}+ </ul>+ </TooltipContent>+ </Tooltip>+ );+};++export const UsedByBundleBadges = ({+ usedBy,+ maxVisible = DEFAULT_MAX_VISIBLE+}: {+ usedBy: TUsage[];+ maxVisible?: number;+}) => {+ if (usedBy.length === 0) return <span className="text-sm text-muted">Unused</span>;++ const bundles = groupByBundle(usedBy);+ const visible = bundles.slice(0, maxVisible);+ const overflow = bundles.slice(maxVisible);++ return (+ <div className="flex min-w-0 items-center gap-1.5">+ {visible.map((bundle) => (+ <BundleBadge key={bundle.accessBundleId} bundle={bundle} />+ ))}+ {overflow.length > 0 && (+ <Popover>+ <PopoverTrigger asChild>+ <Badge variant="neutral" asChild>+ <button type="button">+{overflow.length} more</button>+ </Badge>+ </PopoverTrigger>+ <PopoverContent side="right" className="flex w-auto max-w-sm flex-wrap gap-1.5">+ {overflow.map((bundle) => (+ <BundleBadge key={bundle.accessBundleId} bundle={bundle} />+ ))}+ </PopoverContent>+ </Popover>+ )}+ </div>+ );+};diff --git a/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/VariablesCard.tsx b/frontend/src/pages/agent-vault/AgentVaultVariablesPage/components/VariablesCard.tsxsimilarity index 67%rename from frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/VariablesCard.tsxrename to frontend/src/pages/agent-vault/AgentVaultVariablesPage/components/VariablesCard.tsxindex bd6d6b93ea..e50f72ac11 100644--- a/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/VariablesCard.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultVariablesPage/components/VariablesCard.tsx@@ -1,4 +1,4 @@-import { useMemo, useRef, useState } from "react";+import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";import {ChevronDownIcon,CopyIcon,@@ -12,7 +12,6 @@ import {} from "lucide-react";import { twMerge } from "tailwind-merge";-import { ServiceIconStack } from "@app/components/agent-vault/ServiceIconStack";import { VariableFormDialog } from "@app/components/agent-vault/VariableFormDialog";import { createNotification } from "@app/components/notifications";import {@@ -47,15 +46,16 @@ import {TooltipContent,TooltipTrigger} from "@app/components/v3";-import { toVariableReference } from "@app/helpers/agentVaultVariables";+import { MAX_VARIABLES, toVariableReference } from "@app/helpers/agentVaultVariables";import {useListAgentVaultVariables,useRevealAgentVaultVariableValue} from "@app/hooks/api/agentVault";-import { TAgentVaultService, TAgentVaultVariable } from "@app/hooks/api/agentVault/types";+import { TAgentVaultVariable } from "@app/hooks/api/agentVault/types";import { AgentVaultDocsUrls } from "../../agent-vault-docs-urls";import { DeleteVariableDialog } from "./DeleteVariableDialog";+import { UsedByBundleBadges } from "./UsedByBundleBadges";enum SortColumn {Key = "key",@@ -67,6 +67,109 @@ const MASK = "•".repeat(8);// A revealed value is held against the version it was read from, so an edit hides it again.const revealSlot = (variable: TAgentVaultVariable) => `${variable.id}:${variable.updatedAt}`;+const FADE_MS = 200;++const fadeClassName =+ "col-start-1 row-start-1 font-mono text-sm transition-[opacity,filter] duration-200 ease-out motion-reduce:transition-none";++// The value mounts hidden and fades in two frames later, once the hidden state has painted. Hiding fades it out+// first and only then takes it out of the DOM, so it is never kept longer than the fade.+//+// The box eases between the mask's width and the value's so the button beside it slides rather than jumps. Its width+// is pinned only while that runs: from where it is now to the text's width, capped at what the row leaves it, since+// easing towards a long value's full width would reach the cap in a frame or two and jump anyway. Once the motion is+// done the width goes back to auto.+const RevealableValue = ({ value }: { value?: string }) => {+ const [rendered, setRendered] = useState(value);+ const [isShown, setIsShown] = useState(false);+ const wrapperRef = useRef<HTMLSpanElement>(null);+ const maskRef = useRef<HTMLSpanElement>(null);+ const valueRef = useRef<HTMLSpanElement>(null);+ const hasMounted = useRef(false);++ useEffect(() => {+ if (value !== undefined) {+ setRendered(value);+ let frame = requestAnimationFrame(() => {+ frame = requestAnimationFrame(() => setIsShown(true));+ });+ return () => cancelAnimationFrame(frame);+ }+ setIsShown(false);+ const timer = setTimeout(() => setRendered(undefined), FADE_MS);+ return () => clearTimeout(timer);+ }, [value]);++ useLayoutEffect(() => {+ const wrapper = wrapperRef.current;+ const row = wrapper?.parentElement;+ const text = isShown ? valueRef.current : maskRef.current;+ if (!hasMounted.current || !wrapper || !row || !text) {+ hasMounted.current = true;+ return undefined;+ }++ const siblings = [...row.children].filter((child) => child !== wrapper);+ const gap = parseFloat(getComputedStyle(row).columnGap) || 0;+ const available =+ row.clientWidth -+ siblings.reduce((total, child) => total + child.getBoundingClientRect().width + gap, 0);++ wrapper.style.width = `${wrapper.getBoundingClientRect().width}px`;+ // Commits the starting width, so the change below transitions from it.+ wrapper.getBoundingClientRect();+ wrapper.style.width = `${Math.min(text.scrollWidth, available)}px`;++ if (!isShown) return undefined;+ const timer = setTimeout(() => {+ wrapper.style.width = "";+ }, FADE_MS);+ return () => clearTimeout(timer);+ }, [isShown]);++ // The value enters the DOM before it is shown, and leaves after it is hidden. In both cases the box holds the mask's+ // width until the slide starts or after it ends, or auto would size it to the value for a frame.+ useLayoutEffect(() => {+ const wrapper = wrapperRef.current;+ if (!wrapper) return;+ if (rendered === undefined) {+ wrapper.style.width = "";+ } else if (!isShown && maskRef.current) {+ wrapper.style.width = `${maskRef.current.scrollWidth}px`;+ }+ // Only the value entering or leaving matters here; isShown is read, not watched.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [rendered]);++ return (+ <span+ ref={wrapperRef}+ className="grid min-w-0 grid-cols-[minmax(0,1fr)] items-center transition-[width] duration-200 ease-out motion-reduce:transition-none"+ >+ <span+ ref={maskRef}+ aria-hidden={isShown}+ className={twMerge(+ fadeClassName,+ "justify-self-start tracking-widest text-muted",+ isShown && "opacity-0 blur-[2px]"+ )}+ >+ {MASK}+ </span>+ {rendered !== undefined && (+ <span+ ref={valueRef}+ aria-hidden={!isShown}+ className={twMerge(fadeClassName, "truncate", !isShown && "opacity-0 blur-[2px]")}+ >+ {rendered}+ </span>+ )}+ </span>+ );+};+// Opens only when the column cuts the key off, measured as it opens.const TruncatedKey = ({ value }: { value: string }) => {const ref = useRef<HTMLSpanElement | null>(null);@@ -90,13 +193,8 @@ const TruncatedKey = ({ value }: { value: string }) => {);};-type Props = {- accessBundleId: string;- services: TAgentVaultService[];-};--export const VariablesCard = ({ accessBundleId, services }: Props) => {- const { data: variables = [], isPending } = useListAgentVaultVariables(accessBundleId);+export const VariablesCard = () => {+ const { data: variables = [], isPending } = useListAgentVaultVariables();const revealValue = useRevealAgentVaultVariableValue();const [search, setSearch] = useState("");@@ -108,24 +206,13 @@ export const VariablesCard = ({ accessBundleId, services }: Props) => {const [revealed, setRevealed] = useState<Record<string, string>>({});const [revealingId, setRevealingId] = useState<string | null>(null);- // Joined against the bundle's own service list, so a service deleted in the meantime drops out.- const servicesById = useMemo(- () => new Map(services.map((service) => [service.id, service])),- [services]- );- const usedByOf = (variable: TAgentVaultVariable | null) =>- (variable?.serviceIds ?? []).flatMap((serviceId) => {- const service = servicesById.get(serviceId);- return service ? [service] : [];- });-const displayed = useMemo(() => {const term = search.trim().toLowerCase();const filtered = variables.filter((variable) => variable.key.toLowerCase().includes(term));const compare = (a: TAgentVaultVariable, b: TAgentVaultVariable) =>sortColumn === SortColumn.UsedBy- ? a.serviceIds.length - b.serviceIds.length || a.key.localeCompare(b.key)+ ? a.usedBy.length - b.usedBy.length || a.key.localeCompare(b.key): a.key.localeCompare(b.key);const ordered = [...filtered].sort(compare);@@ -158,7 +245,7 @@ export const VariablesCard = ({ accessBundleId, services }: Props) => {setRevealingId(variable.id);try {- const value = await revealValue.mutateAsync({ accessBundleId, variableId: variable.id });+ const value = await revealValue.mutateAsync(variable.id);setRevealed((prev) => ({ ...prev, [slot]: value }));} catch {// A failed request returns a 4xx that the global request handler surfaces as a toast@@ -173,7 +260,7 @@ export const VariablesCard = ({ accessBundleId, services }: Props) => {const copyValue = async (variable: TAgentVaultVariable) => {let request: Promise<string> | undefined;try {- request = revealValue.mutateAsync({ accessBundleId, variableId: variable.id });+ request = revealValue.mutateAsync(variable.id);if (typeof ClipboardItem === "undefined") {await navigator.clipboard.writeText(await request);} else {@@ -194,6 +281,8 @@ export const VariablesCard = ({ accessBundleId, services }: Props) => {}};+ const isAtLimit = variables.length >= MAX_VARIABLES;+const openForm = (variable: TAgentVaultVariable | null) => {setVariableToEdit(variable);setIsFormOpen(true);@@ -207,14 +296,32 @@ export const VariablesCard = ({ accessBundleId, services }: Props) => {<DocumentationLinkBadge href={AgentVaultDocsUrls.variables} /></CardTitle><CardDescription>- A variable stores one value that any service in this bundle can use as{" "}+ A variable stores one value that any service can use as{" "}<code className="font-mono">{toVariableReference("KEY")}</code>.</CardDescription><CardAction>- <Button variant="av" onClick={() => openForm(null)}>- <PlusIcon />- Add Variable- </Button>+ {isAtLimit ? (+ <Tooltip>+ <TooltipTrigger asChild>+ {/* eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex */}+ <span tabIndex={0}>+ <Button variant="av" isDisabled>+ <PlusIcon />+ Add Variable+ </Button>+ </span>+ </TooltipTrigger>+ <TooltipContent className="max-w-xs">+ Agent Vault can hold at most {MAX_VARIABLES} variables. Delete one that no service+ uses first.+ </TooltipContent>+ </Tooltip>+ ) : (+ <Button variant="av" onClick={() => openForm(null)}>+ <PlusIcon />+ Add Variable+ </Button>+ )}</CardAction></CardHeader>@@ -242,7 +349,7 @@ export const VariablesCard = ({ accessBundleId, services }: Props) => {</EmptyTitle><EmptyDescription>{variables.length === 0- ? "Add a variable to use one value across this bundle's services."+ ? "Add a variable to use one value across services in any access bundle.": "Try a different search term."}</EmptyDescription></EmptyHeader>@@ -290,8 +397,6 @@ export const VariablesCard = ({ accessBundleId, services }: Props) => {displayed.map((variable) => {const revealedValue = revealed[revealSlot(variable)];const isRevealed = revealedValue !== undefined;- const usedBy = usedByOf(variable);-return (<TableRow key={variable.id}><TableCell>@@ -299,15 +404,7 @@ export const VariablesCard = ({ accessBundleId, services }: Props) => {</TableCell><TableCell><div className="flex items-center gap-1.5">- {isRevealed ? (- <span className="min-w-0 truncate font-mono text-sm">- {revealedValue}- </span>- ) : (- <span className="font-mono text-sm tracking-widest text-muted">- {MASK}- </span>- )}+ <RevealableValue value={revealedValue} /><IconButtonvariant="ghost"size="xs"@@ -321,10 +418,7 @@ export const VariablesCard = ({ accessBundleId, services }: Props) => {</div></TableCell><TableCell>- <ServiceIconStack- services={usedBy}- emptyPlaceholder={<span className="text-sm text-muted">Unused</span>}- />+ <UsedByBundleBadges usedBy={variable.usedBy} /></TableCell><TableCell variant="action"><DropdownMenu>@@ -362,15 +456,12 @@ export const VariablesCard = ({ accessBundleId, services }: Props) => {<VariableFormDialogisOpen={isFormOpen}onOpenChange={setIsFormOpen}- accessBundleId={accessBundleId}variable={variableToEdit}existingKeys={variables.map((variable) => variable.key)}- usedByCount={usedByOf(variableToEdit).length}/><DeleteVariableDialogvariable={variableToDelete}- usedBy={usedByOf(variableToDelete)}onOpenChange={(isOpen) => {if (!isOpen) setVariableToDelete(null);}}diff --git a/frontend/src/pages/agent-vault/AgentVaultVariablesPage/route.tsx b/frontend/src/pages/agent-vault/AgentVaultVariablesPage/route.tsxnew file mode 100644index 0000000000..12cf804887--- /dev/null+++ b/frontend/src/pages/agent-vault/AgentVaultVariablesPage/route.tsx@@ -0,0 +1,12 @@+import { createFileRoute } from "@tanstack/react-router";++import { AgentVaultVariablesPage } from "./AgentVaultVariablesPage";++export const Route = createFileRoute(+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/variables"+)({+ component: AgentVaultVariablesPage,+ beforeLoad: ({ context }) => {+ return { breadcrumbs: [...context.breadcrumbs, { label: "Variables" }] };+ }+});diff --git a/frontend/src/routeTree.gen.ts b/frontend/src/routeTree.gen.tsindex 05b47ef72d..fb6a01623d 100644--- a/frontend/src/routeTree.gen.ts+++ b/frontend/src/routeTree.gen.ts@@ -101,6 +101,7 @@ import { Route as pamPamDiscoveryPageRouteImport } from './pages/pam/PamDiscoverimport { Route as pamPamApprovalRequestsPageRouteImport } from './pages/pam/PamApprovalRequestsPage/route'import { Route as organizationNetworkingPageRelayDetailsByIDPageRouteImport } from './pages/organization/NetworkingPage/RelayDetailsByIDPage/route'import { Route as organizationNetworkingPageGatewayDetailsByIDPageRouteImport } from './pages/organization/NetworkingPage/GatewayDetailsByIDPage/route'+import { Route as agentVaultAgentVaultVariablesPageRouteImport } from './pages/agent-vault/AgentVaultVariablesPage/route'import { Route as agentVaultAgentVaultSettingsPageRouteImport } from './pages/agent-vault/AgentVaultSettingsPage/route'import { Route as agentVaultAgentVaultSessionsPageRouteImport } from './pages/agent-vault/AgentVaultSessionsPage/route'import { Route as agentVaultAgentVaultProxiesPageRouteImport } from './pages/agent-vault/AgentVaultProxiesPage/route'@@ -1217,6 +1218,13 @@ const organizationNetworkingPageGatewayDetailsByIDPageRouteRoute =AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdNetworkingRoute,} as any)+const agentVaultAgentVaultVariablesPageRouteRoute =+ agentVaultAgentVaultVariablesPageRouteImport.update({+ id: '/variables',+ path: '/variables',+ getParentRoute: () => agentVaultLayoutRoute,+ } as any)+const agentVaultAgentVaultSettingsPageRouteRoute =agentVaultAgentVaultSettingsPageRouteImport.update({id: '/settings',@@ -3298,6 +3306,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof agentVaultAgentVaultSettingsPageRouteImportparentRoute: typeof agentVaultLayoutImport}+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/variables': {+ id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/variables'+ path: '/variables'+ fullPath: '/organizations/$orgId/agent-vault/variables'+ preLoaderRoute: typeof agentVaultAgentVaultVariablesPageRouteImport+ parentRoute: typeof agentVaultLayoutImport+ }'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/networking/gateways/$gatewayId': {id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/networking/gateways/$gatewayId'path: '/gateways/$gatewayId'@@ -5616,6 +5631,7 @@ interface agentVaultLayoutRouteChildren {agentVaultAgentVaultProxiesPageRouteRoute: typeof agentVaultAgentVaultProxiesPageRouteRouteagentVaultAgentVaultSessionsPageRouteRoute: typeof agentVaultAgentVaultSessionsPageRouteRouteagentVaultAgentVaultSettingsPageRouteRoute: typeof agentVaultAgentVaultSettingsPageRouteRoute+ agentVaultAgentVaultVariablesPageRouteRoute: typeof agentVaultAgentVaultVariablesPageRouteRouteredirectsAgentVaultIndexRedirectRoute: typeof redirectsAgentVaultIndexRedirectRouteAuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAgentVaultAgentVaultLayoutAccessBundlesRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAgentVaultAgentVaultLayoutAccessBundlesRouteWithChildrenprojectAccessControlPageRouteAgentVaultRoute: typeof projectAccessControlPageRouteAgentVaultRoute@@ -5633,6 +5649,8 @@ const agentVaultLayoutRouteChildren: agentVaultLayoutRouteChildren = {agentVaultAgentVaultSessionsPageRouteRoute,agentVaultAgentVaultSettingsPageRouteRoute:agentVaultAgentVaultSettingsPageRouteRoute,+ agentVaultAgentVaultVariablesPageRouteRoute:+ agentVaultAgentVaultVariablesPageRouteRoute,redirectsAgentVaultIndexRedirectRoute: redirectsAgentVaultIndexRedirectRoute,AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAgentVaultAgentVaultLayoutAccessBundlesRoute:AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAgentVaultAgentVaultLayoutAccessBundlesRouteWithChildren,@@ -6186,6 +6204,7 @@ export interface FileRoutesByFullPath {'/organizations/$orgId/agent-vault/proxies': typeof agentVaultAgentVaultProxiesPageRouteRoute'/organizations/$orgId/agent-vault/sessions': typeof agentVaultAgentVaultSessionsPageRouteRoute'/organizations/$orgId/agent-vault/settings': typeof agentVaultAgentVaultSettingsPageRouteRoute+ '/organizations/$orgId/agent-vault/variables': typeof agentVaultAgentVaultVariablesPageRouteRoute'/organizations/$orgId/networking/gateways/$gatewayId': typeof organizationNetworkingPageGatewayDetailsByIDPageRouteRoute'/organizations/$orgId/networking/relays/$relayId': typeof organizationNetworkingPageRelayDetailsByIDPageRouteRoute'/organizations/$orgId/pam/approval-requests': typeof pamPamApprovalRequestsPageRouteRoute@@ -6469,6 +6488,7 @@ export interface FileRoutesByTo {'/organizations/$orgId/agent-vault/proxies': typeof agentVaultAgentVaultProxiesPageRouteRoute'/organizations/$orgId/agent-vault/sessions': typeof agentVaultAgentVaultSessionsPageRouteRoute'/organizations/$orgId/agent-vault/settings': typeof agentVaultAgentVaultSettingsPageRouteRoute+ '/organizations/$orgId/agent-vault/variables': typeof agentVaultAgentVaultVariablesPageRouteRoute'/organizations/$orgId/networking/gateways/$gatewayId': typeof organizationNetworkingPageGatewayDetailsByIDPageRouteRoute'/organizations/$orgId/networking/relays/$relayId': typeof organizationNetworkingPageRelayDetailsByIDPageRouteRoute'/organizations/$orgId/pam/approval-requests': typeof pamPamApprovalRequestsPageRouteRoute@@ -6747,6 +6767,7 @@ export interface FileRoutesById {'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/proxies': typeof agentVaultAgentVaultProxiesPageRouteRoute'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/sessions': typeof agentVaultAgentVaultSessionsPageRouteRoute'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/settings': typeof agentVaultAgentVaultSettingsPageRouteRoute+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/variables': typeof agentVaultAgentVaultVariablesPageRouteRoute'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/networking/gateways/$gatewayId': typeof organizationNetworkingPageGatewayDetailsByIDPageRouteRoute'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/networking/relays/$relayId': typeof organizationNetworkingPageRelayDetailsByIDPageRouteRoute'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/approval-requests': typeof pamPamApprovalRequestsPageRouteRoute@@ -7043,6 +7064,7 @@ export interface FileRouteTypes {| '/organizations/$orgId/agent-vault/proxies'| '/organizations/$orgId/agent-vault/sessions'| '/organizations/$orgId/agent-vault/settings'+ | '/organizations/$orgId/agent-vault/variables'| '/organizations/$orgId/networking/gateways/$gatewayId'| '/organizations/$orgId/networking/relays/$relayId'| '/organizations/$orgId/pam/approval-requests'@@ -7325,6 +7347,7 @@ export interface FileRouteTypes {| '/organizations/$orgId/agent-vault/proxies'| '/organizations/$orgId/agent-vault/sessions'| '/organizations/$orgId/agent-vault/settings'+ | '/organizations/$orgId/agent-vault/variables'| '/organizations/$orgId/networking/gateways/$gatewayId'| '/organizations/$orgId/networking/relays/$relayId'| '/organizations/$orgId/pam/approval-requests'@@ -7601,6 +7624,7 @@ export interface FileRouteTypes {| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/proxies'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/sessions'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/settings'+ | '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/variables'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/networking/gateways/$gatewayId'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/networking/relays/$relayId'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/approval-requests'@@ -8309,6 +8333,7 @@ export const routeTree = rootRoute"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/proxies","/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/sessions","/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/settings",+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/variables","/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/","/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/access-bundles","/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/access-management",@@ -8364,6 +8389,10 @@ export const routeTree = rootRoute"filePath": "agent-vault/AgentVaultSettingsPage/route.tsx","parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout"},+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/variables": {+ "filePath": "agent-vault/AgentVaultVariablesPage/route.tsx",+ "parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout"+ },"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/networking/gateways/$gatewayId": {"filePath": "organization/NetworkingPage/GatewayDetailsByIDPage/route.tsx","parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/networking"diff --git a/frontend/src/routes.ts b/frontend/src/routes.tsindex 94305355f8..9e51da213d 100644--- a/frontend/src/routes.ts+++ b/frontend/src/routes.ts@@ -385,6 +385,7 @@ const agentVaultRoutes = route("/organizations/$orgId/agent-vault", [index("agent-vault/AgentVaultAccessBundlesPage/route.tsx"),route("/$accessBundleId", "agent-vault/AgentVaultAccessBundleDetailPage/route.tsx")]),+ route("/variables", "agent-vault/AgentVaultVariablesPage/route.tsx"),route("/proxies", "agent-vault/AgentVaultProxiesPage/route.tsx"),route("/settings", "agent-vault/AgentVaultSettingsPage/route.tsx"),route("/audit-logs", "project/AuditLogsPage/route-agent-vault.tsx"),