feat(sync): paginate Android sync with change tokens
This commit is contained in:
1 parent
0ff94f9b10
commit
97c237be80
76 files changed
+3401
-851
No files matched your search
@@ -13,7 +13,6 @@ public final class Totp {
|
||||
private static final String BASE32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
|
||||
private static final int SECRET_BYTES = 20;
|
||||
private static final int PERIOD_SECONDS = 30;
|
||||
private static final int WINDOW = 1;
|
||||
private static final int DIGITS = 6;
|
||||
private static final SecureRandom RANDOM = new SecureRandom();
|
||||
|
||||
@@ -43,22 +42,28 @@ public final class Totp {
|
||||
}
|
||||
|
||||
public static boolean verify(String secret, String token, long nowMillis) {
|
||||
return verifyStep(secret, token, nowMillis) >= 0;
|
||||
}
|
||||
|
||||
/** Returns the matching 30-second step, or {@code -1} when no code matches. */
|
||||
public static long verifyStep(String secret, String token, long nowMillis) {
|
||||
String normalizedSecret = normalizeSecret(secret);
|
||||
String normalizedToken = token == null ? "" : token.trim();
|
||||
if (normalizedSecret.isEmpty() || !normalizedToken.matches("\\d{" + DIGITS + "}")) {
|
||||
return false;
|
||||
return -1;
|
||||
}
|
||||
byte[] key;
|
||||
try {
|
||||
key = decodeBase32(normalizedSecret);
|
||||
} catch (IllegalArgumentException ex) {
|
||||
return false;
|
||||
return -1;
|
||||
}
|
||||
if (key.length == 0) {
|
||||
return false;
|
||||
return -1;
|
||||
}
|
||||
long counter = Math.floorDiv(nowMillis, PERIOD_SECONDS * 1000L);
|
||||
for (long offset = -WINDOW; offset <= WINDOW; offset++) {
|
||||
// Prefer the current step if a six-digit collision occurs in the window.
|
||||
for (long offset : new long[] {0, -1, 1}) {
|
||||
if (counter + offset < 0) {
|
||||
continue;
|
||||
}
|
||||
@@ -80,13 +85,13 @@ public final class Totp {
|
||||
String candidate = String.format(Locale.ROOT, "%06d", code % 1_000_000);
|
||||
if (MessageDigest.isEqual(candidate.getBytes(StandardCharsets.US_ASCII),
|
||||
normalizedToken.getBytes(StandardCharsets.US_ASCII))) {
|
||||
return true;
|
||||
return counter + offset;
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
return false;
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
return -1;
|
||||
}
|
||||
|
||||
private static String normalizeSecret(String value) {
|
||||
|
||||
@@ -15,6 +15,7 @@ class TotpTest {
|
||||
void verifyAcceptsTheRfc6238Vectors() {
|
||||
// The RFC lists 8-digit codes; these are their last six digits.
|
||||
assertTrue(Totp.verify(RFC_SECRET, "287082", 59_000L));
|
||||
assertEquals(1L, Totp.verifyStep(RFC_SECRET, "287082", 59_000L));
|
||||
assertTrue(Totp.verify(RFC_SECRET, "081804", 1_111_111_109_000L));
|
||||
assertTrue(Totp.verify(RFC_SECRET, "050471", 1_111_111_111_000L));
|
||||
assertTrue(Totp.verify(RFC_SECRET, "005924", 1_234_567_890_000L));
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"dependencies": {
|
||||
"bcryptjs": "^3.0.3",
|
||||
"pg": "^8.17.2"
|
||||
},
|
||||
"scripts": {
|
||||
|
||||
@@ -1,16 +1,20 @@
|
||||
import crypto from 'node:crypto';
|
||||
import { promisify } from 'node:util';
|
||||
import bcrypt from 'bcryptjs';
|
||||
import { verifyTotpStep } from './totp.js';
|
||||
|
||||
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.
|
||||
// Node's old formats remain readable so successful logins can migrate them.
|
||||
const LEGACY_PASSWORD_ITERATIONS = 100000;
|
||||
const PASSWORD_ITERATIONS = 600000;
|
||||
const MAX_PBKDF2_ITERATIONS = 10000000;
|
||||
const PASSWORD_KEY_LENGTH = 32;
|
||||
const PASSWORD_DIGEST = 'sha256';
|
||||
const PASSWORD_FORMAT = 'pbkdf2-sha256';
|
||||
const BCRYPT_SCHEME = 'bcrypt$';
|
||||
const BCRYPT_SHA256_SCHEME = 'bcrypt-sha256$';
|
||||
const BCRYPT_ROUNDS = 12;
|
||||
const BCRYPT_MAX_PASSWORD_BYTES = 72;
|
||||
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' });
|
||||
@@ -38,6 +42,7 @@ CREATE TABLE IF NOT EXISTS auth_users (
|
||||
role TEXT NOT NULL DEFAULT 'user',
|
||||
totp_secret TEXT NOT NULL DEFAULT '',
|
||||
totp_enabled BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
last_used_step BIGINT NOT NULL DEFAULT -1,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
@@ -45,6 +50,7 @@ ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS email TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS role TEXT NOT NULL DEFAULT 'user';
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_secret TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_enabled BOOLEAN NOT NULL DEFAULT FALSE;
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS last_used_step BIGINT NOT NULL DEFAULT -1;
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT now();
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT now();
|
||||
UPDATE auth_users SET role = 'superadmin'
|
||||
@@ -100,38 +106,47 @@ function assertPasswordLength(password) {
|
||||
if (typeof password !== 'string' || password.length < 8) {
|
||||
throw new Error('Password must be at least 8 characters');
|
||||
}
|
||||
if (Buffer.byteLength(password, 'utf8') > BCRYPT_MAX_PASSWORD_BYTES) {
|
||||
throw new Error(`Password must be at most ${BCRYPT_MAX_PASSWORD_BYTES} bytes`);
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
function parsePbkdf2Hash(stored) {
|
||||
const text = String(stored);
|
||||
let iterations = LEGACY_PASSWORD_ITERATIONS;
|
||||
let salt;
|
||||
let expected;
|
||||
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 };
|
||||
[, iterations, salt, expected] = parts;
|
||||
iterations = Number(iterations);
|
||||
} else if (LEGACY_PASSWORD_PATTERN.test(text)) {
|
||||
[salt, expected] = text.split(':');
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
if (!/^[0-9a-f]{32}$/.test(salt) || !/^[0-9a-f]{64}$/.test(expected)) return null;
|
||||
if (!Number.isSafeInteger(iterations) || iterations < 1 || iterations > MAX_PBKDF2_ITERATIONS) return null;
|
||||
return { iterations, salt, expected };
|
||||
}
|
||||
|
||||
function parseBcryptHash(stored) {
|
||||
const text = String(stored);
|
||||
if (text.startsWith(BCRYPT_SHA256_SCHEME)) return { hash: text.slice(BCRYPT_SHA256_SCHEME.length), prehashed: true };
|
||||
if (text.startsWith(BCRYPT_SCHEME)) return { hash: text.slice(BCRYPT_SCHEME.length), prehashed: false };
|
||||
if (/^\$2[aby]\$/.test(text)) return { hash: text, prehashed: false, 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 validBcryptHash(parsed) {
|
||||
if (!parsed?.hash) return false;
|
||||
try {
|
||||
bcrypt.getRounds(parsed.hash);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function passwordHashMatches(expected, actual) {
|
||||
@@ -140,34 +155,52 @@ function passwordHashMatches(expected, actual) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Blocking PBKDF2 hash. Prefer hashPasswordAsync in request handlers, because
|
||||
* Blocking bcrypt hash. Prefer hashPasswordAsync in request handlers, because
|
||||
* this call holds the event loop for the whole derivation.
|
||||
*/
|
||||
export function hashPassword(password, { iterations = PASSWORD_ITERATIONS } = {}) {
|
||||
export function hashPassword(password) {
|
||||
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);
|
||||
return BCRYPT_SCHEME + bcrypt.hashSync(password, BCRYPT_ROUNDS);
|
||||
}
|
||||
|
||||
/** Non-blocking variant of hashPassword with the same output format. */
|
||||
export async function hashPasswordAsync(password, { iterations = PASSWORD_ITERATIONS } = {}) {
|
||||
/** Non-blocking variant of hashPassword with the same bcrypt format. */
|
||||
export async function hashPasswordAsync(password) {
|
||||
assertPasswordLength(password);
|
||||
return derivePasswordHashAsync(password, iterations);
|
||||
return BCRYPT_SCHEME + await bcrypt.hash(password, BCRYPT_ROUNDS);
|
||||
}
|
||||
|
||||
// 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);
|
||||
// A legacy PBKDF2 password can exceed bcrypt's 72-byte input limit. Preserve
|
||||
// the full password by hashing its UTF-8 bytes before bcrypt and marking that
|
||||
// representation explicitly in the stored scheme.
|
||||
function bcryptInputForLegacyPassword(password) {
|
||||
const text = String(password);
|
||||
if (Buffer.byteLength(text, 'utf8') <= BCRYPT_MAX_PASSWORD_BYTES) {
|
||||
return { scheme: BCRYPT_SCHEME, input: text };
|
||||
}
|
||||
return {
|
||||
scheme: BCRYPT_SHA256_SCHEME,
|
||||
input: crypto.createHash('sha256').update(text, 'utf8').digest('hex'),
|
||||
};
|
||||
}
|
||||
|
||||
async function derivePasswordHashAsync(password) {
|
||||
const { scheme, input } = bcryptInputForLegacyPassword(password);
|
||||
return scheme + await bcrypt.hash(input, BCRYPT_ROUNDS);
|
||||
}
|
||||
|
||||
/** Blocking verify. Prefer verifyPasswordAsync in request handlers. */
|
||||
export function verifyPassword(password, stored) {
|
||||
try {
|
||||
const parsed = usablePasswordHash(stored);
|
||||
const bcryptHash = parseBcryptHash(stored);
|
||||
if (bcryptHash) {
|
||||
if (!validBcryptHash(bcryptHash)) return false;
|
||||
const input = bcryptHash.prehashed
|
||||
? crypto.createHash('sha256').update(String(password), 'utf8').digest('hex')
|
||||
: String(password);
|
||||
if (!bcryptHash.prehashed && Buffer.byteLength(input, 'utf8') > BCRYPT_MAX_PASSWORD_BYTES) return false;
|
||||
return bcrypt.compareSync(input, bcryptHash.hash);
|
||||
}
|
||||
const parsed = parsePbkdf2Hash(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);
|
||||
@@ -179,7 +212,16 @@ export function verifyPassword(password, stored) {
|
||||
/** Non-blocking variant of verifyPassword. */
|
||||
export async function verifyPasswordAsync(password, stored) {
|
||||
try {
|
||||
const parsed = usablePasswordHash(stored);
|
||||
const bcryptHash = parseBcryptHash(stored);
|
||||
if (bcryptHash) {
|
||||
if (!validBcryptHash(bcryptHash)) return false;
|
||||
const input = bcryptHash.prehashed
|
||||
? crypto.createHash('sha256').update(String(password), 'utf8').digest('hex')
|
||||
: String(password);
|
||||
if (!bcryptHash.prehashed && Buffer.byteLength(input, 'utf8') > BCRYPT_MAX_PASSWORD_BYTES) return false;
|
||||
return await bcrypt.compare(input, bcryptHash.hash);
|
||||
}
|
||||
const parsed = parsePbkdf2Hash(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);
|
||||
@@ -189,12 +231,15 @@ export async function verifyPasswordAsync(password, stored) {
|
||||
}
|
||||
|
||||
/**
|
||||
* True when a stored hash should be rewritten after a successful login: a
|
||||
* legacy `salt:hex` hash, or a PBKDF2 hash below PASSWORD_ITERATIONS.
|
||||
* True when a stored hash should be rewritten after a successful login.
|
||||
*/
|
||||
export function passwordHashNeedsUpgrade(stored) {
|
||||
const parsed = parsePasswordHash(stored);
|
||||
return !parsed || parsed.legacy || parsed.iterations < PASSWORD_ITERATIONS;
|
||||
const bcryptHash = parseBcryptHash(stored);
|
||||
if (bcryptHash) {
|
||||
if (!validBcryptHash(bcryptHash)) return true;
|
||||
return Boolean(bcryptHash.legacy) || bcrypt.getRounds(bcryptHash.hash) < BCRYPT_ROUNDS;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -210,7 +255,7 @@ export async function verifyAndUpgradePasswordAsync(password, stored) {
|
||||
if (!passwordHashNeedsUpgrade(stored)) {
|
||||
return { valid: true, upgradedHash: null };
|
||||
}
|
||||
return { valid: true, upgradedHash: await derivePasswordHashAsync(password, PASSWORD_ITERATIONS) };
|
||||
return { valid: true, upgradedHash: await derivePasswordHashAsync(password) };
|
||||
}
|
||||
|
||||
export function createSessionToken() {
|
||||
@@ -412,10 +457,10 @@ export class AuthStore {
|
||||
|
||||
async getTotpState(userId) {
|
||||
const result = await this.database.query(
|
||||
'SELECT COALESCE(totp_secret, \'\') AS secret, COALESCE(totp_enabled, false) AS enabled FROM auth_users WHERE id = $1',
|
||||
'SELECT COALESCE(totp_secret, \'\') AS secret, COALESCE(totp_enabled, false) AS enabled, COALESCE(last_used_step, -1) AS last_used_step FROM auth_users WHERE id = $1',
|
||||
[userId],
|
||||
);
|
||||
return result.rows[0] || { secret: '', enabled: false };
|
||||
return result.rows[0] || { secret: '', enabled: false, last_used_step: -1 };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -425,7 +470,7 @@ export class AuthStore {
|
||||
*/
|
||||
async setTotpSecret(userId, secret) {
|
||||
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',
|
||||
'UPDATE auth_users SET totp_secret = $1, totp_enabled = false, last_used_step = -1, updated_at = now() WHERE id = $2 AND NOT totp_enabled',
|
||||
[secret, userId],
|
||||
);
|
||||
if (result.rowCount === 0 && (await this.getTotpState(userId)).enabled) {
|
||||
@@ -433,16 +478,33 @@ export class AuthStore {
|
||||
}
|
||||
}
|
||||
|
||||
async enableTotp(userId) {
|
||||
await this.database.query(
|
||||
"UPDATE auth_users SET totp_enabled = true, updated_at = now() WHERE id = $1 AND totp_secret <> ''",
|
||||
[userId],
|
||||
async enableTotp(userId, token, now = Date.now()) {
|
||||
const state = await this.getTotpState(userId);
|
||||
if (!state.secret || state.enabled) return false;
|
||||
const step = verifyTotpStep(state.secret, token, now);
|
||||
if (step === null) return false;
|
||||
const result = await this.database.query(
|
||||
"UPDATE auth_users SET totp_enabled = true, last_used_step = $1, updated_at = now() WHERE id = $2 AND totp_secret = $3 AND NOT totp_enabled AND last_used_step < $1",
|
||||
[step, userId, state.secret],
|
||||
);
|
||||
return result.rowCount === 1;
|
||||
}
|
||||
|
||||
async consumeTotpCode(userId, token, now = Date.now()) {
|
||||
const state = await this.getTotpState(userId);
|
||||
if (!state.secret || !state.enabled) return false;
|
||||
const step = verifyTotpStep(state.secret, token, now);
|
||||
if (step === null) return false;
|
||||
const result = await this.database.query(
|
||||
'UPDATE auth_users SET last_used_step = $1, updated_at = now() WHERE id = $2 AND totp_enabled AND totp_secret = $3 AND last_used_step < $1',
|
||||
[step, userId, state.secret],
|
||||
);
|
||||
return result.rowCount === 1;
|
||||
}
|
||||
|
||||
async disableTotp(userId) {
|
||||
await this.database.query(
|
||||
"UPDATE auth_users SET totp_secret = '', totp_enabled = false, updated_at = now() WHERE id = $1",
|
||||
"UPDATE auth_users SET totp_secret = '', totp_enabled = false, last_used_step = -1, updated_at = now() WHERE id = $1",
|
||||
[userId],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -60,16 +60,38 @@ export class Info {
|
||||
}
|
||||
}
|
||||
|
||||
/** Shortest SECRET a service accepts for its internal routes. */
|
||||
export const MIN_INTERNAL_SECRET_LENGTH = 16;
|
||||
|
||||
/**
|
||||
* True when the X-Internal-Auth value equals the configured secret. An unset
|
||||
* or empty secret never matches, and the comparison is constant-time.
|
||||
* Placeholders from .env.example files and the bare variable name. They are
|
||||
* public, so they never gate a route.
|
||||
*/
|
||||
export const EXAMPLE_INTERNAL_SECRETS = new Set(['SECRET', 'change-me-to-a-long-random-value']);
|
||||
|
||||
/**
|
||||
* True when the configured secret is strong enough to gate an internal route:
|
||||
* at least MIN_INTERNAL_SECRET_LENGTH characters and not an example
|
||||
* placeholder. Length counts characters, as the Python and Go helpers do.
|
||||
* @param {unknown} secret
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function internalSecretUsable(secret) {
|
||||
const value = String(secret ?? '');
|
||||
return [...value].length >= MIN_INTERNAL_SECRET_LENGTH && !EXAMPLE_INTERNAL_SECRETS.has(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* True when the X-Internal-Auth value equals the configured secret. A secret
|
||||
* that is not usable (see internalSecretUsable) 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;
|
||||
if (!internalSecretUsable(secret)) return false;
|
||||
const expected = Buffer.from(String(secret));
|
||||
const actual = Buffer.from(String(provided ?? ''));
|
||||
return expected.length === actual.length && crypto.timingSafeEqual(expected, actual);
|
||||
}
|
||||
|
||||
@@ -33,11 +33,15 @@ export {
|
||||
generateTotpSecret,
|
||||
totpProvisioningUri,
|
||||
verifyTotp,
|
||||
verifyTotpStep,
|
||||
} from './totp.js';
|
||||
export { runMigrations } from './migrate.js';
|
||||
export { APIError, AuthClient, InvalidSessionError, createAuthClient } from './authclient.js';
|
||||
export {
|
||||
EXAMPLE_INTERNAL_SECRETS,
|
||||
Info as CoreConfigInfo,
|
||||
MIN_INTERNAL_SECRET_LENGTH,
|
||||
Store as CoreConfigStore,
|
||||
internalSecretMatches,
|
||||
internalSecretUsable,
|
||||
} from './coreconfig.js';
|
||||
@@ -24,19 +24,24 @@ export function totpProvisioningUri(issuer, account, secret) {
|
||||
}
|
||||
|
||||
export function verifyTotp(secret, token, now = Date.now()) {
|
||||
return verifyTotpStep(secret, token, now) !== null;
|
||||
}
|
||||
|
||||
export function verifyTotpStep(secret, token, now = Date.now()) {
|
||||
const normalizedSecret = normalizeSecret(secret);
|
||||
const normalizedToken = normalizeToken(token);
|
||||
if (!normalizedSecret || normalizedToken.length !== TOTP_DIGITS) return false;
|
||||
if (!normalizedSecret || normalizedToken.length !== TOTP_DIGITS) return null;
|
||||
|
||||
let key;
|
||||
try {
|
||||
key = decodeBase32(normalizedSecret);
|
||||
} catch {
|
||||
return false;
|
||||
return null;
|
||||
}
|
||||
if (key.length === 0) return false;
|
||||
if (key.length === 0) return null;
|
||||
const period = Math.floor(now / 1000 / TOTP_PERIOD_SECONDS);
|
||||
for (let offset = -TOTP_WINDOW; offset <= TOTP_WINDOW; offset += 1) {
|
||||
// Prefer the current step if a six-digit collision occurs in the window.
|
||||
for (const offset of [0, -1, 1]) {
|
||||
if (period + offset < 0) continue;
|
||||
const counter = Buffer.alloc(8);
|
||||
counter.writeBigUInt64BE(BigInt(period + offset));
|
||||
@@ -47,9 +52,9 @@ export function verifyTotp(secret, token, now = Date.now()) {
|
||||
| (digest[index + 2] << 8)
|
||||
| digest[index + 3];
|
||||
const candidate = String(value % 1000000).padStart(TOTP_DIGITS, '0');
|
||||
if (crypto.timingSafeEqual(Buffer.from(candidate), Buffer.from(normalizedToken))) return true;
|
||||
if (crypto.timingSafeEqual(Buffer.from(candidate), Buffer.from(normalizedToken))) return period + offset;
|
||||
}
|
||||
return false;
|
||||
return null;
|
||||
}
|
||||
|
||||
function normalizeSecret(value) {
|
||||
|
||||
@@ -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\//);
|
||||
});
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
});
|
||||
@@ -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', () => {
|
||||
|
||||
@@ -129,6 +129,11 @@ async def push_core_services(request):
|
||||
return {"ok": True, "info": info.to_json()}
|
||||
```
|
||||
|
||||
`internal_secret_matches` also refuses a SECRET shorter than `MIN_INTERNAL_SECRET_LENGTH`
|
||||
(16 characters) or equal to an example placeholder (`EXAMPLE_INTERNAL_SECRETS`), so every
|
||||
internal route gated by it rejects all callers until the secret is set properly. Call
|
||||
`internal_secret_usable(SECRET)` at startup to log a warning for that case.
|
||||
|
||||
## `authproxy`: a ready-to-mount FastAPI router (optional)
|
||||
|
||||
Wiring up `authclient` still leaves each service reimplementing the same
|
||||
|
||||
@@ -28,12 +28,12 @@ from .authclient import (
|
||||
token_from_request,
|
||||
)
|
||||
from .config import DatabaseConfig, database_url_from_env
|
||||
from .coreconfig import MIN_INTERNAL_SECRET_LENGTH, internal_secret_matches, internal_secret_usable
|
||||
from .coreconfig import Info as CoreConfigInfo
|
||||
from .coreconfig import Store as CoreConfigStore
|
||||
from .coreconfig import internal_secret_matches
|
||||
from .postgres import Database
|
||||
from .tokens import hash_token, new_session_token
|
||||
from .totp import generate_totp_secret, totp_provisioning_uri, verify_totp
|
||||
from .totp import generate_totp_secret, totp_provisioning_uri, verify_totp, verify_totp_step
|
||||
|
||||
__all__ = [
|
||||
"AuthStore",
|
||||
@@ -47,6 +47,8 @@ __all__ = [
|
||||
"CoreConfigInfo",
|
||||
"CoreConfigStore",
|
||||
"internal_secret_matches",
|
||||
"internal_secret_usable",
|
||||
"MIN_INTERNAL_SECRET_LENGTH",
|
||||
"ROLE_ADMIN",
|
||||
"ROLE_SUPERADMIN",
|
||||
"ROLE_USER",
|
||||
@@ -70,4 +72,5 @@ __all__ = [
|
||||
"verify_password",
|
||||
"verify_password_async",
|
||||
"verify_totp",
|
||||
"verify_totp_step",
|
||||
]
|
||||
@@ -3,6 +3,9 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import hmac
|
||||
import re
|
||||
import secrets
|
||||
import threading
|
||||
from dataclasses import dataclass
|
||||
@@ -12,6 +15,7 @@ import asyncpg
|
||||
import bcrypt
|
||||
|
||||
from .postgres import Database
|
||||
from .totp import verify_totp_step
|
||||
|
||||
_SCHEMA = """
|
||||
CREATE TABLE IF NOT EXISTS auth_users (
|
||||
@@ -22,6 +26,7 @@ CREATE TABLE IF NOT EXISTS auth_users (
|
||||
role TEXT NOT NULL DEFAULT 'user',
|
||||
totp_secret TEXT NOT NULL DEFAULT '',
|
||||
totp_enabled BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
last_used_step BIGINT NOT NULL DEFAULT -1,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
@@ -29,6 +34,7 @@ ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS email TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS role TEXT NOT NULL DEFAULT 'user';
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_secret TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_enabled BOOLEAN NOT NULL DEFAULT FALSE;
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS last_used_step BIGINT NOT NULL DEFAULT -1;
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT now();
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT now();
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_email_idx
|
||||
@@ -179,7 +185,12 @@ def _validate_credentials(username: str | None, password_hash: str | None) -> No
|
||||
# so a stored value reads "bcrypt$$2b$12$...". Unprefixed bcrypt hashes written
|
||||
# before the prefix still verify and are rewritten on the next successful login.
|
||||
_BCRYPT_SCHEME = "bcrypt$"
|
||||
_BCRYPT_SHA256_SCHEME = "bcrypt-sha256$"
|
||||
_LEGACY_BCRYPT_PREFIXES = ("$2a$", "$2b$", "$2y$")
|
||||
_PBKDF2_SCHEME = "pbkdf2-sha256"
|
||||
BCRYPT_MAX_PASSWORD_BYTES = 72
|
||||
_LEGACY_PBKDF2_ITERATIONS = 100_000
|
||||
_MAX_PBKDF2_ITERATIONS = 10_000_000
|
||||
BCRYPT_ROUNDS = 12
|
||||
|
||||
|
||||
@@ -188,9 +199,9 @@ def _new_bcrypt_hash(password: str) -> str:
|
||||
return _BCRYPT_SCHEME + hashed.decode("utf-8")
|
||||
|
||||
|
||||
# bcrypt reads only the first 72 bytes. Older bcrypt releases drop the rest silently, so the limit
|
||||
# is enforced here instead of depending on the installed version.
|
||||
MAX_PASSWORD_BYTES = 72
|
||||
# bcrypt reads only the first 72 bytes, so new passwords are refused above this limit. Legacy
|
||||
# PBKDF2 passwords over the limit are migrated with an explicitly marked SHA-256 pre-hash.
|
||||
MAX_PASSWORD_BYTES = BCRYPT_MAX_PASSWORD_BYTES
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
@@ -209,24 +220,75 @@ def _bcrypt_string_of(stored_hash: str) -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
def _bcrypt_hash_info(stored_hash: str) -> tuple[str, bool, bool] | None:
|
||||
if stored_hash.startswith(_BCRYPT_SHA256_SCHEME):
|
||||
return stored_hash[len(_BCRYPT_SHA256_SCHEME) :], True, False
|
||||
if stored_hash.startswith(_BCRYPT_SCHEME):
|
||||
return stored_hash[len(_BCRYPT_SCHEME) :], False, False
|
||||
if stored_hash.startswith(_LEGACY_BCRYPT_PREFIXES):
|
||||
return stored_hash, False, True
|
||||
return None
|
||||
|
||||
|
||||
def _pbkdf2_hash_info(stored_hash: str) -> tuple[int, str, str] | None:
|
||||
if stored_hash.startswith(f"{_PBKDF2_SCHEME}$"):
|
||||
parts = stored_hash.split("$")
|
||||
if len(parts) != 4:
|
||||
return None
|
||||
_, raw_iterations, salt, expected = parts
|
||||
try:
|
||||
iterations = int(raw_iterations)
|
||||
except ValueError:
|
||||
return None
|
||||
elif re.fullmatch(r"[0-9a-f]+:[0-9a-f]+", stored_hash):
|
||||
salt, expected = stored_hash.split(":", 1)
|
||||
iterations = _LEGACY_PBKDF2_ITERATIONS
|
||||
else:
|
||||
return None
|
||||
if len(salt) != 32 or len(expected) != 64 or not (1 <= iterations <= _MAX_PBKDF2_ITERATIONS):
|
||||
return None
|
||||
return iterations, salt, expected
|
||||
|
||||
|
||||
def _new_bcrypt_sha256_hash(password: str) -> str:
|
||||
digest = hashlib.sha256(password.encode("utf-8")).hexdigest()
|
||||
hashed = bcrypt.hashpw(digest.encode("ascii"), bcrypt.gensalt(rounds=BCRYPT_ROUNDS))
|
||||
return _BCRYPT_SHA256_SCHEME + hashed.decode("utf-8")
|
||||
|
||||
|
||||
def verify_password(password: str, stored_hash: str) -> bool:
|
||||
bcrypt_hash = _bcrypt_string_of(stored_hash)
|
||||
if bcrypt_hash is None:
|
||||
return False
|
||||
try:
|
||||
return bcrypt.checkpw(password.encode("utf-8"), bcrypt_hash.encode("utf-8"))
|
||||
except (ValueError, TypeError):
|
||||
bcrypt_info = _bcrypt_hash_info(stored_hash)
|
||||
if bcrypt_info is not None:
|
||||
bcrypt_hash, prehashed, _ = bcrypt_info
|
||||
raw_password = password.encode("utf-8")
|
||||
if prehashed:
|
||||
raw_password = hashlib.sha256(raw_password).hexdigest().encode("ascii")
|
||||
elif len(raw_password) > BCRYPT_MAX_PASSWORD_BYTES:
|
||||
return False
|
||||
try:
|
||||
return bcrypt.checkpw(raw_password, bcrypt_hash.encode("utf-8"))
|
||||
except (ValueError, TypeError):
|
||||
return False
|
||||
|
||||
parsed = _pbkdf2_hash_info(stored_hash)
|
||||
if parsed is None:
|
||||
return False
|
||||
iterations, salt, expected = parsed
|
||||
actual = hashlib.pbkdf2_hmac(
|
||||
"sha256", password.encode("utf-8"), salt.encode("ascii"), iterations
|
||||
)
|
||||
return hmac.compare_digest(actual.hex(), expected)
|
||||
|
||||
|
||||
def password_hash_needs_upgrade(stored_hash: str) -> bool:
|
||||
"""True for an unprefixed legacy hash, or a bcrypt cost below BCRYPT_ROUNDS."""
|
||||
if not stored_hash.startswith(_BCRYPT_SCHEME):
|
||||
"""True for legacy PBKDF2/bcrypt formats or a bcrypt cost below policy."""
|
||||
bcrypt_info = _bcrypt_hash_info(stored_hash)
|
||||
if bcrypt_info is None:
|
||||
return True
|
||||
# The bcrypt string after the prefix is "$2b$<cost>$<salt+hash>".
|
||||
parts = stored_hash[len(_BCRYPT_SCHEME) :].split("$")
|
||||
bcrypt_hash, _, legacy = bcrypt_info
|
||||
parts = bcrypt_hash.split("$")
|
||||
try:
|
||||
return int(parts[2]) < BCRYPT_ROUNDS
|
||||
return legacy or int(parts[2]) < BCRYPT_ROUNDS
|
||||
except (IndexError, ValueError):
|
||||
return True
|
||||
|
||||
@@ -243,6 +305,8 @@ def verify_and_upgrade_password(password: str, stored_hash: str) -> tuple[bool,
|
||||
if not password_hash_needs_upgrade(stored_hash):
|
||||
return True, None
|
||||
# The length rule applies when a password is first set, not when an old hash is upgraded.
|
||||
if len(password.encode("utf-8")) > BCRYPT_MAX_PASSWORD_BYTES:
|
||||
return True, _new_bcrypt_sha256_hash(password)
|
||||
return True, _new_bcrypt_hash(password)
|
||||
|
||||
|
||||
@@ -431,18 +495,19 @@ class AuthStore:
|
||||
|
||||
async def get_totp_state(self, user_id: int) -> dict[str, object]:
|
||||
row = await self.database.fetchrow(
|
||||
"SELECT COALESCE(totp_secret, '') AS secret, COALESCE(totp_enabled, false) AS enabled "
|
||||
"SELECT COALESCE(totp_secret, '') AS secret, COALESCE(totp_enabled, false) AS enabled, "
|
||||
"COALESCE(last_used_step, -1) AS last_used_step "
|
||||
"FROM auth_users WHERE id = $1",
|
||||
user_id,
|
||||
)
|
||||
return dict(row) if row else {"secret": "", "enabled": False}
|
||||
return dict(row) if row else {"secret": "", "enabled": False, "last_used_step": -1}
|
||||
|
||||
async def set_totp_secret(self, user_id: int, secret: str) -> None:
|
||||
"""Stores a pending secret without enabling two-factor auth. Raises
|
||||
TotpAlreadyEnabledError while it is enabled, so a replaced secret cannot silently switch
|
||||
the second factor off."""
|
||||
status = await self.database.execute(
|
||||
"UPDATE auth_users SET totp_secret = $1, totp_enabled = false, "
|
||||
"UPDATE auth_users SET totp_secret = $1, totp_enabled = false, last_used_step = -1, "
|
||||
"updated_at = now() WHERE id = $2 AND NOT totp_enabled",
|
||||
secret,
|
||||
user_id,
|
||||
@@ -450,16 +515,41 @@ class AuthStore:
|
||||
if status == "UPDATE 0" and (await self.get_totp_state(user_id))["enabled"]:
|
||||
raise TotpAlreadyEnabledError("TOTP is already enabled; disable it first")
|
||||
|
||||
async def enable_totp(self, user_id: int) -> None:
|
||||
await self.database.execute(
|
||||
"UPDATE auth_users SET totp_enabled = true, updated_at = now() "
|
||||
"WHERE id = $1 AND totp_secret <> ''",
|
||||
async def enable_totp(self, user_id: int, token: str, now: float | None = None) -> bool:
|
||||
state = await self.get_totp_state(user_id)
|
||||
if not state["secret"] or state["enabled"]:
|
||||
return False
|
||||
step = verify_totp_step(str(state["secret"]), token, now)
|
||||
if step is None:
|
||||
return False
|
||||
status = await self.database.execute(
|
||||
"UPDATE auth_users SET totp_enabled = true, last_used_step = $1, updated_at = now() "
|
||||
"WHERE id = $2 AND totp_secret = $3 AND NOT totp_enabled AND last_used_step < $1",
|
||||
step,
|
||||
user_id,
|
||||
state["secret"],
|
||||
)
|
||||
return status == "UPDATE 1"
|
||||
|
||||
async def consume_totp_code(self, user_id: int, token: str, now: float | None = None) -> bool:
|
||||
state = await self.get_totp_state(user_id)
|
||||
if not state["secret"] or not state["enabled"]:
|
||||
return False
|
||||
step = verify_totp_step(str(state["secret"]), token, now)
|
||||
if step is None:
|
||||
return False
|
||||
status = await self.database.execute(
|
||||
"UPDATE auth_users SET last_used_step = $1, updated_at = now() "
|
||||
"WHERE id = $2 AND totp_enabled AND totp_secret = $3 AND last_used_step < $1",
|
||||
step,
|
||||
user_id,
|
||||
state["secret"],
|
||||
)
|
||||
return status == "UPDATE 1"
|
||||
|
||||
async def disable_totp(self, user_id: int) -> None:
|
||||
await self.database.execute(
|
||||
"UPDATE auth_users SET totp_secret = '', totp_enabled = false, "
|
||||
"UPDATE auth_users SET totp_secret = '', totp_enabled = false, last_used_step = -1, "
|
||||
"updated_at = now() WHERE id = $1",
|
||||
user_id,
|
||||
)
|
||||
|
||||
@@ -64,11 +64,14 @@ from typing import Any, Mapping
|
||||
|
||||
DEFAULT_COOKIE_NAME = "auth_session"
|
||||
DEFAULT_TIMEOUT = 5.0
|
||||
# validate() results, positive and negative, are reused for this many seconds 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.
|
||||
# validate() results (positive and negative) and /api/me profiles are reused for this many
|
||||
# seconds so a burst of requests with one token costs one AuthGuard call. Revocation through
|
||||
# this client (logout) and token-authenticated writes clear both entries at once; changes made
|
||||
# directly in AuthGuard may take up to two seconds to reach consumers.
|
||||
VALIDATION_CACHE_TTL = 2.0
|
||||
MAX_VALIDATION_CACHE_ENTRIES = 10000
|
||||
PROFILE_CACHE_TTL = VALIDATION_CACHE_TTL
|
||||
MAX_PROFILE_CACHE_ENTRIES = MAX_VALIDATION_CACHE_ENTRIES
|
||||
|
||||
_BEARER_PREFIX = "Bearer "
|
||||
|
||||
@@ -274,6 +277,7 @@ class AuthClient:
|
||||
self.project_key = (project_key or "").strip().lower()
|
||||
self._validation_lock = threading.Lock()
|
||||
self._validation_cache: dict[str, tuple[float, AuthGuardUser | None]] = {}
|
||||
self._profile_cache: dict[str, tuple[float, PublicUser]] = {}
|
||||
|
||||
@staticmethod
|
||||
def _validation_key(token: str) -> str:
|
||||
@@ -307,8 +311,36 @@ class AuthClient:
|
||||
)
|
||||
|
||||
def _forget_validation(self, token: str) -> None:
|
||||
"""Clears cached validation and /api/me data for this token."""
|
||||
with self._validation_lock:
|
||||
self._validation_cache.pop(self._validation_key(token), None)
|
||||
key = self._validation_key(token)
|
||||
self._validation_cache.pop(key, None)
|
||||
self._profile_cache.pop(key, None)
|
||||
|
||||
def _cached_profile(self, token: str) -> tuple[bool, PublicUser | None]:
|
||||
key = self._validation_key(token)
|
||||
with self._validation_lock:
|
||||
entry = self._profile_cache.get(key)
|
||||
if entry is None:
|
||||
return False, None
|
||||
expires, profile = entry
|
||||
if time.monotonic() >= expires:
|
||||
del self._profile_cache[key]
|
||||
return False, None
|
||||
return True, profile
|
||||
|
||||
def _cache_profile(self, token: str, profile: PublicUser) -> None:
|
||||
with self._validation_lock:
|
||||
if len(self._profile_cache) >= MAX_PROFILE_CACHE_ENTRIES:
|
||||
now = time.monotonic()
|
||||
for key in [k for k, entry in self._profile_cache.items() if now >= entry[0]]:
|
||||
del self._profile_cache[key]
|
||||
if len(self._profile_cache) >= MAX_PROFILE_CACHE_ENTRIES:
|
||||
del self._profile_cache[next(iter(self._profile_cache))]
|
||||
self._profile_cache[self._validation_key(token)] = (
|
||||
time.monotonic() + PROFILE_CACHE_TTL,
|
||||
profile,
|
||||
)
|
||||
|
||||
def set_base_url(self, base_url: str) -> None:
|
||||
"""Atomically replaces the AuthGuard base URL this client calls,
|
||||
@@ -326,6 +358,7 @@ class AuthClient:
|
||||
self.base_url = normalized
|
||||
with self._validation_lock:
|
||||
self._validation_cache.clear()
|
||||
self._profile_cache.clear()
|
||||
|
||||
# --- session validation (the original, minimal surface) ----------------
|
||||
|
||||
@@ -465,6 +498,9 @@ class AuthClient:
|
||||
message = str(payload.get("error") or f"request failed ({status})")
|
||||
raise APIError(status, message, totp_required=bool(payload.get("totp_required")))
|
||||
|
||||
if token and method.upper() not in {"GET", "HEAD"}:
|
||||
self._forget_validation(token)
|
||||
|
||||
return payload, list(cookies)
|
||||
|
||||
@staticmethod
|
||||
@@ -533,9 +569,26 @@ class AuthClient:
|
||||
return cookies
|
||||
|
||||
async def me(self, token: str) -> PublicUser:
|
||||
"""Calls GET /api/me, resolving token to its account."""
|
||||
payload, _ = await self._call("GET", "/api/me", token=token)
|
||||
return self._public_user(payload)
|
||||
"""Calls GET /api/me, resolving token to its account.
|
||||
|
||||
Successful profiles are cached by the SHA-256 token digest for the
|
||||
same short window as validate(). This keeps protected API calls from
|
||||
blocking on one AuthGuard round trip each while bounding how long an
|
||||
external profile change or session revocation can remain stale.
|
||||
"""
|
||||
if not self.base_url:
|
||||
raise AuthClientError("authclient: client has no base URL")
|
||||
trimmed = (token or "").strip()
|
||||
if trimmed:
|
||||
hit, cached = self._cached_profile(trimmed)
|
||||
if hit:
|
||||
assert cached is not None
|
||||
return cached
|
||||
payload, _ = await self._call("GET", "/api/me", token=trimmed)
|
||||
profile = self._public_user(payload)
|
||||
if trimmed:
|
||||
self._cache_profile(trimmed, profile)
|
||||
return profile
|
||||
|
||||
# --- TOTP ------------------------------------------------------------------
|
||||
|
||||
|
||||
@@ -56,6 +56,7 @@ from __future__ import annotations
|
||||
|
||||
import abc
|
||||
import os
|
||||
from http.cookies import CookieError, SimpleCookie
|
||||
from typing import Any, Callable, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request, Response
|
||||
@@ -72,6 +73,7 @@ from .authclient import (
|
||||
forwarded_client_ip,
|
||||
)
|
||||
from .clientip import client_address, parse_trusted_proxies, trusted_proxies_from_env
|
||||
from .coreconfig import MIN_INTERNAL_SECRET_LENGTH, internal_secret_matches
|
||||
from .ratelimit import AttemptLimiter
|
||||
|
||||
__all__ = ["ProxyStore", "build_auth_router"]
|
||||
@@ -104,7 +106,10 @@ ERR_FEATURE_REQUIRES_AUTHGUARD = "This feature requires AUTHGUARD_URL to be conf
|
||||
# rather than a generic "internal error" indistinguishable from any other bug.
|
||||
ERR_AUTHGUARD_UNAVAILABLE = "Unable to reach the authentication service. Please try again shortly."
|
||||
ERR_AUTHGUARD_NOT_CONFIGURED = "AUTHGUARD_URL is not configured, so sessions cannot be verified."
|
||||
ERR_SECRET_NOT_SET = "SECRET environment variable is not set."
|
||||
ERR_SECRET_NOT_SET = (
|
||||
"SECRET environment variable is unset, shorter than "
|
||||
f"{MIN_INTERNAL_SECRET_LENGTH} characters, or an example placeholder."
|
||||
)
|
||||
ERR_ADMIN_REQUIRED = "Administrator access required."
|
||||
|
||||
# _LOCAL_PROFILE is the fixed placeholder identity every handler reports when
|
||||
@@ -175,6 +180,8 @@ class UpdateMeRequest(BaseModel):
|
||||
email: str = ""
|
||||
username: str = ""
|
||||
password: str = ""
|
||||
currentPassword: str = ""
|
||||
totpToken: str = ""
|
||||
|
||||
|
||||
class UpdateAccessRequest(BaseModel):
|
||||
@@ -333,8 +340,30 @@ def build_auth_router(
|
||||
)
|
||||
|
||||
def _forward_cookies(response: Response, cookies: list[str]) -> None:
|
||||
for cookie in cookies:
|
||||
response.headers.append("set-cookie", cookie)
|
||||
for header in cookies:
|
||||
parsed = SimpleCookie()
|
||||
try:
|
||||
parsed.load(header)
|
||||
except CookieError:
|
||||
continue
|
||||
for morsel in parsed.values():
|
||||
morsel["httponly"] = True
|
||||
morsel["samesite"] = "lax"
|
||||
if secure_cookie:
|
||||
morsel["secure"] = True
|
||||
response.headers.append("set-cookie", morsel.OutputString())
|
||||
|
||||
def _temporary_session_token(cookies: list[str]) -> str:
|
||||
for header in cookies:
|
||||
parsed = SimpleCookie()
|
||||
try:
|
||||
parsed.load(header)
|
||||
except CookieError:
|
||||
continue
|
||||
morsel = parsed.get(cookie_name)
|
||||
if morsel is not None and morsel.value:
|
||||
return morsel.value
|
||||
return ""
|
||||
|
||||
async def _current_profile(
|
||||
request: Request, client: AuthClient
|
||||
@@ -610,14 +639,42 @@ def build_auth_router(
|
||||
email = _normalize_email(req.email)
|
||||
username = _normalize_username(req.username)
|
||||
password = None
|
||||
temporary_token = ""
|
||||
if req.password:
|
||||
_validate_password(req.password)
|
||||
if not req.currentPassword:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Current password is required to change the password.",
|
||||
)
|
||||
if current.totp_enabled and not req.totpToken.strip():
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="A current authenticator code is required to change the password.",
|
||||
)
|
||||
try:
|
||||
reauthenticated = await client.login(
|
||||
current.username,
|
||||
req.currentPassword,
|
||||
req.totpToken,
|
||||
)
|
||||
except AuthClientError as exc:
|
||||
_raise_authguard_error(exc, "Current credentials could not be verified.")
|
||||
raise # unreachable
|
||||
temporary_token = _temporary_session_token(reauthenticated.cookies)
|
||||
password = req.password
|
||||
|
||||
try:
|
||||
await client.update_managed_user(
|
||||
token, current.id, username=username, email=email, password=password
|
||||
)
|
||||
try:
|
||||
await client.update_managed_user(
|
||||
token, current.id, username=username, email=email, password=password
|
||||
)
|
||||
finally:
|
||||
if password is not None and temporary_token:
|
||||
try:
|
||||
await client.logout(temporary_token)
|
||||
except AuthClientError:
|
||||
pass
|
||||
except AuthClientError as exc:
|
||||
_raise_authguard_error(exc, "Profile could not be updated.")
|
||||
raise # unreachable
|
||||
@@ -651,9 +708,8 @@ def build_auth_router(
|
||||
request: Request,
|
||||
store: ProxyStore = Depends(get_store), # noqa: B008
|
||||
) -> dict[str, bool]:
|
||||
if (
|
||||
not configured_internal_secret
|
||||
or request.headers.get("X-Internal-Auth") != configured_internal_secret
|
||||
if not internal_secret_matches(
|
||||
request.headers.get("X-Internal-Auth"), configured_internal_secret
|
||||
):
|
||||
raise HTTPException(status_code=401, detail="internal service authentication required")
|
||||
await store.set_login_required(req.loginRequired)
|
||||
|
||||
@@ -25,13 +25,29 @@ from dataclasses import dataclass, field
|
||||
from typing import Callable, Optional
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
MIN_INTERNAL_SECRET_LENGTH = 16
|
||||
"""Shortest SECRET a service accepts for its internal routes."""
|
||||
|
||||
EXAMPLE_INTERNAL_SECRETS = frozenset({"SECRET", "change-me-to-a-long-random-value"})
|
||||
"""Placeholders from .env.example files and the bare variable name. They are
|
||||
public, so they never gate a route."""
|
||||
|
||||
|
||||
def internal_secret_usable(secret: Optional[str]) -> bool:
|
||||
"""True when the configured secret is strong enough to gate an internal
|
||||
route: at least MIN_INTERNAL_SECRET_LENGTH characters and not an example
|
||||
placeholder. A route whose secret is not usable rejects every caller."""
|
||||
value = secret or ""
|
||||
return len(value) >= MIN_INTERNAL_SECRET_LENGTH and value not in EXAMPLE_INTERNAL_SECRETS
|
||||
|
||||
|
||||
def internal_secret_matches(provided: Optional[str], secret: Optional[str]) -> bool:
|
||||
"""True when the X-Internal-Auth value equals the configured secret. An
|
||||
unset or empty secret never matches, and the comparison is constant-time."""
|
||||
expected = (secret or "").encode("utf-8")
|
||||
if not expected:
|
||||
"""True when the X-Internal-Auth value equals the configured secret. A
|
||||
secret that is not usable (see internal_secret_usable) never matches, and
|
||||
the comparison is constant-time."""
|
||||
if not internal_secret_usable(secret):
|
||||
return False
|
||||
expected = (secret or "").encode("utf-8")
|
||||
return hmac.compare_digest(expected, (provided or "").encode("utf-8"))
|
||||
|
||||
|
||||
|
||||
@@ -36,19 +36,24 @@ def totp_provisioning_uri(issuer: str, account: str, secret: str) -> str:
|
||||
|
||||
|
||||
def verify_totp(secret: str, token: str, now: float | None = None) -> bool:
|
||||
return verify_totp_step(secret, token, now) is not None
|
||||
|
||||
|
||||
def verify_totp_step(secret: str, token: str, now: float | None = None) -> int | None:
|
||||
normalized_secret = _normalize_secret(secret)
|
||||
normalized_token = _normalize_token(token)
|
||||
if not normalized_secret or len(normalized_token) != TOTP_DIGITS:
|
||||
return False
|
||||
return None
|
||||
try:
|
||||
key = base64.b32decode(normalized_secret + "=" * ((8 - len(normalized_secret) % 8) % 8))
|
||||
except (ValueError, binascii.Error):
|
||||
return False
|
||||
return None
|
||||
if not key:
|
||||
return False
|
||||
return None
|
||||
|
||||
period = int((time.time() if now is None else now) // TOTP_PERIOD_SECONDS)
|
||||
for offset in range(-TOTP_WINDOW, TOTP_WINDOW + 1):
|
||||
# Prefer the current step if a six-digit collision occurs in the window.
|
||||
for offset in (0, -1, 1):
|
||||
counter = period + offset
|
||||
if counter < 0:
|
||||
continue
|
||||
@@ -62,8 +67,8 @@ def verify_totp(secret: str, token: str, now: float | None = None) -> bool:
|
||||
)
|
||||
candidate = f"{value % 1_000_000:06d}"
|
||||
if hmac.compare_digest(candidate, normalized_token):
|
||||
return True
|
||||
return False
|
||||
return counter
|
||||
return None
|
||||
|
||||
|
||||
def _normalize_secret(value: str) -> str:
|
||||
|
||||
@@ -175,15 +175,32 @@ class AccessSettingsTests(unittest.TestCase):
|
||||
self.assertEqual(response.status_code, 500)
|
||||
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": True})
|
||||
|
||||
def test_internal_update_refuses_a_short_or_placeholder_secret(self) -> None:
|
||||
for secret in ("short", "change-me-to-a-long-random-value"):
|
||||
with self.subTest(secret=secret):
|
||||
store = _FakeStore(login_required=True)
|
||||
client = TestClient(
|
||||
_build_app(store, _FakeClient(setup_required=False), internal_secret=secret)
|
||||
)
|
||||
response = client.put(
|
||||
"/api/auth/access/internal",
|
||||
headers={"X-Internal-Auth": secret},
|
||||
json={"loginRequired": False},
|
||||
)
|
||||
self.assertEqual(response.status_code, 401)
|
||||
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": True})
|
||||
|
||||
def test_internal_update_disables_login_and_uses_admin_identity(self) -> None:
|
||||
store = _FakeStore(login_required=True)
|
||||
client = TestClient(
|
||||
_build_app(store, _FakeClient(setup_required=False), internal_secret="secret")
|
||||
_build_app(
|
||||
store, _FakeClient(setup_required=False), internal_secret="internal-test-secret"
|
||||
)
|
||||
)
|
||||
|
||||
response = client.put(
|
||||
"/api/auth/access/internal",
|
||||
headers={"X-Internal-Auth": "secret"},
|
||||
headers={"X-Internal-Auth": "internal-test-secret"},
|
||||
json={"loginRequired": False},
|
||||
)
|
||||
self.assertEqual(response.status_code, 200)
|
||||
@@ -244,6 +261,97 @@ class _RoleClient(_FakeClient):
|
||||
return PublicUser(id=1, username="a", email="a@b.com", role=roles[token])
|
||||
|
||||
|
||||
class _ProfileClient(_RoleClient):
|
||||
def __init__(self, *, totp_enabled: bool = False) -> None:
|
||||
super().__init__()
|
||||
self.totp_enabled = totp_enabled
|
||||
self.login_calls: list[tuple[str, str, str]] = []
|
||||
self.update_calls: list[dict[str, object]] = []
|
||||
|
||||
async def me(self, token: str) -> PublicUser:
|
||||
if token != "admin-token":
|
||||
raise APIError(401, "unauthenticated")
|
||||
return PublicUser(
|
||||
id=1,
|
||||
username="admin",
|
||||
email="admin@example.com",
|
||||
role="superadmin",
|
||||
totp_enabled=self.totp_enabled,
|
||||
)
|
||||
|
||||
async def login(self, username_or_email: str, password: str, totp_token: str = ""):
|
||||
self.login_calls.append((username_or_email, password, totp_token))
|
||||
if password != "current-password":
|
||||
raise APIError(401, "invalid credentials")
|
||||
return SessionResult(
|
||||
user=PublicUser(id=1, username="admin", email="admin@example.com", role="superadmin"),
|
||||
cookies=["auth_session=reauth-token; Path=/; HttpOnly"],
|
||||
)
|
||||
|
||||
async def update_managed_user(self, token: str, user_id: int, **kwargs) -> None:
|
||||
self.update_calls.append({"token": token, "user_id": user_id, **kwargs})
|
||||
|
||||
|
||||
class ProfileReauthenticationTests(unittest.TestCase):
|
||||
def _put(self, fake: _ProfileClient, body: dict[str, str]):
|
||||
client = TestClient(_build_app(_FakeStore(), fake))
|
||||
return client.put(
|
||||
"/api/auth/me",
|
||||
headers={"Cookie": f"{DEFAULT_COOKIE_NAME}=admin-token"},
|
||||
json=body,
|
||||
)
|
||||
|
||||
def test_password_update_requires_current_password_and_totp_when_enabled(self) -> None:
|
||||
no_totp = _ProfileClient()
|
||||
response = self._put(
|
||||
no_totp,
|
||||
{"username": "admin", "email": "admin@example.com", "password": "new-password"},
|
||||
)
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertEqual(no_totp.login_calls, [])
|
||||
|
||||
totp = _ProfileClient(totp_enabled=True)
|
||||
response = self._put(
|
||||
totp,
|
||||
{
|
||||
"username": "admin",
|
||||
"email": "admin@example.com",
|
||||
"password": "new-password",
|
||||
"currentPassword": "current-password",
|
||||
},
|
||||
)
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertEqual(totp.login_calls, [])
|
||||
|
||||
def test_password_update_reauthenticates_and_cleans_up_temporary_session(self) -> None:
|
||||
fake = _ProfileClient(totp_enabled=True)
|
||||
response = self._put(
|
||||
fake,
|
||||
{
|
||||
"username": "admin",
|
||||
"email": "admin@example.com",
|
||||
"password": "new-password",
|
||||
"currentPassword": "current-password",
|
||||
"totpToken": "123456",
|
||||
},
|
||||
)
|
||||
self.assertEqual(response.status_code, 200, response.text)
|
||||
self.assertEqual(fake.login_calls, [("admin", "current-password", "123456")])
|
||||
self.assertEqual(
|
||||
fake.update_calls,
|
||||
[
|
||||
{
|
||||
"token": "admin-token",
|
||||
"user_id": 1,
|
||||
"username": "admin",
|
||||
"email": "admin@example.com",
|
||||
"password": "new-password",
|
||||
}
|
||||
],
|
||||
)
|
||||
self.assertIn("reauth-token", fake.logged_out)
|
||||
|
||||
|
||||
class EnabledModeSetupAndLoginTests(unittest.TestCase):
|
||||
"""Exercises the real (client is not None) path, including the
|
||||
setup-claim flag's interaction with the store."""
|
||||
|
||||
@@ -9,7 +9,12 @@ from shared_backend.auth import (
|
||||
verify_password,
|
||||
)
|
||||
from shared_backend.clientip import client_address, parse_trusted_proxies
|
||||
from shared_backend.totp import verify_totp
|
||||
from shared_backend.coreconfig import (
|
||||
EXAMPLE_INTERNAL_SECRETS,
|
||||
MIN_INTERNAL_SECRET_LENGTH,
|
||||
internal_secret_matches,
|
||||
)
|
||||
from shared_backend.totp import verify_totp, verify_totp_step
|
||||
|
||||
# The Go, Node and Python auth helpers load the same fixtures; see "description" in the file.
|
||||
CONTRACT_PATH = Path(__file__).resolve().parents[3] / "contract" / "auth-contract.json"
|
||||
@@ -27,22 +32,24 @@ class AuthContractTests(unittest.TestCase):
|
||||
password = self.contract["password"]
|
||||
for entry in password["hashes"]:
|
||||
with self.subTest(entry["name"]):
|
||||
plaintext = entry.get("password", password["plaintext"])
|
||||
wrong_password = entry.get("wrongPassword", password["wrongPassword"])
|
||||
self.assertEqual(
|
||||
verify_password(password["plaintext"], entry["hash"]),
|
||||
verify_password(plaintext, entry["hash"]),
|
||||
entry["verifies"]["python"],
|
||||
)
|
||||
self.assertFalse(verify_password(password["wrongPassword"], entry["hash"]))
|
||||
self.assertFalse(verify_password(wrong_password, entry["hash"]))
|
||||
if "python" in entry.get("needsUpgrade", {}):
|
||||
want = entry["needsUpgrade"]["python"]
|
||||
self.assertEqual(password_hash_needs_upgrade(entry["hash"]), want)
|
||||
valid, upgraded = verify_and_upgrade_password(
|
||||
password["plaintext"], entry["hash"]
|
||||
plaintext, entry["hash"]
|
||||
)
|
||||
self.assertTrue(valid)
|
||||
self.assertEqual(upgraded is not None, want)
|
||||
if upgraded is not None:
|
||||
self.assertTrue(upgraded.startswith("bcrypt$"))
|
||||
self.assertTrue(verify_password(password["plaintext"], upgraded))
|
||||
self.assertTrue(upgraded.startswith(("bcrypt$", "bcrypt-sha256$")))
|
||||
self.assertTrue(verify_password(plaintext, upgraded))
|
||||
|
||||
def test_the_password_length_contract_holds_for_python(self) -> None:
|
||||
too_long = self.contract["password"]["tooLongToHash"]
|
||||
@@ -59,6 +66,11 @@ class AuthContractTests(unittest.TestCase):
|
||||
with self.subTest(entry["name"]):
|
||||
secret = entry.get("secret", totp["secret"])
|
||||
self.assertEqual(verify_totp(secret, entry["code"], entry["unix"]), entry["valid"])
|
||||
if entry["valid"]:
|
||||
self.assertEqual(
|
||||
verify_totp_step(secret, entry["code"], entry["unix"]),
|
||||
entry.get("matchedStep", entry["unix"] // 30),
|
||||
)
|
||||
|
||||
def test_client_address_follows_the_contract(self) -> None:
|
||||
section = self.contract["clientAddress"]
|
||||
@@ -72,6 +84,17 @@ class AuthContractTests(unittest.TestCase):
|
||||
with self.subTest(value), self.assertRaises(ValueError):
|
||||
parse_trusted_proxies(value)
|
||||
|
||||
def test_internal_secret_gate_follows_the_contract(self) -> None:
|
||||
rule = self.contract["internalSecret"]
|
||||
self.assertEqual(MIN_INTERNAL_SECRET_LENGTH, rule["minLength"])
|
||||
self.assertEqual(EXAMPLE_INTERNAL_SECRETS, frozenset(rule["placeholders"]))
|
||||
for entry in rule["cases"]:
|
||||
with self.subTest(entry["name"]):
|
||||
self.assertEqual(
|
||||
internal_secret_matches(entry["provided"], entry["secret"]),
|
||||
entry["matches"],
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -22,7 +22,7 @@ from shared_backend.postgres import (
|
||||
retry_startup,
|
||||
)
|
||||
from shared_backend.tokens import hash_token, new_session_token
|
||||
from shared_backend.totp import totp_provisioning_uri, verify_totp
|
||||
from shared_backend.totp import totp_provisioning_uri, verify_totp, verify_totp_step
|
||||
|
||||
|
||||
class SharedBackendTests(unittest.TestCase):
|
||||
@@ -61,6 +61,19 @@ class SharedBackendTests(unittest.TestCase):
|
||||
self.assertTrue(verify_password("correct horse battery staple", upgraded))
|
||||
self.assertFalse(password_hash_needs_upgrade(upgraded))
|
||||
|
||||
def test_long_legacy_pbkdf2_password_migrates_without_truncation(self):
|
||||
import hashlib
|
||||
|
||||
password = "legacy:" + "x" * 80
|
||||
salt = "0123456789abcdef0123456789abcdef"
|
||||
expected = hashlib.pbkdf2_hmac("sha256", password.encode(), salt.encode(), 100_000).hex()
|
||||
legacy = f"{salt}:{expected}"
|
||||
valid, upgraded = verify_and_upgrade_password(password, legacy)
|
||||
self.assertTrue(valid)
|
||||
self.assertTrue(upgraded.startswith("bcrypt-sha256$$2b$12$"))
|
||||
self.assertTrue(verify_password(password, upgraded))
|
||||
self.assertFalse(verify_password(password + "x", upgraded))
|
||||
|
||||
def test_a_cost_below_the_current_policy_is_upgraded(self):
|
||||
low_cost = "bcrypt$" + bcrypt.hashpw(
|
||||
b"correct horse battery staple", bcrypt.gensalt(rounds=4)
|
||||
@@ -151,6 +164,8 @@ class SharedBackendTests(unittest.TestCase):
|
||||
]
|
||||
for timestamp, code in vectors:
|
||||
self.assertTrue(verify_totp(secret, code, timestamp))
|
||||
self.assertEqual(verify_totp_step(secret, code, timestamp), timestamp // 30)
|
||||
self.assertEqual(verify_totp_step(secret, code, timestamp), timestamp // 30)
|
||||
self.assertTrue(
|
||||
totp_provisioning_uri("Example App", "admin@example.com", secret).startswith(
|
||||
"otpauth://totp/"
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import unittest
|
||||
|
||||
from shared_backend.coreconfig import Info, Store, internal_secret_matches
|
||||
from shared_backend.coreconfig import (
|
||||
MIN_INTERNAL_SECRET_LENGTH,
|
||||
Info,
|
||||
Store,
|
||||
internal_secret_matches,
|
||||
internal_secret_usable,
|
||||
)
|
||||
|
||||
|
||||
class StoreDefaultsTests(unittest.TestCase):
|
||||
@@ -62,6 +68,9 @@ class StoreSetTests(unittest.TestCase):
|
||||
self.assertEqual(info.to_json()["carrierNodeUrl"], "http://carrier.example.com")
|
||||
|
||||
|
||||
LONG_SECRET = "shared-secret-value"
|
||||
|
||||
|
||||
class InternalSecretTests(unittest.TestCase):
|
||||
def test_unset_or_empty_secret_never_matches(self):
|
||||
self.assertFalse(internal_secret_matches(None, None))
|
||||
@@ -70,9 +79,26 @@ class InternalSecretTests(unittest.TestCase):
|
||||
self.assertFalse(internal_secret_matches("", None))
|
||||
|
||||
def test_compares_the_whole_secret(self):
|
||||
self.assertTrue(internal_secret_matches("shared-secret", "shared-secret"))
|
||||
self.assertFalse(internal_secret_matches("shared-secreT", "shared-secret"))
|
||||
self.assertFalse(internal_secret_matches(None, "shared-secret"))
|
||||
self.assertTrue(internal_secret_matches(LONG_SECRET, LONG_SECRET))
|
||||
self.assertFalse(internal_secret_matches("shared-secret-valuE", LONG_SECRET))
|
||||
self.assertFalse(internal_secret_matches(None, LONG_SECRET))
|
||||
|
||||
def test_short_secret_never_matches(self):
|
||||
short = "x" * (MIN_INTERNAL_SECRET_LENGTH - 1)
|
||||
self.assertFalse(internal_secret_matches(short, short))
|
||||
|
||||
def test_placeholder_secret_never_matches(self):
|
||||
for placeholder in ("SECRET", "change-me-to-a-long-random-value"):
|
||||
with self.subTest(placeholder=placeholder):
|
||||
self.assertFalse(internal_secret_matches(placeholder, placeholder))
|
||||
|
||||
def test_usable_requires_minimum_length_and_no_placeholder(self):
|
||||
self.assertFalse(internal_secret_usable(None))
|
||||
self.assertFalse(internal_secret_usable(""))
|
||||
self.assertFalse(internal_secret_usable("x" * (MIN_INTERNAL_SECRET_LENGTH - 1)))
|
||||
self.assertTrue(internal_secret_usable("x" * MIN_INTERNAL_SECRET_LENGTH))
|
||||
self.assertFalse(internal_secret_usable("change-me-to-a-long-random-value"))
|
||||
self.assertTrue(internal_secret_usable(LONG_SECRET))
|
||||
|
||||
|
||||
class UrlValidationTests(unittest.TestCase):
|
||||
|
||||
@@ -29,7 +29,7 @@ class _FakeDatabase:
|
||||
async def fetchrow(self, query: str, *args):
|
||||
self.fetched.append((query, args))
|
||||
if "totp_enabled" in query:
|
||||
return {"secret": "S", "enabled": self.totp_enabled}
|
||||
return {"secret": "S", "enabled": self.totp_enabled, "last_used_step": -1}
|
||||
for condition, row in self.rows_by_condition.items():
|
||||
if condition in query:
|
||||
return row
|
||||
@@ -60,6 +60,9 @@ class AuthStoreHardeningTests(unittest.IsolatedAsyncioTestCase):
|
||||
self.assertIn("lower(username)", statements)
|
||||
# The index is created only while no clashing pair exists.
|
||||
self.assertIn("HAVING count(*) > 1", statements)
|
||||
self.assertIn(
|
||||
"ADD COLUMN IF NOT EXISTS last_used_step BIGINT NOT NULL DEFAULT -1", statements
|
||||
)
|
||||
|
||||
async def test_set_totp_secret_refuses_while_enabled(self) -> None:
|
||||
self.db.execute_status = "UPDATE 0"
|
||||
@@ -73,6 +76,52 @@ class AuthStoreHardeningTests(unittest.IsolatedAsyncioTestCase):
|
||||
self.db.execute_status = "UPDATE 0" # no such user: nothing to refuse
|
||||
await self.store.set_totp_secret(2, "NEWSECRET")
|
||||
|
||||
async def test_totp_enrollment_records_its_step_and_replay_is_rejected(self) -> None:
|
||||
class ReplayDatabase(_FakeDatabase):
|
||||
def __init__(self) -> None:
|
||||
super().__init__()
|
||||
self.state = {
|
||||
"secret": "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ",
|
||||
"enabled": False,
|
||||
"last_used_step": -1,
|
||||
}
|
||||
|
||||
async def fetchrow(self, query: str, *args):
|
||||
if "FROM auth_users WHERE id = $1" in query and "totp_enabled" in query:
|
||||
return dict(self.state)
|
||||
return await super().fetchrow(query, *args)
|
||||
|
||||
async def execute(self, query: str, *args) -> str:
|
||||
self.executed.append((query, args))
|
||||
step, _, secret = args
|
||||
if "SET totp_enabled = true" in query:
|
||||
if (
|
||||
not self.state["enabled"]
|
||||
and secret == self.state["secret"]
|
||||
and self.state["last_used_step"] < step
|
||||
):
|
||||
self.state["enabled"] = True
|
||||
self.state["last_used_step"] = step
|
||||
return "UPDATE 1"
|
||||
return "UPDATE 0"
|
||||
if "SET last_used_step = $1" in query:
|
||||
if (
|
||||
self.state["enabled"]
|
||||
and secret == self.state["secret"]
|
||||
and self.state["last_used_step"] < step
|
||||
):
|
||||
self.state["last_used_step"] = step
|
||||
return "UPDATE 1"
|
||||
return "UPDATE 0"
|
||||
return await super().execute(query, *args)
|
||||
|
||||
database = ReplayDatabase()
|
||||
store = AuthStore(database) # type: ignore[arg-type]
|
||||
self.assertTrue(await store.enable_totp(1, "287082", 59.0))
|
||||
self.assertEqual(database.state["last_used_step"], 1)
|
||||
self.assertFalse(await store.consume_totp_code(1, "287082", 59.0))
|
||||
self.assertEqual(database.state["last_used_step"], 1)
|
||||
|
||||
async def test_credential_writes_refuse_an_empty_hash_and_an_at_username(self) -> None:
|
||||
writes = [
|
||||
lambda u, h: self.store.create_user(u, "", h),
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
onTotpSetup,
|
||||
onTotpStatus,
|
||||
totpEnabled = false,
|
||||
requireCredentialsForEmailChange = false,
|
||||
open = $bindable(false)
|
||||
}: {
|
||||
currentEmail?: string;
|
||||
@@ -23,6 +24,7 @@
|
||||
onTotpSetup?: TotpSetupRequest;
|
||||
onTotpStatus?: TotpStatusRequest;
|
||||
totpEnabled?: boolean;
|
||||
requireCredentialsForEmailChange?: boolean;
|
||||
open?: boolean;
|
||||
} = $props();
|
||||
|
||||
@@ -30,8 +32,13 @@
|
||||
let email = $state('');
|
||||
let password = $state('');
|
||||
let confirmPassword = $state('');
|
||||
let currentPassword = $state('');
|
||||
let totpToken = $state('');
|
||||
let error = $state('');
|
||||
let saving = $state(false);
|
||||
let requiresCurrentCredentials = $derived(
|
||||
!!password || (requireCredentialsForEmailChange && email.trim() !== currentEmail.trim())
|
||||
);
|
||||
|
||||
$effect(() => {
|
||||
if (open) {
|
||||
@@ -39,6 +46,8 @@
|
||||
email = currentEmail;
|
||||
password = '';
|
||||
confirmPassword = '';
|
||||
currentPassword = '';
|
||||
totpToken = '';
|
||||
error = '';
|
||||
}
|
||||
});
|
||||
@@ -52,6 +61,16 @@
|
||||
return;
|
||||
}
|
||||
|
||||
if (requiresCurrentCredentials && !currentPassword) {
|
||||
error = 'Enter your current password to change your email or password.';
|
||||
return;
|
||||
}
|
||||
|
||||
if (requiresCurrentCredentials && totpEnabled && !totpToken) {
|
||||
error = 'Enter a current authenticator code to change your email or password.';
|
||||
return;
|
||||
}
|
||||
|
||||
if (!onSave) {
|
||||
error = 'The application has not configured its profile update handler.';
|
||||
return;
|
||||
@@ -59,7 +78,13 @@
|
||||
|
||||
saving = true;
|
||||
try {
|
||||
await onSave({ username, email, password: password || undefined });
|
||||
const input: ProfileUpdateInput = { username, email };
|
||||
if (requiresCurrentCredentials) {
|
||||
input.currentPassword = currentPassword;
|
||||
if (totpEnabled) input.totpToken = totpToken;
|
||||
}
|
||||
if (password) input.password = password;
|
||||
await onSave(input);
|
||||
open = false;
|
||||
} catch (caught) {
|
||||
error = caught instanceof Error ? caught.message : 'Profile update failed.';
|
||||
@@ -100,6 +125,35 @@
|
||||
/>
|
||||
</label>
|
||||
|
||||
{#if requiresCurrentCredentials}
|
||||
<label class="sc-field">
|
||||
<span class="sc-label">Current password</span>
|
||||
<input
|
||||
autocomplete="current-password"
|
||||
class="sc-input"
|
||||
required
|
||||
type="password"
|
||||
bind:value={currentPassword}
|
||||
/>
|
||||
</label>
|
||||
|
||||
{#if totpEnabled}
|
||||
<label class="sc-field">
|
||||
<span class="sc-label">Current authenticator code</span>
|
||||
<input
|
||||
autocomplete="one-time-code"
|
||||
class="sc-input"
|
||||
inputmode="numeric"
|
||||
maxlength="6"
|
||||
pattern="[0-9]{6}"
|
||||
required
|
||||
type="text"
|
||||
bind:value={totpToken}
|
||||
/>
|
||||
</label>
|
||||
{/if}
|
||||
{/if}
|
||||
|
||||
{#if password}
|
||||
<label class="sc-field">
|
||||
<span class="sc-label">Confirm new password</span>
|
||||
|
||||
@@ -42,6 +42,8 @@ export interface ProfileUpdateInput {
|
||||
username: string;
|
||||
email: string;
|
||||
password?: string;
|
||||
currentPassword?: string;
|
||||
totpToken?: string;
|
||||
}
|
||||
|
||||
export type UserRole = "superadmin" | "admin" | "user";
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/svelte';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import ProfileDialog from '../src/lib/components/ProfileDialog.svelte';
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
const fieldLabels: Record<string, string> = {
|
||||
username: 'Username',
|
||||
email: 'Email',
|
||||
password: 'New password',
|
||||
confirmPassword: 'Confirm new password',
|
||||
currentPassword: 'Current password',
|
||||
totpToken: 'Current authenticator code',
|
||||
};
|
||||
|
||||
const field = (name: string): HTMLInputElement => screen.getByLabelText(fieldLabels[name]) as HTMLInputElement;
|
||||
|
||||
async function fill(name: string, value: string): Promise<void> {
|
||||
await fireEvent.input(field(name), { target: { value } });
|
||||
}
|
||||
|
||||
async function submit(): Promise<void> {
|
||||
const form = document.querySelector('form');
|
||||
if (!form) throw new Error('no form');
|
||||
await fireEvent.submit(form);
|
||||
}
|
||||
|
||||
describe('ProfileDialog password changes', () => {
|
||||
it('requires current password and a current TOTP code when enabled', async () => {
|
||||
const onSave = vi.fn().mockResolvedValue(undefined);
|
||||
render(ProfileDialog, { props: { open: true, onSave, totpEnabled: true } });
|
||||
await fill('username', 'alice');
|
||||
await fill('email', 'alice@example.com');
|
||||
await fill('password', 'new-password');
|
||||
await fill('confirmPassword', 'new-password');
|
||||
|
||||
await submit();
|
||||
expect(onSave).not.toHaveBeenCalled();
|
||||
expect(screen.getByText('Enter your current password to change it.')).toBeTruthy();
|
||||
|
||||
await fill('currentPassword', 'old-password');
|
||||
await submit();
|
||||
expect(onSave).not.toHaveBeenCalled();
|
||||
expect(screen.getByText('Enter a current authenticator code to change your password.')).toBeTruthy();
|
||||
|
||||
await fill('totpToken', '123456');
|
||||
await submit();
|
||||
await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1));
|
||||
expect(onSave).toHaveBeenCalledWith({
|
||||
username: 'alice',
|
||||
email: 'alice@example.com',
|
||||
password: 'new-password',
|
||||
currentPassword: 'old-password',
|
||||
totpToken: '123456',
|
||||
});
|
||||
});
|
||||
|
||||
it('does not ask for password proof when only profile fields change', async () => {
|
||||
const onSave = vi.fn().mockResolvedValue(undefined);
|
||||
render(ProfileDialog, { props: { open: true, onSave, totpEnabled: true } });
|
||||
await fill('username', 'alice');
|
||||
await fill('email', 'alice@example.com');
|
||||
await submit();
|
||||
await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1));
|
||||
expect(onSave).toHaveBeenCalledWith({ username: 'alice', email: 'alice@example.com' });
|
||||
expect(screen.queryByLabelText('Current password')).toBeNull();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user