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): limit references per value and filled-in length
Scott Wilsonc1f1035c6011
diff --git a/backend/e2e-test/routes/v1/agent-vault.spec.ts b/backend/e2e-test/routes/v1/agent-vault.spec.tsindex a626da8d6a..d969757b64 100644--- a/backend/e2e-test/routes/v1/agent-vault.spec.ts+++ b/backend/e2e-test/routes/v1/agent-vault.spec.ts@@ -745,6 +745,8 @@ describe("Agent Vault V1 Router", async () => {type TResolved = {services: {name: string;+ allowedMethods: string[] | null;+ allowedPathPrefixes: string[] | null;credential: Record<string, string>;customHeaders: { name: string; prefix: string; value: string }[];substitutions: { placeholder: string; surfaces: string[]; value: string }[];@@ -947,6 +949,27 @@ 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 () => {+ const bundle = await createAccessBundle("variables-oversized");+ const long = await createVariable(bundle.id, { key: "LONG", value: "x".repeat(8192) });+ const created = await inject("POST", servicesUrl(bundle.id), {+ name: "oversized",+ hostPattern: "api.example.com",+ allowedMethods: ["GET"],+ allowedPathPrefixes: ["/v1"],+ credential: { type: "bearer", value: "{{LONG}}{{LONG}}" },+ customHeaders: [{ name: "X-Long", value: "{{LONG}}" }]+ });+ expect(created.statusCode).toBe(200);++ const resolve = await resolverFor(bundle, "variables-oversized");+ const [resolved] = (await resolve()).services;+ expect(resolved.credential).toMatchObject({ type: "bearer", value: `{{${long.id}}}{{${long.id}}}` });+ expect(resolved.customHeaders[0].value).toBe("x".repeat(8192));+ expect(resolved.allowedMethods).toEqual(["GET"]);+ expect(resolved.allowedPathPrefixes).toEqual(["/v1"]);+ });+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" });@@ -1048,6 +1071,31 @@ describe("Agent Vault V1 Router", async () => {expect(await testDb("agent_vault_services").where({ accessBundleId: bundle.id })).toHaveLength(0);});+ test("a value takes ten variable references, a repeat counted each time, and an eleventh fails validation", async () => {+ const bundle = await createAccessBundle("variables-reference-limit");+ await createVariable(bundle.id, { key: "TOKEN", value: "t" });++ const atLimit = await inject("POST", servicesUrl(bundle.id), {+ name: "at-limit",+ hostPattern: "at-limit.example.com",+ credential: { type: "bearer", value: "{{TOKEN}}".repeat(10) }+ });+ expect(atLimit.statusCode).toBe(200);++ const overLimit = await inject("POST", servicesUrl(bundle.id), {+ name: "over-limit",+ hostPattern: "over-limit.example.com",+ credential: { type: "bearer", value: "{{TOKEN}}".repeat(11) }+ });+ expect(overLimit.statusCode).toBe(422);+ expect(overLimit.payload).toContain("at most 10 variable references");++ const services = (await testDb("agent_vault_services").where({ accessBundleId: bundle.id })) as {+ name: string;+ }[];+ expect(services.map((service) => service.name)).toEqual(["at-limit"]);+ });+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" });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 36b418488d..e798650855 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,7 +24,11 @@ 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 {+ AGENT_VAULT_EXPANDED_FIELD_MAX_LENGTH,+ 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";@@ -318,8 +322,9 @@ export const agentVaultProxyServiceFactory = ({};// 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.+ // never leave the two describing different versions of a field. An id with nothing behind it stays as text,+ // and so does a field its variables would fill past the length cap: dropping the service instead would also+ // drop its method and path restrictions.const $expandVariableReferences = async ({sessionId,services,@@ -354,6 +359,7 @@ export const agentVaultProxyServiceFactory = ({const opened = new Map<string, string>();const unresolvedServiceIds = new Set<string>();+ const oversizedServiceIds = new Set<string>();const expanded = services.map((service) => {const valueOf = (variableId: string) => {@@ -370,7 +376,11 @@ export const agentVaultProxyServiceFactory = ({}return value;};- const expand = (text: string) => expandStoredVariableReferences(text, valueOf);+ const expand = (text: string) => {+ const filledIn = expandStoredVariableReferences(text, valueOf);+ if (filledIn === undefined) oversizedServiceIds.add(service.id);+ return filledIn ?? text;+ };let { credential } = service;if (credential.type === "bearer") credential = { ...credential, value: expand(credential.value) };@@ -394,6 +404,11 @@ export const agentVaultProxyServiceFactory = ({`agentVaultResolve: stored variable reference with no variable [sessionId=${sessionId}] [serviceIds=${[...unresolvedServiceIds].join(",")}]`);}+ if (oversizedServiceIds.size) {+ logger.warn(+ `agentVaultResolve: variables fill a field past ${AGENT_VAULT_EXPANDED_FIELD_MAX_LENGTH} characters [sessionId=${sessionId}] [serviceIds=${[...oversizedServiceIds].join(",")}]`+ );+ }return expanded;};diff --git a/backend/src/ee/services/agent-vault/CLAUDE.md b/backend/src/ee/services/agent-vault/CLAUDE.mdindex 3e31591450..309c0341f3 100644--- a/backend/src/ee/services/agent-vault/CLAUDE.md+++ b/backend/src/ee/services/agent-vault/CLAUDE.md@@ -195,10 +195,17 @@ path decides what a service can reach, so it stays literal.refused without quoting it, because the text was cut from a secret. Placeholders can't contain doublebraces. A variable's own value is sent as is and never expanded again, which is also how a service sends aliteral `{{`.+- **A value takes at most 10 references** (`AGENT_VAULT_MAX_REFERENCES_PER_FIELD`), and a repeat counts each+ time: repeating one short reference is what fills a field in to millions of characters. The field schemas+ refuse an eleventh with a 422, and the service sheet checks the same limit before it saves.- Resolve reads variable values on a replica, then asks the primary for any id the replica lacks, since eachquery can land on a different replica. An id with no variable behind it on either stays as text and islogged rather than dropping the service, which would also drop the service's method and path restrictions.Values saved before variables existed hold no id tokens, so they pass through untouched.+- **A field is held to 8,192 characters filled in** (`AGENT_VAULT_EXPANDED_FIELD_MAX_LENGTH`), measured+ before 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.- 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-transformation-schemas.ts b/backend/src/ee/services/agent-vault/agent-vault-transformation-schemas.tsindex 962ce24d83..9e4171cab7 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,7 +9,12 @@ 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";+import {+ AGENT_VAULT_MALFORMED_REFERENCE_MESSAGE,+ AGENT_VAULT_TOO_MANY_REFERENCES_MESSAGE,+ hasMalformedVariableReference,+ hasTooManyVariableReferences+} from "./agent-vault-variable-fns";export const AGENT_VAULT_MAX_CUSTOM_HEADERS = 20;export const AGENT_VAULT_MAX_SUBSTITUTIONS = 20;@@ -49,7 +54,9 @@ const headerPrefixSchema = z// 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);+ schema+ .refine((value) => !hasMalformedVariableReference(value), AGENT_VAULT_MALFORMED_REFERENCE_MESSAGE)+ .refine((value) => !hasTooManyVariableReferences(value), AGENT_VAULT_TOO_MANY_REFERENCES_MESSAGE);const secretValueSchema = acceptsVariableReferences(z.string().min(1).max(8192).regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)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 a0b5cee056..b3c39e6028 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@@ -1,10 +1,13 @@import { describe, expect, it } from "vitest";import {+ AGENT_VAULT_EXPANDED_FIELD_MAX_LENGTH,+ AGENT_VAULT_MAX_REFERENCES_PER_FIELD,expandStoredVariableReferences,findStoredVariableIds,findVariableKeys,hasMalformedVariableReference,+ hasTooManyVariableReferences,isVariableKey,toStoredVariableReferences} from "./agent-vault-variable-fns";@@ -58,6 +61,19 @@ describe("agent vault variable references", () => {});});+ describe("limiting references", () => {+ it("takes up to the limit, counting a repeated reference each time", () => {+ expect(hasTooManyVariableReferences("{{A}}".repeat(AGENT_VAULT_MAX_REFERENCES_PER_FIELD))).toBe(false);+ expect(hasTooManyVariableReferences("{{A}}".repeat(AGENT_VAULT_MAX_REFERENCES_PER_FIELD + 1))).toBe(true);+ });++ it("counts different keys the same way", () => {+ const keys = Array.from({ length: AGENT_VAULT_MAX_REFERENCES_PER_FIELD + 1 }, (_, index) => `{{KEY_${index}}}`);+ expect(hasTooManyVariableReferences(keys.slice(1).join(":"))).toBe(false);+ expect(hasTooManyVariableReferences(keys.join(":"))).toBe(true);+ });+ });+describe("storing", () => {const idOfKey = new Map([["GITHUB_TOKEN", GITHUB_ID],@@ -123,5 +139,24 @@ describe("agent vault variable references", () => {const stored = toStoredVariableReferences("Bearer {{GITHUB_TOKEN}}", idOfKey);expect(expandStoredVariableReferences(stored, (id) => values[id])).toBe("Bearer ghp_alpha");});++ it("fills in up to the length cap, counting the text around the references", () => {+ const value = "v".repeat(AGENT_VAULT_EXPANDED_FIELD_MAX_LENGTH - 1);+ expect(expandStoredVariableReferences(`x{{${GITHUB_ID}}}`, () => value)).toBe(`x${value}`);+ expect(expandStoredVariableReferences(`xy{{${GITHUB_ID}}}`, () => value)).toBeUndefined();+ });++ it("gives up on a field that short references would fill to millions of characters", () => {+ const idOfKey = new Map([["A", GITHUB_ID]]);+ const stored = toStoredVariableReferences("{{A}}".repeat(1638), idOfKey);+ expect(expandStoredVariableReferences(stored, () => "v".repeat(8192))).toBeUndefined();+ });++ it("measures a field by its filled-in length, not its stored one", () => {+ const idOfKey = new Map([["A", GITHUB_ID]]);+ const stored = toStoredVariableReferences("{{A}}".repeat(1638), idOfKey);+ expect(stored.length).toBeGreaterThan(AGENT_VAULT_EXPANDED_FIELD_MAX_LENGTH);+ expect(expandStoredVariableReferences(stored, () => "a")).toBe("a".repeat(1638));+ });});});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 8aaadce2c0..897127c571 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@@ -3,6 +3,11 @@ 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;+// Counts every {{...}}, a repeat included: repeating one short reference is what lets a field fill in to+// millions of characters.+export const AGENT_VAULT_MAX_REFERENCES_PER_FIELD = 10;+// No field that takes a variable accepts more than this typed out, and filled in it is held to the same.+export const AGENT_VAULT_EXPANDED_FIELD_MAX_LENGTH = 8192;export const AGENT_VAULT_VARIABLE_KEY_RE = new RE2(/^[A-Z][A-Z0-9_]*$/);@@ -12,6 +17,8 @@ export const AGENT_VAULT_VARIABLE_KEY_MESSAGE =// 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}`;+export const AGENT_VAULT_TOO_MANY_REFERENCES_MESSAGE = `A value can use at most ${AGENT_VAULT_MAX_REFERENCES_PER_FIELD} variable references, and a reference that repeats counts each time. Combine some into one variable to use fewer.`;+// 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);@@ -26,6 +33,9 @@ const findReferenceTokens = (text: string) => Array.from(text.matchAll(REFERENCEexport const hasMalformedVariableReference = (text: string) =>findReferenceTokens(text).some((token) => !isVariableKey(token));+export const hasTooManyVariableReferences = (text: string) =>+ findReferenceTokens(text).length > AGENT_VAULT_MAX_REFERENCES_PER_FIELD;+export const findVariableKeys = (text: string) => [...new Set(findReferenceTokens(text).filter((token) => isVariableKey(token)))];@@ -48,8 +58,22 @@ export const findStoredVariableIds = (text: string) => [/*** 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.+ *+ * Returns undefined, without building the text, when it would come out longer than+ * AGENT_VAULT_EXPANDED_FIELD_MAX_LENGTH. The input limits alone don't hold it there: ten references to 8,192+ * character values fill one field in to over 80,000 characters.*/-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- );+export const expandStoredVariableReferences = (+ text: string,+ valueOfId: (variableId: string) => string | undefined+): 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;++ 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 5f341dd43e..cef3460c85 100644--- a/docs/documentation/platform/agent-vault/variables.mdx+++ b/docs/documentation/platform/agent-vault/variables.mdx@@ -57,6 +57,8 @@ To use a variable: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`.+A 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.+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.diff --git a/frontend/src/helpers/agentVaultVariables.ts b/frontend/src/helpers/agentVaultVariables.tsindex 42b32253b4..db4212ff8f 100644--- a/frontend/src/helpers/agentVaultVariables.ts+++ b/frontend/src/helpers/agentVaultVariables.ts@@ -1,5 +1,6 @@export const VARIABLE_KEY_MAX_LENGTH = 64;export const VARIABLE_VALUE_MAX_LENGTH = 8192;+export const MAX_REFERENCES_PER_FIELD = 10;export const VARIABLE_KEY_RE = /^[A-Z][A-Z0-9_]*$/;@@ -66,6 +67,10 @@ export const findOpenVariableReference = (textBeforeCaret: string) => {export const variableReferenceError = (text: string, keys?: ReadonlySet<string>): string | null => {const refs = findVariableReferences(text);+ if (refs.length > MAX_REFERENCES_PER_FIELD) {+ return `Use at most ${MAX_REFERENCES_PER_FIELD} variable references in one value. A repeated reference counts each time.`;+ }+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.`;