Skip to content

Fix: encode and validate OpenAPI path parameters in RestApiTool - #638

Merged
ScottMansfield merged 9 commits into
google:mainfrom
AmaadMartin:fix/openapi-path-param-encoding-597
Aug 10, 2026
Merged

ScottMansfield merged 9 commits into
google:mainfrom
AmaadMartin:fix/openapi-path-param-encoding-597

Conversation

@AmaadMartin

Copy link
Copy Markdown
Collaborator

Please ensure you have read the contribution guide before creating a pull request.

Link to Issue or Description of Change

1. Link to an existing issue (if applicable):

Problem:

Values bound to OpenAPI path parameters were substituted into the request URL verbatim, with no percent-encoding (core/src/tools/openapi_tool/rest_api_tool.ts):

if (location === 'path') {
  pathParams[originalName] = String(argValue); // no encoding
}
let url = `${endpoint.baseUrl}${endpoint.path}`; // includes the host
for (const [key, value] of Object.entries(pathParams)) {
  url = url.replace(`{${key}}`, value); // raw string substitution
}

Those values come from the LLM, and applyCredential attaches the application's API key / bearer token to the assembled URL immediately afterwards. This is a defense asymmetry inside a single function: query values in the same loop go through URLSearchParams, and the API key goes through encodeURIComponent — only path values were raw. The three defects reported in #597 followed, plus a fourth smaller one:

