Skip to content

fix(adapter-utils): accept the bridge token in X-API-Key - #12785

Merged
devinfoley merged 4 commits into
paperclipai:masterfrom
superbiche:fix/sandbox-bridge-accept-x-api-key
Oct 15, 2026
Merged

devinfoley merged 4 commits into
paperclipai:masterfrom
superbiche:fix/sandbox-bridge-accept-x-api-key

Conversation

@superbiche

@superbiche superbiche commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Thinking Path

  • Paperclip is the open source app people use to manage AI agents for work
  • An agent can run inside a sandbox. The sandbox callback bridge is the loopback gateway that lets the agent call the Paperclip API from inside that sandbox
  • The gateway authenticates each local call with a per-run bridge token. It read that token from the Authorization: Bearer <token> header only
  • The run hands the agent that token in PAPERCLIP_API_KEY, next to PAPERCLIP_API_URL (execution-target.ts). The token is named an API key, and the public Paperclip API documents that an API key goes in the X-API-Key header
  • An agent that follows the documentation therefore sends X-API-Key first, and its first call fails with 401 Invalid bridge token.
  • The agent then retries with a bearer header and the same token. The run still succeeds, but it wastes a turn and it can leave a confused agent trying unrelated repairs
  • This pull request makes both generated gateways read the bridge token from X-API-Key when the request carries no bearer token
  • The benefit is that a documented header convention stops producing a needless failure, at no cost to the token check

Linked Issues or Issue Description

No existing issue found. I searched the repository for open pull requests matching x-api-key and bridge token. Nothing addresses the in-sandbox gateway header convention. The closest neighbours are unrelated: #12632 (Composio mcp.headers.x-api-key) and #12120 (the HTTP/2 transport for this bridge, already merged). The problem follows bug_report.yml:

What happened?

An agent running in a sandbox calls the Paperclip API through the loopback callback bridge. When it sends the credential as X-API-Key: <bridge token>, the gateway answers 401 with {"error":"Invalid bridge token."}. The token in that header is the correct per-run bridge token.

Expected behavior

The gateway accepts the correct per-run bridge token in either header convention. The public API documents X-API-Key, so an agent that follows the documentation succeeds on its first call.

Steps to reproduce

  1. Start a run whose agent executes in a sandbox execution target, so the callback bridge is active.
  2. The run exports PAPERCLIP_API_URL (the loopback bridge origin) and PAPERCLIP_API_KEY (the bridge token) into the sandbox environment.
  3. From inside the sandbox, call the bridge with that key in the documented header:
    curl -i -H "X-API-Key: $PAPERCLIP_API_KEY" "$PAPERCLIP_API_URL/api/agents/me"
  4. The response is 401 {"error":"Invalid bridge token."}.
  5. Repeat the same call with -H "Authorization: Bearer $PAPERCLIP_API_KEY". The response is 200.

Paperclip version or commit

Branched from master at 06c0e883f.

Deployment mode

Self-hosted Kubernetes, with the agent in a sandbox execution target and a local model behind an OpenAI-compatible endpoint.

Agent adapter(s) involved

Not adapter-specific (core bug). Observed with a local-model adapter on a sandboxed lane. Any agent that follows the public API documentation sends this header.

Additional context

The variable name is the trigger. The run calls the credential PAPERCLIP_API_KEY, and an agent that has read the public API documentation knows an API key goes in X-API-Key. Paperclip's own in-prompt guidance uses Authorization: Bearer $PAPERCLIP_API_KEY, so the two conventions sit side by side.

Across 12 observed runs on that lane, the agent's first bridge call used X-API-Key in 6 runs. Every one of those runs recovered by retrying with a bearer header and the same token. In some runs the agent first tried unrelated repairs, such as writing a test comment, before it changed the header.

What Changed

  • Add one readBridgeToken(req) helper to the generated in-sandbox gateway source. The helper returns the bearer token from Authorization when the header carries one. It otherwise returns the x-api-key header value, or an empty string.
  • Use that helper in both generated gateway request handlers: the file-mode queue gateway and the HTTP/2 gateway. Both previously repeated the same two lines of bearer parsing.
  • The token still goes to the same timingSafeEqual comparison. The change does not alter the comparison, the token, or its lifetime.
  • Extend the file-mode round-trip test to cover an X-API-Key request with the right token, an X-API-Key request with a wrong token, and the fact that the header never reaches the host.
  • Add one HTTP/2-path test that covers the same three cases, and that proves a bearer token still wins when a request carries both headers.

