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): add access bundle variables
Scott Wilson4a6b13a4a1be
diff --git a/backend/e2e-test/routes/v1/agent-vault.spec.ts b/backend/e2e-test/routes/v1/agent-vault.spec.tsindex 65a30caa73..b5b1888a0c 100644--- a/backend/e2e-test/routes/v1/agent-vault.spec.ts+++ b/backend/e2e-test/routes/v1/agent-vault.spec.ts@@ -1,10 +1,13 @@import crypto from "node:crypto";+import * as x509 from "@peculiar/x509";+import { AccessScope, ActionProjectType, OrgMembershipRole, ProjectMembershipRole, ProjectType } from "@app/db/schemas";import { seedData1 } from "@app/db/seed-data";import { agentVaultAccessBundleDALFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-dal";import { agentVaultServiceCustomHeaderDALFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-service-custom-header-dal";import { agentVaultServiceSubstitutionDALFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-service-substitution-dal";+import { 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 { agentVaultProxyServiceFactory } from "@app/ee/services/agent-vault-proxy/agent-vault-proxy-service";import { agentVaultResolveDALFactory } from "@app/ee/services/agent-vault-proxy/agent-vault-resolve-dal";@@ -14,6 +17,7 @@ import { agentVaultSessionServiceFactory } from "@app/ee/services/agent-vault-seimport { groupDALFactory } from "@app/ee/services/group/group-dal";import { permissionDALFactory } from "@app/ee/services/permission/permission-dal";import { permissionServiceFactory } from "@app/ee/services/permission/permission-service";+import { ResourceAuthMethodType } from "@app/ee/services/resource-auth-method/resource-auth-method-fns";import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";import { UnauthorizedError } from "@app/lib/errors";import { initLogger } from "@app/lib/logger";@@ -688,6 +692,380 @@ describe("Agent Vault V1 Router", async () => {});});+ describe("variables", async () => {+ const variablesUrl = (accessBundleId: string) => `/api/v1/agent-vault/access-bundles/${accessBundleId}/variables`;+ const servicesUrl = (accessBundleId: string) => `/api/v1/agent-vault/access-bundles/${accessBundleId}/services`;++ type TReference = {+ variableId: string;+ key: string;+ field: string;+ customHeaderId?: string;+ substitutionId?: string;+ isWholeValue: boolean;+ };++ const createVariable = async (accessBundleId: string, body: { key: string; value: string; isSecret?: boolean }) => {+ const res = await inject("POST", variablesUrl(accessBundleId), body);+ expect(res.statusCode).toBe(200);+ return (JSON.parse(res.payload) as { variable: { id: string; key: string } }).variable;+ };++ const referencesByField = (references: TReference[]) =>+ references.map((reference) => `${reference.field}:${reference.key}`).sort();++ // Enrollment only checks that it is a live CA. ECDSA P-256, because the FIPS image refuses Ed25519.+ const createProxyCaPem = async () => {+ const algorithm = { name: "ECDSA", namedCurve: "P-256", hash: "SHA-256" };+ const keys = await crypto.webcrypto.subtle.generateKey(algorithm, true, ["sign", "verify"]);+ const certificate = await x509.X509CertificateGenerator.createSelfSigned({+ name: "CN=Agent Vault Variables Test CA",+ serialNumber: "01",+ notBefore: new Date(Date.now() - 60_000),+ notAfter: new Date(Date.now() + 24 * 60 * 60 * 1000),+ signingAlgorithm: algorithm,+ keys,+ extensions: [+ new x509.BasicConstraintsExtension(true, undefined, true),+ // eslint-disable-next-line no-bitwise+ new x509.KeyUsagesExtension(x509.KeyUsageFlags.keyCertSign | x509.KeyUsageFlags.cRLSign, true)+ ]+ });+ return certificate.toString("pem");+ };++ type TResolved = {+ services: {+ credential: Record<string, string>;+ customHeaders: { name: string; prefix: string; value: string }[];+ substitutions: { placeholder: string; surfaces: string[]; value: string }[];+ }[];+ };++ // A real enrolled proxy on the real resolve route, unlike the stubbed resolvers elsewhere in this file,+ // so every value goes through the project's actual KMS key.+ const resolverFor = async (bundle: { name: string }, proxyName: string) => {+ const mint = await inject("POST", "/api/v1/agent-vault/sessions", { accessBundles: [bundle.name], ttl: "1h" });+ expect(mint.statusCode).toBe(200);+ const { session } = JSON.parse(mint.payload) as { session: { token: string } };++ const created = await inject("POST", "/api/v1/agent-vault/proxies", { name: proxyName });+ expect(created.statusCode).toBe(200);+ const { token } = JSON.parse(created.payload) as { token: string };+ const login = await testServer.inject({+ method: "POST",+ url: "/api/v1/agent-vault/proxy/login",+ body: { method: ResourceAuthMethodType.Token, token, rootCaCertificate: await createProxyCaPem() }+ });+ expect(login.statusCode).toBe(200);+ const { accessToken } = JSON.parse(login.payload) as { accessToken: string };++ return async () => {+ const resolved = await testServer.inject({+ method: "POST",+ url: "/api/v1/agent-vault/proxy/resolve",+ headers: { authorization: `Bearer ${accessToken}`, "x-infisical-agent-session": session.token }+ });+ expect(resolved.statusCode).toBe(200);+ return JSON.parse(resolved.payload) as TResolved;+ };+ };++ 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", isSecret: false });++ const created = await inject("POST", servicesUrl(bundle.id), {+ name: "github",+ hostPattern: "api.github.com",+ credential: { type: "bearer", value: "{{GITHUB_TOKEN}}" },+ customHeaders: [{ name: "X-Org", value: "org={{ORG_ID}};t={{GITHUB_TOKEN}}" }],+ substitutions: [{ placeholder: "__ORG__", surfaces: ["path"], value: "{{ORG_ID}}" }]+ });+ expect(created.statusCode).toBe(200);+ expect(created.payload).not.toContain("ghp_from_variable");+ const { service } = JSON.parse(created.payload) as {+ service: {+ customHeaders: { id: string }[];+ substitutions: { id: string }[];+ variableReferences: TReference[];+ };+ };+ expect(service.variableReferences).toHaveLength(4);+ // Exact entries, because a reference carries only the id its field uses, not the others as null.+ expect(service.variableReferences).toEqual(+ expect.arrayContaining([+ { variableId: token.id, key: "GITHUB_TOKEN", field: "credential-value", isWholeValue: true },+ {+ variableId: token.id,+ key: "GITHUB_TOKEN",+ field: "custom-header",+ customHeaderId: service.customHeaders[0].id,+ isWholeValue: false+ },+ {+ variableId: org.id,+ key: "ORG_ID",+ field: "custom-header",+ customHeaderId: service.customHeaders[0].id,+ isWholeValue: false+ },+ {+ variableId: org.id,+ key: "ORG_ID",+ field: "substitution",+ substitutionId: service.substitutions[0].id,+ isWholeValue: true+ }+ ])+ );++ const resolve = await resolverFor(bundle, "variables-resolve");+ const [resolved] = (await resolve()).services;+ expect(resolved.credential).toMatchObject({ type: "bearer", value: "ghp_from_variable" });+ expect(resolved.customHeaders[0].value).toBe("org=org-42;t=ghp_from_variable");+ expect(resolved.substitutions[0].value).toBe("org-42");+ });++ 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 created = await inject("POST", servicesUrl(bundle.id), {+ name: "echo",+ hostPattern: "echo.example.com",+ credential: { type: "bearer", value: "{{OLD_NAME}}" }+ });+ expect(created.statusCode).toBe(200);+ 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" });+ expect(renamed.statusCode).toBe(200);+ expect(JSON.parse(renamed.payload).variable).toMatchObject({+ key: "NEW_NAME",+ value: null,+ serviceIds: [serviceId]+ });++ const detail = JSON.parse((await inject("GET", `/api/v1/agent-vault/access-bundles/${bundle.id}`)).payload) as {+ accessBundle: { services: { variableReferences: TReference[] }[] };+ };+ expect(detail.accessBundle.services[0].variableReferences).toEqual([+ expect.objectContaining({ key: "NEW_NAME", field: "credential-value", isWholeValue: true })+ ]);+ 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 resolve()).services[0].credential).toMatchObject({ value: "second" });++ const stale = await inject("POST", servicesUrl(bundle.id), {+ name: "stale",+ hostPattern: "stale.example.com",+ credential: { type: "bearer", value: "{{OLD_NAME}}" }+ });+ expect(stale.statusCode).toBe(400);+ expect(JSON.parse(stale.payload).message).toContain("OLD_NAME");+ });++ 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 created = await inject("POST", servicesUrl(bundle.id), {+ name: "datadog",+ hostPattern: "api.datadoghq.com",+ credential: { type: "bearer", headerName: "DD-API-KEY", value: "{{API_KEY}}" }+ });+ 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}`);+ expect(refused.statusCode).toBe(409);+ expect(JSON.parse(refused.payload).message).toContain("'datadog'");++ const detached = await inject("PATCH", `${servicesUrl(bundle.id)}/${service.id}`, {+ credential: { type: "bearer", value: "literal_value" }+ });+ expect(detached.statusCode).toBe(200);+ expect(JSON.parse(detached.payload).service.variableReferences).toEqual([]);++ const removed = await inject("DELETE", `${variablesUrl(bundle.id)}/${variable.id}`);+ expect(removed.statusCode).toBe(200);+ expect(JSON.parse(removed.payload).variable).toMatchObject({ id: variable.id, key: "API_KEY", value: null });+ });++ test("an unknown key fails the save by name, and a malformed reference fails validation unquoted", async () => {+ const bundle = await createAccessBundle("variables-validation");++ const unknown = await inject("POST", servicesUrl(bundle.id), {+ name: "unknown",+ hostPattern: "unknown.example.com",+ credential: { type: "bearer", value: "{{NOT_DEFINED}}" }+ });+ expect(unknown.statusCode).toBe(400);+ expect(JSON.parse(unknown.payload).message).toContain("NOT_DEFINED");++ const malformed = await inject("POST", servicesUrl(bundle.id), {+ name: "malformed",+ hostPattern: "malformed.example.com",+ credential: { type: "passthrough" },+ customHeaders: [{ name: "X-Key", value: "{{lower_case_secret}}" }]+ });+ expect(malformed.statusCode).toBe(422);+ expect(malformed.payload).not.toContain("lower_case_secret");++ const bracedPlaceholder = await inject("POST", servicesUrl(bundle.id), {+ name: "braced",+ hostPattern: "braced.example.com",+ credential: { type: "passthrough" },+ substitutions: [{ placeholder: "{{PAT}}", surfaces: ["header"], value: "x" }]+ });+ expect(bracedPlaceholder.statusCode).toBe(422);++ expect(await testDb("agent_vault_services").where({ accessBundleId: bundle.id })).toHaveLength(0);+ });++ test("the list carries only values that are not secret, and the value route returns either uncached", async () => {+ const bundle = await createAccessBundle("variables-visibility");+ const hidden = await createVariable(bundle.id, { key: "HIDDEN", value: "hidden_value" });+ await createVariable(bundle.id, { key: "SHOWN", value: "shown_value", isSecret: false });++ const listed = await inject("GET", variablesUrl(bundle.id));+ expect(listed.statusCode).toBe(200);+ expect(listed.payload).not.toContain("hidden_value");+ expect(JSON.parse(listed.payload).variables).toEqual([+ expect.objectContaining({ key: "HIDDEN", isSecret: true, value: null, serviceIds: [] }),+ expect.objectContaining({ key: "SHOWN", isSecret: false, value: "shown_value", serviceIds: [] })+ ]);++ const revealed = await inject("GET", `${variablesUrl(bundle.id)}/${hidden.id}/value`);+ expect(revealed.statusCode).toBe(200);+ expect(JSON.parse(revealed.payload)).toEqual({ value: "hidden_value" });+ expect(revealed.headers["cache-control"]).toContain("no-store");++ const flipped = await inject("PATCH", `${variablesUrl(bundle.id)}/${hidden.id}`, { isSecret: false });+ expect(flipped.statusCode).toBe(200);+ expect(JSON.parse(flipped.payload).variable).toMatchObject({ isSecret: false, value: "hidden_value" });++ const row = await testDb("agent_vault_variables").where({ id: hidden.id }).first();+ expect(row.encryptedValue.toString("utf-8")).not.toContain("hidden_value");+ });++ 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" });++ const duplicate = await inject("POST", variablesUrl(bundle.id), { 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);++ const other = await createAccessBundle("variables-keys-other");+ expect((await inject("POST", variablesUrl(other.id), { key: "TOKEN", value: "three" })).statusCode).toBe(200);+ });++ 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" });++ const created = await inject("POST", servicesUrl(bundle.id), {+ name: "basic",+ hostPattern: "basic.example.com",+ credential: { type: "basic", username: "{{USER}}", password: "{{PASS}}" },+ customHeaders: [{ name: "X-One", value: "{{HEADER}}" }]+ });+ expect(created.statusCode).toBe(200);+ const { service } = JSON.parse(created.payload) as { service: { id: string; customHeaders: { id: string }[] } };+ const url = `${servicesUrl(bundle.id)}/${service.id}`;++ // The password and the renamed header were not sent, so both keep what they had.+ const patched = await inject("PATCH", url, {+ credential: { type: "basic", username: "plain-user" },+ customHeaders: [{ id: service.customHeaders[0].id, name: "X-Renamed" }]+ });+ expect(patched.statusCode).toBe(200);+ expect(referencesByField(JSON.parse(patched.payload).service.variableReferences)).toEqual([+ "credential-value:PASS",+ "custom-header:HEADER"+ ]);++ const resolve = await resolverFor(bundle, "variables-partial");+ const [resolved] = (await resolve()).services;+ expect(resolved.credential).toEqual({ type: "basic", username: "plain-user", password: "the-pass" });+ expect(resolved.customHeaders).toEqual([{ name: "X-Renamed", prefix: "", value: "the-header" }]);++ const switched = await inject("PATCH", url, { credential: { type: "bearer", value: "literal" } });+ expect(switched.statusCode).toBe(200);+ expect(referencesByField(JSON.parse(switched.payload).service.variableReferences)).toEqual([+ "custom-header:HEADER"+ ]);++ const dropped = await inject("PATCH", url, { customHeaders: [] });+ expect(dropped.statusCode).toBe(200);+ expect(JSON.parse(dropped.payload).service.variableReferences).toEqual([]);+ expect(await testDb("agent_vault_service_variable_references").where({ serviceId: service.id })).toHaveLength(0);+ });++ test("deleting a bundle takes its variables and every reference to them", async () => {+ const bundle = await createAccessBundle("variables-bundle-delete");+ const variable = await createVariable(bundle.id, { key: "TOKEN", value: "t" });+ const created = await inject("POST", servicesUrl(bundle.id), {+ name: "one",+ hostPattern: "one.example.com",+ credential: { type: "bearer", value: "{{TOKEN}}" },+ customHeaders: [{ name: "X-Two", value: "{{TOKEN}}" }]+ });+ expect(created.statusCode).toBe(200);++ 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+ );+ });++ 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", isSecret: false });+ const member = await createUaIdentity(`av-variables-member-${Date.now()}`);++ try {+ expect(+ (await inject("POST", "/api/v1/agent-vault/members", { machineIdentityIds: [member.id], role: "member" }))+ .statusCode+ ).toBe(200);+ expect(+ (+ await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/members`, {+ machineIdentityIds: [member.id]+ })+ ).statusCode+ ).toBe(200);++ // The member reaches the bundle, so the refusals below are about variables and nothing else.+ expect((await member.asIdentity("GET", `/api/v1/agent-vault/access-bundles/${bundle.id}`)).statusCode).toBe(+ 200+ );+ const listed = await member.asIdentity("GET", variablesUrl(bundle.id));+ expect(listed.statusCode).toBe(403);+ 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+ );+ } finally {+ await deleteUaIdentity(member.id);+ }+ });+ });+describe("product membership", async () => {const membersUrl = "/api/v1/agent-vault/members";@@ -1527,6 +1905,7 @@ describe("Agent Vault V1 Router", async () => {agentVaultResolveDAL: agentVaultResolveDALFactory(testDb),agentVaultServiceCustomHeaderDAL: agentVaultServiceCustomHeaderDALFactory(testDb),agentVaultServiceSubstitutionDAL: agentVaultServiceSubstitutionDALFactory(testDb),+ agentVaultVariableDAL: agentVaultVariableDALFactory(testDb),agentVaultSessionDAL: agentVaultSessionDALFactory(testDb),membershipDAL: membershipDALFactory(testDb),orgDAL: orgDALFactory(testDb),@@ -1568,6 +1947,7 @@ describe("Agent Vault V1 Router", async () => {agentVaultResolveDAL: agentVaultResolveDALFactory(testDb),agentVaultServiceCustomHeaderDAL: agentVaultServiceCustomHeaderDALFactory(testDb),agentVaultServiceSubstitutionDAL: agentVaultServiceSubstitutionDALFactory(testDb),+ agentVaultVariableDAL: agentVaultVariableDALFactory(testDb),agentVaultSessionDAL: agentVaultSessionDALFactory(testDb),membershipDAL: membershipDALFactory(testDb),orgDAL: orgDALFactory(testDb),@@ -1721,6 +2101,7 @@ describe("Agent Vault V1 Router", async () => {agentVaultResolveDAL: agentVaultResolveDALFactory(testDb),agentVaultServiceCustomHeaderDAL: agentVaultServiceCustomHeaderDALFactory(testDb),agentVaultServiceSubstitutionDAL: agentVaultServiceSubstitutionDALFactory(testDb),+ agentVaultVariableDAL: agentVaultVariableDALFactory(testDb),agentVaultSessionDAL: agentVaultSessionDALFactory(testDb),membershipDAL: membershipDALFactory(testDb),orgDAL: orgDALFactory(testDb),@@ -2388,6 +2769,7 @@ describe("Agent Vault V1 Router", async () => {agentVaultResolveDAL: agentVaultResolveDALFactory(testDb),agentVaultServiceCustomHeaderDAL: agentVaultServiceCustomHeaderDALFactory(testDb),agentVaultServiceSubstitutionDAL: agentVaultServiceSubstitutionDALFactory(testDb),+ agentVaultVariableDAL: agentVaultVariableDALFactory(testDb),agentVaultSessionDAL: agentVaultSessionDALFactory(testDb),membershipDAL: membershipDALFactory(testDb),orgDAL: orgDALFactory(testDb),@@ -2479,6 +2861,7 @@ describe("Agent Vault V1 Router", async () => {agentVaultResolveDAL: agentVaultResolveDALFactory(testDb),agentVaultServiceCustomHeaderDAL: agentVaultServiceCustomHeaderDALFactory(testDb),agentVaultServiceSubstitutionDAL: agentVaultServiceSubstitutionDALFactory(testDb),+ agentVaultVariableDAL: agentVaultVariableDALFactory(testDb),agentVaultSessionDAL: agentVaultSessionDALFactory(testDb),membershipDAL: membershipDALFactory(testDb),orgDAL: orgDALFactory(testDb),diff --git a/backend/src/@types/knex.d.ts b/backend/src/@types/knex.d.tsindex 599f7d3e6c..372232d109 100644--- a/backend/src/@types/knex.d.ts+++ b/backend/src/@types/knex.d.ts@@ -35,12 +35,18 @@ import {TAgentVaultServiceSubstitutionsInsert,TAgentVaultServiceSubstitutionsUpdate,TAgentVaultServicesUpdate,+ TAgentVaultServiceVariableReferences,+ TAgentVaultServiceVariableReferencesInsert,+ TAgentVaultServiceVariableReferencesUpdate,TAgentVaultSessionAccessBundles,TAgentVaultSessionAccessBundlesInsert,TAgentVaultSessionAccessBundlesUpdate,TAgentVaultSessions,TAgentVaultSessionsInsert,TAgentVaultSessionsUpdate,+ TAgentVaultVariables,+ TAgentVaultVariablesInsert,+ TAgentVaultVariablesUpdate,TAlertChannelMemberships,TAlertChannelMembershipsInsert,TAlertChannelMembershipsUpdate,@@ -1809,6 +1815,16 @@ declare module "knex/types/tables" {TAgentVaultServiceSubstitutionsInsert,TAgentVaultServiceSubstitutionsUpdate>;+ [TableName.AgentVaultVariable]: KnexOriginal.CompositeTableType<+ TAgentVaultVariables,+ TAgentVaultVariablesInsert,+ TAgentVaultVariablesUpdate+ >;+ [TableName.AgentVaultServiceVariableReference]: KnexOriginal.CompositeTableType<+ TAgentVaultServiceVariableReferences,+ TAgentVaultServiceVariableReferencesInsert,+ TAgentVaultServiceVariableReferencesUpdate+ >;[TableName.AgentVaultSession]: KnexOriginal.CompositeTableType<TAgentVaultSessions,TAgentVaultSessionsInsert,diff --git a/backend/src/db/migrations/20260924143000_agent-vault-variables.ts b/backend/src/db/migrations/20260924143000_agent-vault-variables.tsnew file mode 100644index 0000000000..428a14f189--- /dev/null+++ b/backend/src/db/migrations/20260924143000_agent-vault-variables.ts@@ -0,0 +1,77 @@+import { Knex } from "knex";++import { TableName } from "../schemas";+import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils";++export async function up(knex: Knex): Promise<void> {+ if (!(await knex.schema.hasTable(TableName.AgentVaultVariable))) {+ await knex.schema.createTable(TableName.AgentVaultVariable, (t) => {+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());++ t.uuid("accessBundleId").notNullable();+ t.foreign("accessBundleId").references("id").inTable(TableName.AgentVaultAccessBundle).onDelete("CASCADE");++ t.string("key", 64).notNullable();+ t.binary("encryptedValue").notNullable();+ // Every value is sealed either way. The flag only decides whether an admin sees it without a reveal.+ t.boolean("isSecret").notNullable().defaultTo(true);++ t.timestamps(true, true, true);++ // Also the index the accessBundleId foreign key needs, as its leftmost column.+ t.unique(["accessBundleId", "key"]);+ });++ await createOnUpdateTrigger(knex, TableName.AgentVaultVariable);+ }++ if (!(await knex.schema.hasTable(TableName.AgentVaultServiceVariableReference))) {+ await knex.schema.createTable(TableName.AgentVaultServiceVariableReference, (t) => {+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());++ t.uuid("serviceId").notNullable();+ t.foreign("serviceId").references("id").inTable(TableName.AgentVaultService).onDelete("CASCADE");+ t.index("serviceId");++ // Deferred, not the NO ACTION default. A bundle delete cascades to its services and its variables in+ // one statement, and an immediate check can run before the service cascade has removed these rows,+ // depending on which constraint was created first. Checked at commit, deleting a variable that is+ // still referenced is refused all the same.+ t.uuid("variableId").notNullable();+ t.foreign("variableId").references("id").inTable(TableName.AgentVaultVariable).deferrable("deferred");+ t.index("variableId");++ t.string("field", 32).notNullable();++ t.uuid("customHeaderId");+ t.foreign("customHeaderId").references("id").inTable(TableName.AgentVaultServiceCustomHeader).onDelete("CASCADE");+ t.index("customHeaderId");++ t.uuid("substitutionId");+ t.foreign("substitutionId").references("id").inTable(TableName.AgentVaultServiceSubstitution).onDelete("CASCADE");+ t.index("substitutionId");++ t.boolean("isWholeValue").notNullable();++ t.timestamps(true, true, true);+ });++ await knex.raw(+ `ALTER TABLE "${TableName.AgentVaultServiceVariableReference}" ADD CONSTRAINT "agent_vault_service_variable_references_field_check" CHECK (+ ("field" = 'custom-header' AND "customHeaderId" IS NOT NULL AND "substitutionId" IS NULL)+ OR ("field" = 'substitution' AND "substitutionId" IS NOT NULL AND "customHeaderId" IS NULL)+ OR ("field" IN ('credential-value', 'credential-username') AND "customHeaderId" IS NULL AND "substitutionId" IS NULL)+ )`+ );++ await createOnUpdateTrigger(knex, TableName.AgentVaultServiceVariableReference);+ }+}++export async function down(knex: Knex): Promise<void> {+ await knex.schema.dropTableIfExists(TableName.AgentVaultServiceVariableReference);+ await dropOnUpdateTrigger(knex, TableName.AgentVaultServiceVariableReference);++ await knex.schema.dropTableIfExists(TableName.AgentVaultVariable);+ await dropOnUpdateTrigger(knex, TableName.AgentVaultVariable);+}diff --git a/backend/src/db/schemas/agent-vault-service-variable-references.ts b/backend/src/db/schemas/agent-vault-service-variable-references.tsnew file mode 100644index 0000000000..438db6ff45--- /dev/null+++ b/backend/src/db/schemas/agent-vault-service-variable-references.ts@@ -0,0 +1,29 @@+// Code generated by automation script, DO NOT EDIT.+// Automated by pulling database and generating zod schema+// To update. Just run npm run generate:schema+// Written by akhilmhdh.++import { z } from "zod";++import { TImmutableDBKeys } from "./models";++export const AgentVaultServiceVariableReferencesSchema = z.object({+ id: z.string().uuid(),+ serviceId: z.string().uuid(),+ variableId: z.string().uuid(),+ field: z.string(),+ customHeaderId: z.string().uuid().nullable().optional(),+ substitutionId: z.string().uuid().nullable().optional(),+ isWholeValue: z.boolean(),+ createdAt: z.date(),+ updatedAt: z.date()+});++export type TAgentVaultServiceVariableReferences = z.infer<typeof AgentVaultServiceVariableReferencesSchema>;+export type TAgentVaultServiceVariableReferencesInsert = Omit<+ z.input<typeof AgentVaultServiceVariableReferencesSchema>,+ TImmutableDBKeys+>;+export type TAgentVaultServiceVariableReferencesUpdate = Partial<+ Omit<z.input<typeof AgentVaultServiceVariableReferencesSchema>, TImmutableDBKeys>+>;diff --git a/backend/src/db/schemas/agent-vault-variables.ts b/backend/src/db/schemas/agent-vault-variables.tsnew file mode 100644index 0000000000..5798036445--- /dev/null+++ b/backend/src/db/schemas/agent-vault-variables.ts@@ -0,0 +1,24 @@+// Code generated by automation script, DO NOT EDIT.+// Automated by pulling database and generating zod schema+// To update. Just run npm run generate:schema+// Written by akhilmhdh.++import { z } from "zod";++import { zodBuffer } from "@app/lib/zod";++import { TImmutableDBKeys } from "./models";++export const AgentVaultVariablesSchema = z.object({+ id: z.string().uuid(),+ accessBundleId: z.string().uuid(),+ key: z.string(),+ encryptedValue: zodBuffer,+ isSecret: z.boolean().default(true),+ createdAt: z.date(),+ updatedAt: z.date()+});++export type TAgentVaultVariables = z.infer<typeof AgentVaultVariablesSchema>;+export type TAgentVaultVariablesInsert = Omit<z.input<typeof AgentVaultVariablesSchema>, TImmutableDBKeys>;+export type TAgentVaultVariablesUpdate = Partial<Omit<z.input<typeof AgentVaultVariablesSchema>, TImmutableDBKeys>>;diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.tsindex 88f3152396..4365cdad3d 100644--- a/backend/src/db/schemas/index.ts+++ b/backend/src/db/schemas/index.ts@@ -8,9 +8,11 @@ export * from "./agent-vault-access-bundles";export * from "./agent-vault-proxies";export * from "./agent-vault-service-custom-headers";export * from "./agent-vault-service-substitutions";+export * from "./agent-vault-service-variable-references";export * from "./agent-vault-services";export * from "./agent-vault-session-access-bundles";export * from "./agent-vault-sessions";+export * from "./agent-vault-variables";export * from "./alert-channel-memberships";export * from "./alert-channel-recipients";export * from "./alert-channels";diff --git a/backend/src/db/schemas/models.ts b/backend/src/db/schemas/models.tsindex fcd9585894..a22f5eec2f 100644--- a/backend/src/db/schemas/models.ts+++ b/backend/src/db/schemas/models.ts@@ -278,6 +278,8 @@ export enum TableName {AgentVaultService = "agent_vault_services",AgentVaultServiceCustomHeader = "agent_vault_service_custom_headers",AgentVaultServiceSubstitution = "agent_vault_service_substitutions",+ AgentVaultVariable = "agent_vault_variables",+ AgentVaultServiceVariableReference = "agent_vault_service_variable_references",AgentVaultSession = "agent_vault_sessions",AgentVaultSessionAccessBundle = "agent_vault_session_access_bundles",AgentVaultProxy = "agent_vault_proxies",diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-access-bundle-router.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-access-bundle-router.tsindex 02d5a75650..024c245c3d 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@@ -10,7 +10,8 @@ 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, writeLimit } from "@app/server/config/rateLimiter";+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";@@ -36,7 +37,10 @@ import {AgentVaultRemovedMemberSchema,AgentVaultServiceSchema,AgentVaultSubstitutionsInputSchema,- AgentVaultSubstitutionsUpdateSchema+ AgentVaultSubstitutionsUpdateSchema,+ AgentVaultVariableKeySchema,+ AgentVaultVariableSchema,+ AgentVaultVariableValueSchema} from "./agent-vault-schemas";const AccessBundleDescriptionSchema = z@@ -66,6 +70,10 @@ const isStoredSecretReplaced = (credential?: z.infer<typeof AgentVaultCredentialreturn true;};+const variableKeysOf = (service: { variableReferences: { key: string }[] }) => [+ ...new Set(service.variableReferences.map((reference) => reference.key))+];+export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodProvider) => {server.route({method: "GET",@@ -328,7 +336,8 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodProallowedMethods: service.allowedMethods,allowedPathPrefixes: service.allowedPathPrefixes,customHeaderNames: service.customHeaders.map((header) => header.name),- substitutionPlaceholders: service.substitutions.map((substitution) => substitution.placeholder)+ substitutionPlaceholders: service.substitutions.map((substitution) => substitution.placeholder),+ variableKeys: variableKeysOf(service)}}});@@ -425,7 +434,11 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodProsubstitutionsReplaced: req.body.substitutions?.filter((substitution) => substitution.value !== undefined).map((substitution) => substitution.placeholder),- credentialReplaced: isStoredSecretReplaced(req.body.credential)+ credentialReplaced: isStoredSecretReplaced(req.body.credential),+ variableKeys:+ req.body.credential || req.body.customHeaders || req.body.substitutions+ ? variableKeysOf(service)+ : undefined}}});@@ -495,6 +508,212 @@ 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),+ isSecret: z.boolean().default(true).describe(AGENT_VAULT.VARIABLE.isSecret)+ }),+ response: { 200: z.object({ variable: AgentVaultVariableSchema }) }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ handler: async (req) => {+ const variable = 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,+ variableId: variable.id,+ key: variable.key,+ isSecret: variable.isSecret+ }+ }+ });++ 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),+ isSecret: z.boolean().optional().describe(AGENT_VAULT.VARIABLE.isSecret)+ })+ .refine(+ (body) => Object.values(body).some((value) => value !== undefined),+ "Provide at least one of 'key', 'value' or 'isSecret' to update"+ ),+ response: { 200: z.object({ variable: AgentVaultVariableSchema }) }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ handler: async (req) => {+ const { variable, previousKey, previousIsSecret } = 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,+ variableId: variable.id,+ key: variable.key,+ previousKey: previousKey === variable.key ? undefined : previousKey,+ isSecret: variable.isSecret,+ previousIsSecret: previousIsSecret === variable.isSecret ? undefined : previousIsSecret,+ valueReplaced: req.body.value !== undefined+ }+ }+ });++ 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 = 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, variableId: variable.id, key: variable.key }+ }+ });++ 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, secret or not",+ 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 } = 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, 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 698bc41079..81d0d4003a 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@@ -9,11 +9,13 @@ import {AgentVaultCredentialType,AgentVaultHttpMethod,AgentVaultMemberType,- AgentVaultSubstitutionSurface+ AgentVaultSubstitutionSurface,+ AgentVaultVariableReferenceField} from "@app/ee/services/agent-vault/agent-vault-enums";import { hostPatternSchema } from "@app/ee/services/agent-vault/agent-vault-host-pattern";import { agentVaultPathPrefixListSchema } from "@app/ee/services/agent-vault/agent-vault-path-prefix";import {+ acceptsVariableReferences,addDuplicateCustomHeaderNameIssues,addDuplicatePlaceholderIssues,AGENT_VAULT_MAX_CUSTOM_HEADERS,@@ -24,6 +26,12 @@ import {AgentVaultSubstitutionInputSchema,AgentVaultSubstitutionUpdateSchema} from "@app/ee/services/agent-vault/agent-vault-transformation-schemas";+import {+ AGENT_VAULT_VARIABLE_KEY_MAX_LENGTH,+ AGENT_VAULT_VARIABLE_KEY_MESSAGE,+ AGENT_VAULT_VARIABLE_KEY_RE,+ AGENT_VAULT_VARIABLE_VALUE_MAX_LENGTH+} from "@app/ee/services/agent-vault/agent-vault-variable-fns";import { AGENT_VAULT_MAX_GRANTEES } from "@app/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service";import { AGENT_VAULT } from "@app/lib/api-docs";import { slugSchema } from "@app/server/lib/schemas";@@ -62,28 +70,20 @@ export const AgentVaultCredentialInputSchema = z.regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE).optional().describe(AGENT_VAULT.SERVICE.headerPrefix),- value: z- .string()- .min(1)- .max(8192)- .regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)- .describe(AGENT_VAULT.SERVICE.value)+ value: acceptsVariableReferences(+ z.string().min(1).max(8192).regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)+ ).describe(AGENT_VAULT.SERVICE.value)}).describe(JSON.stringify({ title: "Bearer" })),z.object({type: z.literal(AgentVaultCredentialType.Basic),- username: z- .string()- .trim()- .max(256)- .regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)- .describe(AGENT_VAULT.SERVICE.username),- password: z- .string()- .max(8192)- .regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)- .describe(AGENT_VAULT.SERVICE.password)+ username: acceptsVariableReferences(+ z.string().trim().max(256).regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)+ ).describe(AGENT_VAULT.SERVICE.username),+ password: acceptsVariableReferences(+ z.string().max(8192).regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)+ ).describe(AGENT_VAULT.SERVICE.password)}).describe(JSON.stringify({ title: "Basic Auth" })),z@@ -106,11 +106,9 @@ export const AgentVaultCredentialUpdateSchema = z.regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE).optional().describe(AGENT_VAULT.SERVICE.headerPrefix),- value: z- .string()- .min(1)- .max(8192)- .regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)+ value: acceptsVariableReferences(+ z.string().min(1).max(8192).regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)+ ).optional().describe(AGENT_VAULT.SERVICE.updateValue)})@@ -118,17 +116,14 @@ export const AgentVaultCredentialUpdateSchema = zz.object({type: z.literal(AgentVaultCredentialType.Basic),- username: z- .string()- .trim()- .max(256)- .regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)+ username: acceptsVariableReferences(+ z.string().trim().max(256).regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)+ ).optional().describe(AGENT_VAULT.SERVICE.updateUsername),- password: z- .string()- .max(8192)- .regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)+ password: acceptsVariableReferences(+ z.string().max(8192).regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)+ ).optional().describe(AGENT_VAULT.SERVICE.updatePassword)})@@ -185,6 +180,37 @@ export const AgentVaultSubstitutionsUpdateSchema = AgentVaultSubstitutionUpdateS.superRefine(addDuplicatePlaceholderIssues).describe(AGENT_VAULT.SERVICE.substitutions);+const variableReferenceBase = {+ variableId: z.string().uuid().describe(AGENT_VAULT.VARIABLE.variableId),+ key: z.string().describe(AGENT_VAULT.VARIABLE.key),+ isWholeValue: z.boolean().describe(AGENT_VAULT.SERVICE.referenceIsWholeValue)+};++export const AgentVaultVariableReferenceSchema = z.discriminatedUnion("field", [+ z+ .object({+ ...variableReferenceBase,+ field: z+ .enum([AgentVaultVariableReferenceField.CredentialValue, AgentVaultVariableReferenceField.CredentialUsername])+ .describe(AGENT_VAULT.SERVICE.referenceField)+ })+ .describe(JSON.stringify({ title: "Credential" })),+ z+ .object({+ ...variableReferenceBase,+ field: z.literal(AgentVaultVariableReferenceField.CustomHeader).describe(AGENT_VAULT.SERVICE.referenceField),+ customHeaderId: z.string().uuid().describe(AGENT_VAULT.SERVICE.referenceCustomHeaderId)+ })+ .describe(JSON.stringify({ title: "Custom Header" })),+ z+ .object({+ ...variableReferenceBase,+ field: z.literal(AgentVaultVariableReferenceField.Substitution).describe(AGENT_VAULT.SERVICE.referenceField),+ substitutionId: z.string().uuid().describe(AGENT_VAULT.SERVICE.referenceSubstitutionId)+ })+ .describe(JSON.stringify({ title: "Substitution" }))+]);+// The sealed value is never in here. This schema is the last thing between the encrypted column and the// wire on every service route: the serializer emits `result.data`, so anything absent here is dropped,// and anything required here but missing from a projection is a 500 rather than a leak.@@ -212,10 +238,37 @@ export const AgentVaultServiceSchema = z.object({}).array().describe(AGENT_VAULT.SERVICE.substitutions),+ variableReferences: AgentVaultVariableReferenceSchema.array().describe(AGENT_VAULT.SERVICE.variableReferences),createdAt: z.date().describe(AGENT_VAULT.SERVICE.createdAt),updatedAt: z.date().describe(AGENT_VAULT.SERVICE.updatedAt)});+export const AgentVaultVariableKeySchema = z+ .string()+ .trim()+ .min(1)+ .max(AGENT_VAULT_VARIABLE_KEY_MAX_LENGTH)+ .regex(AGENT_VAULT_VARIABLE_KEY_RE, AGENT_VAULT_VARIABLE_KEY_MESSAGE);++// Braces are allowed and sent as they are. A value is never expanded again, which is also how a service can+// send a literal {{ it could not take directly.+export const AgentVaultVariableValueSchema = z+ .string()+ .min(1)+ .max(AGENT_VAULT_VARIABLE_VALUE_MAX_LENGTH)+ .regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE);++export 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),+ isSecret: z.boolean().describe(AGENT_VAULT.VARIABLE.isSecret),+ value: z.string().nullable().describe(AGENT_VAULT.VARIABLE.listedValue),+ serviceIds: z.string().uuid().array().describe(AGENT_VAULT.VARIABLE.serviceIds),+ createdAt: z.date().describe(AGENT_VAULT.VARIABLE.createdAt),+ updatedAt: z.date().describe(AGENT_VAULT.VARIABLE.updatedAt)+});+const memberIdsShape = (docs: { userIds: string; machineIdentityIds: string; groupIds: string }) => ({userIds: z.string().uuid().array().default([]).describe(docs.userIds),machineIdentityIds: z.string().uuid().array().default([]).describe(docs.machineIdentityIds),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 d282ebf1f2..626b502750 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@@ -8,6 +8,8 @@ import {TAgentVaultServiceCustomHeaders,TAgentVaultServices,TAgentVaultServiceSubstitutions,+ TAgentVaultServiceVariableReferencesInsert,+ TAgentVaultVariables,TMemberships} from "@app/db/schemas";import { TIdentityGroupMembershipDALFactory } from "@app/ee/services/group/identity-group-membership-dal";@@ -17,7 +19,9 @@ import {ProjectPermissionAgentVaultAccessBundleActions,ProjectPermissionSub} from "@app/ee/services/permission/project-permission";-import { BadRequestError, NotFoundError } from "@app/lib/errors";+import { DatabaseErrorCode } from "@app/lib/error-codes";+import { BadRequestError, ConflictError, NotFoundError } from "@app/lib/errors";+import { hasPostgresErrorCode } from "@app/lib/errors/postgres";import { ActorType } from "@app/services/auth/auth-type";import { TKmsServiceFactory } from "@app/services/kms/kms-service";import { KmsDataKey } from "@app/services/kms/kms-types";@@ -35,9 +39,17 @@ import {AgentVaultHttpMethod,AgentVaultMemberType,AgentVaultResourceRole,- AgentVaultSubstitutionSurface+ AgentVaultSubstitutionSurface,+ AgentVaultVariableReferenceField} from "../agent-vault/agent-vault-enums";import { getAgentVaultReachability } from "../agent-vault/agent-vault-permission";+import {+ AGENT_VAULT_MAX_VARIABLES,+ findVariableKeys,+ isWholeVariableReference,+ toStoredVariableReferences,+ toVariableReference+} from "../agent-vault/agent-vault-variable-fns";import { TAgentVaultMemberDALFactory } from "../agent-vault-member/agent-vault-member-dal";import { TAgentVaultAccessBundleActorRef, TAgentVaultAccessBundleDALFactory } from "./agent-vault-access-bundle-dal";import {@@ -45,27 +57,39 @@ import {TAgentVaultCredentialInput,TAgentVaultCredentialSummary,TAgentVaultCredentialUpdate,+ TAgentVaultVariableReferenceSummary,TCreateAccessBundleDTO,TCreateServiceDTO,+ TCreateVariableDTO,TDeleteAccessBundleDTO,TDeleteServiceDTO,TGetAccessBundleDTO,TListAccessBundlesDTO,TListMembersDTO,+ TListVariablesDTO,TRevokeMembersDTO,TUpdateAccessBundleDTO,- TUpdateServiceDTO+ TUpdateServiceDTO,+ TUpdateVariableDTO,+ TVariableByIdDTO} from "./agent-vault-access-bundle-types";import { TAgentVaultServiceCustomHeaderDALFactory } from "./agent-vault-service-custom-header-dal";import { TAgentVaultServiceDALFactory } from "./agent-vault-service-dal";import { TAgentVaultServiceSubstitutionDALFactory } from "./agent-vault-service-substitution-dal";+import {+ TAgentVaultServiceVariableReferenceDALFactory,+ 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;+ agentVaultServiceVariableReferenceDAL: TAgentVaultServiceVariableReferenceDALFactory;permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;membershipDAL: Pick<@@ -95,6 +119,8 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundagentVaultServiceDAL,agentVaultServiceCustomHeaderDAL,agentVaultServiceSubstitutionDAL,+ agentVaultVariableDAL,+ agentVaultServiceVariableReferenceDAL,permissionService,kmsService,membershipDAL,@@ -349,12 +375,38 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund}};+ const summarizeVariableReference = (+ reference: TAgentVaultVariableReferenceWithKey+ ): TAgentVaultVariableReferenceSummary => {+ const base = { variableId: reference.variableId, key: reference.key, isWholeValue: reference.isWholeValue };+ // The field check constraint guarantees the id that matches the field is set.+ switch (reference.field as AgentVaultVariableReferenceField) {+ case AgentVaultVariableReferenceField.CustomHeader:+ return {+ ...base,+ field: AgentVaultVariableReferenceField.CustomHeader,+ customHeaderId: reference.customHeaderId!+ };+ case AgentVaultVariableReferenceField.Substitution:+ return {+ ...base,+ field: AgentVaultVariableReferenceField.Substitution,+ substitutionId: reference.substitutionId!+ };+ case AgentVaultVariableReferenceField.CredentialUsername:+ return { ...base, field: AgentVaultVariableReferenceField.CredentialUsername };+ default:+ return { ...base, field: AgentVaultVariableReferenceField.CredentialValue };+ }+ };+// Built by hand rather than spread, so the sealed columns stay off the wire even if the response schema is// later loosened.const projectService = (service: TAgentVaultServices,customHeaders: TAgentVaultServiceCustomHeaders[],- substitutions: TAgentVaultServiceSubstitutions[]+ substitutions: TAgentVaultServiceSubstitutions[],+ variableReferences: TAgentVaultVariableReferenceWithKey[]) => ({id: service.id,accessBundleId: service.accessBundleId,@@ -369,18 +421,113 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundplaceholder: substitution.placeholder,surfaces: substitution.surfaces as AgentVaultSubstitutionSurface[]})),+ variableReferences: variableReferences.map(summarizeVariableReference),createdAt: service.createdAt,updatedAt: service.updatedAt});const loadTransformations = async (serviceIds: string[], tx?: Knex) => {- const [customHeaders, substitutions] = await Promise.all([+ const [customHeaders, substitutions, variableReferences] = await Promise.all([agentVaultServiceCustomHeaderDAL.findByServiceIds(serviceIds, tx),- agentVaultServiceSubstitutionDAL.findByServiceIds(serviceIds, tx)+ agentVaultServiceSubstitutionDAL.findByServiceIds(serviceIds, tx),+ agentVaultServiceVariableReferenceDAL.findByServiceIds(serviceIds, tx)]);- return { customHeaders, substitutions };+ return { customHeaders, substitutions, variableReferences };+ };++ // What a missing key's error calls the field. Never the value itself, which is secret.+ type TReferencingText = { label: string; text: string };++ type TReferenceTarget = {+ field: AgentVaultVariableReferenceField;+ customHeaderId?: string;+ substitutionId?: string;+ };++ const credentialReferenceTexts = (+ credential: TAgentVaultCredentialUpdate+ ): (TReferencingText & TReferenceTarget)[] => {+ switch (credential.type) {+ case AgentVaultCredentialType.Bearer:+ return credential.value === undefined+ ? []+ : [{ label: "The token", text: credential.value, field: AgentVaultVariableReferenceField.CredentialValue }];+ case AgentVaultCredentialType.Basic:+ return [+ ...(credential.username === undefined+ ? []+ : [+ {+ label: "The username",+ text: credential.username,+ field: AgentVaultVariableReferenceField.CredentialUsername+ }+ ]),+ ...(credential.password === undefined+ ? []+ : [+ {+ label: "The password",+ text: credential.password,+ field: AgentVaultVariableReferenceField.CredentialValue+ }+ ])+ ];+ default:+ return [];+ }+ };++ // A key the bundle does not define would reach the host as literal braces, so it fails the save instead.+ const resolveVariableKeys = async (accessBundleId: string, texts: TReferencingText[]) => {+ if (!texts.some(({ text }) => findVariableKeys(text).length)) return new Map<string, string>();++ const variables = await agentVaultVariableDAL.findKeysByAccessBundleId(accessBundleId);+ 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.`+ });+ }+ });++ return idOfKey;};+ const toReferenceRows = (+ serviceId: string,+ idOfKey: ReadonlyMap<string, string>,+ targets: (TReferenceTarget & { text: string })[]+ ): TAgentVaultServiceVariableReferencesInsert[] =>+ targets.flatMap(({ text, field, customHeaderId, substitutionId }) =>+ findVariableKeys(text).flatMap((key) => {+ const variableId = idOfKey.get(key);+ if (!variableId) return [];+ return [+ {+ serviceId,+ variableId,+ field,+ customHeaderId: customHeaderId ?? null,+ substitutionId: substitutionId ?? null,+ isWholeValue: isWholeVariableReference(text)+ }+ ];+ })+ );++ // A half kept from storage is already in id form, and storing it again leaves it as it is.+ const storeSecretReferences = (secret: Record<string, string>, store: (text: string) => string) =>+ Object.fromEntries(Object.entries(secret).map(([part, text]) => [part, store(text)]));++ // The reference is stored by id, so a variable deleted between the key lookup and the commit only shows+ // up at commit, as the deferred foreign key.+ const VARIABLE_DELETED_DURING_SAVE_MESSAGE =+ "A variable this service uses was deleted while it was being saved. Check its variable references and save again.";+// Basic has no header name in its config, but the proxy always writes Authorization.const credentialHeaderName = (credentialType: AgentVaultCredentialType, headerName?: string): string | null => {switch (credentialType) {@@ -450,7 +597,9 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund);const services = await agentVaultServiceDAL.findByAccessBundleId(bundle.id);- const { customHeaders, substitutions } = await loadTransformations(services.map((service) => service.id));+ const { customHeaders, substitutions, variableReferences } = await loadTransformations(+ services.map((service) => service.id)+ );return {id: bundle.id,@@ -462,7 +611,8 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundprojectService(service,customHeaders.filter((header) => header.serviceId === service.id),- substitutions.filter((substitution) => substitution.serviceId === service.id)+ substitutions.filter((substitution) => substitution.serviceId === service.id),+ variableReferences.filter((reference) => reference.serviceId === service.id)))};@@ -607,11 +757,23 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundconst { config, secret } = splitCredential(credential);assertCustomHeadersDoNotShadowCredential(config, customHeaders);+ const credentialTexts = credentialReferenceTexts(credential);+ const idOfKey = await resolveVariableKeys(bundle.id, [+ ...credentialTexts,+ ...(customHeaders ?? []).map((header) => ({ label: `The custom header '${header.name}'`, text: header.value })),+ ...(substitutions ?? []).map((substitution) => ({+ label: `The substitution for '${substitution.placeholder}'`,+ text: substitution.value+ }))+ ]);+ const store = (text: string) => toStoredVariableReferences(text, idOfKey);+const { encryptor } = await getProjectCipher(rest.projectId);- const seal = (value: string) => encryptor({ plainText: Buffer.from(JSON.stringify({ value })) }).cipherTextBlob;+ const seal = (value: string) =>+ encryptor({ plainText: Buffer.from(JSON.stringify({ value: store(value) })) }).cipherTextBlob;const encryptedCredential = secret- ? encryptor({ plainText: Buffer.from(JSON.stringify(secret)) }).cipherTextBlob+ ? encryptor({ plainText: Buffer.from(JSON.stringify(storeSecretReferences(secret, store))) }).cipherTextBlob: null;const customHeaderRows = (customHeaders ?? []).map((header, position) => ({name: header.name,@@ -665,7 +827,27 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund): [];- return { created, insertedCustomHeaders, insertedSubstitutions };+ const customHeaderIdAt = new Map(insertedCustomHeaders.map((row) => [row.position, row.id]));+ const substitutionIdAt = new Map(insertedSubstitutions.map((row) => [row.position, row.id]));+ const referenceRows = toReferenceRows(created.id, idOfKey, [+ ...credentialTexts,+ ...(customHeaders ?? []).map((header, position) => ({+ field: AgentVaultVariableReferenceField.CustomHeader,+ customHeaderId: customHeaderIdAt.get(position),+ text: header.value+ })),+ ...(substitutions ?? []).map((substitution, position) => ({+ field: AgentVaultVariableReferenceField.Substitution,+ substitutionId: substitutionIdAt.get(position),+ text: substitution.value+ }))+ ]);+ if (referenceRows.length) await agentVaultServiceVariableReferenceDAL.insertMany(referenceRows, tx);+ const variableReferences = referenceRows.length+ ? await agentVaultServiceVariableReferenceDAL.findByServiceIds([created.id], tx)+ : [];++ return { created, insertedCustomHeaders, insertedSubstitutions, variableReferences };});let result;@@ -675,11 +857,19 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundif (isUniqueViolation(err)) {throw new BadRequestError({ message: `A service named '${name}' already exists in this access bundle` });}+ if (hasPostgresErrorCode(err, DatabaseErrorCode.ForeignKeyViolation)) {+ throw new BadRequestError({ message: VARIABLE_DELETED_DURING_SAVE_MESSAGE });+ }throw err;}return {- service: projectService(result.created, result.insertedCustomHeaders, result.insertedSubstitutions)+ service: projectService(+ result.created,+ result.insertedCustomHeaders,+ result.insertedSubstitutions,+ result.variableReferences+ )};};@@ -719,7 +909,23 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund});}+ // Only the values that arrived. One left out keeps what is sealed, and so keeps its references.+ const credentialTexts = credential ? credentialReferenceTexts(credential) : [];+ const idOfKey = await resolveVariableKeys(bundle.id, [+ ...credentialTexts,+ ...(customHeaders ?? []).flatMap((header) =>+ header.value === undefined ? [] : [{ label: `The custom header '${header.name}'`, text: header.value }]+ ),+ ...(substitutions ?? []).flatMap((substitution) =>+ substitution.value === undefined+ ? []+ : [{ label: `The substitution for '${substitution.placeholder}'`, text: substitution.value }]+ )+ ]);+ const store = (text: string) => toStoredVariableReferences(text, idOfKey);+let credentialUpdate = {};+ let replacedCredentialFields: AgentVaultVariableReferenceField[] = [];let effectiveCredentialConfig = service.credentialConfig as TAgentVaultCredentialConfig;if (credential) {const needsStoredSecret =@@ -740,7 +946,17 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundif (secret === null) encryptedCredential = null;if (secret) {const { encryptor } = cipher ?? (await getProjectCipher(rest.projectId));- encryptedCredential = encryptor({ plainText: Buffer.from(JSON.stringify(secret)) }).cipherTextBlob;+ encryptedCredential = encryptor({+ plainText: Buffer.from(JSON.stringify(storeSecretReferences(secret, store)))+ }).cipherTextBlob;+ }++ // A new type or a pass-through replaces the whole secret, so neither half keeps its references.+ if (secret !== undefined) {+ replacedCredentialFields =+ secret === null || credential.type !== service.credentialType+ ? [AgentVaultVariableReferenceField.CredentialValue, AgentVaultVariableReferenceField.CredentialUsername]+ : credentialTexts.map(({ field }) => field);}credentialUpdate = {@@ -754,7 +970,8 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundconst cipherForTransformations =customHeaders?.length || substitutions?.length ? await getProjectCipher(rest.projectId) : null;const seal = (value: string) =>- cipherForTransformations!.encryptor({ plainText: Buffer.from(JSON.stringify({ value })) }).cipherTextBlob;+ cipherForTransformations!.encryptor({ plainText: Buffer.from(JSON.stringify({ value: store(value) })) })+ .cipherTextBlob;const customHeaderWrites: TTransformationWrite<{ name: string; prefix: string }>[] | undefined = customHeaders?.map((header) => ({@@ -882,7 +1099,59 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund"substitution");- return { updatedService, updatedCustomHeaders, updatedSubstitutions };+ // Every row's position is its index in the list just written, which is how a value finds its row.+ // A row dropped from the list takes its references with it through the foreign key.+ const customHeaderIdAt = new Map(updatedCustomHeaders.map((row) => [row.position, row.id]));+ const substitutionIdAt = new Map(updatedSubstitutions.map((row) => [row.position, row.id]));+ const rewrittenTargets: (TReferenceTarget & { text: string })[] = [+ ...credentialTexts,+ ...(customHeaders ?? []).flatMap((header, position) =>+ header.value === undefined+ ? []+ : [+ {+ field: AgentVaultVariableReferenceField.CustomHeader,+ customHeaderId: customHeaderIdAt.get(position),+ text: header.value+ }+ ]+ ),+ ...(substitutions ?? []).flatMap((substitution, position) =>+ substitution.value === undefined+ ? []+ : [+ {+ field: AgentVaultVariableReferenceField.Substitution,+ substitutionId: substitutionIdAt.get(position),+ text: substitution.value+ }+ ]+ )+ ];+ const rewrittenCustomHeaderIds = rewrittenTargets.flatMap((target) =>+ target.customHeaderId ? [target.customHeaderId] : []+ );+ const rewrittenSubstitutionIds = rewrittenTargets.flatMap((target) =>+ target.substitutionId ? [target.substitutionId] : []+ );++ if (replacedCredentialFields.length) {+ await agentVaultServiceVariableReferenceDAL.delete(+ { serviceId: service.id, $in: { field: replacedCredentialFields } },+ tx+ );+ }+ if (rewrittenCustomHeaderIds.length) {+ await agentVaultServiceVariableReferenceDAL.delete({ $in: { customHeaderId: rewrittenCustomHeaderIds } }, tx);+ }+ if (rewrittenSubstitutionIds.length) {+ await agentVaultServiceVariableReferenceDAL.delete({ $in: { substitutionId: rewrittenSubstitutionIds } }, tx);+ }+ const referenceRows = toReferenceRows(service.id, idOfKey, rewrittenTargets);+ if (referenceRows.length) await agentVaultServiceVariableReferenceDAL.insertMany(referenceRows, tx);+ const variableReferences = await agentVaultServiceVariableReferenceDAL.findByServiceIds([service.id], tx);++ return { updatedService, updatedCustomHeaders, updatedSubstitutions, variableReferences };});let result;@@ -892,11 +1161,19 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundif (isUniqueViolation(err)) {throw new BadRequestError({ message: `A service named '${name}' already exists in this access bundle` });}+ if (hasPostgresErrorCode(err, DatabaseErrorCode.ForeignKeyViolation)) {+ throw new BadRequestError({ message: VARIABLE_DELETED_DURING_SAVE_MESSAGE });+ }throw err;}return {- service: projectService(result.updatedService, result.updatedCustomHeaders, result.updatedSubstitutions)+ service: projectService(+ result.updatedService,+ result.updatedCustomHeaders,+ result.updatedSubstitutions,+ result.variableReferences+ )};};@@ -911,9 +1188,233 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundif (!service) throw new NotFoundError({ message: `Service with ID '${serviceId}' not found` });// Read before the delete, since CASCADE takes these rows with the service.- const { customHeaders, substitutions } = await loadTransformations([service.id]);+ const { customHeaders, substitutions, variableReferences } = await loadTransformations([service.id]);const deleted = await agentVaultServiceDAL.deleteById(service.id);- return projectService(deleted, customHeaders, substitutions);+ return projectService(deleted, customHeaders, substitutions, variableReferences);+ };++ 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;++ // The secret check sits in the projection, so no caller can put a secret value on the wire by passing one.+ const projectVariable = (variable: TAgentVaultVariables, serviceIds: string[], value: string | null) => ({+ id: variable.id,+ accessBundleId: variable.accessBundleId,+ key: variable.key,+ isSecret: variable.isSecret,+ value: variable.isSecret ? null : value,+ 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);+ ForbiddenError.from(permission).throwUnlessCan(+ ProjectPermissionAgentVaultAccessBundleActions.Edit,+ ProjectPermissionSub.AgentVaultAccessBundles+ );+ 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, cipher] = await Promise.all([+ agentVaultServiceVariableReferenceDAL.findByVariableIds(variables.map((variable) => variable.id)),+ variables.some((variable) => !variable.isSecret) ? getProjectCipher(dto.projectId) : null+ ]);++ return variables.map((variable) =>+ projectVariable(+ variable,+ serviceIdsUsing(references, variable.id),+ cipher && !variable.isSecret ? openVariableValue(cipher.decryptor, variable.encryptedValue) : null+ )+ );+ };++ const createVariable = async ({ accessBundleId, key, value, isSecret, ...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, isSecret }, tx);+ });++ try {+ return projectVariable(await write(), [], value);+ } catch (err) {+ if (isUniqueViolation(err)) throw new BadRequestError({ message: duplicateVariableKeyMessage(key) });+ throw err;+ }+ };++ const updateVariable = async ({ accessBundleId, variableId, key, value, isSecret, ...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 cipher =+ value !== undefined || !(isSecret ?? variable.isSecret) ? await getProjectCipher(rest.projectId) : null;+ const encryptedValue = value === undefined ? undefined : sealVariableValue(cipher!.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, isSecret, ...(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;+ // The flag is re-read under the lock, so it can disagree with the replica read the cipher was chosen by.+ let plainValue: string | null = null;+ if (!updated.isSecret) {+ plainValue =+ value ??+ openVariableValue((cipher ?? (await getProjectCipher(rest.projectId))).decryptor, updated.encryptedValue);+ }++ return {+ variable: projectVariable(updated, serviceIdsUsing(references, updated.id), plainValue),+ previousKey: previous.key,+ previousIsSecret: previous.isSecret+ };+ };++ 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;+ }++ const plainValue = deleted.isSecret+ ? null+ : openVariableValue((await getProjectCipher(rest.projectId)).decryptor, deleted.encryptedValue);+ return projectVariable(deleted, [], plainValue);+ };++ 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) };};const listMembers = async ({ accessBundleId, search, limit, offset, ...rest }: TListMembersDTO) => {@@ -1096,6 +1597,11 @@ 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 eb2a61470e..759d211284 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@@ -2,7 +2,8 @@ import { TAgentVaultActorContext } from "../agent-vault/agent-vault-actor-types"import {AgentVaultCredentialType,AgentVaultHttpMethod,- AgentVaultSubstitutionSurface+ AgentVaultSubstitutionSurface,+ AgentVaultVariableReferenceField} from "../agent-vault/agent-vault-enums";import { TAgentVaultAccessBundleOrderBy } from "./agent-vault-access-bundle-dal";@@ -21,6 +22,12 @@ export type TAgentVaultCredentialSummary =| { type: AgentVaultCredentialType.Basic }| { type: AgentVaultCredentialType.Passthrough };+export type TAgentVaultVariableReferenceSummary = { variableId: string; key: string; isWholeValue: boolean } & (+ | { field: AgentVaultVariableReferenceField.CredentialValue | AgentVaultVariableReferenceField.CredentialUsername }+ | { field: AgentVaultVariableReferenceField.CustomHeader; customHeaderId: string }+ | { field: AgentVaultVariableReferenceField.Substitution; substitutionId: string }+);+export type TAgentVaultProjectScoped = { projectId: string; ctx: TAgentVaultActorContext };export type TListAccessBundlesDTO = TAgentVaultProjectScoped & {@@ -93,6 +100,25 @@ export type TDeleteServiceDTO = TAgentVaultProjectScoped & {serviceId: string;};+export type TListVariablesDTO = TAgentVaultProjectScoped & { accessBundleId: string };++export type TCreateVariableDTO = TAgentVaultProjectScoped & {+ accessBundleId: string;+ key: string;+ value: string;+ isSecret: boolean;+};++export type TUpdateVariableDTO = TAgentVaultProjectScoped & {+ accessBundleId: string;+ variableId: string;+ key?: string;+ value?: string;+ isSecret?: boolean;+};++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-service-variable-reference-dal.ts b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-service-variable-reference-dal.tsnew file mode 100644index 0000000000..bb44dc6a12--- /dev/null+++ b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-service-variable-reference-dal.ts@@ -0,0 +1,55 @@+import { Knex } from "knex";++import { TDbClient } from "@app/db";+import { TableName, TAgentVaultServiceVariableReferences } from "@app/db/schemas";+import { DatabaseError } from "@app/lib/errors";+import { ormify, selectAllTableCols } from "@app/lib/knex";++export type TAgentVaultServiceVariableReferenceDALFactory = ReturnType<+ typeof agentVaultServiceVariableReferenceDALFactory+>;++export type TAgentVaultVariableReferenceWithKey = TAgentVaultServiceVariableReferences & { key: string };++export const agentVaultServiceVariableReferenceDALFactory = (db: TDbClient) => {+ const orm = ormify(db, TableName.AgentVaultServiceVariableReference);++ // The key comes from the variable, so a rename shows through without touching these rows.+ const findByServiceIds = async (serviceIds: string[], tx?: Knex): Promise<TAgentVaultVariableReferenceWithKey[]> => {+ if (!serviceIds.length) return [];+ try {+ return (await (tx || db.replicaNode())(TableName.AgentVaultServiceVariableReference)+ .join(+ TableName.AgentVaultVariable,+ `${TableName.AgentVaultServiceVariableReference}.variableId`,+ `${TableName.AgentVaultVariable}.id`+ )+ .whereIn(`${TableName.AgentVaultServiceVariableReference}.serviceId`, serviceIds)+ .orderBy(`${TableName.AgentVaultVariable}.key`, "asc")+ .select(+ selectAllTableCols(TableName.AgentVaultServiceVariableReference),+ db.ref("key").withSchema(TableName.AgentVaultVariable)+ )) as TAgentVaultVariableReferenceWithKey[];+ } catch (error) {+ throw new DatabaseError({ error, name: "Find agent vault variable references" });+ }+ };++ const findByVariableIds = async (+ variableIds: string[],+ tx?: Knex+ ): Promise<TAgentVaultServiceVariableReferences[]> => {+ if (!variableIds.length) return [];+ try {+ return (await (tx || db.replicaNode())(TableName.AgentVaultServiceVariableReference)+ .whereIn("variableId", variableIds)+ .select(+ selectAllTableCols(TableName.AgentVaultServiceVariableReference)+ )) as TAgentVaultServiceVariableReferences[];+ } catch (error) {+ throw new DatabaseError({ error, name: "Find agent vault variable references by variable" });+ }+ };++ return { ...orm, findByServiceIds, findByVariableIds };+};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.tsnew file mode 100644index 0000000000..c66065893c--- /dev/null+++ b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-variable-dal.ts@@ -0,0 +1,59 @@+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);++ const findByAccessBundleId = async (accessBundleId: string, tx?: Knex): Promise<TAgentVaultVariables[]> => {+ try {+ return (await (tx || db.replicaNode())(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. A service write maps keys to ids before it seals, outside its+ // transaction, and a variable created a moment earlier may not have reached a replica yet.+ 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" });+ }+ };++ const findValuesForResolve = async ({+ variableIds,+ accessBundleIds+ }: {+ variableIds: string[];+ accessBundleIds: string[];+ }): Promise<TAgentVaultVariableValueRow[]> => {+ if (!variableIds.length || !accessBundleIds.length) return [];+ try {+ return await db+ .replicaNode()(TableName.AgentVaultVariable)+ .whereIn("id", variableIds)+ .whereIn("accessBundleId", accessBundleIds)+ .select("id", "accessBundleId", "encryptedValue");+ } 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 d7e0c33369..36b418488d 100644--- a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.ts+++ b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.ts@@ -24,8 +24,10 @@ import { TOrgDALFactory } from "@app/services/org/org-dal";import { isUniqueViolation } from "../agent-vault/agent-vault-db-error-fns";import { AgentVaultCredentialType, AgentVaultTrafficPolicy } from "../agent-vault/agent-vault-enums";import { findReachableAccessBundleIds, liveGroupIdsFrom } from "../agent-vault/agent-vault-permission";+import { 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 { RESOURCE_TYPE_AGENT_VAULT_PROXY } from "../resource-auth-method/resource-auth-method-fns";@@ -54,6 +56,7 @@ type TAgentVaultProxyServiceFactoryDep = {agentVaultResolveDAL: TAgentVaultResolveDALFactory;agentVaultServiceCustomHeaderDAL: Pick<TAgentVaultServiceCustomHeaderDALFactory, "findByServiceIds">;agentVaultServiceSubstitutionDAL: Pick<TAgentVaultServiceSubstitutionDALFactory, "findByServiceIds">;+ agentVaultVariableDAL: Pick<TAgentVaultVariableDALFactory, "findValuesForResolve">;agentVaultSessionDAL: Pick<TAgentVaultSessionDALFactory, "findByTokenHash">;membershipDAL: Pick<TMembershipDALFactory, "findResourceMembershipsForActor">;orgDAL: Pick<TOrgDALFactory, "findEffectiveOrgMembership">;@@ -72,6 +75,7 @@ export const agentVaultProxyServiceFactory = ({agentVaultResolveDAL,agentVaultServiceCustomHeaderDAL,agentVaultServiceSubstitutionDAL,+ agentVaultVariableDAL,agentVaultSessionDAL,membershipDAL,orgDAL,@@ -313,6 +317,87 @@ export const agentVaultProxyServiceFactory = ({return { type: "basic", username: secret.username ?? "", password: secret.password ?? "" };};+ // The ids come out of the decrypted fields rather than the reference rows, so a service saved mid-poll can+ // never leave the two describing different versions of a field. An id with nothing behind it stays as text:+ // dropping the service instead would also drop its method and path restrictions.+ const $expandVariableReferences = async ({+ sessionId,+ services,+ accessBundleIdOf,+ decryptValue+ }: {+ sessionId: string;+ services: TResolvedService[];+ accessBundleIdOf: Map<string, string>;+ decryptValue: (encryptedValue: Buffer) => string;+ }): Promise<TResolvedService[]> => {+ const sealedTextsOf = ({ credential, customHeaders, substitutions }: TResolvedService) => [+ ...(credential.type === "bearer" ? [credential.value] : []),+ ...(credential.type === "basic" ? [credential.username, credential.password] : []),+ ...customHeaders.map((header) => header.value),+ ...substitutions.map((substitution) => substitution.value)+ ];++ const variableIds = [+ ...new Set(services.flatMap((service) => sealedTextsOf(service).flatMap(findStoredVariableIds)))+ ];+ if (!variableIds.length) return services;++ const variables = new Map(+ (+ await agentVaultVariableDAL.findValuesForResolve({+ variableIds,+ accessBundleIds: [...new Set(accessBundleIdOf.values())]+ })+ ).map((variable) => [variable.id, variable])+ );++ const opened = new Map<string, string>();+ const unresolvedServiceIds = new Set<string>();++ const expanded = services.map((service) => {+ const valueOf = (variableId: string) => {+ 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)) {+ unresolvedServiceIds.add(service.id);+ return undefined;+ }+ let value = opened.get(variableId);+ if (value === undefined) {+ value = decryptValue(variable.encryptedValue);+ opened.set(variableId, value);+ }+ return value;+ };+ const expand = (text: string) => expandStoredVariableReferences(text, valueOf);++ let { credential } = service;+ if (credential.type === "bearer") credential = { ...credential, value: expand(credential.value) };+ if (credential.type === "basic") {+ credential = { ...credential, username: expand(credential.username), password: expand(credential.password) };+ }++ return {+ ...service,+ credential,+ customHeaders: service.customHeaders.map((header) => ({ ...header, value: expand(header.value) })),+ substitutions: service.substitutions.map((substitution) => ({+ ...substitution,+ value: expand(substitution.value)+ }))+ };+ });++ if (unresolvedServiceIds.size) {+ logger.error(+ `agentVaultResolve: stored variable reference with no variable [sessionId=${sessionId}] [serviceIds=${[...unresolvedServiceIds].join(",")}]`+ );+ }++ return expanded;+ };+/** The only endpoint that decrypts a credential. The proxy's JWT authorizes; the session token is a selector. */const resolveSession = async ({ proxyId, orgId, sessionToken }: TResolveSessionDTO) => {const session = await agentVaultSessionDAL.findByTokenHash(hashSessionToken(sessionToken));@@ -417,7 +502,7 @@ export const agentVaultProxyServiceFactory = ({return (JSON.parse(decryptor({ cipherTextBlob: encryptedValue }).toString("utf-8")) as { value: string }).value;};- const services: TResolvedService[] = rows.map((row) => ({+ const decryptedServices: TResolvedService[] = rows.map((row) => ({id: row.id,name: row.name,accessBundleName: row.accessBundleName,@@ -437,6 +522,13 @@ export const agentVaultProxyServiceFactory = ({}))}));+ const services = await $expandVariableReferences({+ sessionId: session.id,+ services: decryptedServices,+ accessBundleIdOf: new Map(rows.map((row) => [row.id, row.accessBundleId])),+ decryptValue: $decryptValue+ });+logger.info(`agentVaultResolve: resolved [sessionId=${session.id}] [proxyId=${proxyId}] [services=${services.length}]`);diff --git a/backend/src/ee/services/agent-vault-proxy/agent-vault-resolve-dal.ts b/backend/src/ee/services/agent-vault-proxy/agent-vault-resolve-dal.tsindex 9728fc4129..f635534972 100644--- a/backend/src/ee/services/agent-vault-proxy/agent-vault-resolve-dal.ts+++ b/backend/src/ee/services/agent-vault-proxy/agent-vault-resolve-dal.ts@@ -9,6 +9,7 @@ export type TAgentVaultResolveDALFactory = ReturnType<typeof agentVaultResolveDAexport type TResolveServiceRow = {id: string;name: string;+ accessBundleId: string;accessBundleName: string;hostPattern: string;credentialType: string;@@ -69,6 +70,7 @@ export const agentVaultResolveDALFactory = (db: TDbClient) => {db.ref("encryptedCredential").withSchema(TableName.AgentVaultService),db.ref("allowedMethods").withSchema(TableName.AgentVaultService),db.ref("allowedPathPrefixes").withSchema(TableName.AgentVaultService),+ db.ref("accessBundleId").withSchema(TableName.AgentVaultService),// Resolve only reaches live bundles, so the current name is always the truthful one here.db.ref("name").withSchema(TableName.AgentVaultAccessBundle).as("accessBundleName"),db.ref("position").withSchema(TableName.AgentVaultSessionAccessBundle)diff --git a/backend/src/ee/services/agent-vault/CLAUDE.md b/backend/src/ee/services/agent-vault/CLAUDE.mdindex 64edb74115..9de7636cdd 100644--- a/backend/src/ee/services/agent-vault/CLAUDE.md+++ b/backend/src/ee/services/agent-vault/CLAUDE.md@@ -17,7 +17,7 @@ never in anything the agent holds.```agent-vault/ shared: enums, host grammar, conflict detection, reachability-agent-vault-access-bundle/ bundles, services, credential encryption, grants+agent-vault-access-bundle/ bundles, services, variables, credential encryption, grantsagent-vault-member/ product membership (list, add, role, remove)agent-vault-session/ mint, revoke, list, retention sweepagent-vault-project/ the per-org project's lazy bootstrap and resolver@@ -156,6 +156,37 @@ header" is the name in every layer; unqualified "header" means the credential's- A PATCH replaces the whole list. Omitting a row's `value` keeps what is sealed; every other fieldreplaces.+## 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+path 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+ boundary: a service write maps keys to ids before it seals (`toStoredVariableReferences`), reading the+ primary, since a variable created a moment earlier may not be on a replica yet. So a rename is one row.+- `agent_vault_service_variable_references` holds a row per field per variable. It drives Used By, the delete+ refusal, and `isWholeValue`, which is how the sheet shows `{{KEY}}` again for a value that never returns.+ **Resolve does not read it**: it pulls the ids out of the decrypted fields, so a service saved mid-poll can+ never leave the two describing different versions of a field.+- An update rebuilds the rows of only the values it wrote. An omitted value keeps its sealed text and its+ rows, a dropped header or substitution takes its rows through the foreign key, and a new credential type+ or pass-through clears both credential fields.+- 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.+- Every `{{...}}` in a value must be an existing, well-formed key, or the save fails. A malformed one is+ refused without quoting it, because the text was cut from a secret. Placeholders can't contain double+ braces. A variable's own value is sent as is and never expanded again, which is also how a service sends a+ literal `{{`.+- Resolve leaves an id with no variable behind as text and logs it 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.+ Every value is sealed; `isSecret` only decides whether the list returns it. The value route is a GET with+ no-store headers and one audit event per read.+## Credentials at rest- The KMS cipher pair is project-scoped (`KmsDataKey.SecretManager`) and built once per resolve.diff --git a/backend/src/ee/services/agent-vault/agent-vault-enums.ts b/backend/src/ee/services/agent-vault/agent-vault-enums.tsindex f227a5c8aa..1316ba44cb 100644--- a/backend/src/ee/services/agent-vault/agent-vault-enums.ts+++ b/backend/src/ee/services/agent-vault/agent-vault-enums.ts@@ -46,3 +46,11 @@ export enum AgentVaultSessionScope {Mine = "mine",All = "all"}++/** Which part of a service a variable reference sits in. A basic credential's password is its value. */+export enum AgentVaultVariableReferenceField {+ CredentialValue = "credential-value",+ CredentialUsername = "credential-username",+ CustomHeader = "custom-header",+ Substitution = "substitution"+}diff --git a/backend/src/ee/services/agent-vault/agent-vault-transformation-schemas.ts b/backend/src/ee/services/agent-vault/agent-vault-transformation-schemas.tsindex 495154b463..962ce24d83 100644--- a/backend/src/ee/services/agent-vault/agent-vault-transformation-schemas.ts+++ b/backend/src/ee/services/agent-vault/agent-vault-transformation-schemas.ts@@ -9,6 +9,7 @@ import {AGENT_VAULT_NO_CONTROL_CHARS_RE} from "./agent-vault-credential-schemas";import { AgentVaultSubstitutionSurface } from "./agent-vault-enums";+import { AGENT_VAULT_MALFORMED_REFERENCE_MESSAGE, hasMalformedVariableReference } from "./agent-vault-variable-fns";export const AGENT_VAULT_MAX_CUSTOM_HEADERS = 20;export const AGENT_VAULT_MAX_SUBSTITUTIONS = 20;@@ -46,19 +47,26 @@ const headerPrefixSchema = z.max(64).regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE);-const secretValueSchema = z- .string()- .min(1)- .max(8192)- .regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE);+// For every field a variable can be used in, so a mistyped reference fails the save, not the request.+export const acceptsVariableReferences = (schema: z.ZodString) =>+ schema.refine((value) => !hasMalformedVariableReference(value), AGENT_VAULT_MALFORMED_REFERENCE_MESSAGE);-// No minimum length: a short placeholder over-matches, but that is the author's own doing.+const secretValueSchema = acceptsVariableReferences(+ z.string().min(1).max(8192).regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)+);++// No minimum length: a short placeholder over-matches, but that is the author's own doing. No double braces,+// which would read as a variable reference to anyone looking at the service.const placeholderSchema = z.string().trim().min(1).max(255)- .regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE);+ .regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)+ .refine(+ (placeholder) => !placeholder.includes("{{") && !placeholder.includes("}}"),+ "A placeholder can't contain {{ or }}. Double braces are reserved for variable references."+ );const surfacesSchema = z.array(z.nativeEnum(AgentVaultSubstitutionSurface))diff --git a/backend/src/ee/services/agent-vault/agent-vault-variable-fns.test.ts b/backend/src/ee/services/agent-vault/agent-vault-variable-fns.test.tsnew file mode 100644index 0000000000..bcde3e45d3--- /dev/null+++ b/backend/src/ee/services/agent-vault/agent-vault-variable-fns.test.ts@@ -0,0 +1,140 @@+import { describe, expect, it } from "vitest";++import {+ expandStoredVariableReferences,+ findStoredVariableIds,+ findVariableKeys,+ hasMalformedVariableReference,+ isVariableKey,+ isWholeVariableReference,+ toStoredVariableReferences+} from "./agent-vault-variable-fns";++const GITHUB_ID = "0b8c3f4e-3f64-4a0e-9d3b-4f0f6a1c2d11";+const DATADOG_ID = "6f0e2a57-8c1d-4b2f-a9e3-1d2c3b4a5f66";++describe("agent vault variable references", () => {+ describe("keys", () => {+ it.each([["GITHUB_TOKEN"], ["A"], ["A1"], ["DD_API_KEY_2"]])("accepts %s", (key) => {+ expect(isVariableKey(key)).toBe(true);+ });++ it.each([+ ["github_token", "lower case"],+ ["1TOKEN", "leading digit"],+ ["_TOKEN", "leading underscore"],+ ["GITHUB-TOKEN", "dash"],+ ["GITHUB TOKEN", "space"],+ ["", "empty"]+ ])("rejects %s (%s)", (key) => {+ expect(isVariableKey(key)).toBe(false);+ });+ });++ describe("finding references", () => {+ it("finds each key once, in order", () => {+ expect(findVariableKeys("{{A}}:{{B}}-{{A}}")).toEqual(["A", "B"]);+ });++ it("ignores text without braces", () => {+ expect(findVariableKeys("plain-token")).toEqual([]);+ expect(hasMalformedVariableReference("plain-token")).toBe(false);+ });++ it.each([["{{github_token}}"], ["{{ GITHUB_TOKEN }}"], ["{{}}"], ["prefix-{{A}}-{{bad}}"]])(+ "reports %s as malformed",+ (text) => {+ expect(hasMalformedVariableReference(text)).toBe(true);+ }+ );++ it("reads the inner pair of a tripled brace", () => {+ expect(findVariableKeys("{{{A}}}")).toEqual(["A"]);+ expect(hasMalformedVariableReference("{{{A}}}")).toBe(false);+ });++ it("does not count a lone brace pair as a reference", () => {+ expect(hasMalformedVariableReference("{{ no closing")).toBe(false);+ expect(findVariableKeys("no opening }}")).toEqual([]);+ });+ });++ describe("whole references", () => {+ it.each([+ ["{{A}}", true],+ ["{{A}} ", false],+ ["Bearer {{A}}", false],+ ["{{A}}{{B}}", false],+ ["{{a}}", false]+ ])("%s is whole: %s", (text, expected) => {+ expect(isWholeVariableReference(text)).toBe(expected);+ });+ });++ describe("storing", () => {+ const idOfKey = new Map([+ ["GITHUB_TOKEN", GITHUB_ID],+ ["DD_API_KEY", DATADOG_ID]+ ]);++ it("names each variable by id", () => {+ expect(toStoredVariableReferences("{{GITHUB_TOKEN}}:{{DD_API_KEY}}:{{GITHUB_TOKEN}}", idOfKey)).toBe(+ `{{${GITHUB_ID}}}:{{${DATADOG_ID}}}:{{${GITHUB_ID}}}`+ );+ });++ it("leaves text around a reference alone", () => {+ expect(toStoredVariableReferences("token {{GITHUB_TOKEN}}!", idOfKey)).toBe(`token {{${GITHUB_ID}}}!`);+ });+ });++ describe("finding stored references", () => {+ it("finds each id once and skips anything that is not one", () => {+ expect(+ findStoredVariableIds(`{{${GITHUB_ID}}}:{{GITHUB_TOKEN}}:{{${GITHUB_ID}}}:{{not-a-uuid}}:{{${DATADOG_ID}}}`)+ ).toEqual([GITHUB_ID, DATADOG_ID]);+ });++ it("ignores an upper case uuid, which the database never produces", () => {+ expect(findStoredVariableIds(`{{${GITHUB_ID.toUpperCase()}}}`)).toEqual([]);+ });+ });++ describe("expanding", () => {+ const values: Record<string, string> = { [GITHUB_ID]: "ghp_alpha", [DATADOG_ID]: "dd_beta" };++ it("replaces every stored reference", () => {+ expect(expandStoredVariableReferences(`{{${GITHUB_ID}}}-{{${DATADOG_ID}}}`, (id) => values[id])).toBe(+ "ghp_alpha-dd_beta"+ );+ });++ it("keeps a value saved before variables existed exactly as it was, without looking it up", () => {+ const lookedUp: string[] = [];+ const expanded = expandStoredVariableReferences("{{GITHUB_TOKEN}} and {{lower}}", (id) => {+ lookedUp.push(id);+ return values[id];+ });+ expect(expanded).toBe("{{GITHUB_TOKEN}} and {{lower}}");+ expect(lookedUp).toEqual([]);+ });++ it("leaves a stored id with no variable behind it as text", () => {+ expect(expandStoredVariableReferences(`{{${GITHUB_ID}}}`, () => undefined)).toBe(`{{${GITHUB_ID}}}`);+ });++ it("does not expand braces inside a variable's own value", () => {+ expect(expandStoredVariableReferences(`{{${GITHUB_ID}}}`, () => `{{${DATADOG_ID}}}`)).toBe(`{{${DATADOG_ID}}}`);+ });++ it("inserts a value holding a replacement pattern literally", () => {+ expect(expandStoredVariableReferences(`{{${GITHUB_ID}}}`, () => "a$&b$1")).toBe("a$&b$1");+ });++ it("round-trips what the API accepted", () => {+ const idOfKey = new Map([["GITHUB_TOKEN", GITHUB_ID]]);+ const stored = toStoredVariableReferences("Bearer {{GITHUB_TOKEN}}", idOfKey);+ expect(expandStoredVariableReferences(stored, (id) => values[id])).toBe("Bearer ghp_alpha");+ });+ });+});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.tsnew file mode 100644index 0000000000..74157519d9--- /dev/null+++ b/backend/src/ee/services/agent-vault/agent-vault-variable-fns.ts@@ -0,0 +1,59 @@+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_VARIABLE_KEY_RE = new RE2(/^[A-Z][A-Z0-9_]*$/);++export const AGENT_VAULT_VARIABLE_KEY_MESSAGE =+ "A variable key starts with a letter and uses only upper case letters, numbers and underscores, like GITHUB_TOKEN.";++// Never quotes the offending text: it was cut from a secret field, and a 400's message is logged.+export const AGENT_VAULT_MALFORMED_REFERENCE_MESSAGE = `Double braces are reserved for variable references, like {{GITHUB_TOKEN}}. ${AGENT_VAULT_VARIABLE_KEY_MESSAGE}`;++// Every {{...}} counts as a reference, so a mistyped one fails the save instead of reaching a real host as+// literal text.+const REFERENCE_RE = new RE2(/\{\{([^{}]*)\}\}/g);+const WHOLE_REFERENCE_RE = new RE2(/^\{\{[A-Z][A-Z0-9_]*\}\}$/);+const STORED_REFERENCE_RE = new RE2(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/);++export const toVariableReference = (key: string) => `{{${key}}}`;++export const isVariableKey = (candidate: string) => AGENT_VAULT_VARIABLE_KEY_RE.test(candidate);++const findReferenceTokens = (text: string) => Array.from(text.matchAll(REFERENCE_RE), (match) => match[1]);++export const hasMalformedVariableReference = (text: string) =>+ findReferenceTokens(text).some((token) => !isVariableKey(token));++export const findVariableKeys = (text: string) => [+ ...new Set(findReferenceTokens(text).filter((token) => isVariableKey(token)))+];++/** A value that is one reference and nothing else holds no secret, so it can be returned on read. */+export const isWholeVariableReference = (text: string) => WHOLE_REFERENCE_RE.test(text);++/**+ * Sealed text names a variable by its id, not its key. The key form exists only at the API boundary, so a+ * rename touches one row, and resolve can never read a field and a key from either side of one.+ */+export const toStoredVariableReferences = (text: string, idOfKey: ReadonlyMap<string, string>) =>+ text.replace(REFERENCE_RE, (token: string, key: string) => {+ const id = idOfKey.get(key);+ return id ? toVariableReference(id) : token;+ });++// Only id-shaped tokens, so the lookup never hands Postgres a non-uuid and legacy literal braces never match.+export const findStoredVariableIds = (text: string) => [+ ...new Set(findReferenceTokens(text).filter((token) => STORED_REFERENCE_RE.test(token)))+];++/**+ * Anything that is not a known variable id stays as it was stored. A value saved before variables existed+ * can hold literal braces, and it has to keep reaching the host unchanged.+ */+export const expandStoredVariableReferences = (text: string, valueOfId: (variableId: string) => string | undefined) =>+ text.replace(REFERENCE_RE, (token: string, inner: string) =>+ STORED_REFERENCE_RE.test(inner) ? (valueOfId(inner) ?? token) : token+ );diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex 7d0c0e6bc0..6113f48991 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -777,6 +777,10 @@ export enum EventType {AGENT_VAULT_SERVICE_CREATE = "agent-vault-service-create",AGENT_VAULT_SERVICE_UPDATE = "agent-vault-service-update",AGENT_VAULT_SERVICE_DELETE = "agent-vault-service-delete",+ AGENT_VAULT_VARIABLE_CREATE = "agent-vault-variable-create",+ AGENT_VAULT_VARIABLE_UPDATE = "agent-vault-variable-update",+ AGENT_VAULT_VARIABLE_DELETE = "agent-vault-variable-delete",+ AGENT_VAULT_VARIABLE_VALUE_VIEW = "agent-vault-variable-value-view",AGENT_VAULT_MEMBER_ADD = "agent-vault-member-add",AGENT_VAULT_MEMBER_UPDATE = "agent-vault-member-update",AGENT_VAULT_MEMBER_REMOVE = "agent-vault-member-remove",@@ -6345,6 +6349,7 @@ interface AgentVaultServiceCreateEvent {// Names and placeholders only. A sealed value must never reach an audit row.customHeaderNames?: string[];substitutionPlaceholders?: string[];+ variableKeys?: string[];};}@@ -6365,6 +6370,8 @@ interface AgentVaultServiceUpdateEvent {substitutionPlaceholders?: string[];substitutionsReplaced?: string[];credentialReplaced: boolean;+ // Every key the service uses after the update, present when the update wrote a value that can hold one.+ variableKeys?: string[];};}@@ -6377,6 +6384,49 @@ interface AgentVaultServiceDeleteEvent {};}+// Keys and flags only. A variable's value never reaches an audit row, secret or not.+interface AgentVaultVariableCreateEvent {+ type: EventType.AGENT_VAULT_VARIABLE_CREATE;+ metadata: {+ accessBundleId: string;+ variableId: string;+ key: string;+ isSecret: boolean;+ };+}++interface AgentVaultVariableUpdateEvent {+ type: EventType.AGENT_VAULT_VARIABLE_UPDATE;+ metadata: {+ accessBundleId: string;+ variableId: string;+ key: string;+ // The previous* fields are present only when the update changed them.+ previousKey?: string;+ isSecret: boolean;+ previousIsSecret?: boolean;+ valueReplaced: boolean;+ };+}++interface AgentVaultVariableDeleteEvent {+ type: EventType.AGENT_VAULT_VARIABLE_DELETE;+ metadata: {+ accessBundleId: string;+ variableId: string;+ key: string;+ };+}++interface AgentVaultVariableValueViewEvent {+ type: EventType.AGENT_VAULT_VARIABLE_VALUE_VIEW;+ metadata: {+ accessBundleId: string;+ variableId: string;+ key: string;+ };+}+interface AgentVaultProductMemberAddEvent {type: EventType.AGENT_VAULT_MEMBER_ADD;metadata: {@@ -8332,6 +8382,10 @@ export type Event =| AgentVaultServiceCreateEvent| AgentVaultServiceUpdateEvent| AgentVaultServiceDeleteEvent+ | AgentVaultVariableCreateEvent+ | AgentVaultVariableUpdateEvent+ | AgentVaultVariableDeleteEvent+ | AgentVaultVariableValueViewEvent| AgentVaultProductMemberAddEvent| AgentVaultProductMemberUpdateEvent| AgentVaultProductMemberRemoveEventdiff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex ade7d211b5..c87e5be6e0 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -4296,7 +4296,27 @@ export const AGENT_VAULT = {"The fake value your agent already sends. The proxy replaces it with the real secret. Matched as a plain string, so a distinctive placeholder is worth choosing.",surfaces: "Where in the request to look for the placeholder: path, query, header or body.",substitutionValue: "The real value the placeholder is replaced with. Never returned once saved.",- updateSubstitutionValue: "The real value the placeholder is replaced with. Omit to keep the value already stored."+ updateSubstitutionValue: "The real value the placeholder is replaced with. Omit to keep the value already stored.",+ variableReferences: "The variables this service's credential, custom header values and substitution values use.",+ referenceField:+ "Which value uses the variable: credential-value (a bearer token or a basic password), credential-username, custom-header or substitution.",+ referenceCustomHeaderId: "The custom header whose value uses the variable.",+ referenceSubstitutionId: "The substitution whose value uses the variable.",+ referenceIsWholeValue: "Whether the value is this variable and nothing else."+ },+ VARIABLE: {+ variableId: "The ID of the variable.",+ key: "The name services use to refer to the variable, as {{KEY}}. Starts with a letter and uses only upper case letters, numbers and underscores.",+ value: "The value the proxy puts in place of each {{KEY}}.",+ updateValue: "The value the proxy puts in place of each {{KEY}}. Omit to keep the stored value.",+ isSecret: "Whether the value is hidden once saved. A secret value is only returned by the value endpoint.",+ listedValue:+ "The value, for a variable that is not secret. Null for a secret one: read it from the value endpoint.",+ 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.",+ updatedAt: "When the variable was last changed."},MEMBER: {memberId: "The ID of the access bundle membership.",diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex bf6ea352e4..d263d1af23 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -29,6 +29,8 @@ import { agentVaultAccessBundleServiceFactory } from "@app/ee/services/agent-vauimport { agentVaultServiceCustomHeaderDALFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-service-custom-header-dal";import { agentVaultServiceDALFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-service-dal";import { agentVaultServiceSubstitutionDALFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-service-substitution-dal";+import { 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";@@ -1869,6 +1871,8 @@ export const registerRoutes = async (const agentVaultServiceDAL = agentVaultServiceDALFactory(db);const agentVaultServiceCustomHeaderDAL = agentVaultServiceCustomHeaderDALFactory(db);const agentVaultServiceSubstitutionDAL = agentVaultServiceSubstitutionDALFactory(db);+ const agentVaultVariableDAL = agentVaultVariableDALFactory(db);+ const agentVaultServiceVariableReferenceDAL = agentVaultServiceVariableReferenceDALFactory(db);const agentVaultSessionDAL = agentVaultSessionDALFactory(db);const agentVaultSessionAccessBundleDAL = agentVaultSessionAccessBundleDALFactory(db);const agentVaultProxyDAL = agentVaultProxyDALFactory(db);@@ -1879,6 +1883,8 @@ export const registerRoutes = async (agentVaultServiceDAL,agentVaultServiceCustomHeaderDAL,agentVaultServiceSubstitutionDAL,+ agentVaultVariableDAL,+ agentVaultServiceVariableReferenceDAL,permissionService,kmsService,membershipDAL,@@ -2001,6 +2007,7 @@ export const registerRoutes = async (agentVaultResolveDAL,agentVaultServiceCustomHeaderDAL,agentVaultServiceSubstitutionDAL,+ agentVaultVariableDAL,agentVaultSessionDAL,membershipDAL,orgDAL,diff --git a/docs/api-reference/endpoints/agent-vault-variables/create.mdx b/docs/api-reference/endpoints/agent-vault-variables/create.mdxnew file mode 100644index 0000000000..343d5651ff--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-variables/create.mdx@@ -0,0 +1,4 @@+---+title: "Create variable"+openapi: "POST /api/v1/agent-vault/access-bundles/{accessBundleId}/variables"+---diff --git a/docs/api-reference/endpoints/agent-vault-variables/delete.mdx b/docs/api-reference/endpoints/agent-vault-variables/delete.mdxnew file mode 100644index 0000000000..9f2fc9372b--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-variables/delete.mdx@@ -0,0 +1,4 @@+---+title: "Delete variable"+openapi: "DELETE /api/v1/agent-vault/access-bundles/{accessBundleId}/variables/{variableId}"+---diff --git a/docs/api-reference/endpoints/agent-vault-variables/get-value.mdx b/docs/api-reference/endpoints/agent-vault-variables/get-value.mdxnew file mode 100644index 0000000000..50edba8d35--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-variables/get-value.mdx@@ -0,0 +1,4 @@+---+title: "Get variable value"+openapi: "GET /api/v1/agent-vault/access-bundles/{accessBundleId}/variables/{variableId}/value"+---diff --git a/docs/api-reference/endpoints/agent-vault-variables/list.mdx b/docs/api-reference/endpoints/agent-vault-variables/list.mdxnew file mode 100644index 0000000000..be001f38f2--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-variables/list.mdx@@ -0,0 +1,4 @@+---+title: "List variables"+openapi: "GET /api/v1/agent-vault/access-bundles/{accessBundleId}/variables"+---diff --git a/docs/api-reference/endpoints/agent-vault-variables/update.mdx b/docs/api-reference/endpoints/agent-vault-variables/update.mdxnew file mode 100644index 0000000000..05631ecd65--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-variables/update.mdx@@ -0,0 +1,4 @@+---+title: "Update variable"+openapi: "PATCH /api/v1/agent-vault/access-bundles/{accessBundleId}/variables/{variableId}"+---diff --git a/docs/docs.json b/docs/docs.jsonindex 58b1d46503..dd3f0e1676 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -798,6 +798,7 @@"pages": ["documentation/platform/agent-vault/access-bundles","documentation/platform/agent-vault/services",+ "documentation/platform/agent-vault/variables","documentation/platform/agent-vault/sessions","documentation/platform/agent-vault/proxies","documentation/platform/agent-vault/access-control"@@ -4383,6 +4384,16 @@"api-reference/endpoints/agent-vault-services/delete"]},+ {+ "group": "Variables",+ "pages": [+ "api-reference/endpoints/agent-vault-variables/list",+ "api-reference/endpoints/agent-vault-variables/create",+ "api-reference/endpoints/agent-vault-variables/update",+ "api-reference/endpoints/agent-vault-variables/delete",+ "api-reference/endpoints/agent-vault-variables/get-value"+ ]+ },{"group": "Access bundle members","pages": [diff --git a/docs/documentation/platform/agent-vault/access-control.mdx b/docs/documentation/platform/agent-vault/access-control.mdxindex 23afd18e25..7d5762b240 100644--- a/docs/documentation/platform/agent-vault/access-control.mdx+++ b/docs/documentation/platform/agent-vault/access-control.mdx@@ -25,7 +25,7 @@ Agent Vault has one member list for your whole organization, instead of one per| Role | What they can do ||------|------------------|-| **Admin** | <ul><li>Create and manage access bundles, services, and proxies</li><li>Grant access bundles</li><li>Manage membership</li><li>Read audit logs</li></ul> |+| **Admin** | <ul><li>Create and manage access bundles, services, variables, and proxies</li><li>Grant access bundles</li><li>Manage membership</li><li>Read audit logs</li></ul> || **Member** | <ul><li>Create sessions with the access bundles granted to them</li><li>Revoke their own sessions</li></ul> |An admin can use every access bundle without a grant. A member can't use an access bundle until an admin grants it, and only sees the bundles granted to them. On the **Sessions** page, members see their own sessions, and admins can switch between **All Sessions** and **My Sessions**.diff --git a/docs/documentation/platform/agent-vault/overview.mdx b/docs/documentation/platform/agent-vault/overview.mdxindex adcc8a835c..3f071f1fcc 100644--- a/docs/documentation/platform/agent-vault/overview.mdx+++ b/docs/documentation/platform/agent-vault/overview.mdx@@ -31,6 +31,9 @@ Infisical Agent Vault is an access layer for AI agents. It securely equips agent<Card title="Services" icon="plug" href="/documentation/platform/agent-vault/services">External APIs that an AI agent can securely call during a session.</Card>+ <Card title="Variables" icon="braces" href="/documentation/platform/agent-vault/variables">+ Values stored once in an access bundle that any of its services can use.+ </Card><Card title="Sessions" icon="monitor" href="/documentation/platform/agent-vault/sessions">Time-bound grants that let AI agents access services without holding real credentials.</Card>diff --git a/docs/documentation/platform/agent-vault/services.mdx b/docs/documentation/platform/agent-vault/services.mdxindex 7d2c6c96a1..45855bf068 100644--- a/docs/documentation/platform/agent-vault/services.mdx+++ b/docs/documentation/platform/agent-vault/services.mdx@@ -32,6 +32,8 @@ To add a service to an access bundle:</Step><Step>Follow the steps and paste your credentials in the **Credential** section.++ To use a value that several services share, type `{{` in a credential field and pick a [variable](/documentation/platform/agent-vault/variables).</Step><Step>Select **Add Service**. The service appears in the bundle's list.diff --git a/docs/documentation/platform/agent-vault/variables.mdx b/docs/documentation/platform/agent-vault/variables.mdxnew file mode 100644index 0000000000..1f7c6f4fa2--- /dev/null+++ b/docs/documentation/platform/agent-vault/variables.mdx@@ -0,0 +1,100 @@+---+title: "Variables"+description: "Values stored once in an access bundle that any of its services can use."+---++<Info>+ This page is for Agent Vault admins. Members can't see or change variables. [Learn more about roles →](/documentation/platform/agent-vault/access-control#product-membership)+</Info>++A variable is a value stored once in an [access bundle](/documentation/platform/agent-vault/access-bundles) under a key, such as `GITHUB_TOKEN`. Any [service](/documentation/platform/agent-vault/services) in the bundle can use the variable through a reference, which is the key in double braces: `{{GITHUB_TOKEN}}`. Before the [proxy](/documentation/platform/agent-vault/proxies) forwards a request, it replaces each reference with the variable's value.++For example, if several services send the same GitHub token, store the token as `GITHUB_TOKEN` and write `{{GITHUB_TOKEN}}` in each service. When the token changes, you update one variable instead of every service.++## Add a variable++To add a variable to an access bundle:++<Steps>+ <Step>+ In Agent Vault, go to **Access Bundles** and select your access bundle.+ </Step>+ <Step>+ Under **Variables**, select **Add Variable**.+ </Step>+ <Step>+ Enter a **Key** and a **Value**.++ A key starts with a letter and uses only upper case letters, numbers, and underscores. Each key is unique within its access bundle. As you type the key, Infisical changes lower case letters to upper case, and spaces and dashes to underscores.+ </Step>+ <Step>+ Leave **Secret** selected to hide the value once you save it. If the value isn't sensitive, such as an organization ID, clear **Secret** so the value stays visible in the list.+ </Step>+ <Step>+ Select **Add Variable**. The variable appears in the **Variables** list.+ </Step>+</Steps>++## Use a variable in a service++A variable works in any value a service sends: the **Token** of a Bearer credential, the **Username** and **Password** of a Basic credential, the **Value** of a custom header, and the **With** value of a substitution.++To use a variable:++<Steps>+ <Step>+ [Add a service](/documentation/platform/agent-vault/services#add-a-service), or open an existing service's actions menu and select **Edit**. Then go to the **Credential** step.+ </Step>+ <Step>+ In a field that accepts variables, type `{{`. A list of the bundle's variables opens.+ </Step>+ <Step>+ Select a variable, or pick one with the arrow keys and press `Enter`. Infisical inserts the reference, such as `{{GITHUB_TOKEN}}`.++ If the variable doesn't exist yet, finish typing its key and select **Create** at the end of the list. Infisical opens **Add Variable** with the key filled in, and inserts the reference once you save the variable.+ </Step>+</Steps>++A reference can be the whole value or part of it. For example, if a custom header's value is `org-{{ORG_ID}}`, the proxy sends `org-` followed by the value of `ORG_ID`.++The **Sends** preview shows each reference in the headers the proxy attaches. If a reference names a key the bundle doesn't have, Infisical marks the reference in red and won't save the service until you correct the key or add the variable.++Variables don't work in any other field, such as a host pattern, a path, a header name or prefix, or a substitution placeholder.++When you edit a service later, Infisical shows the reference in each field that holds only a reference. If a field mixes a reference with other text, the field stays hidden, like any other stored credential.++## Change or delete a variable++To change a variable, open its actions menu in the **Variables** list and select **Edit**. You can change the key, the value, and whether the value is secret. If the variable is secret, leave **Value** blank to keep the current value.++If you rename a variable, every service that uses it keeps working without any changes. If you change a value, running agents get the new value within one [poll interval](/documentation/platform/agent-vault/proxies#poll-interval), without a restart.++To delete a variable, open its actions menu and select **Delete**. If any service still uses the variable, Infisical lists those services and won't delete the variable until you remove the reference from each one.++## Secret values++Infisical encrypts every variable's value. **Secret** only controls whether the **Variables** list shows the value:++- A secret value is hidden (select the eye icon next to the value to reveal it)+- A value that isn't secret appears in the list as plain text++The [endpoint that lists variables](/api-reference/endpoints/agent-vault-variables/list) also returns only the values that aren't secret. To read a secret value from the API, call [the endpoint that gets a variable's value](/api-reference/endpoints/agent-vault-variables/get-value).++Infisical writes an audit event each time someone reveals a value, and each time someone creates, updates, or deletes a variable. The events record the key and what changed, but never the value. To review the events, open **Audit Logs** in Agent Vault, or scope an [audit log stream](/documentation/platform/audit-log-streams/audit-log-streams) to the Agent Vault product.++## Double braces in a value++In a field that accepts variables, Infisical treats every pair of double braces as a reference. If the braces enclose anything other than a valid key, such as `{{my token}}`, Infisical won't save the service.++If an API expects literal double braces in a value, save that text as the value of a variable and use the variable instead. The proxy sends a variable's value exactly as you saved it, without looking for references in it.++## Next steps++<CardGroup cols={2}>+ <Card title="Services" icon="plug" href="/documentation/platform/agent-vault/services">+ Configure the external APIs that use your variables.+ </Card>+ <Card title="Sessions" icon="monitor" href="/documentation/platform/agent-vault/sessions">+ Create a session to run an agent with the access bundle.+ </Card>+</CardGroup>diff --git a/frontend/src/components/agent-vault/VariableFormDialog.tsx b/frontend/src/components/agent-vault/VariableFormDialog.tsxnew file mode 100644index 0000000000..ba0b748f12--- /dev/null+++ b/frontend/src/components/agent-vault/VariableFormDialog.tsx@@ -0,0 +1,296 @@+import { useEffect, useMemo, useState } from "react";+import { Controller, useForm, useWatch } from "react-hook-form";+import { zodResolver } from "@hookform/resolvers/zod";+import { EyeIcon, EyeOffIcon } from "lucide-react";+import { z } from "zod";++import { createNotification } from "@app/components/notifications";+import {+ Button,+ Checkbox,+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ Field,+ FieldContent,+ FieldDescription,+ FieldError,+ FieldLabel,+ Input,+ InputGroup,+ InputGroupAddon,+ InputGroupButton,+ InputGroupInput,+ Label+} from "@app/components/v3";+import {+ normalizeVariableKey,+ toVariableReference,+ VARIABLE_KEY_MAX_LENGTH,+ VARIABLE_KEY_MESSAGE,+ VARIABLE_KEY_RE,+ VARIABLE_VALUE_MAX_LENGTH+} from "@app/helpers/agentVaultVariables";+import {+ useCreateAgentVaultVariable,+ useUpdateAgentVaultVariable+} from "@app/hooks/api/agentVault";+import { TAgentVaultVariable } from "@app/hooks/api/agentVault/types";++// eslint-disable-next-line no-control-regex+const NO_CONTROL_CHARS_RE = /^[^\x00-\x1f\x7f]*$/;++// A stored secret never comes back, so on edit its field starts empty and empty keeps it. A value that is+// not secret starts filled in, and emptying it is a mistake rather than a way to keep it.+const buildSchema = (takenKeys: string[], isValueRequired: boolean) =>+ z.object({+ key: z+ .string()+ .min(1, "Required")+ .max(VARIABLE_KEY_MAX_LENGTH, `A key can be at most ${VARIABLE_KEY_MAX_LENGTH} characters.`)+ .regex(VARIABLE_KEY_RE, VARIABLE_KEY_MESSAGE)+ .refine(+ (key) => !takenKeys.includes(key),+ "This bundle already has a variable with this key."+ ),+ value: z+ .string()+ .max(+ VARIABLE_VALUE_MAX_LENGTH,+ `A value can be at most ${VARIABLE_VALUE_MAX_LENGTH} characters.`+ )+ .regex(+ NO_CONTROL_CHARS_RE,+ "A value can't contain line breaks or other control characters. Check for a stray newline if you pasted it."+ )+ .refine((value) => !isValueRequired || value.length > 0, "Required"),+ isSecret: z.boolean()+ });++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;+ onCloseAutoFocus?: (event: Event) => void;+};++export const VariableFormDialog = ({+ isOpen,+ onOpenChange,+ accessBundleId,+ variable,+ existingKeys,+ usedByCount = 0,+ initialKey,+ onCreated,+ onCloseAutoFocus+}: Props) => {+ const createVariable = useCreateAgentVaultVariable();+ const updateVariable = useUpdateAgentVaultVariable();+ const isUpdate = Boolean(variable);+ const [isValueVisible, setIsValueVisible] = useState(false);++ const schema = useMemo(+ () =>+ buildSchema(+ existingKeys.filter((key) => key !== variable?.key),+ !variable || !variable.isSecret+ ),+ [existingKeys, variable]+ );++ const {+ control,+ handleSubmit,+ reset,+ setFocus,+ formState: { isDirty, isSubmitting }+ } = useForm<FormData>({ resolver: zodResolver(schema) });++ const key = useWatch({ control, name: "key" });+ const isSecret = useWatch({ control, name: "isSecret" });+ const isRenaming = Boolean(variable) && Boolean(key) && key !== variable?.key;++ useEffect(() => {+ if (!isOpen) return;+ reset({+ key: variable?.key ?? initialKey ?? "",+ value: variable && !variable.isSecret ? (variable.value ?? "") : "",+ isSecret: variable?.isSecret ?? true+ });+ setIsValueVisible(false);+ }, [isOpen, variable, initialKey, reset]);++ const onSubmit = async (data: FormData) => {+ try {+ if (variable) {+ const isValueChanged = variable.isSecret+ ? data.value.length > 0+ : data.value !== (variable.value ?? "");+ await updateVariable.mutateAsync({+ accessBundleId,+ variableId: variable.id,+ key: data.key === variable.key ? undefined : data.key,+ value: isValueChanged ? data.value : undefined,+ isSecret: data.isSecret === variable.isSecret ? undefined : data.isSecret+ });+ createNotification({ text: `Variable "${data.key}" updated`, type: "success" });+ } else {+ const created = await createVariable.mutateAsync({+ accessBundleId,+ key: data.key,+ value: data.value,+ isSecret: data.isSecret+ });+ onCreated?.(created);+ createNotification({ text: `Variable "${data.key}" created`, type: "success" });+ }+ onOpenChange(false);+ } catch {+ // A failed request returns a 4xx that the global request handler surfaces as a toast+ }+ };++ const isMasked = isSecret && !isValueVisible;++ return (+ <Dialog open={isOpen} onOpenChange={onOpenChange}>+ <DialogContent+ // A key that arrives filled in leaves the value as the one thing left to type.+ onOpenAutoFocus={(event) => {+ if (!initialKey) return;+ event.preventDefault();+ setFocus("value");+ }}+ onCloseAutoFocus={onCloseAutoFocus}+ >+ <DialogHeader>+ <DialogTitle>{isUpdate ? "Edit Variable" : "Add Variable"}</DialogTitle>+ <DialogDescription>+ Store a value once and use it from any service in this bundle.+ </DialogDescription>+ </DialogHeader>++ <form onSubmit={handleSubmit(onSubmit)} className="flex flex-col gap-4">+ <Controller+ control={control}+ name="key"+ render={({ field, fieldState }) => (+ <Field>+ <FieldLabel>Key</FieldLabel>+ <FieldContent>+ <Input+ {...field}+ onChange={(event) => field.onChange(normalizeVariableKey(event.target.value))}+ placeholder="GITHUB_TOKEN"+ autoComplete="off"+ spellCheck={false}+ className="font-mono"+ isError={Boolean(fieldState.error)}+ />+ <FieldDescription>+ {isRenaming && usedByCount > 0 ? (+ <>+ {usedByCount === 1+ ? "The service that uses it keeps working"+ : `The ${usedByCount} services that use it keep working`}{" "}+ under the new key.+ </>+ ) : (+ <>+ Services use it as{" "}+ <code className="font-mono">{toVariableReference(key || "KEY")}</code>.+ </>+ )}+ </FieldDescription>+ <FieldError>{fieldState.error?.message}</FieldError>+ </FieldContent>+ </Field>+ )}+ />+ <Controller+ control={control}+ name="value"+ render={({ field, fieldState }) => (+ <Field>+ <FieldLabel>Value</FieldLabel>+ <FieldContent>+ <InputGroup>+ <InputGroupInput+ {...field}+ type={isMasked ? "password" : "text"}+ placeholder={+ variable?.isSecret+ ? "Leave blank to keep the current value"+ : "Enter the value"+ }+ autoComplete="off"+ spellCheck={false}+ isError={Boolean(fieldState.error)}+ />+ {isSecret && (+ <InputGroupAddon align="inline-end">+ <InputGroupButton+ isDisabled={!field.value}+ aria-label={isValueVisible ? "Hide value" : "Show value"}+ onClick={() => setIsValueVisible((prev) => !prev)}+ >+ {isValueVisible ? <EyeOffIcon /> : <EyeIcon />}+ </InputGroupButton>+ </InputGroupAddon>+ )}+ </InputGroup>+ <FieldError>{fieldState.error?.message}</FieldError>+ </FieldContent>+ </Field>+ )}+ />+ <Controller+ control={control}+ name="isSecret"+ render={({ field }) => (+ <Field orientation="horizontal">+ <Checkbox+ id="agent-vault-variable-secret"+ variant="av"+ isChecked={field.value}+ onCheckedChange={(checked) => field.onChange(checked === true)}+ />+ <FieldContent>+ <Label htmlFor="agent-vault-variable-secret">Secret</Label>+ <FieldDescription>Hide the value after saving.</FieldDescription>+ </FieldContent>+ </Field>+ )}+ />++ <DialogFooter>+ <Button type="button" variant="ghost" onClick={() => onOpenChange(false)}>+ Cancel+ </Button>+ <Button+ type="submit"+ variant="av"+ isPending={isSubmitting}+ isDisabled={isUpdate && !isDirty}+ >+ {isUpdate ? "Save" : "Add Variable"}+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ );+};diff --git a/frontend/src/components/agent-vault/service-sheet/CredentialFields.tsx b/frontend/src/components/agent-vault/service-sheet/CredentialFields.tsxindex 10171e6f44..3706a9e17c 100644--- a/frontend/src/components/agent-vault/service-sheet/CredentialFields.tsx+++ b/frontend/src/components/agent-vault/service-sheet/CredentialFields.tsx@@ -1,4 +1,4 @@-import { useEffect, useState } from "react";+import { useEffect, useLayoutEffect, useRef, useState } from "react";import { Controller, ControllerRenderProps, useFormContext } from "react-hook-form";import { EyeIcon, EyeOffIcon, XIcon } from "lucide-react";@@ -6,7 +6,6 @@ import {Alert,AlertDescription,AlertTitle,- CodeBlock,Field,FieldContent,FieldError,@@ -22,9 +21,18 @@ import {SelectTrigger,SelectValue} from "@app/components/v3";+import { cn } from "@app/components/v3/utils";+import { isVariableReferenceOnly } from "@app/helpers/agentVaultVariables";import { AgentVaultCredentialType } from "@app/hooks/api/agentVault";+import { SendsPreview } from "./SendsPreview";import { CREDENTIAL_LABELS, TServiceForm, UNCHANGED_SECRET } from "./serviceSchema";+import { useServiceVariables } from "./ServiceVariablesContext";+import {+ ReferenceHighlights,+ useVariableAutocomplete,+ VariableSuggestions+} from "./VariableReferenceInput";export const credentialPreview = (form: {@@ -47,6 +55,9 @@ type SecretName =| `customHeaders.${number}.value`| `substitutions.${number}.value`;+// Keys the input handles itself while suggestions are open, so they must not re-read the caret after.+const SUGGESTION_KEYS = new Set(["ArrowUp", "ArrowDown", "Enter", "Tab", "Escape"]);+export const SecretInput = <TName extends SecretName>({field,label,@@ -55,7 +66,8 @@ export const SecretInput = <TName extends SecretName>({isError,isUntouched,hasStoredSecret,- canBeCleared+ canBeCleared,+ storedValue}: {field: ControllerRenderProps<TServiceForm, TName>;label: string;@@ -69,64 +81,135 @@ export const SecretInput = <TName extends SecretName>({hasStoredSecret: boolean;/** Whether empty is a value this field can hold. Only such a field offers the clear button. */canBeCleared: boolean;+ /** A stored value that is one variable reference, which the field shows in place of the sentinel. */+ storedValue?: string;}) => {const { setFocus } = useFormContext<TServiceForm>();const [isVisible, setIsVisible] = useState(false);const [isCleared, setIsCleared] = useState(false);+ const inputRef = useRef<HTMLInputElement | null>(null);+ const overlayRef = useRef<HTMLDivElement | null>(null);+ // Where the caret goes after a suggestion is picked. The value is set first, and setting it moves the+ // caret to the end.+ const caretRef = useRef<number | null>(null);++ const value = field.value ?? "";+ const isReferenceOnly = !isUntouched && isVariableReferenceOnly(value);+ // The sentinel must never render as text, and a lone reference holds no secret.+ const isShown = (isVisible && !isUntouched) || isReferenceOnly;+ const isHighlighted = isShown && value.includes("{{");++ const autocomplete = useVariableAutocomplete({+ inputRef,+ onInsert: (next, caret) => {+ setIsCleared(false);+ field.onChange(next);+ caretRef.current = caret;+ setIsVisible(true);+ }+ });// The sheet is not unmounted between opens, so the flag has to follow the value back to the sentinel.useEffect(() => {if (isUntouched) setIsCleared(false);}, [isUntouched]);+ // A value that starts as a reference stays readable as text is typed around it.+ useEffect(() => {+ if (isReferenceOnly) setIsVisible(true);+ }, [isReferenceOnly]);++ const syncOverlay = () => {+ if (overlayRef.current && inputRef.current) {+ overlayRef.current.scrollLeft = inputRef.current.scrollLeft;+ }+ };++ useLayoutEffect(() => {+ const caret = caretRef.current;+ if (caret !== null && inputRef.current) {+ caretRef.current = null;+ inputRef.current.setSelectionRange(caret, caret);+ }+ syncOverlay();+ });+const lowerLabel = label.toLowerCase();return (- <InputGroup>- <InputGroupInput- {...field}- aria-label={ariaLabel}- type={isVisible ? "text" : "password"}- onChange={(event) => {- setIsCleared(false);- field.onChange(event);- }}- onFocus={() => {- if (isUntouched) field.onChange("");- }}- // Empty reads the same whether the secret was meant to go or the field was only clicked into,- // so the clear button is made the one way to say it and passing through loses nothing.- onBlur={() => {- if (hasStoredSecret && !field.value && !isCleared) field.onChange(UNCHANGED_SECRET);- field.onBlur();- }}- placeholder={placeholder}- isError={isError}- />- <InputGroupAddon align="inline-end">- {canBeCleared && hasStoredSecret && (- <InputGroupButton- isDisabled={isCleared}- aria-label={`Clear ${lowerLabel}`}- onClick={() => {- setIsCleared(true);- field.onChange("");- setFocus(field.name);+ <VariableSuggestions autocomplete={autocomplete}>+ <InputGroup>+ <div className="relative flex min-w-0 flex-1 items-center self-stretch">+ {isHighlighted && <ReferenceHighlights value={value} overlayRef={overlayRef} />}+ <InputGroupInput+ {...field}+ ref={(element) => {+ field.ref(element);+ inputRef.current = element;}}+ aria-label={ariaLabel}+ role="combobox"+ aria-autocomplete="list"+ aria-expanded={autocomplete.isOpen}+ aria-controls={autocomplete.isOpen ? autocomplete.listId : undefined}+ aria-activedescendant={autocomplete.activeOptionId}+ type={isShown ? "text" : "password"}+ className={cn(isHighlighted && "text-transparent caret-foreground")}+ onChange={(event) => {+ setIsCleared(false);+ // An emptied field masks again, since what is typed next may be a real secret.+ if (!event.target.value) setIsVisible(false);+ field.onChange(event);+ autocomplete.refresh();+ }}+ onKeyDown={autocomplete.onKeyDown}+ onKeyUp={(event) => {+ if (!SUGGESTION_KEYS.has(event.key)) autocomplete.refresh();+ }}+ onClick={autocomplete.refresh}+ onSelect={syncOverlay}+ onScroll={syncOverlay}+ onFocus={() => {+ if (isUntouched) field.onChange("");+ }}+ // Empty reads the same whether the secret was meant to go or the field was only clicked into,+ // so the clear button is made the one way to say it and passing through loses nothing.+ onBlur={() => {+ autocomplete.close();+ if (hasStoredSecret && !field.value && !isCleared) {+ field.onChange(storedValue ?? UNCHANGED_SECRET);+ }+ field.onBlur();+ }}+ placeholder={placeholder}+ isError={isError}+ />+ </div>+ <InputGroupAddon align="inline-end">+ {canBeCleared && hasStoredSecret && (+ <InputGroupButton+ isDisabled={isCleared}+ aria-label={`Clear ${lowerLabel}`}+ onClick={() => {+ setIsCleared(true);+ field.onChange("");+ setFocus(field.name);+ }}+ >+ <XIcon />+ </InputGroupButton>+ )}+ <InputGroupButton+ // A stored credential is never returned, so until it is replaced there is nothing to reveal.+ isDisabled={isUntouched || !field.value || isReferenceOnly}+ aria-label={`${isVisible ? "Hide" : "Show"} ${lowerLabel}`}+ onClick={() => setIsVisible((prev) => !prev)}>- <XIcon />+ {isVisible ? <EyeOffIcon /> : <EyeIcon />}</InputGroupButton>- )}- <InputGroupButton- // A stored credential is never returned, so until it is replaced there is nothing to reveal.- isDisabled={isUntouched || !field.value}- aria-label={`${isVisible ? "Hide" : "Show"} ${lowerLabel}`}- onClick={() => setIsVisible((prev) => !prev)}- >- {isVisible ? <EyeOffIcon /> : <EyeIcon />}- </InputGroupButton>- </InputGroupAddon>- </InputGroup>+ </InputGroupAddon>+ </InputGroup>+ </VariableSuggestions>);};@@ -136,11 +219,10 @@ type Props = {export const CredentialFields = ({ storedType }: Props) => {const { control, watch, setValue } = useFormContext<TServiceForm>();+ const { seeded } = useServiceVariables();const credentialType = watch("credentialType");const secret = watch("secret");const username = watch("username");- const headerName = watch("headerName");- const headerPrefix = watch("headerPrefix");const isBasic = credentialType === AgentVaultCredentialType.Basic;const isUntouched = secret === UNCHANGED_SECRET;@@ -165,11 +247,14 @@ export const CredentialFields = ({ storedType }: Props) => {<SecretInputfield={field}label={isBasic ? "Password" : "Token"}- placeholder={isBasic ? "Enter the password" : "Enter the token"}+ placeholder={+ isBasic ? "Enter the password, or type {{" : "Enter the token, or type {{"+ }isError={Boolean(fieldState.error)}isUntouched={isUntouched}hasStoredSecret={hasStoredSecret}canBeCleared={isBasic}+ storedValue={hasStoredSecret ? seeded.secret : undefined}/><FieldError>{fieldState.error?.message}</FieldError></FieldContent>@@ -252,11 +337,12 @@ export const CredentialFields = ({ storedType }: Props) => {<SecretInputfield={field}label="Username"- placeholder="Enter the username"+ placeholder="Enter the username, or type {{"isError={Boolean(fieldState.error)}isUntouched={isUsernameUntouched}hasStoredSecret={hasStoredSecret}canBeCleared+ storedValue={hasStoredSecret ? seeded.username : undefined}/><FieldError>{fieldState.error?.message}</FieldError></FieldContent>@@ -267,18 +353,7 @@ export const CredentialFields = ({ storedType }: Props) => {</div>)}- {credentialType !== AgentVaultCredentialType.Passthrough && (- <CodeBlock- label="Sends"- isCopyable={false}- value={- credentialPreview(- { credentialType, headerName, headerPrefix },- isBasic ? "base64(<username>:<password>)" : "<token>"- ) ?? ""- }- />- )}+ {credentialType !== AgentVaultCredentialType.Passthrough && <SendsPreview />}{credentialType === AgentVaultCredentialType.Passthrough && (<Alert variant="info">diff --git a/frontend/src/components/agent-vault/service-sheet/ReviewFields.tsx b/frontend/src/components/agent-vault/service-sheet/ReviewFields.tsxindex 922a641d9f..79b0c53bff 100644--- a/frontend/src/components/agent-vault/service-sheet/ReviewFields.tsx+++ b/frontend/src/components/agent-vault/service-sheet/ReviewFields.tsx@@ -18,6 +18,7 @@ import {TServiceForm,UNCHANGED_SECRET} from "./serviceSchema";+import { useServiceVariables } from "./ServiceVariablesContext";const MASK = "\u2022".repeat(8);@@ -39,6 +40,7 @@ type Props = {export const ReviewFields = ({ isUpdate }: Props) => {const { watch } = useFormContext<TServiceForm>();+ const { seeded } = useServiceVariables();const form = watch();const isBasic = form.credentialType === AgentVaultCredentialType.Basic;@@ -59,9 +61,11 @@ export const ReviewFields = ({ isUpdate }: Props) => {: ""]);- const outcome = (value: string | undefined, canClear: boolean) => {+ const outcome = (value: string | undefined, canClear: boolean, seededValue?: string) => {if (!isUpdate) return value ? "Set" : "None";- if (value === UNCHANGED_SECRET) return "Unchanged";+ if (value === UNCHANGED_SECRET || (seededValue !== undefined && value === seededValue)) {+ return "Unchanged";+ }if (value) return "Replaced";return canClear ? "Cleared" : "Unchanged";};@@ -110,13 +114,13 @@ export const ReviewFields = ({ isUpdate }: Props) => {{isBasic && (<Detail><DetailLabel>Username</DetailLabel>- <DetailValue>{outcome(form.username, true)}</DetailValue>+ <DetailValue>{outcome(form.username, true, seeded.username)}</DetailValue></Detail>)}{form.credentialType !== AgentVaultCredentialType.Passthrough && (<Detail><DetailLabel>{secretLabel}</DetailLabel>- <DetailValue>{outcome(form.secret, isBasic)}</DetailValue>+ <DetailValue>{outcome(form.secret, isBasic, seeded.secret)}</DetailValue></Detail>)}</div>diff --git a/frontend/src/components/agent-vault/service-sheet/SendsPreview.tsx b/frontend/src/components/agent-vault/service-sheet/SendsPreview.tsxnew file mode 100644index 0000000000..a8ba77e24e--- /dev/null+++ b/frontend/src/components/agent-vault/service-sheet/SendsPreview.tsx@@ -0,0 +1,99 @@+import { ReactNode } from "react";+import { useFormContext, useWatch } from "react-hook-form";++import { splitVariableReferences } from "@app/helpers/agentVaultVariables";+import { AgentVaultCredentialType } from "@app/hooks/api/agentVault";++import { TServiceForm, UNCHANGED_SECRET } from "./serviceSchema";+import { useKnownVariableKeys, VariableChip } from "./VariableReferenceInput";++const MASK = "•".repeat(8);++// A reference holds no secret, so it is spelled out. Literal text is masked at a fixed length, which+// says nothing about the secret's own.+const PreviewValue = ({ value, placeholder }: { value?: string; placeholder: string }) => {+ const knownKeys = useKnownVariableKeys();++ if (!value) return <span className="text-muted">{placeholder}</span>;+ if (value === UNCHANGED_SECRET) return <span>{MASK}</span>;++ return (+ <>+ {splitVariableReferences(value).map((segment, index) =>+ segment.type === "text" ? (+ // eslint-disable-next-line react/no-array-index-key+ <span key={index}>{"•".repeat(4)}</span>+ ) : (+ <VariableChip+ // eslint-disable-next-line react/no-array-index-key+ key={index}+ reference={segment.text}+ isKnown={segment.isValid && (!knownKeys || knownKeys.has(segment.key))}+ />+ )+ )}+ </>+ );+};++export const SendsPreview = () => {+ const { control } = useFormContext<TServiceForm>();+ const [credentialType, headerName, headerPrefix, username, secret, customHeaders] = useWatch({+ control,+ name: ["credentialType", "headerName", "headerPrefix", "username", "secret", "customHeaders"]+ });++ const lines: { id: string; content: ReactNode }[] = [];++ if (credentialType === AgentVaultCredentialType.Bearer) {+ lines.push({+ id: "credential",+ content: (+ <>+ {headerName || "Authorization"}: {headerPrefix ? `${headerPrefix} ` : ""}+ <PreviewValue value={secret} placeholder="<token>" />+ </>+ )+ });+ }++ if (credentialType === AgentVaultCredentialType.Basic) {+ lines.push({+ id: "credential",+ content: (+ <>+ Authorization: Basic base64(+ <PreviewValue value={username} placeholder="<username>" />:+ <PreviewValue value={secret} placeholder="<password>" />)+ </>+ )+ });+ }++ customHeaders+ .filter((header) => header.name)+ .forEach((header, index) => {+ lines.push({+ id: header.id ?? `new-${index}`,+ content: (+ <>+ {header.name}: {header.prefix ? `${header.prefix} ` : ""}+ <PreviewValue value={header.value} placeholder="<value>" />+ </>+ )+ });+ });++ if (!lines.length) return null;++ return (+ <div className="max-w-full min-w-0 overflow-hidden rounded-md border border-border bg-container">+ <div className="border-b border-border px-3 py-2 text-xs font-medium text-label">Sends</div>+ <pre className="block thin-scrollbar w-full max-w-full overflow-x-auto p-3 font-mono text-xs leading-relaxed whitespace-pre text-foreground">+ {lines.map((line) => (+ <div key={line.id}>{line.content}</div>+ ))}+ </pre>+ </div>+ );+};diff --git a/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx b/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsxindex b35dde7082..f6829648a6 100644--- a/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx+++ b/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx@@ -1,4 +1,4 @@-import { useEffect, useMemo, useRef, useState } from "react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { FormProvider, useForm } from "react-hook-form";import { zodResolver } from "@hookform/resolvers/zod";import axios from "axios";@@ -21,17 +21,25 @@ import {import { ProviderIcon } from "@app/components/v3/platform/ProviderIcon";import { hostError } from "@app/helpers/agentVaultHostPattern";import { AgentVaultTemplate } from "@app/helpers/agentVaultTemplates";+import { toVariableReference } from "@app/helpers/agentVaultVariables";import { useDiscardChangesGuard, useWizardSteps } from "@app/hooks";import {AgentVaultCredentialType,+ AgentVaultVariableReferenceField,useCreateAgentVaultService,+ useListAgentVaultVariables,useUpdateAgentVaultService} from "@app/hooks/api/agentVault";-import { TAgentVaultService } from "@app/hooks/api/agentVault/types";+import {+ TAgentVaultService,+ TAgentVaultVariable,+ TAgentVaultVariableReference+} from "@app/hooks/api/agentVault/types";import { onRequestError } from "@app/hooks/api/reactQuery";import { ApiErrorTypes, TApiErrors } from "@app/hooks/api/types";import { ServiceTemplateSelect } from "../ServiceTemplateSelect";+import { VariableFormDialog } from "../VariableFormDialog";import { CredentialFields } from "./CredentialFields";import { DetailsFields } from "./DetailsFields";import { ReviewFields } from "./ReviewFields";@@ -45,6 +53,7 @@ import {TServiceForm,UNCHANGED_SECRET} from "./serviceSchema";+import { NO_SEEDED_REFERENCES, ServiceVariablesContext } from "./ServiceVariablesContext";import { SERVICE_DOCS_URL, SERVICE_STEPS } from "./stepMeta";import { ADVANCED_ITEM, TransformationsFields } from "./TransformationsFields";@@ -71,6 +80,46 @@ type Props = {service?: TAgentVaultService | null;};+// A stored value that is one reference and nothing else holds no secret, so it can go back in its field.+const seedReferences = (service?: TAgentVaultService | null) => {+ if (!service) return NO_SEEDED_REFERENCES;++ const whole = service.variableReferences.filter((reference) => reference.isWholeValue);+ const referenceWhere = (match: (reference: TAgentVaultVariableReference) => boolean) => {+ const reference = whole.find(match);+ return reference ? toVariableReference(reference.key) : undefined;+ };+ const byRow = <TRow extends { id: string }>(+ rows: TRow[],+ idOf: (r: TAgentVaultVariableReference) => string | null+ ) =>+ Object.fromEntries(+ rows.flatMap((row) => {+ const reference = referenceWhere((candidate) => idOf(candidate) === row.id);+ return reference ? [[row.id, reference]] : [];+ })+ );++ return {+ secret: referenceWhere(+ (reference) => reference.field === AgentVaultVariableReferenceField.CredentialValue+ ),+ username: referenceWhere(+ (reference) => reference.field === AgentVaultVariableReferenceField.CredentialUsername+ ),+ customHeaders: byRow(service.customHeaders, (reference) =>+ reference.field === AgentVaultVariableReferenceField.CustomHeader+ ? reference.customHeaderId+ : null+ ),+ substitutions: byRow(service.substitutions, (reference) =>+ reference.field === AgentVaultVariableReferenceField.Substitution+ ? reference.substitutionId+ : null+ )+ };+};+// Long enough for the advanced section to open and settle. There is no event to wait on: the section// is a Radix accordion, whose content is unmounted while closed, so the control cannot be measured// until after it mounts and takes its height.@@ -81,9 +130,34 @@ export const ServiceSheet = ({ isOpen, onOpenChange, accessBundleId, service }:const createService = useCreateAgentVaultService();const updateService = useUpdateAgentVaultService();+ const { data: variables } = useListAgentVaultVariables(accessBundleId, isOpen);+ const variableKeys = useMemo(() => variables?.map((variable) => variable.key), [variables]);+ const seeded = useMemo(() => seedReferences(service), [service]);+ // One dialog for every field. The request settles once the dialog has closed, not when the variable is+ // saved: until then the dialog's focus trap would pull focus back from the field that asked.+ const [newVariableKey, setNewVariableKey] = useState<string | null>(null);+ const newVariableRequest = useRef<{+ resolve: (variable: TAgentVaultVariable | null) => void;+ created: TAgentVaultVariable | null;+ } | null>(null);+ const requestVariable = useCallback(+ (key: string) =>+ new Promise<TAgentVaultVariable | null>((resolve) => {+ newVariableRequest.current?.resolve(null);+ newVariableRequest.current = { resolve, created: null };+ setNewVariableKey(key);+ }),+ []+ );++ const serviceVariables = useMemo(+ () => ({ variables, seeded, requestVariable }),+ [variables, seeded, requestVariable]+ );+const [template, setTemplate] = useState<AgentVaultTemplate | null>(null);- const schema = useMemo(() => buildServiceSchema(service), [service]);+ const schema = useMemo(() => buildServiceSchema(service, variableKeys), [service, variableKeys]);const formMethods = useForm<TServiceForm>({defaultValues: BLANK_SERVICE_FORM,@@ -165,28 +239,35 @@ export const ServiceSheet = ({ isOpen, onOpenChange, accessBundleId, service }:: "Authorization",headerPrefix:credential.type === AgentVaultCredentialType.Bearer ? credential.headerPrefix : "Bearer",- username: credential.type === AgentVaultCredentialType.Basic ? UNCHANGED_SECRET : undefined,- secret: credential.type === AgentVaultCredentialType.Passthrough ? "" : UNCHANGED_SECRET,+ username:+ credential.type === AgentVaultCredentialType.Basic+ ? (seeded.username ?? UNCHANGED_SECRET)+ : undefined,+ secret:+ credential.type === AgentVaultCredentialType.Passthrough+ ? ""+ : (seeded.secret ?? UNCHANGED_SECRET),methods: service.allowedMethods ?? [...HTTP_METHODS],pathPrefixes: service.allowedPathPrefixes ?? [],- // The stored values never come back, so each row carries the sentinel until it is retyped.+ // The stored values never come back, so each row carries the sentinel until it is retyped,+ // unless its value is a lone variable reference.customHeaders: service.customHeaders.map((header) => ({id: header.id,name: header.name,prefix: header.prefix,- value: UNCHANGED_SECRET+ value: seeded.customHeaders[header.id] ?? UNCHANGED_SECRET})),substitutions: service.substitutions.map((substitution) => ({id: substitution.id,placeholder: substitution.placeholder,surfaces: substitution.surfaces,- value: UNCHANGED_SECRET+ value: seeded.substitutions[substitution.id] ?? UNCHANGED_SECRET}))});} else {reset(BLANK_SERVICE_FORM);}- }, [isOpen, service, isUpdate, reset, setStep]);+ }, [isOpen, service, seeded, isUpdate, reset, setStep]);const handleTemplatePicked = (picked: AgentVaultTemplate | null) => {setTemplate(picked);@@ -232,16 +313,24 @@ export const ServiceSheet = ({ isOpen, onOpenChange, accessBundleId, service }:};};+ // A seeded reference left as it was is omitted like the sentinel, so a save neither re-seals it nor+ // records it as replaced. Not across a type change, where the stored secret no longer applies.+ const isKept = (value: string | undefined, seededValue: string | undefined) =>+ value === UNCHANGED_SECRET || (seededValue !== undefined && value === seededValue);+const buildCredentialPatch = (data: TServiceForm) => {if (data.credentialType === AgentVaultCredentialType.Passthrough) {return { type: AgentVaultCredentialType.Passthrough as const };}- const untouched = data.secret === UNCHANGED_SECRET;+ const isSameType = service?.credential.type === data.credentialType;+ const untouched = isKept(data.secret, isSameType ? seeded.secret : undefined);if (data.credentialType === AgentVaultCredentialType.Basic) {return {type: AgentVaultCredentialType.Basic as const,- username: data.username === UNCHANGED_SECRET ? undefined : (data.username ?? ""),+ username: isKept(data.username, isSameType ? seeded.username : undefined)+ ? undefined+ : (data.username ?? ""),password: untouched ? undefined : (data.secret ?? "")};}@@ -263,13 +352,20 @@ export const ServiceSheet = ({ isOpen, onOpenChange, accessBundleId, service }:...(header.id ? { id: header.id } : {}),name: header.name,prefix: header.prefix,- ...(header.value === UNCHANGED_SECRET ? {} : { value: header.value })+ ...(isKept(header.value, header.id ? seeded.customHeaders[header.id] : undefined)+ ? {}+ : { value: header.value })})),substitutions: data.substitutions.map((substitution) => ({...(substitution.id ? { id: substitution.id } : {}),placeholder: substitution.placeholder,surfaces: substitution.surfaces,- ...(substitution.value === UNCHANGED_SECRET ? {} : { value: substitution.value })+ ...(isKept(+ substitution.value,+ substitution.id ? seeded.substitutions[substitution.id] : undefined+ )+ ? {}+ : { value: substitution.value })}))});@@ -488,12 +584,18 @@ export const ServiceSheet = ({ isOpen, onOpenChange, accessBundleId, service }:{current.step === ServiceStep.Details && <DetailsFields />}{current.step === ServiceStep.Credential && (- <div className="flex flex-col gap-5">- <CredentialFields storedType={service?.credential.type} />- <TransformationsFields openItem={openItem} onOpenChange={setOpenItem} />- </div>+ <ServiceVariablesContext.Provider value={serviceVariables}>+ <div className="flex flex-col gap-5">+ <CredentialFields storedType={service?.credential.type} />+ <TransformationsFields openItem={openItem} onOpenChange={setOpenItem} />+ </div>+ </ServiceVariablesContext.Provider>+ )}+ {current.step === ServiceStep.Review && (+ <ServiceVariablesContext.Provider value={serviceVariables}>+ <ReviewFields isUpdate={isUpdate} />+ </ServiceVariablesContext.Provider>)}- {current.step === ServiceStep.Review && <ReviewFields isUpdate={isUpdate} />}</div><aside className="hidden w-80 shrink-0 flex-col gap-4 overflow-y-auto border-l border-border px-6 py-6 lg:flex">@@ -505,6 +607,9 @@ export const ServiceSheet = ({ isOpen, onOpenChange, accessBundleId, service }:</div><p className="text-sm font-semibold text-foreground">What this step does</p><p className="text-sm leading-relaxed text-muted">{current.rightDescription}</p>+ {current.rightTip && (+ <p className="text-sm leading-relaxed text-muted">{current.rightTip}</p>+ )}</aside></div>@@ -533,6 +638,27 @@ export const ServiceSheet = ({ isOpen, onOpenChange, accessBundleId, service }:)}</FormProvider>+ <VariableFormDialog+ isOpen={newVariableKey !== null}+ onOpenChange={(open) => {+ if (!open) setNewVariableKey(null);+ }}+ accessBundleId={accessBundleId}+ initialKey={newVariableKey ?? undefined}+ existingKeys={variableKeys ?? []}+ onCreated={(variable) => {+ if (newVariableRequest.current) newVariableRequest.current.created = variable;+ }}+ // The dialog opens from no trigger, so its default would drop focus on the body.+ onCloseAutoFocus={(event) => {+ const request = newVariableRequest.current;+ if (!request) return;+ event.preventDefault();+ newVariableRequest.current = null;+ request.resolve(request.created);+ }}+ />+<DiscardChangesAlertDialogopen={isDiscardDialogOpen}onOpenChange={setIsDiscardDialogOpen}diff --git a/frontend/src/components/agent-vault/service-sheet/ServiceVariablesContext.ts b/frontend/src/components/agent-vault/service-sheet/ServiceVariablesContext.tsnew file mode 100644index 0000000000..928d4767b9--- /dev/null+++ b/frontend/src/components/agent-vault/service-sheet/ServiceVariablesContext.ts@@ -0,0 +1,28 @@+import { createContext, useContext } from "react";++import { TAgentVaultVariable } from "@app/hooks/api/agentVault/types";++type TServiceVariables = {+ /** Undefined while the list loads, when no key can be called unknown yet. */+ variables?: TAgentVaultVariable[];+ /** The stored values that are one reference and nothing else, by field, so they can be shown again. */+ seeded: {+ secret?: string;+ username?: string;+ customHeaders: Record<string, string>;+ substitutions: Record<string, string>;+ };+ /** Opens the new-variable dialog on top of the sheet. Resolves to null if it is dismissed. */+ requestVariable?: (key: string) => Promise<TAgentVaultVariable | null>;+};++export const NO_SEEDED_REFERENCES: TServiceVariables["seeded"] = {+ customHeaders: {},+ substitutions: {}+};++export const ServiceVariablesContext = createContext<TServiceVariables>({+ seeded: NO_SEEDED_REFERENCES+});++export const useServiceVariables = () => useContext(ServiceVariablesContext);diff --git a/frontend/src/components/agent-vault/service-sheet/TransformationsFields.tsx b/frontend/src/components/agent-vault/service-sheet/TransformationsFields.tsxindex cb6f061d3c..a64e7820e0 100644--- a/frontend/src/components/agent-vault/service-sheet/TransformationsFields.tsx+++ b/frontend/src/components/agent-vault/service-sheet/TransformationsFields.tsx@@ -32,6 +32,7 @@ import {TServiceForm,UNCHANGED_SECRET} from "./serviceSchema";+import { useServiceVariables } from "./ServiceVariablesContext";import { SubstitutionExample } from "./SubstitutionExample";export const ADVANCED_ITEM = "advanced-options";@@ -75,6 +76,7 @@ export const TransformationsFields = ({onOpenChange: (item: string) => void;}) => {const { control, getValues } = useFormContext<TServiceForm>();+ const { seeded } = useServiceVariables();const customHeaders = useFieldArray({ control, name: "customHeaders" });const substitutions = useFieldArray({ control, name: "substitutions" });@@ -148,11 +150,14 @@ export const TransformationsFields = ({field={field}label="Header value"ariaLabel="Header value"- placeholder="Enter the value"+ placeholder="Enter the value, or type {{"isError={Boolean(fieldState.error)}isUntouched={field.value === UNCHANGED_SECRET}hasStoredSecret={Boolean(getValues(`customHeaders.${index}.id`))}canBeCleared={false}+ storedValue={+ seeded.customHeaders[getValues(`customHeaders.${index}.id`) ?? ""]+ }/><FieldError>{fieldState.error?.message}</FieldError></FieldContent>@@ -243,11 +248,14 @@ export const TransformationsFields = ({field={field}label="Substitution value"ariaLabel="Substitution value"- placeholder="Enter the real value"+ placeholder="Enter the real value, or type {{"isError={Boolean(fieldState.error)}isUntouched={field.value === UNCHANGED_SECRET}hasStoredSecret={Boolean(getValues(`substitutions.${index}.id`))}canBeCleared={false}+ storedValue={+ seeded.substitutions[getValues(`substitutions.${index}.id`) ?? ""]+ }/><FieldError>{fieldState.error?.message}</FieldError></FieldContent>diff --git a/frontend/src/components/agent-vault/service-sheet/VariableReferenceInput.tsx b/frontend/src/components/agent-vault/service-sheet/VariableReferenceInput.tsxnew file mode 100644index 0000000000..5658139e1d--- /dev/null+++ b/frontend/src/components/agent-vault/service-sheet/VariableReferenceInput.tsx@@ -0,0 +1,321 @@+import {+ Fragment,+ KeyboardEvent,+ ReactNode,+ RefObject,+ useId,+ useMemo,+ useRef,+ useState+} from "react";+import { LockIcon, PlusIcon } from "lucide-react";++import { Popover, PopoverAnchor, PopoverContent } from "@app/components/v3";+import { cn } from "@app/components/v3/utils";+import {+ findOpenVariableReference,+ normalizeVariableKey,+ splitVariableReferences,+ toVariableReference,+ VARIABLE_KEY_RE+} from "@app/helpers/agentVaultVariables";+import { TAgentVaultVariable } from "@app/hooks/api/agentVault/types";++import { useServiceVariables } from "./ServiceVariablesContext";++/** Undefined while the list loads, so nothing is marked unknown before it can be known. */+export const useKnownVariableKeys = () => {+ const { variables } = useServiceVariables();+ return useMemo(+ () => (variables ? new Set(variables.map((variable) => variable.key)) : undefined),+ [variables]+ );+};++const chipTone = (isKnown: boolean) =>+ isKnown+ ? "bg-product-av/15 text-product-av ring-product-av/30"+ : "bg-danger/15 text-danger ring-danger/40";++export const VariableChip = ({ reference, isKnown }: { reference: string; isKnown: boolean }) => (+ <span className={cn("rounded-[3px] px-1 ring-1 ring-inset", chipTone(isKnown))}>{reference}</span>+);++/**+ * The value drawn behind a transparent input, with each reference marked. Marks add colour and a ring+ * but no padding, so every character sits exactly where the input's own would.+ */+export const ReferenceHighlights = ({+ value,+ overlayRef+}: {+ value: string;+ overlayRef: RefObject<HTMLDivElement>;+}) => {+ const knownKeys = useKnownVariableKeys();++ return (+ <div aria-hidden className="pointer-events-none absolute inset-0 flex items-center px-2.5">+ <div+ ref={overlayRef}+ className="w-full overflow-hidden text-sm whitespace-pre text-foreground"+ >+ {splitVariableReferences(value).map((segment, index) =>+ segment.type === "text" ? (+ // eslint-disable-next-line react/no-array-index-key+ <span key={index}>{segment.text}</span>+ ) : (+ <mark+ // eslint-disable-next-line react/no-array-index-key+ key={index}+ className={cn(+ "rounded-[3px] ring-1 ring-inset",+ chipTone(segment.isValid && (!knownKeys || knownKeys.has(segment.key)))+ )}+ >+ {segment.text}+ </mark>+ )+ )}+ {/* The caret's width: the input scrolls past it at the end, and plain text has nothing there. */}+ <span className="inline-block w-0.5" />+ </div>+ </div>+ );+};++type TOpenReference = { start: number; query: string };++type TSuggestion =+ | { type: "variable"; variable: TAgentVaultVariable }+ | { type: "create"; key: string; isKeyValid: boolean };++export const useVariableAutocomplete = ({+ inputRef,+ onInsert+}: {+ inputRef: RefObject<HTMLInputElement>;+ /** The whole new value, and where in it the caret belongs. */+ onInsert: (value: string, caret: number) => void;+}) => {+ const { variables, requestVariable } = useServiceVariables();+ const [openReference, setOpenReference] = useState<TOpenReference | null>(null);+ const [activeIndex, setActiveIndex] = useState(0);+ // Escape closes the list for the reference being typed, not for the field: it opens again at the next {{.+ const dismissedAt = useRef<number | null>(null);+ const listId = useId();++ const suggestions = useMemo((): TSuggestion[] => {+ if (!openReference || !variables) return [];+ const key = normalizeVariableKey(openReference.query);+ const matches = variables+ .filter((variable) => variable.key.includes(key))+ .sort(+ (a, b) =>+ Number(b.key.startsWith(key)) - Number(a.key.startsWith(key)) ||+ a.key.localeCompare(b.key)+ )+ .map((variable) => ({ type: "variable" as const, variable }));++ if (!requestVariable || variables.some((variable) => variable.key === key)) return matches;+ return [...matches, { type: "create", key, isKeyValid: VARIABLE_KEY_RE.test(key) }];+ }, [openReference, variables, requestVariable]);++ const close = () => setOpenReference(null);++ const refresh = () => {+ const input = inputRef.current;+ const caret = input?.selectionStart ?? null;+ const next =+ input && caret !== null && caret === input.selectionEnd+ ? findOpenVariableReference(input.value.slice(0, caret))+ : null;++ if (!next) {+ dismissedAt.current = null;+ close();+ return;+ }+ if (next.start === dismissedAt.current) return;+ if (openReference?.start !== next.start || openReference.query !== next.query) {+ setOpenReference(next);+ setActiveIndex(0);+ }+ };++ const dismiss = () => {+ dismissedAt.current = openReference?.start ?? null;+ close();+ };++ // Read when a suggestion is chosen, before the list closes. Retyping the key inside a reference that is+ // already closed replaces it, rather than leaving the old key's tail behind the new one.+ const surroundings = () => {+ const input = inputRef.current;+ if (!input || !openReference) return null;+ const caret = input.selectionStart ?? input.value.length;+ const tail = /^[A-Za-z0-9_]*\}\}/.exec(input.value.slice(caret));+ return {+ before: input.value.slice(0, openReference.start),+ after: input.value.slice(caret + (tail?.[0].length ?? 0))+ };+ };++ const choose = async (suggestion: TSuggestion) => {+ const input = inputRef.current;+ const parts = surroundings();+ if (!input || !parts) return;+ const caret = input.selectionStart ?? input.value.length;+ close();++ const insert = (key: string) => {+ const reference = toVariableReference(key);+ onInsert(parts.before + reference + parts.after, parts.before.length + reference.length);+ };++ if (suggestion.type === "variable") {+ insert(suggestion.variable.key);+ return;+ }++ // Settles once the dialog has closed. The field cannot change while it is open, so what surrounded+ // the reference still does, and focus comes back to where the caret was.+ const created = await requestVariable?.(suggestion.key);+ input.focus();+ if (created) insert(created.key);+ else input.setSelectionRange(caret, caret);+ };++ const onKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {+ if (!openReference || !suggestions.length) return;+ if (event.key === "ArrowDown" || event.key === "ArrowUp") {+ event.preventDefault();+ const step = event.key === "ArrowDown" ? 1 : -1;+ setActiveIndex((index) => (index + step + suggestions.length) % suggestions.length);+ return;+ }+ const active = suggestions[Math.min(activeIndex, suggestions.length - 1)];+ // Tab completes a variable that exists. Opening a dialog is not what a Tab means.+ if (event.key === "Enter" || (event.key === "Tab" && active.type === "variable")) {+ event.preventDefault();+ choose(active);+ }+ };++ const optionId = (index: number) => `${listId}-option-${index}`;++ return {+ isOpen: Boolean(openReference),+ suggestions,+ activeIndex,+ setActiveIndex,+ listId,+ activeOptionId: openReference && suggestions.length ? optionId(activeIndex) : undefined,+ optionId,+ refresh,+ close,+ dismiss,+ choose,+ onKeyDown+ };+};++type TAutocomplete = ReturnType<typeof useVariableAutocomplete>;++export const VariableSuggestions = ({+ autocomplete,+ children+}: {+ autocomplete: TAutocomplete;+ children: ReactNode;+}) => {+ const { variables } = useServiceVariables();+ const anchorRef = useRef<HTMLDivElement>(null);+ const { isOpen, suggestions, activeIndex, setActiveIndex, listId, optionId, choose, dismiss } =+ autocomplete;++ return (+ <Popover+ open={isOpen}+ onOpenChange={(open) => {+ if (!open) dismiss();+ }}+ >+ <PopoverAnchor asChild>+ <div ref={anchorRef}>{children}</div>+ </PopoverAnchor>+ <PopoverContent+ align="start"+ className="w-(--radix-popover-trigger-width) min-w-56 p-1"+ // Focus stays in the field the whole time: the list is driven from its keyboard.+ onOpenAutoFocus={(event) => event.preventDefault()}+ onCloseAutoFocus={(event) => event.preventDefault()}+ onInteractOutside={(event) => {+ if (anchorRef.current?.contains(event.target as Node)) event.preventDefault();+ }}+ >+ {suggestions.length > 0 ? (+ <ul+ id={listId}+ role="listbox"+ aria-label="Variables"+ className="max-h-60 overflow-y-auto"+ >+ {suggestions.map((suggestion, index) => (+ <Fragment key={suggestion.type === "variable" ? suggestion.variable.id : "create"}>+ {suggestion.type === "create" && index > 0 && (+ <li role="presentation" className="-mx-1 my-1 h-px bg-border" />+ )}+ {/* eslint-disable-next-line jsx-a11y/click-events-have-key-events */}+ <li+ id={optionId(index)}+ role="option"+ aria-selected={index === activeIndex}+ className={cn(+ "flex cursor-pointer items-center gap-3 rounded-sm px-2 py-1.5",+ index === activeIndex && "bg-container-hover"+ )}+ onMouseEnter={() => setActiveIndex(index)}+ onMouseDown={(event) => event.preventDefault()}+ onClick={() => choose(suggestion)}+ >+ {suggestion.type === "variable" ? (+ <>+ <span className="flex-1 truncate font-mono text-xs">+ {suggestion.variable.key}+ </span>+ {suggestion.variable.isSecret ? (+ <LockIcon className="size-3 shrink-0 text-muted" aria-label="Secret" />+ ) : (+ <span className="max-w-32 truncate text-xs text-muted">+ {suggestion.variable.value}+ </span>+ )}+ </>+ ) : (+ <>+ <PlusIcon className="size-3.5 shrink-0 text-muted" />+ {suggestion.isKeyValid ? (+ <span className="min-w-0 truncate text-xs">+ Create <span className="font-mono">{suggestion.key}</span>+ </span>+ ) : (+ <span className="text-xs">Create Variable</span>+ )}+ </>+ )}+ </li>+ </Fragment>+ ))}+ </ul>+ ) : (+ <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."}+ </p>+ )}+ </PopoverContent>+ </Popover>+ );+};diff --git a/frontend/src/components/agent-vault/service-sheet/serviceSchema.ts b/frontend/src/components/agent-vault/service-sheet/serviceSchema.tsindex 4c2e525bb6..22be40d407 100644--- a/frontend/src/components/agent-vault/service-sheet/serviceSchema.ts+++ b/frontend/src/components/agent-vault/service-sheet/serviceSchema.ts@@ -2,6 +2,7 @@ import { z } from "zod";import { addHostIssues, hostError } from "@app/helpers/agentVaultHostPattern";import { addPathPrefixIssues, pathPrefixError } from "@app/helpers/agentVaultPathPrefix";+import { variableReferenceError } from "@app/helpers/agentVaultVariables";import {AgentVaultCredentialType,AgentVaultHttpMethod,@@ -97,7 +98,8 @@ export const SERVICE_STEP_FIELDS: Record<ServiceStep, string[]> = {[ServiceStep.Review]: []};-export const buildServiceSchema = (service?: TAgentVaultService | null) =>+/** `variableKeys` stays undefined while the list loads, so only the shape of a reference is checked. */+export const buildServiceSchema = (service?: TAgentVaultService | null, variableKeys?: string[]) =>z.object({name: slugSchema({ max: 64, field: "Name" }),@@ -257,6 +259,14 @@ export const buildServiceSchema = (service?: TAgentVaultService | null) =>at("placeholder", "Required");} else if (!NO_CONTROL_CHARS_RE.test(substitution.placeholder)) {at("placeholder", CONTROL_CHARS_MESSAGE);+ } else if (+ substitution.placeholder.includes("{{") ||+ substitution.placeholder.includes("}}")+ ) {+ at(+ "placeholder",+ "A placeholder can't contain {{ or }}. Those wrap a variable reference."+ );} else if (seenPlaceholders.has(substitution.placeholder)) {at("placeholder", "This placeholder is listed twice.");}@@ -269,6 +279,26 @@ export const buildServiceSchema = (service?: TAgentVaultService | null) =>}});+ const variableKeySet = variableKeys ? new Set(variableKeys) : undefined;+ const addReferenceIssue = (value: string | undefined, path: (string | number)[]) => {+ if (!value || value === UNCHANGED_SECRET) return;+ const message = variableReferenceError(value, variableKeySet);+ if (message) ctx.addIssue({ code: z.ZodIssueCode.custom, path, message });+ };++ if (data.credentialType !== AgentVaultCredentialType.Passthrough) {+ addReferenceIssue(data.secret, ["secret"]);+ }+ if (data.credentialType === AgentVaultCredentialType.Basic) {+ addReferenceIssue(data.username, ["username"]);+ }+ data.customHeaders.forEach((header, index) =>+ addReferenceIssue(header.value, ["customHeaders", index, "value"])+ );+ data.substitutions.forEach((substitution, index) =>+ addReferenceIssue(substitution.value, ["substitutions", index, "value"])+ );+if (data.credentialType === AgentVaultCredentialType.Passthrough) return;const isUnchanged = data.secret === UNCHANGED_SECRET;diff --git a/frontend/src/components/agent-vault/service-sheet/stepMeta.ts b/frontend/src/components/agent-vault/service-sheet/stepMeta.tsindex db193c5f55..86b2644984 100644--- a/frontend/src/components/agent-vault/service-sheet/stepMeta.ts+++ b/frontend/src/components/agent-vault/service-sheet/stepMeta.ts@@ -12,6 +12,7 @@ type StepMeta = {subtitle?: string;rightLabel?: string;rightDescription?: string;+ rightTip?: string;};export const SERVICE_STEPS: StepMeta[] = [@@ -37,7 +38,9 @@ export const SERVICE_STEPS: StepMeta[] = [subtitle: "How requests to this service are authenticated, and anything else to add to them.",rightLabel: "CREDENTIAL",rightDescription:- "Agents reach this service without ever holding the credential themselves. Custom headers go out on top of it, and a substitution swaps a placeholder your agent already sends for the real value."+ "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."},{step: ServiceStep.Review,diff --git a/frontend/src/helpers/agentVaultVariables.ts b/frontend/src/helpers/agentVaultVariables.tsnew file mode 100644index 0000000000..42b32253b4--- /dev/null+++ b/frontend/src/helpers/agentVaultVariables.ts@@ -0,0 +1,78 @@+export const VARIABLE_KEY_MAX_LENGTH = 64;+export const VARIABLE_VALUE_MAX_LENGTH = 8192;++export const VARIABLE_KEY_RE = /^[A-Z][A-Z0-9_]*$/;++export const VARIABLE_KEY_MESSAGE =+ "Start with a letter, then use upper case letters, numbers and underscores, like GITHUB_TOKEN.";++// Every {{...}} counts as a reference, so a malformed one is caught on save instead of being sent to a+// real host as literal text.+const REFERENCE_RE = /\{\{([^{}]*)\}\}/g;++const REFERENCE_ONLY_RE = /^\{\{[A-Z][A-Z0-9_]*\}\}$/;++// An opened reference the caret is still inside, so the suggestions can follow what is typed.+const OPEN_REFERENCE_RE = /\{\{([A-Za-z0-9_]*)$/;++export const toVariableReference = (key: string) => `{{${key}}}`;++export const findVariableReferences = (text: string) =>+ Array.from(text.matchAll(REFERENCE_RE), (match) => match[1]);++export const findVariableKeys = (text: string) =>+ Array.from(new Set(findVariableReferences(text).filter((ref) => VARIABLE_KEY_RE.test(ref))));++/** A lone reference holds no secret, so a masked field can show it as text. */+export const isVariableReferenceOnly = (text: string | undefined) =>+ Boolean(text) && REFERENCE_ONLY_RE.test(text as string);++/** Upper cases the input and turns spaces and dashes into underscores, so `github-token` lands valid. */+export const normalizeVariableKey = (input: string) => input.toUpperCase().replace(/[\s-]/g, "_");++export type TVariableSegment =+ | { type: "text"; text: string }+ | { type: "reference"; text: string; key: string; isValid: boolean };++/** Splits a value into literal text and the references in it, in order, so each can render on its own. */+export const splitVariableReferences = (text: string): TVariableSegment[] => {+ const segments: TVariableSegment[] = [];+ let last = 0;+ Array.from(text.matchAll(REFERENCE_RE)).forEach((match) => {+ const start = match.index ?? 0;+ if (start > last) segments.push({ type: "text", text: text.slice(last, start) });+ segments.push({+ type: "reference",+ text: match[0],+ key: match[1],+ isValid: VARIABLE_KEY_RE.test(match[1])+ });+ last = start + match[0].length;+ });+ if (last < text.length) segments.push({ type: "text", text: text.slice(last) });+ return segments;+};++/** Where an unfinished reference starts and what has been typed of its key, or null. */+export const findOpenVariableReference = (textBeforeCaret: string) => {+ const match = OPEN_REFERENCE_RE.exec(textBeforeCaret);+ return match ? { start: match.index, query: match[1] } : null;+};++/**+ * The first problem with the references in a field, or null. Without `keys`, which is the case while+ * the list loads, only the shape of each reference is checked.+ */+export const variableReferenceError = (text: string, keys?: ReadonlySet<string>): string | null => {+ const refs = findVariableReferences(text);++ const malformed = refs.find((ref) => !VARIABLE_KEY_RE.test(ref));+ if (malformed !== undefined) {+ return `"${toVariableReference(malformed)}" is not a variable. Keys are upper case, like GITHUB_TOKEN.`;+ }++ 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.`;++ return null;+};diff --git a/frontend/src/hooks/api/agentVault/enums.ts b/frontend/src/hooks/api/agentVault/enums.tsindex c4e620051d..2d18e13235 100644--- a/frontend/src/hooks/api/agentVault/enums.ts+++ b/frontend/src/hooks/api/agentVault/enums.ts@@ -42,3 +42,11 @@ export enum AgentVaultSessionScope {Mine = "mine",All = "all"}++/** Which value of a service uses a variable. A basic credential's password is its credential-value. */+export enum AgentVaultVariableReferenceField {+ CredentialValue = "credential-value",+ CredentialUsername = "credential-username",+ CustomHeader = "custom-header",+ Substitution = "substitution"+}diff --git a/frontend/src/hooks/api/agentVault/mutations.tsx b/frontend/src/hooks/api/agentVault/mutations.tsxindex 16e96f524b..a227e6b142 100644--- a/frontend/src/hooks/api/agentVault/mutations.tsx+++ b/frontend/src/hooks/api/agentVault/mutations.tsx@@ -18,12 +18,16 @@ import {TAgentVaultProxy,TAgentVaultProxySettingsDTO,TAgentVaultService,+ TAgentVaultVariable,+ TAgentVaultVariableRef,TAgentVaultWrittenMember,TCreateAgentVaultAccessBundleDTO,TCreateAgentVaultServiceDTO,TCreateAgentVaultSessionDTO,+ TCreateAgentVaultVariableDTO,TUpdateAgentVaultAccessBundleDTO,- TUpdateAgentVaultServiceDTO+ TUpdateAgentVaultServiceDTO,+ TUpdateAgentVaultVariableDTO} from "./types";export const useCreateAgentVaultAccessBundle = () => {@@ -359,3 +363,75 @@ export const useRevokeAgentVaultMembers = () => {onSuccess: () => invalidateMembers(queryClient, currentOrg.id)});};++// 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) });++export const useCreateAgentVaultVariable = () => {+ const { currentOrg } = useOrganization();+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: async ({ accessBundleId, ...params }: TCreateAgentVaultVariableDTO) => {+ const { data } = await apiRequest.post<{ variable: TAgentVaultVariable }>(+ `/api/v1/agent-vault/access-bundles/${accessBundleId}/variables`,+ params+ );+ return data.variable;+ },+ onSuccess: (variable, { accessBundleId }) => {+ // 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),+ (prev) => (prev ? [...prev, variable].sort((a, b) => a.key.localeCompare(b.key)) : prev)+ );+ return invalidateVariables(queryClient, currentOrg.id, accessBundleId);+ }+ });+};++export const useUpdateAgentVaultVariable = () => {+ const { currentOrg } = useOrganization();+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: async ({ accessBundleId, variableId, ...params }: TUpdateAgentVaultVariableDTO) => {+ const { data } = await apiRequest.patch<{ variable: TAgentVaultVariable }>(+ `/api/v1/agent-vault/access-bundles/${accessBundleId}/variables/${variableId}`,+ params+ );+ return data.variable;+ },+ onSuccess: (_, { accessBundleId }) =>+ invalidateVariables(queryClient, currentOrg.id, accessBundleId)+ });+};++export const useDeleteAgentVaultVariable = () => {+ const { currentOrg } = useOrganization();+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: async ({ accessBundleId, variableId }: TAgentVaultVariableRef) => {+ const { data } = await apiRequest.delete<{ variable: TAgentVaultVariable }>(+ `/api/v1/agent-vault/access-bundles/${accessBundleId}/variables/${variableId}`+ );+ return data.variable;+ },+ onSuccess: (_, { accessBundleId }) =>+ invalidateVariables(queryClient, currentOrg.id, accessBundleId)+ });+};++// A mutation rather than a query, so a revealed value never enters the query cache.+export const useRevealAgentVaultVariableValue = () =>+ useMutation({+ mutationFn: async ({ accessBundleId, variableId }: TAgentVaultVariableRef) => {+ const { data } = await apiRequest.get<{ value: string }>(+ `/api/v1/agent-vault/access-bundles/${accessBundleId}/variables/${variableId}/value`+ );+ return data.value;+ }+ });diff --git a/frontend/src/hooks/api/agentVault/queries.tsx b/frontend/src/hooks/api/agentVault/queries.tsxindex 7fdfb949d3..4f4bce47e0 100644--- a/frontend/src/hooks/api/agentVault/queries.tsx+++ b/frontend/src/hooks/api/agentVault/queries.tsx@@ -13,6 +13,7 @@ import {TAgentVaultProductMemberOf,TAgentVaultProxy,TAgentVaultSession,+ TAgentVaultVariable,TListAgentVaultAccessBundlesDTO,TListAgentVaultMembersDTO,TListAgentVaultProxiesDTO,@@ -54,6 +55,8 @@ 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,members: (orgId: string) => [...agentVaultKeys.all(orgId), "members"] as const,memberList: (orgId: string, params?: TListAgentVaultMembersDTO) =>[...agentVaultKeys.members(orgId), params] as const,@@ -216,3 +219,18 @@ export const useListAgentVaultProxies = (params: TListAgentVaultProxiesDTO = {})placeholderData: (prev) => prev});};++export const useListAgentVaultVariables = (accessBundleId: string, enabled = true) => {+ const { currentOrg } = useOrganization();++ return useQuery({+ queryKey: agentVaultKeys.accessBundleVariables(currentOrg.id, accessBundleId),+ queryFn: async () => {+ const { data } = await apiRequest.get<{ variables: TAgentVaultVariable[] }>(+ `/api/v1/agent-vault/access-bundles/${accessBundleId}/variables`+ );+ return data.variables;+ },+ enabled: enabled && Boolean(accessBundleId)+ });+};diff --git a/frontend/src/hooks/api/agentVault/types.ts b/frontend/src/hooks/api/agentVault/types.tsindex b9815e5a44..97bc284bbe 100644--- a/frontend/src/hooks/api/agentVault/types.ts+++ b/frontend/src/hooks/api/agentVault/types.ts@@ -5,7 +5,8 @@ import {AgentVaultSessionScope,AgentVaultSessionStatus,AgentVaultSubstitutionSurface,- AgentVaultTrafficPolicy+ AgentVaultTrafficPolicy,+ AgentVaultVariableReferenceField} from "./enums";export type TAgentVaultCredentialSummary =@@ -57,6 +58,21 @@ export type TAgentVaultSubstitutionInput = {value?: string;};+/** `isWholeValue` means the value is exactly {{key}}, so the sheet can show it where a value never returns. */+export type TAgentVaultVariableReference = {+ variableId: string;+ key: string;+ isWholeValue: boolean;+} & (+ | {+ field:+ | AgentVaultVariableReferenceField.CredentialValue+ | AgentVaultVariableReferenceField.CredentialUsername;+ }+ | { field: AgentVaultVariableReferenceField.CustomHeader; customHeaderId: string }+ | { field: AgentVaultVariableReferenceField.Substitution; substitutionId: string }+);+export type TAgentVaultService = {id: string;accessBundleId: string;@@ -68,6 +84,7 @@ export type TAgentVaultService = {credential: TAgentVaultCredentialSummary;customHeaders: TAgentVaultCustomHeaderSummary[];substitutions: TAgentVaultSubstitutionSummary[];+ variableReferences: TAgentVaultVariableReference[];createdAt: string;updatedAt: string;};@@ -279,3 +296,33 @@ export type TAgentVaultProxySettingsDTO = {allowedHosts?: string | null;pollInterval?: number;};++export type TAgentVaultVariable = {+ id: string;+ accessBundleId: string;+ key: string;+ isSecret: boolean;+ /** Null for a secret variable, whose value comes only from the value route. */+ value: string | null;+ serviceIds: string[];+ createdAt: string;+ updatedAt: string;+};++export type TAgentVaultVariableRef = {+ accessBundleId: string;+ variableId: string;+};++export type TCreateAgentVaultVariableDTO = {+ accessBundleId: string;+ key: string;+ value: string;+ isSecret: boolean;+};++export type TUpdateAgentVaultVariableDTO = TAgentVaultVariableRef & {+ key?: string;+ value?: string;+ isSecret?: boolean;+};diff --git a/frontend/src/hooks/api/auditLogs/constants.tsx b/frontend/src/hooks/api/auditLogs/constants.tsxindex fa7793a6c0..2dc21c3b0e 100644--- a/frontend/src/hooks/api/auditLogs/constants.tsx+++ b/frontend/src/hooks/api/auditLogs/constants.tsx@@ -469,6 +469,10 @@ export const eventToNameMap: { [K in EventType]: string } = {[EventType.AGENT_VAULT_SERVICE_CREATE]: "Create service",[EventType.AGENT_VAULT_SERVICE_UPDATE]: "Update service",[EventType.AGENT_VAULT_SERVICE_DELETE]: "Delete service",+ [EventType.AGENT_VAULT_VARIABLE_CREATE]: "Create variable",+ [EventType.AGENT_VAULT_VARIABLE_UPDATE]: "Update variable",+ [EventType.AGENT_VAULT_VARIABLE_DELETE]: "Delete variable",+ [EventType.AGENT_VAULT_VARIABLE_VALUE_VIEW]: "View variable value",[EventType.AGENT_VAULT_MEMBER_ADD]: "Add member",[EventType.AGENT_VAULT_MEMBER_UPDATE]: "Change member role",[EventType.AGENT_VAULT_MEMBER_REMOVE]: "Remove member",@@ -542,6 +546,10 @@ export const projectToEventsMap: Partial<Record<ProjectType, EventType[]>> = {EventType.AGENT_VAULT_SERVICE_CREATE,EventType.AGENT_VAULT_SERVICE_UPDATE,EventType.AGENT_VAULT_SERVICE_DELETE,+ EventType.AGENT_VAULT_VARIABLE_CREATE,+ EventType.AGENT_VAULT_VARIABLE_UPDATE,+ EventType.AGENT_VAULT_VARIABLE_DELETE,+ EventType.AGENT_VAULT_VARIABLE_VALUE_VIEW,EventType.AGENT_VAULT_MEMBER_ADD,EventType.AGENT_VAULT_MEMBER_UPDATE,EventType.AGENT_VAULT_MEMBER_REMOVE,diff --git a/frontend/src/hooks/api/auditLogs/enums.tsx b/frontend/src/hooks/api/auditLogs/enums.tsxindex e7aee8583a..03822d5d26 100644--- a/frontend/src/hooks/api/auditLogs/enums.tsx+++ b/frontend/src/hooks/api/auditLogs/enums.tsx@@ -467,6 +467,10 @@ export enum EventType {AGENT_VAULT_SERVICE_CREATE = "agent-vault-service-create",AGENT_VAULT_SERVICE_UPDATE = "agent-vault-service-update",AGENT_VAULT_SERVICE_DELETE = "agent-vault-service-delete",+ AGENT_VAULT_VARIABLE_CREATE = "agent-vault-variable-create",+ AGENT_VAULT_VARIABLE_UPDATE = "agent-vault-variable-update",+ AGENT_VAULT_VARIABLE_DELETE = "agent-vault-variable-delete",+ AGENT_VAULT_VARIABLE_VALUE_VIEW = "agent-vault-variable-value-view",AGENT_VAULT_MEMBER_ADD = "agent-vault-member-add",AGENT_VAULT_MEMBER_UPDATE = "agent-vault-member-update",AGENT_VAULT_MEMBER_REMOVE = "agent-vault-member-remove",diff --git a/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/AgentVaultAccessBundleDetailPage.tsx b/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/AgentVaultAccessBundleDetailPage.tsxindex 0d11f95981..20daaace69 100644--- a/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/AgentVaultAccessBundleDetailPage.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/AgentVaultAccessBundleDetailPage.tsx@@ -35,6 +35,7 @@ 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();@@ -139,6 +140,11 @@ export const AgentVaultAccessBundleDetailPage = () => {}}/>+ {/* The variables routes are admin only. */}+ {isAdmin && (+ <VariablesCard accessBundleId={accessBundle.id} services={accessBundle.services} />+ )}+<ManageAccessSheetaccessBundle={isManageAccessOpen ? accessBundle : null}onOpenChange={setIsManageAccessOpen}diff --git a/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/DeleteVariableDialog.tsx b/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/DeleteVariableDialog.tsxnew file mode 100644index 0000000000..e4913165a8--- /dev/null+++ b/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/DeleteVariableDialog.tsx@@ -0,0 +1,80 @@+import { ServiceIcon } from "@app/components/agent-vault/ServiceIconStack";+import { createNotification } from "@app/components/notifications";+import {+ AlertDialog,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+ Button+} from "@app/components/v3";+import { useDeleteAgentVaultVariable } from "@app/hooks/api/agentVault";+import { TAgentVaultService, 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) => {+ const deleteVariable = useDeleteAgentVaultVariable();+ const isInUse = usedBy.length > 0;++ const handleDelete = async () => {+ if (!variable) return;+ try {+ await deleteVariable.mutateAsync({+ accessBundleId: variable.accessBundleId,+ variableId: variable.id+ });+ createNotification({ text: `Variable "${variable.key}" deleted`, type: "success" });+ onOpenChange(false);+ } catch {+ // A failed request returns a 4xx that the global request handler surfaces as a toast+ }+ };++ return (+ <AlertDialog open={Boolean(variable)} onOpenChange={onOpenChange}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>Delete "{variable?.key}"</AlertDialogTitle>+ <AlertDialogDescription>+ {isInUse+ ? `${usedBy.length === 1 ? "A service uses" : `${usedBy.length} services use`} this variable. Remove the reference from ${usedBy.length === 1 ? "it" : "them"} before you delete it.`+ : "Its value is deleted with it. This cannot be undone."}+ </AlertDialogDescription>+ </AlertDialogHeader>++ {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">+ <ServiceIcon hostPattern={service.hostPattern} />+ {service.name}+ </li>+ ))}+ </ul>+ )}++ <AlertDialogFooter>+ <AlertDialogCancel variant="outline">Cancel</AlertDialogCancel>+ {/* A plain button rather than AlertDialogAction, which closes on click and would drop the+ pending state before the request settles. */}+ <Button+ variant="danger"+ size="sm"+ isDisabled={isInUse}+ isPending={deleteVariable.isPending}+ onClick={handleDelete}+ >+ Delete Variable+ </Button>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ );+};diff --git a/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/VariablesCard.tsx b/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/VariablesCard.tsxnew file mode 100644index 0000000000..a1305fa827--- /dev/null+++ b/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/VariablesCard.tsx@@ -0,0 +1,329 @@+import { useMemo, useState } from "react";+import {+ ChevronDownIcon,+ EyeIcon,+ EyeOffIcon,+ LockIcon,+ MoreHorizontalIcon,+ PencilIcon,+ PlusIcon,+ SearchIcon,+ TrashIcon+} from "lucide-react";+import { twMerge } from "tailwind-merge";++import { VariableFormDialog } from "@app/components/agent-vault/VariableFormDialog";+import {+ Button,+ Card,+ CardAction,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+ DocumentationLinkBadge,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+ Empty,+ EmptyDescription,+ EmptyHeader,+ EmptyTitle,+ IconButton,+ InputGroup,+ InputGroupAddon,+ InputGroupInput,+ Skeleton,+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow+} from "@app/components/v3";+import { toVariableReference } from "@app/helpers/agentVaultVariables";+import {+ useListAgentVaultVariables,+ useRevealAgentVaultVariableValue+} from "@app/hooks/api/agentVault";+import { TAgentVaultService, TAgentVaultVariable } from "@app/hooks/api/agentVault/types";++import { AgentVaultDocsUrls } from "../../agent-vault-docs-urls";+import { DeleteVariableDialog } from "./DeleteVariableDialog";++enum SortColumn {+ Key = "key",+ UsedBy = "usedBy"+}++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}`;++type Props = {+ accessBundleId: string;+ services: TAgentVaultService[];+};++export const VariablesCard = ({ accessBundleId, services }: Props) => {+ const { data: variables = [], isPending } = useListAgentVaultVariables(accessBundleId);+ const revealValue = useRevealAgentVaultVariableValue();++ const [search, setSearch] = useState("");+ const [sortColumn, setSortColumn] = useState(SortColumn.Key);+ const [sortDirection, setSortDirection] = useState<"ascending" | "descending">("ascending");+ const [isFormOpen, setIsFormOpen] = useState(false);+ const [variableToEdit, setVariableToEdit] = useState<TAgentVaultVariable | null>(null);+ const [variableToDelete, setVariableToDelete] = useState<TAgentVaultVariable | null>(null);+ 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.key.localeCompare(b.key);++ const ordered = [...filtered].sort(compare);+ return sortDirection === "ascending" ? ordered : ordered.reverse();+ }, [variables, search, sortColumn, sortDirection]);++ const handleSort = (column: SortColumn, direction: "ascending" | "descending" | "none") => {+ if (direction === "none") {+ setSortColumn(SortColumn.Key);+ setSortDirection("ascending");+ return;+ }+ setSortColumn(column);+ setSortDirection(direction);+ };++ const sortIconClassName = (column: SortColumn) =>+ twMerge(+ "size-3.5 transition-transform",+ sortColumn === column && sortDirection === "descending" && "rotate-180",+ sortColumn !== column && "opacity-30"+ );++ const toggleReveal = async (variable: TAgentVaultVariable) => {+ const slot = revealSlot(variable);+ if (revealed[slot] !== undefined) {+ setRevealed((prev) => Object.fromEntries(Object.entries(prev).filter(([id]) => id !== slot)));+ return;+ }++ setRevealingId(variable.id);+ try {+ const value = await revealValue.mutateAsync({ accessBundleId, variableId: variable.id });+ setRevealed((prev) => ({ ...prev, [slot]: value }));+ } catch {+ // A failed request returns a 4xx that the global request handler surfaces as a toast+ } finally {+ setRevealingId(null);+ }+ };++ const openForm = (variable: TAgentVaultVariable | null) => {+ setVariableToEdit(variable);+ setIsFormOpen(true);+ };++ return (+ <Card>+ <CardHeader>+ <CardTitle>+ Variables+ <DocumentationLinkBadge href={AgentVaultDocsUrls.variables} />+ </CardTitle>+ <CardDescription>+ A variable stores one value that any service in this bundle can use as{" "}+ <code className="font-mono">{toVariableReference("KEY")}</code>.+ </CardDescription>+ <CardAction>+ <Button variant="av" onClick={() => openForm(null)}>+ <PlusIcon />+ Add Variable+ </Button>+ </CardAction>+ </CardHeader>++ {variables.length > 0 && (+ <CardContent>+ <InputGroup>+ <InputGroupAddon>+ <SearchIcon />+ </InputGroupAddon>+ <InputGroupInput+ value={search}+ onChange={(e) => setSearch(e.target.value)}+ placeholder="Search variables..."+ />+ </InputGroup>+ </CardContent>+ )}++ {!isPending && displayed.length === 0 ? (+ <CardContent>+ <Empty className="border">+ <EmptyHeader>+ <EmptyTitle>+ {variables.length === 0 ? "No variables yet" : "No variables match your search"}+ </EmptyTitle>+ <EmptyDescription>+ {variables.length === 0+ ? "Add a variable to use one value across this bundle's services."+ : "Try a different search term."}+ </EmptyDescription>+ </EmptyHeader>+ </Empty>+ </CardContent>+ ) : (+ // Fixed layout, so revealing a secret can't resize the columns the way auto layout would.+ <Table className="w-full min-w-[640px] table-fixed">+ <TableHeader>+ <TableRow>+ <TableHead+ className="w-[35%]"+ sortDirection={sortColumn === SortColumn.Key ? sortDirection : "none"}+ onSortChange={(direction) => handleSort(SortColumn.Key, direction)}+ >+ Key+ <ChevronDownIcon className={sortIconClassName(SortColumn.Key)} />+ </TableHead>+ <TableHead className="w-[35%]">Value</TableHead>+ <TableHead+ sortDirection={sortColumn === SortColumn.UsedBy ? sortDirection : "none"}+ onSortChange={(direction) => handleSort(SortColumn.UsedBy, direction)}+ >+ Used By+ <ChevronDownIcon className={sortIconClassName(SortColumn.UsedBy)} />+ </TableHead>+ <TableHead variant="action" className="w-12" />+ </TableRow>+ </TableHeader>+ <TableBody>+ {isPending &&+ Array.from({ length: 3 }).map((_, index) => (+ // eslint-disable-next-line react/no-array-index-key+ <TableRow key={`variable-skeleton-${index}`}>+ {Array.from({ length: 3 }).map((__, cell) => (+ // eslint-disable-next-line react/no-array-index-key+ <TableCell key={`variable-skeleton-${index}-${cell}`}>+ <Skeleton className="h-4 w-full" />+ </TableCell>+ ))}+ <TableCell variant="action" />+ </TableRow>+ ))}+ {!isPending &&+ displayed.map((variable) => {+ const revealedValue = revealed[revealSlot(variable)];+ const isRevealed = revealedValue !== undefined;+ const usedBy = usedByOf(variable);++ return (+ <TableRow key={variable.id}>+ <TableCell>+ <span className="block truncate font-mono text-sm">{variable.key}</span>+ </TableCell>+ <TableCell>+ {variable.isSecret ? (+ <div className="flex items-center gap-1.5">+ <LockIcon className="size-3.5 shrink-0 text-muted" aria-label="Secret" />+ {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>+ )}+ <IconButton+ variant="ghost"+ size="xs"+ className="shrink-0"+ aria-label={`${isRevealed ? "Hide" : "Reveal"} ${variable.key}`}+ isPending={revealingId === variable.id}+ onClick={() => toggleReveal(variable)}+ >+ {isRevealed ? <EyeOffIcon /> : <EyeIcon />}+ </IconButton>+ </div>+ ) : (+ <span className="block truncate font-mono text-sm">{variable.value}</span>+ )}+ </TableCell>+ <TableCell>+ {usedBy.length === 0 ? (+ <span className="text-sm text-muted">Unused</span>+ ) : (+ <span className="block truncate text-sm">+ {usedBy.map((service) => service.name).join(", ")}+ </span>+ )}+ </TableCell>+ <TableCell variant="action">+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <IconButton variant="ghost" size="xs" aria-label="Open variable actions">+ <MoreHorizontalIcon />+ </IconButton>+ </DropdownMenuTrigger>+ <DropdownMenuContent sideOffset={2} align="end">+ <DropdownMenuItem onClick={() => openForm(variable)}>+ <PencilIcon />+ Edit+ </DropdownMenuItem>+ <DropdownMenuItem+ variant="danger"+ onClick={() => setVariableToDelete(variable)}+ >+ <TrashIcon />+ Delete+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </TableCell>+ </TableRow>+ );+ })}+ </TableBody>+ </Table>+ )}++ <VariableFormDialog+ isOpen={isFormOpen}+ onOpenChange={setIsFormOpen}+ accessBundleId={accessBundleId}+ variable={variableToEdit}+ existingKeys={variables.map((variable) => variable.key)}+ usedByCount={usedByOf(variableToEdit).length}+ />++ <DeleteVariableDialog+ variable={variableToDelete}+ usedBy={usedByOf(variableToDelete)}+ onOpenChange={(isOpen) => {+ if (!isOpen) setVariableToDelete(null);+ }}+ />+ </Card>+ );+};diff --git a/frontend/src/pages/agent-vault/agent-vault-docs-urls.ts b/frontend/src/pages/agent-vault/agent-vault-docs-urls.tsindex 5fecdac389..84592bc894 100644--- a/frontend/src/pages/agent-vault/agent-vault-docs-urls.ts+++ b/frontend/src/pages/agent-vault/agent-vault-docs-urls.ts@@ -5,6 +5,7 @@ export const AgentVaultDocsUrls = {quickstart: `${AGENT_VAULT_DOCS_BASE_URL}/quickstart`,accessBundles: `${AGENT_VAULT_DOCS_BASE_URL}/access-bundles`,services: `${AGENT_VAULT_DOCS_BASE_URL}/services`,+ variables: `${AGENT_VAULT_DOCS_BASE_URL}/variables`,sessions: `${AGENT_VAULT_DOCS_BASE_URL}/sessions`,proxies: `${AGENT_VAULT_DOCS_BASE_URL}/proxies`} as const;