Repository navigation
feat(dev): add Origin validation to the dev server (DNS-rebinding defense in depth) - #557
Conversation
|
Hi @kalenkevich, I have tested and validated the proposed changes in this PR. Could you please review this PR? |
07bf654 to
0ea34eb
Compare
kalenkevich
left a comment
There was a problem hiding this comment.
Nice work — the design is right, the module is small and well tested, and I confirmed the gate really does cover the A2A routes mounted later by initA2A() (403 for both a forged Host and a foreign Origin).
I merged the branch onto current main and ran it: 171 dev tests pass, tsc -p dev clean, eslint/prettier clean, and origin_check.ts is at 100% line and branch coverage.
One blocking bug: this 403s adk deploy cloud_run --with_ui. Details inline, plus two smaller things.
Also: the branch is 33 commits behind main (merges cleanly), and since AdkApiServer is exported from dev/src/index.ts, the new 403s deserve a release note.
| // Forwarding headers are deliberately ignored -- an untrusted | ||
| // `X-Forwarded-Host` would let a caller forge this side of the comparison -- | ||
| // and the dev server never terminates TLS, so the scheme is always http. | ||
| return headers.host !== undefined && origin === `http://${headers.host}`; |
There was a problem hiding this comment.
Blocking. Hardcoding http:// breaks any TLS-terminated deploy.
deploy_utils.ts:111 runs adk web --host=0.0.0.0 and Cloud Run terminates TLS, so the browser sends Origin: https://svc.a.run.app while the container sees Host: svc.a.run.app — every POST from the deployed dev UI is 403. Verified locally. Same for ngrok/Codespaces.
Compare authorities instead, no forwarding header needed:
if (headers.host === undefined) return false;
try {
return new URL(origin).host === headers.host.toLowerCase();
} catch {
return false;
}A browser can't forge Host, so this opens no cross-origin hole.
There was a problem hiding this comment.
Fixed in 5105d74: the same-origin check now compares new URL(origin).host to Host instead of prefixing http://, so an https Origin behind a TLS terminator matches its http Host. Added a test for the Cloud Run authority case.
| const allowedHosts = new Set<string>(); | ||
| for (const hostname of [serverHost, configuredHost, ...LOOPBACK_HOSTS]) { | ||
| const authority = net.isIPv6(hostname) ? `[${hostname}]` : hostname; | ||
| allowedHosts.add(`${authority}:${port}`.toLowerCase()); |
There was a problem hiding this comment.
--port 80 403s everything: the set gets localhost:80, but browsers omit the default port and send Host: localhost. Add the port-less spelling when port === 80.
There was a problem hiding this comment.
Fixed in 5105d74: buildOriginPolicy now also adds the port-less host when port === 80. Test added.
| // Keep tunnelled or proxied setups declared via --allow_origins working. | ||
| for (const origin of allowedOrigins) { | ||
| try { | ||
| allowedHosts.add(new URL(origin).host); |
There was a problem hiding this comment.
Nit: --allow_origins http://localhost:4200/ allowlists the host here, but the origin check is an exact includes and never matches — the escape hatch half-works. new URL(o).origin at parse time would make both sides agree.
There was a problem hiding this comment.
Fixed in 5105d74: --allow_origins entries are normalized with new URL(o).origin at parse time, so both the gate and cors() match the browser Origin. Test added.
| }); | ||
|
|
||
| if (this.allowOrigins) { | ||
| if (this.allowedOrigins.length > 0) { |
There was a problem hiding this comment.
The description lists /, /health and /dev-ui bypassing cors() as a bug this fixes, but cors() is still registered after those routes. Confirmed at runtime: with --allow_origins http://localhost:4200, /list-apps gets Access-Control-Allow-Origin and /version gets none. Move the block above the routes, or drop the claim.
There was a problem hiding this comment.
Fixed in 5105d74: cors() is now registered before the routes, so /, /health, /dev-ui and /version also carry the header. The description now holds.
| * to: `port: 0` picks a free port, so it is only known once it is listening -- | ||
| * which it always is by the time a request reaches the middleware. | ||
| */ | ||
| private policy(): OriginPolicy { |
There was a problem hiding this comment.
Nit: this rebuilds the Set and re-parses every allowed origin on each request, including every dev-UI static asset. The bound address can't change after listen, so it could be memoized on first use.
There was a problem hiding this comment.
Fixed in 5105d74: the policy is memoized on first use once the server is listening, so it is built once, not per request.
|
On the release note: the |
|
Heads up: the ground under this PR moved today. #744 — "fix: guard reads in the dev server against DNS rebinding" — merged as What merged, and where it collides
That is why GitHub now reports The overlap is not incidental — it is function-for-function on the Host side:
#744 also went through three rounds of hardening the Host path specifically — a port-validation bug where What still stands, and is worth keepingThe Origin half is not on It also has upstream precedent — adk-python carries both halves: Being straight about how much it matters, because it affects how you scope the rebase: In the first two rows the server executes the cross-origin request but the browser refuses the response, and a JSON POST still needs a preflight that fails — so this is defence in depth rather than an open door. The third row is the real one: The askRebase onto current
That should be a much smaller change than the current +674/−11, and it stops this duplicating code that already shipped. kalenkevich's |
…ng guard Rebased onto main. PR #744 shipped the Host-based DNS-rebinding guard, so this drops the duplicate Host allowlist and keeps only the Origin gate, which has no equivalent on main. The gate rejects cross-origin state-changing requests and compares authorities, so a TLS-terminating proxy (Cloud Run, ngrok) still passes as same-origin. Also fixes multi-origin --allow_origins parsing: comma-separated origins now reach cors as a list, and each origin host is vouched for by the guard. The CORS block is registered before the routes so /, /health and /version carry CORS headers too.
5105d74 to
70e3d60
Compare
|
Rebased onto
Host coverage lives in #744's tests, so I dropped the duplicate Host test and kept the Origin and CORS tests. |
kalenkevich
left a comment
There was a problem hiding this comment.
Re-reviewed the rebased head. All five earlier comments are fixed and the scope cut after #744 is right — 152 dev/server tests, tsc, eslint and prettier are clean here, and the gate does cover the A2A routes mounted later by initA2A().
One blocking bug found by probing config edge cases, plus small things inline. Two with no diff line to hang off:
ServerOptions.allowOrigins(adk_api_server.ts:77) still has no doc comment, though it is now a comma-separated list and a request gate, not just a CORS header. It is exported public API.- The description is stale post-rebase — host allowlist,
buildOriginPolicy,--trust_proxy_headers,Forbidden: host not allowed, 100% coverage. It becomes the squash commit message.
| return origin; | ||
| } | ||
| try { | ||
| return new URL(origin).origin; |
There was a problem hiding this comment.
Blocking. new URL(x).origin is the string "null" for a scheme-less entry, so --allow_origins localhost:4200 puts 'null' on the allowlist. Verified against a running server:
- POST
Origin: http://localhost:4200→ 403 (the origin the user meant to allow) - POST
Origin: null→ 200,Access-Control-Allow-Origin: null
So a forgotten scheme inverts the escape hatch and grants every opaque origin: sandboxed iframes, data:/file:// documents, cross-origin-redirected POSTs. Same for --allow_origins file://.
Accept only entries parsing to an http:/https: URL, drop anything whose .origin is 'null', and warn on the dropped entry so the typo surfaces at startup.
There was a problem hiding this comment.
Fixed in ac31e8b. normalizeOrigin now returns null for any entry that is not an http:/https: URL, and parseAllowedOrigins drops it and logs a warning at startup, so localhost:4200 and file:// no longer put null on the allowlist. An end-to-end test asserts that Origin: null gets a 403 under --allow_origins localhost:4200.
| } | ||
| const reason = 'Forbidden: origin not allowed'; | ||
| logger.warn( | ||
| `${reason}: ${req.method} ${req.originalUrl} (host: ${req.headers.host}, origin: ${req.headers.origin})`, |
There was a problem hiding this comment.
The Host guard logs JSON.stringify(String(req.headers.host).slice(0, 128)) after #744's review rounds; this interpolates host, origin and URL raw and unbounded. Worth one shared helper rather than two conventions.
There was a problem hiding this comment.
Fixed in ac31e8b. Both the Host guard and the Origin gate now log through one helper, formatHeaderForLog in dev/src/utils/log_utils.ts, which quotes the value and caps it at 128 characters.
| [], | ||
| ), | ||
| ).toBe(false); | ||
| }); |
There was a problem hiding this comment.
Coverage here is 95.9% stmts / 94.1% branches, not the 100% the description claims. The gap is the malformed-Origin catch (origin_check.ts:57-58) — which is exactly the path Origin: null takes, so it is worth a case.
Also missing: a POST with no Origin passing. That is the compat contract for AdkApiClient and curl; I confirmed it returns 200, it is just not pinned.
There was a problem hiding this comment.
Fixed in ac31e8b. Added a unit case for the malformed-Origin catch (Origin: null -> false) and an end-to-end case for a no-Origin POST returning 200, plus parseAllowedOrigins cases.
| * The hosts of every configured origin, so the DNS-rebinding guard vouches | ||
| * for each one. Naming an origin in `--allow_origins` vouches for its host. | ||
| */ | ||
| private allowOriginHosts(): string[] { |
There was a problem hiding this comment.
This re-derives what getAllowedRequestHosts already does internally, and since only '*' | undefined now reaches its first parameter, that branch is dead outside its own tests (and its doc comment describes work the caller does). Consider getAllowedRequestHosts(allowedOrigins: string[], extraAllowedHosts?) and dropping this helper.
There was a problem hiding this comment.
Fixed in ac31e8b. getAllowedRequestHosts now takes the parsed string[] and derives every origin's host itself; allowOriginHosts is gone and the caller passes this.allowedOrigins directly.
| const allowedRequestHosts = getAllowedRequestHosts( | ||
| this.allowOrigins, | ||
| this.allowedHosts, | ||
| this.allowedOrigins.includes('*') ? '*' : undefined, |
There was a problem hiding this comment.
--allow_origins 'http://localhost:4200,*' now returns null here and switches the DNS-rebinding guard off entirely; on main that string never equalled '*', so the guard stayed on. Defensible, but make it deliberate with a test.
There was a problem hiding this comment.
Fixed in ac31e8b. Added a test pinning that getAllowedRequestHosts(['http://localhost:4200', '*']) returns null, so a wildcard anywhere in the list disables the guard deliberately.
- Reject scheme-less/opaque `--allow_origins` entries so a typo like `localhost:4200` (whose opaque origin is the string "null") can no longer allowlist every `Origin: null` request; warn on each dropped entry. - Share one bounded, quoted header-logging helper (`formatHeaderForLog`) across the Host guard and the Origin gate instead of two conventions. - Derive the DNS-rebinding host allowlist from the parsed origins list (`getAllowedRequestHosts(string[])`) and drop the redundant `allowOriginHosts` helper in the server. - Document `ServerOptions.allowOrigins` (now a request gate, not just CORS). - Tests: opaque-origin drop and parse behaviour, the malformed-Origin path, a no-Origin POST passing, and the wildcard-in-list guard opt-out.
|
Both items in the re-review with no diff line are addressed in ac31e8b: |
…ense in depth) (google#557) * feat(dev): add dev-server Origin validation on top of the DNS-rebinding guard Rebased onto main. PR google#744 shipped the Host-based DNS-rebinding guard, so this drops the duplicate Host allowlist and keeps only the Origin gate, which has no equivalent on main. The gate rejects cross-origin state-changing requests and compares authorities, so a TLS-terminating proxy (Cloud Run, ngrok) still passes as same-origin. Also fixes multi-origin --allow_origins parsing: comma-separated origins now reach cors as a list, and each origin host is vouched for by the guard. The CORS block is registered before the routes so /, /health and /version carry CORS headers too. * fix(dev): address origin-gate review feedback - Reject scheme-less/opaque `--allow_origins` entries so a typo like `localhost:4200` (whose opaque origin is the string "null") can no longer allowlist every `Origin: null` request; warn on each dropped entry. - Share one bounded, quoted header-logging helper (`formatHeaderForLog`) across the Host guard and the Origin gate instead of two conventions. - Derive the DNS-rebinding host allowlist from the parsed origins list (`getAllowedRequestHosts(string[])`) and drop the redundant `allowOriginHosts` helper in the server. - Document `ServerOptions.allowOrigins` (now a request gate, not just CORS). - Tests: opaque-origin drop and parse behaviour, the malformed-Origin path, a no-Origin POST passing, and the wildcard-in-list guard opt-out. --------- Co-authored-by: Amaad Martin <[email protected]>
Link to Issue or Description of Change
Describe the change:
Problem
The dev server's DNS-rebinding guard (from #744) inspects the
Hostheader but notOrigin, so a page on another origin can still drive state-changing requests (create a session, run an agent) that the browser sends with anOrigin.--allow_originswas wired only tocors(), which sets response headers and never rejects a request. A comma-separated value also reachedcors()as one string that no browserOrigincan equal.Solution
Add an Origin gate (
dev/src/server/origin_check.ts) registered before every route, alongside the existing Host guard. A state-changing request (any method outsideGET/HEAD/OPTIONS) that carries anOriginmust be same-origin or on the allowlist; a request with noOriginpasses, so curl, the ADK CLI andAdkApiClientare unaffected.--allow_originsis parsed as a comma-separated list ofhttp:/https:origins, each origin's host is also added to the DNS-rebinding allowlist, and'*'allows every origin and turns that guard off. A rejected request returns403 Forbidden: origin not allowed.Behavioural change, intentional. A cross-origin state-changing browser request that used to succeed now returns
403. The escape hatch is--allow_origins <origin>.This mirrors the request gate in the adk-python dev server (
_OriginCheckMiddleware).Testing Plan
dev/test/server/origin_check_test.ts—normalizeOrigin,parseAllowedOriginsandisRequestOriginAllowed, including the opaqueOrigin: nullpath.dev/test/server/adk_api_server_origin_check_test.ts— the gate end to end overnode:http, including a no-OriginPOST (200) and a scheme-less--allow_originsentry that must not allowlistOrigin: null.dev/test/server/dns_rebinding_guard_test.ts— updated for thestring[]signature, plus the wildcard-in-list opt-out.dev/test/utils/log_utils_test.ts— the shared header-logging helper.Checklist