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): refuse values that fill in past the length cap
Scott Wilson68dd2449fd36
diff --git a/backend/e2e-test/routes/v1/agent-vault.spec.ts b/backend/e2e-test/routes/v1/agent-vault.spec.tsindex d969757b64..72fa0ad730 100644--- a/backend/e2e-test/routes/v1/agent-vault.spec.ts+++ b/backend/e2e-test/routes/v1/agent-vault.spec.ts@@ -949,9 +949,52 @@ describe("Agent Vault V1 Router", async () => {expect(resolved.substitutions[0].value).toBe("org-42");});- test("a field its variables would fill past 8,192 characters is sent as stored, and its service keeps its restrictions", async () => {+ test("a save its variables would fill past 8,192 characters is refused, from the service and from the variable", async () => {+ const bundle = await createAccessBundle("variables-overlong");+ await createVariable(bundle.id, { key: "LONG", value: "x".repeat(8192) });+ const short = await createVariable(bundle.id, { key: "SHORT", value: "s" });++ const doubled = await inject("POST", servicesUrl(bundle.id), {+ name: "doubled",+ hostPattern: "doubled.example.com",+ credential: { type: "bearer", value: "{{LONG}}{{LONG}}" }+ });+ expect(doubled.statusCode).toBe(400);+ expect(JSON.parse(doubled.payload).message).toContain("The token would be longer than 8192 characters");++ const created = await inject("POST", servicesUrl(bundle.id), {+ name: "at-cap",+ hostPattern: "at-cap.example.com",+ credential: { type: "bearer", value: "{{SHORT}}{{SHORT}}" },+ customHeaders: [{ name: "X-Long", value: "{{LONG}}" }]+ });+ expect(created.statusCode).toBe(200);+ const { service } = JSON.parse(created.payload) as { service: { id: string; customHeaders: { id: string }[] } };++ const prefixed = await inject("PATCH", `${servicesUrl(bundle.id)}/${service.id}`, {+ customHeaders: [{ id: service.customHeaders[0].id, name: "X-Long", value: "x{{LONG}}" }]+ });+ expect(prefixed.statusCode).toBe(400);+ expect(JSON.parse(prefixed.payload).message).toContain("The custom header 'X-Long' would be longer");++ // The token uses SHORT twice, so half the cap is the most SHORT can hold.+ const grown = await inject("PATCH", `${variablesUrl(bundle.id)}/${short.id}`, { value: "y".repeat(4097) });+ expect(grown.statusCode).toBe(400);+ expect(JSON.parse(grown.payload).message).toContain("the token of the service 'at-cap' would be longer");++ const resolve = await resolverFor(bundle, "variables-overlong");+ expect((await resolve()).services[0].credential).toMatchObject({ value: "ss" });++ const atCap = await inject("PATCH", `${variablesUrl(bundle.id)}/${short.id}`, { value: "y".repeat(4096) });+ expect(atCap.statusCode).toBe(200);+ const [resolved] = (await resolve()).services;+ expect(resolved.credential).toMatchObject({ value: "y".repeat(8192) });+ expect(resolved.customHeaders[0].value).toBe("x".repeat(8192));+ });++ test("a field that ends up past 8,192 characters anyway is sent as stored, and its service keeps its restrictions", async () => {const bundle = await createAccessBundle("variables-oversized");- const long = await createVariable(bundle.id, { key: "LONG", value: "x".repeat(8192) });+ const long = await createVariable(bundle.id, { key: "LONG", value: "x" });const created = await inject("POST", servicesUrl(bundle.id), {name: "oversized",hostPattern: "api.example.com",@@ -962,6 +1005,15 @@ describe("Agent Vault V1 Router", async () => {});expect(created.statusCode).toBe(200);+ // Sealed past the value check, the way a change that raced the service save would land.+ const { encryptor } = await cipherFor(bundle.id);+ await testDb("agent_vault_variables")+ .where({ id: long.id })+ .update({+ encryptedValue: encryptor({ plainText: Buffer.from(JSON.stringify({ value: "x".repeat(8192) })) })+ .cipherTextBlob+ });+const resolve = await resolverFor(bundle, "variables-oversized");const [resolved] = (await resolve()).services;expect(resolved.credential).toMatchObject({ type: "bearer", value: `{{${long.id}}}{{${long.id}}}` });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 8316b1316b..a253a850b8 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@@ -44,7 +44,9 @@ import {} from "../agent-vault/agent-vault-enums";import { getAgentVaultReachability } from "../agent-vault/agent-vault-permission";import {+ AGENT_VAULT_EXPANDED_FIELD_MAX_LENGTH,AGENT_VAULT_MAX_VARIABLES,+ filledInVariableLength,findStoredVariableIds,findVariableKeys,toStoredVariableReferences,@@ -285,6 +287,14 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundconst getProjectCipher = (projectId: string) =>kmsService.createCipherPairWithDataKey({ type: KmsDataKey.SecretManager, projectId });+ type TProjectCipher = Awaited<ReturnType<typeof getProjectCipher>>;++ const sealVariableValue = (encryptor: TProjectCipher["encryptor"], value: string) =>+ encryptor({ plainText: Buffer.from(JSON.stringify({ value })) }).cipherTextBlob;++ const openVariableValue = (decryptor: TProjectCipher["decryptor"], encryptedValue: Buffer) =>+ (JSON.parse(decryptor({ cipherTextBlob: encryptedValue }).toString("utf-8")) as { value: string }).value;+// `null` clears the sealed column, `undefined` leaves it alone. $decryptCredential reads a NULL secret// as passthrough, so the two are not interchangeable.type TCredentialWrite = { config: TAgentVaultCredentialConfig; secret: Record<string, string> | null | undefined };@@ -487,6 +497,66 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundreturn { idOfKey, variableIds: new Set(variables.map((variable) => variable.id)) };};+ // What an error calls each part of a sealed credential.+ const CREDENTIAL_PART_NOUNS: Record<string, string> = { value: "token", username: "username", password: "password" };++ // Resolve sends a field its variables would fill in past the cap as stored text, which reaches the host in place+ // of the credential, so every write that could build one measures it first. Measured before the lock, so a+ // service save racing a change to one of its variables can still land a field over the cap, and resolve then+ // holds it there.+ const findOverlongText = async <T extends { text: string }>({+ projectId,+ accessBundleId,+ texts,+ cipher,+ replacing+ }: {+ projectId: string;+ accessBundleId: string;+ texts: T[];+ cipher: TProjectCipher | null;+ replacing?: { variableId: string; value: string };+ }): Promise<T | undefined> => {+ const variableIds = new Set(texts.flatMap(({ text }) => findStoredVariableIds(text)));+ if (replacing) variableIds.delete(replacing.variableId);++ const lengthOf = new Map<string, number>();+ if (variableIds.size) {+ const [variables, { decryptor }] = await Promise.all([+ agentVaultVariableDAL.findByAccessBundleId(accessBundleId),+ cipher ?? getProjectCipher(projectId)+ ]);+ variables.forEach((variable) => {+ if (variableIds.has(variable.id)) {+ lengthOf.set(variable.id, openVariableValue(decryptor, variable.encryptedValue).length);+ }+ });+ }+ if (replacing) lengthOf.set(replacing.variableId, replacing.value.length);++ return texts.find(+ ({ text }) =>+ filledInVariableLength(text, (variableId) => lengthOf.get(variableId)) > AGENT_VAULT_EXPANDED_FIELD_MAX_LENGTH+ );+ };++ const assertServiceFieldsFitWhenFilledIn = async (params: {+ projectId: string;+ accessBundleId: string;+ texts: TReferencingText[];+ cipher: TProjectCipher | null;+ }) => {+ const overlong = await findOverlongText(params);+ if (overlong) {+ throw new BadRequestError({+ message: `${overlong.label} would be longer than ${AGENT_VAULT_EXPANDED_FIELD_MAX_LENGTH} characters once its variables are filled in. Use fewer variables in it, or shorten their values.`+ });+ }+ };++ const storedCredentialTexts = (storedSecret: TCredentialWrite["secret"]): TReferencingText[] =>+ Object.entries(storedSecret ?? {}).map(([part, text]) => ({ label: `The ${CREDENTIAL_PART_NOUNS[part]}`, text }));+// 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 = (@@ -804,7 +874,8 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund);assertCustomHeadersDoNotShadowCredential(config, customHeaders);- const { encryptor } = await getProjectCipher(rest.projectId);+ const cipher = await getProjectCipher(rest.projectId);+ const { encryptor } = cipher;const seal = (value: string) => encryptor({ plainText: Buffer.from(JSON.stringify({ value })) }).cipherTextBlob;const encryptedCredential = secret@@ -813,6 +884,22 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund// 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));+ await assertServiceFieldsFitWhenFilledIn({+ projectId: rest.projectId,+ accessBundleId: bundle.id,+ cipher,+ texts: [+ ...storedCredentialTexts(secret),+ ...(customHeaders ?? []).map((header, position) => ({+ label: `The custom header '${header.name}'`,+ text: storedCustomHeaderValues[position]+ })),+ ...(substitutions ?? []).map((substitution, position) => ({+ label: `The substitution for '${substitution.placeholder}'`,+ text: storedSubstitutionValues[position]+ }))+ ]+ });const customHeaderRows = (customHeaders ?? []).map((header, position) => ({name: header.name,prefix: header.prefix ?? "",@@ -1021,6 +1108,22 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundconst storedSubstitutionValues = (substitutions ?? []).map((substitution) =>substitution.value === undefined ? undefined : store(substitution.value));+ await assertServiceFieldsFitWhenFilledIn({+ projectId: rest.projectId,+ accessBundleId: bundle.id,+ cipher: storedSecretCipher ?? cipherForTransformations,+ texts: [+ ...storedCredentialTexts(writtenSecret),+ ...(customHeaders ?? []).flatMap((header, index) => {+ const text = storedCustomHeaderValues[index];+ return text === undefined ? [] : [{ label: `The custom header '${header.name}'`, text }];+ }),+ ...(substitutions ?? []).flatMap((substitution, index) => {+ const text = storedSubstitutionValues[index];+ return text === undefined ? [] : [{ label: `The substitution for '${substitution.placeholder}'`, text }];+ })+ ]+ });const customHeaderWrites: TTransformationWrite<{ name: string; prefix: string }>[] | undefined = customHeaders?.map((header, index) => ({@@ -1268,14 +1371,6 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund};};- 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,@@ -1368,6 +1463,88 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund}};+ // A new value reaches every field that uses the variable on the next resolve, so each of them is measured with it.+ const assertValueFitsItsServices = async ({+ projectId,+ accessBundleId,+ variableId,+ value,+ cipher+ }: {+ projectId: string;+ accessBundleId: string;+ variableId: string;+ value: string;+ cipher: TProjectCipher;+ }) => {+ const references = await agentVaultServiceVariableReferenceDAL.findByVariableIds([variableId]);+ if (!references.length) return;++ const serviceIds = [...new Set(references.map((reference) => reference.serviceId))];+ const [services, { customHeaders, substitutions }] = await Promise.all([+ agentVaultServiceDAL.find({ accessBundleId, $in: { id: serviceIds } }),+ loadTransformations(serviceIds, undefined, { withVariableReferences: false })+ ]);+ const serviceNameOf = new Map(services.map((service) => [service.id, service.name]));++ const usedInCredential = new Set(+ references+ .filter(+ (reference) =>+ reference.field === AgentVaultVariableReferenceField.CredentialValue ||+ reference.field === AgentVaultVariableReferenceField.CredentialUsername+ )+ .map((reference) => reference.serviceId)+ );+ const usedInRow = new Set(+ references.flatMap((reference) => {+ const rowId = reference.customHeaderId ?? reference.substitutionId;+ return rowId ? [rowId] : [];+ })+ );++ const open = (sealed: Buffer) =>+ JSON.parse(cipher.decryptor({ cipherTextBlob: sealed }).toString("utf-8")) as Record<string, string>;+ const fields = [+ ...services.flatMap((service) =>+ usedInCredential.has(service.id) && service.encryptedCredential+ ? Object.entries(open(service.encryptedCredential)).map(([part, text]) => ({+ serviceId: service.id,+ label: `the ${CREDENTIAL_PART_NOUNS[part]}`,+ text+ }))+ : []+ ),+ ...customHeaders+ .filter((row) => usedInRow.has(row.id) && serviceNameOf.has(row.serviceId))+ .map((row) => ({+ serviceId: row.serviceId,+ label: `the custom header '${row.name}'`,+ text: open(row.encryptedValue).value+ })),+ ...substitutions+ .filter((row) => usedInRow.has(row.id) && serviceNameOf.has(row.serviceId))+ .map((row) => ({+ serviceId: row.serviceId,+ label: `the substitution for '${row.placeholder}'`,+ text: open(row.encryptedValue).value+ }))+ ];++ const overlong = await findOverlongText({+ projectId,+ accessBundleId,+ texts: fields,+ cipher,+ replacing: { variableId, value }+ });+ if (overlong) {+ throw new BadRequestError({+ message: `With this value, ${overlong.label} of the service '${serviceNameOf.get(overlong.serviceId)}' would be longer than ${AGENT_VAULT_EXPANDED_FIELD_MAX_LENGTH} characters once its variables are filled in. Use a shorter value, or fewer variables in it.`+ });+ }+ };+const updateVariable = async ({ accessBundleId, variableId, key, value, isSecret, ...rest }: TUpdateVariableDTO) => {const bundle = await resolveVariableBundle({ ...rest, accessBundleId });@@ -1377,6 +1554,15 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundconst cipher =value !== undefined || !(isSecret ?? variable.isSecret) ? await getProjectCipher(rest.projectId) : null;const encryptedValue = value === undefined ? undefined : sealVariableValue(cipher!.encryptor, value);+ if (value !== undefined) {+ await assertValueFitsItsServices({+ projectId: rest.projectId,+ accessBundleId: bundle.id,+ variableId: variable.id,+ value,+ cipher: cipher!+ });+ }const write = () =>agentVaultVariableDAL.transaction(async (tx) => {diff --git a/backend/src/ee/services/agent-vault/CLAUDE.md b/backend/src/ee/services/agent-vault/CLAUDE.mdindex 309c0341f3..5c807c6a4f 100644--- a/backend/src/ee/services/agent-vault/CLAUDE.md+++ b/backend/src/ee/services/agent-vault/CLAUDE.md@@ -204,8 +204,11 @@ path decides what a service can reach, so it stays literal.Values saved before variables existed hold no id tokens, so they pass through untouched.- **A field is held to 8,192 characters filled in** (`AGENT_VAULT_EXPANDED_FIELD_MAX_LENGTH`), measuredbefore anything is built. The input limits don't hold it there: ten references to 8,192 character values- fill one field in to over 80,000 characters, and a service has up to 42 such fields. A field over the cap- stays as stored text and is logged, for the same reason as an unresolved id. Saves don't check it.+ fill one field in to over 80,000 characters, and a service has up to 42 such fields. Saves refuse a field+ that would pass it, since resolve would send its stored text to the host in place of the credential: a+ service save measures each value it seals, and a value change measures every field that uses the variable.+ Both measure before the lock, so a service save racing a value change can still land a field over the cap.+ Resolve sends that field as stored text and logs it, for the same reason as an unresolved id.- Admin only, reads included: every variable route checks `Edit` on access bundles, which a member lacks,and the bundle read gives a member its services without `variableReferences` (left out, not empty, sincean empty list would claim they use none). Every value is sealed;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.tsindex b3c39e6028..4e5ffc5199 100644--- 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.ts@@ -4,6 +4,7 @@ import {AGENT_VAULT_EXPANDED_FIELD_MAX_LENGTH,AGENT_VAULT_MAX_REFERENCES_PER_FIELD,expandStoredVariableReferences,+ filledInVariableLength,findStoredVariableIds,findVariableKeys,hasMalformedVariableReference,@@ -103,6 +104,29 @@ describe("agent vault variable references", () => {});});+ describe("measuring filled-in length", () => {+ const lengths: Record<string, number> = { [GITHUB_ID]: 100, [DATADOG_ID]: 7 };++ it("counts each reference as its value, a repeat included, plus the text around it", () => {+ expect(filledInVariableLength(`a{{${GITHUB_ID}}}b{{${DATADOG_ID}}}{{${GITHUB_ID}}}`, (id) => lengths[id])).toBe(+ 2 + 100 + 7 + 100+ );+ });++ it("counts a stored id with no length behind it, and a key-form reference, as the text they stay as", () => {+ expect(filledInVariableLength(`{{${GITHUB_ID}}}`, () => undefined)).toBe(`{{${GITHUB_ID}}}`.length);+ expect(filledInVariableLength("{{GITHUB_TOKEN}}", () => 100)).toBe("{{GITHUB_TOKEN}}".length);+ });++ it("agrees with the length expanding produces", () => {+ const values: Record<string, string> = { [GITHUB_ID]: "ghp_alpha", [DATADOG_ID]: "dd_beta" };+ const stored = `Bearer {{${GITHUB_ID}}}:{{${DATADOG_ID}}}`;+ expect(filledInVariableLength(stored, (id) => values[id]?.length)).toBe(+ expandStoredVariableReferences(stored, (id) => values[id])!.length+ );+ });+ });+describe("expanding", () => {const values: Record<string, string> = { [GITHUB_ID]: "ghp_alpha", [DATADOG_ID]: "dd_beta" };diff --git a/backend/src/ee/services/agent-vault/agent-vault-variable-fns.ts b/backend/src/ee/services/agent-vault/agent-vault-variable-fns.tsindex 897127c571..aa501886d1 100644--- a/backend/src/ee/services/agent-vault/agent-vault-variable-fns.ts+++ b/backend/src/ee/services/agent-vault/agent-vault-variable-fns.ts@@ -55,6 +55,16 @@ export const findStoredVariableIds = (text: string) => [...new Set(findReferenceTokens(text).filter((token) => STORED_REFERENCE_RE.test(token)))];+/**+ * How long stored text comes out once its references are filled in, measured without building it. An id with+ * no length behind it counts as its own token, which is what expanding leaves in its place.+ */+export const filledInVariableLength = (text: string, lengthOfId: (variableId: string) => number | undefined) =>+ Array.from(text.matchAll(REFERENCE_RE)).reduce((length, [token, inner]) => {+ const valueLength = STORED_REFERENCE_RE.test(inner) ? lengthOfId(inner) : undefined;+ return valueLength === undefined ? length : length + valueLength - token.length;+ }, text.length);+/*** 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.@@ -69,11 +79,11 @@ export const expandStoredVariableReferences = (): string | undefined => {const valueOf = (inner: string) => (STORED_REFERENCE_RE.test(inner) ? valueOfId(inner) : undefined);- const expandedLength = Array.from(text.matchAll(REFERENCE_RE)).reduce((length, [token, inner]) => {- const value = valueOf(inner);- return value === undefined ? length : length + value.length - token.length;- }, text.length);- if (expandedLength > AGENT_VAULT_EXPANDED_FIELD_MAX_LENGTH) return undefined;+ if (+ filledInVariableLength(text, (variableId) => valueOfId(variableId)?.length) > AGENT_VAULT_EXPANDED_FIELD_MAX_LENGTH+ ) {+ return undefined;+ }return text.replace(REFERENCE_RE, (token: string, inner: string) => valueOf(inner) ?? token);};diff --git a/docs/documentation/platform/agent-vault/variables.mdx b/docs/documentation/platform/agent-vault/variables.mdxindex cef3460c85..768843c72a 100644--- a/docs/documentation/platform/agent-vault/variables.mdx+++ b/docs/documentation/platform/agent-vault/variables.mdx@@ -59,6 +59,8 @@ A reference can be the whole value or part of it. For example, if a custom headeA value can contain up to 10 references. If a value uses the same key more than once, each use counts as a reference, so `{{ORG_ID}}/{{ORG_ID}}` contains two.+A value can be at most 8,192 characters long after the proxy replaces its references. If a value would be longer, Infisical won't save the service.+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.@@ -71,6 +73,8 @@ To change a variable, open its actions menu in the **Variables** list and selectIf 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.+If the new value would make one of a service's values longer than 8,192 characters, Infisical won't save the change, and the error names the service.+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