# variant url before this change
1 path traversal — user_id: '../../admin/export' on /v1/users/{user_id} https://api.example.com/v1/users/../../admin/export, which fetch's URL parse resolves to https://api.example.com/admin/export?key=SECRET
2 query smuggling — user_id: 'x?role=admin&debug=true' https://api.example.com/v1/users/x?role=admin&debug=true; role/debug are adopted as real query parameters by the ?-splitting block
3 SSRF + credential exfiltration — baseUrl: 'https://{region}.api.example.com', region: 'evil.attacker.com/' https://evil.attacker.com/.api.example.com/v1/data?key=SECRET_API_KEY — the substitution loop ran over the host, and collectOperations never resolved OpenAPI Server Object variables, so {region} survived into baseUrl
4 String.replace with a string pattern replaces only the first occurrence and expands $& / $` / $' / $1 in the replacement a repeated placeholder stayed unsubstituted; a value containing $& was corrupted

Honest scope statement: exploiting this requires the model to be steered into emitting the malicious argument, i.e. there is a prompt-injection precondition. This is a defense-in-depth / hardening fix, not a directly-exploitable remote vulnerability. It is nonetheless a concrete encoding gap in a boundary the spec is expected to enforce. #597 records that this was reported to the Google OSS VRP (538901535), that the team declined to track it as a security bug, and that public disclosure was authorized — so there is no embargo on the description above.

Solution:

Two source files change (+75 lines of src).

core/src/tools/openapi_tool/rest_api_tool.ts

  • New module-level encodePathParamValue(name, value): encodeURIComponent the value, and reject a value that is exactly . or ... Encoding alone is not sufficient for a dot-segment — measured, not assumed: encodeURIComponent('..') returns '..' unchanged (dots are unreserved), and even a hand-written %2E%2E is normalized by the WHATWG URL parser, so new URL('https://a.com/v1/users/%2E%2E/x').pathname is /v1/x. Conversely a raw % becomes %25 under encodeURIComponent ('%2e%2e' -> '%252e%252e'), so the two exact-string comparisons are complete: no input other than the literal ./.. can re-form a dot-segment. This is deliberately not a ../ blocklist — '../../admin/export' and '..%2F' are accepted and encoded; only the two exact strings a URL parser treats as dot-segments are rejected. The error names the parameter but never echoes the value, which is attacker-influenced and reaches the model and the logs.
  • Placeholders are resolved against endpoint.path only, then concatenated with an untouched baseUrl, so a path parameter is structurally incapable of reaching the host. The single regex pass with a function replacement also fixes defect 4.
  • pathParams becomes a Map, not a plain object. This is required, not cosmetic: placeholder names come from the spec's path template, and an object lookup would resolve {constructor} against Object.prototype and substitute a function into the URL.

core/src/tools/openapi_tool/openapi_spec_parser/openapi_spec_parser.ts

  • New module-level resolveServerUrl(server) substitutes Server Object {name} variables from their declared default, falling back to the first enum entry when the default is the empty string. collectOperations uses it instead of reading servers[0].url verbatim. A placeholder that no declared variable can fill throws from inside the replacer, naming the offending variable and the servers[].variables field. It reports the first unresolved variable rather than aggregating every one: collecting them all needs an accumulator, a return placeholder branch and a trailing check (24 lines against 13) to buy a marginally kinder message in a case no test pins, and a spec author fixing them one re-run at a time reaches the same place.

This second file is not separable scope: confining substitution to endpoint.path is what fixes variant 3, but on its own it would leave a literal {region} in the host for exactly the specs that previously had it filled in by a same-named path parameter — turning a steerable request into a broken one. Resolving the variable from its declared default is the spec-compliant way to fill that placeholder, so the two changes have to land together for variant 3 to end up at a working, non-steerable request rather than a malformed URL.

Post-fix results for the three variants from #597:

variant url after
1 https://api.example.com/v1/users/..%2F..%2Fadmin%2Fexport (new URL(url).pathname === '/v1/users/..%2F..%2Fadmin%2Fexport')
2 https://api.example.com/v1/users/x%3Frole%3Dadmin%26debug%3Dtrue ([...new URL(url).searchParams.keys()] is empty)
3 with variables: {region: {default: 'us-central1'}} the parser yields https://us-central1.api.example.com and the request stays there; an endpoint whose baseUrl still holds a literal {region} keeps it — evil.attacker.com never appears
user_id: '..' throws Error, no request is sent

Two intentional behavior changes, both without an opt-out.

  1. Reserved and sub-delimiter characters in path values are now encoded. A spec that binds a multi-segment resource name (projects/p/locations/l) to a single {name} path parameter now produces projects%2Fp%2Flocations%2Fl instead of multiple path segments. That is the conformant encoding for a style: simple path parameter (allowReserved is defined only for in: query), and a value that can add path segments is precisely the vulnerability — the spec-side fix is to declare the segments as separate path parameters. This package implements no parameter serialization styles at all today (String(argValue) for every type), so no working feature regresses. There is deliberately no flag to disable the encoding: a knob that turns it off is a knob that restores the vulnerability. Everything in this package is @experimental.
  2. A templated servers[0].url with an undeclared variable now throws at toolset construction instead of silently issuing a request to a literal {region}.api.example.com host. OpenAPI requires every server variable to be declared, so only invalid specs are affected, and those specs were already sending broken requests. Verified that nothing existing starts throwing: no fixture or test in the repo uses a templated server URL (core/test/tools/openapi_tool/fixtures/petstore.yaml, fixtures/truanon.yaml and openapi_toolset_test.ts all use plain hosts), and the full core/test/tools/openapi_tool/ suite passes.

Deliberate omission. No post-substitution new URL(...) host allowlist check, which is the third remediation bullet in #597. Once placeholders can only land in endpoint.path and every value is percent-encoded, a value cannot reach the authority component at all, so such a check would be unreachable defensive code that invites the reader to think the structural guarantee is weaker than it is.

Not a parity change. adk-python has the identical gap (_prepare_request_params uses a plain str.format, and its OpenApiSpecParser reads servers[0]['url'] verbatim), so this is net-new behavior relative to Python and no parity claim is made. adk-python is untouched here.

Testing Plan

Unit Tests:

  • I have added or updated unit tests for my change.
  • All unit tests pass locally.

26 new test cases, all additive — no pre-existing test was edited, renamed, skipped or deleted.

  • core/test/tools/openapi_tool/rest_api_tool_test.ts — new nested describe('path parameter encoding') with 17 cases: traversal encoding, query smuggling (asserting the assembled URL carries zero query parameters), the credential still landing on a contained path via applyCredential + createApiKeyScheme, declared query parameters merging alongside an encoded path value, .. rejection, . rejection (exact message), no substitution into the host, reserved characters, $& non-expansion, repeated placeholder, unsupplied placeholder left literal, {constructor} not resolved from Object.prototype, %2e%2e double-encoding, and the positive round-trips — space, non-ASCII (café -> caf%C3%A9), a value of pure reserved characters asserted to decodeURIComponent back verbatim, and non-string (123, true) values.
  • core/test/tools/openapi_tool/openapi_spec_parser_test.ts — new describe('server URL resolution') with 8 cases: variables resolved from defaults (including two placeholders in one URL), enum[0] fallback when the default is empty, a throw naming an undeclared variable, a throw when a declared variable supplies neither default nor enum, a throw naming the unresolved variable when a sibling resolves (exact message), no servers, plain URL unchanged, and an end-to-end containment case that parses a templated spec and feeds parsed[0].endpoint straight into prepareRequestParams with region: 'evil.attacker.com/', asserting new URL(result.url).host === 'us-central1.api.example.com'. That case lives here rather than in the integration test because the property it pins is a property of the parser's output — that the baseUrl this parser produces cannot be steered by a later path argument — so it reads as parse -> parsed[0].endpoint -> prepareRequestParams with nothing mocked in between.
  • core/test/tools/openapi_tool/openapi_toolset_integration_test.ts — one case driving spec -> OpenAPIToolset -> RestApiTool.runAsync -> mocked fetch, the only place the encoding, applyCredential and the final URL are observed together. It builds a real Context/InvocationContext/Session rather than a cast mock.

Commands run:

npx vitest run --project unit:core core/test/tools/openapi_tool/   # 8 files, 108 tests passed
npm run build                                                      # clean
npm run lint                                                       # clean
npm run format:check                                               # clean
npm run docs:check                                                 # clean
npm run test                                                       # full suite, see below

npm run ts:check is not green in this repo and was not made so by this change: it reports 287 errors on main, all from test files resolving @google/adk to core/dist/types after a local build while also importing core/src relatively. Every such error in a file this PR touches (openapi_spec_parser_test.ts:141, :172, openapi_toolset_integration_test.ts:57, :92) git blames to #385 / #386, not to this branch, and no error references either src file this PR changes. .github/workflows/validation.yaml does not run ts:check.

Coverage. core/src/tools/openapi_tool/rest_api_tool.ts measures 100% statements / branches / functions / lines. In openapi_spec_parser.ts every statement and branch of the new resolveServerUrl and of its collectOperations call site is covered (checked per-branch against coverage-final.json, not just the file total); the file's only remaining gaps — the delete schemaDict['type'] line in sanitizeSchemaTypes and the options.preservePropertyNames ?? false default — are pre-existing and untouched.

Mutation proof. Every new test is killed by at least one mutation. Each source hunk was mutated in turn, the suite re-run, and the tree restored (baseline: 108 passed):

mutation result
a. return encodeURIComponent(value) -> return value 11 failed / 97 passed. expected 'http://api.example.com/v1/users/a b#c…' to be 'http://api.example.com/v1/users/a%20b…', and end to end expected '/admin/export' to be '/v1/users/..%2F..%2Fadmin%2Fexport'
b. substitute over baseUrl + path again 1 failed / 107 passed. expected 'https://evil.attacker.com%2F.api.exam…' to be 'https://{region}.api.example.com/v1/d…'
c. resolveServerUrl(...) -> spec.servers?.[0]?.url || '' 6 failed / 102 passed. expected '{region}.api.example.com' to be 'us-central1.api.example.com'; expected [Function] to throw an error
d. delete the ./.. guard, keep encodeURIComponent 2 failed / 106 passed. expected [Function] to throw an error
e. drop the enum fallback 1 failed / 107 passed. Unresolved server URL variable 'region' in 'https://{region}.api.example.com'.
f. never throw on an unresolved placeholder 3 failed / 105 passed. expected [Function] to throw an error
g. Map -> plain object lookup 1 failed / 107 passed. expected 'http://api.example.com/v1/function Ob…' to be 'http://api.example.com/v1/{constructo…'
h. drop the /g regex flag 1 failed / 107 passed. expected 'http://api.example.com/a/7/b/{id}' to be 'http://api.example.com/a/7/b/7'

Manual End-to-End (E2E) Tests:

No new e2e test: tests/e2e/tools/rest_api_tool_auth_e2e_test.ts uses path: '/test' with no path parameters, so it is unaffected by this change. It was run and fails at new Gemini(...) with API key must be provided via constructor or GOOGLE_GENAI_API_KEY or GEMINI_API_KEY environment variable — it needs live model credentials, which this environment does not have. That failure is environmental and was confirmed to reproduce identically on an unmodified tree.

To reproduce the fix by hand against a real endpoint:

  1. Register an OpenAPIToolset whose spec declares servers: [{url: 'https://api.example.com'}] and a path /v1/users/{user_id} with an apiKey security scheme.
  2. Invoke the generated tool with user_id = '../../admin/export'.
  3. Before this change the request went to https://api.example.com/admin/export?key=<your key>. After it, the request goes to https://api.example.com/v1/users/..%2F..%2Fadmin%2Fexport?key=<your key> — still authenticated, still inside the declared endpoint.
  4. Invoke it with user_id = '..': the tool now rejects with Invalid value for path parameter 'user_id': relative path segments ('.' and '..') are not allowed. and no request is sent. The throw propagates out of runAsync and the tool-calling flow converts it into the function-response error the model sees (and fires the plugin onToolError hook), so no new try/catch was added.
  5. To see change 2, give the spec servers: [{url: 'https://{region}.api.example.com'}] with no variables: the OpenAPIToolset constructor now throws Unresolved server URL variable 'region' in 'https://{region}.api.example.com'. Declare a default under servers[].variables. Adding variables: {region: {default: 'us-central1'}} resolves it.

Checklist

  • I have read the CONTRIBUTING.md document.
  • I have performed a self-review of my own code.
  • I have commented my code, particularly in hard-to-understand areas.
  • I have added tests that prove my fix is effective or that my feature works.
  • New and existing unit tests pass locally with my changes.

Amaad Martin added 7 commits August 6, 2026 21:11
…tApiTool

Path parameter values come from the model and were substituted into the
request URL verbatim, so a `/`, `?` or `#` let a value escape the path
segment (and the endpoint) the spec declared, and the substitution loop
ran over `baseUrl + path` so a value could reach the host.

