Repository navigation
Fix tj ping: omit empty Bearer header so the test span is delivered - #431
Conversation
`tj ping` threw `httpx.LocalProtocolError: Illegal header value b'Bearer '`
whenever the resolved config had no `security.ingest_secret`. The SDK's OTLP
span exporter (`TjHttpExporter`) unconditionally built
`Authorization: Bearer {ingest_secret}`, so an empty secret produced the
literal header value `Bearer ` — a trailing-whitespace value that h11 rejects
at send time per RFC 9110. The export raised inside `BatchSpanProcessor`, the
span never reached `tj serve`, and ping reported "emitted … but not confirmed
received."
Only attach the `Authorization` header when a secret is actually configured;
when there is none, omit the header entirely rather than sending an illegal
empty `Bearer ` (Critical Rule 4 — a real secret still sends
`Bearer <secret>`). Verified end-to-end against v0.5.4: with an empty secret
the pre-fix build tracebacks and drops the span, the fixed build delivers it
and reports "confirmed received"; with a matching secret ping exits 0 with
`confirmed: true`.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_015e3DZGhb1R5sXX2x52Y2Ar
|
| Filename | Overview |
|---|---|
| tokenjam/sdk/http_exporter.py | Conditionally builds the Authorization header — only adds Bearer <secret> when the secret is non-empty, preventing the LocalProtocolError on empty secrets; whitespace-only secrets remain an unguarded edge case. |
| tests/unit/test_http_exporter_auth.py | New regression test covering "" and None secrets (no Authorization header) and a well-formed secret (correct Bearer format); does not cover whitespace-only secrets that would still produce an illegal header. |
Flowchart
%%{init: {'theme': 'neutral'}}%%
flowchart TD
A["TjHttpExporter.__init__(endpoint, ingest_secret)"] --> B["self._ingest_secret = ingest_secret or ''"]
B --> C{"self._ingest_secret\ntruthiness check"}
C -- "non-empty" --> D["_headers['Authorization'] = 'Bearer <secret>'"]
C -- "empty / None" --> E["No Authorization header added"]
D --> F["export() → httpx.post(headers=_headers)"]
E --> F
F --> G{"HTTP response"}
G -- "2xx" --> H["SpanExportResult.SUCCESS"]
G -- "401" --> I["Log ERROR + drop count\nSpanExportResult.FAILURE"]
G -- "other" --> J["Log WARNING\nSpanExportResult.FAILURE"]
F -- "ConnectError / TimeoutException" --> K["Log WARNING\nSpanExportResult.FAILURE"]
F -. "LocalProtocolError (whitespace secret)" .-> L["Uncaught — bubbles to BatchSpanProcessor"]
%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%%
flowchart TD
A["TjHttpExporter.__init__(endpoint, ingest_secret)"] --> B["self._ingest_secret = ingest_secret or ''"]
B --> C{"self._ingest_secret\ntruthiness check"}
C -- "non-empty" --> D["_headers['Authorization'] = 'Bearer <secret>'"]
C -- "empty / None" --> E["No Authorization header added"]
D --> F["export() → httpx.post(headers=_headers)"]
E --> F
F --> G{"HTTP response"}
G -- "2xx" --> H["SpanExportResult.SUCCESS"]
G -- "401" --> I["Log ERROR + drop count\nSpanExportResult.FAILURE"]
G -- "other" --> J["Log WARNING\nSpanExportResult.FAILURE"]
F -- "ConnectError / TimeoutException" --> K["Log WARNING\nSpanExportResult.FAILURE"]
F -. "LocalProtocolError (whitespace secret)" .-> L["Uncaught — bubbles to BatchSpanProcessor"]
Comments Outside Diff (1)
-
tokenjam/sdk/http_exporter.py, line 80-81 (link)httpx.LocalProtocolErrorstill not caught inexport()The fix prevents the illegal-header path for empty/
Nonesecrets, but if a whitespace-only secret slips through (see the other comment), or if some other HTTP-level protocol error arises,LocalProtocolErroris still not listed in theexceptclause and will surface as an uncaught export traceback inBatchSpanProcessor. Addinghttpx.LocalProtocolErroralongsideConnectError/TimeoutExceptionwould make this method fully defensive against protocol-layer failures.Prompt To Fix With AI
This is a comment left during a code review. Path: tokenjam/sdk/http_exporter.py Line: 80-81 Comment: **`httpx.LocalProtocolError` still not caught in `export()`** The fix prevents the illegal-header path for empty/`None` secrets, but if a whitespace-only secret slips through (see the other comment), or if some other HTTP-level protocol error arises, `LocalProtocolError` is still not listed in the `except` clause and will surface as an uncaught export traceback in `BatchSpanProcessor`. Adding `httpx.LocalProtocolError` alongside `ConnectError`/`TimeoutException` would make this method fully defensive against protocol-layer failures. How can I resolve this? If you propose a fix, please make it concise.
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
Prompt To Fix All With AI
Fix the following 2 code review issues. Work through them one at a time, proposing concise fixes.
---
### Issue 1 of 2
tokenjam/sdk/http_exporter.py:33-34
**Whitespace-only secret still produces an illegal header**
`if self._ingest_secret:` is truthy for `" "` (a whitespace-only string), so a config value like `ingest_secret = " "` would produce `"Bearer "` — still an RFC 9110 violation that triggers the same `LocalProtocolError` this PR is fixing. Consider checking `if self._ingest_secret.strip():` and using the stripped value in the header to close this gap entirely.
### Issue 2 of 2
tokenjam/sdk/http_exporter.py:80-81
**`httpx.LocalProtocolError` still not caught in `export()`**
The fix prevents the illegal-header path for empty/`None` secrets, but if a whitespace-only secret slips through (see the other comment), or if some other HTTP-level protocol error arises, `LocalProtocolError` is still not listed in the `except` clause and will surface as an uncaught export traceback in `BatchSpanProcessor`. Adding `httpx.LocalProtocolError` alongside `ConnectError`/`TimeoutException` would make this method fully defensive against protocol-layer failures.
Reviews (1): Last reviewed commit: "Merge branch 'main' into fix/tj-ping-bea..." | Re-trigger Greptile
| if self._ingest_secret: | ||
| self._headers["Authorization"] = f"Bearer {self._ingest_secret}" |
There was a problem hiding this comment.
Whitespace-only secret still produces an illegal header
if self._ingest_secret: is truthy for " " (a whitespace-only string), so a config value like ingest_secret = " " would produce "Bearer " — still an RFC 9110 violation that triggers the same LocalProtocolError this PR is fixing. Consider checking if self._ingest_secret.strip(): and using the stripped value in the header to close this gap entirely.
Prompt To Fix With AI
This is a comment left during a code review.
Path: tokenjam/sdk/http_exporter.py
Line: 33-34
Comment:
**Whitespace-only secret still produces an illegal header**
`if self._ingest_secret:` is truthy for `" "` (a whitespace-only string), so a config value like `ingest_secret = " "` would produce `"Bearer "` — still an RFC 9110 violation that triggers the same `LocalProtocolError` this PR is fixing. Consider checking `if self._ingest_secret.strip():` and using the stripped value in the header to close this gap entirely.
How can I resolve this? If you propose a fix, please make it concise.… (#434) Five review findings from the just-merged onboarding batch, addressed together because they cluster around the same onboard/uninstall UX and the SDK exporter/backfill idempotency touched in that batch. #432 (P1): the combination path double-ran the Codex backfill and printed the closing home banner up to three times. `_onboard_codex` ran its own backfill AND printed the banner, `_onboard_claude_code` printed the banner too, and `_onboard_combination` did both again. Fix: give both per-path sub-onboarders a `standalone: bool = True` parameter. The combination flow passes `standalone=False`, which suppresses each sub-onboarder's own Codex backfill and closing banner — so the backfill runs exactly once (in the combination leg) and the banner prints exactly once (at the very end). Single-path flows keep `standalone=True` and are unchanged. #430 (P1): after a successful `pipx uninstall tokenjam`, the venv is gone, so the printed reinstall hint `pipx upgrade tokenjam` would fail ("not installed"). Added `_package_fresh_install_hint()` (bare `pipx install` / `pip install`) and use it only on the successful-removal path. The upgrade/--force hint stays where it belongs — when the package REMAINS (a plain install would no-op there). #430 (P2): `--remove-package` help text overstated ("runs pipx/pip uninstall") — for non-pipx installs it only PRINTS the command. Reworded the help + option text and the interactive confirm prompt so they say "runs" for pipx and "prints … for you to run" for pip/venv. #431 (P2): a whitespace-only ingest secret was truthy, so `TjHttpExporter` built `Authorization: Bearer ` — the same illegal header value the empty case already guards against. Now guard on `.strip()` so a blank secret omits the header entirely. #433 (P2): `ingest_codex` issued one `SELECT 1 FROM spans WHERE span_id=$1` per span. Aligned it with the Claude Code path's bulk idempotency by reusing `core.backfill._existing_span_ids` — one chunked `WHERE span_id IN (...)` per session partitions new-vs-existing spans, replacing the per-span existence SELECT. Backends without a `conn` (InMemoryBackend) fall back to plain inserts and let the PRIMARY KEY conflict skip duplicates. Tests: combination path backfills each source ONCE and prints the banner ONCE (TestCombinationPathNoDoubleRun); after-removal reinstall hint is `pipx install` not upgrade; prompt wording matches install type; whitespace-only secret omits the Authorization header; a DuckDB-backed idempotency test exercises the new bulk `_existing_span_ids` path. Claude-Session: https://claude.ai/code/session_015e3DZGhb1R5sXX2x52Y2Ar Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
tj pingthrewhttpx.LocalProtocolError: Illegal header value b'Bearer 'and never delivered its test span whenever the resolved config had nosecurity.ingest_secret. This makes the command's proof-of-life useless in exactly the situation where a user is debugging their wiring.Summary
Authorizationheader conditionally inTjHttpExporter: sendBearer <secret>when a secret exists, omit the header entirely when there is none.Bearer <secret>, no stray whitespace) when a secret is set, and absent — never an emptyBearer— when it isn't.Root cause
TjHttpExporter.__init__(intokenjam/sdk/http_exporter.py) unconditionally built:When
config.security.ingest_secretis empty, that produces the literal header valueBearer(trailing whitespace). Per RFC 9110, header values may not have leading/trailing whitespace, so h11/httpcore raiseLocalProtocolError: Illegal header value b'Bearer 'at send time — deep insideBatchSpanProcessor. The OTLP span export never completes, the span never reachestj serve, andtj pingfalls through to the "Span emitted … but not confirmed received" branch. The narrowexcept (httpx.ConnectError, httpx.TimeoutException)inexport()doesn't cover this error, so it surfaces as an uncaught export traceback.Fix
Only attach
Authorizationwhen a secret is configured. If there genuinely is no secret, the request goes out without the header;tj servereturns 401 if it requires auth, which the existingexport()401 branch already handles gracefully (Critical Rule 4 preserved — a configured secret still sendsBearer <secret>).Tests / Verification
tests/unit/test_http_exporter_auth.py: header isBearer <secret>(stripped, single space) with a secret; noAuthorizationheader (and neverBearer) with""/None.1596 passed, 2 skipped.ruff check tokenjam/andmypy tokenjam/sdk/http_exporter.pyclean.tj serve:tj pingprints theLocalProtocolError: Illegal header value b'Bearer 'traceback; span dropped.✓ Delivered to tj serve … (confirmed received).tj ping --json→{"confirmed": true, ...}, exit 0.What's NOT in this PR
tj ping's CLI config andbootstrap.ensure_initialised()already callload_config(), so a configured secret does reach the exporter; the observed failure is purely the empty-Bearer header. Left the config-discovery path untouched to keep scope to the header bug.export()exception handling / retry semantics beyond preventing the illegal header from being constructed in the first place.🤖 Generated with Claude Code