ci: expand CI checks and make consumer sync opt-in
- Add Go, npm, Python, and Java validation to CI - Run Go tests against PostgreSQL - Record performance fixes in the report
This commit is contained in:
1 parent
199a5efaef
commit
22887fef03
100 files changed
+9740
-429
No files matched your search
@@ -1,11 +1,16 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import crypto from 'node:crypto';
|
||||
import {
|
||||
ResetManager,
|
||||
createSessionToken,
|
||||
hashPassword,
|
||||
hashPasswordAsync,
|
||||
hashToken,
|
||||
passwordHashNeedsUpgrade,
|
||||
verifyAndUpgradePasswordAsync,
|
||||
verifyPassword,
|
||||
verifyPasswordAsync,
|
||||
} from '../src/auth.js';
|
||||
import { totpProvisioningUri, verifyTotp } from '../src/totp.js';
|
||||
|
||||
@@ -33,6 +38,74 @@ test('password hashes verify and reject a different password', () => {
|
||||
assert.equal(verifyPassword('wrong password', hash), false);
|
||||
});
|
||||
|
||||
test('new password hashes record their iteration count', () => {
|
||||
const hash = hashPassword('correct horse battery staple');
|
||||
assert.match(hash, /^pbkdf2-sha256\$600000\$[0-9a-f]{32}\$[0-9a-f]{64}$/);
|
||||
});
|
||||
|
||||
test('legacy salt:hex hashes still verify at the original iteration count', () => {
|
||||
const salt = crypto.randomBytes(16).toString('hex');
|
||||
const hash = crypto.pbkdf2Sync('legacy password', salt, 100000, 32, 'sha256').toString('hex');
|
||||
assert.equal(verifyPassword('legacy password', `${salt}:${hash}`), true);
|
||||
assert.equal(verifyPassword('wrong password', `${salt}:${hash}`), false);
|
||||
});
|
||||
|
||||
test('a hash with a malformed iteration count never verifies', () => {
|
||||
assert.equal(verifyPassword('correct horse battery staple', 'pbkdf2-sha256$0$aa$bb'), false);
|
||||
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\$/);
|
||||
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']) {
|
||||
assert.equal(verifyPassword('correct horse battery staple', stored), false);
|
||||
}
|
||||
assert.equal(passwordHashNeedsUpgrade('$2b$12$abc'), true);
|
||||
});
|
||||
|
||||
test('a legacy salt:hex hash is rewritten in the current scheme after a successful login', async () => {
|
||||
const salt = crypto.randomBytes(16).toString('hex');
|
||||
const legacy = `${salt}:${crypto.pbkdf2Sync('legacy password', salt, 100000, 32, 'sha256').toString('hex')}`;
|
||||
assert.equal(passwordHashNeedsUpgrade(legacy), true);
|
||||
|
||||
const result = await verifyAndUpgradePasswordAsync('legacy password', legacy);
|
||||
assert.equal(result.valid, true);
|
||||
assert.match(result.upgradedHash, /^pbkdf2-sha256\$600000\$/);
|
||||
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 });
|
||||
const lowResult = await verifyAndUpgradePasswordAsync('correct horse battery staple', low);
|
||||
assert.match(lowResult.upgradedHash, /^pbkdf2-sha256\$600000\$/);
|
||||
|
||||
const salt = crypto.randomBytes(16).toString('hex');
|
||||
const shortLegacy = `${salt}:${crypto.pbkdf2Sync('short', salt, 100000, 32, 'sha256').toString('hex')}`;
|
||||
const shortResult = await verifyAndUpgradePasswordAsync('short', shortLegacy);
|
||||
assert.equal(shortResult.valid, true);
|
||||
assert.equal(verifyPassword('short', shortResult.upgradedHash), true);
|
||||
});
|
||||
|
||||
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 });
|
||||
assert.deepEqual(await verifyAndUpgradePasswordAsync('wrong password', hash), { valid: false, upgradedHash: null });
|
||||
|
||||
const current = await hashPasswordAsync('correct horse battery staple');
|
||||
assert.equal(passwordHashNeedsUpgrade(current), false);
|
||||
assert.deepEqual(await verifyAndUpgradePasswordAsync('correct horse battery staple', current), {
|
||||
valid: true,
|
||||
upgradedHash: null,
|
||||
});
|
||||
});
|
||||
|
||||
test('TOTP verifies RFC 6238 SHA-1 vectors', () => {
|
||||
const secret = 'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ';
|
||||
const vectors = [
|
||||
|
||||
@@ -108,6 +108,43 @@ test('validate throws InvalidSessionError when AuthGuard reports invalid', async
|
||||
await assert.rejects(() => client.validate('bad-token'), InvalidSessionError);
|
||||
});
|
||||
|
||||
test('validate reuses a positive and a negative answer within the cache window', async () => {
|
||||
const fetchImpl = recordingFetch([
|
||||
{ status: 200, body: { valid: true, user_id: 7, username: 'gabriel', role: 'admin' } },
|
||||
{ status: 401, body: { valid: false } },
|
||||
]);
|
||||
const client = new AuthClient('https://auth.example.com', { fetchImpl });
|
||||
assert.deepEqual(await client.validate('good-token'), { id: 7, username: 'gabriel', role: 'admin' });
|
||||
assert.deepEqual(await client.validate('good-token'), { id: 7, username: 'gabriel', role: 'admin' });
|
||||
await assert.rejects(() => client.validate('bad-token'), InvalidSessionError);
|
||||
await assert.rejects(() => client.validate('bad-token'), InvalidSessionError);
|
||||
assert.equal(fetchImpl.calls.length, 2);
|
||||
});
|
||||
|
||||
test('logout drops the cached answer for that token', async () => {
|
||||
const fetchImpl = recordingFetch([
|
||||
{ status: 200, body: { valid: true, user_id: 7, username: 'gabriel', role: 'admin' } },
|
||||
{ status: 200, body: {} },
|
||||
{ status: 401, body: { valid: false } },
|
||||
]);
|
||||
const client = new AuthClient('https://auth.example.com', { fetchImpl });
|
||||
await client.validate('good-token');
|
||||
await client.logout('good-token');
|
||||
await assert.rejects(() => client.validate('good-token'), InvalidSessionError);
|
||||
assert.equal(fetchImpl.calls.length, 3);
|
||||
});
|
||||
|
||||
test('setBaseUrl clears cached answers', async () => {
|
||||
const fetchImpl = recordingFetch([
|
||||
{ status: 200, body: { valid: true, user_id: 7, username: 'gabriel', role: 'admin' } },
|
||||
]);
|
||||
const client = new AuthClient('https://auth.example.com', { fetchImpl });
|
||||
await client.validate('good-token');
|
||||
client.setBaseUrl('https://auth2.example.com');
|
||||
await client.validate('good-token');
|
||||
assert.equal(fetchImpl.calls.length, 2);
|
||||
});
|
||||
|
||||
test('tokenFromRequest prefers the Authorization header over the cookie', () => {
|
||||
const client = new AuthClient('https://auth.example.com');
|
||||
const req = {
|
||||
@@ -361,3 +398,32 @@ test('deleteManagedUser DELETEs /api/admin/users/{id}', async () => {
|
||||
assert.equal(fetchImpl.calls[0].init.method, 'DELETE');
|
||||
assert.equal(fetchImpl.calls[0].url, 'https://auth.example.com/api/admin/users/6');
|
||||
});
|
||||
|
||||
test('credential calls send the end user address as X-Forwarded-For when given a clientIp', async () => {
|
||||
const user = { id: 1, username: 'a', email: '', role: 'user' };
|
||||
const fetchImpl = recordingFetch([{ status: 200, body: { user } }]);
|
||||
const client = new AuthClient('https://authguard.example', { fetchImpl });
|
||||
await client.login('a', 'secret-password', '', { clientIp: '203.0.113.9' });
|
||||
await client.register('a', 'a@b.com', 'secret-password', { clientIp: '2001:db8::1' });
|
||||
await client.totpVerify('tok', '123456', { clientIp: '203.0.113.9' });
|
||||
await client.totpDisable('tok', '123456', { clientIp: '203.0.113.9' });
|
||||
await client.requestPasswordReset('a', { clientIp: '203.0.113.9' });
|
||||
await client.confirmPasswordReset('CODE', 'secret-password', { clientIp: '203.0.113.9' });
|
||||
assert.deepEqual(
|
||||
fetchImpl.calls.map((call) => call.init.headers['X-Forwarded-For']),
|
||||
['203.0.113.9', '2001:db8::1', '203.0.113.9', '203.0.113.9', '203.0.113.9', '203.0.113.9'],
|
||||
);
|
||||
});
|
||||
|
||||
test('no X-Forwarded-For is sent without a clientIp, or for a value that is not an IP address', async () => {
|
||||
const user = { id: 1, username: 'a', email: '', role: 'user' };
|
||||
const fetchImpl = recordingFetch([{ status: 200, body: { user } }]);
|
||||
const client = new AuthClient('https://authguard.example', { fetchImpl });
|
||||
await client.login('a', 'secret-password');
|
||||
await client.login('a', 'secret-password', '', { clientIp: '203.0.113.9\r\nX-Evil: 1' });
|
||||
await client.login('a', 'secret-password', '', { clientIp: 'not-an-ip' });
|
||||
await client.me('tok');
|
||||
for (const call of fetchImpl.calls) {
|
||||
assert.equal('X-Forwarded-For' in call.init.headers, false);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { AuthStore } from '../src/auth.js';
|
||||
|
||||
// A Database-like object that records every query and answers from canned results.
|
||||
function fakeDatabase({ rowCount = 1, totpEnabled = false, rowsByCondition = {} } = {}) {
|
||||
const queries = [];
|
||||
return {
|
||||
queries,
|
||||
async query(text, params = []) {
|
||||
queries.push({ text, params });
|
||||
if (text.includes('totp_enabled, false) AS enabled')) {
|
||||
return { rows: [{ secret: 'S', enabled: totpEnabled }], rowCount: 1 };
|
||||
}
|
||||
for (const [condition, row] of Object.entries(rowsByCondition)) {
|
||||
if (text.includes(condition)) return { rows: [row], rowCount: 1 };
|
||||
}
|
||||
return { rows: [], rowCount };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test('ensureSchema requests the case-insensitive username index, only while no clashing pair exists', async () => {
|
||||
const database = fakeDatabase();
|
||||
await new AuthStore(database, { singleUser: false }).ensureSchema();
|
||||
const statements = database.queries.map((query) => query.text).join('\n');
|
||||
assert.match(statements, /auth_users_username_lower_idx/);
|
||||
assert.match(statements, /lower\(username\)/);
|
||||
assert.match(statements, /HAVING count\(\*\) > 1/);
|
||||
});
|
||||
|
||||
test('setTotpSecret refuses to replace an enabled second factor', async () => {
|
||||
const database = fakeDatabase({ rowCount: 0, totpEnabled: true });
|
||||
const store = new AuthStore(database);
|
||||
await assert.rejects(store.setTotpSecret(1, 'NEWSECRET'), { code: 'AUTH_TOTP_ALREADY_ENABLED' });
|
||||
assert.match(database.queries[0].text, /NOT totp_enabled/);
|
||||
});
|
||||
|
||||
test('setTotpSecret stores a pending secret while TOTP is off, and ignores an unknown user', async () => {
|
||||
await new AuthStore(fakeDatabase()).setTotpSecret(1, 'NEWSECRET');
|
||||
await new AuthStore(fakeDatabase({ rowCount: 0 })).setTotpSecret(2, 'NEWSECRET');
|
||||
});
|
||||
|
||||
test('credential writes refuse an empty hash and a username containing @', async () => {
|
||||
const database = fakeDatabase();
|
||||
const store = new AuthStore(database);
|
||||
const writes = [
|
||||
(username, hash) => store.createUser(username, '', hash),
|
||||
(username, hash) => store.createManagedUser(username, '', hash),
|
||||
(username, hash) => store.updateCredentials(1, username, '', hash),
|
||||
(username, hash) => store.updateUser(1, { username, passwordHash: hash }),
|
||||
];
|
||||
for (const write of writes) {
|
||||
await assert.rejects(write('alice', ''), { code: 'AUTH_EMPTY_PASSWORD_HASH' });
|
||||
await assert.rejects(write('alice@example.com', 'hash'), { code: 'AUTH_INVALID_USERNAME' });
|
||||
}
|
||||
assert.equal(database.queries.length, 0);
|
||||
});
|
||||
|
||||
test('updateUser leaves unspecified fields alone', async () => {
|
||||
const database = fakeDatabase();
|
||||
const store = new AuthStore(database);
|
||||
await store.updateUser(1, { email: 'a@b.com' });
|
||||
await store.updateUser(1, { role: 'admin' });
|
||||
assert.equal(database.queries.length, 2);
|
||||
assert.doesNotMatch(database.queries[0].text, /password_hash|username/);
|
||||
});
|
||||
|
||||
test('findByIdentifier tries the username before the email', async () => {
|
||||
const database = fakeDatabase({
|
||||
rowsByCondition: {
|
||||
'username = $1': { id: 1, username: 'owner@example.com' },
|
||||
'lower(email) = lower($1)': { id: 2, username: 'owner' },
|
||||
},
|
||||
});
|
||||
const store = new AuthStore(database);
|
||||
assert.equal((await store.findByIdentifier('owner@example.com')).username, 'owner@example.com');
|
||||
assert.equal(database.queries.length, 1);
|
||||
|
||||
const emailOnly = fakeDatabase({ rowsByCondition: { 'lower(email) = lower($1)': { id: 2, username: 'owner' } } });
|
||||
assert.equal((await new AuthStore(emailOnly).findByIdentifier('OWNER@example.com')).username, 'owner');
|
||||
assert.equal(await new AuthStore(fakeDatabase()).findByIdentifier('nobody'), null);
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
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';
|
||||
|
||||
// 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);
|
||||
const contract = existsSync(contractUrl) ? JSON.parse(readFileSync(contractUrl, 'utf8')) : null;
|
||||
const skip = contract ? false : 'contract/auth-contract.json is not part of this checkout';
|
||||
|
||||
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`);
|
||||
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);
|
||||
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);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
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 });
|
||||
} catch {
|
||||
didHash = false;
|
||||
}
|
||||
assert.equal(didHash, accepted.node);
|
||||
});
|
||||
|
||||
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);
|
||||
}
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { Info, Store } from '../src/coreconfig.js';
|
||||
import { Info, Store, internalSecretMatches } 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' });
|
||||
@@ -48,3 +48,20 @@ test('Info.fromJSON/toJSON round-trip the wire shape', () => {
|
||||
assert.deepEqual(info.carrierNodeUrls, ['http://carrier.example.com', 'http://carrier2.example.com']);
|
||||
assert.equal(info.toJSON().carrierNodeUrl, 'http://carrier.example.com');
|
||||
});
|
||||
|
||||
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);
|
||||
});
|
||||
|
||||
test('set rejects a URL that is not an http or https URL and changes nothing', () => {
|
||||
const store = new Store({ authGuardUrl: 'http://auth.example.com' });
|
||||
assert.throws(() => store.set({ authGuardUrl: 'javascript:alert(1)' }), TypeError);
|
||||
assert.throws(() => store.set({ authGuardUrl: 'auth.example.com' }), TypeError);
|
||||
assert.throws(() => store.set({ carrierNodeUrls: ['ftp://carrier.example.com'] }), TypeError);
|
||||
assert.equal(store.authGuardUrl, 'http://auth.example.com');
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import { Database, isReadOnlyStatement } from '../src/db.js';
|
||||
|
||||
function fakePool(results) {
|
||||
const pool = new EventEmitter();
|
||||
pool.calls = [];
|
||||
pool.query = async (text, values) => {
|
||||
pool.calls.push({ text, values });
|
||||
const next = results.shift();
|
||||
if (next instanceof Error) throw next;
|
||||
return next ?? { rows: [] };
|
||||
};
|
||||
return pool;
|
||||
}
|
||||
|
||||
const transient = () => Object.assign(new Error('connection reset'), { code: 'ECONNRESET' });
|
||||
|
||||
test('only plain SELECT statements are treated as read-only', () => {
|
||||
assert.equal(isReadOnlyStatement('SELECT id FROM auth_users'), true);
|
||||
assert.equal(isReadOnlyStatement(' select 1'), true);
|
||||
assert.equal(isReadOnlyStatement('INSERT INTO auth_users (id) VALUES (1)'), false);
|
||||
assert.equal(isReadOnlyStatement('WITH x AS (DELETE FROM t RETURNING 1) SELECT * FROM x'), false);
|
||||
assert.equal(isReadOnlyStatement('SELECT * FROM t FOR UPDATE'), false);
|
||||
assert.equal(isReadOnlyStatement('SELECT nextval(\'seq\')'), false);
|
||||
assert.equal(isReadOnlyStatement('SELECT * INTO copy FROM t'), false);
|
||||
});
|
||||
|
||||
test('an idle pool error is logged instead of thrown', () => {
|
||||
const logged = [];
|
||||
const pool = fakePool([]);
|
||||
new Database({ pool, log: message => logged.push(message) });
|
||||
assert.doesNotThrow(() => pool.emit('error', new Error('terminating connection')));
|
||||
assert.equal(logged.length, 1);
|
||||
assert.match(logged[0], /terminating connection/);
|
||||
});
|
||||
|
||||
test('a transient error is retried for a read-only statement', async () => {
|
||||
const pool = fakePool([transient(), { rows: [{ ok: 1 }] }]);
|
||||
const db = new Database({ pool, log() {} });
|
||||
db.ready = true;
|
||||
const result = await db.query('SELECT 1 AS ok');
|
||||
assert.deepEqual(result.rows, [{ ok: 1 }]);
|
||||
assert.equal(pool.calls.length, 2);
|
||||
});
|
||||
|
||||
test('a transient error is not retried for a write', async () => {
|
||||
const pool = fakePool([transient(), { rows: [] }]);
|
||||
const db = new Database({ pool, log() {} });
|
||||
db.ready = true;
|
||||
await assert.rejects(db.query('INSERT INTO t (id) VALUES ($1)', [1]), { code: 'ECONNRESET' });
|
||||
assert.equal(pool.calls.length, 1);
|
||||
});
|
||||
|
||||
test('a write is retried only when the caller opts in', async () => {
|
||||
const pool = fakePool([transient(), { rows: [] }]);
|
||||
const db = new Database({ pool, log() {} });
|
||||
db.ready = true;
|
||||
await db.query('INSERT INTO t (id) VALUES ($1)', [1], { retry: true });
|
||||
assert.equal(pool.calls.length, 2);
|
||||
});
|
||||
Reference in new issue
Block a user