From 9f60e82a6bbe005991646994231c3dff43c7a83c Mon Sep 17 00:00:00 2001 From: snekxs <26660858+snekxs@users.noreply.github.com> Date: Thu, 24 Sep 2026 01:51:02 -0600 Subject: [PATCH] test: stop the GET rate-limit test flaking on a minute boundary MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The limiter buckets requests as `window::: { test("the guard rate-limits aggressive GET traffic with a strike", async () => { const kv = new FakeKV(); + // The limiter buckets requests into `window:::` from the + // wall clock. Pin the clock so the loop cannot straddle a minute boundary — + // a rollover resets the counter mid-loop and the cap is never reached, which + // made this test pass or fail depending on when it happened to run. + const now = Date.now; + const frozenMinute = Math.floor(now() / 60_000) * 60_000 + 1_000; + Date.now = () => frozenMinute; let lastStatus = 200; - for (let i = 0; i < 241; i++) { - const response = await guarded(new Request("https://openmouse.app/assets/app.js"), kv); - lastStatus = response.status; + try { + for (let i = 0; i < 240; i++) { + await guarded(new Request("https://openmouse.app/assets/app.js"), kv); + } + // The cap allows 240 GETs per minute; the 241st crosses it. + lastStatus = ( + await guarded(new Request("https://openmouse.app/assets/app.js"), kv) + ).status; + } finally { + Date.now = now; } assert.equal(lastStatus, 429); assert.ok(await kv.get("strikes:unknown")); }); +test("the GET rate limit resets on a new minute", async () => { + const kv = new FakeKV(); + const now = Date.now; + let clock = Math.floor(now() / 60_000) * 60_000 + 1_000; + Date.now = () => clock; + let lastStatus = 200; + try { + for (let i = 0; i < 241; i++) { + lastStatus = ( + await guarded(new Request("https://openmouse.app/assets/app.js"), kv) + ).status; + } + clock += 60_000; // next minute -> a fresh window bucket + lastStatus = ( + await guarded(new Request("https://openmouse.app/assets/app.js"), kv) + ).status; + } finally { + Date.now = now; + } + assert.equal(lastStatus, 200); +}); + test("repeated abuse permanently bans the IP", async () => { const kv = new FakeKV(); let lastStatus = 200;