docs: record auth hash alignment and validation results

This commit is contained in:
Gabriel20xx committed 2026-10-20 15:26:58 +00:00
1 parent 22887fef03
commit f7819904b9
51 files changed
+1792 -542

No files matched your search

+25 -12
View File
@@ -12,7 +12,7 @@ import {
verifyPassword,
verifyPasswordAsync,
} from '../src/auth.js';
import { totpProvisioningUri, verifyTotp } from '../src/totp.js';
import { totpProvisioningUri, verifyTotp, verifyTotpStep } from '../src/totp.js';
test('reset codes are printed, case-insensitive, expiring, and one-time', () => {
const messages = [];
@@ -38,9 +38,9 @@ test('password hashes verify and reject a different password', () => {
assert.equal(verifyPassword('wrong password', hash), false);
});
test('new password hashes record their iteration count', () => {
test('new password hashes use the shared bcrypt scheme and cost', () => {
const hash = hashPassword('correct horse battery staple');
assert.match(hash, /^pbkdf2-sha256\$600000\$[0-9a-f]{32}\$[0-9a-f]{64}$/);
assert.match(hash, /^bcrypt\$\$2b\$12\$/);
});
test('legacy salt:hex hashes still verify at the original iteration count', () => {
@@ -55,16 +55,16 @@ test('a hash with a malformed iteration count never verifies', () => {
assert.equal(verifyPassword('correct horse battery staple', 'pbkdf2-sha256$x$aa$bb'), false);
});
test('async password helpers produce and verify the same format', async () => {
const hash = await hashPasswordAsync('correct horse battery staple', { iterations: 1000 });
assert.match(hash, /^pbkdf2-sha256\$1000\$/);
test('async password helpers produce and verify the same bcrypt format', async () => {
const hash = await hashPasswordAsync('correct horse battery staple');
assert.match(hash, /^bcrypt\$\$2b\$12\$/);
assert.equal(await verifyPasswordAsync('correct horse battery staple', hash), true);
assert.equal(await verifyPasswordAsync('wrong password', hash), false);
assert.equal(verifyPassword('correct horse battery staple', hash), true);
});
test('formats this module does not verify fail closed', () => {
for (const stored of ['', '$2b$12$abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQ', 'bcrypt$$2a$12$abc', 'pbkdf2-sha256$600000$00$00$extra']) {
for (const stored of ['', '$2b$12$abc', 'bcrypt$$2a$12$abc', 'bcrypt-sha256$$2b$12$abc', 'pbkdf2-sha256$600000$00$00$extra']) {
assert.equal(verifyPassword('correct horse battery staple', stored), false);
}
assert.equal(passwordHashNeedsUpgrade('$2b$12$abc'), true);
@@ -77,15 +77,27 @@ test('a legacy salt:hex hash is rewritten in the current scheme after a successf
const result = await verifyAndUpgradePasswordAsync('legacy password', legacy);
assert.equal(result.valid, true);
assert.match(result.upgradedHash, /^pbkdf2-sha256\$600000\$/);
assert.match(result.upgradedHash, /^bcrypt\$\$2b\$12\$/);
assert.equal(passwordHashNeedsUpgrade(result.upgradedHash), false);
assert.equal(verifyPassword('legacy password', result.upgradedHash), true);
});
test('a hash below the current iteration count is rewritten, and a short legacy password still upgrades', async () => {
const low = await hashPasswordAsync('correct horse battery staple', { iterations: 1000 });
test('a long legacy PBKDF2 password is migrated without truncation', async () => {
const longPassword = 'a'.repeat(80);
const salt = crypto.randomBytes(16).toString('hex');
const legacy = `pbkdf2-sha256$600000$${salt}$${crypto.pbkdf2Sync(longPassword, salt, 600000, 32, 'sha256').toString('hex')}`;
const result = await verifyAndUpgradePasswordAsync(longPassword, legacy);
assert.equal(result.valid, true);
assert.match(result.upgradedHash, /^bcrypt-sha256\$\$2b\$12\$/);
assert.equal(await verifyPasswordAsync(longPassword, result.upgradedHash), true);
assert.equal(await verifyPasswordAsync(`${longPassword}x`, result.upgradedHash), false);
});
test('a low-cost bcrypt hash is rewritten, and a short legacy password still upgrades', async () => {
const bcrypt = (await import('bcryptjs')).default;
const low = `bcrypt$${await bcrypt.hash('correct horse battery staple', 4)}`;
const lowResult = await verifyAndUpgradePasswordAsync('correct horse battery staple', low);
assert.match(lowResult.upgradedHash, /^pbkdf2-sha256\$600000\$/);
assert.match(lowResult.upgradedHash, /^bcrypt\$\$2b\$12\$/);
const salt = crypto.randomBytes(16).toString('hex');
const shortLegacy = `${salt}:${crypto.pbkdf2Sync('short', salt, 100000, 32, 'sha256').toString('hex')}`;
@@ -95,7 +107,7 @@ test('a hash below the current iteration count is rewritten, and a short legacy
});
test('a wrong password neither verifies nor upgrades, and a current hash is not rewritten', async () => {
const hash = await hashPasswordAsync('correct horse battery staple', { iterations: 1000 });
const hash = await hashPasswordAsync('correct horse battery staple');
assert.deepEqual(await verifyAndUpgradePasswordAsync('wrong password', hash), { valid: false, upgradedHash: null });
const current = await hashPasswordAsync('correct horse battery staple');
@@ -117,6 +129,7 @@ test('TOTP verifies RFC 6238 SHA-1 vectors', () => {
];
for (const [seconds, code] of vectors) {
assert.equal(verifyTotp(secret, code, seconds * 1000), true);
assert.equal(verifyTotpStep(secret, code, seconds * 1000), Math.floor(seconds / 30));
}
assert.match(totpProvisioningUri('Example App', 'admin@example.com', secret), /^otpauth:\/\/totp\//);
});
+35 -1
View File
@@ -10,7 +10,7 @@ function fakeDatabase({ rowCount = 1, totpEnabled = false, rowsByCondition = {}
async query(text, params = []) {
queries.push({ text, params });
if (text.includes('totp_enabled, false) AS enabled')) {
return { rows: [{ secret: 'S', enabled: totpEnabled }], rowCount: 1 };
return { rows: [{ secret: 'S', enabled: totpEnabled, last_used_step: -1 }], rowCount: 1 };
}
for (const [condition, row] of Object.entries(rowsByCondition)) {
if (text.includes(condition)) return { rows: [row], rowCount: 1 };
@@ -27,6 +27,7 @@ test('ensureSchema requests the case-insensitive username index, only while no c
assert.match(statements, /auth_users_username_lower_idx/);
assert.match(statements, /lower\(username\)/);
assert.match(statements, /HAVING count\(\*\) > 1/);
assert.match(statements, /ADD COLUMN IF NOT EXISTS last_used_step BIGINT NOT NULL DEFAULT -1/);
});
test('setTotpSecret refuses to replace an enabled second factor', async () => {
@@ -41,6 +42,39 @@ test('setTotpSecret stores a pending secret while TOTP is off, and ignores an un
await new AuthStore(fakeDatabase({ rowCount: 0 })).setTotpSecret(2, 'NEWSECRET');
});
test('TOTP enrollment records its code step and a replay is rejected atomically', async () => {
const state = { secret: 'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ', enabled: false, last_used_step: -1 };
const database = {
async query(text, params = []) {
if (text.startsWith('SELECT COALESCE(totp_secret')) {
return { rows: [{ ...state }], rowCount: 1 };
}
const [step, , secret] = params;
if (text.includes('SET totp_enabled = true')) {
if (!state.enabled && secret === state.secret && state.last_used_step < step) {
state.enabled = true;
state.last_used_step = step;
return { rows: [], rowCount: 1 };
}
return { rows: [], rowCount: 0 };
}
if (text.includes('SET last_used_step = $1')) {
if (state.enabled && secret === state.secret && state.last_used_step < step) {
state.last_used_step = step;
return { rows: [], rowCount: 1 };
}
return { rows: [], rowCount: 0 };
}
throw new Error(`unexpected query: ${text}`);
},
};
const store = new AuthStore(database);
assert.equal(await store.enableTotp(1, '287082', 59000), true);
assert.equal(state.last_used_step, 1);
assert.equal(await store.consumeTotpCode(1, '287082', 59000), false);
assert.equal(state.last_used_step, 1);
});
test('credential writes refuse an empty hash and a username containing @', async () => {
const database = fakeDatabase();
const store = new AuthStore(database);
+28 -6
View File
@@ -2,7 +2,12 @@ import test from 'node:test';
import assert from 'node:assert/strict';
import { existsSync, readFileSync } from 'node:fs';
import { hashPassword, passwordHashNeedsUpgrade, verifyAndUpgradePasswordAsync, verifyPassword } from '../src/auth.js';
import { verifyTotp } from '../src/totp.js';
import { verifyTotp, verifyTotpStep } from '../src/totp.js';
import {
EXAMPLE_INTERNAL_SECRETS,
MIN_INTERNAL_SECRET_LENGTH,
internalSecretMatches,
} from '../src/coreconfig.js';
// The Go, Node and Python auth helpers load the same fixtures; see "description" in the file.
const contractUrl = new URL('../../../contract/auth-contract.json', import.meta.url);
@@ -12,14 +17,16 @@ const skip = contract ? false : 'contract/auth-contract.json is not part of this
test('password hashes verify as the contract says for Node', { skip }, async () => {
const { plaintext, wrongPassword, hashes } = contract.password;
for (const entry of hashes) {
assert.equal(verifyPassword(plaintext, entry.hash), entry.verifies.node, entry.name);
assert.equal(verifyPassword(wrongPassword, entry.hash), false, `${entry.name}: wrong password`);
const password = entry.password ?? plaintext;
const rejectedPassword = entry.wrongPassword ?? wrongPassword;
assert.equal(verifyPassword(password, entry.hash), entry.verifies.node, entry.name);
assert.equal(verifyPassword(rejectedPassword, entry.hash), false, `${entry.name}: wrong password`);
if ('node' in (entry.needsUpgrade ?? {})) {
assert.equal(passwordHashNeedsUpgrade(entry.hash), entry.needsUpgrade.node, `${entry.name}: needs upgrade`);
const { valid, upgradedHash } = await verifyAndUpgradePasswordAsync(plaintext, entry.hash);
const { valid, upgradedHash } = await verifyAndUpgradePasswordAsync(password, entry.hash);
assert.equal(valid, true, `${entry.name}: valid on upgrade`);
assert.equal(upgradedHash !== null, entry.needsUpgrade.node, `${entry.name}: upgraded hash`);
if (upgradedHash) assert.equal(verifyPassword(plaintext, upgradedHash), true);
if (upgradedHash) assert.equal(verifyPassword(password, upgradedHash), true);
}
}
});
@@ -28,7 +35,7 @@ test('the password length contract holds for Node', { skip }, () => {
const { bytes, accepted } = contract.password.tooLongToHash;
let didHash = true;
try {
hashPassword('a'.repeat(bytes), { iterations: 1000 });
hashPassword('a'.repeat(bytes));
} catch {
didHash = false;
}
@@ -39,5 +46,20 @@ test('TOTP verifies as the contract says', { skip }, () => {
for (const entry of contract.totp.cases) {
const secret = entry.secret ?? contract.totp.secret;
assert.equal(verifyTotp(secret, entry.code, entry.unix * 1000), entry.valid, entry.name);
if (entry.valid)
assert.equal(
verifyTotpStep(secret, entry.code, entry.unix * 1000),
entry.matchedStep ?? Math.floor(entry.unix / 30),
entry.name,
);
}
});
test('the internal secret gate matches the contract for Node', { skip }, () => {
const rule = contract.internalSecret;
assert.equal(MIN_INTERNAL_SECRET_LENGTH, rule.minLength);
assert.deepEqual([...EXAMPLE_INTERNAL_SECRETS].sort(), [...rule.placeholders].sort());
for (const entry of rule.cases) {
assert.equal(internalSecretMatches(entry.provided, entry.secret), entry.matches, entry.name);
}
});
+28 -4
View File
@@ -1,6 +1,13 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { Info, Store, internalSecretMatches } from '../src/coreconfig.js';
import {
EXAMPLE_INTERNAL_SECRETS,
Info,
MIN_INTERNAL_SECRET_LENGTH,
Store,
internalSecretMatches,
internalSecretUsable,
} from '../src/coreconfig.js';
test('store seeds from the fallback Info', () => {
const store = new Store({ authGuardUrl: 'http://auth.example.com', carrierNodeUrl: 'http://carrier.example.com' });
@@ -49,13 +56,30 @@ test('Info.fromJSON/toJSON round-trip the wire shape', () => {
assert.equal(info.toJSON().carrierNodeUrl, 'http://carrier.example.com');
});
const LONG_SECRET = 'shared-secret-value';
test('internal secret check fails closed when the secret is unset or empty', () => {
assert.equal(internalSecretMatches(undefined, undefined), false);
assert.equal(internalSecretMatches(undefined, ''), false);
assert.equal(internalSecretMatches('', ''), false);
assert.equal(internalSecretMatches(undefined, 'shared-secret'), false);
assert.equal(internalSecretMatches('shared-secreT', 'shared-secret'), false);
assert.equal(internalSecretMatches('shared-secret', 'shared-secret'), true);
assert.equal(internalSecretMatches(undefined, LONG_SECRET), false);
assert.equal(internalSecretMatches('shared-secret-valuE', LONG_SECRET), false);
assert.equal(internalSecretMatches(LONG_SECRET, LONG_SECRET), true);
});
test('internal secret check refuses a short or placeholder secret', () => {
const short = 'x'.repeat(MIN_INTERNAL_SECRET_LENGTH - 1);
assert.equal(internalSecretMatches(short, short), false);
for (const placeholder of EXAMPLE_INTERNAL_SECRETS) {
assert.equal(internalSecretMatches(placeholder, placeholder), false, placeholder);
}
});
test('internal secret usability needs the minimum length and no placeholder', () => {
assert.equal(internalSecretUsable('x'.repeat(MIN_INTERNAL_SECRET_LENGTH - 1)), false);
assert.equal(internalSecretUsable('x'.repeat(MIN_INTERNAL_SECRET_LENGTH)), true);
assert.equal(internalSecretUsable('change-me-to-a-long-random-value'), false);
assert.equal(internalSecretUsable(undefined), false);
});
test('set rejects a URL that is not an http or https URL and changes nothing', () => {