ci: expand shared package validation and test coverage
Lint / Lint (push) Successful in 32s
Docker / Docker Build & Push (push) Failing after 2m22s
Tests / Go backend (push) Failing after 1m2s
Tests / Dashboard checks (push) Failing after 35s

- Add lint, formatting, vet, and publish workflow checks
- Run Go database tests with PostgreSQL and add Java tests
- Make consumer sync opt-in; update docs and Go dependency
This commit is contained in:
Gabriel20xx committed 2026-10-19 21:46:52 +00:00
1 parent 937f51b4fb
commit 0ff94f9b10
107 files changed
+10124 -410

No files matched your search

+13 -6
View File
@@ -3,8 +3,8 @@
Shared Node.js backend infrastructure for services that use PostgreSQL:
- validated `DATABASE_URL` and pool settings;
- one pool owner with startup retry, transient query retry, transactions, and shutdown;
- PBKDF2 password hashing and secure session-token helpers;
- one pool owner with startup retry, transient retry for read-only queries, transactions, and shutdown;
- PBKDF2 password hashing (`verifyAndUpgradePasswordAsync` returns a current-scheme hash for a login to store) and secure session-token helpers;
- short-lived, one-time admin reset codes printed to the server console;
- common account/session persistence;
- transaction-locked ordered migrations.
@@ -20,7 +20,9 @@ share one PostgreSQL database, so their migration histories cannot collide.
Database startup uses `DB_INIT_RETRY_INTERVAL_MS` (default `5000`, minimum
`250`) and `DB_INIT_RETRY_MAX_ATTEMPTS` (default `0`, retry indefinitely).
Run `npm test` from this package or `npm run test --workspace=@gabriel20xx/node-backend` from `shared`.
Run `npm test` from this package or `npm run test --workspace=@gabriel20xx/node-backend` from `shared`; `npm run lint` runs ESLint with the repository's config.
`AuthClient`'s `register`, `login`, `totpVerify`, `totpDisable`, `requestPasswordReset` and `confirmPasswordReset` take an optional trailing `{ clientIp }`, sent to AuthGuard as `X-Forwarded-For` so its per-address limits see the end user. Pass an address you have verified (for example the socket peer, or `X-Forwarded-For` only from a proxy you trust), never a raw request header. `AuthStore` refuses an empty password hash and a username containing `@`, refuses `setTotpSecret` while TOTP is enabled (error code `AUTH_TOTP_ALREADY_ENABLED`), and makes usernames unique ignoring case when no clashing pair already exists.
## `authclient`/`coreconfig`: adopting AuthGuard instead of local auth
@@ -39,7 +41,7 @@ live whenever ProjectConfigurator pushes a fresh
`authClient.setBaseUrl` so a project never needs to hardcode `AUTHGUARD_URL`:
```js
import { AuthClient, CoreConfigStore } from '@gabriel20xx/node-backend';
import { AuthClient, CoreConfigStore, internalSecretMatches } from '@gabriel20xx/node-backend';
const authClient = new AuthClient('');
const coreConfig = new CoreConfigStore({ authGuardUrl: '' });
@@ -47,10 +49,15 @@ coreConfig.onUpdate((info) => authClient.setBaseUrl(info.authGuardUrl));
// in your own route for PUT /api/core-services/internal:
app.put('/api/core-services/internal', (req, res) => {
if (req.get('X-Internal-Auth') !== process.env.SECRET) {
if (!internalSecretMatches(req.get('X-Internal-Auth'), process.env.SECRET)) {
return res.status(401).json({ error: 'internal service authentication required' });
}
const info = coreConfig.set(req.body);
let info;
try {
info = coreConfig.set(req.body);
} catch (error) {
return res.status(400).json({ error: error.message });
}
res.json({ ok: true, info: info.toJSON() });
});
```
+2 -1
View File
@@ -22,7 +22,8 @@
"pg": "^8.17.2"
},
"scripts": {
"test": "node --test"
"test": "node --test",
"lint": "eslint ."
},
"engines": {
"node": ">=20"
+174 -24
View File
@@ -1,8 +1,17 @@
import crypto from 'node:crypto';
import { promisify } from 'node:util';
const PASSWORD_ITERATIONS = 100000;
const pbkdf2 = promisify(crypto.pbkdf2);
// Hashes written before the format recorded its parameters are `salt:hex` at
// this count. They still verify and are rewritten on the next successful login.
// New hashes use PASSWORD_ITERATIONS and carry the scheme prefix PASSWORD_FORMAT.
const LEGACY_PASSWORD_ITERATIONS = 100000;
const PASSWORD_ITERATIONS = 600000;
const PASSWORD_KEY_LENGTH = 32;
const PASSWORD_DIGEST = 'sha256';
const PASSWORD_FORMAT = 'pbkdf2-sha256';
const LEGACY_PASSWORD_PATTERN = /^[0-9a-f]+:[0-9a-f]+$/;
export const RESET_CODE_TTL_MS = 5 * 60 * 1000;
export const USER_ROLES = Object.freeze({ SUPERADMIN: 'superadmin', ADMIN: 'admin', USER: 'user' });
@@ -53,33 +62,157 @@ CREATE INDEX IF NOT EXISTS auth_sessions_expiry_idx ON auth_sessions (expires_at
CREATE INDEX IF NOT EXISTS auth_sessions_user_idx ON auth_sessions (user_id);
`;
export function hashPassword(password, { iterations = PASSWORD_ITERATIONS } = {}) {
// Usernames are unique ignoring case ("Admin" and "admin" are one identity to a reader). The index
// is created only while no such pair exists, so a database that already holds one still starts and
// raises a warning; it is built on the first start after one account of each pair is renamed.
const USERNAME_CASE_INDEX = `
DO $$
BEGIN
IF EXISTS (SELECT 1 FROM auth_users GROUP BY lower(username) HAVING count(*) > 1) THEN
RAISE WARNING 'auth_users holds usernames that differ only by case; the case-insensitive username index was not created';
ELSE
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_username_lower_idx ON auth_users (lower(username));
END IF;
EXCEPTION WHEN unique_violation THEN
RAISE WARNING 'the case-insensitive username index was not created: a clashing username was just added';
END
$$
`;
function authError(message, code) {
const error = new Error(message);
error.code = code;
return error;
}
// Refuses a write that would leave an account without a password hash, or store a username that
// could be mistaken for another account's email. undefined means "leave unchanged".
function assertCredentials(username, passwordHash) {
if (passwordHash !== undefined && !passwordHash) {
throw authError('password hash is required', 'AUTH_EMPTY_PASSWORD_HASH');
}
if (typeof username === 'string' && username.includes('@')) {
throw authError('username cannot contain @', 'AUTH_INVALID_USERNAME');
}
}
function assertPasswordLength(password) {
if (typeof password !== 'string' || password.length < 8) {
throw new Error('Password must be at least 8 characters');
}
const salt = crypto.randomBytes(16).toString('hex');
const hash = crypto.pbkdf2Sync(password, salt, iterations, PASSWORD_KEY_LENGTH, PASSWORD_DIGEST);
return `${salt}:${hash.toString('hex')}`;
}
function encodePasswordHash(salt, hash, iterations) {
return [PASSWORD_FORMAT, iterations, salt, hash.toString('hex')].join('$');
}
// Returns the salt, expected hash and iteration count recorded in a stored hash,
// or null for a format this module does not verify (such as bcrypt written by
// the Python or Go packages).
function parsePasswordHash(stored) {
const text = String(stored);
if (text.startsWith(`${PASSWORD_FORMAT}$`)) {
const parts = text.split('$');
if (parts.length !== 4) return null;
const [, iterations, salt, expected] = parts;
return { iterations: Number(iterations), salt, expected, legacy: false };
}
if (LEGACY_PASSWORD_PATTERN.test(text)) {
const [salt, expected] = text.split(':');
return { iterations: LEGACY_PASSWORD_ITERATIONS, salt, expected, legacy: true };
}
return null;
}
function usablePasswordHash(stored) {
const parsed = parsePasswordHash(stored);
if (!parsed || !parsed.salt || !parsed.expected || !isValidIterations(parsed.iterations)) return null;
return parsed;
}
function isValidIterations(iterations) {
return Number.isSafeInteger(iterations) && iterations >= 1;
}
function passwordHashMatches(expected, actual) {
const expectedBytes = Buffer.from(expected, 'hex');
return expectedBytes.length === actual.length && crypto.timingSafeEqual(expectedBytes, actual);
}
/**
* Blocking PBKDF2 hash. Prefer hashPasswordAsync in request handlers, because
* this call holds the event loop for the whole derivation.
*/
export function hashPassword(password, { iterations = PASSWORD_ITERATIONS } = {}) {
assertPasswordLength(password);
const salt = crypto.randomBytes(16).toString('hex');
const hash = crypto.pbkdf2Sync(password, salt, iterations, PASSWORD_KEY_LENGTH, PASSWORD_DIGEST);
return encodePasswordHash(salt, hash, iterations);
}
/** Non-blocking variant of hashPassword with the same output format. */
export async function hashPasswordAsync(password, { iterations = PASSWORD_ITERATIONS } = {}) {
assertPasswordLength(password);
return derivePasswordHashAsync(password, iterations);
}
// The length rule belongs to user-facing hashing. Upgrading an old hash must
// not refuse a password that was accepted when it was first set.
async function derivePasswordHashAsync(password, iterations) {
const salt = crypto.randomBytes(16).toString('hex');
const hash = await pbkdf2(String(password), salt, iterations, PASSWORD_KEY_LENGTH, PASSWORD_DIGEST);
return encodePasswordHash(salt, hash, iterations);
}
/** Blocking verify. Prefer verifyPasswordAsync in request handlers. */
export function verifyPassword(password, stored) {
try {
const [salt, expected] = String(stored).split(':');
if (!salt || !expected) return false;
const actual = crypto.pbkdf2Sync(
String(password),
salt,
PASSWORD_ITERATIONS,
PASSWORD_KEY_LENGTH,
PASSWORD_DIGEST
);
const expectedBytes = Buffer.from(expected, 'hex');
return expectedBytes.length === actual.length && crypto.timingSafeEqual(expectedBytes, actual);
const parsed = usablePasswordHash(stored);
if (!parsed) return false;
const actual = crypto.pbkdf2Sync(String(password), parsed.salt, parsed.iterations, PASSWORD_KEY_LENGTH, PASSWORD_DIGEST);
return passwordHashMatches(parsed.expected, actual);
} catch {
return false;
}
}
/** Non-blocking variant of verifyPassword. */
export async function verifyPasswordAsync(password, stored) {
try {
const parsed = usablePasswordHash(stored);
if (!parsed) return false;
const actual = await pbkdf2(String(password), parsed.salt, parsed.iterations, PASSWORD_KEY_LENGTH, PASSWORD_DIGEST);
return passwordHashMatches(parsed.expected, actual);
} catch {
return false;
}
}
/**
* True when a stored hash should be rewritten after a successful login: a
* legacy `salt:hex` hash, or a PBKDF2 hash below PASSWORD_ITERATIONS.
*/
export function passwordHashNeedsUpgrade(stored) {
const parsed = parsePasswordHash(stored);
return !parsed || parsed.legacy || parsed.iterations < PASSWORD_ITERATIONS;
}
/**
* Verifies a password and, when it matches a hash in an older scheme, returns a
* replacement in the current scheme. The caller stores upgradedHash, for example
* with AuthStore.updateUser(id, { passwordHash }). upgradedHash is null when the
* password does not match or no rewrite is needed.
*/
export async function verifyAndUpgradePasswordAsync(password, stored) {
if (!(await verifyPasswordAsync(password, stored))) {
return { valid: false, upgradedHash: null };
}
if (!passwordHashNeedsUpgrade(stored)) {
return { valid: true, upgradedHash: null };
}
return { valid: true, upgradedHash: await derivePasswordHashAsync(password, PASSWORD_ITERATIONS) };
}
export function createSessionToken() {
const token = crypto.randomBytes(32).toString('base64url');
return { token, tokenHash: hashToken(token) };
@@ -143,6 +276,7 @@ export class AuthStore {
async ensureSchema() {
await this.database.query(AUTH_SCHEMA);
await this.database.query(USERNAME_CASE_INDEX);
if (this.singleUser) {
await this.database.query('CREATE UNIQUE INDEX IF NOT EXISTS auth_users_singleton_idx ON auth_users ((true))');
} else {
@@ -156,6 +290,7 @@ export class AuthStore {
}
async createUser(username, email, passwordHash) {
assertCredentials(username, passwordHash ?? '');
try {
const result = await this.database.query(
`INSERT INTO auth_users (username, email, password_hash, role, updated_at)
@@ -177,15 +312,20 @@ export class AuthStore {
}
async findByIdentifier(identifier) {
const result = await this.database.query(
`SELECT id, username, email, password_hash, role, created_at, updated_at
FROM auth_users WHERE username = $1 OR lower(email) = lower($1)`,
[identifier]
);
return result.rows[0] || null;
// Usernames are tried before emails, so an identifier resolves to one account in a fixed order.
for (const condition of ['username = $1', 'lower(email) = lower($1)']) {
const result = await this.database.query(
`SELECT id, username, email, password_hash, role, created_at, updated_at
FROM auth_users WHERE ${condition}`,
[identifier]
);
if (result.rows[0]) return result.rows[0];
}
return null;
}
async updateCredentials(id, username, email, passwordHash) {
assertCredentials(username, passwordHash ?? '');
await this.database.query(
`UPDATE auth_users SET username = $1, email = $2, password_hash = $3, updated_at = now()
WHERE id = $4`,
@@ -226,6 +366,7 @@ export class AuthStore {
}
async createManagedUser(username, email, passwordHash, role = USER_ROLES.USER) {
assertCredentials(username, passwordHash ?? '');
try {
const result = await this.database.query(
`INSERT INTO auth_users (username, email, password_hash, role, updated_at)
@@ -245,6 +386,7 @@ export class AuthStore {
}
async updateUser(id, { username, email, passwordHash, role } = {}) {
assertCredentials(username, passwordHash);
const fields = [];
const values = [];
const add = (sql, value) => { fields.push(sql); values.push(value); };
@@ -276,11 +418,19 @@ export class AuthStore {
return result.rows[0] || { secret: '', enabled: false };
}
/**
* Stores a pending secret without enabling two-factor auth. Throws an error with code
* AUTH_TOTP_ALREADY_ENABLED while it is enabled, so a replaced secret cannot silently switch the
* second factor off.
*/
async setTotpSecret(userId, secret) {
await this.database.query(
'UPDATE auth_users SET totp_secret = $1, totp_enabled = false, updated_at = now() WHERE id = $2',
const result = await this.database.query(
'UPDATE auth_users SET totp_secret = $1, totp_enabled = false, updated_at = now() WHERE id = $2 AND NOT totp_enabled',
[secret, userId],
);
if (result.rowCount === 0 && (await this.getTotpState(userId)).enabled) {
throw authError('TOTP is already enabled; disable it before setting a new secret', 'AUTH_TOTP_ALREADY_ENABLED');
}
}
async enableTotp(userId) {
+82 -13
View File
@@ -22,8 +22,16 @@
// requestPasswordReset/confirmPasswordReset, list/create/update/delete
// ManagedUser(s), setupStatus.
import { createHash } from 'node:crypto';
import { isIP } from 'node:net';
const DEFAULT_COOKIE_NAME = 'auth_session';
const DEFAULT_TIMEOUT_MS = 5000;
// validate() results, positive and negative, are reused for this long so a burst of requests
// with one token costs one AuthGuard call. Revocation through this client (logout) clears the
// entry at once; revocation elsewhere is seen within the TTL. Mirrors the Go client.
const VALIDATION_CACHE_TTL_MS = 2000;
const MAX_VALIDATION_CACHE_ENTRIES = 10000;
// PROJECT_KEY_HEADER is the header AuthClient attaches to every request when
// constructed with a projectKey, identifying the calling project to
@@ -31,6 +39,14 @@ const DEFAULT_TIMEOUT_MS = 5000;
// AuthGuard's project-scope admin UI). Mirrors Go's authclient.ProjectKeyHeader.
export const PROJECT_KEY_HEADER = 'X-Project-Key';
// FORWARDED_FOR_HEADER carries the end user's address on the credential calls (the `clientIp`
// option of register, login, totpVerify, totpDisable and the password-reset calls), so AuthGuard's
// per-address limits see the end user instead of this service. AuthGuard reads it only when the
// calling service's own address is in its TRUSTED_PROXIES, so sending it changes nothing for a
// deployment that has not opted in. Pass an address the caller has already verified, never a raw
// request header; anything that is not an IP address is ignored.
export const FORWARDED_FOR_HEADER = 'X-Forwarded-For';
export class InvalidSessionError extends Error {
constructor(message = 'authclient: invalid or missing session') {
super(message);
@@ -81,6 +97,40 @@ export class AuthClient {
// Normally a project's own lowercase identifier, matching the key
// ProjectConfigurator registers it under.
this.projectKey = String(options.projectKey ?? '').trim().toLowerCase();
this._validationCache = new Map();
}
_validationKey(token) {
return createHash('sha256').update(token).digest('hex');
}
/** Returns the cached validate() outcome for token: a user, null for a known-invalid session, or undefined on a miss. */
_cachedValidation(token) {
const key = this._validationKey(token);
const entry = this._validationCache.get(key);
if (!entry) return undefined;
if (Date.now() >= entry.expires) {
this._validationCache.delete(key);
return undefined;
}
return entry.user;
}
_cacheValidation(token, user) {
if (this._validationCache.size >= MAX_VALIDATION_CACHE_ENTRIES) {
const now = Date.now();
for (const [key, entry] of this._validationCache) {
if (now >= entry.expires) this._validationCache.delete(key);
}
if (this._validationCache.size >= MAX_VALIDATION_CACHE_ENTRIES) {
// Map keeps insertion order, so this drops the oldest entry.
this._validationCache.delete(this._validationCache.keys().next().value);
}
}
this._validationCache.set(this._validationKey(token), {
user,
expires: Date.now() + VALIDATION_CACHE_TTL_MS,
});
}
_projectKeyHeaders() {
@@ -105,6 +155,7 @@ export class AuthClient {
const normalized = AuthClient._normalizeBaseUrl(baseUrl);
if (normalized) {
this.baseUrl = normalized;
this._validationCache.clear();
}
}
@@ -172,6 +223,13 @@ export class AuthClient {
if (!trimmed) {
throw new InvalidSessionError();
}
const cached = this._cachedValidation(trimmed);
if (cached === null) {
throw new InvalidSessionError();
}
if (cached !== undefined) {
return { ...cached };
}
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
@@ -192,15 +250,22 @@ export class AuthClient {
payload = await response.json();
} catch (err) {
if (response.status === 401) {
this._cacheValidation(trimmed, null);
throw new InvalidSessionError();
}
throw new Error(`authclient: decode AuthGuard response: ${err.message}`, { cause: err });
}
if (response.status !== 200 || !payload?.valid) {
if (response.status === 401 || (response.status === 200 && !payload?.valid)) {
this._cacheValidation(trimmed, null);
throw new InvalidSessionError();
}
return { id: payload.user_id, username: payload.username, role: payload.role };
if (response.status !== 200) {
throw new InvalidSessionError();
}
const user = { id: payload.user_id, username: payload.username, role: payload.role };
this._cacheValidation(trimmed, user);
return { ...user };
}
/**
@@ -258,13 +323,14 @@ export class AuthClient {
* AuthClient._call exactly.
* @returns {Promise<{payload: any, cookies: string[]}>}
*/
async _call(method, path, { token = '', body } = {}) {
async _call(method, path, { token = '', body, clientIp } = {}) {
if (!this.baseUrl) {
throw new Error('authclient: client has no base URL');
}
const headers = { ...this._projectKeyHeaders() };
if (body !== undefined) headers['Content-Type'] = 'application/json';
if (token) headers.Authorization = `Bearer ${token}`;
if (typeof clientIp === 'string' && isIP(clientIp.trim())) headers[FORWARDED_FOR_HEADER] = clientIp.trim();
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
@@ -353,9 +419,10 @@ export class AuthClient {
* starting a session for it.
* @returns {Promise<{user: object, cookies: string[]}>}
*/
async register(username, email, password) {
async register(username, email, password, { clientIp } = {}) {
const { payload, cookies } = await this._call('POST', '/api/register', {
body: { username, email, password },
clientIp,
});
return { user: AuthClient._publicUser(payload), cookies };
}
@@ -366,10 +433,10 @@ export class AuthClient {
* enabled and no valid code was supplied.
* @returns {Promise<{user: object, cookies: string[]}>}
*/
async login(usernameOrEmail, password, totpToken = '') {
async login(usernameOrEmail, password, totpToken = '', { clientIp } = {}) {
const body = { username_or_email: usernameOrEmail, password };
if (totpToken) body.totp_token = totpToken;
const { payload, cookies } = await this._call('POST', '/api/login', { body });
const { payload, cookies } = await this._call('POST', '/api/login', { body, clientIp });
return { user: AuthClient._publicUser(payload), cookies };
}
@@ -381,6 +448,7 @@ export class AuthClient {
*/
async logout(token) {
const { cookies } = await this._call('POST', '/api/logout', { token });
this._validationCache.delete(this._validationKey(String(token ?? '').trim()));
return cookies;
}
@@ -411,8 +479,8 @@ export class AuthClient {
* Calls POST /api/totp/verify, confirming code against the pending
* secret totpEnable provisioned and activating two-factor auth.
*/
async totpVerify(token, code) {
await this._call('POST', '/api/totp/verify', { token, body: { token: code } });
async totpVerify(token, code, { clientIp } = {}) {
await this._call('POST', '/api/totp/verify', { token, body: { token: code }, clientIp });
}
/**
@@ -420,8 +488,8 @@ export class AuthClient {
* account. AuthGuard requires code to be one last valid TOTP code as
* proof of possession.
*/
async totpDisable(token, code) {
await this._call('POST', '/api/totp/disable', { token, body: { token: code } });
async totpDisable(token, code, { clientIp } = {}) {
await this._call('POST', '/api/totp/disable', { token, body: { token: code }, clientIp });
}
// --- password reset ("break glass", console-only - see AuthGuard's README) --
@@ -434,9 +502,9 @@ export class AuthClient {
* the intended place to drive this, not an individual project (see
* AuthGuard's README's "Web UI" section).
*/
async requestPasswordReset(usernameOrEmail = '') {
async requestPasswordReset(usernameOrEmail = '', { clientIp } = {}) {
const body = usernameOrEmail ? { username_or_email: usernameOrEmail } : {};
await this._call('POST', '/api/password-reset/request', { body });
await this._call('POST', '/api/password-reset/request', { body, clientIp });
}
/**
@@ -444,9 +512,10 @@ export class AuthClient {
* relayed out-of-band and a new password, and invalidates every
* existing session for that account.
*/
async confirmPasswordReset(code, newPassword) {
async confirmPasswordReset(code, newPassword, { clientIp } = {}) {
await this._call('POST', '/api/password-reset/confirm', {
body: { code, password: newPassword },
clientIp,
});
}
+41 -3
View File
@@ -18,6 +18,8 @@
* example.
*/
import crypto from 'node:crypto';
/**
* @typedef {{authGuardUrl?: string, carrierNodeUrl?: string, carrierNodeUrls?: string[]}} InfoLike
*/
@@ -58,6 +60,29 @@ export class Info {
}
}
/**
* True when the X-Internal-Auth value equals the configured secret. An unset
* or empty secret never matches, and the comparison is constant-time.
* @param {unknown} provided
* @param {unknown} secret
* @returns {boolean}
*/
export function internalSecretMatches(provided, secret) {
const expected = Buffer.from(String(secret ?? ''));
if (expected.length === 0) return false;
const actual = Buffer.from(String(provided ?? ''));
return expected.length === actual.length && crypto.timingSafeEqual(expected, actual);
}
function isServiceUrl(value) {
try {
const url = new URL(value);
return (url.protocol === 'http:' || url.protocol === 'https:') && url.host !== '';
} catch {
return false;
}
}
function normalize(info) {
let cleaned = (info.carrierNodeUrls ?? []).map((u) => String(u ?? '').trim()).filter(Boolean);
if (cleaned.length === 0 && String(info.carrierNodeUrl ?? '').trim()) {
@@ -115,13 +140,20 @@ export class Store {
/**
* Replaces the current Info, field by field, ignoring a blank/empty field
* so a partial push (e.g. only carrierNodeUrl(s) changed) never clobbers
* the other value. Returns the resulting Info. Minimal Express usage:
* the other value. Every URL must be an http or https URL with a host;
* otherwise nothing is changed and an error is thrown. Returns the resulting
* Info. Minimal Express usage:
*
* app.put('/api/core-services/internal', (req, res) => {
* if (req.get('X-Internal-Auth') !== process.env.SECRET) {
* if (!internalSecretMatches(req.get('X-Internal-Auth'), process.env.SECRET)) {
* return res.status(401).json({ error: 'internal service authentication required' });
* }
* const info = coreConfigStore.set(Info.fromJSON(req.body));
* let info;
* try {
* info = coreConfigStore.set(Info.fromJSON(req.body));
* } catch (error) {
* return res.status(400).json({ error: error.message });
* }
* res.json({ ok: true, info: info.toJSON() });
* });
*
@@ -130,6 +162,12 @@ export class Store {
*/
set(nextInfo) {
const next = normalize(nextInfo instanceof Info ? nextInfo : new Info(nextInfo));
const badUrl = [next.authGuardUrl, ...next.carrierNodeUrls].find(
(url) => url && !isServiceUrl(url)
);
if (badUrl !== undefined) {
throw new TypeError(`core service URL must be an http or https URL with a host: ${badUrl}`);
}
if (next.authGuardUrl) {
this._info.authGuardUrl = next.authGuardUrl;
}
+30 -3
View File
@@ -32,6 +32,18 @@ export function isTransientConnectionError(error) {
);
}
const READ_ONLY_STATEMENT = /^\s*select\b/i;
const LOCKING_OR_WRITING_READ = /\bfor\s+(update|share|no\s+key\s+update|key\s+share)\b|\binto\b|\b(nextval|setval)\s*\(/i;
/**
* True for a plain SELECT that cannot change data or sequences. Only these
* statements are retried after a transient error by default.
*/
export function isReadOnlyStatement(text) {
const sql = String(text);
return READ_ONLY_STATEMENT.test(sql) && !LOCKING_OR_WRITING_READ.test(sql);
}
/**
* Owns one pg pool and exposes bounded startup, retry, transaction, and
* shutdown behavior. Domain repositories should depend on this abstraction
@@ -39,10 +51,18 @@ export function isTransientConnectionError(error) {
*/
export class Database {
constructor(options = {}) {
const { pool, ...poolOptions } = options;
const { pool, log = console.error, ...poolOptions } = options;
this.pool = pool || new Pool(poolOptions);
this.ownsPool = !pool;
this.ready = false;
this.log = log;
if (typeof this.pool.on === 'function') {
// pg emits 'error' for an idle client that fails, for example after a
// database restart. With no listener the event is thrown and can end the process.
this.pool.on('error', error => {
this.log(`[database] idle pool client error: ${error?.message || error}`);
});
}
}
static fromEnv(env = process.env) {
@@ -77,12 +97,19 @@ export class Database {
}
}
async query(text, values = []) {
/**
* Runs one statement. After a transient connection error the statement is
* retried only when it is read-only, so a write that committed before the
* connection dropped is not applied twice. Pass `{ retry: true }` to opt a
* known-idempotent statement in, or `{ retry: false }` to opt a read out.
*/
async query(text, values = [], options = {}) {
await this.connect();
try {
return await this.pool.query(text, values);
} catch (error) {
if (!isTransientConnectionError(error)) throw error;
const retry = options.retry ?? isReadOnlyStatement(text);
if (!retry || !isTransientConnectionError(error)) throw error;
return this.pool.query(text, values);
}
}
+9 -1
View File
@@ -15,12 +15,16 @@ export {
ResetManager,
createSessionToken,
hashPassword,
hashPasswordAsync,
hashToken,
USER_ROLES,
canAssignRole,
canManageUsers,
normalizeRole,
passwordHashNeedsUpgrade,
verifyAndUpgradePasswordAsync,
verifyPassword,
verifyPasswordAsync,
} from './auth.js';
export {
TOTP_DIGITS,
@@ -32,4 +36,8 @@ export {
} from './totp.js';
export { runMigrations } from './migrate.js';
export { APIError, AuthClient, InvalidSessionError, createAuthClient } from './authclient.js';
export { Info as CoreConfigInfo, Store as CoreConfigStore } from './coreconfig.js';
export {
Info as CoreConfigInfo,
Store as CoreConfigStore,
internalSecretMatches,
} from './coreconfig.js';
@@ -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);
});