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:
+2
-2
@@ -31,5 +31,5 @@ SENTRY_DSN=
|
||||
LOG_LEVEL=info
|
||||
|
||||
# Upstash Redis — rate limit on /api/* and short-TTL snapshot cache for GET /api/state
|
||||
UPSTASH_REDIS_REST_URL=
|
||||
UPSTASH_REDIS_REST_TOKEN=
|
||||
UPSTASH_REDIS_REST_URL="https://natural-baboon-144595.upstash.io"
|
||||
UPSTASH_REDIS_REST_TOKEN="gQAAAAAAAjTTAAIgcDE0MDk4MGZlOWMwN2M0NTdiOWQ5MWYxMjVhOWMyNWVlZQ"
|
||||
|
||||
@@ -348,7 +348,7 @@ Eso no indica que el bot “no funcione”: indica que el filtro económico es e
|
||||
- **Pre-commit:** Husky runs lint-staged (`eslint --fix`, `prettier --write`) on staged `*.ts` / `*.tsx` in `src/` and `web/src/`.
|
||||
- **API contracts:** Zod schemas per REST endpoint → OpenAPI via `@asteasolutions/zod-to-openapi` → Scalar UI at `/api-docs`. Request bodies validated with Zod in route handlers.
|
||||
- **Observability:** `@sentry/node` captures REST, WebSocket feed, and SSE errors; `pino` JSON logs with `correlationId` (from `x-request-id` or per book tick); OpenTelemetry spans (`ws.message` → `orderbook.process` → `arbitrage.evaluate` → `sse.broadcast`) export to Sentry via `@sentry/opentelemetry` when `SENTRY_DSN` is set. Dev probe: `GET /api/debug/sentry`; verify with `npm run test:observability`.
|
||||
- **Rate limiting & cache:** Upstash sliding-window limits per IP on read/write/SSE routes (`429` + `Retry-After`). Latest `StateSnapshot` cached in Redis (~1s TTL) for `GET /api/state` and refreshed on SSE broadcast. Set `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN`.
|
||||
- **Rate limiting & cache:** Upstash sliding-window limits per IP on read/write/SSE routes (`429` + `Retry-After`). Latest `StateSnapshot` cached in Redis (~1s TTL) for `GET /api/state` and refreshed on SSE broadcast. Set `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN`. Verify with `npm run test:rate-limit`.
|
||||
- **CI:** GitHub Actions quality pipeline (typecheck, unit tests, build); Playwright smoke on PRs — dashboard loads and SSE connects (`npm run test:e2e`, workflow `e2e.yml`, `DEMO_MODE=true` in CI).
|
||||
- **Security scanning:** CodeQL (`.github/workflows/codeql.yml`); Dependabot for npm (root + `web/`) and GitHub Actions.
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
"build": "npm --prefix web install && npm --prefix web run build",
|
||||
"typecheck": "tsc --noEmit && npm --prefix web run typecheck",
|
||||
"test": "node scripts/run-tests.mjs",
|
||||
"test:rate-limit": "node --import tsx --test src/interfaces/http/rate-limit.test.ts",
|
||||
"test:e2e": "playwright test",
|
||||
"test:observability": "playwright test observability.spec.ts",
|
||||
"lint": "eslint .",
|
||||
|
||||
@@ -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");
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user