Public: anyone can read this; the crew can change it.
Signup is rate-limited per source and per forge, set on /admin/limits like sign-in #2294
scout/forge:scout/2277-signup-is-rate-limited-per-source-and-pe → main 2 commits fork
8 files
changed +186
−4
src/http/api.ts +4
| @@ -389,6 +389,7 @@ import { COPIES_PER_DAY, makeItYours } from "../actions/make_it_yours.ts"; | ||
| 389 | 389 | import { passportRoutes } from "./passport_edge.ts"; |
| 390 | 390 | import type { Router } from "./router.ts"; |
| 391 | 391 | import { clientAddress, clientBucket } from "./peer.ts"; |
| 392 | import { signupAllowed, signupWait } from "./signup-limit.ts"; | |
| 392 | 393 | import { manifestFor } from "../actions/here.ts"; |
| 393 | 394 | import { |
| 394 | 395 | acceptReport, |
| @@ -1194,6 +1195,9 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 1194 | 1195 | const input = await boundedBody(ctx.request, STRANGER_MAX); |
| 1195 | 1196 | if (input === "too_large") |
| 1196 | 1197 | return apiError("too_large", 413, `at most ${STRANGER_MAX} bytes`); |
| 1198 | const wait = signupAllowed(ctx); | |
| 1199 | if (wait !== undefined) | |
| 1200 | return json({ error: "rate_limited", message: signupWait(wait) }, 429, { "retry-after": String(wait) }); | |
| 1197 | 1201 | const created = await signUp( |
| 1198 | 1202 | ctx.app, |
| 1199 | 1203 | { |
src/http/signup-limit.ts added +44
| @@ -0,0 +1,44 @@ | ||
| 1 | /** | |
| 2 | * Signups, throttled. An account costs a password hash and a row, and the | |
| 3 | * token limiter sees no credential yet, so two sliding windows stand in | |
| 4 | * front of every door that makes one: a source may try so many times a | |
| 5 | * minute at one route, and the forge as a whole so many from everyone. The | |
| 6 | * source is the socket's peer address (`clientAddress`, which reads a | |
| 7 | * forwarding header only from a proxy the operator trusts), never a header | |
| 8 | * the client chose. A refused attempt is not counted. One limiter per forge. | |
| 9 | */ | |
| 10 | import type { App } from "../app.ts"; | |
| 11 | import { RateLimiter } from "../core/ratelimit.ts"; | |
| 12 | import { limitValue } from "../settings/limits.ts"; | |
| 13 | import type { Ctx } from "./context.ts"; | |
| 14 | import { bucketOf, clientAddress } from "./peer.ts"; | |
| 15 | ||
| 16 | const limiters = new WeakMap<App, RateLimiter>(); | |
| 17 | ||
| 18 | /** Seconds to wait when the attempt is refused; undefined when it may go on. */ | |
| 19 | export function signupAllowedFor(app: App, address: string, route: string): number | undefined { | |
| 20 | let limiter = limiters.get(app); | |
| 21 | if (limiter === undefined) { | |
| 22 | limiter = new RateLimiter({ perMinute: 0, adminPerMinute: 0, enabled: true }); | |
| 23 | limiters.set(app, limiter); | |
| 24 | } | |
| 25 | // Read on every attempt, so a change on /admin/limits governs the next one. | |
| 26 | limiter.setLimits({ | |
| 27 | perMinute: limitValue(app.db, "signup.per_source"), | |
| 28 | adminPerMinute: limitValue(app.db, "signup.per_forge"), | |
| 29 | enabled: true, | |
| 30 | }); | |
| 31 | // The source first: one already refused must not spend the forge's budget. | |
| 32 | const one = limiter.take(`source:${bucketOf(address)}:${route}`, "ro"); | |
| 33 | if (!one.allowed) return one.retryAfter; | |
| 34 | const whole = limiter.take("forge", "admin"); | |
| 35 | return whole.allowed ? undefined : whole.retryAfter; | |
| 36 | } | |
| 37 | ||
| 38 | /** The same, for a request: its peer address and its route. */ | |
| 39 | export function signupAllowed(ctx: Ctx): number | undefined { | |
| 40 | return signupAllowedFor(ctx.app, clientAddress(ctx.request), ctx.url.pathname); | |
| 41 | } | |
| 42 | ||
| 43 | export const signupWait = (wait: number): string => | |
| 44 | `Too many signups. Try again in ${wait === 1 ? "a second" : `${wait} seconds`}.`; |
src/settings/limits.ts +19 −1
| @@ -32,7 +32,9 @@ export type LimitKey = | ||
| 32 | 32 | | "front.hidden_max" |
| 33 | 33 | | "share.daily_max" |
| 34 | 34 | | "signin.per_account" |
| 35 | | "signin.per_forge"; | |
| 35 | | "signin.per_forge" | |
| 36 | | "signup.per_source" | |
| 37 | | "signup.per_forge"; | |
| 36 | 38 | |
| 37 | 39 | export interface LimitDef { |
| 38 | 40 | readonly label: string; |
| @@ -132,6 +134,22 @@ export const LIMITS: Record<LimitKey, LimitDef> = { | ||
| 132 | 134 | max: 100_000, |
| 133 | 135 | reason: "Spread across many accounts, guessing still burns CPU on hashes, so the forge as a whole has a ceiling.", |
| 134 | 136 | }, |
| 137 | "signup.per_source": { | |
| 138 | label: "Signups per source a minute", | |
| 139 | unit: "signups", | |
| 140 | default: 5, | |
| 141 | min: 1, | |
| 142 | max: 1_000, | |
| 143 | reason: "Every signup costs a password hash and an account row, and one address has no need to make many.", | |
| 144 | }, | |
| 145 | "signup.per_forge": { | |
| 146 | label: "Signups per forge a minute", | |
| 147 | unit: "signups", | |
| 148 | default: 60, | |
| 149 | min: 1, | |
| 150 | max: 100_000, | |
| 151 | reason: "Spread across many addresses, mass signup still burns hashes and fills the table, so the forge as a whole has a ceiling.", | |
| 152 | }, | |
| 135 | 153 | }; |
| 136 | 154 | |
| 137 | 155 | export const LIMIT_KEYS = Object.keys(LIMITS) as LimitKey[]; |
src/tui/screens/signin.ts +6
| @@ -9,6 +9,7 @@ | ||
| 9 | 9 | */ |
| 10 | 10 | |
| 11 | 11 | import { SIGNUP_CLOSED_MESSAGE, signUp, signupClosed } from "../../actions/users.ts"; |
| 12 | import { signupAllowedFor, signupWait } from "../../http/signup-limit.ts"; | |
| 12 | 13 | import { hasAnyUser } from "../../core/users.ts"; |
| 13 | 14 | import type { Ctx, Screen } from "../app/app.ts"; |
| 14 | 15 | import { binding } from "../app/keys.ts"; |
| @@ -66,6 +67,11 @@ export function signInScreen(f: Session, ctx: Ctx, onDone: () => void): Screen { | ||
| 66 | 67 | string, |
| 67 | 68 | string, |
| 68 | 69 | ]; |
| 70 | const wait = signupAllowedFor(f.app, f.identity.remoteAddress, "terminal"); | |
| 71 | if (wait !== undefined) { | |
| 72 | error = signupWait(wait); | |
| 73 | return; | |
| 74 | } | |
| 69 | 75 | const created = await signUp( |
| 70 | 76 | f.app, |
| 71 | 77 | { username, email, password }, |
src/web/pages/signup-passkey.ts +4 −3
| @@ -16,7 +16,8 @@ import { STRANGER_MAX } from "../../http/limits.ts"; | ||
| 16 | 16 | import { clientAddress } from "../../http/peer.ts"; |
| 17 | 17 | import { boundedBody, json, str } from "../../http/respond.ts"; |
| 18 | 18 | import { relying, store } from "./passkeys.ts"; |
| 19 | import { safeNext, sessionCookie, signinAllowed } from "./site.ts"; | |
| 19 | import { signupAllowed, signupWait } from "../../http/signup-limit.ts"; | |
| 20 | import { safeNext, sessionCookie } from "./site.ts"; | |
| 20 | 21 | |
| 21 | 22 | const refuse = (status: number, message: string) => |
| 22 | 23 | json({ error: "refused", message }, status); |
| @@ -43,9 +44,9 @@ function problem(ctx: Ctx, username: string, email: string): string | undefined | ||
| 43 | 44 | |
| 44 | 45 | function guard(ctx: Ctx): Response | undefined { |
| 45 | 46 | if (crossOrigin(ctx.request, ctx.url, ctx.app.log)) return refuse(403, "forbidden"); |
| 46 | const wait = signinAllowed(ctx, `signup:${clientAddress(ctx.request)}`); | |
| 47 | const wait = signupAllowed(ctx); | |
| 47 | 48 | if (wait !== undefined) |
| 48 | return json({ error: "rate_limited", message: `Too many attempts. Try again in ${wait}s.` }, 429, { "retry-after": String(wait) }); | |
| 49 | return json({ error: "rate_limited", message: signupWait(wait) }, 429, { "retry-after": String(wait) }); | |
| 49 | 50 | return undefined; |
| 50 | 51 | } |
| 51 | 52 |
src/web/pages/site.ts +16
| @@ -12,6 +12,7 @@ import { storageLimitMessage } from "../../core/storage.ts"; | ||
| 12 | 12 | import { limitValue } from "../../settings/limits.ts"; |
| 13 | 13 | import { signOutHere } from "../../actions/signins.ts"; |
| 14 | 14 | import { clientAddress } from "../../http/peer.ts"; |
| 15 | import { signupAllowed, signupWait } from "../../http/signup-limit.ts"; | |
| 15 | 16 | import { verifyEmail } from "../../actions/verify.ts"; |
| 16 | 17 | import { STRANGER_MAX } from "../../http/limits.ts"; |
| 17 | 18 | import { createRepo, repositoryLimitMessage, resolveOwner } from "../../actions/repos.ts"; |
| @@ -534,6 +535,21 @@ export async function signupSubmit(ctx: Ctx): Promise<Response> { | ||
| 534 | 535 | if (form instanceof Response) return form; |
| 535 | 536 | const username = field(form, "username"); |
| 536 | 537 | const email = field(form, "email"); |
| 538 | const wait = signupAllowed(ctx); | |
| 539 | if (wait !== undefined) { | |
| 540 | const response = page( | |
| 541 | { | |
| 542 | ctx, | |
| 543 | title: "Sign up", | |
| 544 | body: authForm(ctx, "signup", { values: { username, email }, errors: { password: signupWait(wait) } }), | |
| 545 | turnstile: siteKey(ctx) !== undefined, | |
| 546 | ...(ctx.app.config.passkeyOnlySignup === true ? { scriptJs: passkeyJs } : {}), | |
| 547 | }, | |
| 548 | 429, | |
| 549 | ); | |
| 550 | response.headers.set("retry-after", String(wait)); | |
| 551 | return response; | |
| 552 | } | |
| 537 | 553 | const created = await signUp( |
| 538 | 554 | ctx.app, |
| 539 | 555 | { |
test/signup-limit.test.ts added +89
| @@ -0,0 +1,89 @@ | ||
| 1 | /** | |
| 2 | * Signup is throttled per source and per forge (#2277): rapid signups from | |
| 3 | * one source meet 429 with retry-after, another route from the same source | |
| 4 | * does not, and the forge-wide window holds across sources. | |
| 5 | */ | |
| 6 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 7 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 8 | import { tmpdir } from "node:os"; | |
| 9 | import { join } from "node:path"; | |
| 10 | import { createApp, type App } from "../src/app.ts"; | |
| 11 | import { signupAllowedFor } from "../src/http/signup-limit.ts"; | |
| 12 | import { createUser } from "../src/core/users.ts"; | |
| 13 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 14 | import { LIMITS, limitValue, setLimit } from "../src/settings/limits.ts"; | |
| 15 | import { quietLogs } from "./helpers/globals.ts"; | |
| 16 | ||
| 17 | quietLogs(); | |
| 18 | ||
| 19 | describe("signup throttle", () => { | |
| 20 | let dir = ""; | |
| 21 | let app: App; | |
| 22 | let servers: Servers; | |
| 23 | ||
| 24 | beforeAll(async () => { | |
| 25 | dir = await mkdtemp(join(tmpdir(), "forge-signup-limit-")); | |
| 26 | app = createApp({ dataDir: dir, port: 0 }); | |
| 27 | servers = await serve(app); | |
| 28 | }); | |
| 29 | afterAll(async () => { | |
| 30 | servers.stop(); | |
| 31 | app.close(); | |
| 32 | await rm(dir, { recursive: true, force: true }); | |
| 33 | }); | |
| 34 | ||
| 35 | const api = () => | |
| 36 | fetch(`${servers.url}/api/v1/users`, { | |
| 37 | method: "POST", | |
| 38 | headers: { "content-type": "application/json", }, | |
| 39 | body: JSON.stringify({ username: "!", email: "x", password: "y" }), | |
| 40 | }); | |
| 41 | ||
| 42 | test("defaults are shown with the other limits", () => { | |
| 43 | expect(LIMITS["signup.per_source"].default).toBe(5); | |
| 44 | expect(LIMITS["signup.per_forge"].default).toBe(60); | |
| 45 | expect(limitValue(app.db, "signup.per_source")).toBe(5); | |
| 46 | }); | |
| 47 | ||
| 48 | test("rapid signups from one source are throttled, with retry-after", async () => { | |
| 49 | const seen: number[] = []; | |
| 50 | for (let i = 0; i < 7; i++) seen.push((await api()).status); | |
| 51 | expect(seen.slice(0, 5).every((s) => s !== 429)).toBe(true); | |
| 52 | expect(seen[5]).toBe(429); | |
| 53 | const res = await api(); | |
| 54 | expect(res.status).toBe(429); | |
| 55 | expect(Number(res.headers.get("retry-after"))).toBeGreaterThan(0); | |
| 56 | }); | |
| 57 | ||
| 58 | test("the form answers with a page that says when to try again", async () => { | |
| 59 | const post = () => | |
| 60 | fetch(`${servers.url}/signup`, { | |
| 61 | method: "POST", | |
| 62 | headers: { origin: servers.url, "content-type": "application/x-www-form-urlencoded" }, | |
| 63 | body: new URLSearchParams({ username: "a", email: "b", password: "c" }), | |
| 64 | }); | |
| 65 | let res = await post(); | |
| 66 | for (let i = 0; i < 5; i++) res = await post(); | |
| 67 | expect(res.status).toBe(429); | |
| 68 | expect(Number(res.headers.get("retry-after"))).toBeGreaterThan(0); | |
| 69 | expect(await res.text()).toContain("Try again in"); | |
| 70 | }); | |
| 71 | ||
| 72 | test("a different route from the same source is not throttled", () => { | |
| 73 | expect(signupAllowedFor(app, "1.2.3.4", "/a")).toBeUndefined(); | |
| 74 | for (let i = 0; i < 10; i++) signupAllowedFor(app, "1.2.3.4", "/a"); | |
| 75 | expect(signupAllowedFor(app, "1.2.3.4", "/a")).toBeGreaterThan(0); | |
| 76 | expect(signupAllowedFor(app, "1.2.3.4", "/b")).toBeUndefined(); | |
| 77 | }); | |
| 78 | ||
| 79 | test("the per-forge window holds across sources", async () => { | |
| 80 | const other = createApp({ dataDir: await mkdtemp(join(tmpdir(), "forge-signup-forge-")), port: 0 }); | |
| 81 | const admin = await createUser(other.db, { username: "boss", email: "[email protected]", password: "a-long-passphrase", adminIfFirst: true, trusted: true }); | |
| 82 | if (!admin.ok) throw new Error(`no admin: ${JSON.stringify(admin.error)}`); | |
| 83 | expect(setLimit(other.db, "signup.per_forge", 3, admin.value.id).ok).toBe(true); | |
| 84 | const out = [1, 2, 3, 4, 5].map((n) => signupAllowedFor(other, `5.5.5.${n}`, "/f")); | |
| 85 | expect(out.slice(0, 3)).toEqual([undefined, undefined, undefined]); | |
| 86 | expect(out[3]).toBeGreaterThan(0); | |
| 87 | expect(signupAllowedFor(other, "5.5.5.200", "/g")).toBeGreaterThan(0); | |
| 88 | }); | |
| 89 | }); |
test/signup.test.ts +4
| @@ -12,6 +12,7 @@ import { createApp, type App } from "../src/app.ts"; | ||
| 12 | 12 | import { configProblem } from "../src/kernel/preflight.ts"; |
| 13 | 13 | import { BOOT_ACTOR, getSignup, setSignup, signupChanges, signupFromEnv } from "../src/settings/signup.ts"; |
| 14 | 14 | import { createSession } from "../src/core/sessions.ts"; |
| 15 | import { setLimit } from "../src/settings/limits.ts"; | |
| 15 | 16 | import { createToken } from "../src/core/tokens.ts"; |
| 16 | 17 | import { createUser, getUserByName, type User } from "../src/core/users.ts"; |
| 17 | 18 | import { serve, type Servers } from "../src/http/server.ts"; |
| @@ -182,6 +183,9 @@ describe("signup closed (#2166)", () => { | ||
| 182 | 183 | beforeAll(async () => { |
| 183 | 184 | dataDir = await mkdtemp(join(tmpdir(), "forge-signup-closed-")); |
| 184 | 185 | app = createApp({ dataDir, port: 0, edgeToken: EDGE }); |
| 186 | // These tests make many attempts from one address; the limiter has its own. | |
| 187 | setLimit(app.db, "signup.per_source", 1_000, "boot"); | |
| 188 | setLimit(app.db, "signup.per_forge", 100_000, "boot"); | |
| 185 | 189 | servers = await serve(app); |
| 186 | 190 | }); |
| 187 | 191 | afterAll(async () => { |
new above
offline