Files
heidi/lib/domain/limits.test.ts

170 lines
7.5 KiB
TypeScript

import { test } from "node:test";
import assert from "node:assert/strict";
import { callerKey, chat, dialectCheck, modelCheck, tooMany } from "./limits.ts";
/**
* Every public endpoint ran with NO limit until this existed. Two of them
* spend money on every call and both are reachable with curl, so these assert
* the shape of the protection rather than trusting that it is wired.
*/
function req(ip = "203.0.113.7"): Request {
return new Request("https://heidi.orangecat.ch/api/chat", {
method: "POST",
headers: { "x-forwarded-for": ip },
});
}
test("the probe is much tighter than the chat", () => {
// It makes a real outbound call with whatever key it is handed, which makes
// it the one endpoint that could test stolen credentials in bulk.
assert.ok(modelCheck.memory.peek("a").limit < chat.memory.peek("a").limit);
});
test("a conversation of ordinary length is never refused", () => {
// A dozen turns is a normal session; meeting the ceiling while working
// through one WhatsApp thread would make the limit the product's problem.
const limiter = chat.memory;
const key = `ordinary:${Math.random()}`;
for (let i = 0; i < 12; i++) {
assert.equal(limiter.check(key).allowed, true, `turn ${i + 1} was refused`);
}
});
test("the probe refuses a burst and says how long to wait", () => {
const key = `burst:${Math.random()}`;
let last = modelCheck.memory.check(key);
for (let i = 0; i < 20; i++) last = modelCheck.memory.check(key);
assert.equal(last.allowed, false);
assert.equal(last.remaining, 0);
// Never fabricated — derived from the oldest counted hit.
assert.ok(last.retryAfterSeconds > 0);
});
test("one caller's burst does not refuse another caller", () => {
const mine = `iso-a:${Math.random()}`;
const theirs = `iso-b:${Math.random()}`;
for (let i = 0; i < 20; i++) modelCheck.memory.check(mine);
assert.equal(modelCheck.memory.check(theirs).allowed, true);
});
test("callers are told apart by address, and endpoints keep separate budgets", () => {
assert.notEqual(callerKey(req("198.51.100.1"), "chat"), callerKey(req("203.0.113.9"), "chat"));
// Spending the chat allowance must not lock someone out of the dialect check.
assert.notEqual(callerKey(req(), "chat"), callerKey(req(), "dialect-check"));
});
test("a caller behind a proxy with no forwarded header still gets a key", () => {
const bare = new Request("https://heidi.orangecat.ch/api/chat", { method: "POST" });
assert.ok(callerKey(bare, "chat").length > "chat:".length);
});
test("a refusal answers 429 with the headers a client already reads", async () => {
const key = `headers:${Math.random()}`;
let last = modelCheck.memory.check(key);
for (let i = 0; i < 20; i++) last = modelCheck.memory.check(key);
const res = tooMany(last);
assert.equal(res.status, 429);
assert.ok(res.headers.get("retry-after"), "no Retry-After");
assert.ok(res.headers.get("x-ratelimit-limit"), "no X-RateLimit-Limit");
// The message is the client's to localise; the body must not leak internals.
const body = await res.json();
assert.equal(body.operator, false);
});
test("the dialect check is the most generous, being free to run", () => {
assert.ok(dialectCheck.memory.peek("a").limit > chat.memory.peek("a").limit);
});
/**
* WHO COUNTS WHERE (`allow`). The anonymous half needs nothing; the signed-in
* half needs a database, like the route tests.
*/
import { describe, before, mock } from "node:test";
import { allow, actorKey, speak } from "./limits.ts";
import { ACTIVE_COURSE } from "../course/registry.ts";
import { dbConfigured } from "../db/index.ts";
test("an anonymous caller is counted in memory, by address, and one address does not spend another's", async () => {
const a = `198.51.100.${Math.floor(Math.random() * 200)}`;
const first = await allow(modelCheck, req(a), "t-anon");
assert.equal(first.allowed, true);
// `peek` answers for the NEXT hit: one fewer than the hit just counted left.
assert.equal(modelCheck.memory.peek(callerKey(req(a), "t-anon")).remaining, first.remaining - 1, "it is the in-memory window that counted");
for (let i = 0; i < 10; i++) await allow(modelCheck, req(a), "t-anon");
assert.equal((await allow(modelCheck, req(a), "t-anon")).allowed, false);
assert.equal((await allow(modelCheck, req("203.0.113.250"), "t-anon")).allowed, true);
});
test("a signed-in caller's key names the purpose, the course and the account", () => {
assert.equal(actorKey("alice", "chat"), `chat:${ACTIVE_COURSE.id}:alice`);
});
describe("a signed-in caller", { skip: dbConfigured() ? false : "DATABASE_URL unset" }, () => {
let signedInAs: string | null = null;
let sessionReads = 0;
const rows = async (key: string) => {
const { getDb } = await import("../db/index.ts");
return (await getDb().$client.query(`select count from rate_limits where key = $1`, [key])).rows as { count: number }[];
};
const withCookie = (ip: string) =>
new Request("https://heidi.orangecat.ch/api/speak", { method: "POST", headers: { "x-forwarded-for": ip, cookie: "heidi.session_token=abc" } });
before(async () => {
mock.module(new URL("../auth/index.ts", import.meta.url).href, {
namedExports: {
authEnabled: true,
auth: async () => {
sessionReads += 1;
return signedInAs ? { actorId: signedInAs } : null;
},
},
});
const { getDb } = await import("../db/index.ts");
await getDb().$client.query(`delete from rate_limits where key like 't-%'`);
});
test("is counted in the database under their account, whatever address they come from", async () => {
const who = `u${Math.random().toString(36).slice(2)}`;
signedInAs = who;
const first = await allow(speak, withCookie("198.51.100.1"), "t-speak");
const second = await allow(speak, withCookie("203.0.113.77"), "t-speak");
assert.equal(first.remaining - second.remaining, 1, "two addresses, one allowance");
assert.deepEqual(await rows(actorKey(who, "t-speak")), [{ count: 2 }]);
assert.equal(speak.memory.peek(callerKey(withCookie("198.51.100.1"), "t-speak")).remaining, speak.rule.limit - 1, "nothing was counted against the address");
});
test("a route that already knows the account passes it, and no session is read", async () => {
const who = `u${Math.random().toString(36).slice(2)}`;
sessionReads = 0;
await allow(speak, req(), "t-known", who);
await allow(speak, null, "t-known", who);
assert.equal(sessionReads, 0);
assert.deepEqual(await rows(actorKey(who, "t-known")), [{ count: 2 }]);
});
test("a request without a session cookie never causes a session lookup", async () => {
sessionReads = 0;
signedInAs = "somebody";
await allow(speak, req("198.51.100.200"), "t-nocookie");
assert.equal(sessionReads, 0);
assert.deepEqual(await rows(actorKey("somebody", "t-nocookie")), []);
});
test("a cookie that is nobody's session is an anonymous caller, counted by address", async () => {
signedInAs = null;
const request = withCookie("198.51.100.201");
const before = speak.memory.peek(callerKey(request, "t-forged")).remaining;
await allow(speak, request, "t-forged");
assert.equal(speak.memory.peek(callerKey(request, "t-forged")).remaining, before - 1);
});
test("the allowance is the same number as the anonymous one: only where it is kept differs", async () => {
const who = `u${Math.random().toString(36).slice(2)}`;
let allowed = 0;
for (let i = 0; i < modelCheck.rule.limit + 3; i++) if ((await allow(modelCheck, null, "t-same", who)).allowed) allowed += 1;
assert.equal(allowed, modelCheck.rule.limit);
});
});