From f5f62571fd55c2d7690c95ff51751a483cb15435 Mon Sep 17 00:00:00 2001 From: Peter Spark Date: Thu, 2 Apr 2026 19:45:27 +0000 Subject: [PATCH] =?UTF-8?q?feat(ingest-api):=20ingestion=20hardening=20?= =?UTF-8?q?=E2=80=94=20fingerprints,=20per-key=20rate=20limits=20(BIT-735)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Migration: er_ingest_keys.rate_limit_max and rate_limit_window_ms (nullable overrides). - Fingerprint policy v2: server-side digest includes normalized stacktrace (UUID/hex/line noise). - In-memory fixed-window limits: per API key after auth; per-IP for unauthenticated POSTs (INGEST_ANON_IP_*). Removed @fastify/rate-limit dependency. - OpenAPI documents 429; runbook at docs/operations/ingest-hardening-runbook.md. Paperclip-Agent: 0b1fcf92-5fe3-4ac0-9f29-df4ab72f5376 Paperclip-Issue: BIT-735 Paperclip-Run: 0a91be22-6f8f-4c60-b889-44b99048d3a2 Made-with: Cursor --- ...0402140000_ingest_key_rate_limits.down.sql | 7 ++ ...260402140000_ingest_key_rate_limits.up.sql | 17 ++++ docs/operations/ingest-hardening-runbook.md | 47 +++++++++++ ingest-api/package-lock.json | 12 --- ingest-api/package.json | 1 - ingest-api/src/buildApp.ts | 68 ++++++++++++---- ingest-api/src/config/env.ts | 4 + .../src/integration.twoProjects.test.ts | 80 +++++++++++++++++++ ingest-api/src/lib/fingerprintPolicy.test.ts | 14 ++++ ingest-api/src/lib/fingerprintPolicy.ts | 30 ++++++- ingest-api/src/lib/noisePolicy.ts | 1 + ingest-api/src/lib/normalize.test.ts | 26 ++++++ ingest-api/src/lib/normalize.ts | 8 ++ ingest-api/src/services/ingestAuth.ts | 18 ++++- .../src/services/ingestRateLimit.test.ts | 15 ++++ ingest-api/src/services/ingestRateLimit.ts | 34 ++++++++ ingest-api/src/types/fastify.d.ts | 7 +- 17 files changed, 353 insertions(+), 36 deletions(-) create mode 100644 database/error_reporting/migrations/20260402140000_ingest_key_rate_limits.down.sql create mode 100644 database/error_reporting/migrations/20260402140000_ingest_key_rate_limits.up.sql create mode 100644 docs/operations/ingest-hardening-runbook.md create mode 100644 ingest-api/src/services/ingestRateLimit.test.ts create mode 100644 ingest-api/src/services/ingestRateLimit.ts diff --git a/database/error_reporting/migrations/20260402140000_ingest_key_rate_limits.down.sql b/database/error_reporting/migrations/20260402140000_ingest_key_rate_limits.down.sql new file mode 100644 index 0000000..c26d50a --- /dev/null +++ b/database/error_reporting/migrations/20260402140000_ingest_key_rate_limits.down.sql @@ -0,0 +1,7 @@ +BEGIN; + +ALTER TABLE er_ingest_keys + DROP COLUMN rate_limit_window_ms, + DROP COLUMN rate_limit_max; + +COMMIT; diff --git a/database/error_reporting/migrations/20260402140000_ingest_key_rate_limits.up.sql b/database/error_reporting/migrations/20260402140000_ingest_key_rate_limits.up.sql new file mode 100644 index 0000000..0b1c2e4 --- /dev/null +++ b/database/error_reporting/migrations/20260402140000_ingest_key_rate_limits.up.sql @@ -0,0 +1,17 @@ +BEGIN; + +ALTER TABLE er_ingest_keys + ADD COLUMN rate_limit_max INT NULL + COMMENT 'Max ingest requests per window for this key; NULL inherits INGEST_RATE_LIMIT_MAX' + AFTER revoked_at, + ADD COLUMN rate_limit_window_ms INT NULL + COMMENT 'Rate limit window in ms; NULL inherits INGEST_RATE_LIMIT_WINDOW_MS' + AFTER rate_limit_max; + +ALTER TABLE er_ingest_keys + ADD CONSTRAINT er_ingest_keys_rate_limit_max_chk + CHECK (rate_limit_max IS NULL OR rate_limit_max > 0), + ADD CONSTRAINT er_ingest_keys_rate_limit_window_ms_chk + CHECK (rate_limit_window_ms IS NULL OR rate_limit_window_ms > 0); + +COMMIT; diff --git a/docs/operations/ingest-hardening-runbook.md b/docs/operations/ingest-hardening-runbook.md new file mode 100644 index 0000000..a9fa713 --- /dev/null +++ b/docs/operations/ingest-hardening-runbook.md @@ -0,0 +1,47 @@ +# Ingest hardening — validation runbook (BIT-735) + +Use this after deploying ingest API or changing fingerprint / noise / rate-limit behaviour. + +## Prerequisites + +- Apply DB migrations through `20260402140000_ingest_key_rate_limits` so `er_ingest_keys` exposes `rate_limit_max` and `rate_limit_window_ms`. +- Ingest keys are created in MariaDB (`er_ingest_keys`); clients send the raw token via `Authorization: Bearer` or `X-Api-Key` (never a shared WDMI env secret on the wire). + +## Environment + +| Variable | Role | +|----------|------| +| `INGEST_RATE_LIMIT_MAX` / `INGEST_RATE_LIMIT_WINDOW_MS` | Default per-key budget when DB columns are NULL | +| `INGEST_ANON_IP_MAX` / `INGEST_ANON_IP_WINDOW_MS` | Budget for `POST /v1/ingest/events` **without** credentials (abuse of 401 path) | + +Per-key overrides: set `rate_limit_max` and/or `rate_limit_window_ms` on the key row; NULL means inherit the corresponding env default. + +## Fingerprint quality + +- Server-side fingerprint policy version is returned on each ingest response as `fingerprint_policy_version`. +- When the client omits `fingerprint`, the hub hashes: normalized first line of `message`, `context` location (`file_path` / `stack_info`), project slug/name hints, and a digest of a **normalized** `stacktrace` (volatile tokens such as UUIDs and `0x…` addresses collapsed). +- **Check:** send the same logical error twice from different hosts; incident count should stay stable (one fingerprint) if `stacktrace` and `context` align. +- **Check:** change only a UUID inside the stack; fingerprint should remain stable. + +## Noise filter coverage + +- Rules live in `ingest-api/src/lib/noisePolicy.ts`; ruleset id: `noise_ruleset_version` in the ingest response. +- **Check:** send a known-noise payload (for example ResizeObserver message at non-fatal level); expect `skipped: true`, `noise_filtered_count` incremented, and no new `er_incidents` row. +- **Check:** send the same pattern at `fatal` / `critical` level; expect **not** skipped (noise rules do not hide critical). + +## Rate limits + +- Authenticated traffic: `429` + `Retry-After` when the per-key window is exhausted (DB limits or env defaults). +- Unauthenticated traffic: same for the client IP after `INGEST_ANON_*` budget. +- **Check:** `curl` three rapid unauthenticated posts; third should be `429` if `INGEST_ANON_IP_MAX=2`. +- **Check:** lower `rate_limit_max` on a test key to `2` and confirm the third authenticated request returns `429`. + +## Automated tests + +From `ingest-api/`: + +```bash +npm test +``` + +Integration tests need `ERROR_REPORTING_TEST_DATABASE_URL` and an applied schema including rate-limit columns. diff --git a/ingest-api/package-lock.json b/ingest-api/package-lock.json index 2084af5..bc5954f 100644 --- a/ingest-api/package-lock.json +++ b/ingest-api/package-lock.json @@ -8,7 +8,6 @@ "name": "@bitreport/error-reporting-ingest-api", "version": "0.1.0", "dependencies": { - "@fastify/rate-limit": "^9.1.0", "@fastify/swagger": "^8.15.0", "@fastify/swagger-ui": "^3.1.0", "dotenv": "^16.4.5", @@ -512,17 +511,6 @@ "fast-deep-equal": "^3.1.3" } }, - "node_modules/@fastify/rate-limit": { - "version": "9.1.0", - "resolved": "https://registry.npmjs.org/@fastify/rate-limit/-/rate-limit-9.1.0.tgz", - "integrity": "sha512-h5dZWCkuZXN0PxwqaFQLxeln8/LNwQwH9popywmDCFdKfgpi4b/HoMH1lluy6P+30CG9yzzpSpwTCIPNB9T1JA==", - "license": "MIT", - "dependencies": { - "@lukeed/ms": "^2.0.1", - "fastify-plugin": "^4.0.0", - "toad-cache": "^3.3.1" - } - }, "node_modules/@fastify/send": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/@fastify/send/-/send-2.1.0.tgz", diff --git a/ingest-api/package.json b/ingest-api/package.json index a615c8a..0807ab2 100644 --- a/ingest-api/package.json +++ b/ingest-api/package.json @@ -13,7 +13,6 @@ "test:watch": "vitest" }, "dependencies": { - "@fastify/rate-limit": "^9.1.0", "@fastify/swagger": "^8.15.0", "@fastify/swagger-ui": "^3.1.0", "dotenv": "^16.4.5", diff --git a/ingest-api/src/buildApp.ts b/ingest-api/src/buildApp.ts index 7fd8777..d647bb9 100644 --- a/ingest-api/src/buildApp.ts +++ b/ingest-api/src/buildApp.ts @@ -3,11 +3,10 @@ import fastify from "fastify"; import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify"; import swagger from "@fastify/swagger"; import swaggerUi from "@fastify/swagger-ui"; -import rateLimit from "@fastify/rate-limit"; import type { Pool } from "mysql2/promise"; import type { IngestEnv } from "./config/env.js"; -import { sha256Hex } from "./lib/hash.js"; import { attachIngestAuth } from "./services/ingestAuth.js"; +import { createIngestRateLimiter } from "./services/ingestRateLimit.js"; import { computeRequestBodyHash, processIngestBatch, @@ -71,19 +70,13 @@ const _ingestResultSkippedSchema = { }, } as const; -function _rateLimitKey(request: { headers: Record; ip: string }): string { - const _auth = request.headers.authorization; - const _ak = request.headers["x-api-key"]; - if (typeof _auth === "string" && _auth.trim() !== "") { - return `hdr:${sha256Hex(_auth)}`; - } - if (typeof _ak === "string" && _ak.trim() !== "") { - return `hdr:${sha256Hex(`x-api-key:${_ak}`)}`; - } - return `ip:${request.ip}`; +function _ingestEventsPostPath(url: string): boolean { + const _path = url.split("?", 1)[0] ?? url; + return _path === "/v1/ingest/events" || _path.endsWith("/v1/ingest/events"); } export async function buildApp(input: { env: IngestEnv; pool: Pool }): Promise { + const _ingestLimiter = createIngestRateLimiter(); const _app = fastify({ logger: true, requestIdHeader: "x-request-id", @@ -141,10 +134,30 @@ export async function buildApp(input: { env: IngestEnv; pool: Pool }): Promise { - await ingestScope.register(rateLimit, { - max: input.env.INGEST_RATE_LIMIT_MAX, - timeWindow: input.env.INGEST_RATE_LIMIT_WINDOW_MS, - keyGenerator: _rateLimitKey, + ingestScope.addHook("onRequest", async (request: FastifyRequest, reply: FastifyReply) => { + if (request.method !== "POST" || !_ingestEventsPostPath(request.url)) { + return; + } + const _auth = request.headers.authorization; + const _ak = request.headers["x-api-key"]; + const _hasCred = + (typeof _auth === "string" && _auth.trim() !== "") || + (typeof _ak === "string" && _ak.trim() !== ""); + if (_hasCred) { + return; + } + const _r = _ingestLimiter.tryConsume( + `anon_ip:${request.ip}`, + input.env.INGEST_ANON_IP_MAX, + input.env.INGEST_ANON_IP_WINDOW_MS, + ); + if (!_r.ok) { + reply.header("retry-after", String(_r.retryAfterSec)); + return reply.status(429).send({ + error: "rate_limited", + message: "Too many unauthenticated ingest attempts from this address.", + }); + } }); ingestScope.post("/events", { @@ -181,6 +194,13 @@ export async function buildApp(input: { env: IngestEnv; pool: Pool }): Promise { await attachIngestAuth(input.pool, request, reply); }, + preHandler: async (request: FastifyRequest, reply: FastifyReply) => { + const _a = request.ingestAuth; + if (!_a) { + return; + } + const _max = _a.rateLimitMax ?? input.env.INGEST_RATE_LIMIT_MAX; + const _win = _a.rateLimitWindowMs ?? input.env.INGEST_RATE_LIMIT_WINDOW_MS; + const _r = _ingestLimiter.tryConsume(`ingest_key:${_a.keyId}`, _max, _win); + if (!_r.ok) { + reply.header("retry-after", String(_r.retryAfterSec)); + return reply.status(429).send({ + error: "rate_limited", + message: "Ingest rate limit exceeded for this API key; retry after the Retry-After interval.", + }); + } + }, handler: async (request: FastifyRequest, reply: FastifyReply) => { if (!request.ingestAuth) { return; diff --git a/ingest-api/src/config/env.ts b/ingest-api/src/config/env.ts index f0ac49a..36530e6 100644 --- a/ingest-api/src/config/env.ts +++ b/ingest-api/src/config/env.ts @@ -5,6 +5,8 @@ export type IngestEnv = { DATABASE_URL: string; INGEST_RATE_LIMIT_MAX: number; INGEST_RATE_LIMIT_WINDOW_MS: number; + INGEST_ANON_IP_MAX: number; + INGEST_ANON_IP_WINDOW_MS: number; NODE_ENV: string; }; @@ -29,6 +31,8 @@ export function loadEnv(): IngestEnv { DATABASE_URL: _databaseUrl.trim(), INGEST_RATE_LIMIT_MAX: _parseIntWithDefault(process.env.INGEST_RATE_LIMIT_MAX, 300), INGEST_RATE_LIMIT_WINDOW_MS: _parseIntWithDefault(process.env.INGEST_RATE_LIMIT_WINDOW_MS, 60_000), + INGEST_ANON_IP_MAX: _parseIntWithDefault(process.env.INGEST_ANON_IP_MAX, 120), + INGEST_ANON_IP_WINDOW_MS: _parseIntWithDefault(process.env.INGEST_ANON_IP_WINDOW_MS, 60_000), NODE_ENV: process.env.NODE_ENV ?? "development", }; } diff --git a/ingest-api/src/integration.twoProjects.test.ts b/ingest-api/src/integration.twoProjects.test.ts index f2651f9..22860bd 100644 --- a/ingest-api/src/integration.twoProjects.test.ts +++ b/ingest-api/src/integration.twoProjects.test.ts @@ -12,6 +12,7 @@ describe.skipIf(!_testUrl)("two-project passive ingest (BIT-179)", () => { let _app: Awaited>; const _tokenA = "er_tst_a_secret_one"; const _tokenB = "er_tst_b_secret_two"; + const _tokenC = "er_tst_c_rate_limited_key"; let _projectIdA = ""; let _projectIdB = ""; @@ -49,11 +50,18 @@ describe.skipIf(!_testUrl)("two-project passive ingest (BIT-179)", () => { VALUES (?, 'default', 'tok_pr_b', ?, 'active')`, [_projectIdB, sha256Hex(_tokenB)], ); + await _pool.execute( + `INSERT INTO er_ingest_keys (project_id, label, token_prefix, token_hash, status, rate_limit_max, rate_limit_window_ms) + VALUES (?, 'ratelimit', 'tok_rl_c', ?, 'active', 2, 60000)`, + [_projectIdA, sha256Hex(_tokenC)], + ); const _env: IngestEnv = { PORT: 0, DATABASE_URL: _testUrl!, INGEST_RATE_LIMIT_MAX: 10_000, INGEST_RATE_LIMIT_WINDOW_MS: 60_000, + INGEST_ANON_IP_MAX: 10_000, + INGEST_ANON_IP_WINDOW_MS: 60_000, NODE_ENV: "test", }; _app = await buildApp({ env: _env, pool: _pool }); @@ -237,4 +245,76 @@ describe.skipIf(!_testUrl)("two-project passive ingest (BIT-179)", () => { }); expect(_r2.statusCode).toBe(409); }); + + it("returns 429 when per-key ingest limit is exceeded (er_ingest_keys rate columns)", async () => { + const _payload = (fp: string) => ({ + events: [ + { + schema_version: 1, + occurred_at: "2026-03-22T13:00:00.000Z", + level: "error", + message: "rate limit probe", + fingerprint: fp, + }, + ], + }); + const _h = { authorization: `Bearer ${_tokenC}` }; + const _r1 = await _app.inject({ + method: "POST", + url: "/v1/ingest/events", + headers: _h, + payload: _payload("fp-rl-1"), + }); + const _r2 = await _app.inject({ + method: "POST", + url: "/v1/ingest/events", + headers: _h, + payload: _payload("fp-rl-2"), + }); + const _r3 = await _app.inject({ + method: "POST", + url: "/v1/ingest/events", + headers: _h, + payload: _payload("fp-rl-3"), + }); + expect(_r1.statusCode).toBe(200); + expect(_r2.statusCode).toBe(200); + expect(_r3.statusCode).toBe(429); + const _j = JSON.parse(_r3.body) as { error?: string }; + expect(_j.error).toBe("rate_limited"); + }); + + it("returns 429 for anonymous callers after the IP budget (INGEST_ANON_*)", async () => { + const _env: IngestEnv = { + PORT: 0, + DATABASE_URL: _testUrl!, + INGEST_RATE_LIMIT_MAX: 10_000, + INGEST_RATE_LIMIT_WINDOW_MS: 60_000, + INGEST_ANON_IP_MAX: 2, + INGEST_ANON_IP_WINDOW_MS: 60_000, + NODE_ENV: "test", + }; + const _anonApp = await buildApp({ env: _env, pool: _pool }); + await _anonApp.ready(); + const _payload = { + events: [ + { + schema_version: 1, + occurred_at: "2026-03-22T14:00:00.000Z", + level: "error", + message: "no auth", + fingerprint: "fp-anon", + }, + ], + }; + expect((await _anonApp.inject({ method: "POST", url: "/v1/ingest/events", payload: _payload })).statusCode).toBe( + 401, + ); + expect((await _anonApp.inject({ method: "POST", url: "/v1/ingest/events", payload: _payload })).statusCode).toBe( + 401, + ); + const _third = await _anonApp.inject({ method: "POST", url: "/v1/ingest/events", payload: _payload }); + expect(_third.statusCode).toBe(429); + await _anonApp.close(); + }); }); diff --git a/ingest-api/src/lib/fingerprintPolicy.test.ts b/ingest-api/src/lib/fingerprintPolicy.test.ts index 6deeef0..a1da4b6 100644 --- a/ingest-api/src/lib/fingerprintPolicy.test.ts +++ b/ingest-api/src/lib/fingerprintPolicy.test.ts @@ -4,6 +4,7 @@ import { extractLocationFromContext, extractProjectStableKey, normalizeMessageForFingerprint, + normalizeStacktraceForFingerprint, } from "./fingerprintPolicy.js"; describe("normalizeMessageForFingerprint", () => { @@ -46,14 +47,27 @@ describe("computeFingerprintFromBasis", () => { normalizedMessage: "m", filePath: "/f", lineNumber: 3, + stackDigest: "", }); const _b = computeFingerprintFromBasis({ projectStableKey: "p", normalizedMessage: "m", filePath: "/f", lineNumber: 3, + stackDigest: "", }); expect(_a).toBe(_b); expect(_a).toMatch(/^[a-f0-9]{64}$/); }); }); + +describe("normalizeStacktraceForFingerprint", () => { + it("strips volatile hex addresses and UUIDs", () => { + const _raw = + "Error: boom\n at x (/app/a.js:0x7fffdeadbeef:12)\n trace id f47ac10b-58cc-4372-a567-0e02b2c3d479"; + const _n = normalizeStacktraceForFingerprint(_raw); + expect(_n).not.toContain("deadbeef"); + expect(_n).not.toContain("f47ac10b-58cc"); + expect(_n).toContain(""); + }); +}); diff --git a/ingest-api/src/lib/fingerprintPolicy.ts b/ingest-api/src/lib/fingerprintPolicy.ts index 445ebc9..d655bfc 100644 --- a/ingest-api/src/lib/fingerprintPolicy.ts +++ b/ingest-api/src/lib/fingerprintPolicy.ts @@ -1,7 +1,7 @@ import { sha256Hex } from "./hash.js"; /** Bumped when fingerprint basis algorithm changes (dedup / parity). */ -export const FINGERPRINT_POLICY_VERSION = 1; +export const FINGERPRINT_POLICY_VERSION = 2; /** * Normalize message text for stable dedup (CRM-style: trim, collapse whitespace, NFKC). @@ -71,17 +71,39 @@ export function extractProjectStableKey(context: Record | null return _asTrimmedString(context.project_name) || _asTrimmedString(context.project); } +/** Any 8-4-4-4-12 hex segment shape (not strict RFC variant; good enough for noise stripping). */ +const _UUID_RE = /\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi; + +/** + * Normalize stack text so identical logical stacks hash the same across machines + * (addresses, UUIDs, temp paths damped). Used only for server-side fingerprints. + */ +export function normalizeStacktraceForFingerprint(stack: string): string { + const _lines = stack.replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n"); + const _maxLines = 28; + const _trimmed = _lines.slice(0, _maxLines).map((ln) => ln.trim()); + let _joined = _trimmed.join("\n"); + _joined = _joined.replace(/0x[0-9a-f]{4,}/gi, "0x_"); + _joined = _joined.replace(/\b0x[0-9a-f]+\b/gi, "0x_"); + _joined = _joined.replace(_UUID_RE, ""); + _joined = _joined.replace(/:\d{1,5}\b/g, ":_"); + return _joined; +} + /** * Hub fingerprint when the client does not send one: CRM capture parity - * (`project|message|file|line`) then SHA-256 hex (64 chars). `project_id` is - * already scoped per row — this key matches cross-reporter CRM strings. + * (`project|message|file|line|stackDigest`) then SHA-256 hex (64 chars). + * `stackDigest` is sha256 of {@link normalizeStacktraceForFingerprint} or empty + * when no stack was sent. */ export function computeFingerprintFromBasis(input: { projectStableKey: string; normalizedMessage: string; filePath: string; lineNumber: number; + stackDigest: string; }): string { - const _basis = `${input.projectStableKey}|${input.normalizedMessage}|${input.filePath}|${input.lineNumber}`; + const _sd = input.stackDigest.trim() === "" ? "-" : input.stackDigest.trim(); + const _basis = `${input.projectStableKey}|${input.normalizedMessage}|${input.filePath}|${input.lineNumber}|${_sd}`; return sha256Hex(_basis); } diff --git a/ingest-api/src/lib/noisePolicy.ts b/ingest-api/src/lib/noisePolicy.ts index 0e7884c..7b95788 100644 --- a/ingest-api/src/lib/noisePolicy.ts +++ b/ingest-api/src/lib/noisePolicy.ts @@ -2,6 +2,7 @@ import { normalizeLevelToSeverity } from "./normalize.js"; /** * Versioned ruleset id (document in release notes when rules change). + * Rule inventory and validation steps: `docs/operations/ingest-hardening-runbook.md`. */ export const NOISE_RULESET_VERSION = "1.0.0"; diff --git a/ingest-api/src/lib/normalize.test.ts b/ingest-api/src/lib/normalize.test.ts index a16a94a..7271727 100644 --- a/ingest-api/src/lib/normalize.test.ts +++ b/ingest-api/src/lib/normalize.test.ts @@ -34,6 +34,32 @@ describe("computeFingerprint", () => { expect(_a).toMatch(/^[a-f0-9]{64}$/); }); + it("stable fingerprint when only stack UUIDs / addresses differ", () => { + const _ctx = { file_path: "x.php", line_number: 1 }; + const _stackA = + "Error: boom\n at x (/app/module.js:10:1) ref f47ac10b-58cc-4372-a567-0e02b2c3d479 ptr 0x7fffabcdef01"; + const _stackB = + "Error: boom\n at x (/app/module.js:10:1) ref 11111111-1111-1111-1111-111111111111 ptr 0x00000002"; + const _fpA = computeFingerprint({ message: "same", context: _ctx, stacktrace: _stackA }); + const _fpB = computeFingerprint({ message: "same", context: _ctx, stacktrace: _stackB }); + expect(_fpA).toBe(_fpB); + }); + + it("differs when stack shape differs", () => { + const _ctx = { file_path: "x.php", line_number: 1 }; + const _fp1 = computeFingerprint({ + message: "same", + context: _ctx, + stacktrace: "at a (file.js:1:1)", + }); + const _fp2 = computeFingerprint({ + message: "same", + context: _ctx, + stacktrace: "at b (other.js:9:1)", + }); + expect(_fp1).not.toBe(_fp2); + }); + it("collapses whitespace in message for fingerprint", () => { const _ctx = { file_path: "x", line_number: 0 }; expect(computeFingerprint({ message: "a b", context: _ctx })).toBe( diff --git a/ingest-api/src/lib/normalize.ts b/ingest-api/src/lib/normalize.ts index dd5df3c..b986223 100644 --- a/ingest-api/src/lib/normalize.ts +++ b/ingest-api/src/lib/normalize.ts @@ -3,7 +3,9 @@ import { extractLocationFromContext, extractProjectStableKey, normalizeMessageForFingerprint, + normalizeStacktraceForFingerprint, } from "./fingerprintPolicy.js"; +import { sha256Hex } from "./hash.js"; export function normalizeLevelToSeverity(level: string): string { const _l = level.trim().toLowerCase(); @@ -41,11 +43,17 @@ export function computeFingerprint(input: { const _loc = extractLocationFromContext(_ctx); const _proj = extractProjectStableKey(_ctx); const _normMsg = normalizeMessageForFingerprint(input.message); + const _stackRaw = + typeof input.stacktrace === "string" && input.stacktrace.trim() !== "" + ? normalizeStacktraceForFingerprint(input.stacktrace) + : ""; + const _stackDigest = _stackRaw === "" ? "" : sha256Hex(_stackRaw); return computeFingerprintFromBasis({ projectStableKey: _proj, normalizedMessage: _normMsg, filePath: _loc.filePath, lineNumber: _loc.lineNumber, + stackDigest: _stackDigest, }); } diff --git a/ingest-api/src/services/ingestAuth.ts b/ingest-api/src/services/ingestAuth.ts index 8365b66..055f347 100644 --- a/ingest-api/src/services/ingestAuth.ts +++ b/ingest-api/src/services/ingestAuth.ts @@ -6,6 +6,8 @@ import { sha256Hex } from "../lib/hash.js"; export type IngestAuthContext = { keyId: string; projectId: string; + rateLimitMax: number | null; + rateLimitWindowMs: number | null; }; function _extractBearerToken(header: string | undefined): string | null { @@ -37,7 +39,10 @@ export async function attachIngestAuth( } const _hash = sha256Hex(_token); const [rows] = await pool.execute( - `SELECT CAST(id AS CHAR) AS id, CAST(project_id AS CHAR) AS project_id + `SELECT CAST(id AS CHAR) AS id, + CAST(project_id AS CHAR) AS project_id, + rate_limit_max, + rate_limit_window_ms FROM er_ingest_keys WHERE token_hash = ? AND status = 'active' @@ -52,7 +57,12 @@ export async function attachIngestAuth( }); return; } - const _row = rows[0] as { id: string; project_id: string }; + const _row = rows[0] as { + id: string; + project_id: string; + rate_limit_max: unknown; + rate_limit_window_ms: unknown; + }; if (!_row) { await reply.status(401).send({ error: "unauthorized", @@ -60,8 +70,12 @@ export async function attachIngestAuth( }); return; } + const _rlMaxNum = _row.rate_limit_max != null ? Number(_row.rate_limit_max) : NaN; + const _rlWinNum = _row.rate_limit_window_ms != null ? Number(_row.rate_limit_window_ms) : NaN; request.ingestAuth = { keyId: _row.id, projectId: _row.project_id, + rateLimitMax: Number.isFinite(_rlMaxNum) && _rlMaxNum > 0 ? _rlMaxNum : null, + rateLimitWindowMs: Number.isFinite(_rlWinNum) && _rlWinNum > 0 ? _rlWinNum : null, }; } diff --git a/ingest-api/src/services/ingestRateLimit.test.ts b/ingest-api/src/services/ingestRateLimit.test.ts new file mode 100644 index 0000000..5c85991 --- /dev/null +++ b/ingest-api/src/services/ingestRateLimit.test.ts @@ -0,0 +1,15 @@ +import { describe, expect, it } from "vitest"; +import { createIngestRateLimiter } from "./ingestRateLimit.js"; + +describe("createIngestRateLimiter", () => { + it("allows up to max requests per window", () => { + const _lim = createIngestRateLimiter(); + expect(_lim.tryConsume("k1", 2, 60_000).ok).toBe(true); + expect(_lim.tryConsume("k1", 2, 60_000).ok).toBe(true); + const _ex = _lim.tryConsume("k1", 2, 60_000); + expect(_ex.ok).toBe(false); + if (!_ex.ok) { + expect(_ex.retryAfterSec).toBeGreaterThan(0); + } + }); +}); diff --git a/ingest-api/src/services/ingestRateLimit.ts b/ingest-api/src/services/ingestRateLimit.ts new file mode 100644 index 0000000..3fddc10 --- /dev/null +++ b/ingest-api/src/services/ingestRateLimit.ts @@ -0,0 +1,34 @@ +type _Bucket = { windowStartMs: number; count: number }; + +/** + * Fixed-window counter (aligned to first request in window), in-memory only. + */ +export function createIngestRateLimiter() { + const _buckets = new Map(); + return { + tryConsume( + key: string, + max: number, + windowMs: number, + ): { ok: true } | { ok: false; retryAfterSec: number } { + if (!Number.isFinite(max) || max <= 0 || !Number.isFinite(windowMs) || windowMs <= 0) { + return { ok: true }; + } + const _now = Date.now(); + let _b = _buckets.get(key); + if (!_b || _now - _b.windowStartMs >= windowMs) { + _b = { windowStartMs: _now, count: 0 }; + _buckets.set(key, _b); + } + if (_b.count >= max) { + const _msLeft = windowMs - (_now - _b.windowStartMs); + return { + ok: false, + retryAfterSec: Math.max(1, Math.ceil(_msLeft / 1000)), + }; + } + _b.count += 1; + return { ok: true }; + }, + }; +} diff --git a/ingest-api/src/types/fastify.d.ts b/ingest-api/src/types/fastify.d.ts index 71e079b..63e828a 100644 --- a/ingest-api/src/types/fastify.d.ts +++ b/ingest-api/src/types/fastify.d.ts @@ -2,6 +2,11 @@ import "fastify"; declare module "fastify" { interface FastifyRequest { - ingestAuth?: { keyId: string; projectId: string }; + ingestAuth?: { + keyId: string; + projectId: string; + rateLimitMax: number | null; + rateLimitWindowMs: number | null; + }; } } -- 2.47.3