Files
Kelx/tests/username-uniqueness-enforcement.test.js
2026-11-30 16:32:37 +00:00

335 lines
16 KiB
JavaScript

"use strict";
// POST /api/account/username used to write users.username with no uniqueness
// enforcement of any kind: the handler validated length and charset and then
// UPDATEd the row straight into the table. Two accounts could therefore share
// a username, or hold names differing only by letter case (the table's
// utf8mb4_unicode_ci collation folds case everywhere else in the app), and
// since the dashboard presents the username as an account identity marker, a
// second account could impersonate the first. The fix is layered, and this
// file pins every layer by reading the sources as text, like the other audit
// tests:
//
// * mysql-schema.sql — the users table declares
// UNIQUE KEY uniq_users_username (username), case-insensitive through the
// table's utf8mb4_unicode_ci collation, with the column still NULL-able so
// multiple accounts without a username stay legal (MySQL unique indexes
// allow multiple NULLs);
// * startup migration — pre-existing duplicates are collapsed first (lowest
// id keeps the name, the rest get username = NULL,
// username_changed_at = NULL), then an idempotent SHOW INDEX FROM users
// check for uniq_users_username gates an
// ALTER TABLE users ADD UNIQUE KEY, and the whole step sits right after
// the username_changed_at column-add step;
// * handler — an explicit pre-check SELECT (WHERE username = ? AND
// id <> ? LIMIT 1) answers 409 "Username is already taken" BEFORE the
// write, with an ER_DUP_ENTRY catch backstop returning the SAME 409 for
// the race window, and the check sits AFTER the 7-day cooldown gate so a
// taken-name probe pays the same gate as a real change (anti-enumeration
// ordering: no-op shortcut -> length -> charset -> cooldown 429 ->
// uniqueness 409 -> UPDATE);
// * single-writer lock — the cooldown gate, the pre-check and the write run
// under withKeyedLock(`account-username:${user.id}`) with a fresh re-fetch
// inside, so two concurrent changes cannot both pass the read-then-act
// cooldown gate and commit inside the 7-day window (the 429/409 responses
// are sent from the post-lock outcome switch, keyed off { kind: ... });
// * compare-and-swap — the UPDATE pins the previously read
// username_changed_at with the null-safe <=> operator (the column is
// BIGINT UNSIGNED epoch millis, NULL until the first change), so a second
// change cannot commit inside the window even without the lock; a lost
// race fails closed (same 429 while the fresh row is cooling down, else
// the shared 500);
// * single-writer — no INSERT INTO users may list the username column: the
// change endpoint stays the only code path that writes users.username, so
// no insert can bypass the uniqueness checks (and trip the unique index
// as an unhandled 500);
// * frontend — dashboard.js surfaces data.error from the non-ok response so
// the 409 message actually reaches the user instead of a generic fallback.
const test = require("node:test");
const assert = require("node:assert");
const fs = require("node:fs");
const path = require("node:path");
const ROOT = path.join(__dirname, "..");
const INDEX_JS = path.join(ROOT, "index.js");
const SCHEMA_SQL = path.join(ROOT, "mysql-schema.sql");
const CREATE_USER_JS = path.join(ROOT, "scripts", "create-user.js");
const DASHBOARD_JS = path.join(ROOT, "public", "js", "dashboard.js");
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
const schemaSource = fs.readFileSync(SCHEMA_SQL, "utf8");
const createUserSource = fs.readFileSync(CREATE_USER_JS, "utf8");
const dashboardSource = fs.readFileSync(DASHBOARD_JS, "utf8");
function extractRoute(source, routeMarker, nextRouteMarker) {
const start = source.indexOf(routeMarker);
assert.ok(start >= 0, `route marker not found: ${routeMarker}`);
const end = source.indexOf(nextRouteMarker, start);
assert.ok(end > start, `next route marker not found after route: ${nextRouteMarker}`);
return source.slice(start, end);
}
// The users CREATE TABLE block runs to the next table definition in the
// schema file, so the unique-key assertion cannot be satisfied by a key on
// some other table.
const USERS_TABLE_START = "CREATE TABLE IF NOT EXISTS users (";
const USERS_TABLE_END = "CREATE TABLE IF NOT EXISTS nodes (";
const HANDLER_START = 'app.post("/api/account/username"';
// Verified against index.js: the avatar upload route is the next app.*
// registration after the username handler.
const HANDLER_END = 'app.post("/api/account/avatar/upload"';
const usersTableBlock = extractRoute(schemaSource, USERS_TABLE_START, USERS_TABLE_END);
const handler = extractRoute(indexSource, HANDLER_START, HANDLER_END);
const TAKEN_MESSAGE = "Username is already taken";
const TAKEN_BODY = /error:\s*["']Username is already taken["']/;
const PRECHECK_SQL = /SELECT\s+id\s+FROM\s+users\s+WHERE\s+username\s*=\s*\?\s+AND\s+id\s*<>\s*\?\s+LIMIT\s+1/i;
const DEDUPE_SQL = /UPDATE\s+users\s+SET\s+username\s*=\s*NULL\s*,\s*username_changed_at\s*=\s*NULL/;
const ADD_UNIQUE_KEY_SQL = /ALTER\s+TABLE\s+users\s+ADD\s+UNIQUE\s+KEY\s+uniq_users_username/;
const SHOW_INDEX_SQL = /SHOW\s+INDEX\s+FROM\s+users/;
const USERNAME_CHANGED_AT_COLUMN_STEP = "SHOW COLUMNS FROM users LIKE 'username_changed_at'";
const UPDATE_USERNAME_SQL = "UPDATE users SET username = ?";
// The status code attached to the response carrying `needle`: the nearest
// res.status( token before it, so the message quietly reattached to a
// 400/500 is caught, not just any 409 somewhere in the block.
function statusOfResponseCarrying(block, needle, label) {
const at = block.indexOf(needle);
assert.ok(at >= 0, `${label} not found`);
const statusAt = block.lastIndexOf("res.status(", at);
assert.ok(statusAt >= 0, `${label} must be returned through res.status(...)`);
const digits = block.slice(statusAt + "res.status(".length, statusAt + "res.status(".length + 3);
assert.match(digits, /^\d{3}$/, `${label} must carry a 3-digit status`);
return digits;
}
// indexOf that also accepts regex markers, honoring a start offset either way.
function indexOfMarker(block, marker, from = 0) {
if (marker instanceof RegExp) {
const at = block.slice(from).search(marker);
return at < 0 ? -1 : from + at;
}
return block.indexOf(marker, from);
}
test("mysql-schema.sql gives users.username a case-insensitive unique key", () => {
assert.match(
usersTableBlock,
/UNIQUE\s+KEY\s+uniq_users_username\s*\(\s*username\s*\)/,
"the users CREATE TABLE block must declare UNIQUE KEY uniq_users_username (username)"
);
// The impersonation risk spans letter case, so the key must fold case: the
// table-level utf8mb4_unicode_ci collation is what makes the index
// case-insensitive.
assert.match(
usersTableBlock,
/COLLATE\s*=\s*utf8mb4_unicode_ci/,
"the users table must keep the utf8mb4_unicode_ci collation so the unique key folds letter case"
);
// Multiple NULLs are only possible while the column stays nullable; the
// schema must not "tighten" username to NOT NULL along the way.
assert.match(
usersTableBlock,
/username\s+VARCHAR\(50\)\s+NULL/,
"username must stay NULL-able: the unique key must allow multiple accounts that never set a username"
);
});
test("username handler pre-checks uniqueness against OTHER accounts before the write", () => {
const updateIdx = handler.indexOf(UPDATE_USERNAME_SQL);
assert.ok(updateIdx >= 0, "the handler must still write through UPDATE users SET username");
const preWriteBlock = handler.slice(0, updateIdx);
// The gate, the pre-check and the write run under the per-user keyed lock
// (with a fresh re-fetch inside), so two concurrent changes cannot both
// pass the read-then-act cooldown gate and commit inside the 7-day window.
assert.match(
preWriteBlock,
/withKeyedLock\(`account-username:\$\{user\.id\}`/,
"the gate, pre-check and write must run under withKeyedLock(`account-username:${user.id}`)"
);
assert.match(
preWriteBlock,
PRECHECK_SQL,
"before the UPDATE the handler must run SELECT id FROM users WHERE username = ? AND id <> ? LIMIT 1 (the id <> ? self-exclusion keeps resaving your own name from 409ing)"
);
// The pre-check's canonical 409 is sent from the post-lock outcome switch
// ({ kind: "taken" } resolves after the UPDATE text), so it is pinned
// against the whole handler rather than the pre-write slice.
assert.match(
handler,
TAKEN_BODY,
"the pre-check must answer with the canonical 'Username is already taken' message"
);
assert.equal(
statusOfResponseCarrying(handler, TAKEN_MESSAGE, "the pre-check rejection"),
"409",
"the pre-check rejection must be a 409 (Conflict), not 400 or 500"
);
});
test("the ER_DUP_ENTRY race backstop returns the same 409 message as the pre-check", () => {
const updateIdx = handler.indexOf(UPDATE_USERNAME_SQL);
assert.ok(updateIdx >= 0, "the handler must still write through UPDATE users SET username");
const catchIdx = handler.indexOf("catch (err)", updateIdx);
assert.ok(catchIdx >= 0, "the write must stay wrapped in a try/catch");
const catchBlock = handler.slice(catchIdx);
assert.match(
catchBlock,
/err\.code\s*===\s*["']ER_DUP_ENTRY["']/,
"the catch must branch on err.code === 'ER_DUP_ENTRY' to backstop the pre-check/UPDATE race window against the unique key"
);
assert.match(
catchBlock,
TAKEN_BODY,
"the race backstop must return the SAME 'Username is already taken' message as the pre-check"
);
assert.equal(
statusOfResponseCarrying(catchBlock, TAKEN_MESSAGE, "the race backstop rejection"),
"409",
"the race backstop must answer 409 (Conflict), matching the pre-check"
);
});
test("uniqueness check sits AFTER the cooldown gate: no-op, length, charset, 429, 409, UPDATE", () => {
// Final handler order per the contract: no-op shortcut -> length 3-30 ->
// charset -> cooldown (429) -> uniqueness (409) -> UPDATE. Under the
// account-username lock the gate and the pre-check are EVALUATED in that
// order on the fresh row while the 429/409 sends live in the post-lock
// outcome switch, so the in-order markers are the lock, the gate evaluation
// and the pre-check, with the 429 send pinned after the UPDATE.
const sequence = [
["unchanged: true", "no-op save shortcut"],
["must be 3-30 characters", "length validation"],
["can only contain letters, numbers", "charset validation"],
["withKeyedLock(`account-username:", "per-user serialization lock"],
["usernameChangeCooldownReply(", "7-day cooldown gate"],
[PRECHECK_SQL, "uniqueness pre-check"],
[UPDATE_USERNAME_SQL, "username UPDATE"],
["res.status(429", "429 cooldown response"],
];
let cursor = 0;
for (const [marker, label] of sequence) {
const at = indexOfMarker(handler, marker, cursor);
assert.ok(at >= 0, `the username handler must keep the ${label}`);
cursor = at;
}
const gateIdx = handler.indexOf("usernameChangeCooldownReply(");
const precheckIdx = indexOfMarker(handler, PRECHECK_SQL);
assert.ok(
gateIdx >= 0 && precheckIdx >= 0 && gateIdx < precheckIdx,
"the cooldown gate must be EVALUATED before the uniqueness pre-check in the handler text: a taken-name probe must pay the same gate as a real change, so clients over quota learn nothing about which usernames exist (anti-enumeration)"
);
});
test("the username UPDATE is a null-safe compare-and-swap on username_changed_at", () => {
// Defense in depth behind the keyed lock (the recovery-code claim's
// treatment): the write pins the previously read username_changed_at with
// the null-safe <=> so a second change cannot commit inside the 7-day
// window even without the lock, and a lost race fails closed — the handler
// re-reads the row and answers the same 429 while it is cooling down,
// otherwise the shared 500. The column is BIGINT UNSIGNED epoch millis,
// NULL until the first change, so the null-safe operator is required.
assert.match(
handler,
/UPDATE\s+users\s+SET\s+username\s*=\s*\?,\s*username_changed_at\s*=\s*\?\s+WHERE\s+LOWER\(email\)\s*=\s*LOWER\(\?\)\s+AND\s+username_changed_at\s*<=>\s*\?/i,
"the UPDATE must pin username_changed_at <=> ? so it only lands on the previously read cooldown value"
);
assert.match(
handler,
/result\.affectedRows\s*!==\s*1/,
"the handler must observe affectedRows on the CAS UPDATE and fail closed when it loses the race"
);
});
test("startup migration dedupes legacy usernames before adding the unique key, after the username_changed_at column step", () => {
const dedupeAt = indexSource.search(DEDUPE_SQL);
assert.ok(
dedupeAt >= 0,
"the startup migration must collapse duplicate usernames with UPDATE users SET username = NULL, username_changed_at = NULL (lowest id keeps the name)"
);
const showIndexAt = indexSource.search(SHOW_INDEX_SQL);
assert.ok(
showIndexAt >= 0,
"the startup migration must probe SHOW INDEX FROM users so the ALTER is idempotent across restarts"
);
const alterAt = indexSource.search(ADD_UNIQUE_KEY_SQL);
assert.ok(
alterAt >= 0,
"the startup migration must ALTER TABLE users ADD UNIQUE KEY uniq_users_username"
);
assert.ok(
indexSource.slice(showIndexAt, alterAt).includes("uniq_users_username"),
"the SHOW INDEX existence check must look for the uniq_users_username key name before deciding to ALTER"
);
assert.ok(
dedupeAt < alterAt,
"legacy duplicates must be collapsed BEFORE the unique key is added, otherwise the ALTER fails on existing data and the fail-open path would silently drop enforcement"
);
// Ordering pin: the whole step belongs right after the username_changed_at
// column-add step in the startup migration block.
const columnStepAt = indexSource.indexOf(USERNAME_CHANGED_AT_COLUMN_STEP);
assert.ok(
columnStepAt >= 0,
"the username_changed_at column-add step must exist in the startup migration block"
);
assert.ok(
columnStepAt < dedupeAt,
"the username uniqueness migration must run right after the username_changed_at column-add step in index.js"
);
});
test("no INSERT INTO users writes the username column (single-writer pin)", () => {
// POST /api/account/username must remain the ONLY code path that writes
// users.username: every INSERT INTO users has to leave the column out of
// its column list, so a new account can never be created with a name that
// bypassed the change endpoint's checks (and the unique index would turn
// such an insert into an unhandled 500 instead of a clean rejection).
const sources = [
["panel provisioning", indexSource + fs.readFileSync(path.join(ROOT, "services", "account-credentials.js"), "utf8")],
["scripts/create-user.js", createUserSource],
];
for (const [name, source] of sources) {
const inserts = [];
const re = /INSERT\s+INTO\s+users\s*\(/gi;
let match;
while ((match = re.exec(source)) !== null) {
const columns = source.slice(match.index + match[0].length, source.indexOf(")", match.index));
inserts.push(columns);
assert.doesNotMatch(
columns,
/\busername\b/,
`${name}: INSERT INTO users must not list username in its column list (found "${columns.trim().replace(/\s+/g, " ")}") — POST /api/account/username is the only writer of users.username`
);
}
assert.ok(
inserts.length > 0,
`${name} must still contain INSERT INTO users statements with explicit column lists for this pin to stay meaningful`
);
}
});
test("dashboard surfaces the server's error message from a failed username save", () => {
const fetchMatch = dashboardSource.match(/fetch\((['"])\/api\/account\/username\1/);
assert.ok(fetchMatch, "dashboard.js must still POST to /api/account/username");
const callBlock = dashboardSource.slice(fetchMatch.index, fetchMatch.index + 600);
assert.match(
callBlock,
/if\s*\(\s*!res\.ok\s*\)\s*throw\s+new\s+Error\(\s*data\.error/,
"the non-ok branch must throw new Error(data.error) so the 409 'Username is already taken' reaches the user's alert() instead of a generic fallback"
);
});