Public: anyone can read this; the crew can change it.
Perimeter mediums: lockout-safe sign-in throttle, persistent spawn caps, no secrets in idempotency storage, login CSRF #2945
mason/forge:mason/2922-perimeter-mediums-lockout-safe-sign-in-t → main 10 commits fork 4 threads · 4 unresolved
docs/THREATS.md +4 −2
| @@ -37,8 +37,10 @@ Wants: to act as the person or agent it was issued to, for as long as it works. | ||
| 37 | 37 | - A passport (`fp1.…`) is bound to one audience and scope set and dies in |
| 38 | 38 | minutes, so a copy lifted from a run is useful to one door briefly. |
| 39 | 39 | Test: `test/passport.test.ts` |
| 40 | - Sign-in attempts are throttled per client, with a whole-forge cap beside it. | |
| 41 | Test: `test/signin-throttle.test.ts` | |
| 40 | - Sign-in attempts are throttled per account from one source and per source, | |
| 41 | never forge-wide, so a guesser shuts out only their own source; a bounded | |
| 42 | hash gate caps the argon2 a flood can buy. | |
| 43 | Test: `test/signin-lockout.test.ts` | |
| 42 | 44 | - Stored provider tokens (origins) are sealed under a key in `secret.key`, never |
| 43 | 45 | returned by any route. |
| 44 | 46 | Test: `test/origins-security-auth.test.ts` |
src/core/hash-gate.ts added +55
| @@ -0,0 +1,55 @@ | ||
| 1 | /** | |
| 2 | * The hash gate: how many password hashes may run at once. One argon2 | |
| 3 | * verify holds 64 MiB and a core for a while, and every door that takes a | |
| 4 | * password — the form, the API, HTTP Basic on every git request, the | |
| 5 | * terminal — spends one per attempt. The sign-in windows | |
| 6 | * (`core/signin-window.ts`) bound what one source may try; this bounds what | |
| 7 | * the machine spends when many sources try at once (#2922): a few hashes in | |
| 8 | * flight, a short queue behind them in arrival order, and past the queue the | |
| 9 | * attempt is refused before it costs anything, as a throttle is. | |
| 10 | * | |
| 11 | * One gate per process, not per forge: the memory and the cores it guards | |
| 12 | * are the machine's. | |
| 13 | */ | |
| 14 | ||
| 15 | /** Hashes allowed to run at once: 4 × 64 MiB at most, held by argon2. */ | |
| 16 | export const HASHES_IN_FLIGHT = 4; | |
| 17 | /** Attempts allowed to wait for a slot; past this they are refused. */ | |
| 18 | export const HASHES_WAITING = 32; | |
| 19 | /** What a refused attempt is told to wait, in seconds. */ | |
| 20 | export const HASH_GATE_RETRY_S = 1; | |
| 21 | ||
| 22 | export class HashGate { | |
| 23 | private running = 0; | |
| 24 | private readonly waiting: (() => void)[] = []; | |
| 25 | ||
| 26 | constructor( | |
| 27 | private readonly inFlight = HASHES_IN_FLIGHT, | |
| 28 | private readonly queue = HASHES_WAITING, | |
| 29 | ) {} | |
| 30 | ||
| 31 | /** | |
| 32 | * Run `work` once a slot is free, or answer `"busy"` at once when the | |
| 33 | * queue is full. The slot is given back however `work` ends. | |
| 34 | */ | |
| 35 | async run<T>(work: () => Promise<T>): Promise<T | "busy"> { | |
| 36 | if (this.running >= this.inFlight) { | |
| 37 | if (this.waiting.length >= this.queue) return "busy"; | |
| 38 | await new Promise<void>((resolve) => this.waiting.push(resolve)); | |
| 39 | } else { | |
| 40 | this.running++; | |
| 41 | } | |
| 42 | try { | |
| 43 | return await work(); | |
| 44 | } finally { | |
| 45 | // Hand the slot straight to the next waiter, so `running` never dips | |
| 46 | // and a newcomer cannot jump the queue. | |
| 47 | const next = this.waiting.shift(); | |
| 48 | if (next !== undefined) next(); | |
| 49 | else this.running--; | |
| 50 | } | |
| 51 | } | |
| 52 | } | |
| 53 | ||
| 54 | /** The gate every password verify passes through (`core/users.ts`). */ | |
| 55 | export const passwordHashes = new HashGate(); |
src/core/migrations/20261019180000-anonymous-spawns.ts added +13
| @@ -0,0 +1,13 @@ | ||
| 1 | // Every child forge a stranger started (#2922 M2): when, and from which | |
| 2 | // client bucket (`http/peer.ts` `bucketOf`, an address or an IPv6 /64), so | |
| 3 | // the anonymous spawn limits (`spawn/rate.ts`) hold across a restart. A row | |
| 4 | // older than a day counts for nothing and is dropped when the next is kept. | |
| 5 | export default ` | |
| 6 | CREATE TABLE anon_spawn ( | |
| 7 | id INTEGER PRIMARY KEY, | |
| 8 | bucket TEXT NOT NULL, | |
| 9 | at INTEGER NOT NULL | |
| 10 | ); | |
| 11 | CREATE INDEX anon_spawn_at ON anon_spawn (at); | |
| 12 | CREATE INDEX anon_spawn_bucket ON anon_spawn (bucket, at); | |
| 13 | `; |
src/core/signin-window.ts +37 −26
| @@ -1,15 +1,25 @@ | ||
| 1 | 1 | /** |
| 2 | 2 | * Sign-in attempts, throttled. The token limiter does not see a password |
| 3 | 3 | * form — a stranger has no credential yet — so guessing a password runs at |
| 4 | * line speed and each guess costs a slow hash. Three sliding windows, checked | |
| 5 | * before the hash: an account may be tried twenty times a minute, a source | |
| 6 | * sixty, and the forge as a whole two hundred, so neither one account, one | |
| 7 | * source nor every account at once is worth the trying. A person signing in | |
| 8 | * does not notice; a refused attempt is not counted, so the door reopens | |
| 9 | * exactly a window later. One limiter per forge database, so a test's forge | |
| 10 | * never throttles another's. Every door that proves a secret asks here: the | |
| 11 | * password doors through `verifyPasswordThrottled` (`core/users.ts`), the | |
| 12 | * passkey, claim and parent doors with a key of their own. | |
| 4 | * line speed and each guess costs a slow hash. Two sliding windows, checked | |
| 5 | * before the hash: one account may be tried twenty times a minute from one | |
| 6 | * source, and one source sixty times a minute whatever it names, so neither | |
| 7 | * hammering one account nor walking through many is worth the trying. | |
| 8 | * | |
| 9 | * Neither window is the account's alone or the forge's as a whole (#2922): | |
| 10 | * a window a stranger can fill from anywhere is a door they can shut on | |
| 11 | * someone else, so a guesser at the admin's name locks out that guesser's | |
| 12 | * source and nobody else's, and a flood never closes sign-in for everyone. | |
| 13 | * What bounds the hashing a flood can buy is the hash gate | |
| 14 | * (`core/hash-gate.ts`): a few in flight, a short queue, the rest refused. | |
| 15 | * A passkey or a token is a way in that never asks here at all. | |
| 16 | * | |
| 17 | * A person signing in does not notice; a refused attempt is not counted, so | |
| 18 | * the door reopens exactly a window later. One limiter per forge database, | |
| 19 | * so a test's forge never throttles another's. Every door that proves a | |
| 20 | * secret asks here: the password doors through `verifyPasswordThrottled` | |
| 21 | * (`core/users.ts`), the passkey, claim and parent doors with a key of | |
| 22 | * their own. | |
| 13 | 23 | */ |
| 14 | 24 | |
| 15 | 25 | import type { Database } from "bun:sqlite"; |
| @@ -18,7 +28,7 @@ import { bucketOf } from "../http/peer.ts"; | ||
| 18 | 28 | import { limitValue } from "../settings/limits.ts"; |
| 19 | 29 | |
| 20 | 30 | const accounts = new WeakMap<Database, RateLimiter>(); |
| 21 | // The third window, by the socket's peer: a source trying many accounts. | |
| 31 | // The second window, by the socket's peer: a source trying many accounts. | |
| 22 | 32 | const sources = new WeakMap<Database, RateLimiter>(); |
| 23 | 33 | |
| 24 | 34 | function limiterOf(map: WeakMap<Database, RateLimiter>, db: Database): RateLimiter { |
| @@ -35,8 +45,11 @@ export type SigninAdmission = | ||
| 35 | 45 | | { readonly admitted: false; readonly retryAfter: number } |
| 36 | 46 | | { |
| 37 | 47 | readonly admitted: true; |
| 38 | /** The secret proved right: give the attempt back to every window. */ | |
| 39 | readonly succeeded: () => void; | |
| 48 | /** | |
| 49 | * Give the attempt back to every window: the secret proved right, or | |
| 50 | * it was never checked (the hash gate turned it away). | |
| 51 | */ | |
| 52 | readonly giveBack: () => void; | |
| 40 | 53 | }; |
| 41 | 54 | |
| 42 | 55 | /** |
| @@ -49,28 +62,26 @@ export type SigninAdmission = | ||
| 49 | 62 | export function admitSignin(db: Database, account: string, address: string): SigninAdmission { |
| 50 | 63 | const limiter = limiterOf(accounts, db); |
| 51 | 64 | // Read on every attempt, so a change on /admin/limits governs the next one. |
| 52 | limiter.setLimits({ | |
| 53 | perMinute: limitValue(db, "signin.per_account"), | |
| 54 | adminPerMinute: limitValue(db, "signin.per_forge"), | |
| 55 | enabled: true, | |
| 56 | }); | |
| 57 | const accountKey = `account:${account.toLowerCase()}`; | |
| 58 | // The one key first: a key already refused must not spend the forge's budget. | |
| 65 | limiter.setLimits({ perMinute: limitValue(db, "signin.per_account"), adminPerMinute: 0, enabled: true }); | |
| 66 | const source = bucketOf(address); | |
| 67 | // The account as tried from this source: its window shuts on this source only. | |
| 68 | const accountKey = `account:${account.toLowerCase()}@${source}`; | |
| 69 | // The one key first: a key already refused must not spend the source's budget. | |
| 59 | 70 | const one = limiter.take(accountKey, "ro"); |
| 60 | 71 | if (!one.allowed) return { admitted: false, retryAfter: one.retryAfter }; |
| 61 | 72 | const peers = limiterOf(sources, db); |
| 62 | 73 | peers.setLimits({ perMinute: limitValue(db, "signin.per_source"), adminPerMinute: 0, enabled: true }); |
| 63 | const sourceKey = `source:${bucketOf(address)}`; | |
| 64 | const source = peers.take(sourceKey, "ro"); | |
| 65 | if (!source.allowed) return { admitted: false, retryAfter: source.retryAfter }; | |
| 66 | const whole = limiter.take("forge", "admin"); | |
| 67 | if (!whole.allowed) return { admitted: false, retryAfter: whole.retryAfter }; | |
| 74 | const sourceKey = `source:${source}`; | |
| 75 | const whole = peers.take(sourceKey, "ro"); | |
| 76 | if (!whole.allowed) { | |
| 77 | limiter.refund(accountKey); | |
| 78 | return { admitted: false, retryAfter: whole.retryAfter }; | |
| 79 | } | |
| 68 | 80 | return { |
| 69 | 81 | admitted: true, |
| 70 | succeeded: () => { | |
| 82 | giveBack: () => { | |
| 71 | 83 | limiter.refund(accountKey); |
| 72 | 84 | peers.refund(sourceKey); |
| 73 | limiter.refund("forge"); | |
| 74 | 85 | }, |
| 75 | 86 | }; |
| 76 | 87 | } |
src/core/users.ts +17 −7
| @@ -10,6 +10,7 @@ import { reservedName } from "./reserved.ts"; | ||
| 10 | 10 | import { id } from "../kernel/id.ts"; |
| 11 | 11 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 12 | 12 | import { admitSignin } from "./signin-window.ts"; |
| 13 | import { HASH_GATE_RETRY_S, passwordHashes } from "./hash-gate.ts"; | |
| 13 | 14 | import { getSignup } from "../settings/signup.ts"; |
| 14 | 15 | import { inviteOpen, redeemInvite, reopenInvite } from "./invites.ts"; |
| 15 | 16 | import type { SignupSlot } from "../actions/signup-window.ts"; |
| @@ -484,11 +485,14 @@ export interface PasswordAttempt { | ||
| 484 | 485 | |
| 485 | 486 | /** |
| 486 | 487 | * The only way to prove a password. The attempt is counted in the sign-in |
| 487 | * windows (per account, per source, per forge: `core/signin-window.ts`) | |
| 488 | * before the hash, so no door can guess at line speed or spend the CPU on | |
| 489 | * argon2; a right password is given back, so a git client that sends it on | |
| 490 | * every request is not throttled. The check itself is not exported: a new door cannot skip the | |
| 491 | * windows, because there is nothing else to call. | |
| 488 | * windows (per account from one source, per source: `core/signin-window.ts`) | |
| 489 | * before the hash, so no door can guess at line speed, and the hash itself | |
| 490 | * waits its turn at the hash gate (`core/hash-gate.ts`), so a flood from many | |
| 491 | * sources cannot spend the machine's memory on argon2. A right password is | |
| 492 | * given back, so a git client that sends it on every request is not | |
| 493 | * throttled; so is an attempt the gate turned away unchecked. The check | |
| 494 | * itself is not exported: a new door cannot skip the windows, because there | |
| 495 | * is nothing else to call. | |
| 492 | 496 | */ |
| 493 | 497 | export async function verifyPasswordThrottled( |
| 494 | 498 | db: Database, |
| @@ -497,9 +501,15 @@ export async function verifyPasswordThrottled( | ||
| 497 | 501 | const admission = admitSignin(db, attempt.username, attempt.source); |
| 498 | 502 | if (!admission.admitted) |
| 499 | 503 | return err({ reason: "throttled", retryAfter: admission.retryAfter }); |
| 500 | const checked = await checkPassword(db, attempt.username, attempt.password); | |
| 504 | const checked = await passwordHashes.run(() => | |
| 505 | checkPassword(db, attempt.username, attempt.password), | |
| 506 | ); | |
| 507 | if (checked === "busy") { | |
No test covers this branch. If you delete |
||
| 508 | admission.giveBack(); | |
| 509 | return err({ reason: "throttled", retryAfter: HASH_GATE_RETRY_S }); | |
| 510 | } | |
| 501 | 511 | if (!checked.ok) return err({ reason: "bad_credentials" }); |
| 502 | admission.succeeded(); | |
| 512 | admission.giveBack(); | |
| 503 | 513 | return checked; |
| 504 | 514 | } |
| 505 | 515 |
src/http/api.ts +4
| @@ -1280,6 +1280,10 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 1280 | 1280 | }); |
| 1281 | 1281 | |
| 1282 | 1282 | router.add("POST", "/api/v1/sessions", async (ctx) => { |
| 1283 | // It sets a session cookie, so it is same-origin like the form at | |
| 1284 | // /signin: another site must not sign a browser into its own account | |
| 1285 | // here (login CSRF) and watch what that person then does. | |
| 1286 | if (crossOrigin(ctx.request, ctx.url, ctx.app.log)) return forbidden(); | |
| 1283 | 1287 | // Anyone may call this, so its body is a stranger's (`http/limits.ts`). |
| 1284 | 1288 | const input = await boundedBody(ctx.request, STRANGER_MAX); |
| 1285 | 1289 | if (input === "too_large") |
src/http/server.ts +24 −10
| @@ -1736,21 +1736,35 @@ async function withIdempotency( | ||
| 1736 | 1736 | } |
| 1737 | 1737 | |
| 1738 | 1738 | /** |
| 1739 | * Fields of an API answer that are a secret shown once (a spawned child's | |
| 1740 | * claim link): an idempotent replay must not return them, and the | |
| 1741 | * idempotency table must not keep them. | |
| 1739 | * Fields of an API answer that are a secret shown once — a minted token | |
| 1740 | * (`POST /api/v1/tokens`, the first admin's, a proposal token), a webhook's | |
| 1741 | * signing secret, an invite's token and the link that carries it, a spawned | |
| 1742 | * child's claim link: an idempotent replay must not return them, and the | |
| 1743 | * idempotency table (and every backup of it) must not keep them. Matched by | |
| 1744 | * name at any depth, so a secret nested in an answer is kept out too. | |
| 1745 | * | |
| 1746 | * The cost is chosen: a field by one of these names that is not a secret | |
outdated
Minor: matching by name at any depth means any non-secret |
||
| 1747 | * (a share's or a feed item's `link`) comes back from a replay as the note, | |
| 1748 | * not its value. A replay is a retry that already had the first answer, so | |
| 1749 | * losing a public link there is cheap; missing a secret because a new | |
| 1750 | * route nested it under a name not listed here would not be. | |
| 1742 | 1751 | */ |
| 1743 | const SHOWN_ONCE = ["claimUrl"] as const; | |
| 1752 | const SHOWN_ONCE: ReadonlySet<string> = new Set(["claimUrl", "token", "secret", "link"]); | |
| 1744 | 1753 | export const SHOWN_ONCE_NOTE = "shown once, in the first answer"; |
| 1745 | 1754 | |
| 1755 | function redactShownOnce(value: unknown): unknown { | |
| 1756 | if (Array.isArray(value)) return value.map(redactShownOnce); | |
| 1757 | if (typeof value !== "object" || value === null) return value; | |
| 1758 | const copy: Record<string, unknown> = {}; | |
| 1759 | for (const [k, v] of Object.entries(value)) | |
| 1760 | copy[k] = SHOWN_ONCE.has(k) && typeof v === "string" ? SHOWN_ONCE_NOTE : redactShownOnce(v); | |
| 1761 | return copy; | |
| 1762 | } | |
| 1763 | ||
| 1746 | 1764 | export function withoutShownOnce(body: string): string { |
| 1747 | if (!SHOWN_ONCE.some((k) => body.includes(`"${k}"`))) return body; | |
| 1765 | if (![...SHOWN_ONCE].some((k) => body.includes(`"${k}"`))) return body; | |
| 1748 | 1766 | try { |
| 1749 | const parsed = JSON.parse(body) as unknown; | |
| 1750 | if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return body; | |
| 1751 | const copy: Record<string, unknown> = { ...(parsed as Record<string, unknown>) }; | |
| 1752 | for (const k of SHOWN_ONCE) if (k in copy) copy[k] = SHOWN_ONCE_NOTE; | |
| 1753 | return JSON.stringify(copy); | |
| 1767 | return JSON.stringify(redactShownOnce(JSON.parse(body) as unknown)); | |
| 1754 | 1768 | } catch { |
| 1755 | 1769 | return body; |
| 1756 | 1770 | } |
src/settings/limits.ts +13 −4
| @@ -36,6 +36,7 @@ export type LimitKey = | ||
| 36 | 36 | | "signin.per_forge" |
| 37 | 37 | | "signup.per_source" |
| 38 | 38 | | "signup.per_forge" |
| 39 | | "spawn.anon_per_forge" | |
| 39 | 40 | | "api.anonymous_per_source"; |
| 40 | 41 | |
| 41 | 42 | export interface LimitDef { |
| @@ -121,12 +122,12 @@ export const LIMITS: Record<LimitKey, LimitDef> = { | ||
| 121 | 122 | reason: "A person's feed is theirs: shares past the day's allowance wait instead of crowding it out.", |
| 122 | 123 | }, |
| 123 | 124 | "signin.per_account": { |
| 124 | label: "Sign-in attempts per account a minute", | |
| 125 | label: "Sign-in attempts per account from one source a minute", | |
| 125 | 126 | unit: "attempts", |
| 126 | 127 | default: 20, |
| 127 | 128 | min: 1, |
| 128 | 129 | max: 1_000, |
| 129 | reason: "Every attempt costs a password hash, and a guesser gets only so many tries at one account.", | |
| 130 | reason: "Every attempt costs a password hash, and a guesser gets only so many tries at one account; counted per source, so a guesser shuts out only themselves.", | |
| 130 | 131 | }, |
| 131 | 132 | "signin.per_source": { |
| 132 | 133 | label: "Sign-in attempts per source a minute", |
| @@ -137,12 +138,12 @@ export const LIMITS: Record<LimitKey, LimitDef> = { | ||
| 137 | 138 | reason: "One source trying account after account is guessing, and each try costs a hash, so a source has a ceiling of its own.", |
| 138 | 139 | }, |
| 139 | 140 | "signin.per_forge": { |
| 140 | label: "Sign-in attempts per forge a minute", | |
| 141 | label: "First-admin claim attempts per forge a minute", | |
| 141 | 142 | unit: "attempts", |
| 142 | 143 | default: 200, |
| 143 | 144 | min: 1, |
| 144 | 145 | max: 100_000, |
| 145 | reason: "Spread across many accounts, guessing still burns CPU on hashes, so the forge as a whole has a ceiling.", | |
| 146 | reason: "The first-admin code is one secret for the whole forge, so guessing it from many sources at once has a ceiling. Password sign-in has none forge-wide: it would let a stranger shut everyone out.", | |
| 146 | 147 | }, |
| 147 | 148 | "signup.per_source": { |
| 148 | 149 | label: "Sign-ups per source a minute", |
| @@ -160,6 +161,14 @@ export const LIMITS: Record<LimitKey, LimitDef> = { | ||
| 160 | 161 | max: 100_000, |
| 161 | 162 | reason: "Spread across many sources, sign-ups still cost hashes and accounts, so the forge as a whole has a ceiling.", |
| 162 | 163 | }, |
| 164 | "spawn.anon_per_forge": { | |
| 165 | label: "Anonymous child forges per forge a day", | |
| 166 | unit: "forges", | |
| 167 | default: 20, | |
| 168 | min: 1, | |
| 169 | max: 10_000, | |
| 170 | reason: "Every child forge a stranger starts holds disk and a process on this machine, so strangers together have a ceiling, kept across restarts.", | |
| 171 | }, | |
| 163 | 172 | "api.anonymous_per_source": { |
| 164 | 173 | label: "API reads without a token per source a minute", |
| 165 | 174 | unit: "reads", |
src/spawn/door.ts +19 −13
| @@ -27,7 +27,7 @@ import { | ||
| 27 | 27 | } from "./placement.ts"; |
| 28 | 28 | import { dryRun, planSpawn, KEY_BUDGET_NOTE, MAX_APPS, type CatalogApp, type CrewBrief, type SpawnSource } from "./plan.ts"; |
| 29 | 29 | import { bootHostedChild } from "./host.ts"; |
| 30 | import { ANON_SPAWNS_PER_DAY, checkAnonSpawn, noteAnonSpawn } from "./rate.ts"; | |
| 30 | import { reserveAnonSpawn } from "./rate.ts"; | |
| 31 | 31 | import { readdirSync, readFileSync } from "node:fs"; |
| 32 | 32 | import { readdir, stat } from "node:fs/promises"; |
| 33 | 33 | import { join } from "node:path"; |
| @@ -274,17 +274,19 @@ export async function spawnDoor( | ||
| 274 | 274 | }; |
| 275 | 275 | } |
| 276 | 276 | // A stranger may start only a few children a day; the plan above is free. |
| 277 | if (anon) { | |
| 278 | const limit = checkAnonSpawn(ctx.request); | |
| 279 | if (!limit.allowed) | |
| 280 | return { | |
| 281 | status: 429, | |
| 282 | body: { | |
| 283 | error: "rate_limited", | |
| 284 | message: `anonymous spawns are limited to ${ANON_SPAWNS_PER_DAY} per day; try again after ${limit.resetsAt}`, | |
| 285 | }, | |
| 286 | }; | |
| 287 | } | |
| 277 | // The slot is taken before the spawn, so a race cannot overrun it. | |
| 278 | const reserved = anon ? reserveAnonSpawn(ctx.app.db, ctx.request) : undefined; | |
| 279 | if (reserved !== undefined && !reserved.allowed) | |
| 280 | return { | |
| 281 | status: 429, | |
| 282 | body: { | |
| 283 | error: "rate_limited", | |
| 284 | message: | |
| 285 | reserved.scope === "client" | |
| 286 | ? `anonymous spawns are limited to ${reserved.limit} per day; try again after ${reserved.resetsAt}` | |
| 287 | : `anonymous spawns on this forge are limited to ${reserved.limit} per day; try again after ${reserved.resetsAt}`, | |
| 288 | }, | |
| 289 | }; | |
| 288 | 290 | const startedAt = Date.now(); |
| 289 | 291 | const made = await spawnForge(ctx.app, user, input, source, { |
| 290 | 292 | placement: placementFor(ctx.app), |
| @@ -292,9 +294,13 @@ export async function spawnDoor( | ||
| 292 | 294 | url: ctx.url, |
| 293 | 295 | ...(typeof modelKey === "string" ? { modelKey } : {}), |
| 294 | 296 | ...(modelEndpoint === undefined ? {} : { modelEndpoint }), |
| 297 | }).catch((e: unknown) => { | |
| 298 | reserved?.release(); | |
| 299 | throw e; | |
| 295 | 300 | }); |
| 301 | // Only a child actually made counts against the stranger. | |
| 302 | if (reserved !== undefined && (!made.ok || made.value.existed)) reserved.release(); | |
If you delete this release, nothing fails: |
||
| 296 | 303 | if (!made.ok) return spawnWords(made.error); |
| 297 | if (anon && !made.value.existed) noteAnonSpawn(ctx.request); | |
| 298 | 304 | // Its apps come up now, so the first visit after a claim finds them awake. |
| 299 | 305 | if (!made.value.existed) { |
| 300 | 306 | void bootHostedChild(ctx.app, made.value.name); |
src/spawn/rate.ts +52 −39
| @@ -1,54 +1,67 @@ | ||
| 1 | 1 | /** |
| 2 | * The anonymous spawn limit: a stranger may start at most this many child | |
| 3 | * forges in any 24 hours, keyed by their client bucket (`http/peer.ts`). | |
| 4 | * A light guard against abuse, not a durable ledger — it lives in memory, | |
| 5 | * so a restart clears it, which is fine for a rate limit. Signed-in | |
| 6 | * callers are not counted here. | |
| 2 | * The anonymous spawn limits: a stranger may start at most this many child | |
| 3 | * forges in any 24 hours, keyed by their client bucket (`http/peer.ts`), | |
| 4 | * and strangers together at most `spawn.anon_per_forge` (/admin/limits). | |
| 5 | * Every child holds disk and a process, so the count is kept in the | |
| 6 | * `anon_spawn` table and holds across a restart (#2922): a restart is not a | |
| 7 | * fresh allowance. Signed-in callers are not counted here. | |
| 8 | * | |
| 9 | * A spawn is reserved before it is made and given back if nothing was | |
| 10 | * made, so two requests racing for the last slot cannot both take it. | |
| 7 | 11 | */ |
| 8 | 12 | |
| 13 | import type { Database } from "bun:sqlite"; | |
| 9 | 14 | import { clientBucket } from "../http/peer.ts"; |
| 15 | import { limitValue } from "../settings/limits.ts"; | |
| 10 | 16 | |
| 11 | 17 | /** Anonymous spawns allowed per client in any 24 hours. */ |
| 12 | 18 | export const ANON_SPAWNS_PER_DAY = 3; |
| 13 | 19 | const DAY_MS = 86_400_000; |
| 14 | 20 | |
| 15 | /** When each counted spawn happened, oldest first, per client bucket. */ | |
| 16 | const seen = new Map<string, number[]>(); | |
| 21 | export type AnonSpawnReservation = | |
| 22 | | { | |
| 23 | readonly allowed: false; | |
| 24 | /** Whose allowance is spent: this client's, or every stranger's. */ | |
| 25 | readonly scope: "client" | "forge"; | |
| 26 | /** The allowance that was spent. */ | |
| 27 | readonly limit: number; | |
| 28 | /** When the oldest counted spawn leaves the window, ISO. */ | |
| 29 | readonly resetsAt: string; | |
| 30 | } | |
| 31 | | { | |
| 32 | readonly allowed: true; | |
| 33 | /** Nothing was made after all: give the reservation back. */ | |
| 34 | readonly release: () => void; | |
| 35 | }; | |
| 17 | 36 | |
| 18 | const prune = (bucket: string, now: number): number[] => { | |
| 19 | const kept = (seen.get(bucket) ?? []).filter((t) => now - t < DAY_MS); | |
| 20 | if (kept.length === 0) seen.delete(bucket); | |
| 21 | else seen.set(bucket, kept); | |
| 22 | return kept; | |
| 23 | }; | |
| 37 | const resetsAt = (oldest: number | null, now: number): string => | |
| 38 | new Date((oldest ?? now) + DAY_MS).toISOString(); | |
| 24 | 39 | |
| 25 | export interface RateLimit { | |
| 26 | /** True when another anonymous spawn may be made now. */ | |
| 27 | readonly allowed: boolean; | |
| 28 | /** When the oldest counted spawn leaves the window, ISO. */ | |
| 29 | readonly resetsAt: string; | |
| 30 | } | |
| 31 | ||
| 32 | /** Whether this request's client may anonymously spawn now. */ | |
| 33 | export function checkAnonSpawn(request: Request, now = Date.now()): RateLimit { | |
| 40 | /** Reserve one anonymous spawn for this request's client, or say why not. */ | |
| 41 | export function reserveAnonSpawn(db: Database, request: Request, now = Date.now()): AnonSpawnReservation { | |
| 34 | 42 | const bucket = clientBucket(request); |
| 35 | const kept = prune(bucket, now); | |
| 36 | const oldest = kept[0] ?? now; | |
| 37 | return { | |
| 38 | allowed: kept.length < ANON_SPAWNS_PER_DAY, | |
| 39 | resetsAt: new Date(oldest + DAY_MS).toISOString(), | |
| 40 | }; | |
| 43 | const since = now - DAY_MS; | |
| 44 | const forgeLimit = limitValue(db, "spawn.anon_per_forge"); | |
| 45 | return db.transaction((): AnonSpawnReservation => { | |
| 46 | db.query("DELETE FROM anon_spawn WHERE at <= ?1").run(since); | |
| 47 | const mine = db | |
| 48 | .query<{ n: number; oldest: number | null }, [string]>("SELECT count(*) AS n, min(at) AS oldest FROM anon_spawn WHERE bucket = ?1") | |
| 49 | .get(bucket)!; | |
| 50 | if (mine.n >= ANON_SPAWNS_PER_DAY) | |
| 51 | return { allowed: false, scope: "client", limit: ANON_SPAWNS_PER_DAY, resetsAt: resetsAt(mine.oldest, now) }; | |
| 52 | const all = db.query<{ n: number; oldest: number | null }, []>("SELECT count(*) AS n, min(at) AS oldest FROM anon_spawn").get()!; | |
| 53 | if (all.n >= forgeLimit) return { allowed: false, scope: "forge", limit: forgeLimit, resetsAt: resetsAt(all.oldest, now) }; | |
| 54 | const id = db.query<{ id: number }, [string, number]>("INSERT INTO anon_spawn (bucket, at) VALUES (?1, ?2) RETURNING id").get(bucket, now)!.id; | |
| 55 | return { | |
| 56 | allowed: true, | |
| 57 | release: () => { | |
| 58 | db.query("DELETE FROM anon_spawn WHERE id = ?1").run(id); | |
| 59 | }, | |
| 60 | }; | |
| 61 | })(); | |
| 41 | 62 | } |
| 42 | 63 | |
| 43 | /** Count an anonymous spawn against this request's client. */ | |
| 44 | export function noteAnonSpawn(request: Request, now = Date.now()): void { | |
| 45 | const bucket = clientBucket(request); | |
| 46 | const kept = prune(bucket, now); | |
| 47 | kept.push(now); | |
| 48 | seen.set(bucket, kept); | |
| 49 | } | |
| 50 | ||
| 51 | /** Forget every counted spawn (tests). */ | |
| 52 | export function resetAnonSpawns(): void { | |
| 53 | seen.clear(); | |
| 64 | /** Forget every counted spawn on this forge (tests). */ | |
| 65 | export function resetAnonSpawns(db: Database): void { | |
| 66 | db.run("DELETE FROM anon_spawn"); | |
| 54 | 67 | } |
src/web/markdown.ts +8 −2
| @@ -30,8 +30,14 @@ function inline(escaped: string): string { | ||
| 30 | 30 | // and reject anything carrying a scheme other than http(s), which is |
| 31 | 31 | // what keeps javascript:, data: and vbscript: out. What is left is a |
| 32 | 32 | // relative path (`docs/keeping.md`), a rooted one, or an anchor — |
| 33 | // all of which stay on this origin by construction. | |
| 34 | if (url.startsWith("//")) return match; | |
| 33 | // all of which stay on this origin by construction. A browser | |
| 34 | // strips C0 controls and DEL from a URL before it reads the scheme, | |
| 35 | // so "\x01javascript:" would pass the test below and still run: | |
| 36 | // a link carrying any control byte is not a link. | |
| 37 | if (/[\x00-\x1f\x7f]/.test(url)) return match; | |
| 38 | // A browser reads a backslash as "/" in a web URL, so "/\host" and | |
| 39 | // "\\host" are "//host" in disguise. | |
| 40 | if (/^[/\\][/\\]/.test(url)) return match; | |
| 35 | 41 | const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(url); |
| 36 | 42 | if (scheme && !/^https?$/i.test(scheme[1]!)) return match; |
| 37 | 43 | return `<a href="${url}" rel="nofollow noopener">${text}</a>`; |
test/idempotency-secrets.test.ts added +93
| @@ -0,0 +1,93 @@ | ||
| 1 | /** | |
| 2 | * An Idempotency-Key never keeps a secret (#2922 M6): the answer to | |
| 3 | * `POST /api/v1/tokens` carries a token and a webhook's creation carries its | |
| 4 | * signing secret, each shown once. The idempotency table — and every backup | |
| 5 | * of it — keeps neither, and a replay says it was shown instead. | |
| 6 | */ | |
| 7 | ||
| 8 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 9 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 10 | import { tmpdir } from "node:os"; | |
| 11 | import { join } from "node:path"; | |
| 12 | import { createRepo } from "../src/actions/repos.ts"; | |
| 13 | import { createApp, type App } from "../src/app.ts"; | |
| 14 | import { createSession } from "../src/core/sessions.ts"; | |
| 15 | import { createToken } from "../src/core/tokens.ts"; | |
| 16 | import { serve, SHOWN_ONCE_NOTE, withoutShownOnce, type Servers } from "../src/http/server.ts"; | |
| 17 | import { seedAdmin } from "./helpers/admin.ts"; | |
| 18 | import { quietLogs } from "./helpers/globals.ts"; | |
| 19 | ||
| 20 | quietLogs(); | |
| 21 | ||
| 22 | let dir = ""; | |
| 23 | let app: App; | |
| 24 | let servers: Servers; | |
| 25 | let cookie = ""; | |
| 26 | let admin = ""; | |
| 27 | ||
| 28 | beforeAll(async () => { | |
| 29 | dir = await mkdtemp(join(tmpdir(), "idem-secrets-")); | |
| 30 | app = createApp({ dataDir: dir, port: 0 }); | |
| 31 | servers = await serve(app); | |
| 32 | const pat = await seedAdmin(app, { username: "pat", email: "[email protected]", password: "a-long-family-passphrase" }); | |
| 33 | if (!pat.ok) throw new Error("setup"); | |
| 34 | cookie = `forge_session=${createSession(app.db, pat.value.id).token}`; | |
| 35 | admin = createToken(app.db, pat.value.id, "t", "admin").token; | |
| 36 | const repo = await createRepo(app, pat.value, { name: "ledger" }); | |
| 37 | if (!repo.ok) throw new Error("setup"); | |
| 38 | }); | |
| 39 | ||
| 40 | afterAll(async () => { | |
| 41 | servers.stop(); | |
| 42 | await rm(dir, { recursive: true, force: true }); | |
| 43 | }); | |
| 44 | ||
| 45 | const kept = (): string[] => | |
| 46 | (app.db.query("SELECT body FROM idempotency").all() as { body: string }[]).map((r) => r.body); | |
| 47 | ||
| 48 | describe("Idempotency-Key and secrets shown once", () => { | |
| 49 | test("a minted token is not kept, and its replay says it was shown once", async () => { | |
| 50 | const send = () => | |
| 51 | fetch(`${servers.url}/api/v1/tokens`, { | |
| 52 | method: "POST", | |
| 53 | headers: { cookie, origin: servers.url, "content-type": "application/json", "idempotency-key": "mint-1" }, | |
| 54 | body: JSON.stringify({ name: "ci", scope: "ro", adminConfirm: true }), | |
| 55 | }); | |
| 56 | const first = await send(); | |
| 57 | expect(first.status).toBe(201); | |
| 58 | const { token } = (await first.json()) as { token: string }; | |
| 59 | expect(token).toStartWith("forge_"); | |
| 60 | expect(kept().some((b) => b.includes(token))).toBe(false); | |
| 61 | const again = await send(); | |
| 62 | expect(again.headers.get("idempotent-replay")).toBe("true"); | |
| 63 | expect(((await again.json()) as { token: string }).token).toBe(SHOWN_ONCE_NOTE); | |
| 64 | }); | |
| 65 | ||
| 66 | test("a webhook's signing secret is not kept, and its replay says it was shown once", async () => { | |
| 67 | const send = () => | |
| 68 | fetch(`${servers.url}/api/v1/repos/pat/ledger/hooks`, { | |
| 69 | method: "POST", | |
| 70 | headers: { authorization: `Bearer ${admin}`, "content-type": "application/json", "idempotency-key": "hook-1" }, | |
| 71 | body: JSON.stringify({ url: "https://hooks.example/in" }), | |
| 72 | }); | |
| 73 | const first = await send(); | |
| 74 | expect(first.status).toBe(201); | |
| 75 | const made = (await first.json()) as { id: string; secret: string }; | |
| 76 | expect(made.secret.length).toBeGreaterThan(16); | |
| 77 | expect(kept().some((b) => b.includes(made.secret))).toBe(false); | |
| 78 | const again = (await (await send()).json()) as { id: string; secret: string }; | |
| 79 | expect(again.id).toBe(made.id); | |
| 80 | expect(again.secret).toBe(SHOWN_ONCE_NOTE); | |
| 81 | }); | |
| 82 | ||
| 83 | test("a secret nested in an answer is redacted too, and the rest is untouched", () => { | |
| 84 | const body = JSON.stringify({ id: 1, items: [{ token: "forge_x", name: "a" }], invite: { link: "https://f/i#t" }, count: 2 }); | |
| 85 | expect(JSON.parse(withoutShownOnce(body))).toEqual({ | |
| 86 | id: 1, | |
| 87 | items: [{ token: SHOWN_ONCE_NOTE, name: "a" }], | |
| 88 | invite: { link: SHOWN_ONCE_NOTE }, | |
| 89 | count: 2, | |
| 90 | }); | |
| 91 | expect(withoutShownOnce('{"title":"plain"}')).toBe('{"title":"plain"}'); | |
| 92 | }); | |
| 93 | }); |
test/markdown-links.test.ts added +33
| @@ -0,0 +1,33 @@ | ||
| 1 | /** | |
| 2 | * Markdown links keep to safe schemes (#2922 L3): a browser strips C0 | |
| 3 | * controls and DEL before reading a URL's scheme, so a control byte in front | |
| 4 | * of `javascript:` must not slip a script link past the scheme test, and a | |
| 5 | * backslash must not disguise "//host". | |
| 6 | */ | |
| 7 | ||
| 8 | import { describe, expect, test } from "bun:test"; | |
| 9 | import { renderMarkdown } from "../src/web/markdown.ts"; | |
| 10 | ||
| 11 | const html = (source: string): string => String(renderMarkdown(source)); | |
| 12 | ||
| 13 | describe("markdown links", () => { | |
| 14 | test("http(s), rooted, relative and anchor links render", () => { | |
| 15 | expect(html("[a](https://example.com/x)")).toContain('href="https://example.com/x"'); | |
| 16 | expect(html("[a](/docs/x.md)")).toContain('href="/docs/x.md"'); | |
| 17 | expect(html("[a](docs/x.md)")).toContain('href="docs/x.md"'); | |
| 18 | expect(html("[a](#top)")).toContain('href="#top"'); | |
| 19 | }); | |
| 20 | ||
| 21 | test("a control byte anywhere in the URL refuses the link", () => { | |
| 22 | for (const c of ["\x00", "\x01", "\x08", "\x0e", "\x1b", "\x1f", "\x7f"]) { | |
| 23 | const out = html(`[x](${c}javascript:alert(1))`); | |
| 24 | expect(out).not.toContain("<a "); | |
| 25 | expect(html(`[x](java${c}script:alert(1))`)).not.toContain("<a "); | |
| 26 | } | |
| 27 | }); | |
| 28 | ||
| 29 | test("other schemes and protocol-relative links stay text", () => { | |
| 30 | for (const url of ["javascript:alert(1)", "JaVaScRiPt:alert(1)", "data:text/html,x", "vbscript:x", "//evil.example", "/\\evil.example", "\\\\evil.example", "\\/evil.example"]) | |
| 31 | expect(html(`[x](${url})`)).not.toContain("<a "); | |
| 32 | }); | |
| 33 | }); |
test/signin-lockout.test.ts added +153
| @@ -0,0 +1,153 @@ | ||
| 1 | /** | |
| 2 | * No stranger can shut someone else out of sign-in (#2922 M1, M3). The | |
| 3 | * account's window is counted per source, so guesses at the admin's name | |
| 4 | * from one source close that source only; there is no forge-wide window for | |
| 5 | * a flood to fill. What bounds the hashing is the hash gate: a few verifies | |
| 6 | * in flight, a short queue, and past it a refusal that costs nothing. | |
| 7 | */ | |
| 8 | ||
| 9 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 10 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 11 | import { tmpdir } from "node:os"; | |
| 12 | import { join } from "node:path"; | |
| 13 | import { createApp, type App } from "../src/app.ts"; | |
| 14 | import { HashGate, HASH_GATE_RETRY_S, HASHES_IN_FLIGHT, HASHES_WAITING, passwordHashes } from "../src/core/hash-gate.ts"; | |
| 15 | import { createUser, verifyPasswordThrottled } from "../src/core/users.ts"; | |
| 16 | import { signinWindow } from "../src/core/signin-window.ts"; | |
| 17 | import { setLimit } from "../src/settings/limits.ts"; | |
| 18 | ||
| 19 | const PASSWORD = "a-good-passphrase"; | |
| 20 | let dir = ""; | |
| 21 | let app: App; | |
| 22 | let adminId = ""; | |
| 23 | ||
| 24 | beforeAll(async () => { | |
| 25 | dir = await mkdtemp(join(tmpdir(), "signin-lockout-")); | |
| 26 | app = createApp({ dataDir: dir, port: 0 }); | |
| 27 | const made = await createUser(app.db, { origin: "seed", trusted: true, username: "sam", email: "[email protected]", password: PASSWORD, adminIfFirst: true }); | |
| 28 | if (!made.ok) throw new Error(made.error); | |
| 29 | // The windows count before the hash, so the hash need not be costly here. | |
| 30 | const cheap = await Bun.password.hash(PASSWORD, { algorithm: "argon2id", memoryCost: 8, timeCost: 1 }); | |
| 31 | app.db.run("UPDATE user SET password_hash = ?1 WHERE username = 'sam'", [cheap]); | |
| 32 | adminId = made.value.id; | |
| 33 | setLimit(app.db, "signin.per_account", 3, adminId); | |
| 34 | }); | |
| 35 | ||
| 36 | afterAll(async () => { | |
| 37 | app.close(); | |
| 38 | await rm(dir, { recursive: true, force: true }); | |
| 39 | }); | |
| 40 | ||
| 41 | const tryAs = (password: string, source: string, username = "sam") => | |
| 42 | verifyPasswordThrottled(app.db, { username, password, source }); | |
| 43 | ||
| 44 | describe("the sign-in windows lock out no one but the guesser", () => { | |
| 45 | test("guessing at the admin from one source shuts that source, not the admin's", async () => { | |
| 46 | for (let i = 0; i < 3; i++) expect((await tryAs(`wrong-${i}`, "198.51.100.7")).ok).toBe(false); | |
| 47 | const shut = await tryAs(PASSWORD, "198.51.100.7"); | |
| 48 | expect(shut.ok ? "signed in" : shut.error.reason).toBe("throttled"); | |
| 49 | // The admin, from where they are, still signs in. | |
| 50 | expect((await tryAs(PASSWORD, "203.0.113.20")).ok).toBe(true); | |
| 51 | }); | |
| 52 | ||
| 53 | test("an IPv6 guesser walking its /64 is still one source", async () => { | |
| 54 | for (let i = 0; i < 3; i++) expect((await tryAs(`wrong-${i}`, `2001:db8:1:2::${i + 1}`)).ok).toBe(false); | |
| 55 | const shut = await tryAs(PASSWORD, "2001:db8:1:2::99"); | |
| 56 | expect(shut.ok ? "signed in" : shut.error.reason).toBe("throttled"); | |
| 57 | }); | |
| 58 | ||
| 59 | test("a flood across many sources and accounts leaves password sign-in open", async () => { | |
| 60 | // More than the old forge-wide window of 200, each source at its own | |
| 61 | // account: counted as wrong guesses are, without 260 decoy hashes. | |
| 62 | for (let i = 0; i < 260; i++) expect(signinWindow(app.db, `nobody${i}`, `10.9.${i >> 8}.${i & 255}`)).toBeUndefined(); | |
| 63 | expect((await tryAs(PASSWORD, "203.0.113.21")).ok).toBe(true); | |
| 64 | }); | |
| 65 | }); | |
| 66 | ||
| 67 | describe("the hash gate bounds the hashing", () => { | |
| 68 | test("at most the in-flight count runs at once; past the queue the attempt is refused", async () => { | |
| 69 | const gate = new HashGate(2, 3); | |
| 70 | let running = 0; | |
| 71 | let peak = 0; | |
| 72 | const releases: (() => void)[] = []; | |
| 73 | const work = () => | |
| 74 | gate.run(async () => { | |
| 75 | running++; | |
| 76 | peak = Math.max(peak, running); | |
| 77 | await new Promise<void>((resolve) => releases.push(resolve)); | |
| 78 | running--; | |
| 79 | return "done"; | |
| 80 | }); | |
| 81 | const admitted = Array.from({ length: 5 }, work); | |
| 82 | // Two run, three wait, the sixth is turned away at once. | |
| 83 | expect(await work()).toBe("busy"); | |
| 84 | while (releases.length > 0 || running > 0) { | |
| 85 | await Bun.sleep(0); | |
| 86 | releases.shift()?.(); | |
| 87 | } | |
| 88 | expect(await Promise.all(admitted)).toEqual(["done", "done", "done", "done", "done"]); | |
| 89 | expect(peak).toBe(2); | |
| 90 | // The slots came back: the gate admits again. | |
| 91 | expect(await gate.run(async () => "again")).toBe("again"); | |
| 92 | }); | |
| 93 | ||
| 94 | test("a slot is given back when the work throws", async () => { | |
| 95 | const gate = new HashGate(1, 0); | |
| 96 | await expect(gate.run(async () => { throw new Error("boom"); })).rejects.toThrow("boom"); | |
| 97 | expect(await gate.run(async () => "ok")).toBe("ok"); | |
| 98 | }); | |
| 99 | ||
| 100 | test("the password gate holds a few 64 MiB hashes, not a flood of them", () => { | |
| 101 | expect(HASHES_IN_FLIGHT).toBeLessThanOrEqual(8); | |
| 102 | expect(HASHES_WAITING).toBeLessThanOrEqual(64); | |
| 103 | }); | |
| 104 | }); | |
| 105 | ||
| 106 | describe("a refusal costs no attempt the person did not make", () => { | |
| 107 | test("an attempt the full hash gate turns away is not counted against the account", async () => { | |
| 108 | // Fill every slot and the whole queue with work that waits. | |
| 109 | const releases: (() => void)[] = []; | |
| 110 | let settled = 0; | |
| 111 | const held = Array.from({ length: HASHES_IN_FLIGHT + HASHES_WAITING }, () => | |
| 112 | passwordHashes.run(() => new Promise<void>((resolve) => releases.push(resolve))).finally(() => settled++), | |
| 113 | ); | |
| 114 | try { | |
| 115 | for (let i = 0; i < 3; i++) { | |
| 116 | const busy = await tryAs(PASSWORD, "192.0.2.40"); | |
| 117 | expect(busy.ok ? "signed in" : busy.error).toEqual({ reason: "throttled", retryAfter: HASH_GATE_RETRY_S }); | |
| 118 | } | |
| 119 | } finally { | |
| 120 | while (settled < held.length) { | |
| 121 | releases.shift()?.(); | |
| 122 | await Bun.sleep(0); | |
| 123 | } | |
| 124 | await Promise.all(held); | |
| 125 | } | |
| 126 | // The account at that source still has every one of its three attempts. | |
| 127 | for (let i = 0; i < 3; i++) { | |
| 128 | const wrong = await tryAs(`wrong-${i}`, "192.0.2.40"); | |
| 129 | expect(wrong.ok ? "signed in" : wrong.error.reason).toBe("bad_credentials"); | |
| 130 | } | |
| 131 | const shut = await tryAs(PASSWORD, "192.0.2.40"); | |
| 132 | expect(shut.ok ? "signed in" : shut.error.reason).toBe("throttled"); | |
| 133 | }); | |
| 134 | ||
| 135 | test("a source refused by its own window keeps the account's window untouched", async () => { | |
| 136 | setLimit(app.db, "signin.per_source", 2, adminId); | |
| 137 | try { | |
| 138 | expect(signinWindow(app.db, "walk1", "192.0.2.50")).toBeUndefined(); | |
| 139 | expect(signinWindow(app.db, "walk2", "192.0.2.50")).toBeUndefined(); | |
| 140 | // The source is spent: sam is refused from here, three times over. | |
| 141 | for (let i = 0; i < 3; i++) expect(signinWindow(app.db, "sam", "192.0.2.50")).toBeNumber(); | |
| 142 | } finally { | |
| 143 | setLimit(app.db, "signin.per_source", 60, adminId); | |
| 144 | } | |
| 145 | // With the source's ceiling raised, sam from there has all three attempts. | |
| 146 | for (let i = 0; i < 3; i++) { | |
| 147 | const wrong = await tryAs(`wrong-${i}`, "192.0.2.50"); | |
| 148 | expect(wrong.ok ? "signed in" : wrong.error.reason).toBe("bad_credentials"); | |
| 149 | } | |
| 150 | const shut = await tryAs(PASSWORD, "192.0.2.50"); | |
| 151 | expect(shut.ok ? "signed in" : shut.error.reason).toBe("throttled"); | |
| 152 | }); | |
| 153 | }); |
test/signin-password-doors.test.ts +20
| @@ -94,6 +94,26 @@ describe("password doors share the sign-in windows", () => { | ||
| 94 | 94 | }); |
| 95 | 95 | }); |
| 96 | 96 | |
| 97 | describe("POST /api/v1/sessions is same-origin (#2922 L1)", () => { | |
| 98 | test("another site cannot sign a browser in: no cookie, no attempt counted", async () => { | |
| 99 | const { url } = await forge(); | |
| 100 | const cross = await fetch(`${url}/api/v1/sessions`, { | |
| 101 | method: "POST", | |
| 102 | headers: { "content-type": "application/json", origin: "https://evil.example" }, | |
| 103 | body: JSON.stringify({ username: "pat", password: PASSWORD }), | |
| 104 | }); | |
| 105 | expect(cross.status).toBe(403); | |
| 106 | expect(cross.headers.get("set-cookie")).toBeNull(); | |
| 107 | const same = await fetch(`${url}/api/v1/sessions`, { | |
| 108 | method: "POST", | |
| 109 | headers: { "content-type": "application/json", origin: new URL(url).origin }, | |
| 110 | body: JSON.stringify({ username: "pat", password: PASSWORD }), | |
| 111 | }); | |
| 112 | expect(same.status).toBe(201); | |
| 113 | expect(same.headers.get("set-cookie")).toContain("forge_session="); | |
| 114 | }); | |
| 115 | }); | |
| 116 | ||
| 97 | 117 | describe("no door verifies a password around the windows", () => { |
| 98 | 118 | test("core/users exports no unthrottled password check", () => { |
| 99 | 119 | expect(Object.keys(users)).not.toContain("verifyPassword"); |
test/signin-throttle.test.ts +1 −1
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | /** |
| 2 | 2 | * Guessing a password is throttled: an account may be tried twenty times a |
| 3 | * minute, the forge two hundred, checked before the hash runs. A refused | |
| 3 | * minute from one source, checked before the hash runs. A refused | |
| 4 | 4 | * attempt answers 429 with Retry-After and is not counted, and the right |
| 5 | 5 | * password still works once the window has slid. |
| 6 | 6 | */ |
test/spawn-anon-ledger.test.ts added +86
| @@ -0,0 +1,86 @@ | ||
| 1 | /** | |
| 2 | * The anonymous spawn limits are kept, not remembered (#2922 M2): a | |
| 3 | * restart is not a fresh allowance, strangers together have a forge-wide | |
| 4 | * ceiling (`spawn.anon_per_forge`), a reservation that made nothing is | |
| 5 | * given back, and a day later the slots come back. | |
| 6 | */ | |
| 7 | ||
| 8 | import { afterEach, describe, expect, test } from "bun:test"; | |
| 9 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 10 | import { tmpdir } from "node:os"; | |
| 11 | import { join } from "node:path"; | |
| 12 | import { createApp, type App } from "../src/app.ts"; | |
| 13 | import { notePeer } from "../src/http/peer.ts"; | |
| 14 | import { setLimit } from "../src/settings/limits.ts"; | |
| 15 | import { ANON_SPAWNS_PER_DAY, reserveAnonSpawn } from "../src/spawn/rate.ts"; | |
| 16 | ||
| 17 | let dir = ""; | |
| 18 | const opened: App[] = []; | |
| 19 | ||
| 20 | afterEach(async () => { | |
| 21 | for (const app of opened.splice(0)) app.close(); | |
| 22 | await rm(dir, { recursive: true, force: true }); | |
| 23 | }); | |
| 24 | ||
| 25 | async function forge(): Promise<App> { | |
| 26 | dir = await mkdtemp(join(tmpdir(), "anon-ledger-")); | |
| 27 | return open(); | |
| 28 | } | |
| 29 | ||
| 30 | function open(): App { | |
| 31 | const app = createApp({ dataDir: dir, port: 0 }); | |
| 32 | opened.push(app); | |
| 33 | return app; | |
| 34 | } | |
| 35 | ||
| 36 | const from = (address: string): Request => { | |
| 37 | const request = new Request("http://forge.test/api/v1/forges", { method: "POST" }); | |
| 38 | notePeer(request, address); | |
| 39 | return request; | |
| 40 | }; | |
| 41 | ||
| 42 | describe("the anonymous spawn ledger", () => { | |
| 43 | test("a restart does not hand a stranger a fresh allowance", async () => { | |
| 44 | const app = await forge(); | |
| 45 | for (let i = 0; i < ANON_SPAWNS_PER_DAY; i++) expect(reserveAnonSpawn(app.db, from("198.51.100.4")).allowed).toBe(true); | |
| 46 | app.close(); | |
| 47 | opened.splice(0); | |
| 48 | const again = open(); | |
| 49 | const refused = reserveAnonSpawn(again.db, from("198.51.100.4")); | |
| 50 | expect(refused.allowed).toBe(false); | |
| 51 | if (!refused.allowed) expect(refused.scope).toBe("client"); | |
| 52 | // Another stranger still has theirs. | |
| 53 | expect(reserveAnonSpawn(again.db, from("198.51.100.5")).allowed).toBe(true); | |
| 54 | }); | |
| 55 | ||
| 56 | test("strangers together stop at the forge-wide ceiling", async () => { | |
| 57 | const app = await forge(); | |
| 58 | setLimit(app.db, "spawn.anon_per_forge", 4, "setup"); | |
| 59 | for (let i = 0; i < 4; i++) expect(reserveAnonSpawn(app.db, from(`10.0.0.${i + 1}`)).allowed).toBe(true); | |
| 60 | const refused = reserveAnonSpawn(app.db, from("10.0.0.99")); | |
| 61 | expect(refused.allowed).toBe(false); | |
| 62 | if (!refused.allowed) { | |
| 63 | expect(refused.scope).toBe("forge"); | |
| 64 | expect(refused.limit).toBe(4); | |
| 65 | } | |
| 66 | }); | |
| 67 | ||
| 68 | test("a reservation that made nothing is given back", async () => { | |
| 69 | const app = await forge(); | |
| 70 | for (let i = 0; i < 10; i++) { | |
| 71 | const slot = reserveAnonSpawn(app.db, from("203.0.113.3")); | |
| 72 | expect(slot.allowed).toBe(true); | |
| 73 | if (slot.allowed) slot.release(); | |
| 74 | } | |
| 75 | }); | |
| 76 | ||
| 77 | test("a day later the slots come back", async () => { | |
| 78 | const app = await forge(); | |
| 79 | const start = Date.parse("2026-10-19T00:00:00Z"); | |
| 80 | for (let i = 0; i < ANON_SPAWNS_PER_DAY; i++) reserveAnonSpawn(app.db, from("192.0.2.8"), start); | |
| 81 | const shut = reserveAnonSpawn(app.db, from("192.0.2.8"), start + 1000); | |
| 82 | expect(shut.allowed).toBe(false); | |
| 83 | if (!shut.allowed) expect(shut.resetsAt).toBe(new Date(start + 86_400_000).toISOString()); | |
| 84 | expect(reserveAnonSpawn(app.db, from("192.0.2.8"), start + 86_400_001).allowed).toBe(true); | |
| 85 | }); | |
| 86 | }); |
test/spawn-anon.test.ts +24 −2
| @@ -12,6 +12,7 @@ import { createApp, type App } from "../src/app.ts"; | ||
| 12 | 12 | import { commitToBranch, createRepo } from "../src/actions/repos.ts"; |
| 13 | 13 | import { usePlacement, useProbe } from "../src/spawn/door.ts"; |
| 14 | 14 | import { resetAnonSpawns } from "../src/spawn/rate.ts"; |
| 15 | import { setStrangerLimits } from "../src/http/strangers.ts"; | |
| 15 | 16 | import { createToken } from "../src/core/tokens.ts"; |
| 16 | 17 | import { createUser } from "../src/core/users.ts"; |
| 17 | 18 | import { serve, type Servers } from "../src/http/server.ts"; |
| @@ -39,7 +40,6 @@ describe("anonymous spawn", () => { | ||
| 39 | 40 | |
| 40 | 41 | beforeAll(async () => { |
| 41 | 42 | dataDir = await mkdtemp(join(tmpdir(), "forge-spawn-anon-")); |
| 42 | resetAnonSpawns(); | |
| 43 | 43 | app = createApp({ dataDir, port: 0, forgeRepo: "alice/forge-code" }); |
| 44 | 44 | servers = await serve(app); |
| 45 | 45 | base = servers.url; |
| @@ -164,7 +164,7 @@ describe("anonymous spawn", () => { | ||
| 164 | 164 | // A dry run is free: the plan still comes back. |
| 165 | 165 | const dry = await post({ name: "kid5" }); |
| 166 | 166 | expect(dry.status).toBe(200); |
| 167 | resetAnonSpawns(); | |
| 167 | resetAnonSpawns(app.db); | |
| 168 | 168 | }); |
| 169 | 169 | |
| 170 | 170 | test("a signed-in spawn still works (regression)", async () => { |
| @@ -183,4 +183,26 @@ describe("anonymous spawn", () => { | ||
| 183 | 183 | } |
| 184 | 184 | expect(await readdir(join(dataDir, "children")).catch(() => [])).toHaveLength(4); |
| 185 | 185 | }); |
| 186 | ||
| 187 | test("a spawn that makes nothing does not use up a stranger's daily slot", async () => { | |
| 188 | resetAnonSpawns(app.db); | |
| 189 | // The tests above spent this minute's plans; this one is about the day's slots. | |
| 190 | setStrangerLimits(app, {}); | |
| 191 | for (let i = 0; i < 3; i++) { | |
| 192 | // The same plan again: the child already exists, so nothing is made. | |
| 193 | const again = await post({ name: "kid", apps: ["alice/notes"], dryRun: false }); | |
| 194 | expect(again.status).toBe(200); | |
| 195 | // Another plan under a taken name: refused, so nothing is made. | |
| 196 | const taken = await post({ name: "kid", dryRun: false }); | |
| 197 | expect(taken.status).not.toBe(201); | |
| 198 | expect(taken.status).not.toBe(429); | |
| 199 | } | |
| 200 | // All three of the day's slots are still there. | |
| 201 | for (const name of ["kid6", "kid7", "kid8"]) { | |
| 202 | const res = await post({ name, dryRun: false }); | |
| 203 | expect(res.status).toBe(201); | |
| 204 | } | |
| 205 | expect((await post({ name: "kid9", dryRun: false })).status).toBe(429); | |
| 206 | resetAnonSpawns(app.db); | |
| 207 | }); | |
| 186 | 208 | }); |
The refund is right, but if you delete it no test fails. Add a test where a source is refused by
signin.per_sourceand then shows its per-account window untouched.