Public: anyone can read this; the crew can change it.

A wrong password and an unknown user take the same time and give the same words, proven by a test #15651

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/15640-a-wrong-password-and-an-unknown-user-tak → main 0 commits fork

  • Merged. scout/15640-a-wrong-password-and-an-unknown-user-tak was merged into main as e949ec2.

Review

Sign in to review this change.
2 files changed +150 −4
src/core/users.ts +12 −4
@@ -594,6 +594,14 @@ export function hasPassword(db: Database, userId: string): boolean {
594594 );
595595 }
596596
597 /**
598 * What a password is checked against when the name has no hash to check:
599 * an argon2id at `hashPassword`'s own cost (Bun's default, m=64 MiB, t=2),
600 * so a miss spends what a hit does (#15640). No password verifies against it.
601 */
602 export const DECOY_HASH =
603 "$argon2id$v=19$m=65536,t=2,p=1$AAAAAAAAAAAAAAAAAAAAAA$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
604
597605 /** Constant-shape verification: always burns an argon2 verify, hit or miss. */
598606 async function checkPassword(
599607 db: Database,
@@ -606,10 +614,10 @@ async function checkPassword(
606614 [string]
607615 >("SELECT * FROM user WHERE username = ?1 COLLATE NOCASE")
608616 .get(username);
609 // A decoy hash keeps timing identical whether or not the user exists.
610 const hash =
611 row?.password_hash ??
612 "$argon2id$v=19$m=65536,t=2,p=1$AAAAAAAAAAAAAAAAAAAAAA$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
617 // The decoy keeps timing identical whether or not the user exists, and
618 // for an account with no password (passkey-only, agent): an empty hash
619 // would fail at once without hashing, which says the name is taken.
620 const hash = row !== null && row.password_hash !== "" ? row.password_hash : DECOY_HASH;
613621 const valid = await Bun.password.verify(password, hash).catch(() => false);
614622 // Org rows own repos but never authenticate, whatever their stored hash;
615623 // neither does an agent, whose hash is empty besides.
test/signin-same.test.ts added +138
@@ -0,0 +1,138 @@
1 /**
2 * Sign-in does not tell a stranger which usernames exist (#15640). A wrong
3 * password at a real account and any password at an unknown name answer the
4 * same status, headers and body, byte for byte; both spend one argon2 verify
5 * at the real cost (the decoy for a name with no hash, a passkey-only account
6 * too); and both fill the sign-in window the same, so the 429 that follows is
7 * the same answer with the same Retry-After.
8 */
9 import { afterAll, beforeAll, describe, expect, setSystemTime, 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 { createUser, DECOY_HASH } from "../src/core/users.ts";
15 import { realHash } from "./helpers/cheap-hash.ts";
16 import { FAILURES_PER_ACCOUNT } from "../src/core/signin-window.ts";
17 import { serve, type Servers } from "../src/http/server.ts";
18
19 const PASSWORD = "a-good-passphrase";
20
21 interface Answer {
22 readonly status: number;
23 readonly retryAfter: string | null;
24 readonly contentType: string | null;
25 readonly setCookie: string | null;
26 readonly body: string;
27 }
28
29 let dataDir = "";
30 let app: App;
31 let servers: Servers;
32 let cheap = "";
33 let decoys = 0;
34 const verify = Bun.password.verify;
35
36 async function attempt(username: string, password: string): Promise<Answer> {
37 const res = await fetch(`${servers.url}/signin`, {
38 method: "POST",
39 headers: { origin: servers.url },
40 body: new URLSearchParams({ username, password }),
41 redirect: "manual",
42 });
43 return {
44 status: res.status,
45 retryAfter: res.headers.get("retry-after"),
46 contentType: res.headers.get("content-type"),
47 setCookie: res.headers.get("set-cookie"),
48 body: await res.text(),
49 };
50 }
51
52 async function makeUser(username: string, hash: string): Promise<void> {
53 const made = await createUser(app.db, {
54 origin: "seed",
55 trusted: true,
56 username,
57 email: `${username}@forge.local`,
58 password: PASSWORD,
59 adminIfFirst: false,
60 });
61 if (!made.ok) throw new Error(made.error);
62 app.db.run("UPDATE user SET password_hash = ?1 WHERE username = ?2", [hash, username]);
63 }
64
65 beforeAll(async () => {
66 dataDir = await mkdtemp(join(tmpdir(), "forge-signin-same-"));
67 app = createApp({ dataDir, port: 0 });
68 servers = await serve(app);
69 // Cheapest argon2id for real accounts; the decoy is counted and stood in
70 // for by the same cheap hash, so the test stays fast and still says no.
71 cheap = await Bun.password.hash(PASSWORD, { algorithm: "argon2id", memoryCost: 8, timeCost: 1 });
72 const wrong = await Bun.password.hash("never-typed", { algorithm: "argon2id", memoryCost: 8, timeCost: 1 });
73 Bun.password.verify = (password, hash, algorithm) => {
74 if (hash === DECOY_HASH) {
75 decoys++;
76 return verify(password, wrong, algorithm);
77 }
78 return verify(password, hash, algorithm);
79 };
80 await makeUser("first", cheap);
81 });
82 afterAll(async () => {
83 Bun.password.verify = verify;
84 setSystemTime();
85 servers.stop();
86 app.close();
87 await rm(dataDir, { recursive: true, force: true });
88 });
89
90 describe("a wrong password and an unknown user", () => {
91 test("the decoy costs what a real hash costs", async () => {
92 // `hashPassword` asks for Bun's argon2id default; the test preload
93 // cheapens every hash, so the real cost is read from the unwrapped one.
94 const real = await realHash("anything", "argon2id");
95 const params = (h: string) => h.split("$").slice(1, 4).join("$");
96 expect(params(DECOY_HASH)).toBe(params(real));
97 expect(await verify("", DECOY_HASH)).toBe(false);
98 });
99
100 test("answer the same status, headers and body, byte for byte", async () => {
101 // One name, asked before it exists and after: nothing else differs.
102 const before = decoys;
103 const unknown = await attempt("ghost", "wrong-1");
104 expect(decoys).toBe(before + 1);
105 await makeUser("ghost", cheap);
106 const wrong = await attempt("ghost", "wrong-2");
107 expect(decoys).toBe(before + 1);
108 expect(unknown.status).toBe(422);
109 expect(unknown.retryAfter).toBeNull();
110 expect(wrong).toEqual(unknown);
111 expect(Buffer.from(wrong.body)).toEqual(Buffer.from(unknown.body));
112 });
113
114 test("an account with no password is checked against the decoy too", async () => {
115 await makeUser("keyonly", "");
116 const before = decoys;
117 const answer = await attempt("keyonly", "anything");
118 expect(decoys).toBe(before + 1);
119 expect(answer.status).toBe(422);
120 });
121
122 test("both fill the window the same and are refused with the same Retry-After", async () => {
123 setSystemTime(new Date("2026-11-22T10:00:00Z"));
124 await makeUser("realx", cheap);
125 const answers = async (name: string): Promise<Answer[]> => {
126 const out: Answer[] = [];
127 for (let i = 0; i <= FAILURES_PER_ACCOUNT; i++) out.push(await attempt(name, `wrong-${i}`));
128 return out;
129 };
130 // The page says the name back; with it set aside the answers are equal.
131 const strip = (a: Answer, name: string): Answer => ({ ...a, body: a.body.replaceAll(name, "NAME") });
132 const real = (await answers("realx")).map((a) => strip(a, "realx"));
133 const fake = (await answers("fakex")).map((a) => strip(a, "fakex"));
134 expect(real.map((a) => a.status)).toEqual([...Array(FAILURES_PER_ACCOUNT).fill(422), 429]);
135 expect(real.at(-1)!.retryAfter).toMatch(/^[1-9]\d*$/);
136 expect(fake).toEqual(real);
137 });
138 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs