Skip to content

fix(crypto): reject invalid hex operands in timingSafeEqualHex - #1760

Merged
JSONbored merged 2 commits into
JSONbored:mainfrom
andriypolanski:fix/crypto-timing-safe-equal-hex
Jun 29, 2026
Merged

fix(crypto): reject invalid hex operands in timingSafeEqualHex#1760
JSONbored merged 2 commits into
JSONbored:mainfrom
andriypolanski:fix/crypto-timing-safe-equal-hex

Conversation

@andriypolanski

Copy link
Copy Markdown
Contributor

Summary

  • Fixes timingSafeEqualHex so distinct invalid hex strings no longer compare equal.
  • Aligns hexToBytes fail behavior with src/orb/relay.ts (return null / false on invalid input instead of an empty byte array).
  • Adds regression tests covering mismatched invalid hex, odd-length hex, and valid equal/unequal pairs.

Closes #ISSUE_NUMBER (open a bug issue first — none exists yet for this).

Bug

In src/utils/crypto.ts, hexToBytes returns an empty Uint8Array for invalid hex:

function hexToBytes(hex: string): Uint8Array {
  if (!/^[0-9a-f]+$/i.test(hex) || hex.length % 2 !== 0) return new Uint8Array();
  // ...
}

Two different invalid strings (e.g. "zz" vs "yy", or "not-hex-a" vs "not-hex-b") both parse to length-0 arrays, so timingSafeEqualHex returns true. That violates the contract of a constant-time equality check and diverges from src/orb/relay.ts, where invalid hex causes verification to fail.

Current call sites (verifyGitHubSignature, draft OAuth state checks) always compare against valid 64-char SHA-256 hex on at least one side, so this is latent — but the exported primitive is incorrect and unsafe for reuse.

Proposed fix

function hexToBytes(hex: string): Uint8Array | null {
  if (!/^[0-9a-f]+$/i.test(hex) || hex.length % 2 !== 0) return null;
  // ...
}

export function timingSafeEqualHex(left: string, right: string): boolean {
  const leftBytes = hexToBytes(left);
  const rightBytes = hexToBytes(right);
  if (!leftBytes || !rightBytes) return false;
  if (leftBytes.length !== rightBytes.length) return false;
  // ... constant-time compare unchanged
}

Scope

  • The PR title follows type(scope): short summary Conventional Commit format.
  • This PR is focused and does not mix unrelated backend, UI, MCP, docs, dependency, and deploy changes.
  • This follows CONTRIBUTING.md and does not reintroduce GitHub Pages, VitePress, site/, or CNAME.
  • I linked an issue, or this is small enough that the summary explains why an issue is not needed.

Validation

  • git diff --check
  • npm run actionlint
  • npm run typecheck
  • npm run test:coverage locally; codecov/patch requires ≥97% coverage of the lines AND branches you changed
  • npm run test:workers
  • npm run build:mcp
  • npm run test:mcp-pack
  • npm run ui:openapi:check
  • npm run ui:lint
  • npm run ui:typecheck
  • npm run ui:build
  • npm audit --audit-level=moderate
  • New or changed behavior has unit/integration tests for new branches, fallback paths, and sanitizer boundaries

If any required check was skipped, explain why:

  • N/A — all gates expected to run.

Safety

  • No secrets, wallet details, hotkeys, coldkeys, user PATs, private keys, raw trust scores, private rankings, or private maintainer evidence are exposed.
  • Public GitHub text stays sanitized, low-noise, and does not imply compensation guarantees or optimization tactics.
  • Auth, cookie, CORS, GitHub App, Cloudflare, or session changes include negative-path tests.
  • API/OpenAPI/MCP behavior is updated and tested where needed.
  • UI changes use live API data or real empty/error/loading states, not production mock/demo fallbacks.
  • Visible UI changes include a UI Evidence section below. (N/A — crypto utility only)

Test plan

  • Add or extend test/unit/security-internals.test.ts (or a dedicated crypto.test.ts if one exists):
    • timingSafeEqualHex("zz", "yy")false
    • timingSafeEqualHex("abc", "abcd")false (odd length)
    • timingSafeEqualHex(valid64, valid64)true
    • timingSafeEqualHex(valid64a, valid64b)false
  • Existing auth/draft tests that exercise verifyGitHubSignature and draft OAuth still pass.
  • npm run test:ci green.

Files to change

File Change
src/utils/crypto.ts Return null from hexToBytes on invalid input; fail closed in timingSafeEqualHex
test/unit/security-internals.test.ts or new test/unit/crypto.test.ts Regression tests for invalid hex branches

Notes

@dosubot dosubot Bot added the size:XS label Jun 29, 2026
@loopover-orb

loopover-orb Bot commented Jun 29, 2026

Copy link
Copy Markdown
Contributor

Tip

🟩🟩🟩🟩🟩🟩🟩🟩🟩🟩🟩🟩

✅ Gittensory review result - approve/merge recommended

Review updated: 2026-06-29 21:43:37 UTC

2 files · 1 AI reviewer · no blockers · readiness 66/100 · CI green · clean

✅ Suggested Action - Approve/Merge

  • safe to merge

Review summary
The change fixes the real invalid-hex equality bug by making `hexToBytes` fail closed with `null` and by having `timingSafeEqualHex` reject either invalid operand before comparing byte lengths. The post-change file shows the exported helper and `verifyGitHubSignature` both route through that guard, and the tests cover distinct invalid operands, odd-length input, valid mismatch, and valid equality. This is a focused crypto utility fix with no visible contract break for the provided callers.

Nits — 3 non-blocking
  • nit: test/unit/crypto.test.ts:26 should add an explicit `timingSafeEqualHex("", "")` expectation if empty strings are now part of the invalid-input contract being enforced.
  • test/unit/crypto.test.ts:26 Add a direct empty-vs-empty regression so the `hex.length === 0` branch is locked to `false`, not just covered through one-sided empty input.
  • Readiness score is below the configured threshold — Use the readiness panel as advisory maintainer context; the score does not block this PR.
Signal Result Evidence
Code review ✅ No blockers 1 reviewer
Linked issue ⚠️ Missing No linked issue or no-issue rationale found.
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 (size label size:XS; no linked issue context).
Validation posture ❌ 5/25 Preflight is holding this PR; address the blocker before review.
Contributor workload ✅ 10/10 Author activity: 84 registered-repo PR(s), 57 merged, 5 issue(s).
Contributor context ✅ Confirmed Gittensor contributor andriypolanski; Gittensor profile; 84 PR(s), 5 issue(s).
Gate result ✅ Passing No configured blocker found.
Review context
  • Author: andriypolanski
  • Role context: outside_contributor
  • Public audience mode: oss maintainer
  • Lane context: Repository registration is not available in the local Gittensory cache.
  • Public profile languages: not available
  • Official Gittensor activity: 84 PR(s), 5 issue(s).
  • PR-specific overlap: none found.
Contributor next steps
  • Explain no-issue PR.
  • Fix the blocker.
  • Triage stale or unlinked PRs.
  • Refresh registry data or choose a registered active repo.
  • Link the issue being solved, or explicitly explain why this is a no-issue PR.
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.

🟩 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 Gittensory, a quiet PR intelligence layer for OSS maintainers.

  • Re-run Gittensory review

@loopover-orb loopover-orb Bot added gittensor gittensor:bug Gittensor-scored bug fix — scores a 0.05x multiplier. labels Jun 29, 2026
@dosubot dosubot Bot added the lgtm label Jun 29, 2026
@JSONbored
JSONbored merged commit 5733910 into JSONbored:main Jun 29, 2026
15 checks passed
@github-project-automation github-project-automation Bot moved this from Todo to Done in gittensory - v1 roadmap Jun 29, 2026
@andriypolanski
andriypolanski deleted the fix/crypto-timing-safe-equal-hex branch July 16, 2026 15:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gittensor:bug Gittensor-scored bug fix — scores a 0.05x multiplier.

Projects

No open projects
Status: Done

Development

Successfully merging this pull request may close these issues.

2 participants