test(m3): add Upstash read-tier rate limit HTTP test

Node test asserts 429 with Retry-After after 60 GET requests per IP.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Mauricio Barragan
2026-06-17 21:35:11 -06:00
parent 8c7127cfde
commit f6e8381c20
5 changed files with 99 additions and 3 deletions
+60
View File
@@ -0,0 +1,60 @@
import assert from "node:assert/strict";
import { randomUUID } from "node:crypto";
import type { AddressInfo } from "node:net";
import { test } from "node:test";
import express, { Router } from "express";
import { isUpstashConfigured } from "../../infrastructure/cache/upstash.js";
import { loadEnvLocal } from "../../test-support/load-env-local.js";
import { createRateLimitMiddleware } from "./rate-limit.js";
loadEnvLocal();
const READ_LIMIT_PER_MIN = 60;
test(
"read tier returns 429 with Retry-After after limit",
{ skip: !isUpstashConfigured() },
async () => {
const app = express();
const router = Router();
router.use(createRateLimitMiddleware());
router.get("/state", (_req, res) => {
res.json({ success: true, data: { ok: true } });
});
app.use("/api", router);
const server = await new Promise<ReturnType<typeof app.listen>>(
(resolve) => {
const s = app.listen(0, "127.0.0.1", () => resolve(s));
},
);
const port = (server.address() as AddressInfo).port;
const url = `http://127.0.0.1:${port}/api/state`;
const clientIp = `rate-limit-qa-${randomUUID()}`;
try {
for (let i = 0; i < READ_LIMIT_PER_MIN; i++) {
const res = await fetch(url, {
headers: { "x-forwarded-for": clientIp },
});
assert.equal(res.status, 200, `request ${i + 1} should pass`);
}
const blocked = await fetch(url, {
headers: { "x-forwarded-for": clientIp },
});
assert.equal(blocked.status, 429);
assert.ok(blocked.headers.get("retry-after"));
const body = (await blocked.json()) as { error?: string };
assert.equal(body.error, "Too many requests");
} finally {
await new Promise<void>((resolve, reject) => {
server.close((err) => (err ? reject(err) : resolve()));
});
}
},
);
test("reports whether Upstash REST credentials are set", () => {
assert.equal(typeof isUpstashConfigured(), "boolean");
});
+35
View File
@@ -0,0 +1,35 @@
import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
/** Loads `.env.local` without overriding variables already set in the shell. */
export function loadEnvLocal(): void {
const file = join(process.cwd(), ".env.local");
if (!existsSync(file)) {
return;
}
for (const line of readFileSync(file, "utf8").split(/\r?\n/)) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith("#")) {
continue;
}
const eq = trimmed.indexOf("=");
if (eq <= 0) {
continue;
}
const key = trimmed.slice(0, eq).trim();
let value = trimmed.slice(eq + 1).trim();
if (
(value.startsWith('"') && value.endsWith('"')) ||
(value.startsWith("'") && value.endsWith("'"))
) {
value = value.slice(1, -1);
}
if (process.env[key] === undefined) {
process.env[key] = value;
}
}
}