feat(ingest-api): ingestion hardening — fingerprints, per-key rate limits (BIT-735)
- 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
This commit is contained in:
1 parent
c6e4305c79
commit
f5f62571fd
17 files changed
+353
-36
No files matched your search
@@ -0,0 +1,7 @@
|
||||
BEGIN;
|
||||
|
||||
ALTER TABLE er_ingest_keys
|
||||
DROP COLUMN rate_limit_window_ms,
|
||||
DROP COLUMN rate_limit_max;
|
||||
|
||||
COMMIT;
|
||||
@@ -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;
|
||||
@@ -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.
|
||||
Generated
-12
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
+52
-16
@@ -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<string, unknown>; 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<FastifyInstance> {
|
||||
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<F
|
||||
|
||||
await _app.register(
|
||||
async (ingestScope: FastifyInstance) => {
|
||||
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<F
|
||||
message: { type: "string" },
|
||||
},
|
||||
},
|
||||
429: {
|
||||
type: "object",
|
||||
properties: {
|
||||
error: { type: "string" },
|
||||
message: { type: "string" },
|
||||
},
|
||||
},
|
||||
409: {
|
||||
type: "object",
|
||||
properties: {
|
||||
@@ -200,6 +220,22 @@ export async function buildApp(input: { env: IngestEnv; pool: Pool }): Promise<F
|
||||
preValidation: async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
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;
|
||||
|
||||
@@ -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",
|
||||
};
|
||||
}
|
||||
@@ -12,6 +12,7 @@ describe.skipIf(!_testUrl)("two-project passive ingest (BIT-179)", () => {
|
||||
let _app: Awaited<ReturnType<typeof buildApp>>;
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -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("<uuid>");
|
||||
});
|
||||
});
|
||||
@@ -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<string, unknown> | 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, "<uuid>");
|
||||
_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);
|
||||
}
|
||||
@@ -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";
|
||||
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -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<RowDataPacket[]>(
|
||||
`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,
|
||||
};
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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<string, _Bucket>();
|
||||
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 };
|
||||
},
|
||||
};
|
||||
}
|
||||
Vendored
+6
-1
@@ -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;
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user