Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
fix(agent-vault): derive variable references from what is sealed
Scott Wilson2917a900dc5d
diff --git a/backend/e2e-test/routes/v1/agent-vault.spec.ts b/backend/e2e-test/routes/v1/agent-vault.spec.tsindex 392da3ba42..a626da8d6a 100644--- a/backend/e2e-test/routes/v1/agent-vault.spec.ts+++ b/backend/e2e-test/routes/v1/agent-vault.spec.ts@@ -15,15 +15,24 @@ import { agentVaultSessionAccessBundleDALFactory } from "@app/ee/services/agent-import { agentVaultSessionDALFactory } from "@app/ee/services/agent-vault-session/agent-vault-session-dal";import { agentVaultSessionServiceFactory } from "@app/ee/services/agent-vault-session/agent-vault-session-service";import { groupDALFactory } from "@app/ee/services/group/group-dal";+import { isHsmActiveAndEnabled } from "@app/ee/services/hsm/hsm-fns";import { permissionDALFactory } from "@app/ee/services/permission/permission-dal";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 { getConfig, initEnvConfig } from "@app/lib/config/env";import { UnauthorizedError } from "@app/lib/errors";-import { initLogger } from "@app/lib/logger";+import { initLogger, logger } from "@app/lib/logger";import { additionalPrivilegeDALFactory } from "@app/services/additional-privilege/additional-privilege-dal";import { ActorType } from "@app/services/auth/auth-type";import { identityDALFactory } from "@app/services/identity/identity-dal";+import { internalKmsDALFactory } from "@app/services/kms/internal-kms-dal";+import { internalKmsKeyVersionDALFactory } from "@app/services/kms/internal-kms-key-version-dal";+import { kmsKekHistoryDALFactory } from "@app/services/kms/kms-kek-history-dal";+import { kmskeyDALFactory } from "@app/services/kms/kms-key-dal";+import { kmsLegacyEncryptionKeyDALFactory } from "@app/services/kms/kms-legacy-encryption-key-dal";+import { kmsServiceFactory, TKmsServiceFactory } from "@app/services/kms/kms-service";+import { KmsDataKey } from "@app/services/kms/kms-types";import { usageCounterDALFactory } from "@app/services/license-client/usage/usage-counter-dal";import { membershipDALFactory } from "@app/services/membership/membership-dal";import { orgDALFactory } from "@app/services/org/org-dal";@@ -735,6 +744,7 @@ describe("Agent Vault V1 Router", async () => {type TResolved = {services: {+ name: string;credential: Record<string, string>;customHeaders: { name: string; prefix: string; value: string }[];substitutions: { placeholder: string; surfaces: string[]; value: string }[];@@ -770,6 +780,118 @@ describe("Agent Vault V1 Router", async () => {};};+ // The project's own key, loaded the way the server loads it, so a test can read and write sealed text directly.+ // The spec runs in its own module graph, which is why the env config is initialized again here.+ let kmsService: TKmsServiceFactory | undefined;+ const cipherFor = async (accessBundleId: string) => {+ if (!kmsService) {+ await initEnvConfig(testHsmService, testKmsRootConfigDAL, testSuperAdminDAL, logger);+ kmsService = kmsServiceFactory({+ kmsRootConfigDAL: testKmsRootConfigDAL,+ kmsLegacyEncryptionKeyDAL: kmsLegacyEncryptionKeyDALFactory(testDb),+ kmsKekHistoryDAL: kmsKekHistoryDALFactory(testDb),+ kmsDAL: kmskeyDALFactory(testDb),+ internalKmsDAL: internalKmsDALFactory(testDb),+ internalKmsKeyVersionDAL: internalKmsKeyVersionDALFactory(testDb),+ orgDAL: orgDALFactory(testDb),+ projectDAL: projectDALFactory(testDb),+ hsmService: testHsmService,+ keyStore: {+ getItem: async () => null,+ setItemWithExpiry: async () => "OK" as const,+ deleteItem: async () => 0+ },+ envConfig: getConfig()+ });+ const hsmStatus = await isHsmActiveAndEnabled({+ hsmService: testHsmService,+ kmsRootConfigDAL: testKmsRootConfigDAL+ });+ await kmsService.startService(hsmStatus, { skipRotationState: true });+ }+ const { projectId } = (await testDb("agent_vault_access_bundles").where({ id: accessBundleId }).first()) as {+ projectId: string;+ };+ return kmsService.createCipherPairWithDataKey({ type: KmsDataKey.SecretManager, projectId });+ };++ const STORED_REFERENCE = /\{\{([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\}\}/g;++ // What the delete refusal rests on: every field's rows name exactly the ids in its sealed text that resolve+ // expands, which are those of the bundle's own variables. Read off the sealed text, not through the service.+ const expectReferencesMatchSealedText = async (accessBundleId: string) => {+ const { decryptor } = await cipherFor(accessBundleId);+ const open = (sealed: Buffer) =>+ JSON.parse(decryptor({ cipherTextBlob: sealed }).toString("utf-8")) as Record<string, string>;+ const variableIds = new Set(+ ((await testDb("agent_vault_variables").where({ accessBundleId }).select("id")) as { id: string }[]).map(+ (row) => row.id+ )+ );+ const idsIn = (text: string) =>+ [...new Set(Array.from(text.matchAll(STORED_REFERENCE), (match) => match[1]))].filter((id) =>+ variableIds.has(id)+ );++ const services = (await testDb("agent_vault_services").where({ accessBundleId })) as {+ id: string;+ encryptedCredential: Buffer | null;+ }[];+ const serviceIds = services.map((service) => service.id);+ type TSealedRow = { id: string; serviceId: string; encryptedValue: Buffer };+ const customHeaders = (await testDb("agent_vault_service_custom_headers").whereIn(+ "serviceId",+ serviceIds+ )) as TSealedRow[];+ const substitutions = (await testDb("agent_vault_service_substitutions").whereIn(+ "serviceId",+ serviceIds+ )) as TSealedRow[];+ const references = (await testDb("agent_vault_service_variable_references").whereIn("serviceId", serviceIds)) as {+ serviceId: string;+ variableId: string;+ field: string;+ customHeaderId: string | null;+ substitutionId: string | null;+ }[];++ const expected = [+ ...services.flatMap((service) =>+ Object.entries(service.encryptedCredential ? open(service.encryptedCredential) : {}).flatMap(([part, text]) =>+ idsIn(text).map(+ (id) => `${service.id} ${part === "username" ? "credential-username" : "credential-value"} ${id}`+ )+ )+ ),+ ...customHeaders.flatMap((row) =>+ idsIn(open(row.encryptedValue).value).map((id) => `${row.serviceId} custom-header:${row.id} ${id}`)+ ),+ ...substitutions.flatMap((row) =>+ idsIn(open(row.encryptedValue).value).map((id) => `${row.serviceId} substitution:${row.id} ${id}`)+ )+ ];+ const actual = references.map((row) => {+ const target = row.customHeaderId ?? row.substitutionId;+ return `${row.serviceId} ${row.field}${target ? `:${target}` : ""} ${row.variableId}`;+ });+ expect(actual.sort()).toEqual(expected.sort());+ };++ // Resolves once a backend waits on a lock the given one holds: by then a request has done everything it+ // does before the lock and is queued behind it.+ const waitUntilBlockedBy = async (pid: number, attemptsLeft = 200): Promise<void> => {+ const { rows } = await testDb.raw(+ "select count(*)::int as waiting from pg_stat_activity where ? = any(pg_blocking_pids(pid))",+ [pid]+ );+ if (rows[0].waiting > 0) return;+ if (attemptsLeft === 0) throw new Error(`No request queued behind the lock held by backend ${pid}`);+ await new Promise((resolve) => {+ setTimeout(resolve, 25);+ });+ await waitUntilBlockedBy(pid, attemptsLeft - 1);+ };+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" });@@ -816,6 +938,7 @@ describe("Agent Vault V1 Router", async () => {}]));+ await expectReferencesMatchSealedText(bundle.id);const resolve = await resolverFor(bundle, "variables-resolve");const [resolved] = (await resolve()).services;@@ -850,6 +973,7 @@ describe("Agent Vault V1 Router", async () => {expect(detail.accessBundle.services[0].variableReferences).toEqual([expect.objectContaining({ key: "NEW_NAME", field: "credential-value" })]);+ await expectReferencesMatchSealedText(bundle.id);expect((await resolve()).services[0].credential).toMatchObject({ value: "first" });expect((await inject("PATCH", `${variablesUrl(bundle.id)}/${variable.id}`, { value: "second" })).statusCode).toBe(@@ -886,6 +1010,7 @@ describe("Agent Vault V1 Router", async () => {});expect(detached.statusCode).toBe(200);expect(JSON.parse(detached.payload).service.variableReferences).toEqual([]);+ await expectReferencesMatchSealedText(bundle.id);const removed = await inject("DELETE", `${variablesUrl(bundle.id)}/${variable.id}`);expect(removed.statusCode).toBe(200);@@ -988,6 +1113,7 @@ describe("Agent Vault V1 Router", async () => {"credential-value:PASS","custom-header:HEADER"]);+ await expectReferencesMatchSealedText(bundle.id);const resolve = await resolverFor(bundle, "variables-partial");const [resolved] = (await resolve()).services;@@ -999,6 +1125,7 @@ describe("Agent Vault V1 Router", async () => {expect(referencesByField(JSON.parse(switched.payload).service.variableReferences)).toEqual(["custom-header:HEADER"]);+ await expectReferencesMatchSealedText(bundle.id);const dropped = await inject("PATCH", url, { customHeaders: [] });expect(dropped.statusCode).toBe(200);@@ -1006,6 +1133,118 @@ describe("Agent Vault V1 Router", async () => {expect(await testDb("agent_vault_service_variable_references").where({ serviceId: service.id })).toHaveLength(0);});+ test("a basic credential's kept half is stored text, so one saved before variables existed stays as it was", async () => {+ const bundle = await createAccessBundle("variables-legacy-half");+ await createVariable(bundle.id, { key: "FOO", value: "foo-value" });+ await createVariable(bundle.id, { key: "USER", value: "the-user" });++ const created = await inject("POST", servicesUrl(bundle.id), {+ name: "legacy",+ hostPattern: "legacy.example.com",+ credential: { type: "basic", username: "u", password: "p" }+ });+ expect(created.statusCode).toBe(200);+ const { service } = JSON.parse(created.payload) as { service: { id: string } };++ // Sealed the way a service saved before variables existed was: literal braces and no reference rows. The+ // id-shaped pair names no variable at all.+ const legacyPassword = `{{FOO}}:{{${crypto.randomUUID()}}}`;+ const { encryptor } = await cipherFor(bundle.id);+ await testDb("agent_vault_services")+ .where({ id: service.id })+ .update({+ encryptedCredential: encryptor({+ plainText: Buffer.from(JSON.stringify({ username: "u", password: legacyPassword }))+ }).cipherTextBlob+ });++ const patched = await inject("PATCH", `${servicesUrl(bundle.id)}/${service.id}`, {+ credential: { type: "basic", username: "{{USER}}" }+ });+ expect(patched.statusCode).toBe(200);+ expect(referencesByField(JSON.parse(patched.payload).service.variableReferences)).toEqual([+ "credential-username:USER"+ ]);+ await expectReferencesMatchSealedText(bundle.id);++ const resolve = await resolverFor(bundle, "variables-legacy-half");+ expect((await resolve()).services[0].credential).toEqual({+ type: "basic",+ username: "the-user",+ password: legacyPassword+ });+ });++ test("a partial basic update refuses to write over a credential another save changed while it waited", async () => {+ const bundle = await createAccessBundle("variables-stale-half");+ await createVariable(bundle.id, { key: "FIRST_USER", value: "first-user" });+ await createVariable(bundle.id, { key: "SECOND_USER", value: "second-user" });+ await createVariable(bundle.id, { key: "PASS", value: "the-pass" });++ const created = await inject("POST", servicesUrl(bundle.id), {+ name: "stale",+ hostPattern: "stale.example.com",+ credential: { type: "basic", username: "{{FIRST_USER}}", password: "plain-pass" }+ });+ expect(created.statusCode).toBe(200);+ const { service } = JSON.parse(created.payload) as { service: { id: string } };+ const url = `${servicesUrl(bundle.id)}/${service.id}`;++ // What the other save commits, sealed by the API itself on a second service: a new username.+ const other = await inject("POST", servicesUrl(bundle.id), {+ name: "other",+ hostPattern: "other.example.com",+ credential: { type: "basic", username: "{{SECOND_USER}}", password: "plain-pass" }+ });+ expect(other.statusCode).toBe(200);+ const otherId = (JSON.parse(other.payload) as { service: { id: string } }).service.id;+ const otherRow = (await testDb("agent_vault_services").where({ id: otherId }).first()) as {+ encryptedCredential: Buffer;+ };+ const otherReferences = (await testDb("agent_vault_service_variable_references").where({+ serviceId: otherId+ })) as { variableId: string; field: string }[];++ // Holding the bundle lock like the other save would, so this one reads the service and then waits.+ const trx = await testDb.transaction();+ try {+ const { rows } = await trx.raw("select pg_backend_pid() as pid");+ await trx("agent_vault_access_bundles").where({ id: bundle.id }).forUpdate().first();++ const pending = inject("PATCH", url, { credential: { type: "basic", password: "{{PASS}}" } });+ await waitUntilBlockedBy(rows[0].pid);++ await trx("agent_vault_services")+ .where({ id: service.id })+ .update({ encryptedCredential: otherRow.encryptedCredential });+ await trx("agent_vault_service_variable_references").where({ serviceId: service.id }).del();+ await trx("agent_vault_service_variable_references").insert(+ otherReferences.map(({ variableId, field }) => ({ serviceId: service.id, variableId, field }))+ );+ await trx.commit();++ const refused = await pending;+ expect(refused.statusCode).toBe(409);+ } catch (err) {+ if (!trx.isCompleted()) await trx.rollback();+ throw err;+ }++ const kept = (await testDb("agent_vault_services").where({ id: service.id }).first()) as {+ encryptedCredential: Buffer;+ };+ expect(kept.encryptedCredential.equals(otherRow.encryptedCredential)).toBe(true);+ await expectReferencesMatchSealedText(bundle.id);++ const retried = await inject("PATCH", url, { credential: { type: "basic", password: "{{PASS}}" } });+ expect(retried.statusCode).toBe(200);+ await expectReferencesMatchSealedText(bundle.id);++ const resolve = await resolverFor(bundle, "variables-stale-half");+ const resolved = (await resolve()).services.find((entry) => entry.name === "stale");+ expect(resolved?.credential).toEqual({ type: "basic", username: "second-user", password: "the-pass" });+ });+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" });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 8113720533..8316b1316b 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@@ -45,6 +45,7 @@ import {import { getAgentVaultReachability } from "../agent-vault/agent-vault-permission";import {AGENT_VAULT_MAX_VARIABLES,+ findStoredVariableIds,findVariableKeys,toStoredVariableReferences,toVariableReference@@ -447,34 +448,14 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundsubstitutionId?: string;};- const credentialReferenceTexts = (- credential: TAgentVaultCredentialUpdate- ): (TReferencingText & TReferenceTarget)[] => {+ const credentialReferenceTexts = (credential: TAgentVaultCredentialUpdate): TReferencingText[] => {switch (credential.type) {case AgentVaultCredentialType.Bearer:- return credential.value === undefined- ? []- : [{ label: "The token", text: credential.value, field: AgentVaultVariableReferenceField.CredentialValue }];+ return credential.value === undefined ? [] : [{ label: "The token", text: credential.value }];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- }- ])+ ...(credential.username === undefined ? [] : [{ label: "The username", text: credential.username }]),+ ...(credential.password === undefined ? [] : [{ label: "The password", text: credential.password }])];default:return [];@@ -482,8 +463,14 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund};// A key the bundle does not define would reach the host as literal braces, so it fails the save instead.- const resolveVariableKeys = async (accessBundleId: string, texts: TReferencingText[]) => {- if (!texts.some(({ text }) => findVariableKeys(text).length)) return new Map<string, string>();+ // Stored text that a save keeps rather than writes needs the lookup only for the ids it holds.+ const loadBundleVariables = async (accessBundleId: string, texts: TReferencingText[], storedTexts: string[] = []) => {+ if (+ !texts.some(({ text }) => findVariableKeys(text).length) &&+ !storedTexts.some((text) => findStoredVariableIds(text).length)+ ) {+ return { idOfKey: new Map<string, string>(), variableIds: new Set<string>() };+ }const variables = await agentVaultVariableDAL.findKeysByAccessBundleId(accessBundleId);const idOfKey = new Map(variables.map((variable) => [variable.key, variable.id]));@@ -497,39 +484,76 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund}});- return idOfKey;+ return { idOfKey, variableIds: new Set(variables.map((variable) => variable.id)) };+ };++ // Only text that arrived with the request is stored. A basic credential's kept half is already stored text,+ // and one saved before variables existed has to keep reaching the host exactly as it was.+ const storeCredentialReferences = (+ credential: TAgentVaultCredentialUpdate,+ store: (text: string) => string+ ): TAgentVaultCredentialUpdate => {+ switch (credential.type) {+ case AgentVaultCredentialType.Bearer:+ return credential.value === undefined ? credential : { ...credential, value: store(credential.value) };+ case AgentVaultCredentialType.Basic:+ return {+ ...credential,+ ...(credential.username === undefined ? {} : { username: store(credential.username) }),+ ...(credential.password === undefined ? {} : { password: store(credential.password) })+ };+ default:+ return credential;+ }};- const toReferenceRows = (+ // Read off the stored text the way resolve reads it, never off the request. Nothing in the database can check+ // the rows against sealed text, and an id resolve expands without a row is a variable the delete refusal lets+ // go while a service still uses it.+ const referenceRowsOf = (serviceId: string,- idOfKey: ReadonlyMap<string, string>,- targets: (TReferenceTarget & { text: string })[]+ target: TReferenceTarget,+ storedText: string,+ variableIds: ReadonlySet<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- }- ];- })+ findStoredVariableIds(storedText)+ // Resolve leaves an id that names no variable of this bundle as text, so it gets no row either.+ .filter((variableId) => variableIds.has(variableId))+ .map((variableId) => ({+ serviceId,+ variableId,+ field: target.field,+ customHeaderId: target.customHeaderId ?? null,+ substitutionId: target.substitutionId ?? null+ }));++ const credentialReferenceRowsOf = (+ serviceId: string,+ storedSecret: TCredentialWrite["secret"],+ variableIds: ReadonlySet<string>+ ) =>+ Object.entries(storedSecret ?? {}).flatMap(([part, text]) =>+ referenceRowsOf(+ serviceId,+ {+ field:+ part === "username"+ ? AgentVaultVariableReferenceField.CredentialUsername+ : AgentVaultVariableReferenceField.CredentialValue+ },+ text,+ variableIds+ ));- // 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.";+ const CREDENTIAL_CHANGED_DURING_SAVE_MESSAGE =+ "This service's credential was changed by another save while this one was in progress. Reload the service and save again.";+// Basic has no header name in its config, but the proxy always writes Authorization.const credentialHeaderName = (credentialType: AgentVaultCredentialType, headerName?: string): string | null => {switch (credentialType) {@@ -764,13 +788,8 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundawait checkHostPatternConflicts({ accessBundleId: bundle.id, hostPattern });- // Encrypt before the lock: KMS is a network call and the transaction has to stay short.- const { config, secret } = splitCredential(credential);- assertCustomHeadersDoNotShadowCredential(config, customHeaders);-- const credentialTexts = credentialReferenceTexts(credential);- const idOfKey = await resolveVariableKeys(bundle.id, [- ...credentialTexts,+ const { idOfKey, variableIds } = await loadBundleVariables(bundle.id, [+ ...credentialReferenceTexts(credential),...(customHeaders ?? []).map((header) => ({ label: `The custom header '${header.name}'`, text: header.value })),...(substitutions ?? []).map((substitution) => ({label: `The substitution for '${substitution.placeholder}'`,@@ -779,24 +798,32 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund]);const store = (text: string) => toStoredVariableReferences(text, idOfKey);+ // Encrypt before the lock: KMS is a network call and the transaction has to stay short.+ const { config, secret } = splitCredential(+ storeCredentialReferences(credential, store) as TAgentVaultCredentialInput+ );+ assertCustomHeadersDoNotShadowCredential(config, customHeaders);+const { encryptor } = await getProjectCipher(rest.projectId);- const seal = (value: string) =>- encryptor({ plainText: Buffer.from(JSON.stringify({ value: store(value) })) }).cipherTextBlob;+ const seal = (value: string) => encryptor({ plainText: Buffer.from(JSON.stringify({ value })) }).cipherTextBlob;const encryptedCredential = secret- ? encryptor({ plainText: Buffer.from(JSON.stringify(storeSecretReferences(secret, store))) }).cipherTextBlob+ ? encryptor({ plainText: Buffer.from(JSON.stringify(secret)) }).cipherTextBlob: null;+ // Stored once, so the sealed text and the references read off it are the same string.+ const storedCustomHeaderValues = (customHeaders ?? []).map((header) => store(header.value));+ const storedSubstitutionValues = (substitutions ?? []).map((substitution) => store(substitution.value));const customHeaderRows = (customHeaders ?? []).map((header, position) => ({name: header.name,prefix: header.prefix ?? "",position,- encryptedValue: seal(header.value)+ encryptedValue: seal(storedCustomHeaderValues[position])}));const substitutionRows = (substitutions ?? []).map((substitution, position) => ({placeholder: substitution.placeholder,surfaces: substitution.surfaces,position,- encryptedValue: seal(substitution.value)+ encryptedValue: seal(storedSubstitutionValues[position])}));// The pre-check above is only a fast failure. The authoritative one runs under the bundle row lock,@@ -838,21 +865,25 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund): [];- 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- }))- ]);+ const referenceRows = [+ ...credentialReferenceRowsOf(created.id, secret, variableIds),+ ...insertedCustomHeaders.flatMap((row) =>+ referenceRowsOf(+ created.id,+ { field: AgentVaultVariableReferenceField.CustomHeader, customHeaderId: row.id },+ storedCustomHeaderValues[row.position],+ variableIds+ )+ ),+ ...insertedSubstitutions.flatMap((row) =>+ referenceRowsOf(+ created.id,+ { field: AgentVaultVariableReferenceField.Substitution, substitutionId: row.id },+ storedSubstitutionValues[row.position],+ variableIds+ )+ )+ ];if (referenceRows.length) await agentVaultServiceVariableReferenceDAL.insertMany(referenceRows, tx);const variableReferences = referenceRows.length? await agentVaultServiceVariableReferenceDAL.findByServiceIds([created.id], tx)@@ -921,55 +952,51 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund});}+ // A partial basic update keeps the other half from the sealed secret read here, before the lock, so the write+ // re-checks under the lock that nothing replaced it since.+ const needsStoredSecret =+ credential?.type === AgentVaultCredentialType.Basic &&+ service.credentialType === AgentVaultCredentialType.Basic &&+ (credential.username === undefined) !== (credential.password === undefined) &&+ Boolean(service.encryptedCredential);+ const storedSecretCipher = needsStoredSecret ? await getProjectCipher(rest.projectId) : null;+ const storedSecret = storedSecretCipher+ ? (JSON.parse(+ storedSecretCipher.decryptor({ cipherTextBlob: service.encryptedCredential! }).toString("utf-8")+ ) as Record<string, string>)+ : null;+// 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 { idOfKey, variableIds } = await loadBundleVariables(+ bundle.id,+ [+ ...(credential ? credentialReferenceTexts(credential) : []),+ ...(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 }]+ )+ ],+ storedSecret ? Object.values(storedSecret) : []+ );const store = (text: string) => toStoredVariableReferences(text, idOfKey);let credentialUpdate = {};- let replacedCredentialFields: AgentVaultVariableReferenceField[] = [];+ // Undefined leaves the sealed secret, and the references read off it, as they are.+ let writtenSecret: TCredentialWrite["secret"];let effectiveCredentialConfig = service.credentialConfig as TAgentVaultCredentialConfig;if (credential) {- const needsStoredSecret =- credential.type === AgentVaultCredentialType.Basic &&- service.credentialType === AgentVaultCredentialType.Basic &&- (credential.username === undefined) !== (credential.password === undefined) &&- Boolean(service.encryptedCredential);- const cipher = needsStoredSecret ? await getProjectCipher(rest.projectId) : null;- const storedSecret = cipher- ? (JSON.parse(cipher.decryptor({ cipherTextBlob: service.encryptedCredential! }).toString("utf-8")) as Record<- string,- string- >)- : null;-- const { config, secret } = mergeCredential(credential, service, storedSecret);+ const { config, secret } = mergeCredential(storeCredentialReferences(credential, store), service, storedSecret);let encryptedCredential: Buffer | null | undefined;if (secret === null) encryptedCredential = null;if (secret) {- const { encryptor } = cipher ?? (await getProjectCipher(rest.projectId));- 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);+ const { encryptor } = storedSecretCipher ?? (await getProjectCipher(rest.projectId));+ encryptedCredential = encryptor({ plainText: Buffer.from(JSON.stringify(secret)) }).cipherTextBlob;}+ writtenSecret = secret;credentialUpdate = {credentialType: credential.type,@@ -981,30 +1008,40 @@ 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: store(value) })) })- .cipherTextBlob;+ const seal = (storedValue: string | undefined) =>+ storedValue === undefined+ ? undefined+ : cipherForTransformations!.encryptor({ plainText: Buffer.from(JSON.stringify({ value: storedValue })) })+ .cipherTextBlob;++ // Stored once, so the sealed text and the references read off it are the same string.+ const storedCustomHeaderValues = (customHeaders ?? []).map((header) =>+ header.value === undefined ? undefined : store(header.value)+ );+ const storedSubstitutionValues = (substitutions ?? []).map((substitution) =>+ substitution.value === undefined ? undefined : store(substitution.value)+ );const customHeaderWrites: TTransformationWrite<{ name: string; prefix: string }>[] | undefined = customHeaders?.map(- (header) => ({+ (header, index) => ({id: header.id,naturalKey: header.name.toLowerCase(),label: header.name,// An omitted prefix is cleared, not kept: it comes back in the response so a caller can resend it,// which is the thing a sealed value can never do.columns: { name: header.name, prefix: header.prefix ?? "" },- encryptedValue: header.value === undefined ? undefined : seal(header.value)+ encryptedValue: seal(storedCustomHeaderValues[index])}));const substitutionWrites:| TTransformationWrite<{ placeholder: string; surfaces: AgentVaultSubstitutionSurface[] }>[]- | undefined = substitutions?.map((substitution) => ({+ | undefined = substitutions?.map((substitution, index) => ({id: substitution.id,naturalKey: substitution.placeholder,label: substitution.placeholder,columns: { placeholder: substitution.placeholder, surfaces: substitution.surfaces },- encryptedValue: substitution.value === undefined ? undefined : seal(substitution.value)+ encryptedValue: seal(storedSubstitutionValues[index])}));// Same lock as create, and below the credential work so no KMS call sits inside the transaction. The@@ -1021,6 +1058,19 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundawait checkHostPatternConflicts({ accessBundleId: bundle.id, hostPattern, excludeServiceId: service.id }, tx);}+ // The credential was merged against the row read before the lock, whose type decided how the request+ // reads. If another save changed it since, writing now would set a half this request left out back to+ // an older value.+ if (credential) {+ const current = await agentVaultServiceDAL.findById(service.id, tx);+ if (!current) throw new NotFoundError({ message: `Service with ID '${serviceId}' not found` });+ const secretChanged =+ storedSecret !== null && !current.encryptedCredential?.equals(service.encryptedCredential!);+ if (current.credentialType !== service.credentialType || secretChanged) {+ throw new ConflictError({ message: CREDENTIAL_CHANGED_DURING_SAVE_MESSAGE });+ }+ }+// Both halves read under the lock and on the primary. The service read above the transaction came off// a replica, and stale it would admit the very collision this check exists to stop.if (credential || customHeaders) {@@ -1111,55 +1161,64 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund"substitution");- // 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] : []- );+ // Every value this save sealed has its rows rebuilt from what it sealed: the whole secret when it was+ // rewritten, since a kept half is sealed again with it. A row's position is its index in the list just+ // written, which is how a value finds its row, and a row dropped from the list takes its references+ // with it through the foreign key.+ const rewrittenCustomHeaders = updatedCustomHeaders.flatMap((row) => {+ const storedValue = storedCustomHeaderValues[row.position];+ return storedValue === undefined ? [] : [{ id: row.id, storedValue }];+ });+ const rewrittenSubstitutions = updatedSubstitutions.flatMap((row) => {+ const storedValue = storedSubstitutionValues[row.position];+ return storedValue === undefined ? [] : [{ id: row.id, storedValue }];+ });- if (replacedCredentialFields.length) {+ if (writtenSecret !== undefined) {await agentVaultServiceVariableReferenceDAL.delete(- { serviceId: service.id, $in: { field: replacedCredentialFields } },+ {+ serviceId: service.id,+ $in: {+ field: [+ AgentVaultVariableReferenceField.CredentialValue,+ AgentVaultVariableReferenceField.CredentialUsername+ ]+ }+ },tx);}- if (rewrittenCustomHeaderIds.length) {- await agentVaultServiceVariableReferenceDAL.delete({ $in: { customHeaderId: rewrittenCustomHeaderIds } }, tx);+ if (rewrittenCustomHeaders.length) {+ await agentVaultServiceVariableReferenceDAL.delete(+ { $in: { customHeaderId: rewrittenCustomHeaders.map((row) => row.id) } },+ tx+ );}- if (rewrittenSubstitutionIds.length) {- await agentVaultServiceVariableReferenceDAL.delete({ $in: { substitutionId: rewrittenSubstitutionIds } }, tx);+ if (rewrittenSubstitutions.length) {+ await agentVaultServiceVariableReferenceDAL.delete(+ { $in: { substitutionId: rewrittenSubstitutions.map((row) => row.id) } },+ tx+ );}- const referenceRows = toReferenceRows(service.id, idOfKey, rewrittenTargets);+ const referenceRows = [+ ...(writtenSecret === undefined ? [] : credentialReferenceRowsOf(service.id, writtenSecret, variableIds)),+ ...rewrittenCustomHeaders.flatMap(({ id, storedValue }) =>+ referenceRowsOf(+ service.id,+ { field: AgentVaultVariableReferenceField.CustomHeader, customHeaderId: id },+ storedValue,+ variableIds+ )+ ),+ ...rewrittenSubstitutions.flatMap(({ id, storedValue }) =>+ referenceRowsOf(+ service.id,+ { field: AgentVaultVariableReferenceField.Substitution, substitutionId: id },+ storedValue,+ variableIds+ )+ )+ ];if (referenceRows.length) await agentVaultServiceVariableReferenceDAL.insertMany(referenceRows, tx);const variableReferences = await agentVaultServiceVariableReferenceDAL.findByServiceIds([service.id], tx);diff --git a/backend/src/ee/services/agent-vault/CLAUDE.md b/backend/src/ee/services/agent-vault/CLAUDE.mdindex 4e342db5bd..3e31591450 100644--- a/backend/src/ee/services/agent-vault/CLAUDE.md+++ b/backend/src/ee/services/agent-vault/CLAUDE.md@@ -169,13 +169,24 @@ path decides what a service can reach, so it stays literal.refusal, and the keys the service sheet lists under a stored value. **Resolve does not read it**: it pullsthe ids out of the decrypted fields, so a service saved mid-poll can never leave the two describingdifferent versions of a field.+- **The rows are read off the stored text, never off the request**: `findStoredVariableIds`, kept to the+ bundle's own variables, which is exactly what resolve expands. Nothing in the database can compare the+ rows with sealed text, and an id with no row is a variable the delete refusal lets go while a service still+ sends it. Any new path that seals a service field derives its rows the same way, and moving a service to+ another bundle would have to remap its ids, since resolve expands only its own bundle's.- A stored value never comes back in any form, a lone `{{KEY}}` included. The sheet lists the keys a storedfield uses under the field and keeps the field masked until it is retyped. Settled: putting a lonereference back in its field made it the one stored field that shows, and left a field mixing text with areference looking like it used none.-- 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.+- A save rebuilds the rows of each value it seals: both credential fields whenever the secret is written, since+ a kept basic half is sealed again with it, and each header or substitution whose value arrived. An omitted+ value keeps its sealed text and its rows, and a dropped header or substitution takes its rows through the+ foreign key.+- Only text that arrived is mapped from keys to ids. A kept basic half is already stored text, and one saved+ before variables existed has to keep reaching the host as it was, braces included.+- A credential update merges against the service read before the lock, so under the lock it re-reads the row+ and returns a 409 if the type changed, or, for a partial basic update, the sealed secret did. Otherwise the+ half left out is written back stale, and its rows describe text that is no longer sealed.- The `variableId` key is `DEFERRABLE INITIALLY DEFERRED`. A bundle delete cascades to its services and itsvariables in one statement, and an immediate check can fire before the service cascade has removed therows, depending on which constraint was created first. The refusal that matters is the check under the