Values are now percent-encoded at capture time, `.` and `..` are
rejected (URL normalization resolves `%2E%2E` like a literal `..`), and
placeholders are resolved against `endpoint.path` only. A single regex
pass with a function replacement also fixes the first-occurrence-only
and `$&`-expansion defects of `String.replace` with a string pattern.
`servers[0].url` was taken verbatim, so a spec declaring
`https://{region}.api.example.com` kept a literal placeholder in
`baseUrl`. Variables are now substituted from their declared `default`,
which the Server Object requires. An undeclared placeholder is left
literal rather than throwing, so specs that parse today keep parsing.
…oint

Covers spec -> OpenAPIToolset -> RestApiTool.runAsync -> fetch, the only
place the encoding, the credential attachment and the final request URL
are observed together.
An empty variable map already leaves every placeholder literal via the
`?? placeholder` fallback, so the early return bought nothing.
Resolve a Server Object variable from its declared default, falling back
to the first enum entry when the default is empty. A placeholder with no
value left to resolve it would otherwise be carried into the request as a
literal {name} host, so report it naming the offending variable instead.
…path parameters

Cover the remaining cases from google#597: the API key lands on a
contained path, declared query parameters still merge alongside an encoded
path value, and spaces, non-ASCII text, reserved characters and non-string
values all survive the encoder unchanged.
…server variables

