Skip to content

fix(auth): normalize INTERNAL_JOB_TOKEN whitespace like the three private secrets - #9772

Merged
JSONbored merged 1 commit into
JSONbored:mainfrom
shin-core:fix/internal-token-nonblank-9713
Jul 29, 2026
Merged

fix(auth): normalize INTERNAL_JOB_TOKEN whitespace like the three private secrets#9772
JSONbored merged 1 commit into
JSONbored:mainfrom
shin-core:fix/internal-token-nonblank-9713

Conversation

@shin-core

Copy link
Copy Markdown
Contributor

What & why

src/auth/security.ts has two token authenticators side by side. authenticatePrivateToken early-returns null for a falsy token, then compares against nonBlank(env.LOOPOVER_API_TOKEN), nonBlank(env.LOOPOVER_MCP_ADMIN_TOKEN), and nonBlank(env.LOOPOVER_MCP_TOKEN). authenticateInternalToken was the only one of the four comparing against the raw env.INTERNAL_JOB_TOKEN, with no nonBlank() and no early exit.

extractBearerToken already trims the incoming bearer, so a configured INTERNAL_JOB_TOKEN carrying leading/trailing whitespace — the exact shape a secret file or a wrangler secret put piped from a file produces when it ends in a newline — could never be matched by any caller, while the same whitespace on LOOPOVER_API_TOKEN is tolerated. The failure mode is a blanket 401 unauthorized from the /v1/internal/* middleware for every internal job route and read endpoint, with nothing pointing at whitespace as the cause.

The fix

authenticateInternalToken now applies nonBlank() to env.INTERNAL_JOB_TOKEN and early-returns null for an absent/empty token, mirroring authenticatePrivateToken exactly (the existing module-local nonBlank helper and the existing timingSafeEqual call shape — no new helper, no change to timingSafeEqual semantics, no change at the middleware call site or to the incoming bearer).

This is a normalization gap, not a fail-open one: timingSafeEqual already returns false for an empty/undefined expected value, and nonBlank(" ") is undefined, so a whitespace-only secret still authenticates nobody.

Tests (test/unit/auth-security-helpers.test.ts)

New #9713 suite covering every DoD case:

  • INTERNAL_JOB_TOKEN = " secret ", bearer "secret"{ kind: "static", actor: "internal" } (named regression; fails on current main).
  • Untrimmed correct secret ("secret" / "secret") → internal identity (unchanged behavior).
  • INTERNAL_JOB_TOKEN = " " (whitespace-only) → authenticateInternalToken(env, " ") and (env, "") both null.
  • authenticateInternalToken(env, undefined)null without consulting the secret.
  • A non-matching token → null.

Both arms of the new if (!token) guard and both arms of the nonBlank result are covered.

Validation

  • npm run typecheck green; full auth suite green.
  • Diff branch coverage on src/auth/security.ts is 100% (every added line and branch); the file's whole-file branch coverage is well above the gate floor.
  • git diff --check clean; no route/schema/wrangler/migration change, so nothing to regenerate.
  • Diff is two files: src/auth/security.ts + its unit test.

Closes #9713

…vate secrets

`authenticateInternalToken` compared the incoming bearer against the raw
`env.INTERNAL_JOB_TOKEN`, while its sibling `authenticatePrivateToken` wraps each
of its three secrets in `nonBlank()` (trim → undefined-if-empty) and early-exits
on a falsy token. `extractBearerToken` already trims the incoming token, so an
`INTERNAL_JOB_TOKEN` secret carrying a trailing newline — the shape a
`wrangler secret put` piped from a file produces — could never match any caller
and returned a blanket 401 for every `/v1/internal/*` route, while the same
whitespace on `LOOPOVER_API_TOKEN` was tolerated.

Apply `nonBlank()` and the `if (!token) return null` early exit, mirroring
`authenticatePrivateToken` exactly. This is a normalization gap, not a fail-open
one: `timingSafeEqual` already returns false for an empty/undefined expected
value, and `nonBlank("   ")` is `undefined`, so a whitespace-only secret still
authenticates nobody.

Closes JSONbored#9713
@shin-core
shin-core requested a review from JSONbored as a code owner July 29, 2026 07:51
@superagent-security superagent-security Bot added the contributor:flagged Contributor flagged for review by trust analysis. label Jul 29, 2026
@superagent-security

Copy link
Copy Markdown
Contributor

🚨 Contributor flagged. Click here for more info: Superagent Dashboard

@loopover-orb

loopover-orb Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

Warning

⏸️ LoopOver review result - manual review recommended

Review updated: 2026-07-29 08:06:45 UTC

2 files · 1 AI reviewer · no blockers · CI green · unstable

⏸️ Suggested Action - Manual Review

Review summary
This fix correctly closes the normalization gap: authenticateInternalToken now mirrors authenticatePrivateToken by early-returning null on a falsy token and passing env.INTERNAL_JOB_TOKEN through nonBlank() before the timingSafeEqual comparison, so a secret with trailing whitespace (e.g. from a piped wrangler secret put) will now match a trimmed bearer token. The change is minimal, single-purpose, and directly traces to the described bug — timingSafeEqual already fails closed on undefined/empty values, so nonBlank() returning undefined for whitespace-only secrets preserves fail-closed behavior rather than introducing a fail-open path. Tests cover the whitespace-trim regression, untrimmed-correct-secret, whitespace-only-secret, absent-bearer early-exit, and wrong-token rejection cases, all exercising the real authenticateInternalToken function against realistic Env shapes.

Nits — 3 non-blocking
  • The inline comment block in src/auth/security.ts:121-125 is fairly verbose for a one-line normalization fix; the existing authenticatePrivateToken function above it has no equivalent comment despite doing the same thing, so consider trimming it for consistency.
  • test/unit/auth-security-helpers.test.ts uses `as unknown as Env` casts for a minimal env stub — fine here, but worth confirming this matches the convention used elsewhere in the test suite for partial Env mocks.
  • Consider whether authenticateInternalToken's comment could be shortened to a single line referencing auth: authenticateInternalToken skips the nonBlank() normalization its three siblings apply #9713, matching the terser style used elsewhere in this file for similar fixes (e.g. isAuthorizedGitHubSessionLogin's docblock is justified by complexity, but this is a simple mirror-fix).

Decision drivers

  • ✅ Code review — No blockers (1 reviewer)
  • ✅ Gate result — Passing (No configured blocker found.)
Context & advisory signals — never blocks the verdict
Signal Result Evidence
Linked issue ✅ Linked #9713
Related work ✅ No active overlap found No same-issue or scoped active PR overlap found.
Change scope ✅ 20/20 Low review scope from cached public metadata (1 linked issue).
Validation posture ❌ 5/25 Preflight is holding this PR: the review lane is unavailable, so it is not ready for automated review.
Contributor workload ✅ 10/10 Author activity: 50 registered-repo PR(s), 35 merged, 0 issue(s).
Contributor context ✅ Confirmed Gittensor contributor shin-core; Gittensor profile; 50 PR(s), 0 issue(s).
Improvement ✅ Minor risk: clean · value: minor
Linked issue satisfaction

Addressed
The diff adds the `if (!token) return null` early exit and wraps env.INTERNAL_JOB_TOKEN with nonBlank() in authenticateInternalToken, exactly mirroring authenticatePrivateToken and using the required existing helper/timingSafeEqual shape, and the new test suite covers the trimmed-secret regression case, whitespace-only denial for both blank and empty bearer, the undefined-bearer early exit, and an

Review context
  • Author: shin-core
  • Role context: outside_contributor
  • Public audience mode: oss maintainer
  • Lane context: Repository is registered but has no active allocation in the current snapshot.
  • Public profile languages: not available
  • Official Gittensor activity: 50 PR(s), 0 issue(s).
  • PR-specific overlap: none found.
Contributor next steps
  • Start here: Await review-lane availability.
  • Then work through the remaining 2 steps in the Signals table above.
Signal definitions
  • Related work = same linked issue, overlapping active PRs, or title/path similarity.
  • Change scope = cached public metadata such as size labels, draft state, and review-burden hints.
  • Validation posture = whether the PR provides enough public validation/test evidence for maintainer review.
  • Contributor workload = public contributor activity and cleanup pressure, not a repo-wide quality failure.
  • Contributor context = public GitHub/Gittensor identity context; non-Gittensor status is not a blocker.
🧪 Chat with LoopOver

Ask LoopOver a question about this PR directly in a comment — grounded only in the same cached, public-safe facts shown above, never a new claim.

  • @loopover ask <question> answers contribution-quality Q&A with source citations and freshness.
  • @loopover chat <question> answers in natural prose from cached decision-pack facts via local inference (maintainer/collaborator; read-only).
  • A plain-language @loopover mention with a real question is routed to the closest matching read-only command automatically — no exact syntax required.

Full command reference: https://loopover.ai/docs/loopover-commands

🧪 Experimental — new and may change.

Decision record
  • action: hold · clause: success
  • config: 1fff06be1e4bd13075d66ba2b132d279be3602db3d834a05d67bdd68e18c11dc · pack: oss-anti-slop · ci: passed
  • record: 5c14f33b872f05f481fc7a948003b34a54bdfca8834e43c1895b9556eb6d8495 (schema v5, head 743afe6)

🟩 Safe / merged · 🟦 Advisory · 🟨 Held for review · 🟥 Blocked / closed


💰 Earn for open-source contributions like this. Gittensor lets GitHub contributors earn for the work they already do — register to start earning →.

Checked by LoopOver, a quiet PR intelligence layer for OSS maintainers.

  • Re-run LoopOver review

@superagent-security

Copy link
Copy Markdown
Contributor

Superagent didn't find any vulnerabilities or security issues in this PR.

@loopover-orb loopover-orb Bot added the gittensor:bug Gittensor-scored bug fix — scores a 0.05x multiplier. label Jul 29, 2026
@codecov

codecov Bot commented Jul 29, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 76.63%. Comparing base (8e02fab) to head (743afe6).
⚠️ Report is 2 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #9772      +/-   ##
==========================================
+ Coverage   76.58%   76.63%   +0.04%     
==========================================
  Files         282      283       +1     
  Lines       59464    59575     +111     
  Branches     6555     6595      +40     
==========================================
+ Hits        45543    45653     +110     
  Misses      13639    13639              
- Partials      282      283       +1     
Flag Coverage Δ
backend 99.09% <100.00%> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
src/auth/security.ts 99.09% <100.00%> (ø)

@loopover-orb

loopover-orb Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

Held for manual review: the gate and required CI are green, but GitHub reports this pull request's mergeable state as unstable because a non-required check or status is not passing, so LoopOver will not auto-merge. A maintainer can resolve the failing check or review and merge manually. This is an automated maintenance action.

@loopover-orb loopover-orb Bot added the manual-review Gittensor contributor context label Jul 29, 2026
@JSONbored
JSONbored merged commit 8618983 into JSONbored:main Jul 29, 2026
7 of 8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

contributor:flagged Contributor flagged for review by trust analysis. gittensor:bug Gittensor-scored bug fix — scores a 0.05x multiplier. manual-review Gittensor contributor context

Projects

None yet

Development

Successfully merging this pull request may close these issues.

auth: authenticateInternalToken skips the nonBlank() normalization its three siblings apply

2 participants