Verification

Commands run on this branch:

node_modules/.bin/vitest run packages/adapter-utils/src/sandbox-callback-bridge.test.ts
  Test Files  1 passed (1)
       Tests  52 passed (52)

cd packages/adapter-utils && ../../node_modules/.bin/tsc --noEmit
  0 errors in the two files this pull request touches

Both new tests are real regression guards. With the test file in place and the source change reverted, each one fails with expected 401 to be 200: the file-mode round-trip test and the HTTP/2 test. Both pass with the source change applied.

A reviewer can confirm the security properties by reading two things. First, tokensMatch in the generated source is unchanged, so the constant-time comparison against the same per-run token is unchanged. Second, allowedHeaders in the same source is a closed allowlist of accept, content-type, if-match, and if-none-match. normalizeHeaders drops every other header, so neither authorization nor x-api-key leaves the sandbox on either transport. The independent host-side check in http2-bridge-server.ts is untouched, because each gateway sets authorization: Bearer <token> on the request it forwards.

ROADMAP.md check: I grepped ROADMAP.md for bridge, x-api-key, redaction, and sandbox callback. There were no matches. This is a small bug fix in an existing subsystem, so it does not overlap planned core work.

Duplicate search: I searched pull requests in this repository for x-api-key and bridge token. No open or merged pull request changes how the in-sandbox gateway reads the token.

Risks

Low risk.

  • The change widens which header the gateway reads. It does not widen what the gateway accepts. A request still needs the exact per-run bridge token, and it still passes the same constant-time comparison.
  • A bearer token keeps priority. A request that carries both headers behaves exactly as it did before, which a test now pins.
  • A caller that presents a non-bearer Authorization header and a valid X-API-Key header now succeeds instead of failing. This is intentional: the bridge only ever issues bearer tokens, so no bridge caller relied on that failure.
  • The header allowlist already excluded x-api-key, so no forwarded request changes shape.
  • No migration, no configuration change, and no behavior change for a caller that already sends a bearer token.

Model Used

Claude Opus 5 (claude-opus-5), extended thinking at high effort — verify before merge.

Checklist

  • I have included a thinking path that traces from project context to this change
  • I have specified the model used (with version and capability details)
  • I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work
  • I have searched GitHub for duplicate or related PRs and linked them above
  • I have either (a) linked existing issues with Fixes: # / Closes # / Refs # OR (b) described the issue in-PR following the relevant issue template
  • I have not referenced internal/instance-local Paperclip issues or links (only public GitHub #NNN / github.com/paperclipai/paperclip URLs)
  • My branch name describes the change (e.g. docs/..., fix/...) and contains no internal Paperclip ticket id or instance-derived details
  • I have run tests locally and they pass
  • I have added or updated tests where applicable
  • I have updated relevant documentation to reflect my changes — no documentation describes the bridge's header convention, so there is nothing to update
  • I have considered and documented any risks above
  • All Paperclip CI gates are green
  • Greptile is 5/5 with no open P2s, recommendations, or follow-ups
  • I will address all Greptile and reviewer comments before requesting merge

@superbiche · contributor · drafted with Claude Opus 5, reviewed before posting; the voice and decisions are mine.

The in-sandbox callback gateway read the bridge token only from
"Authorization: Bearer <token>". The public Paperclip API documents the
"X-API-Key: <token>" header, so an agent that follows those docs sends
that header first and gets a 401 with "Invalid bridge token." The agent
then retries with a bearer header and the same token.

Both gateways now read the token through one helper. The helper prefers a
bearer token in the Authorization header. It falls back to the X-API-Key
header. The token still goes to the same constant-time comparison, and the
closed header allowlist still strips both headers before either gateway
forwards a request.

Claude-Session: https://claude.ai/code/session_01U9PF3d9SASC9tomDRjyeVt
@greptile-apps

greptile-apps Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5 Tier: apex

[Critical impact] The PR appears safe to merge; no actionable issues remain.

Summary

Both sandbox gateways now accept the per-run token in X-API-Key when Authorization has no bearer value.

  • Sandbox callers can use X-API-Key for the bridge token.

Reviews (6) · Last reviewed commit: "test(adapter-utils): keep queue response..." · Reviewed by Greptile

@commitperclip

commitperclip Bot commented Oct 1, 2026

Copy link
Copy Markdown
Contributor

@greptileai

@devinfoley

Copy link
Copy Markdown
Contributor

@greptileai apex

@devinfoley
devinfoley merged commit 5b15de9 into paperclipai:master Oct 15, 2026
34 checks passed
nickyleach added a commit that referenced this pull request Oct 15, 2026
…16507)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Sandbox agents use the callback bridge to call the Paperclip API.
> - The bridge round-trip test checks request delivery and credential
removal.
> - #12785 added an accepted API-key request before the feedback
request.
> - The feedback assertions still read request 2, which is now the
GitHub credentials request.
> - This PR checks request 3 and verifies that all four accepted
requests reached the host.
> - This restores the shared test gate while retaining the Unicode
payload and token checks.

