Skip to content

Fix tj ping: omit empty Bearer header so the test span is delivered - #431

Merged
anilmurty merged 2 commits into
mainfrom
fix/tj-ping-bearer
Jul 8, 2026
Merged

anilmurty merged 2 commits into
mainfrom
fix/tj-ping-bearer

Conversation

@anilmurty

Copy link
Copy Markdown
Contributor

tj ping threw httpx.LocalProtocolError: Illegal header value b'Bearer ' and never delivered its test span whenever the resolved config had no security.ingest_secret. This makes the command's proof-of-life useless in exactly the situation where a user is debugging their wiring.

Summary

  • Build the Authorization header conditionally in TjHttpExporter: send Bearer <secret> when a secret exists, omit the header entirely when there is none.
  • Add a unit test asserting the header is well-formed (Bearer <secret>, no stray whitespace) when a secret is set, and absent — never an empty Bearer — when it isn't.

Root cause

TjHttpExporter.__init__ (in tokenjam/sdk/http_exporter.py) unconditionally built:

"Authorization": f"Bearer {ingest_secret}"

When config.security.ingest_secret is empty, that produces the literal header value Bearer (trailing whitespace). Per RFC 9110, header values may not have leading/trailing whitespace, so h11/httpcore raise LocalProtocolError: Illegal header value b'Bearer ' at send time — deep inside BatchSpanProcessor. The OTLP span export never completes, the span never reaches tj serve, and tj ping falls through to the "Span emitted … but not confirmed received" branch. The narrow except (httpx.ConnectError, httpx.TimeoutException) in export() doesn't cover this error, so it surfaces as an uncaught export traceback.

Fix

Only attach Authorization when a secret is configured. If there genuinely is no secret, the request goes out without the header; tj serve returns 401 if it requires auth, which the existing export() 401 branch already handles gracefully (Critical Rule 4 preserved — a configured secret still sends Bearer <secret>).

Tests / Verification

  • New tests/unit/test_http_exporter_auth.py: header is Bearer <secret> (stripped, single space) with a secret; no Authorization header (and never Bearer ) with ""/None.
  • Full unit suite green: 1596 passed, 2 skipped. ruff check tokenjam/ and mypy tokenjam/sdk/http_exporter.py clean.
  • End-to-end against v0.5.4 with a live tj serve:
    • Empty secret, pre-fix: tj ping prints the LocalProtocolError: Illegal header value b'Bearer ' traceback; span dropped.
    • Empty secret, fixed: ✓ Delivered to tj serve … (confirmed received).
    • Matching secret, fixed: tj ping --json → {"confirmed": true, ...}, exit 0.

What's NOT in this PR

  • The separate "config secret didn't load into the exporter" resolution question. Both tj ping's CLI config and bootstrap.ensure_initialised() already call load_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.
  • No change to the export() exception handling / retry semantics beyond preventing the illegal header from being constructed in the first place.

🤖 Generated with Claude Code

anilmurty and others added 2 commits July 8, 2026 16:21
`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
@anilmurty
anilmurty marked this pull request as ready for review July 8, 2026 23:53
@anilmurty
anilmurty merged commit 02529de into main Jul 8, 2026
4 checks passed
@anilmurty
anilmurty deleted the fix/tj-ping-bearer branch July 8, 2026 23:53
@greptile-apps

greptile-apps Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes tj ping crashing with LocalProtocolError: Illegal header value b'Bearer ' when ingest_secret is empty or unset, by conditionally omitting the Authorization header instead of unconditionally building a malformed one.

  • tokenjam/sdk/http_exporter.py: __init__ now only appends Authorization: Bearer <secret> to _headers when self._ingest_secret is truthy; empty/None secrets result in no Authorization header, letting the request proceed and allowing the existing 401 branch to handle auth failures gracefully.
  • tests/unit/test_http_exporter_auth.py: New unit test asserting the header is well-formed Bearer <secret> when a secret is provided, and completely absent (never Bearer ) for "" or None inputs.

Confidence Score: 4/5

The fix is correct for the reported case and safe to merge; the remaining gap is whitespace-only secrets, which are a pathological config value unlikely to appear in practice.

The core change correctly prevents Bearer from being constructed for empty or None secrets, resolving the crash. Two residual gaps exist: a whitespace-only secret (e.g. " ") would still pass the truthiness check and produce an illegal header value triggering the same LocalProtocolError, and export() still doesn't catch httpx.LocalProtocolError, so any protocol error that slips through would surface as an unhandled traceback. Neither gap represents a regression introduced by this PR, and the whitespace-only case is an unlikely config error.

Both changed files are straightforward; tokenjam/sdk/http_exporter.py is worth a quick second look at the secret-truthiness check and the except clause if the whitespace-secret edge case matters to the team.

Important Files Changed

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"]
Loading
%%{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"]
Loading

Comments Outside Diff (1)

  1. tokenjam/sdk/http_exporter.py, line 80-81 (link)

    P2 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.

    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

Comment on lines +33 to +34
if self._ingest_secret:
self._headers["Authorization"] = f"Bearer {self._ingest_secret}"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 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.

anilmurty added a commit that referenced this pull request Jul 9, 2026
… (#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]>
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.

1 participant