Collecting every unresolved variable to join into one message needed an
accumulator, a pass-through branch and a trailing check. Reporting the first
one throws where it is found and drops 11 lines.

@ScottMansfield ScottMansfield left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just one thing, changing Map to Record, otherwise LGTM.

// A Map, not a plain object: placeholder names come from the spec's path
// template, and an object lookup would resolve `{constructor}` against
// Object.prototype.
const pathParams = new Map<string, string>();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This can be Record<string, string> instead of a Map

Amaad Martin added 2 commits August 10, 2026 13:01
The Map bought nothing over the object literal its neighbours already use;
guarding the placeholder lookup with Object.hasOwn keeps a spec that names a
path parameter 'constructor' from resolving it off Object.prototype.
…rsed-spec containment test

The pattern constant had one use eighteen lines below it and did not centralize
anything, since rest_api_tool.ts inlines the same literal. The containment case
asserts on prepareRequestParams, so it belongs with the other prepareRequestParams
cases rather than reaching across layers from the parser suite.
@ScottMansfield
ScottMansfield merged commit cedd2a5 into google:main Aug 10, 2026
12 checks passed
@kalenkevich kalenkevich mentioned this pull request Aug 7, 2026
prasanna8585 pushed a commit to prasanna8585/adk-js that referenced this pull request Aug 21, 2026
…le#638)

