Repository navigation
fix(runtime): server-configured agent headers take precedence over forwarded inbound headers - #5782
Merged
Merged
Conversation
Contributor
📣 Social Copy GeneratorGenerate social media copies (Twitter/X, LinkedIn, Blog Post) for this PR using Claude.
|
@copilotkit/a2ui-renderer
@copilotkit/agentcore-runner
@copilotkit/angular
@copilotkit/bot
@copilotkit/bot-discord
@copilotkit/bot-slack
@copilotkit/bot-teams
@copilotkit/bot-telegram
@copilotkit/bot-ui
@copilotkit/bot-whatsapp
@copilotkit/core
@copilotkit/react-core
@copilotkit/react-native
@copilotkit/react-textarea
@copilotkit/react-ui
@copilotkit/runtime
@copilotkit/runtime-client-gql
@copilotkit/sdk-js
@copilotkit/shared
@copilotkit/sqlite-runner
@copilotkit/voice
@copilotkit/vue
@copilotkit/web-components
@copilotkit/web-inspector
commit: |
Contributor
|
Size Change: 0 B Total Size: 1.1 MB ℹ️ View Unchanged
|
…rwarded inbound headers When a request hits the /run path, inbound headers are forwarded to the agent. Previously, forwarded inbound headers could clobber the server-configured agent.headers on a key collision, letting a client override server-set values (e.g. authorization). This is the #5712 bug. Introduce mergeForwardableHeaders (header-utils.ts): a case-insensitive merge where server-configured agent.headers always win on collision, regardless of header-name casing. agent-utils.ts now uses this helper on the /run path so server-configured values are authoritative and inbound headers only fill keys the server did not set. Fixes #5712
…ward-looking plumbing The /connect path now builds the same server-wins merged headers as the /run path and passes them into runner.connect(). This does NOT fix connect-path auth: no shipped runner consumes the headers field of AgentRunnerConnectRequest today. The in-memory, intelligence, telemetry, and sqlite runners all read only threadId from the connect request and ignore headers entirely. The real outbound header forwarding lives on the /run path, where agent.headers is mutated before the agent runs. Passing merged headers here is the correct argument shape for a future outbound-connecting runner, and keeps the connect path's merge semantics consistent with /run. The comments and JSDoc are rewritten to state this plainly rather than implying an active auth fix: the connect-site cloneAgentForRequest call is documented as the sole agentId-existence guard (the intelligence branch never re-validates the id), and cloneAgentForRequest's AbstractAgent | Response (404) dual-return contract that both callers depend on is now documented.
…-* uniqueness, agent-undefined forwarding Cover the #5712 header-precedence behavior across both paths: - agent-header-precedence.test.ts: server-configured agent.headers win over forwarded inbound headers on collision (case-insensitive), with single-key uniqueness assertions for both authorization and the x-* family (exactly one surviving key carrying the SERVER value). - agent-utils-header-forwarding.test.ts: the /run path merges via mergeForwardableHeaders so server values are authoritative and inbound headers fill only unset keys. - sse/__tests__/sse-connect-agent-id.test.ts: the /connect path applies the same merge, plus the agent-undefined case (no server agent.headers) degrades to forwarding allowlisted inbound headers only and does not crash.
jpr5
force-pushed
the
fix/runtime-inbound-header-precedence
branch
from
June 30, 2026 21:40
33828d9 to
8bdb3a1
Compare
… mergeForwardableHeaders
When an agent is configured with both case-variants of the same header
in agent.headers (e.g. Authorization and authorization), the prior
{ ...base } spread kept both keys — the exact undici comma-join hazard
the function guards against for inbound collisions. Collapse server-self
case-collisions to a single first-occurrence-wins entry; server-wins-over
-inbound and case-insensitive inbound suppression are unchanged.
jpr5
marked this pull request as ready for review
June 30, 2026 22:08
jpr5
requested review from
marthakelly,
mme,
ranst91 and
tylerslaton
as code owners
June 30, 2026 22:08
AlemTuzlak
approved these changes
Jul 2, 2026
jpr5
added a commit
that referenced
this pull request
Jul 6, 2026
Document the v2 runtime's inbound-header forwarding behavior on the Copilot Runtime page: the default denylist (authorization + x-* minus known infra/proxy/platform headers), the x-request-id upgrade note, server-configured header precedence (#5782), and the forwardHeaders config option (deny/denyPrefixes/allow/useDefaultDenylist) with the allowlist-mode denylist-bypass footgun. Refs #5712, #5783
jpr5
added a commit
that referenced
this pull request
Jul 6, 2026
…ault infra/platform denylist (#5783) ## Problem — the leak The v2 runtime's `shouldForwardHeader` forwarded `authorization` **and any header whose name starts with `x-`** onto the outgoing agent call. In a real deployment the inbound request has already traversed a browser, CDN/edge, load balancer, and hosting platform — each stamping its own `x-*` headers — so the wide `x-*` wildcard silently forwarded: - **Hop-by-hop / topology:** `x-forwarded-for`, `x-real-ip`, `x-forwarded-proto/host/port` - **Cloud / CDN tracing:** `x-amzn-trace-id`, `x-amz-cf-id`, `x-cloud-trace-context`, `x-azure-*`, `x-fastly-*`, `x-request-id` - **Platform-injected:** `x-vercel-*`, `x-middleware-*` - **CopilotKit Cloud platform credential:** `x-copilotcloud-public-api-key` The last item is a real credential-exfiltration concern: a platform key scoped to Copilot Cloud reaching a third-party agent URL. This is the **breadth** half of #5712 (option 3); the **precedence** half was fixed in #5782. ## Design — denylist default + config knob, both paths - **Default denylist (safe default).** Keep the `authorization` + `x-*` base eligibility, but strip a curated, greppable set of known infra/proxy/platform headers (exact names + prefix families) before forwarding. Legitimate custom `x-*` application headers (`x-tenant-id`, `x-api-key`, …) keep flowing untouched. The authoritative list is a single exported constant in `header-utils.ts`. - **Configurable policy (`forwardHeaders` runtime option).** - `useDefaultDenylist?: boolean` (default **true**) — `false` restores the previous wide-open behavior. - `deny?` / `denyPrefixes?` — extend the default denylist. - `allow?` — opt into strict allowlist mode (only listed headers forward). - **Resolve once.** The constructor resolves `forwardHeaders` into a `forwardHeadersPolicy: ResolvedForwardHeadersPolicy` field (mirroring the existing `debug` → `ResolvedDebugConfig` resolve-once), exposed on `CopilotRuntimeLike` / `BaseCopilotRuntime` with a passthrough getter on the `CopilotRuntime` shim. - **Both paths.** The resolved policy is read at **/run** (`configureAgentForRequest`) and **/connect** (`handleSseConnect`) via `mergeForwardableHeaders`, so the two can never diverge. Server-wins precedence and server-self case-dedup from #5782 are untouched. ## Semver **Minor with an opt-out.** Removing a leak is a fix, not a contract change, and we ship a documented escape hatch: `new CopilotRuntime({ agents, forwardHeaders: { useDefaultDenylist: false } })` restores the prior behavior. Custom-header forwarders (the common case) are unaffected. ## Red-green proof (real surface, both paths) RED — with the predicate reverted to the old wide-open `authorization || x-*` (policy ignored), the new behavior assertions fail; the leak reproduces (`x-forwarded-for: 203.0.113.7` forwards on both /run and /connect): ``` ❯ header-utils.test.ts (19 tests | 8 failed) × strips known infra/proxy/platform headers by exact name → expected true to be false × strips known infra/platform header families by prefix → expected true to be false × strips denylisted headers case-insensitively → expected true to be false × deny extends the default set → expected true to be false × denyPrefixes extends the default set → expected true to be false × allow switches to allowlist mode → expected true to be false × extractForwardableHeaders drops denylisted x-* infra → expected {…4} to deeply equal {…1} ❯ agent-utils-header-forwarding.test.ts (/run) (10 tests | 1 failed) × strips denylisted infra/platform headers (#5712 breadth) → expected '203.0.113.7' to be undefined ❯ sse-connect-agent-id.test.ts (/connect) (5 tests | 1 failed) × strips denylisted infra/platform headers → expected '203.0.113.7' to be undefined ``` GREEN — with the real policy in place: ``` ✓ header-utils.test.ts (19 tests) ✓ agent-utils-header-forwarding.test.ts (10 tests) # /run path ✓ sse-connect-agent-id.test.ts (5 tests) # /connect path ✓ agent-header-precedence.test.ts (2 tests) Test Files 4 passed (4) Tests 36 passed (36) ``` Full `@copilotkit/runtime` suite: **113 files / 1593 tests passed.** Typecheck, oxlint (0 errors), oxfmt, and build all green. ## Builds on #5782 This branches off #5782's head (`636bcad05`) and reuses that PR's `mergeForwardableHeaders` (server-wins precedence + server-self case-dedup). It should land **after #5782**. It addresses the **forwarding-breadth half of #5712** — #5712's precedence core is fixed by #5782; this is the breadth follow-up (not `Fixes #5712`).
4 of 5 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.
Problem
When a self-hosted v2
CopilotRuntimeis configured with a server-side agent (an@ag-ui/clientHttpAgentwith staticheadersfor service-to-service auth), the runtime forwards inboundauthorization/x-*request headers onto the agent's outgoing call and lets them override the headers the server configured — silently breaking service-to-service auth to a secured backend (e.g. a private Cloud Run agent behind IAM).Fixes #5712Root cause
packages/runtime/src/v2/runtime/handlers/shared/agent-utils.ts:125-128merged forwarded inbound headers last, so they won on collision:There are actually two failure modes:
authorizationoverwrites a serverauthorization(last-write-wins).extractForwardableHeaderslowercases inbound keys (authorization), while the server typically configures canonical casing (Authorization). A plain spread treats those as distinct keys and emits both — which undici downstream comma-joins into a single invalid"Bearer A, Bearer B"("multiple JWTs") value. Flipping the spread order alone does not fix this case.Fix
In
agent-utils.ts, make server-configuredagent.headersauthoritative on collision, matched case-insensitively: drop any forwarded inbound header whose name (case-insensitively) is already set on the agent, and let non-colliding inbound headers pass through unchanged. This preserves the existing forward-for-auth behavior for headers the server does not set, while guaranteeing a server-set token is never overridden or duplicated.The merge logic lives in a shared
mergeForwardableHeaders(serverHeaders, request)helper inpackages/runtime/src/v2/runtime/handlers/header-utils.tsso the precedence semantics are defined in exactly one place.Scope note
This is the conservative precedence + case-insensitive-dedup fix (the issue's suggested fix #1). I did not tighten the default allowlist to drop hop-by-hop/platform
x-*headers (x-serverless-*,x-forwarded-*, …) or add an opt-out — those alter existing forwarding behavior and are worth a separate, deliberate change. The precedence fix alone resolves the reported breakage (the server-set token now wins regardless of what the platform injects on a colliding header name).A documented workaround already exists for users on released versions: pass a custom
fetchto theHttpAgentthat builds outgoing headers from scratch (it runs afterconfigureAgentForRequestand survives the per-requestagent.clone()).Red-green proof (the real fix —
/runpath)The load-bearing assertion: there must be exactly one authorization header carrying the server value.
RED (fix stashed, against unmodified
agent-utils.ts)The pre-existing
agent-utils-header-forwarding.test.tsalso failed, because it explicitly encoded the buggy behavior (expect(...["x-aimock-context"]).toBe("new-context")— inbound winning):GREEN (fix applied)
The colliding test (
agent-utils-header-forwarding.test.ts) was updated from asserting the old bug to asserting corrected precedence + a new case-insensitive-dedup guard. The non-colliding-forward test is retained unchanged as a regression guard.Quality gates
/connect-path change — forward-looking plumbing, inert todayThe original issue and a prior eval flagged the same forwarding pattern at
handlers/sse/connect.ts. To keep the two paths' merge semantics consistent, the/connectpath now builds the same server-wins merged headers (via the sharedmergeForwardableHeadershelper) and passes them intorunner.connect().This is not an active auth fix, and it is not red-green-proven as one — because there is no live bug to fix on the connect path today. No shipped runner consumes the
headersfield ofAgentRunnerConnectRequest: the in-memory, intelligence, telemetry, and sqlite runners all destructure onlythreadIdfrom the connect request and ignoreheadersentirely. Connect is a thread replay/reconnect, not a fresh outgoing agent call. So whatever headers we pass intorunner.connect()are dropped on the floor by every runner that ships.What this change actually does:
handle-connect.ts → handleSseConnectso the connect path has access to the server-configuredagent.headers(it previously did not).mergeForwardableHeaders(agent?.headers, request)intorunner.connect()— the correct, server-wins argument shape for a future outbound-connecting runner that would consume connect-path headers.cloneAgentForRequestcall is the soleagentId-existence guard (the intelligence branch never re-validates the id), and documentscloneAgentForRequest'sAbstractAgent | Response(404) dual-return contract that both callers depend on.The real outbound header forwarding — the thing that fixes #5712 — is the
/runpath'sagent.headersmutation described above. The connect change is staged plumbing so that if/when a runner starts honoring connect-path headers, it inherits the same server-wins precedence without a second fix.Tests on the
/connectpathThe connect tests assert the merge shape that reaches
runner.connect()(server value wins on collision, exactly oneauthorizationkey, non-collidingx-*still forwards) and that the agent-undefined case (no serveragent.headers) degrades to forwarding allowlisted inbound headers only and does not crash. These verify the argument we construct is correctly shaped — not that any shipped runner consumes it.Files
packages/runtime/src/v2/runtime/handlers/header-utils.ts— sharedmergeForwardableHeadershelper (case-insensitive, server-wins).packages/runtime/src/v2/runtime/handlers/shared/agent-utils.ts—/runpath uses the helper so server headers win on collision (the real fix).packages/runtime/src/v2/runtime/handlers/sse/connect.ts—/connectpath uses the helper; forward-looking plumbing, inert until a runner consumes connect-path headers.packages/runtime/src/v2/runtime/handlers/handle-connect.ts— threads the per-request agent clone intohandleSseConnect.packages/runtime/src/v2/runtime/__tests__/agent-header-precedence.test.ts—/runregression test exercising the realconfigureAgentForRequestsurface with a realHttpAgent.packages/runtime/src/v2/runtime/__tests__/agent-utils-header-forwarding.test.ts— updated the test that encoded the old (buggy) precedence; added a case-mismatch dedup guard.packages/runtime/src/v2/runtime/handlers/sse/__tests__/sse-connect-agent-id.test.ts— connect-path merge-shape + agent-undefined coverage.Notes
@ag-ui/clientHttpAgentfetchworkaround already exists for attaching service-to-service auth the runtime can't override (see the issue). This change makes the workaround unnecessary for the/runprecedence case./runplus forward-looking connect plumbing. Tightening the default allowlist (dropping hop-by-hop / platformx-serverless-*,x-forwarded-*,x-cloud-trace-context, …) and an opt-out switch — issue suggestions turbo refactor #2/readme #3 — are intentionally left as a follow-up to keep the security-policy change minimal.