Public: anyone can read this; the crew can change it.
Password sign-in limits cannot be used to lock everyone out or to grow memory without bound #14924
Check · Review · Land · Live done — Landed and live in production.
torque/forge:torque/14907-password-sign-in-limits-cannot-be-used-t → main 3 commits fork
7 files
changed +386
−48
scripts/unused-exports-allow.json +1
| @@ -50,6 +50,7 @@ | ||
| 50 | 50 | "src/core/search.ts grepCount", |
| 51 | 51 | "src/core/search.ts grepRepo", |
| 52 | 52 | "src/core/sessions.ts sessionUser", |
| 53 | "src/core/signin-window.ts signinKeyCount", | |
| 53 | 54 | "src/core/starts.ts startOfAccount", |
| 54 | 55 | "src/core/subscriptions.ts listAllGrants", |
| 55 | 56 | "src/core/team-metrics.ts keptFigures", |
src/core/ratelimit.ts +32 −3
| @@ -45,6 +45,12 @@ export interface RateLimits { | ||
| 45 | 45 | readonly enabled: boolean; |
| 46 | 46 | /** The window's length, for a limit counted over more than a minute. */ |
| 47 | 47 | readonly windowMs?: number; |
| 48 | /** | |
| 49 | * The most keys tracked at once. Past it the least recently counted key is | |
| 50 | * forgotten, so memory stays bounded however many keys a caller invents. | |
| 51 | * Unset: bounded only by the sweep. | |
| 52 | */ | |
| 53 | readonly maxKeys?: number; | |
| 48 | 54 | } |
| 49 | 55 | |
| 50 | 56 | /** |
| @@ -137,7 +143,9 @@ export class RateLimiter { | ||
| 137 | 143 | if (live.length >= limit) { |
| 138 | 144 | const oldest = live[0] ?? at; |
| 139 | 145 | const waitMs = Math.max(0, oldest + this.windowMs - at); |
| 140 | this.hits.set(key, live); | |
| 146 | // A refused take counts nothing, so it creates no key either. | |
| 147 | if (live.length > 0) this.touch(key, live); | |
| 148 | else this.hits.delete(key); | |
| 141 | 149 | return { |
| 142 | 150 | allowed: false, |
| 143 | 151 | limit, |
| @@ -148,7 +156,7 @@ export class RateLimiter { | ||
| 148 | 156 | } |
| 149 | 157 | |
| 150 | 158 | live.push(at); |
| 151 | this.hits.set(key, live); | |
| 159 | this.touch(key, live); | |
| 152 | 160 | return { |
| 153 | 161 | allowed: true, |
| 154 | 162 | limit, |
| @@ -165,8 +173,10 @@ export class RateLimiter { | ||
| 165 | 173 | */ |
| 166 | 174 | refund(key: string): void { |
| 167 | 175 | const times = this.hits.get(key); |
| 168 | if (times === undefined || times.length === 0) return; | |
| 176 | if (times === undefined) return; | |
| 169 | 177 | times.pop(); |
| 178 | // An emptied key is forgotten, so a refund leaves nothing behind. | |
| 179 | if (times.length === 0) this.hits.delete(key); | |
| 170 | 180 | } |
| 171 | 181 | |
| 172 | 182 | /** Forget every request counted on `key`: its window starts empty. */ |
| @@ -174,6 +184,25 @@ export class RateLimiter { | ||
| 174 | 184 | this.hits.delete(key); |
| 175 | 185 | } |
| 176 | 186 | |
| 187 | /** | |
| 188 | * Store `key`'s hits as its most recent use (a Map keeps insertion order, | |
| 189 | * so re-inserting moves it to the end), and past `maxKeys` forget the least | |
| 190 | * recently counted: the first in the Map's order, so one take at the cap | |
| 191 | * deletes one key and scans none. Expired keys still go on the sweep's | |
| 192 | * interval; they are the oldest too, so they are the ones evicted first. | |
| 193 | */ | |
| 194 | private touch(key: string, live: number[]): void { | |
| 195 | this.hits.delete(key); | |
| 196 | const cap = this.limits.maxKeys; | |
| 197 | if (cap !== undefined && this.hits.size >= cap) { | |
| 198 | for (const oldest of this.hits.keys()) { | |
| 199 | if (this.hits.size < cap) break; | |
| 200 | this.hits.delete(oldest); | |
| 201 | } | |
| 202 | } | |
| 203 | this.hits.set(key, live); | |
| 204 | } | |
| 205 | ||
| 177 | 206 | /** |
| 178 | 207 | * Forget keys whose whole window has passed. Without this the map grows by |
| 179 | 208 | * one entry per token that ever spoke to the forge — small, but unbounded |
src/core/signin-window.ts +138 −39
| @@ -22,18 +22,54 @@ | ||
| 22 | 22 | * so a guesser learns nothing from which answers are 429. A right password |
| 23 | 23 | * clears it. Keyed by account *and* source like the minute window, so a |
| 24 | 24 | * stranger fills only their own and the owner, elsewhere, is never locked out. |
| 25 | * | |
| 26 | * Neither lockout nor memory is for sale (#14907). The source's window is | |
| 27 | * checked first, so a source past its ceiling creates no key for any | |
| 28 | * account; the account name in a key is cut to `KEY_NAME_MAX`; a refund that | |
| 29 | * empties a key deletes it; every limiter holds at most `MAX_KEYS`. And a | |
| 30 | * source that proved a right password in the last `GOOD_SOURCE_MS` is not | |
| 31 | * refused by the forge-wide window alone: a handful of sources flooding it | |
| 32 | * shuts out strangers, never the people who signed in today. | |
| 25 | 33 | */ |
| 26 | 34 | |
| 27 | 35 | import type { Database } from "bun:sqlite"; |
| 28 | import { RateLimiter } from "./ratelimit.ts"; | |
| 36 | import { RateLimiter, type RateLimits } from "./ratelimit.ts"; | |
| 29 | 37 | import { bucketOf } from "../http/peer.ts"; |
| 30 | 38 | import { limitValue } from "../settings/limits.ts"; |
| 39 | import { perOwner } from "../kernel/per_owner.ts"; | |
| 31 | 40 | |
| 32 | 41 | const accounts = new WeakMap<Database, RateLimiter>(); |
| 33 | 42 | // The third window, by the socket's peer: a source trying many accounts. |
| 34 | 43 | const sources = new WeakMap<Database, RateLimiter>(); |
| 35 | 44 | // The slow window: wrong passwords at one account from one source. |
| 36 | 45 | const failures = new WeakMap<Database, RateLimiter>(); |
| 46 | // Sources that proved a right password: bucket → when, oldest first. | |
| 47 | const goodSources = new WeakMap<Database, Map<string, number>>(); | |
| 48 | // The clock the last attempt at a database read, so a test can move time. | |
| 49 | const clocks = new WeakMap<Database, () => number>(); | |
| 50 | ||
| 51 | /** | |
| 52 | * Keys one sign-in limiter tracks at most. A key is a few hundred bytes (a | |
| 53 | * short name and at most `signin.per_account` timestamps), so this is ~20 MB | |
| 54 | * at the worst. At the default limits the forge-wide window (200 a minute) | |
| 55 | * lets at most 2,000 keys live in the ten-minute slow window, so 50,000 is | |
| 56 | * twenty-five times the steady state: a real forge never reaches it, and a | |
| 57 | * flood that does evicts its own least recent keys first. | |
| 58 | */ | |
| 59 | export const MAX_KEYS = 50_000; | |
| 60 | /** | |
| 61 | * Characters of the account name kept in a key. Usernames are at most 40 | |
| 62 | * (`core/chapters.ts` `NAME`), so no real account shares a key; a longer | |
| 63 | * name names no one, and every such name sharing one key costs nothing. | |
| 64 | */ | |
| 65 | export const KEY_NAME_MAX = 64; | |
| 66 | /** | |
| 67 | * How long a right password vouches for its source: a day, so someone who | |
| 68 | * signed in this morning is let past a forge-wide flood this afternoon. | |
| 69 | */ | |
| 70 | export const GOOD_SOURCE_MS = 24 * 60 * 60_000; | |
| 71 | /** Sources remembered as good at most; past it the oldest is forgotten. */ | |
| 72 | export const MAX_GOOD_SOURCES = 10_000; | |
| 37 | 73 | |
| 38 | 74 | /** |
| 39 | 75 | * Wrong passwords one account may take from one source in `FAILURES_WINDOW_MS`: more than a person |
| @@ -46,27 +82,62 @@ export const FAILURES_PER_ACCOUNT = 8; | ||
| 46 | 82 | */ |
| 47 | 83 | export const FAILURES_WINDOW_MS = 10 * 60_000; |
| 48 | 84 | |
| 49 | function limiterOf(map: WeakMap<Database, RateLimiter>, db: Database): RateLimiter { | |
| 50 | let limiter = map.get(db); | |
| 51 | if (limiter === undefined) { | |
| 52 | limiter = new RateLimiter({ perMinute: 0, adminPerMinute: 0, enabled: true }); | |
| 53 | map.set(db, limiter); | |
| 54 | } | |
| 85 | /** Milliseconds now, by the clock the latest attempt at `db` was given. */ | |
| 86 | function nowOf(db: Database): number { | |
| 87 | return (clocks.get(db) ?? Date.now)(); | |
| 88 | } | |
| 89 | ||
| 90 | function limiterOf(map: WeakMap<Database, RateLimiter>, db: Database, limits: RateLimits): RateLimiter { | |
| 91 | const limiter = perOwner(map, db, () => new RateLimiter(limits, () => nowOf(db))); | |
| 92 | // Read on every attempt, so a change on /admin/limits governs the next one. | |
| 93 | limiter.setLimits(limits); | |
| 55 | 94 | return limiter; |
| 56 | 95 | } |
| 57 | 96 | |
| 58 | function failuresOf(db: Database): RateLimiter { | |
| 59 | let limiter = failures.get(db); | |
| 60 | if (limiter === undefined) { | |
| 61 | limiter = new RateLimiter({ | |
| 62 | perMinute: FAILURES_PER_ACCOUNT, | |
| 63 | adminPerMinute: 0, | |
| 64 | enabled: true, | |
| 65 | windowMs: FAILURES_WINDOW_MS, | |
| 66 | }); | |
| 67 | failures.set(db, limiter); | |
| 97 | function goodOf(db: Database): Map<string, number> { | |
| 98 | return perOwner(goodSources, db, () => new Map()); | |
| 99 | } | |
| 100 | ||
| 101 | /** Remember that `bucket` proved a right password now; past `cap`, forget the oldest. */ | |
| 102 | function vouch(db: Database, bucket: string, cap: number): void { | |
| 103 | const good = goodOf(db); | |
| 104 | good.delete(bucket); | |
| 105 | good.set(bucket, nowOf(db)); | |
| 106 | for (const oldest of good.keys()) { | |
| 107 | if (good.size <= cap) break; | |
| 108 | good.delete(oldest); | |
| 68 | 109 | } |
| 69 | return limiter; | |
| 110 | } | |
| 111 | ||
| 112 | /** Whether `bucket` proved a right password within `GOOD_SOURCE_MS`. */ | |
| 113 | function vouched(db: Database, bucket: string): boolean { | |
| 114 | const at = goodOf(db).get(bucket); | |
| 115 | if (at === undefined) return false; | |
| 116 | if (nowOf(db) - at < GOOD_SOURCE_MS) return true; | |
| 117 | goodOf(db).delete(bucket); | |
| 118 | return false; | |
| 119 | } | |
| 120 | ||
| 121 | /** | |
| 122 | * Keys the sign-in limiters of `db` hold, every window together: for the | |
| 123 | * test that no attempt leaves more behind than it should. | |
| 124 | */ | |
| 125 | export function signinKeyCount(db: Database): number { | |
| 126 | return [accounts, sources, failures].reduce((sum, map) => sum + (map.get(db)?.size ?? 0), 0); | |
| 127 | } | |
| 128 | ||
| 129 | /** How one attempt is counted. */ | |
| 130 | export interface SigninOptions { | |
| 131 | /** `false`: the operator's door, not counted in the forge-wide window. */ | |
| 132 | readonly forgeWide?: boolean; | |
| 133 | /** `false`: a door that cannot say the secret was wrong; no slow window. */ | |
| 134 | readonly failures?: boolean; | |
| 135 | /** Milliseconds now; `Date.now` unless a test moves time. */ | |
| 136 | readonly now?: () => number; | |
| 137 | /** Keys each limiter holds at most; `MAX_KEYS` unless a test makes it reachable. */ | |
| 138 | readonly maxKeys?: number; | |
| 139 | /** Good sources remembered at most; `MAX_GOOD_SOURCES` unless a test makes it reachable. */ | |
| 140 | readonly maxGoodSources?: number; | |
| 70 | 141 | } |
| 71 | 142 | |
| 72 | 143 | /** The answer to one attempt: refused with a wait, or let through. */ |
| @@ -97,43 +168,70 @@ export function admitSignin( | ||
| 97 | 168 | db: Database, |
| 98 | 169 | account: string, |
| 99 | 170 | address: string, |
| 100 | options: { readonly forgeWide?: boolean; readonly failures?: boolean } = {}, | |
| 171 | options: SigninOptions = {}, | |
| 101 | 172 | ): SigninAdmission { |
| 102 | const limiter = limiterOf(accounts, db); | |
| 103 | // Read on every attempt, so a change on /admin/limits governs the next one. | |
| 104 | limiter.setLimits({ | |
| 173 | clocks.set(db, options.now ?? Date.now); | |
| 174 | const maxKeys = options.maxKeys ?? MAX_KEYS; | |
| 175 | const maxGood = options.maxGoodSources ?? MAX_GOOD_SOURCES; | |
| 176 | const limiter = limiterOf(accounts, db, { | |
| 105 | 177 | perMinute: limitValue(db, "signin.per_account"), |
| 106 | 178 | adminPerMinute: limitValue(db, "signin.per_forge"), |
| 107 | 179 | enabled: true, |
| 180 | maxKeys, | |
| 108 | 181 | }); |
| 182 | const bucket = bucketOf(address); | |
| 183 | // The source first: a source past its ceiling creates no key for any | |
| 184 | // account, so naming account after account grows nothing. | |
| 185 | const peers = limiterOf(sources, db, { | |
| 186 | perMinute: limitValue(db, "signin.per_source"), | |
| 187 | adminPerMinute: 0, | |
| 188 | enabled: true, | |
| 189 | maxKeys, | |
| 190 | }); | |
| 191 | const sourceKey = `source:${bucket}`; | |
| 192 | const source = peers.take(sourceKey, "ro"); | |
| 193 | if (!source.allowed) return { admitted: false, retryAfter: source.retryAfter }; | |
| 109 | 194 | // By account *and* source: a stranger spamming "admin" fills only their |
| 110 | 195 | // own window, never the owner's, so guessing cannot be turned into a lockout. |
| 111 | const accountKey = `account:${account.toLowerCase()}|${bucketOf(address)}`; | |
| 112 | // The one key first: a key already refused must not spend the forge's budget. | |
| 113 | // The slow window first, so an account shut there spends no minute budget. | |
| 114 | const slow = options.failures === false ? undefined : failuresOf(db); | |
| 115 | if (slow !== undefined) { | |
| 116 | const failed = slow.take(accountKey, "ro"); | |
| 117 | if (!failed.allowed) return { admitted: false, retryAfter: failed.retryAfter }; | |
| 118 | } | |
| 196 | const accountKey = `account:${account.toLowerCase().slice(0, KEY_NAME_MAX)}|${bucket}`; | |
| 197 | // Each refusal gives back what was already counted, newest first. | |
| 198 | const taken: (() => void)[] = [() => peers.refund(sourceKey)]; | |
| 119 | 199 | const refused = (retryAfter: number): SigninAdmission => { |
| 120 | // A refused attempt is not counted, in the slow window either. | |
| 121 | slow?.refund(accountKey); | |
| 200 | for (const giveBack of taken.reverse()) giveBack(); | |
| 122 | 201 | return { admitted: false, retryAfter }; |
| 123 | 202 | }; |
| 203 | // The slow window next, so an account shut there spends no minute budget. | |
| 204 | const slow = | |
| 205 | options.failures === false | |
| 206 | ? undefined | |
| 207 | : limiterOf(failures, db, { | |
| 208 | perMinute: FAILURES_PER_ACCOUNT, | |
| 209 | adminPerMinute: 0, | |
| 210 | enabled: true, | |
| 211 | windowMs: FAILURES_WINDOW_MS, | |
| 212 | maxKeys, | |
| 213 | }); | |
| 214 | if (slow !== undefined) { | |
| 215 | const failed = slow.take(accountKey, "ro"); | |
| 216 | if (!failed.allowed) return refused(failed.retryAfter); | |
| 217 | // A refused attempt is not counted, in the slow window either. | |
| 218 | taken.push(() => slow.refund(accountKey)); | |
| 219 | } | |
| 220 | // The one key before the forge's: a key already refused must not spend the forge's budget. | |
| 124 | 221 | const one = limiter.take(accountKey, "ro"); |
| 125 | 222 | if (!one.allowed) return refused(one.retryAfter); |
| 126 | const peers = limiterOf(sources, db); | |
| 127 | peers.setLimits({ perMinute: limitValue(db, "signin.per_source"), adminPerMinute: 0, enabled: true }); | |
| 128 | const sourceKey = `source:${bucketOf(address)}`; | |
| 129 | const source = peers.take(sourceKey, "ro"); | |
| 130 | if (!source.allowed) return refused(source.retryAfter); | |
| 223 | taken.push(() => limiter.refund(accountKey)); | |
| 131 | 224 | // The operator's door (a passkey: a signature cannot be guessed) skips the |
| 132 | 225 | // forge-wide window, so a flood of password guesses cannot lock it out. |
| 133 | const counted = options.forgeWide !== false; | |
| 226 | // A source with a right password today is let past a full forge window | |
| 227 | // too, uncounted, still held by its own and its account's windows. | |
| 228 | let counted = options.forgeWide !== false; | |
| 134 | 229 | if (counted) { |
| 135 | 230 | const whole = limiter.take("forge", "admin"); |
| 136 | if (!whole.allowed) return refused(whole.retryAfter); | |
| 231 | if (!whole.allowed) { | |
| 232 | if (!vouched(db, bucket)) return refused(whole.retryAfter); | |
| 233 | counted = false; | |
| 234 | } | |
| 137 | 235 | } |
| 138 | 236 | const giveBack = () => { |
| 139 | 237 | limiter.refund(accountKey); |
| @@ -145,6 +243,7 @@ export function admitSignin( | ||
| 145 | 243 | succeeded: () => { |
| 146 | 244 | giveBack(); |
| 147 | 245 | slow?.forget(accountKey); |
| 246 | vouch(db, bucket, maxGood); | |
| 148 | 247 | }, |
| 149 | 248 | notJudged: () => { |
| 150 | 249 | giveBack(); |
src/kernel/per_owner.ts added +14
| @@ -0,0 +1,14 @@ | ||
| 1 | /** | |
| 2 | * State kept per owner (a database, an app) in a WeakMap, made on first use: | |
| 3 | * the owner's going frees it, and a test's owner never shares another's. | |
| 4 | */ | |
| 5 | ||
| 6 | /** The value `owner` holds in `map`, made by `make` and kept the first time. */ | |
| 7 | export function perOwner<K extends object, V>(map: WeakMap<K, V>, owner: K, make: () => V): V { | |
| 8 | let value = map.get(owner); | |
| 9 | if (value === undefined) { | |
| 10 | value = make(); | |
| 11 | map.set(owner, value); | |
| 12 | } | |
| 13 | return value; | |
| 14 | } |
src/machines/shell.ts +2 −6
| @@ -40,6 +40,7 @@ import { reachableApps, type Machine } from "../crew/machines.ts"; | ||
| 40 | 40 | import { ownApp, ownAppUrls } from "../crew/app_hosts.ts"; |
| 41 | 41 | import { limitValue } from "../settings/limits.ts"; |
| 42 | 42 | import { id as newId } from "../kernel/id.ts"; |
| 43 | import { perOwner } from "../kernel/per_owner.ts"; | |
| 43 | 44 | import { readFileAt } from "../apps/checkout.ts"; |
| 44 | 45 | import { parseManifest } from "../apps/manifest.ts"; |
| 45 | 46 | import { resolveOid } from "../git/merge.ts"; |
| @@ -347,12 +348,7 @@ export function shellOptions(app: App): ShellOptions | undefined { | ||
| 347 | 348 | } |
| 348 | 349 | |
| 349 | 350 | function sessionsOf(app: App): Map<string, Session> { |
| 350 | let map = sessions.get(app); | |
| 351 | if (map === undefined) { | |
| 352 | map = new Map(); | |
| 353 | sessions.set(app, map); | |
| 354 | } | |
| 355 | return map; | |
| 351 | return perOwner(sessions, app, () => new Map()); | |
| 356 | 352 | } |
| 357 | 353 | |
| 358 | 354 | /** The sessions running now. */ |
test/ratelimit.test.ts +65
| @@ -223,3 +223,68 @@ describe("limitsFromEnv", () => { | ||
| 223 | 223 | ).toBe(50); |
| 224 | 224 | }); |
| 225 | 225 | }); |
| 226 | ||
| 227 | describe("RateLimiter keys stay bounded (#14907)", () => { | |
| 228 | test("a refund that empties a key deletes it", () => { | |
| 229 | const { limiter } = clocked({ perMinute: 3 }); | |
| 230 | limiter.take("k", "ro"); | |
| 231 | limiter.refund("k"); | |
| 232 | expect(limiter.has("k")).toBe(false); | |
| 233 | expect(limiter.size).toBe(0); | |
| 234 | }); | |
| 235 | ||
| 236 | test("a refused take on a key with nothing counted creates no key", () => { | |
| 237 | const { limiter } = clocked({ perMinute: 0 }); | |
| 238 | expect(limiter.take("k", "ro").allowed).toBe(false); | |
| 239 | expect(limiter.has("k")).toBe(false); | |
| 240 | }); | |
| 241 | ||
| 242 | test("past maxKeys the least recently counted key is forgotten", () => { | |
| 243 | const { clock, limiter } = clocked({ perMinute: 3, maxKeys: 3 }); | |
| 244 | for (const key of ["a", "b", "c"]) { | |
| 245 | clock.at += 1; | |
| 246 | limiter.take(key, "ro"); | |
| 247 | } | |
| 248 | clock.at += 1; | |
| 249 | limiter.take("a", "ro"); // a is now the most recent | |
| 250 | clock.at += 1; | |
| 251 | limiter.take("d", "ro"); | |
| 252 | expect(limiter.size).toBe(3); | |
| 253 | expect(limiter.has("b")).toBe(false); | |
| 254 | expect(limiter.has("a")).toBe(true); | |
| 255 | expect(limiter.has("d")).toBe(true); | |
| 256 | for (let i = 0; i < 1_000; i++) limiter.take(`k${i}`, "ro"); | |
| 257 | expect(limiter.size).toBe(3); | |
| 258 | }); | |
| 259 | ||
| 260 | test("at maxKeys, keys whose window passed go before any live one", () => { | |
| 261 | const { clock, limiter } = clocked({ perMinute: 3, maxKeys: 2 }); | |
| 262 | limiter.take("old", "ro"); | |
| 263 | clock.at = 70_000; | |
| 264 | limiter.take("live", "ro"); | |
| 265 | clock.at = 70_001; | |
| 266 | limiter.take("new", "ro"); | |
| 267 | expect(limiter.has("old")).toBe(false); | |
| 268 | expect(limiter.has("live")).toBe(true); | |
| 269 | }); | |
| 270 | ||
| 271 | test("a take at maxKeys evicts the one oldest key and sweeps no earlier than its interval", () => { | |
| 272 | const { clock, limiter } = clocked({ perMinute: 3, maxKeys: 4 }); | |
| 273 | for (const key of ["x", "y", "z"]) { | |
| 274 | clock.at += 1; | |
| 275 | limiter.take(key, "ro"); | |
| 276 | } | |
| 277 | clock.at = 60_000; // the sweep runs here, and is next due at 120 000 | |
| 278 | limiter.take("w", "ro"); | |
| 279 | clock.at = 100_000; // x, y and z have expired; the sweep is not due | |
| 280 | limiter.take("v", "ro"); | |
| 281 | // One key went, the oldest; the rest wait for the sweep, not a scan per take. | |
| 282 | expect(limiter.has("x")).toBe(false); | |
| 283 | expect(limiter.has("y")).toBe(true); | |
| 284 | expect(limiter.size).toBe(4); | |
| 285 | clock.at = 120_000; | |
| 286 | limiter.take("u", "ro"); | |
| 287 | expect(limiter.has("y")).toBe(false); | |
| 288 | expect(limiter.has("z")).toBe(false); | |
| 289 | }); | |
| 290 | }); |
test/signin-window-bounds.test.ts added +134
| @@ -0,0 +1,134 @@ | ||
| 1 | /** | |
| 2 | * The sign-in windows cannot be turned into a lockout or a memory leak | |
| 3 | * (#14907): the source is checked before any account key exists, the name in | |
| 4 | * a key is cut short, an emptied key is deleted, and a source with a right | |
| 5 | * password today is not refused by the forge-wide window alone. | |
| 6 | */ | |
| 7 | import { afterEach, beforeEach, expect, test } from "bun:test"; | |
| 8 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 9 | import { tmpdir } from "node:os"; | |
| 10 | import { join } from "node:path"; | |
| 11 | import { createApp, type App } from "../src/app.ts"; | |
| 12 | import { admitSignin, GOOD_SOURCE_MS, KEY_NAME_MAX, signinKeyCount } from "../src/core/signin-window.ts"; | |
| 13 | ||
| 14 | let dataDir = ""; | |
| 15 | let app: App; | |
| 16 | beforeEach(async () => { | |
| 17 | dataDir = await mkdtemp(join(tmpdir(), "forge-window-bounds-")); | |
| 18 | app = createApp({ dataDir, port: 0 }); | |
| 19 | }); | |
| 20 | afterEach(async () => { | |
| 21 | app.close(); | |
| 22 | await rm(dataDir, { recursive: true, force: true }); | |
| 23 | }); | |
| 24 | ||
| 25 | const minuteOnly = { failures: false } as const; | |
| 26 | ||
| 27 | test("a source past its window creates no key for the accounts it names", () => { | |
| 28 | for (let i = 0; i < 60; i++) admitSignin(app.db, `user${i}`, "198.51.100.7"); | |
| 29 | const before = signinKeyCount(app.db); | |
| 30 | for (let i = 0; i < 500; i++) { | |
| 31 | expect(admitSignin(app.db, `other${i}`, "198.51.100.7").admitted).toBe(false); | |
| 32 | } | |
| 33 | expect(signinKeyCount(app.db)).toBe(before); | |
| 34 | }); | |
| 35 | ||
| 36 | test("the account name in a key is cut short, so a long name buys no key of its own", () => { | |
| 37 | const stem = "x".repeat(KEY_NAME_MAX); | |
| 38 | for (let i = 0; i < 20; i++) { | |
| 39 | expect(admitSignin(app.db, `${stem}${"a".repeat(5_000)}${i}`, "203.0.113.4", minuteOnly).admitted).toBe(true); | |
| 40 | } | |
| 41 | // Twenty different names, one key: the twenty-first is refused. | |
| 42 | expect(admitSignin(app.db, `${stem}b`, "203.0.113.4", minuteOnly).admitted).toBe(false); | |
| 43 | }); | |
| 44 | ||
| 45 | test("an attempt given back leaves no key behind", () => { | |
| 46 | const right = admitSignin(app.db, "carol", "203.0.113.5"); | |
| 47 | if (!right.admitted) throw new Error("refused"); | |
| 48 | right.succeeded(); | |
| 49 | const unjudged = admitSignin(app.db, "dave", "203.0.113.6", minuteOnly); | |
| 50 | if (!unjudged.admitted) throw new Error("refused"); | |
| 51 | unjudged.notJudged(); | |
| 52 | expect(signinKeyCount(app.db)).toBe(0); | |
| 53 | }); | |
| 54 | ||
| 55 | test("a refusal by the forge-wide window gives back the account and source keys it took", () => { | |
| 56 | // Fill the forge's two hundred from four sources of fifty each. | |
| 57 | for (let s = 0; s < 4; s++) { | |
| 58 | for (let i = 0; i < 50; i++) admitSignin(app.db, `u${i}`, `192.0.2.${s + 1}`, minuteOnly); | |
| 59 | } | |
| 60 | const before = signinKeyCount(app.db); | |
| 61 | for (let i = 0; i < 50; i++) { | |
| 62 | expect(admitSignin(app.db, `late${i}`, "192.0.2.99", minuteOnly).admitted).toBe(false); | |
| 63 | } | |
| 64 | expect(signinKeyCount(app.db)).toBe(before); | |
| 65 | }); | |
| 66 | ||
| 67 | test("a source with a right password today is not refused by the forge-wide window alone", () => { | |
| 68 | const morning = admitSignin(app.db, "alice", "203.0.113.50"); | |
| 69 | if (!morning.admitted) throw new Error("refused"); | |
| 70 | morning.succeeded(); | |
| 71 | for (let s = 0; s < 4; s++) { | |
| 72 | for (let i = 0; i < 50; i++) admitSignin(app.db, `u${i}`, `192.0.2.${s + 1}`, minuteOnly); | |
| 73 | } | |
| 74 | // A stranger is refused by the full forge window … | |
| 75 | expect(admitSignin(app.db, "alice", "203.0.113.99").admitted).toBe(false); | |
| 76 | // … the source that signed in this morning is not. | |
| 77 | expect(admitSignin(app.db, "alice", "203.0.113.50").admitted).toBe(true); | |
| 78 | }); | |
| 79 | ||
| 80 | /** Fill the forge's two hundred a minute from four sources of fifty each. */ | |
| 81 | function fillForge(options: Parameters<typeof admitSignin>[3] = {}): void { | |
| 82 | for (let s = 0; s < 4; s++) { | |
| 83 | for (let i = 0; i < 50; i++) admitSignin(app.db, `u${i}`, `192.0.2.${s + 1}`, { ...minuteOnly, ...options }); | |
| 84 | } | |
| 85 | } | |
| 86 | ||
| 87 | function signIn(account: string, address: string, options: Parameters<typeof admitSignin>[3] = {}): void { | |
| 88 | const right = admitSignin(app.db, account, address, options); | |
| 89 | if (!right.admitted) throw new Error(`refused: ${account} from ${address}`); | |
| 90 | right.succeeded(); | |
| 91 | } | |
| 92 | ||
| 93 | test("a source that is not good meets a full forge window, and is refused again after the first", () => { | |
| 94 | fillForge(); | |
| 95 | expect(admitSignin(app.db, "erin", "203.0.113.77").admitted).toBe(false); | |
| 96 | // The first refusal gave back what it took; the second meets the same full window. | |
| 97 | expect(admitSignin(app.db, "erin", "203.0.113.77").admitted).toBe(false); | |
| 98 | expect(admitSignin(app.db, "frank", "203.0.113.77").admitted).toBe(false); | |
| 99 | }); | |
| 100 | ||
| 101 | test("a source stops being good GOOD_SOURCE_MS after its right password", () => { | |
| 102 | const clock = { at: 1_000_000 }; | |
| 103 | const now = () => clock.at; | |
| 104 | signIn("alice", "203.0.113.50", { now }); | |
| 105 | // A minute short of a day later the forge is full and the source still vouched for. | |
| 106 | clock.at += GOOD_SOURCE_MS - 60_000; | |
| 107 | fillForge({ now }); | |
| 108 | expect(admitSignin(app.db, "alice", "203.0.113.50", { now }).admitted).toBe(true); | |
| 109 | // A day and a minute later, with the forge full again, it is a stranger. | |
| 110 | clock.at += 120_000; | |
| 111 | fillForge({ now }); | |
| 112 | expect(admitSignin(app.db, "alice", "203.0.113.50", { now }).admitted).toBe(false); | |
| 113 | }); | |
| 114 | ||
| 115 | test("past MAX_GOOD_SOURCES the oldest good source is forgotten first", () => { | |
| 116 | const maxGoodSources = 3; | |
| 117 | for (const s of [1, 2, 3, 4]) signIn("alice", `203.0.113.${s}`, { maxGoodSources }); | |
| 118 | fillForge(); | |
| 119 | // Three remembered, the first forgotten. | |
| 120 | expect(admitSignin(app.db, "alice", "203.0.113.1").admitted).toBe(false); | |
| 121 | for (const s of [2, 3, 4]) expect(admitSignin(app.db, "alice", `203.0.113.${s}`).admitted).toBe(true); | |
| 122 | }); | |
| 123 | ||
| 124 | test("a flood of distinct accounts and sources leaves the sign-in limiters at their cap", () => { | |
| 125 | const maxKeys = 50; | |
| 126 | // Four thousand pairs: well past the forge window, so every limiter is pressed. | |
| 127 | for (let s = 0; s < 200; s++) { | |
| 128 | for (let i = 0; i < 20; i++) admitSignin(app.db, `flood${s}-${i}`, `10.${s >> 8}.${s & 255}.1`, { maxKeys }); | |
| 129 | } | |
| 130 | // Three limiters (account, source, wrong passwords), each at most maxKeys; | |
| 131 | // uncapped the same flood leaves over four hundred. | |
| 132 | expect(signinKeyCount(app.db)).toBeGreaterThan(0); | |
| 133 | expect(signinKeyCount(app.db)).toBeLessThanOrEqual(3 * maxKeys); | |
| 134 | }); |
new above
offline