* Fix: percent-encode and validate OpenAPI path parameter values in RestApiTool

Path parameter values come from the model and were substituted into the
request URL verbatim, so a `/`, `?` or `#` let a value escape the path
segment (and the endpoint) the spec declared, and the substitution loop
ran over `baseUrl + path` so a value could reach the host.

Values are now percent-encoded at capture time, `.` and `..` are
rejected (URL normalization resolves `%2E%2E` like a literal `..`), and
placeholders are resolved against `endpoint.path` only. A single regex
pass with a function replacement also fixes the first-occurrence-only
and `$&`-expansion defects of `String.replace` with a string pattern.

* Fix: resolve OpenAPI Server Object variables when collecting operations

`servers[0].url` was taken verbatim, so a spec declaring
`https://{region}.api.example.com` kept a literal placeholder in
`baseUrl`. Variables are now substituted from their declared `default`,
which the Server Object requires. An undeclared placeholder is left
literal rather than throwing, so specs that parse today keep parsing.

* Test: assert a malicious path argument stays inside the declared endpoint

Covers spec -> OpenAPIToolset -> RestApiTool.runAsync -> fetch, the only
place the encoding, the credential attachment and the final request URL
are observed together.

* Fix: collapse the redundant variables guard in resolveServerUrl

An empty variable map already leaves every placeholder literal via the
`?? placeholder` fallback, so the early return bought nothing.

* Fix: fail loudly on an unresolvable OpenAPI server URL variable

Resolve a Server Object variable from its declared default, falling back
to the first enum entry when the default is empty. A placeholder with no
value left to resolve it would otherwise be carried into the request as a
literal {name} host, so report it naming the offending variable instead.

* Test: pin credential attachment and value round-tripping for encoded path parameters

Cover the remaining cases from google#597: the API key lands on a
contained path, declared query parameters still merge alongside an encoded
path value, and spaces, non-ASCII text, reserved characters and non-string
values all survive the encoder unchanged.

* Refactor: throw from the replacer instead of accumulating unresolved server variables

Collecting every unresolved variable to join into one message needed an
accumulator, a pass-through branch and a trailing check. Reporting the first
one throws where it is found and drops 11 lines.

* Refactor: hold path parameters in a Record instead of a Map

The Map bought nothing over the object literal its neighbours already use;
guarding the placeholder lookup with Object.hasOwn keeps a spec that names a
path parameter 'constructor' from resolving it off Object.prototype.

* Refactor: inline the single-use server-variable regex and move the parsed-spec containment test

The pattern constant had one use eighteen lines below it and did not centralize
anything, since rest_api_tool.ts inlines the same literal. The containment case
asserts on prepareRequestParams, so it belongs with the other prepareRequestParams
cases rather than reaching across layers from the parser suite.

---------

Co-authored-by: Amaad Martin <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants