Skip to content

fix(auth): fail closed on rate limiter errors#5109

Open
JSONbored wants to merge 1 commit into
mainfrom
codex/propose-fix-for-rate-limiter-bypass
Open

fix(auth): fail closed on rate limiter errors#5109
JSONbored wants to merge 1 commit into
mainfrom
codex/propose-fix-for-rate-limiter-bypass

Conversation

@JSONbored

Copy link
Copy Markdown
Owner

Motivation

  • A global rate-limit middleware was failing open when the Durable Object check threw, which unthrottled strict/expensive and unauthenticated endpoints during limiter outages and created an abuse-control bypass.
  • The change ensures the middleware preserves the global abuse-control boundary by returning a structured fail-closed response instead of allowing the request to proceed.

Description

  • Change enforceRateLimit in src/auth/rate-limit.ts to return a structured 503 JSON response { error: "rate_limiter_unavailable" } with a Retry-After: 5 header when the Durable Object idFromName/get/fetch path throws.
  • Preserve best-effort audit semantics so a failed rate_limit.denied audit write does not convert an already-denied 429 into a crash.
  • Update test/unit/auth.test.ts to assert the new fail-closed behavior for both Error and non-Error Durable Object failures and adjust test names/comments to match the structured response expectation.

Testing

  • Ran the targeted regression suite: npx vitest run test/unit/auth.test.ts -t "REGRESSION (#5000)" --reporter=verbose, which passed the updated regression checks.
  • Ran the full auth unit file: npx vitest run test/unit/auth.test.ts --reporter=verbose, which passed (all auth.test.ts cases passed locally).
  • Attempted full coverage with npm run test:coverage in this environment but the complete repo-wide coverage run could not be completed here due to unrelated long-running/timeout failures in other unit shards; recommend running the full local gate (npm run test:ci / npm run test:coverage) before pushing.

Codex Task

@superagent-security

Copy link
Copy Markdown
Contributor

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

@codecov

codecov Bot commented Jul 11, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.13%. Comparing base (cd1a905) to head (091ebae).
⚠️ Report is 23 commits behind head on main.
✅ All tests successful. No failed tests found.

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #5109   +/-   ##
=======================================
  Coverage   94.13%   94.13%           
=======================================
  Files         466      466           
  Lines       39573    39573           
  Branches    14436    14436           
=======================================
  Hits        37254    37254           
  Misses       1664     1664           
  Partials      655      655           
Flag Coverage Δ
shard-1 46.50% <0.00%> (-0.02%) ⬇️
shard-2 33.44% <100.00%> (-0.12%) ⬇️
shard-3 31.60% <0.00%> (+0.25%) ⬆️
shard-4 32.70% <0.00%> (+0.01%) ⬆️
shard-5 33.18% <0.00%> (-0.24%) ⬇️
shard-6 45.14% <0.00%> (+0.19%) ⬆️

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

Files with missing lines Coverage Δ
src/auth/rate-limit.ts 98.88% <100.00%> (ø)
🚀 New features to boost your workflow:
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@JSONbored JSONbored self-assigned this Jul 11, 2026
@gittensory-orb gittensory-orb Bot added the gittensor:bug Gittensor-scored bug fix — scores a 0.05x multiplier. label Jul 11, 2026
@gittensory-orb

gittensory-orb Bot commented Jul 11, 2026

Copy link
Copy Markdown

Warning

🟨🟨🟨🟨🟨🟨🟨🟨🟨🟨🟨🟨

⏸️ Gittensory review result - manual review recommended

Review updated: 2026-07-12 01:10:44 UTC

2 files · 1 AI reviewer · 2 blockers · readiness 93/100 · CI green · unstable

⏸️ Suggested Action - Manual Review

  • No linked issue detected — If this PR is intended to solve an issue, link it explicitly in the PR body.
  • Maintainer requires a linked issue — Link the relevant issue (for example Closes #123) before opening the PR.

Review summary
This PR flips `enforceRateLimit`'s Durable Object error handling in src/auth/rate-limit.ts from fail-open (returning null, letting the request proceed unthrottled) to fail-closed (returning a structured 503 with a Retry-After header), correctly closing the abuse-control bypass described in the motivation. The change is small, self-contained, and the accompanying test updates in auth.test.ts directly assert the new 503 status, retry-after header, and JSON body for both Error and non-Error DO failures, mirroring the reversed intent of the original #5000 regression tests. The best-effort audit-write comment tweak is a no-op clarification, not a functional change.

Nits — 5 non-blocking
  • src/auth/rate-limit.ts:77,79 use bare literals `5` and `503` for the retry delay and status code; a named constant (e.g. `RATE_LIMITER_UNAVAILABLE_RETRY_SECONDS`) would keep this in sync with the `retryAfterSeconds` value in the JSON body if either needs to change later.
  • The fail-closed behavior now applies uniformly to every routeClass, including auth routes gated pre-auth (e.g. /v1/auth/session via isPreAuthRateLimitPath) — worth confirming in the PR description or a comment that a limiter outage intentionally blocks login/session endpoints too, since that's a stronger UX/availability tradeoff than just gating 'strict/expensive' routes as the motivation text emphasizes.
  • Consider extracting the retry-after seconds value (5) into a shared constant referenced by both the header and the JSON body in src/auth/rate-limit.ts:73-82 to avoid future drift.
  • If not already covered elsewhere, add a brief note in the PR description confirming which upstream middleware treats a non-null Response from enforceRateLimit as a short-circuit for every routeClass, since this diff now relies on that for auth-adjacent routes too.
  • nit: `src/auth/rate-limit.ts:77` repeats the fallback retry delay as raw `5`/`"5"`; name it once so the body and `Retry-After` header cannot drift.

Concerns raised — review before merging

  • No linked issue detected — If this PR is intended to solve an issue, link it explicitly in the PR body.
  • Maintainer requires a linked issue — Link the relevant issue (for example Closes #123) before opening the PR.
Signal Result Evidence
Code review ❌ 2 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 (no linked issue context).
Validation posture ✅ 25/25 PR body includes validation/test evidence.
Contributor workload ✅ 10/10 Author activity: 45 registered-repo PR(s), 37 merged, 415 issue(s).
Contributor context ✅ Confirmed Gittensor contributor JSONbored; Gittensor profile; 45 PR(s), 415 issue(s).
Gate result ❌ Blocking Repo-configured hard blocker found.
Improvement ✅ Minor risk: clean · value: minor — Code changes are accompanied by test evidence.
Review context
  • Author: JSONbored
  • Role context: owner (maintainer lane)
  • Public audience mode: oss maintainer
  • Lane context: Repository is configured for direct PR review.
  • Public profile languages: Python, TypeScript, Ruby, Go, JavaScript, MDX, Shell, Solidity
  • Official Gittensor activity: 45 PR(s), 415 issue(s).
  • PR-specific overlap: none found.
Contributor next steps
  • Treat this as maintainer-lane context rather than normal contributor-lane activity.
  • Explain no-issue PR.
  • 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.
[BETA] Chat with Gittensory

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

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

Full command reference: https://gittensory.aethereal.dev/docs/gittensory-commands

🟩 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

@gittensory-orb gittensory-orb Bot added the manual-review Gittensor contributor context label Jul 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

aardvark codex 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.

1 participant