test: property-check the auth rate limiter against a sliding-window oracle
Summary
- Adds a fast-check property suite for
lib/auth-rate-limit.ts— the sliding-window limiter that gates OAuth attempts per account. The natural companion to #592's circuit-breaker suite: this module is the L3 convention's canonical module-state example, and its oracle (timestamps-in-window) is trivial enough for a clean model-based test.
What Changed
New test/property/auth-rate-limit.property.test.ts (3 properties, real module under vi.useFakeTimers() with a 3-attempt / 1-second config so sequences cross the expiry boundary):
- Model-based equivalence — for any interleaving of record/reset/advance events across three accounts, with every call going through a decorated id spelling (uppercase, leading/trailing whitespace, tabs),
getAttemptsRemainingandcanAttemptAuthmatch a trivial timestamps-in-window oracle keyed by canonical id. One property pins both the sliding window arithmetic and the trim+lowercase bucket mapping. - Gate fidelity —
checkAuthRateLimitthrowsAuthRateLimitErrorexactly whencanAttemptAuthis false, and the error's payload is live: the canonical accountId,attemptsRemaining === 0, andresetAfterMsagreeing withgetTimeUntilReset(and strictly positive). - No wedged buckets —
recordAuthAttemptdoesn't cap atmaxAttempts, so a burst can stack more timestamps than the limit; the property proves any burst (up to 4× the limit, arbitrary intra-burst gaps) still unblocks completely after one quiet window, withgetTimeUntilResetbounded bywindowMsthroughout.
Validation
- [x]
npm test -- test/property/auth-rate-limit.property.test.ts test/auth-rate-limit.test.ts— 25/25 (new 3 + existing 22 untouched) - [x]
npm run typecheck(also via pre-commit hook) - [x]
npx eslint test/property/auth-rate-limit.property.test.ts --max-warnings=0 - [x] Module-state hygiene: config restored to the documented defaults and buckets cleared in
afterEach; ids namespaced per fc iteration so no run can observe another's buckets
Docs and Governance Checklist
- [x] Test-only; no behavior or docs surface changed
Risk and Rollback
- Risk level: minimal — additive test file; conventions match the existing
test/property/suites (explicit vitest imports, plainfc.assert, fake timers scoped withtry/finally). - Rollback plan: revert the single commit.
https://claude.ai/code/session_01XNtnkLbBiXZxfQQYLMpucB
Generated by Claude Code
note: greptile review for oc-chatgpt-multi-auth. cite files like lib/foo.ts:123. confirm regression tests + windows concurrency/token redaction coverage.
Greptile Summary
adds test/property/auth-rate-limit.property.test.ts — a fast-check property suite for the sliding-window OAuth rate limiter. three properties cover model equivalence (oracle vs module across record/reset/advance interleavings with decorated id spellings), gate fidelity (checkAuthRateLimit throw/no-throw agreement with canAttemptAuth), and burst unblocking (over-limit recording cannot permanently wedge a bucket).
- fake-timer hygiene is solid:
vi.useFakeTimers()+vi.setSystemTime(T0)inside each property callback withtry/finallyrestoration, andrunCounter-namespaced ids prevent cross-iteration bucket leakage. gapsarray size is driven byMAX_ATTEMPTS * 4 - 1(no hardcoded literal), and theif/else ifevent dispatch uses explicit branches.- in property 1's invariant check loop,
canAttemptAuthis still queried with the canonicalidrather than the decoratedspell(index), leaving the trim+lowercase mapping untested for that specific function.
Confidence Score: 5/5
additive test-only file with no behavior changes; correct fake-timer discipline and id namespacing make cross-run interference impossible
the change is a single new test file targeting an existing, stable module. fake timers are scoped properly with try/finally, module state is reset before each property run, and the oracle logic matches the module's pruning criterion exactly. the only gap is that canAttemptAuth is not exercised under decorated spellings in property 1's invariant loop — a minor coverage asymmetry that poses no correctness risk to the module under test.
no files require special attention; test/property/auth-rate-limit.property.test.ts is the only changed file and is straightforward to review
Important Files Changed
| Filename | Overview |
|---|---|
| test/property/auth-rate-limit.property.test.ts | adds 3 fast-check property tests for the sliding-window rate limiter — model equivalence, gate fidelity, and burst unblocking; logic is sound and fake-timer hygiene is correct |
Flowchart
%%{init: {'theme': 'neutral'}}%%
flowchart TD
A[fc.property callback] --> B[vi.useFakeTimers + setSystemTime T0]
B --> C[resetAllAuthRateLimits]
C --> D{event kind}
D -->|advance| E[now += ms\nvi.setSystemTime]
D -->|record| F[recordAuthAttempt spell account\nmodel.push now]
D -->|reset| G[resetAuthRateLimit spell account\nmodel.set empty]
E --> H[Invariant check all 3 accounts]
F --> H
G --> H
H --> I[getAttemptsRemaining spell index\n== oracle inWindow count]
H --> J[canAttemptAuth id\n== oracle live lt MAX]
I --> D
J --> D
D -->|loop done| K[vi.useRealTimers in finally]
Prompt To Fix All With AI
Fix the following 1 code review issue. Work through them one at a time, proposing concise fixes.
---
### Issue 1 of 1
test/property/auth-rate-limit.property.test.ts:99-104
`canAttemptAuth` is only checked with the canonical `id` here, while `getAttemptsRemaining` is checked with the decorated `spell(index)`. the PR description claims "regardless of which spelling recorded the attempts" — but that claim is only verified for `getAttemptsRemaining`. using `canAttemptAuth(spell(index))` instead closes the gap and exercises the trim+lowercase bucket mapping for both functions uniformly.
Reviews (2): Last reviewed commit: "test: exhaustive event narrowing and con..." | Re-trigger Greptile
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. Credits must be used to enable repository wide code reviews.
[!CAUTION]
Review failed
Pull request was closed or merged during review
📝 Walkthrough
This pull request introduces a comprehensive property-based test suite for the auth rate limiter module using Vitest and fast-check. The addition is test-only (no production code changes) and strengthens security validation by covering edge cases across interleaved rate-limit operations, decorated account ID variants, and boundary conditions. All existing tests remain unchanged, ensuring regression coverage is maintained.
The suite validates three core properties: (1) a sliding-window oracle that tracks attempt timestamps and verifies both getAttemptsRemaining and canAttemptAuth across arbitrary record/reset/time-advance sequences with canonicalized account IDs, (2) gate fidelity ensuring checkAuthRateLimit throws AuthRateLimitError precisely when blocked with correct error payloads, and (3) no wedged buckets confirming that bursts exceeding the limit fully unblock after a quiet window. Tests use a 3-attempt/1-second window configuration with fake timers, proper state isolation between iterations, and exhaustive event narrowing to guard against silent modeling errors. The commit sequence demonstrates iterative refinement addressing code review feedback on timer hygiene and maintainability (replacing hardcoded values with derived constants).
Walkthrough
adds a single property-based test file at test/property/auth-rate-limit.property.test.ts with three fast-check properties: a sliding-window oracle check, checkAuthRateLimit throw-semantics validation, and a quiet-window unblocking assertion. uses fake timers and per-run unique account ids to isolate state across runs.
Changes
Auth Rate Limit Property Tests
| Layer / File(s) | Summary |
|---|---|
Test harness setup test/property/auth-rate-limit.property.test.ts:1-63 |
defines WINDOW_MS, MAX_ATTEMPTS, per-run account id counter, and beforeEach/afterEach hooks that call configureAuthRateLimit, resetAllAuthRateLimits, and toggle fake/real timers. |
Sliding-window oracle property test/property/auth-rate-limit.property.test.ts:65-111 |
generates random record/reset/advance steps and whitespace/case-variant account id decorations; maintains an oracle tracking raw timestamps per account and asserts getAttemptsRemaining and canAttemptAuth match oracle after every step. |
checkAuthRateLimit throw-semantics property test/property/auth-rate-limit.property.test.ts:113-156 |
for the same randomized sequences, asserts checkAuthRateLimit throws AuthRateLimitError with correct accountId, attemptsRemaining (=0), and resetAfterMs == getTimeUntilReset when blocked, and does not throw when allowed. |
Unblocking-after-quiet-window property test/property/auth-rate-limit.property.test.ts:158-200 |
generates over-burst attempt counts and gap durations; verifies account stays blocked immediately after exceeding maxAttempts, then confirms unblocking and reset of getAttemptsRemaining to MAX_ATTEMPTS and getTimeUntilReset to 0 after advancing WINDOW_MS + 1. |
Estimated code review effort
🎯 3 (Moderate) | ⏱️ ~20 minutes
a few things to flag explicitly:
missing edge cases at test/property/auth-rate-limit.property.test.ts:
-
test/...:65-111— the oracle only tracks three canonical account ids. there's no property covering concurrent interleaving of multiple distinct accounts advancing time simultaneously. if the underlying implementation (lib/auth-rate-limit) holds a single shared timestamp store, you're not testing cross-account isolation under concurrent access patterns. -
test/...:1-63—WINDOW_MSandMAX_ATTEMPTSare set to small test values but there's no property that exercises the boundary at exactlymaxAttempts(i.e., thenth attempt that is still allowed vs. then+1th that blocks). the oracle path at line 65–111 could miss an off-by-one in the production sliding window if the generated sequences never land on that exact boundary count. -
test/...:158-200— the unblocking property only advances by exactlyWINDOW_MS + 1. there's no case for advancing by less thanWINDOW_MSwith some but not all attempts having expired. that's the core sliding-window behavior; without it, a fixed-window implementation could pass these tests incorrectly. -
test/...:113-156—resetAfterMsis asserted equal togetTimeUntilResetat the same instant, but there's no test for what happens when time is advanced between the throw and readinggetTimeUntilReset. minor, but if those calls aren't atomic, this assertion could flake under real timers.
no regression tests flagged for windows-style environments: if lib/auth-rate-limit uses Date.now() internally, fake timer behavior across platforms should be verified — test/...:1-63 uses vi.useFakeTimers() but doesn't explicitly set an initial clock value, which could cause the oracle timestamps to start at 0 vs. the real epoch in some environments.
🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)
| Check name | Status | Explanation | Resolution |
|---|---|---|---|
| Title check | ⚠️ Warning | title exceeds 72 character limit at 74 chars; conventional commit format and type are correct but summary length violates requirements. | shorten summary to ≤72 chars, e.g. 'test: property-check auth rate limiter against sliding-window oracle' (67 chars). |
✅ Passed checks (4 passed)
| Check name | Status | Explanation |
|---|---|---|
| Description check | ✅ Passed | description comprehensively covers all required template sections: summary, what changed, validation checklist (all marked complete), governance checklist, and risk/rollback details. |
| Docstring Coverage | ✅ Passed | No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check. |
| Linked Issues check | ✅ Passed | Check skipped because no linked issues were found for this pull request. |
| Out of Scope Changes check | ✅ Passed | Check skipped because no linked issues were found for this pull request. |
✏️ Tip: You can configure your own custom pre-merge checks in the settings.
✨ Finishing Touches
📝 Generate docstrings
- [ ] Create stacked PR
- [ ] Commit on current branch
🧪 Generate unit tests (beta)
- [ ] Create PR with unit tests
- [ ] Commit unit tests in branch
claude/audit-74-auth-rate-limit-property
✨ Simplify code
- [ ] Create PR with simplified code
- [ ] Commit simplified code in branch
claude/audit-74-auth-rate-limit-property
[!WARNING] There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.
🔧 ESLint
If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.
test/property/auth-rate-limit.property.test.ts
Oops! Something went wrong! :(
ESLint: 10.0.0
Error: The 'jiti' library is required for loading TypeScript configuration files. Make sure to install it. at /node_modules/eslint/lib/config/config-loader.js:145:10 at async loadTypeScriptConfigFileWithJiti (/node_modules/eslint/lib/config/config-loader.js:144:3) at async loadConfigFile (/node_modules/eslint/lib/config/config-loader.js:265:11) at async ConfigLoader.calculateConfigArray (/node_modules/eslint/lib/config/config-loader.js:588:23) at async
#calculateConfigArray(/node_modules/eslint/lib/config/config-loader.js:369:19) at async Promise.all (index 0) at async findFiles (/node_modules/eslint/lib/eslint/eslint-helpers.js:635:25) at async ESLint.lintFiles (/node_modules/eslint/lib/eslint/eslint.js:1014:21) at async Object.execute (/node_modules/eslint/lib/cli.js:386:14) at async main (/node_modules/eslint/bin/eslint.js:175:19)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Comment @coderabbitai help to get the list of available commands and usage tips.