## Linked Issues or Issue Description

Related PR: #12785 introduced the stale feedback index. The reported
failure appears on #16486 and master. Searches for `workspaces-b`,
`sandbox-callback-bridge`, `surrogate`, and `EncoderFallbackException`
found no duplicate fix.

**What happened?**

The `General tests (workspaces-b)` job fails on PRs and master. The
hosted PR job and AWS master job both report
`System.Text.EncoderFallbackException` for an unpaired `\uD83D`. The
runner exits during the test step and does not upload that step's log.

The unchanged master test reproduces a deterministic assertion failure
at the feedback request. It compares `/runtime-tools/github/credentials`
with `/api/companies/company-1/agent-commentary` and prints a diff
containing 5,000 crying emoji. The assertion output is the likely
trigger for the runner's Unicode logging crash.

- [Reported PR
job](https://github.com/paperclipai/paperclip/actions/runs/38818474563/job/116719880033)
- [Master job with the same runner
exception](https://github.com/paperclipai/paperclip/actions/runs/38821128038/job/116717690951)

**Expected behavior**

The test checks the actual feedback request, verifies its full payload,
and confirms that its authorization header is removed. Both shared CI
lanes complete normally.

**Steps to reproduce**

1. Check out master at `c4a16cbe981f96e2756c7014103c88da67e5514f`.
2. Install dependencies with pnpm 9.15.4.
3. Run `node_modules/.bin/vitest run
packages/adapter-utils/src/sandbox-callback-bridge.test.ts -t
'round-trips localhost bridge requests'`.
4. Observe the feedback assertion reading the preceding GitHub
credentials request.

**Paperclip version or commit**

Master at `c4a16cbe981f96e2756c7014103c88da67e5514f`.

**Deployment mode**

Built from source. GitHub-hosted PR CI and AWS post-merge CI.

## What Changed

- Assert that four accepted requests reached the host.
- Check feedback delivery and authorization stripping on request 3.
- Retain the large Unicode payload and all existing authentication
checks.

## Verification

- Unchanged master: the focused round-trip test fails at the stale
feedback index.
- Fixed branch: all 68 tests in `sandbox-callback-bridge.test.ts` pass
with real localhost gateways.
- `pnpm --filter @paperclipai/adapter-utils typecheck` passes.
- `git diff --check` passes.
- Exact CI group: `node scripts/run-vitest-stable.mjs --mode general
--group general-workspaces-b` passes (4,800 tests passed, 28 skipped
across 17 projects).
- `pnpm --filter @paperclipai/adapter-utils build` passes.
- Greptile reviewed current head
`3de15d3374354809ea84ca4df5f93c2473715f02`: 5/5, success, no comments or
actionable findings.
- All GitHub checks pass on current head
`3de15d3374354809ea84ca4df5f93c2473715f02`: 55 successful checks and 2
intentional skips, including `workspaces-b`, build, typecheck, Runner
verification, and e2e.
- Full local `pnpm test:run` was started and stopped after the CI test
lanes passed; it did not complete locally. No worktree-owned test
processes remained afterward.
- Full local typecheck and build were attempted. Both stop at the Runner
Rust commands because `cargo` is absent from the shell PATH. The changed
package typecheck passes. The complete repository typecheck and build
pass in CI.
- The first sandboxed local reproduction could not bind localhost
(`EPERM`). It was repeated with listener permission and reached the
deterministic assertion failure described above.

## Risks

Low risk. This changes three test lines. Runtime behavior, credentials,
workflow settings, and payload coverage stay the same. The GitHub runner
Unicode logging defect remains upstream; this fix removes the incorrect
assertion that triggers it in this test.

## Model Used

OpenAI GPT-6 in Codex, with reasoning, repository inspection, and
command execution. The exact runtime model identifier and context window
size are not exposed in this session.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` OR (b) described the issue in-PR following the relevant issue
template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

Co-authored-by: Paperclip <[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

Development

Successfully merging this pull request may close these issues.

2 participants