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

@@ -73,24 +73,21 @@ import java.util.regex.Pattern;
* this class can be built and tested in isolation (see this package's
* README); it targets Java 8 for the same reason.
*
* <p>{@link #validate(String)} still hand-parses AuthGuard's small, fixed
* {@code GET /api/session/validate} response shape with a few targeted
* regular expressions rather than Jackson, keeping the minimal
* validate-only surface dependency-free beyond the JDK - {@code ResetManager},
* {@code Roles}, and {@code Totp}, the other classes in this package, stay
* that way too. The full-proxy methods added below (register/login/setup/
* reset/admin-user-management) are a different tradeoff: they must both
* build and parse a handful of small JSON request/response bodies, which
* would be considerably worse hand-rolled than {@code validate}'s
* fixed-shape parsing, so they use Jackson ({@code jackson-databind})
* instead. This makes {@code jackson-databind} a compile-time dependency of
* <p>{@link #validate(String)} parses AuthGuard's {@code GET /api/session/validate}
* response with Jackson and reads top-level fields only, so a nested object
* with the same field names cannot change the decision. {@code ResetManager},
* {@code Roles}, and {@code Totp}, the other classes in this package, use only
* the JDK. The full-proxy methods added below (register/login/setup/
* reset/admin-user-management) also build and parse a handful of small JSON
* request/response bodies, which would be considerably worse hand-rolled, so
* they use Jackson ({@code jackson-databind}) too. This makes {@code jackson-databind} a compile-time dependency of
* this whole class (Java has no way to make an import conditional on which
* methods a given consumer actually calls) - acceptable here because
* MegaBasterd, this package's only verified consumer, already depends on
* Jackson for its own code. A hypothetical future consumer that only ever
* calls {@code validate}/{@code middleware} and doesn't already carry
* Jackson would need to add it just to compile this file; that tradeoff was
* chosen deliberately over hand-rolling JSON request bodies with regex.
* chosen deliberately over hand-rolling JSON with regular expressions.
*/
public final class AuthClient {
@@ -106,10 +103,6 @@ public final class AuthClient {
*/
public static final String PROJECT_KEY_HEADER = "X-Project-Key";
private static final Pattern VALID_PATTERN = Pattern.compile("\"valid\"\\s*:\\s*(true|false)");
private static final Pattern USER_ID_PATTERN = Pattern.compile("\"user_id\"\\s*:\\s*(-?\\d+)");
private static final Pattern USERNAME_PATTERN = Pattern.compile("\"username\"\\s*:\\s*\"((?:[^\"\\\\]|\\\\.)*)\"");
private static final Pattern ROLE_PATTERN = Pattern.compile("\"role\"\\s*:\\s*\"((?:[^\"\\\\]|\\\\.)*)\"");
private static final String BEARER_PREFIX = "Bearer ";
/** Used only by the full-proxy methods below; see the class javadoc's Jackson tradeoff note. */
@@ -279,7 +272,8 @@ public final class AuthClient {
User user;
try {
user = validate(token);
} catch (InvalidSessionException | IOException ex) {
} catch (InvalidSessionException | IOException | IllegalStateException ex) {
// IllegalStateException is a client with no base URL yet; it fails closed like Node's middleware.
return onUnauthorized.get();
}
return onAuthenticated.handle(user);
@@ -829,59 +823,43 @@ public final class AuthClient {
return buffer.toString(StandardCharsets.UTF_8.name());
}
/** Defensively hand-parses AuthGuard's small, fixed response shape - see the class javadoc for why. */
/**
* Parses AuthGuard's response with Jackson and reads top-level fields only, so a nested object
* with the same field names cannot stand in for the real answer.
*/
private static RawPayload parsePayload(String body) {
if (body == null || body.isEmpty()) {
throw new IllegalArgumentException("empty AuthGuard response body");
}
Matcher validMatcher = VALID_PATTERN.matcher(body);
if (!validMatcher.find()) {
JsonNode root;
try {
root = JSON.readTree(body);
} catch (IOException ex) {
throw new IllegalArgumentException("AuthGuard response is not JSON: " + ex.getMessage(), ex);
}
if (root == null || !root.isObject()) {
throw new IllegalArgumentException("AuthGuard response is not a JSON object");
}
JsonNode validNode = root.get("valid");
if (validNode == null || !validNode.isBoolean()) {
throw new IllegalArgumentException("missing \"valid\" field in AuthGuard response");
}
boolean valid = Boolean.parseBoolean(validMatcher.group(1));
long userId = 0L;
Matcher userIdMatcher = USER_ID_PATTERN.matcher(body);
if (userIdMatcher.find()) {
userId = Long.parseLong(userIdMatcher.group(1));
JsonNode userIdNode = root.get("user_id");
if (userIdNode != null && userIdNode.isIntegralNumber()) {
if (!userIdNode.canConvertToLong()) {
throw new IllegalArgumentException("user_id is out of range in AuthGuard response");
}
userId = userIdNode.longValue();
}
return new RawPayload(valid, userId, extractString(USERNAME_PATTERN, body), extractString(ROLE_PATTERN, body));
return new RawPayload(validNode.booleanValue(), userId, textualField(root, "username"), textualField(root, "role"));
}
private static String extractString(Pattern pattern, String body) {
Matcher matcher = pattern.matcher(body);
return matcher.find() ? unescapeJson(matcher.group(1)) : "";
}
private static String unescapeJson(String raw) {
StringBuilder result = new StringBuilder(raw.length());
for (int index = 0; index < raw.length(); index++) {
char current = raw.charAt(index);
if (current != '\\' || index + 1 >= raw.length()) {
result.append(current);
continue;
}
char next = raw.charAt(++index);
switch (next) {
case '"': result.append('"'); break;
case '\\': result.append('\\'); break;
case '/': result.append('/'); break;
case 'n': result.append('\n'); break;
case 't': result.append('\t'); break;
case 'r': result.append('\r'); break;
case 'b': result.append('\b'); break;
case 'f': result.append('\f'); break;
case 'u':
if (index + 4 < raw.length()) {
result.append((char) Integer.parseInt(raw.substring(index + 1, index + 5), 16));
index += 4;
}
break;
default: result.append(next);
}
}
return result.toString();
private static String textualField(JsonNode root, String name) {
JsonNode node = root.get(name);
return node != null && node.isTextual() ? node.textValue() : "";
}
private static final class RawPayload {
@@ -2,6 +2,7 @@ package com.gabriel20xx.shared.auth;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Locale;
import javax.crypto.Mac;
@@ -77,7 +78,8 @@ public final class Totp {
| ((hash[index + 2] & 0xff) << 8)
| (hash[index + 3] & 0xff);
String candidate = String.format(Locale.ROOT, "%06d", code % 1_000_000);
if (candidate.equals(normalizedToken)) {
if (MessageDigest.isEqual(candidate.getBytes(StandardCharsets.US_ASCII),
normalizedToken.getBytes(StandardCharsets.US_ASCII))) {
return true;
}
} catch (Exception ex) {
@@ -278,6 +278,54 @@ class AuthClientTest {
assertEquals("user", result.role);
}
@Test
void validateReadsTopLevelFieldsOnlyWhenNestedFieldsRepeatThem() throws Exception {
// The nested object says valid:true, but the top-level answer is valid:false, so the session is invalid.
server = fakeAuthGuard(200, "{\"session\":{\"valid\":true,\"user_id\":99,\"username\":\"evil\",\"role\":\"admin\"},\"valid\":false}");
AuthClient client = new AuthClient(baseUrl(server));
assertThrows(InvalidSessionException.class, () -> client.validate("token"));
}
@Test
void validateIgnoresANestedValidFieldWhenTheTopLevelOneIsMissing() throws Exception {
server = fakeAuthGuard(200, "{\"data\":{\"valid\":true,\"user_id\":5,\"username\":\"x\",\"role\":\"admin\"}}");
AuthClient client = new AuthClient(baseUrl(server));
assertThrows(IOException.class, () -> client.validate("token"));
}
@Test
void validateAcceptsReorderedTopLevelFields() throws Exception {
server = fakeAuthGuard(200, "{\"username\":\"gabriel\",\"role\":\"admin\",\"user_id\":7,\"valid\":true}");
AuthClient client = new AuthClient(baseUrl(server));
AuthClient.User user = client.validate("token");
assertEquals(7L, user.id);
assertEquals("gabriel", user.username);
assertEquals("admin", user.role);
}
@Test
void validateDecodesEscapedUsernames() throws Exception {
server = fakeAuthGuard(200, "{\"valid\":true,\"user_id\":3,\"username\":\"a\\\"b\\u00e9\",\"role\":\"user\"}");
AuthClient client = new AuthClient(baseUrl(server));
assertEquals("a\"b\u00e9", client.validate("token").username);
}
@Test
void middlewareFailsClosedOnAClientWithNoBaseUrlYet() throws Exception {
AuthClient client = new AuthClient("");
Function<String, String> headerLookup = name -> "Authorization".equals(name) ? "Bearer some-token" : null;
String result = client.middleware(headerLookup, null,
user -> "authenticated", () -> "unauthorized");
assertEquals("unauthorized", result);
}
/** Like fakeAuthGuard, but for one arbitrary path instead of the fixed /api/session/validate one. */
private static HttpServer fakeEndpoint(String path, int status, String body) throws IOException {
return fakeEndpointCapturingRequest(path, status, body, new String[0]);
@@ -0,0 +1,76 @@
package com.gabriel20xx.shared.auth;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import org.junit.jupiter.api.Test;
class ResetManagerTest {
@Test
void requestReturnsAnEightDigitHexCodeAndPrintsIt() {
ResetManager manager = new ResetManager();
PrintStream original = System.out;
ByteArrayOutputStream captured = new ByteArrayOutputStream();
System.setOut(new PrintStream(captured));
String code;
try {
code = manager.request();
} finally {
System.setOut(original);
}
assertTrue(code.matches("[0-9A-F]{8}"));
assertTrue(captured.toString().contains("ADMIN RESET CODE: " + code));
}
@Test
void confirmAcceptsTheCodeOnceAndTrimsAndCase() {
ResetManager manager = new ResetManager();
String code = quietRequest(manager);
assertFalse(manager.confirm(null));
assertTrue(manager.confirm(" " + code.toLowerCase() + " "));
assertFalse(manager.confirm(code));
}
@Test
void confirmRejectsAWrongCodeButKeepsTheCodeRetryable() {
ResetManager manager = new ResetManager();
String code = quietRequest(manager);
String wrong = code.charAt(0) == '0' ? "1" + code.substring(1) : "0" + code.substring(1);
assertFalse(manager.confirm(wrong));
assertTrue(manager.confirm(code));
}
@Test
void confirmFailsWithoutARequestedCode() {
assertFalse(new ResetManager().confirm("00000000"));
}
@Test
void aNewRequestInvalidatesThePreviousCode() {
ResetManager manager = new ResetManager();
String first = quietRequest(manager);
String second = quietRequest(manager);
if (!first.equals(second)) {
assertFalse(manager.confirm(first));
}
assertTrue(manager.confirm(second));
}
private static String quietRequest(ResetManager manager) {
PrintStream original = System.out;
System.setOut(new PrintStream(new ByteArrayOutputStream()));
try {
return manager.request();
} finally {
System.setOut(original);
}
}
}
@@ -0,0 +1,36 @@
package com.gabriel20xx.shared.auth;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class RolesTest {
@Test
void normalizeIsCaseInsensitiveAndDefaultsToUser() {
assertEquals(Roles.SUPERADMIN, Roles.normalize(" SuperAdmin "));
assertEquals(Roles.ADMIN, Roles.normalize("ADMIN"));
assertEquals(Roles.USER, Roles.normalize("moderator"));
assertEquals(Roles.USER, Roles.normalize(""));
assertEquals(Roles.USER, Roles.normalize(null));
}
@Test
void onlyAdminRolesCanManageUsers() {
assertTrue(Roles.canManageUsers(Roles.SUPERADMIN));
assertTrue(Roles.canManageUsers(Roles.ADMIN));
assertFalse(Roles.canManageUsers(Roles.USER));
assertFalse(Roles.canManageUsers("moderator"));
}
@Test
void onlySuperadminCanAssignNonSuperadminRoles() {
assertTrue(Roles.canAssignRole(Roles.SUPERADMIN, Roles.ADMIN));
assertTrue(Roles.canAssignRole(Roles.SUPERADMIN, Roles.USER));
assertFalse(Roles.canAssignRole(Roles.SUPERADMIN, Roles.SUPERADMIN));
assertFalse(Roles.canAssignRole(Roles.ADMIN, Roles.USER));
assertFalse(Roles.canAssignRole(Roles.USER, Roles.USER));
}
}
@@ -0,0 +1,76 @@
package com.gabriel20xx.shared.auth;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class TotpTest {
// RFC 6238 SHA-1 test secret "12345678901234567890", base32-encoded.
private static final String RFC_SECRET = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ";
@Test
void verifyAcceptsTheRfc6238Vectors() {
// The RFC lists 8-digit codes; these are their last six digits.
assertTrue(Totp.verify(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));
assertTrue(Totp.verify(RFC_SECRET, "279037", 2_000_000_000_000L));
}
@Test
void verifyAcceptsOneStepEitherSideOfTheCurrentTime() {
// At t=59 the counter is 1. Counter 0 (t=0) and counter 2 (t=60) are inside the window.
assertTrue(Totp.verify(RFC_SECRET, "755224", 59_000L));
assertTrue(Totp.verify(RFC_SECRET, "359152", 59_000L));
}
@Test
void verifyRejectsCodesOutsideTheWindow() {
// Counter 3 (t=90) is two steps ahead of counter 1; 2 steps behind would need a negative counter.
assertFalse(Totp.verify(RFC_SECRET, "969429", 59_000L));
}
@Test
void verifyRejectsMalformedInput() {
assertFalse(Totp.verify(RFC_SECRET, null, 59_000L));
assertFalse(Totp.verify(RFC_SECRET, "", 59_000L));
assertFalse(Totp.verify(RFC_SECRET, "28708", 59_000L));
assertFalse(Totp.verify(RFC_SECRET, "28708a", 59_000L));
assertFalse(Totp.verify(RFC_SECRET, "2870821", 59_000L));
assertFalse(Totp.verify("", "287082", 59_000L));
assertFalse(Totp.verify(null, "287082", 59_000L));
assertFalse(Totp.verify("not base32!", "287082", 59_000L));
}
@Test
void verifyTrimsWhitespaceAroundTheCode() {
assertTrue(Totp.verify(RFC_SECRET, " 287082 ", 59_000L));
}
@Test
void verifyAcceptsASecretWithSpacesAndPadding() {
String spaced = "GEZD GNBV GY3T QOJQ GEZD GNBV GY3T QOJQ====";
assertTrue(Totp.verify(spaced, "287082", 59_000L));
}
@Test
void generatedSecretsAreBase32OfTheExpectedLength() {
String first = Totp.generateSecret();
String second = Totp.generateSecret();
assertEquals(32, first.length());
assertTrue(first.matches("[A-Z2-7]+"));
assertFalse(first.equals(second));
}
@Test
void provisioningUriCarriesTheSecretAndParameters() {
String uri = Totp.provisioningUri("Shared App", "gabriel", RFC_SECRET);
assertTrue(uri.startsWith("otpauth://totp/Shared%20App%3Agabriel?secret=" + RFC_SECRET));
assertTrue(uri.contains("&issuer=Shared%20App"));
assertTrue(uri.endsWith("&algorithm=SHA1&digits=6&period=30"));
}
}
+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);
});
+26 -5
View File
@@ -4,7 +4,7 @@ Shared Python backend infrastructure for services using `asyncpg`:
- validated `DATABASE_URL` and pool settings;
- one async pool owner with startup retry, ping, and graceful shutdown;
- bcrypt password and secure session-token helpers;
- bcrypt password helpers (`verify_and_upgrade_password_async` 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 for the single-admin or optional multi-user model;
- an `authclient` module for services that adopt AuthGuard, the centralized
@@ -20,7 +20,25 @@ pip install "git+https://repos.gfranz.ch/Gabriel20xx/shared@v0.1.0#subdirectory=
```
Database startup uses `DB_INIT_RETRY_INTERVAL_MS` (default `5000`, minimum
`250`) and `DB_INIT_RETRY_MAX_ATTEMPTS` (default `0`, retry indefinitely).
`250`) and `DB_INIT_RETRY_MAX_ATTEMPTS` (default `0`, retry indefinitely). Only
transient connection errors are retried; bad credentials or a missing database
fail at once.
`authproxy.build_auth_router` limits login attempts (10 per account and 200 per
client address per 15 minutes) and TOTP verify/disable attempts (5 per user), in
process memory, and answers `429` beyond that. The client address is the TCP
peer; `X-Forwarded-For` is read only from peers inside `TRUSTED_PROXIES` (a
comma-separated list of CIDR ranges or IP addresses, empty by default; the
`trusted_proxies` argument overrides it, and an invalid list raises
`ValueError` at startup). The same address reaches AuthGuard as
`X-Forwarded-For` through `authclient.forwarded_client_ip`, which AuthGuard reads
only from peers in its own `TRUSTED_PROXIES`.
`AuthStore` refuses an empty password hash and a username containing `@`
(`EmptyPasswordHashError`, `InvalidUsernameError` in `shared_backend.auth`),
refuses `set_totp_secret` while TOTP is enabled (`TotpAlreadyEnabledError`), and
makes usernames unique ignoring case when no clashing pair already exists.
`hash_password` refuses a password longer than 72 bytes, the most bcrypt reads.
## `authclient`: adopting AuthGuard instead of local auth
@@ -92,7 +110,7 @@ give it, and updated live whenever ProjectConfigurator pushes a fresh
`PUT /api/core-services/internal`. A service wires the actual route itself:
```python
from shared_backend import AuthClient, CoreConfigInfo, CoreConfigStore
from shared_backend import AuthClient, CoreConfigInfo, CoreConfigStore, internal_secret_matches
auth_client = AuthClient("") # pending: no URL yet, still safe to use
core_config = CoreConfigStore(CoreConfigInfo(auth_guard_url=""))
@@ -101,10 +119,13 @@ core_config.on_update(lambda info: auth_client.set_base_url(info.auth_guard_url)
# in your framework's route for PUT /api/core-services/internal:
async def push_core_services(request):
if request.headers.get("X-Internal-Auth") != SECRET:
if not internal_secret_matches(request.headers.get("X-Internal-Auth"), SECRET):
raise HTTPException(status_code=401)
body = await request.json()
info = core_config.set(CoreConfigInfo.from_json(body))
try:
info = core_config.set(CoreConfigInfo.from_json(body))
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
return {"ok": True, "info": info.to_json()}
```
@@ -11,8 +11,13 @@ from .auth import (
can_assign_role,
can_manage_users,
hash_password,
hash_password_async,
normalize_role,
password_hash_needs_upgrade,
verify_and_upgrade_password,
verify_and_upgrade_password_async,
verify_password,
verify_password_async,
)
from .authclient import (
AuthClient,
@@ -25,6 +30,7 @@ from .authclient import (
from .config import DatabaseConfig, database_url_from_env
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
@@ -40,6 +46,7 @@ __all__ = [
"token_from_request",
"CoreConfigInfo",
"CoreConfigStore",
"internal_secret_matches",
"ROLE_ADMIN",
"ROLE_SUPERADMIN",
"ROLE_USER",
@@ -52,10 +59,15 @@ __all__ = [
"database_url_from_env",
"generate_totp_secret",
"hash_password",
"hash_password_async",
"hash_token",
"new_session_token",
"normalize_role",
"password_hash_needs_upgrade",
"totp_provisioning_uri",
"verify_and_upgrade_password",
"verify_and_upgrade_password_async",
"verify_password",
"verify_password_async",
"verify_totp",
]
@@ -2,6 +2,7 @@
from __future__ import annotations
import asyncio
import secrets
import threading
from dataclasses import dataclass
@@ -30,9 +31,6 @@ ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_secret TEXT NOT NULL DEFAUL
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 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'
WHERE id = (SELECT id FROM auth_users ORDER BY created_at, id LIMIT 1)
AND NOT EXISTS (SELECT 1 FROM auth_users WHERE role = 'superadmin');
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_email_idx
ON auth_users (lower(email)) WHERE email <> '';
CREATE TABLE IF NOT EXISTS auth_sessions (
@@ -46,6 +44,39 @@ 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);
"""
# 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.
_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
$$
"""
_ROLE_COLUMN_MISSING = """
SELECT NOT EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_schema = current_schema() AND table_name = 'auth_users' AND column_name = 'role'
)
"""
_PROMOTE_OLDEST_SUPERADMIN = """
UPDATE auth_users SET role = 'superadmin'
WHERE id = (SELECT id FROM auth_users ORDER BY created_at, id LIMIT 1)
AND NOT EXISTS (SELECT 1 FROM auth_users WHERE role = 'superadmin')
"""
RESET_CODE_TTL = timedelta(minutes=5)
ROLE_SUPERADMIN = "superadmin"
@@ -107,10 +138,12 @@ class ResetManager:
@dataclass(frozen=True, slots=True)
class AuthUser:
"""A stored account. Only the lookups that verify credentials fill password_hash."""
id: int
username: str
email: str
password_hash: str
password_hash: str = ""
role: str = ROLE_USER
created_at: datetime | None = None
updated_at: datetime | None = None
@@ -120,26 +153,129 @@ class UserExistsError(Exception):
"""Raised when a user violates a unique or single-user constraint."""
class TotpAlreadyEnabledError(Exception):
"""Raised by set_totp_secret while two-factor auth is enabled."""
class EmptyPasswordHashError(ValueError):
"""Raised when a credential write carries no password hash."""
class InvalidUsernameError(ValueError):
"""Raised for a username containing "@", which would be read as an email."""
def _validate_credentials(username: str | None, password_hash: str | None) -> None:
"""Refuse a write that would leave an account without a password hash, or store a username
that could be mistaken for another account's email. None means "leave unchanged"."""
if password_hash is not None and not password_hash:
raise EmptyPasswordHashError("password hash is required")
if username is not None and "@" in username:
raise InvalidUsernameError("username cannot contain @")
# Every hash this module writes starts with this scheme prefix, so verification
# picks the algorithm from the stored value. The bcrypt string follows unchanged,
# 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$"
_LEGACY_BCRYPT_PREFIXES = ("$2a$", "$2b$", "$2y$")
BCRYPT_ROUNDS = 12
def _new_bcrypt_hash(password: str) -> str:
hashed = bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt(rounds=BCRYPT_ROUNDS))
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
def hash_password(password: str) -> str:
if len(password) < 8:
raise ValueError("Password must be at least 8 characters")
return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
if len(password.encode("utf-8")) > MAX_PASSWORD_BYTES:
raise ValueError(f"Password must be at most {MAX_PASSWORD_BYTES} bytes")
return _new_bcrypt_hash(password)
def _bcrypt_string_of(stored_hash: str) -> str | None:
if stored_hash.startswith(_BCRYPT_SCHEME):
return stored_hash[len(_BCRYPT_SCHEME) :]
if stored_hash.startswith(_LEGACY_BCRYPT_PREFIXES):
return stored_hash
return None
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"), stored_hash.encode("utf-8"))
return bcrypt.checkpw(password.encode("utf-8"), bcrypt_hash.encode("utf-8"))
except (ValueError, TypeError):
return False
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):
return True
# The bcrypt string after the prefix is "$2b$<cost>$<salt+hash>".
parts = stored_hash[len(_BCRYPT_SCHEME) :].split("$")
try:
return int(parts[2]) < BCRYPT_ROUNDS
except (IndexError, ValueError):
return True
def verify_and_upgrade_password(password: str, stored_hash: str) -> tuple[bool, str | None]:
"""Check a password and, on a match against an older scheme, return a replacement hash.
Returns (valid, upgraded_hash). upgraded_hash is None when the password does not match or
the stored hash is already current. Store upgraded_hash, for example with
AuthStore.update_user(user_id, password_hash=...).
"""
if not verify_password(password, stored_hash):
return False, None
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.
return True, _new_bcrypt_hash(password)
async def hash_password_async(password: str) -> str:
"""Non-blocking hash_password: bcrypt runs in a worker thread."""
return await asyncio.to_thread(hash_password, password)
async def verify_password_async(password: str, stored_hash: str) -> bool:
"""Non-blocking verify_password: bcrypt runs in a worker thread."""
return await asyncio.to_thread(verify_password, password, stored_hash)
async def verify_and_upgrade_password_async(
password: str, stored_hash: str
) -> tuple[bool, str | None]:
"""Non-blocking verify_and_upgrade_password: bcrypt runs in a worker thread."""
return await asyncio.to_thread(verify_and_upgrade_password, password, stored_hash)
class AuthStore:
def __init__(self, database: Database, *, single_user: bool = True) -> None:
self.database = database
self.single_user = single_user
async def ensure_schema(self) -> None:
# Only a table that predates the role column needs its oldest account promoted, so the
# promotion runs once, in the migration that adds the column.
role_column_missing = await self.database.fetchval(_ROLE_COLUMN_MISSING)
await self.database.execute(_SCHEMA)
await self.database.execute(_USERNAME_CASE_INDEX)
if role_column_missing:
await self.database.execute(_PROMOTE_OLDEST_SUPERADMIN)
if self.single_user:
await self.database.execute(
"CREATE UNIQUE INDEX IF NOT EXISTS auth_users_singleton_idx ON auth_users ((true))"
@@ -151,6 +287,7 @@ class AuthStore:
return int(await self.database.fetchval("SELECT count(*) FROM auth_users"))
async def create_user(self, username: str, email: str, password_hash: str) -> AuthUser:
_validate_credentials(username, password_hash or "")
try:
row = await self.database.fetchrow(
"""
@@ -159,7 +296,7 @@ class AuthStore:
CASE WHEN EXISTS (SELECT 1 FROM auth_users) THEN 'user'
ELSE 'superadmin' END,
now())
RETURNING id, username, email, password_hash, role, created_at, updated_at
RETURNING id, username, email, role, created_at, updated_at
""",
username,
email,
@@ -171,19 +308,25 @@ class AuthStore:
return AuthUser(**dict(row))
async def find_by_identifier(self, identifier: str) -> AuthUser | None:
row = await self.database.fetchrow(
"""
SELECT id, username, email, password_hash, role, created_at, updated_at
FROM auth_users
WHERE username = $1 OR lower(email) = lower($1)
""",
identifier,
)
return AuthUser(**dict(row)) if row else None
# Usernames are tried before emails, so an identifier resolves to one account in a
# fixed order.
for condition in ("username = $1", "lower(email) = lower($1)"):
row = await self.database.fetchrow(
f"""
SELECT id, username, email, password_hash, role, created_at, updated_at
FROM auth_users
WHERE {condition}
""",
identifier,
)
if row:
return AuthUser(**dict(row))
return None
async def update_credentials(
self, user_id: int, username: str, email: str, password_hash: str
) -> None:
_validate_credentials(username, password_hash or "")
await self.database.execute(
"""
UPDATE auth_users
@@ -224,7 +367,7 @@ class AuthStore:
async def list_users(self) -> list[AuthUser]:
rows = await self.database.fetch(
"SELECT id, username, email, role, password_hash, created_at, updated_at "
"SELECT id, username, email, role, created_at, updated_at "
"FROM auth_users ORDER BY created_at, id"
)
return [AuthUser(**dict(row)) for row in rows]
@@ -232,12 +375,13 @@ class AuthStore:
async def create_managed_user(
self, username: str, email: str, password_hash: str, role: str = ROLE_USER
) -> AuthUser:
_validate_credentials(username, password_hash or "")
try:
row = await self.database.fetchrow(
"""
INSERT INTO auth_users (username, email, password_hash, role, updated_at)
VALUES ($1, $2, $3, $4, now())
RETURNING id, username, email, password_hash, role, created_at, updated_at
RETURNING id, username, email, role, created_at, updated_at
""",
username,
email,
@@ -258,6 +402,7 @@ class AuthStore:
password_hash: str | None = None,
role: str | None = None,
) -> None:
_validate_credentials(username, password_hash)
fields: list[str] = []
values: list[object] = []
for column, value in (
@@ -293,12 +438,17 @@ class AuthStore:
return dict(row) if row else {"secret": "", "enabled": False}
async def set_totp_secret(self, user_id: int, secret: str) -> None:
await self.database.execute(
"""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, "
"updated_at = now() WHERE id = $2",
"updated_at = now() WHERE id = $2 AND NOT totp_enabled",
secret,
user_id,
)
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(
@@ -49,15 +49,26 @@ concrete Response object and knows how to attach headers to it.
from __future__ import annotations
import asyncio
import contextlib
import contextvars
import hashlib
import ipaddress
import json
import threading
import time
import urllib.error
import urllib.request
from collections.abc import Iterator
from dataclasses import dataclass, field
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.
VALIDATION_CACHE_TTL = 2.0
MAX_VALIDATION_CACHE_ENTRIES = 10000
_BEARER_PREFIX = "Bearer "
@@ -66,6 +77,34 @@ _BEARER_PREFIX = "Bearer "
# so it can enforce per-user project-access restriction (see AuthGuard's
# project-scope admin UI). Mirrors Go's authclient.ProjectKeyHeader.
PROJECT_KEY_HEADER = "X-Project-Key"
# Carries the end user's address on every AuthGuard call made inside a `forwarded_client_ip`
# block, so AuthGuard's per-address limits see the end user instead of this service. AuthGuard
# reads the header 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.
FORWARDED_FOR_HEADER = "X-Forwarded-For"
_forwarded_client_ip: contextvars.ContextVar[str | None] = contextvars.ContextVar(
"authclient_forwarded_client_ip", default=None
)
@contextlib.contextmanager
def forwarded_client_ip(ip: str | None) -> Iterator[None]:
"""Makes AuthClient calls awaited inside the block send `ip` as X-Forwarded-For. Pass an
address the caller has already verified (see shared_backend.clientip.client_address), never a
raw request header. Anything that is not an IP address is ignored."""
token = _forwarded_client_ip.set(ip)
try:
yield
finally:
_forwarded_client_ip.reset(token)
def _valid_ip(value: str | None) -> str:
"""The canonical form of an IP address, or "" for anything else (no header injection)."""
try:
return str(ipaddress.ip_address((value or "").strip()))
except ValueError:
return ""
def _normalize_base_url(base_url: str) -> str:
@@ -233,6 +272,43 @@ class AuthClient:
# restriction. Normally a project's own lowercase identifier,
# matching the key ProjectConfigurator registers it under.
self.project_key = (project_key or "").strip().lower()
self._validation_lock = threading.Lock()
self._validation_cache: dict[str, tuple[float, AuthGuardUser | None]] = {}
@staticmethod
def _validation_key(token: str) -> str:
return hashlib.sha256(token.encode("utf-8")).hexdigest()
def _cached_validation(self, token: str) -> tuple[bool, AuthGuardUser | None]:
"""Returns (hit, user); user is None for a cached invalid session."""
key = self._validation_key(token)
with self._validation_lock:
entry = self._validation_cache.get(key)
if entry is None:
return False, None
expires, user = entry
if time.monotonic() >= expires:
del self._validation_cache[key]
return False, None
return True, user
def _cache_validation(self, token: str, user: AuthGuardUser | None) -> None:
with self._validation_lock:
if len(self._validation_cache) >= MAX_VALIDATION_CACHE_ENTRIES:
now = time.monotonic()
for key in [k for k, entry in self._validation_cache.items() if now >= entry[0]]:
del self._validation_cache[key]
if len(self._validation_cache) >= MAX_VALIDATION_CACHE_ENTRIES:
# dicts keep insertion order, so this drops the oldest entry.
del self._validation_cache[next(iter(self._validation_cache))]
self._validation_cache[self._validation_key(token)] = (
time.monotonic() + VALIDATION_CACHE_TTL,
user,
)
def _forget_validation(self, token: str) -> None:
with self._validation_lock:
self._validation_cache.pop(self._validation_key(token), None)
def set_base_url(self, base_url: str) -> None:
"""Atomically replaces the AuthGuard base URL this client calls,
@@ -248,6 +324,8 @@ class AuthClient:
normalized = _normalize_base_url(base_url)
if normalized:
self.base_url = normalized
with self._validation_lock:
self._validation_cache.clear()
# --- session validation (the original, minimal surface) ----------------
@@ -262,6 +340,11 @@ class AuthClient:
trimmed = (token or "").strip()
if not trimmed:
raise InvalidSessionError()
hit, cached = self._cached_validation(trimmed)
if hit:
if cached is None:
raise InvalidSessionError()
return cached
return await asyncio.to_thread(self._validate_sync, trimmed)
def _validate_sync(self, token: str) -> AuthGuardUser:
@@ -293,17 +376,23 @@ class AuthClient:
raise TypeError(f"expected a JSON object, got {type(payload).__name__}")
except (ValueError, TypeError, UnicodeDecodeError) as exc:
if status == 401:
self._cache_validation(token, None)
raise InvalidSessionError() from exc
raise AuthClientError(f"authclient: decode AuthGuard response: {exc}") from exc
if status != 200 or not payload.get("valid"):
if status == 401 or (status == 200 and not payload.get("valid")):
self._cache_validation(token, None)
raise InvalidSessionError()
if status != 200:
raise InvalidSessionError()
return AuthGuardUser(
user = AuthGuardUser(
id=int(payload.get("user_id") or 0),
username=str(payload.get("username") or ""),
role=str(payload.get("role") or ""),
)
self._cache_validation(token, user)
return user
# --- shared request/response plumbing for everything below -------------
@@ -333,6 +422,11 @@ class AuthClient:
headers: dict[str, str] = {}
if self.project_key:
headers[PROJECT_KEY_HEADER] = self.project_key
# asyncio.to_thread runs this in a copy of the caller's context, so the address set by
# forwarded_client_ip is visible here.
address = _valid_ip(_forwarded_client_ip.get())
if address:
headers[FORWARDED_FOR_HEADER] = address
if body is not None:
data = json.dumps(body).encode()
headers["Content-Type"] = "application/json"
@@ -435,6 +529,7 @@ class AuthClient:
server-side. Returns the (cookie-clearing) Set-Cookie header
value(s) AuthGuard's response carried."""
_, cookies = await self._call("POST", "/api/logout", token=token)
self._forget_validation((token or "").strip())
return cookies
async def me(self, token: str) -> PublicUser:
@@ -61,7 +61,7 @@ from typing import Any, Callable, Optional
from fastapi import APIRouter, Depends, HTTPException, Request, Response
from pydantic import BaseModel
from .auth import ROLE_SUPERADMIN, can_manage_users, normalize_role
from .auth import MAX_PASSWORD_BYTES, ROLE_SUPERADMIN, can_manage_users, normalize_role
from .authclient import (
DEFAULT_COOKIE_NAME,
APIError,
@@ -69,11 +69,20 @@ from .authclient import (
AuthClientError,
ManagedUser,
PublicUser,
forwarded_client_ip,
)
from .clientip import client_address, parse_trusted_proxies, trusted_proxies_from_env
from .ratelimit import AttemptLimiter
__all__ = ["ProxyStore", "build_auth_router"]
MIN_PASSWORD_LEN = 8
# Attempt limits for login and the TOTP verify/disable routes, the same numbers as the Go proxy
# (backend/auth/ratelimit.go): each key may make `limit` attempts per window.
ATTEMPT_WINDOW_SECONDS = 15 * 60
LOGIN_ACCOUNT_LIMIT = 10
LOGIN_CLIENT_LIMIT = 200
TOTP_ATTEMPT_LIMIT = 5
MAX_USERNAME_LEN = 64
MAX_EMAIL_LEN = 254
@@ -81,6 +90,7 @@ ERR_AUTH_REQUIRED = "Authentication required."
ERR_SETUP_COMPLETE = "Setup has already been completed."
ERR_INVALID_CREDENTIALS = "Invalid username or password."
ERR_INVALID_INPUT = "Invalid authentication input."
ERR_TOO_MANY_ATTEMPTS = "Too many attempts. Try again later."
ERR_SELF_SERVICE_PROFILE = (
"Self-service profile editing is only available to administrator accounts; "
"ask an administrator to update this account."
@@ -93,6 +103,7 @@ ERR_FEATURE_REQUIRES_AUTHGUARD = "This feature requires AUTHGUARD_URL to be conf
# never this error - so every caller can safely report this same message
# 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_ADMIN_REQUIRED = "Administrator access required."
@@ -202,6 +213,11 @@ def _normalize_email(email: str) -> str:
def _validate_password(password: str) -> None:
if len(password or "") < MIN_PASSWORD_LEN:
raise HTTPException(status_code=400, detail="Password must be at least 8 characters.")
# bcrypt reads only the first 72 bytes, so a longer password could not be stored faithfully.
if len(password.encode("utf-8")) > MAX_PASSWORD_BYTES:
raise HTTPException(
status_code=400, detail=f"Password must be at most {MAX_PASSWORD_BYTES} bytes."
)
def _raise_authguard_error(err: Exception, fallback: str) -> None:
@@ -246,14 +262,38 @@ def build_auth_router(
cookie_name: str = DEFAULT_COOKIE_NAME,
configuration_error: str | None = None,
internal_secret: str | None = None,
local_profile_without_authguard: bool = False,
trusted_proxies: str | None = None,
) -> APIRouter:
"""Builds a ready-to-mount APIRouter implementing the full standardized
AuthGuard-proxy surface (no prefix baked in - mount it at "/api/auth",
matching every existing consumer). See the module docstring for the
`get_client`/`get_store` contract."""
`get_client`/`get_store` contract.
When `get_client` returns None (AUTHGUARD_URL unset) the guarded routes
refuse requests with a 500 unless `local_profile_without_authguard` is
True. Pass True only for a deployment that is meant to run without
AuthGuard; otherwise a missing environment variable would silently make
every guarded route run as the local superadmin.
Login and the TOTP routes refuse further attempts with 429: per account and per client
address for login (10 and 200 per 15 minutes), per user for TOTP verify and disable (5 per 15
minutes). The counters live in this process. The client address is the TCP peer;
`trusted_proxies` (default: the TRUSTED_PROXIES environment variable, a comma-separated list
of CIDR ranges or IP addresses, empty by default) names the reverse proxies whose
X-Forwarded-For is believed. An invalid list raises ValueError here, at startup. The address
is also sent to AuthGuard as X-Forwarded-For, which AuthGuard reads only from peers in its own
TRUSTED_PROXIES."""
router = APIRouter()
login_required_override: bool | None = None
trusted_networks = (
trusted_proxies_from_env()
if trusted_proxies is None
else parse_trusted_proxies(trusted_proxies)
)
login_account_attempts = AttemptLimiter(ATTEMPT_WINDOW_SECONDS, LOGIN_ACCOUNT_LIMIT)
login_client_attempts = AttemptLimiter(ATTEMPT_WINDOW_SECONDS, LOGIN_CLIENT_LIMIT)
totp_attempts = AttemptLimiter(ATTEMPT_WINDOW_SECONDS, TOTP_ATTEMPT_LIMIT)
configured_internal_secret = (
os.environ.get("SECRET", "") if internal_secret is None else internal_secret
).strip()
@@ -265,6 +305,21 @@ def build_auth_router(
def _enabled(client: Optional[AuthClient]) -> bool:
return client is not None
def _configured_client(
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
) -> Optional[AuthClient]:
"""Resolves the route's AuthClient. A missing client fails closed with a
500 unless running without AuthGuard was opted into."""
if client is None and not local_profile_without_authguard:
raise HTTPException(
status_code=500, detail=configuration_error or ERR_AUTHGUARD_NOT_CONFIGURED
)
return client
def _client_address(request: Request) -> str:
peer = request.client.host if request.client else ""
return client_address(peer, request.headers.getlist("x-forwarded-for"), trusted_networks)
def _session_token(request: Request) -> str:
return request.cookies.get(cookie_name, "") or ""
@@ -307,14 +362,12 @@ def build_auth_router(
return profile, token
async def _login_required(store: ProxyStore) -> bool:
if login_required_override is not None:
return login_required_override
return await store.login_required()
async def require_session(
request: Request,
store: ProxyStore = Depends(get_store), # noqa: B008
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> PublicUser:
"""FastAPI dependency gating a route behind a valid session."""
if not _enabled(client) or not await _login_required(store):
@@ -326,7 +379,7 @@ def build_auth_router(
async def _require_user_manager(
request: Request,
store: ProxyStore = Depends(get_store), # noqa: B008
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> str:
"""Returns the caller's session token, or "" in auth-disabled mode
(each handler decides its own auth-disabled response). Authorization
@@ -341,7 +394,7 @@ def build_auth_router(
async def require_admin(
request: Request,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> PublicUser:
"""FastAPI dependency gating a route behind an administrator session
(the Python counterpart of Go's RequireAdmin). Unlike require_session it
@@ -362,7 +415,7 @@ def build_auth_router(
async def get_me(
request: Request,
store: ProxyStore = Depends(get_store), # noqa: B008
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> dict[str, Any]:
_ensure_configured()
login_required = await _login_required(store)
@@ -383,7 +436,7 @@ def build_auth_router(
@router.get("/admin-needed")
async def get_admin_needed(
store: ProxyStore = Depends(get_store), # noqa: B008
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> dict[str, bool]:
if not _enabled(client):
return {"adminNeeded": False}
@@ -402,7 +455,7 @@ def build_auth_router(
async def get_status(
request: Request,
store: ProxyStore = Depends(get_store), # noqa: B008
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> dict[str, Any]:
_ensure_configured()
if not _enabled(client):
@@ -444,9 +497,10 @@ def build_auth_router(
@router.post("/setup", status_code=201)
async def setup(
req: SetupRequest,
request: Request,
response: Response,
store: ProxyStore = Depends(get_store), # noqa: B008
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> dict[str, Any]:
if not _enabled(client):
return {"user": _user_payload(_LOCAL_PROFILE)}
@@ -468,7 +522,8 @@ def build_auth_router(
raise HTTPException(status_code=409, detail=ERR_SETUP_COMPLETE)
try:
result = await client.register(username, email, req.password)
with forwarded_client_ip(_client_address(request)):
result = await client.register(username, email, req.password)
except AuthClientError as exc:
await store.unclaim_setup()
_raise_authguard_error(exc, "Could not create account.")
@@ -480,8 +535,9 @@ def build_auth_router(
@router.post("/login")
async def login(
req: LoginRequest,
request: Request,
response: Response,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> dict[str, Any]:
if not _enabled(client):
return {"user": _user_payload(_LOCAL_PROFILE)}
@@ -489,8 +545,13 @@ def build_auth_router(
identifier = (req.identifier or req.username or req.email or "").strip()
if not identifier or len(identifier) > MAX_EMAIL_LEN:
raise HTTPException(status_code=401, detail=ERR_INVALID_CREDENTIALS)
address = _client_address(request)
account_ok = login_account_attempts.allow(identifier.lower())
if not (account_ok and login_client_attempts.allow(address)):
raise HTTPException(status_code=429, detail=ERR_TOO_MANY_ATTEMPTS)
try:
result = await client.login(identifier, req.password, req.totpToken)
with forwarded_client_ip(address):
result = await client.login(identifier, req.password, req.totpToken)
except APIError as exc:
if exc.totp_required:
raise HTTPException(
@@ -513,7 +574,7 @@ def build_auth_router(
async def logout(
request: Request,
response: Response,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> dict[str, bool]:
if _enabled(client):
assert client is not None
@@ -537,7 +598,7 @@ def build_auth_router(
async def update_me(
req: UpdateMeRequest,
request: Request,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> dict[str, Any]:
if not _enabled(client):
raise HTTPException(status_code=409, detail=ERR_FEATURE_REQUIRES_AUTHGUARD)
@@ -581,9 +642,7 @@ def build_auth_router(
store: ProxyStore = Depends(get_store), # noqa: B008
_admin: PublicUser = Depends(require_admin), # noqa: B008
) -> dict[str, bool]:
nonlocal login_required_override
await store.set_login_required(req.loginRequired)
login_required_override = req.loginRequired
return {"loginRequired": req.loginRequired}
@router.put("/access/internal")
@@ -592,21 +651,19 @@ def build_auth_router(
request: Request,
store: ProxyStore = Depends(get_store), # noqa: B008
) -> dict[str, bool]:
nonlocal login_required_override
if (
not configured_internal_secret
or 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)
login_required_override = req.loginRequired
return {"loginRequired": req.loginRequired}
# --- admin user management ----------------------------------------------
@router.get("/users")
async def list_users(
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
token: str = Depends(_require_user_manager), # noqa: B008
) -> list[dict[str, Any]]:
if not _enabled(client):
@@ -622,7 +679,7 @@ def build_auth_router(
@router.post("/users", status_code=201)
async def create_managed_user(
req: ManagedUserRequest,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
token: str = Depends(_require_user_manager), # noqa: B008
) -> dict[str, Any]:
if not _enabled(client):
@@ -642,7 +699,7 @@ def build_auth_router(
async def update_managed_user(
user_id: int,
req: ManagedUserRequest,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
token: str = Depends(_require_user_manager), # noqa: B008
) -> dict[str, Any]:
if not _enabled(client):
@@ -673,7 +730,7 @@ def build_auth_router(
@router.delete("/users/{user_id}")
async def delete_managed_user(
user_id: int,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
token: str = Depends(_require_user_manager), # noqa: B008
) -> dict[str, bool]:
if not _enabled(client):
@@ -691,7 +748,7 @@ def build_auth_router(
@router.get("/totp/status")
async def get_totp_status(
request: Request,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> dict[str, bool]:
if not _enabled(client):
return {"enabled": False, "mfaEnabled": False}
@@ -702,7 +759,7 @@ def build_auth_router(
@router.post("/totp/initiate")
async def initiate_totp(
request: Request,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> dict[str, Any]:
if not _enabled(client):
raise HTTPException(status_code=409, detail=ERR_FEATURE_REQUIRES_AUTHGUARD)
@@ -730,15 +787,18 @@ def build_auth_router(
async def verify_totp(
req: TotpTokenRequest,
request: Request,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> dict[str, Any]:
if not _enabled(client):
raise HTTPException(status_code=409, detail=ERR_FEATURE_REQUIRES_AUTHGUARD)
assert client is not None
_, token = await _current_profile_or_401(request, client)
profile, token = await _current_profile_or_401(request, client)
if not totp_attempts.allow(str(profile.id)):
raise HTTPException(status_code=429, detail=ERR_TOO_MANY_ATTEMPTS)
code = req.totpToken or req.token
try:
await client.totp_verify(token, code)
with forwarded_client_ip(_client_address(request)):
await client.totp_verify(token, code)
except Exception as exc:
raise HTTPException(status_code=401, detail="Invalid authenticator code.") from exc
return {"data": {"mfaEnabled": True, "enabled": True, "backupCodes": []}}
@@ -747,15 +807,18 @@ def build_auth_router(
async def disable_totp(
req: TotpTokenRequest,
request: Request,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> dict[str, Any]:
if not _enabled(client):
raise HTTPException(status_code=409, detail=ERR_FEATURE_REQUIRES_AUTHGUARD)
assert client is not None
_, token = await _current_profile_or_401(request, client)
profile, token = await _current_profile_or_401(request, client)
if not totp_attempts.allow(str(profile.id)):
raise HTTPException(status_code=429, detail=ERR_TOO_MANY_ATTEMPTS)
code = req.totpToken or req.token
try:
await client.totp_disable(token, code)
with forwarded_client_ip(_client_address(request)):
await client.totp_disable(token, code)
except Exception as exc:
raise HTTPException(status_code=401, detail="Invalid authenticator code.") from exc
return {"data": {"mfaEnabled": False, "enabled": False}}
@@ -0,0 +1,76 @@
"""Trusted-proxy-aware client address, the Python counterpart of backend/auth/clientip.go.
The address used for attempt limits and forwarded to AuthGuard is the TCP peer. X-Forwarded-For is
read only when that peer is inside a configured trusted-proxy list (the TRUSTED_PROXIES setting),
and is then walked from the right to the first hop that is not itself a trusted proxy. The list is
empty by default, so a client can never choose its own address.
"""
from __future__ import annotations
import ipaddress
import os
from collections.abc import Iterable, Mapping, Sequence
__all__ = ["client_address", "parse_trusted_proxies", "trusted_proxies_from_env"]
IPNetwork = ipaddress.IPv4Network | ipaddress.IPv6Network
IPAddress = ipaddress.IPv4Address | ipaddress.IPv6Address
def parse_trusted_proxies(value: str | None) -> list[IPNetwork]:
"""Parses a comma-separated list of CIDR ranges or bare IP addresses. An empty value trusts no
proxy. Raises ValueError for an entry that is neither."""
networks: list[IPNetwork] = []
for entry in (value or "").split(","):
entry = entry.strip()
if not entry:
continue
try:
networks.append(ipaddress.ip_network(entry, strict=False))
except ValueError as exc:
raise ValueError(
f"trusted proxy {entry!r} is neither an IP address nor a CIDR range"
) from exc
return networks
def trusted_proxies_from_env(env: Mapping[str, str] | None = None) -> list[IPNetwork]:
"""Reads the TRUSTED_PROXIES setting."""
source = os.environ if env is None else env
return parse_trusted_proxies(source.get("TRUSTED_PROXIES", ""))
def _parse_ip(value: str) -> IPAddress | None:
try:
ip = ipaddress.ip_address(value)
except ValueError:
return None
if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped is not None:
return ip.ipv4_mapped
return ip
def _is_trusted(ip: IPAddress, trusted: Sequence[IPNetwork]) -> bool:
return any(ip.version == network.version and ip in network for network in trusted)
def client_address(peer: str, forwarded_for: Iterable[str], trusted: Sequence[IPNetwork]) -> str:
"""Returns the address a request is counted against. peer is the TCP peer's host and
forwarded_for the values of every X-Forwarded-For header line. A malformed entry makes the peer
the answer, so a bad header can never choose the key."""
peer_ip = _parse_ip(peer)
if peer_ip is None or not _is_trusted(peer_ip, trusted):
return peer
hops = [part.strip() for line in forwarded_for for part in line.split(",") if part.strip()]
if not hops:
return peer
for hop in reversed(hops):
ip = _parse_ip(hop)
if ip is None:
return peer
if not _is_trusted(ip, trusted):
return str(ip)
# Every hop is a trusted proxy, so the left-most one is closest to the client.
first = _parse_ip(hops[0])
return str(first) if first is not None else peer
@@ -19,9 +19,29 @@ for a minimal FastAPI example.
from __future__ import annotations
import hmac
import threading
from dataclasses import dataclass, field
from typing import Callable, Optional
from urllib.parse import urlsplit
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:
return False
return hmac.compare_digest(expected, (provided or "").encode("utf-8"))
def _is_service_url(value: str) -> bool:
try:
parts = urlsplit(value)
parts.port # noqa: B018 - raises ValueError for an invalid port
except ValueError:
return False
return parts.scheme in ("http", "https") and bool(parts.hostname)
@dataclass
@@ -104,17 +124,26 @@ 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 FastAPI usage:
Info. Every URL must be an http or https URL with a host; otherwise
nothing is changed and ValueError is raised. Minimal FastAPI usage:
@app.put("/api/core-services/internal")
async def push_core_services(request: Request):
if request.headers.get("X-Internal-Auth") != SECRET:
if not internal_secret_matches(request.headers.get("X-Internal-Auth"), SECRET):
raise HTTPException(status_code=401)
body = await request.json()
info = core_config_store.set(Info.from_json(body))
try:
info = core_config_store.set(Info.from_json(body))
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
return {"ok": True, "info": info.to_json()}
"""
next_info = _normalize(next_info)
for url in [next_info.auth_guard_url, *next_info.carrier_node_urls]:
if url and not _is_service_url(url):
raise ValueError(
f"core service URL must be an http or https URL with a host: {url}"
)
with self._lock:
if next_info.auth_guard_url:
self._info.auth_guard_url = next_info.auth_guard_url
@@ -15,6 +15,24 @@ from .config import DatabaseConfig
_logger = logging.getLogger(__name__)
# The same connection failures that database.js treats as transient: refused,
# reset and broken sockets, an administrative shutdown, a dropped connection
# (SQLSTATE class 08) and a connect timeout. Other errors, such as bad
# credentials or a missing database, are raised at once instead of retried.
_TRANSIENT_CONNECTION_ERRORS = (
ConnectionRefusedError,
ConnectionResetError,
BrokenPipeError,
TimeoutError,
asyncpg.exceptions.AdminShutdownError,
asyncpg.exceptions.PostgresConnectionError,
)
def is_transient_connection_error(exc: BaseException) -> bool:
"""Return True for connection failures that a startup retry can recover from."""
return isinstance(exc, _TRANSIENT_CONNECTION_ERRORS)
@dataclass(frozen=True, slots=True)
class StartupRetryOptions:
@@ -50,7 +68,11 @@ async def retry_startup(
operation: Callable[[], Awaitable[Any]],
options: StartupRetryOptions | None = None,
) -> Any:
"""Retry a startup operation until it succeeds or the context is cancelled."""
"""Retry a startup operation on transient connection errors only.
Any other exception is raised immediately, so a wrong password or a missing
database does not spin until the process is stopped.
"""
policy = options or startup_retry_options_from_env()
attempt = 0
@@ -61,6 +83,8 @@ async def retry_startup(
except asyncio.CancelledError:
raise
except Exception as exc:
if not is_transient_connection_error(exc):
raise
if policy.max_attempts and attempt >= policy.max_attempts:
raise
_logger.warning(
@@ -0,0 +1,47 @@
"""Fixed-window attempt counters for credential endpoints, the Python counterpart of
backend/auth/ratelimit.go. Counters live in this process; AuthGuard's own limits apply on top."""
from __future__ import annotations
import threading
import time
from collections.abc import Callable
__all__ = ["AttemptLimiter"]
MAX_TRACKED_ATTEMPT_KEYS = 10000
class AttemptLimiter:
"""Each key may make `limit` attempts per `window` seconds; further attempts are refused until
the window ends. When the table is full of live keys a new key is refused rather than tracked,
so flooding distinct keys cannot grow memory without bound."""
def __init__(
self, window: float, limit: int, *, clock: Callable[[], float] = time.monotonic
) -> None:
self._window = window
self._limit = limit
self._clock = clock
self._lock = threading.Lock()
self._counts: dict[str, tuple[float, int]] = {}
def allow(self, key: str) -> bool:
"""Records one attempt for key and reports whether it is within the limit."""
now = self._clock()
with self._lock:
tracked = key in self._counts
if not tracked and len(self._counts) >= MAX_TRACKED_ATTEMPT_KEYS:
self._counts = {
existing: state
for existing, state in self._counts.items()
if now - state[0] < self._window
}
if len(self._counts) >= MAX_TRACKED_ATTEMPT_KEYS:
return False
start, count = self._counts.get(key, (now, 0))
if now - start >= self._window:
start, count = now, 0
count += 1
self._counts[key] = (start, count)
return count <= self._limit
@@ -72,4 +72,5 @@ def _normalize_secret(value: str) -> str:
def _normalize_token(value: str) -> str:
token = str(value or "").strip()
return token if len(token) == TOTP_DIGITS and token.isdigit() else ""
# str.isdigit() accepts other scripts' digits too, and hmac.compare_digest refuses those.
return token if len(token) == TOTP_DIGITS and token.isascii() and token.isdigit() else ""
@@ -0,0 +1,81 @@
import unittest
from shared_backend.clientip import client_address, parse_trusted_proxies
from shared_backend.ratelimit import MAX_TRACKED_ATTEMPT_KEYS, AttemptLimiter
class ParseTrustedProxiesTests(unittest.TestCase):
def test_accepts_cidrs_and_bare_addresses(self) -> None:
networks = parse_trusted_proxies(" 10.0.0.0/8, 192.168.1.5 ,fd00::/8,, ::1 ")
self.assertEqual(
[str(network) for network in networks],
["10.0.0.0/8", "192.168.1.5/32", "fd00::/8", "::1/128"],
)
def test_empty_trusts_no_proxy(self) -> None:
self.assertEqual(parse_trusted_proxies(" "), [])
self.assertEqual(parse_trusted_proxies(None), [])
def test_rejects_invalid_entries(self) -> None:
for value in ("not-an-ip", "10.0.0.0/33", "10.0.0.1, bogus"):
with self.assertRaises(ValueError, msg=value):
parse_trusted_proxies(value)
class ClientAddressTests(unittest.TestCase):
def test_forwarded_for_is_ignored_without_trusted_proxies(self) -> None:
self.assertEqual(client_address("203.0.113.7", ["198.51.100.1"], []), "203.0.113.7")
def test_forwarded_for_is_ignored_from_an_unknown_peer(self) -> None:
trusted = parse_trusted_proxies("10.0.0.0/8")
self.assertEqual(client_address("203.0.113.7", ["198.51.100.1"], trusted), "203.0.113.7")
def test_a_trusted_peer_has_its_header_honoured(self) -> None:
trusted = parse_trusted_proxies("10.0.0.0/8, 172.16.0.0/12")
cases = [
("single client", ["198.51.100.9"], "198.51.100.9"),
("second trusted hop", ["198.51.100.9, 172.16.4.4"], "198.51.100.9"),
("spoofed left-most entry", ["6.6.6.6, 198.51.100.9, 172.16.4.4"], "198.51.100.9"),
("entries across header lines", ["6.6.6.6", "198.51.100.9"], "198.51.100.9"),
("malformed entry", ["198.51.100.9, not-an-ip"], "10.0.0.2"),
("no header", [], "10.0.0.2"),
("every hop trusted", ["10.1.1.1, 172.16.4.4"], "10.1.1.1"),
]
for name, forwarded, want in cases:
with self.subTest(name):
self.assertEqual(client_address("10.0.0.2", forwarded, trusted), want)
def test_an_ipv4_mapped_peer_matches_an_ipv4_range(self) -> None:
trusted = parse_trusted_proxies("10.0.0.0/8")
self.assertEqual(
client_address("::ffff:10.0.0.2", ["198.51.100.9"], trusted), "198.51.100.9"
)
def test_a_non_ip_peer_is_returned_as_is(self) -> None:
self.assertEqual(client_address("testclient", ["198.51.100.9"], []), "testclient")
class AttemptLimiterTests(unittest.TestCase):
def test_window_and_limit(self) -> None:
now = [1000.0]
limiter = AttemptLimiter(60, 2, clock=lambda: now[0])
self.assertTrue(limiter.allow("k"))
self.assertTrue(limiter.allow("k"))
self.assertFalse(limiter.allow("k"))
self.assertTrue(limiter.allow("other"))
now[0] += 60
self.assertTrue(limiter.allow("k"))
def test_the_table_is_bounded(self) -> None:
now = [0.0]
limiter = AttemptLimiter(3600, 1, clock=lambda: now[0])
for i in range(MAX_TRACKED_ATTEMPT_KEYS):
limiter.allow(str(i))
self.assertFalse(limiter.allow("new-key"))
self.assertFalse(limiter.allow("0")) # a tracked key keeps its own count
now[0] += 3600 # every window has ended, so stale keys are dropped to make room
self.assertTrue(limiter.allow("new-key"))
if __name__ == "__main__":
unittest.main()
@@ -13,6 +13,7 @@ from shared_backend.authclient import (
InvalidSessionError,
ManagedUser,
PublicUser,
forwarded_client_ip,
resolve_user,
token_from_request,
)
@@ -49,6 +50,37 @@ def _fake_http_error(status: int, payload: dict) -> urllib.error.HTTPError:
)
class AuthClientForwardedClientIpTests(unittest.IsolatedAsyncioTestCase):
"""forwarded_client_ip makes credential calls carry the end user's address (S-009)."""
async def _login_request(self, address):
client = AuthClient("https://authguard.example")
payload = {"user": {"id": 1, "username": "a", "email": "", "role": "user"}}
with patch(
"shared_backend.authclient.urllib.request.urlopen",
return_value=_FakeResponse(200, payload),
) as urlopen:
if address is None:
await client.login("a", "secret-password")
else:
with forwarded_client_ip(address):
await client.login("a", "secret-password")
return urlopen.call_args.args[0]
async def test_the_address_is_sent_as_x_forwarded_for(self) -> None:
request = await self._login_request("203.0.113.9")
self.assertEqual(request.get_header("X-forwarded-for"), "203.0.113.9")
async def test_no_header_is_sent_outside_the_block(self) -> None:
request = await self._login_request(None)
self.assertIsNone(request.get_header("X-forwarded-for"))
async def test_a_value_that_is_not_an_ip_address_is_dropped(self) -> None:
for value in ("203.0.113.9\r\nX-Evil: 1", "not-an-ip", ""):
request = await self._login_request(value)
self.assertIsNone(request.get_header("X-forwarded-for"), repr(value))
class AuthClientBaseUrlTests(unittest.TestCase):
def test_bare_public_host_assumes_https(self) -> None:
self.assertEqual(AuthClient("auth.example.com").base_url, "https://auth.example.com")
@@ -155,6 +187,57 @@ class AuthClientValidateTests(unittest.IsolatedAsyncioTestCase):
await self.client.validate("a-token")
class AuthClientValidationCacheTests(unittest.IsolatedAsyncioTestCase):
def setUp(self) -> None:
self.client = AuthClient("https://authguard.example")
payload = {"valid": True, "user_id": 42, "username": "alice", "role": "admin"}
self.valid = _FakeResponse(200, payload)
async def test_repeated_validate_reuses_the_answer(self) -> None:
with patch(
"shared_backend.authclient.urllib.request.urlopen", return_value=self.valid
) as urlopen:
first = await self.client.validate("a-token")
second = await self.client.validate("a-token")
self.assertEqual(first, second)
urlopen.assert_called_once()
async def test_invalid_session_is_cached_too(self) -> None:
with patch(
"shared_backend.authclient.urllib.request.urlopen",
return_value=_FakeResponse(401, {"valid": False}),
) as urlopen:
with self.assertRaises(InvalidSessionError):
await self.client.validate("bad-token")
with self.assertRaises(InvalidSessionError):
await self.client.validate("bad-token")
urlopen.assert_called_once()
async def test_logout_drops_the_cached_answer(self) -> None:
with patch(
"shared_backend.authclient.urllib.request.urlopen",
side_effect=[self.valid, _FakeResponse(200, {}), _FakeResponse(401, {"valid": False})],
) as urlopen:
await self.client.validate("a-token")
await self.client.logout("a-token")
with self.assertRaises(InvalidSessionError):
await self.client.validate("a-token")
self.assertEqual(urlopen.call_count, 3)
async def test_set_base_url_clears_the_cache(self) -> None:
with patch(
"shared_backend.authclient.urllib.request.urlopen", return_value=self.valid
) as urlopen:
await self.client.validate("a-token")
self.client.set_base_url("https://authguard2.example")
await self.client.validate("a-token")
self.assertEqual(urlopen.call_count, 2)
class TokenFromRequestTests(unittest.TestCase):
def test_prefers_authorization_header_over_cookie(self) -> None:
headers = {"Authorization": "Bearer header-token"}
@@ -10,6 +10,7 @@ from shared_backend.authclient import (
AuthClient,
PublicUser,
SessionResult,
_forwarded_client_ip,
)
@@ -44,6 +45,8 @@ def _build_app(
client: AuthClient | None = None,
*,
internal_secret: str | None = None,
local_profile_without_authguard: bool = False,
trusted_proxies: str = "",
) -> FastAPI:
def get_client(request: Request) -> AuthClient | None:
return client
@@ -53,15 +56,23 @@ def _build_app(
app = FastAPI()
app.include_router(
ap.build_auth_router(get_client, get_store, internal_secret=internal_secret),
ap.build_auth_router(
get_client,
get_store,
internal_secret=internal_secret,
local_profile_without_authguard=local_profile_without_authguard,
trusted_proxies=trusted_proxies,
),
prefix="/api/auth",
)
return app
class AuthDisabledModeTests(unittest.TestCase):
"""client=None (AUTHGUARD_URL unset) - every route reports the fixed
placeholder superadmin identity and nothing is gated. This is also a
"""client=None (AUTHGUARD_URL unset) with the local-mode opt-in - every
route reports the fixed placeholder superadmin identity and nothing is
gated. Without the opt-in the same deployment fails closed; see
UnconfiguredAuthGuardTests. This is also a
regression test for a real bug this module had: request/response models
declared *inside* build_auth_router, combined with `from __future__
import annotations`, made FastAPI silently misparse every JSON body as a
@@ -69,7 +80,7 @@ class AuthDisabledModeTests(unittest.TestCase):
bug)."""
def setUp(self) -> None:
self.client = TestClient(_build_app(_FakeStore()))
self.client = TestClient(_build_app(_FakeStore(), local_profile_without_authguard=True))
def test_status_reports_local_superadmin(self) -> None:
response = self.client.get("/api/auth/status")
@@ -118,6 +129,25 @@ class AuthDisabledModeTests(unittest.TestCase):
self.assertEqual(self.client.put("/api/auth/me", json={}).status_code, 409)
class UnconfiguredAuthGuardTests(unittest.TestCase):
"""client=None without local_profile_without_authguard: a missing
AUTHGUARD_URL must not turn guarded routes into the local superadmin."""
def setUp(self) -> None:
self.client = TestClient(
_build_app(_FakeStore(login_required=True)), raise_server_exceptions=False
)
def test_guarded_routes_fail_closed(self) -> None:
self.assertEqual(self.client.get("/api/auth/status").status_code, 500)
self.assertEqual(self.client.get("/api/auth/me").status_code, 500)
self.assertEqual(self.client.get("/api/auth/users").status_code, 500)
self.assertEqual(self.client.post("/api/auth/logout").status_code, 500)
def test_login_flag_read_is_still_public(self) -> None:
self.assertEqual(self.client.get("/api/auth/access").json(), {"loginRequired": True})
class AccessSettingsTests(unittest.TestCase):
def test_get_is_public_and_put_requires_an_admin_session(self) -> None:
store = _FakeStore(login_required=True)
@@ -142,7 +172,7 @@ class AccessSettingsTests(unittest.TestCase):
store = _FakeStore(login_required=True)
client = TestClient(_build_app(store))
response = client.put("/api/auth/access", json={"loginRequired": False})
self.assertEqual(response.status_code, 401)
self.assertEqual(response.status_code, 500)
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": True})
def test_internal_update_disables_login_and_uses_admin_identity(self) -> None:
@@ -275,12 +305,142 @@ class EnabledModeSetupAndLoginTests(unittest.TestCase):
self.assertIsNone(body["user"])
class _AddressRecordingClient(_RoleClient):
"""Records the address AuthClient would send as X-Forwarded-For for each credential call, and
counts the calls that reached AuthGuard."""
def __init__(self) -> None:
super().__init__()
self.forwarded: list[str | None] = []
self.login_calls = 0
self.totp_calls = 0
async def login(self, username_or_email: str, password: str, totp_token: str = ""):
self.login_calls += 1
self.forwarded.append(_forwarded_client_ip.get())
return await super().login(username_or_email, password, totp_token)
async def register(self, username: str, email: str, password: str) -> SessionResult:
self.forwarded.append(_forwarded_client_ip.get())
return await super().register(username, email, password)
async def totp_verify(self, token: str, code: str) -> None:
self.totp_calls += 1
self.forwarded.append(_forwarded_client_ip.get())
if code != "123456":
raise APIError(401, "bad code")
async def totp_disable(self, token: str, code: str) -> None:
self.totp_calls += 1
self.forwarded.append(_forwarded_client_ip.get())
raise APIError(401, "bad code")
class AttemptLimitTests(unittest.TestCase):
"""Login and the TOTP routes refuse further attempts with 429 (S-009)."""
def _login(self, client: TestClient, identifier: str = "Victim") -> int:
response = client.post(
"/api/auth/login", json={"identifier": identifier, "password": "wrong"}
)
return response.status_code
def test_login_is_limited_per_account_before_authguard_is_called(self) -> None:
fake = _AddressRecordingClient()
client = TestClient(_build_app(_FakeStore(), fake))
for attempt in range(ap.LOGIN_ACCOUNT_LIMIT):
self.assertEqual(self._login(client), 401, f"attempt {attempt + 1}")
self.assertEqual(self._login(client), 429)
self.assertEqual(self._login(client, "VICTIM"), 429) # the account key ignores case
self.assertEqual(fake.login_calls, ap.LOGIN_ACCOUNT_LIMIT)
self.assertEqual(self._login(client, "someone-else"), 401)
def test_login_is_limited_per_client_address(self) -> None:
fake = _AddressRecordingClient()
client = TestClient(_build_app(_FakeStore(), fake), client=("203.0.113.7", 40000))
statuses = [self._login(client, f"user{i}") for i in range(ap.LOGIN_CLIENT_LIMIT + 1)]
self.assertEqual(statuses[:-1], [401] * ap.LOGIN_CLIENT_LIMIT)
self.assertEqual(statuses[-1], 429)
def test_totp_verify_and_disable_share_a_per_user_limit(self) -> None:
fake = _AddressRecordingClient()
client = TestClient(_build_app(_FakeStore(), fake))
client.cookies.set(DEFAULT_COOKIE_NAME, "user-token")
for _ in range(ap.TOTP_ATTEMPT_LIMIT - 1):
response = client.post("/api/auth/totp/verify", json={"totpToken": "000000"})
self.assertEqual(response.status_code, 401)
self.assertEqual(
client.post("/api/auth/totp/disable", json={"totpToken": "000000"}).status_code, 401
)
self.assertEqual(
client.post("/api/auth/totp/verify", json={"totpToken": "123456"}).status_code, 429
)
self.assertEqual(
client.post("/api/auth/totp/disable", json={"totpToken": "000000"}).status_code, 429
)
self.assertEqual(fake.totp_calls, ap.TOTP_ATTEMPT_LIMIT)
class ClientAddressForwardingTests(unittest.TestCase):
"""The client address is the TCP peer unless the peer is a trusted proxy (decision 5), and it
reaches AuthGuard as X-Forwarded-For through forwarded_client_ip."""
def _login_address(self, *, peer: str, trusted: str, forwarded: str | None) -> str | None:
fake = _AddressRecordingClient()
client = TestClient(
_build_app(_FakeStore(), fake, trusted_proxies=trusted), client=(peer, 40000)
)
headers = {"X-Forwarded-For": forwarded} if forwarded is not None else {}
response = client.post(
"/api/auth/login",
json={"identifier": "a@b.com", "password": "correct"},
headers=headers,
)
self.assertEqual(response.status_code, 200)
return fake.forwarded[-1]
def test_the_tcp_peer_is_forwarded_without_trusted_proxies(self) -> None:
got = self._login_address(peer="203.0.113.7", trusted="", forwarded="6.6.6.6")
self.assertEqual(got, "203.0.113.7")
def test_a_spoofed_header_from_an_untrusted_peer_is_ignored(self) -> None:
got = self._login_address(peer="203.0.113.7", trusted="10.0.0.0/8", forwarded="6.6.6.6")
self.assertEqual(got, "203.0.113.7")
def test_a_trusted_peer_has_its_header_walked_right_to_left(self) -> None:
got = self._login_address(
peer="10.0.0.2", trusted="10.0.0.0/8", forwarded="6.6.6.6, 198.51.100.9, 10.0.0.1"
)
self.assertEqual(got, "198.51.100.9")
def test_setup_and_totp_forward_the_address_too(self) -> None:
fake = _AddressRecordingClient()
fake.setup_required = True
client = TestClient(_build_app(_FakeStore(), fake), client=("198.51.100.20", 40000))
client.post(
"/api/auth/setup",
json={"username": "admin", "email": "admin@example.com", "password": "password123"},
)
client.cookies.set(DEFAULT_COOKIE_NAME, "user-token")
client.post("/api/auth/totp/verify", json={"totpToken": "123456"})
client.post("/api/auth/totp/disable", json={"totpToken": "123456"})
self.assertEqual(fake.forwarded, ["198.51.100.20"] * 3)
def test_the_forwarded_address_does_not_leak_outside_the_call(self) -> None:
self._login_address(peer="203.0.113.7", trusted="", forwarded=None)
self.assertIsNone(_forwarded_client_ip.get())
def test_an_invalid_trusted_proxy_list_fails_at_startup(self) -> None:
with self.assertRaises(ValueError):
_build_app(_FakeStore(), trusted_proxies="10.0.0.0/8, not-an-ip")
class RequestValidationTests(unittest.TestCase):
"""Every JSON-body route must actually parse its body (see the docstring
on AuthDisabledModeTests for the regression this guards against)."""
def setUp(self) -> None:
self.client = TestClient(_build_app(_FakeStore()))
self.client = TestClient(_build_app(_FakeStore(), local_profile_without_authguard=True))
def test_setup_rejects_missing_fields_with_422_not_500(self) -> None:
response = self.client.post("/api/auth/setup", json={})
@@ -0,0 +1,77 @@
import json
import unittest
from pathlib import Path
from shared_backend.auth import (
hash_password,
password_hash_needs_upgrade,
verify_and_upgrade_password,
verify_password,
)
from shared_backend.clientip import client_address, parse_trusted_proxies
from shared_backend.totp import verify_totp
# 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"
@unittest.skipUnless(
CONTRACT_PATH.exists(), "contract/auth-contract.json is not part of this checkout"
)
class AuthContractTests(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
cls.contract = json.loads(CONTRACT_PATH.read_text(encoding="utf-8"))
def test_password_hashes_verify_as_the_contract_says_for_python(self) -> None:
password = self.contract["password"]
for entry in password["hashes"]:
with self.subTest(entry["name"]):
self.assertEqual(
verify_password(password["plaintext"], entry["hash"]),
entry["verifies"]["python"],
)
self.assertFalse(verify_password(password["wrongPassword"], 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"]
)
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))
def test_the_password_length_contract_holds_for_python(self) -> None:
too_long = self.contract["password"]["tooLongToHash"]
try:
hash_password("a" * too_long["bytes"])
accepted = True
except ValueError:
accepted = False
self.assertEqual(accepted, too_long["accepted"]["python"])
def test_totp_verifies_as_the_contract_says(self) -> None:
totp = self.contract["totp"]
for entry in totp["cases"]:
with self.subTest(entry["name"]):
secret = entry.get("secret", totp["secret"])
self.assertEqual(verify_totp(secret, entry["code"], entry["unix"]), entry["valid"])
def test_client_address_follows_the_contract(self) -> None:
section = self.contract["clientAddress"]
for entry in section["cases"]:
with self.subTest(entry["name"]):
trusted = parse_trusted_proxies(entry["trusted"])
self.assertEqual(
client_address(entry["peer"], entry["forwarded"], trusted), entry["want"]
)
for value in section["invalidTrustedProxyLists"]:
with self.subTest(value), self.assertRaises(ValueError):
parse_trusted_proxies(value)
if __name__ == "__main__":
unittest.main()
@@ -1,9 +1,26 @@
import asyncio
import os
import unittest
from datetime import timedelta
from shared_backend.auth import ResetManager, hash_password, verify_password
import bcrypt
from shared_backend.auth import (
ResetManager,
hash_password,
hash_password_async,
password_hash_needs_upgrade,
verify_and_upgrade_password,
verify_and_upgrade_password_async,
verify_password,
verify_password_async,
)
from shared_backend.config import DatabaseConfig
from shared_backend.postgres import (
StartupRetryOptions,
is_transient_connection_error,
retry_startup,
)
from shared_backend.tokens import hash_token, new_session_token
from shared_backend.totp import totp_provisioning_uri, verify_totp
@@ -14,6 +31,95 @@ class SharedBackendTests(unittest.TestCase):
self.assertTrue(verify_password("correct horse battery staple", password_hash))
self.assertFalse(verify_password("wrong password", password_hash))
def test_async_password_helpers_match_the_sync_ones(self):
async def run():
password_hash = await hash_password_async("correct horse battery staple")
self.assertTrue(verify_password("correct horse battery staple", password_hash))
self.assertTrue(
await verify_password_async("correct horse battery staple", password_hash)
)
self.assertFalse(await verify_password_async("wrong password", password_hash))
asyncio.run(run())
def test_new_hashes_carry_the_scheme_prefix_and_the_current_cost(self):
password_hash = hash_password("correct horse battery staple")
self.assertTrue(password_hash.startswith("bcrypt$$2b$12$"))
self.assertFalse(password_hash_needs_upgrade(password_hash))
def test_unprefixed_legacy_bcrypt_hashes_still_verify_and_are_upgraded(self):
legacy = bcrypt.hashpw(
b"correct horse battery staple", bcrypt.gensalt(rounds=12)
).decode()
self.assertTrue(verify_password("correct horse battery staple", legacy))
self.assertFalse(verify_password("wrong password", legacy))
self.assertTrue(password_hash_needs_upgrade(legacy))
valid, upgraded = verify_and_upgrade_password("correct horse battery staple", legacy)
self.assertTrue(valid)
self.assertTrue(upgraded.startswith("bcrypt$$2b$12$"))
self.assertTrue(verify_password("correct horse battery staple", upgraded))
self.assertFalse(password_hash_needs_upgrade(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)
).decode()
self.assertTrue(password_hash_needs_upgrade(low_cost))
valid, upgraded = verify_and_upgrade_password("correct horse battery staple", low_cost)
self.assertTrue(valid)
self.assertIsNotNone(upgraded)
def test_a_wrong_password_and_a_current_hash_are_not_rewritten(self):
current = hash_password("correct horse battery staple")
password = "correct horse battery staple"
self.assertEqual(verify_and_upgrade_password(password, current), (True, None))
self.assertEqual(verify_and_upgrade_password("wrong password", current), (False, None))
def test_unknown_formats_fail_closed(self):
unknown = [
"",
"bcrypt$",
"bcrypt$not-a-bcrypt-string",
"pbkdf2-sha256$600000$00$00",
"$1$abc",
]
for stored in unknown:
self.assertFalse(verify_password("correct horse battery staple", stored), stored)
def test_async_upgrade_matches_the_sync_one(self):
password = "correct horse battery staple"
legacy = bcrypt.hashpw(password.encode(), bcrypt.gensalt(rounds=12)).decode()
async def run():
valid, upgraded = await verify_and_upgrade_password_async(password, legacy)
self.assertTrue(valid)
self.assertTrue(await verify_password_async(password, upgraded))
asyncio.run(run())
def test_startup_retry_only_retries_transient_connection_errors(self):
import asyncpg
async def retry_with(error):
attempts = []
async def operation():
attempts.append(1)
raise error
policy = StartupRetryOptions(interval_seconds=0.001, max_attempts=3)
with self.assertRaises(type(error)):
await retry_startup(operation, policy)
return len(attempts)
self.assertTrue(is_transient_connection_error(ConnectionRefusedError()))
self.assertTrue(is_transient_connection_error(asyncpg.exceptions.ConnectionDoesNotExistError("closed")))
self.assertFalse(is_transient_connection_error(asyncpg.exceptions.InvalidPasswordError("bad")))
self.assertFalse(is_transient_connection_error(ValueError("bad")))
self.assertEqual(asyncio.run(retry_with(ValueError("bad"))), 1)
self.assertEqual(asyncio.run(retry_with(ConnectionRefusedError())), 3)
def test_session_token_hash(self):
token, token_hash = new_session_token()
self.assertNotEqual(token, token_hash)
@@ -1,6 +1,6 @@
import unittest
from shared_backend.coreconfig import Info, Store
from shared_backend.coreconfig import Info, Store, internal_secret_matches
class StoreDefaultsTests(unittest.TestCase):
@@ -62,5 +62,29 @@ class StoreSetTests(unittest.TestCase):
self.assertEqual(info.to_json()["carrierNodeUrl"], "http://carrier.example.com")
class InternalSecretTests(unittest.TestCase):
def test_unset_or_empty_secret_never_matches(self):
self.assertFalse(internal_secret_matches(None, None))
self.assertFalse(internal_secret_matches(None, ""))
self.assertFalse(internal_secret_matches("", ""))
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"))
class UrlValidationTests(unittest.TestCase):
def test_rejects_urls_that_are_not_http_or_https_with_a_host(self):
store = Store(Info(auth_guard_url="http://auth.example.com"))
for bad in ["javascript:alert(1)", "auth.example.com", "ftp://carrier.example.com", "http://"]:
with self.subTest(url=bad), self.assertRaises(ValueError):
store.set(Info(auth_guard_url=bad))
with self.assertRaises(ValueError):
store.set(Info(carrier_node_urls=["http://carrier.example.com:99999"]))
self.assertEqual(store.auth_guard_url, "http://auth.example.com")
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,120 @@
import unittest
from shared_backend.auth import (
AuthStore,
EmptyPasswordHashError,
InvalidUsernameError,
TotpAlreadyEnabledError,
hash_password,
)
class _FakeDatabase:
"""Records queries and answers them from canned results."""
def __init__(self) -> None:
self.executed: list[tuple[str, tuple]] = []
self.fetched: list[tuple[str, tuple]] = []
self.execute_status = "UPDATE 1"
self.totp_enabled = False
self.rows_by_condition: dict[str, dict] = {}
async def execute(self, query: str, *args) -> str:
self.executed.append((query, args))
return self.execute_status
async def fetchval(self, query: str, *args):
return False
async def fetchrow(self, query: str, *args):
self.fetched.append((query, args))
if "totp_enabled" in query:
return {"secret": "S", "enabled": self.totp_enabled}
for condition, row in self.rows_by_condition.items():
if condition in query:
return row
return None
def _user_row(username: str, email: str = "") -> dict:
return {
"id": 1,
"username": username,
"email": email,
"password_hash": "h",
"role": "user",
"created_at": None,
"updated_at": None,
}
class AuthStoreHardeningTests(unittest.IsolatedAsyncioTestCase):
def setUp(self) -> None:
self.db = _FakeDatabase()
self.store = AuthStore(self.db, single_user=False) # type: ignore[arg-type]
async def test_ensure_schema_requests_the_case_insensitive_username_index(self) -> None:
await self.store.ensure_schema()
statements = " ".join(query for query, _ in self.db.executed)
self.assertIn("auth_users_username_lower_idx", statements)
self.assertIn("lower(username)", statements)
# The index is created only while no clashing pair exists.
self.assertIn("HAVING count(*) > 1", statements)
async def test_set_totp_secret_refuses_while_enabled(self) -> None:
self.db.execute_status = "UPDATE 0"
self.db.totp_enabled = True
with self.assertRaises(TotpAlreadyEnabledError):
await self.store.set_totp_secret(1, "NEWSECRET")
self.assertIn("NOT totp_enabled", self.db.executed[0][0])
async def test_set_totp_secret_succeeds_while_disabled(self) -> None:
await self.store.set_totp_secret(1, "NEWSECRET")
self.db.execute_status = "UPDATE 0" # no such user: nothing to refuse
await self.store.set_totp_secret(2, "NEWSECRET")
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),
lambda u, h: self.store.create_managed_user(u, "", h),
lambda u, h: self.store.update_credentials(1, u, "", h),
lambda u, h: self.store.update_user(1, username=u, password_hash=h),
]
for write in writes:
with self.assertRaises(EmptyPasswordHashError):
await write("alice", "")
with self.assertRaises(InvalidUsernameError):
await write("alice@example.com", "hash")
self.assertEqual(self.db.executed, [])
self.assertEqual(self.db.fetched, [])
async def test_update_user_leaves_unspecified_fields_alone(self) -> None:
await self.store.update_user(1, email="a@b.com")
await self.store.update_user(1, role="admin")
self.assertEqual(len(self.db.executed), 2)
async def test_find_by_identifier_tries_the_username_before_the_email(self) -> None:
self.db.rows_by_condition = {
"username = $1": _user_row("owner@example.com", "second@example.com"),
"lower(email) = lower($1)": _user_row("owner", "owner@example.com"),
}
found = await self.store.find_by_identifier("owner@example.com")
self.assertEqual(found.username, "owner@example.com")
self.assertEqual(len(self.db.fetched), 1)
del self.db.rows_by_condition["username = $1"]
found = await self.store.find_by_identifier("owner@example.com")
self.assertEqual(found.username, "owner")
class PasswordLengthTests(unittest.TestCase):
def test_hash_password_refuses_more_than_72_bytes(self) -> None:
with self.assertRaises(ValueError):
hash_password("a" * 73)
with self.assertRaises(ValueError):
hash_password("é" * 37) # 74 bytes
self.assertTrue(hash_password("a" * 72).startswith("bcrypt$"))
if __name__ == "__main__":
unittest.main()
+11 -8
View File
@@ -5,7 +5,7 @@
"license": "MIT",
"type": "module",
"files": [
"src",
"dist",
"README.md"
],
"sideEffects": [
@@ -15,6 +15,7 @@
"svelte": "^5.0.0"
},
"dependencies": {
"@gabriel20xx/design-tokens": "0.1.1",
"@lucide/svelte": "1.28.0"
},
"devDependencies": {
@@ -26,17 +27,19 @@
},
"scripts": {
"check": "svelte-check --tsconfig ./tsconfig.json",
"package": "svelte-package"
"lint": "eslint .",
"package": "svelte-package",
"test": "vitest run"
},
"svelte": "./src/index.ts",
"types": "./src/index.ts",
"svelte": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./src/index.ts",
"svelte": "./src/index.ts",
"import": "./src/index.ts"
"types": "./dist/index.d.ts",
"svelte": "./dist/index.js",
"import": "./dist/index.js"
},
"./styles.css": "./src/lib/styles.css",
"./styles.css": "./dist/styles.css",
"./package.json": "./package.json"
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
@import '../../../design-tokens/theme.css';
@import "@gabriel20xx/design-tokens/theme.css";
:where(.sc-root, .sc-root *) {
box-sizing: border-box;
+5 -1
View File
@@ -1 +1,5 @@
export default {};
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
export default {
preprocess: vitePreprocess()
};
@@ -0,0 +1,166 @@
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/svelte';
import { afterEach, describe, expect, it, vi } from 'vitest';
import AuthPage from '../src/lib/components/AuthPage.svelte';
afterEach(cleanup);
const input = (name: string): HTMLInputElement => {
const element = document.querySelector<HTMLInputElement>(`input[name="${name}"]`);
if (!element) throw new Error(`no input named ${name}`);
return element;
};
async function fill(name: string, value: string): Promise<void> {
await fireEvent.input(input(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('AuthPage login', () => {
it('shows the login form and passes the trimmed credentials to onLogin', async () => {
const onLogin = vi.fn().mockResolvedValue(undefined);
render(AuthPage, { props: { brand: 'Demo', onLogin } });
expect(screen.getByRole('heading', { name: 'Welcome back' })).toBeTruthy();
expect(document.querySelector('input[name="confirmPassword"]')).toBeNull();
await fill('identifier', 'alice@example.com');
await fill('password', 'correct horse');
await submit();
await waitFor(() => expect(onLogin).toHaveBeenCalledTimes(1));
expect(onLogin).toHaveBeenCalledWith({
identifier: 'alice@example.com',
password: 'correct horse',
totpToken: '',
});
});
it('shows the error from a failed login and lets the user retry', async () => {
const onLogin = vi
.fn()
.mockRejectedValueOnce(new Error('Invalid username or password.'))
.mockResolvedValue(undefined);
render(AuthPage, { props: { onLogin } });
await fill('identifier', 'alice');
await fill('password', 'wrong password');
await submit();
await waitFor(() => expect(screen.getByText('Invalid username or password.')).toBeTruthy());
await submit();
await waitFor(() => expect(onLogin).toHaveBeenCalledTimes(2));
await waitFor(() => expect(screen.queryByText('Invalid username or password.')).toBeNull());
});
it('asks for the authenticator code after a two-factor challenge and sends it on the next try', async () => {
const onLogin = vi
.fn()
.mockRejectedValueOnce(new Error('Two-factor authentication code required.'))
.mockResolvedValue(undefined);
render(AuthPage, { props: { onLogin } });
await fill('identifier', 'alice');
await fill('password', 'correct horse');
expect(document.querySelector('input[name="totpToken"]')).toBeNull();
await submit();
await waitFor(() => expect(input('totpToken')).toBeTruthy());
expect(screen.getByText('Enter the six-digit authenticator code to continue.')).toBeTruthy();
await submit(); // an empty code is not sent
expect(onLogin).toHaveBeenCalledTimes(1);
await fill('totpToken', ' 123456 ');
await submit();
await waitFor(() => expect(onLogin).toHaveBeenCalledTimes(2));
expect(onLogin).toHaveBeenLastCalledWith({ identifier: 'alice', password: 'correct horse', totpToken: '123456' });
});
it('does not offer the authenticator field when showTotp is off', async () => {
const onLogin = vi.fn().mockRejectedValue(new Error('Two-factor authentication code required.'));
render(AuthPage, { props: { onLogin, showTotp: false } });
await fill('identifier', 'alice');
await submit();
await waitFor(() => expect(screen.getByText('Two-factor authentication code required.')).toBeTruthy());
expect(document.querySelector('input[name="totpToken"]')).toBeNull();
});
it('reports a missing login handler instead of failing silently', async () => {
render(AuthPage);
await submit();
await waitFor(() => expect(screen.getByText('The application has not configured its login handler.')).toBeTruthy());
});
it('shows only the loading heading while loading', () => {
render(AuthPage, { props: { loading: true } });
expect(screen.getByRole('heading', { name: 'Loading...' })).toBeTruthy();
expect(document.querySelector('form')).toBeNull();
});
it('falls back to the login view when the status check failed, whatever setupRequired says', () => {
render(AuthPage, { props: { setupRequired: true, error: 'Could not reach the server.' } });
expect(screen.getByRole('heading', { name: 'Welcome back' })).toBeTruthy();
expect(screen.getByText('Could not reach the server.')).toBeTruthy();
});
});
describe('AuthPage setup', () => {
it('refuses mismatched passwords without calling onSetup', async () => {
const onSetup = vi.fn();
render(AuthPage, { props: { setupRequired: true, onSetup } });
expect(screen.getByRole('heading', { name: 'Create your account' })).toBeTruthy();
await fill('username', 'root');
await fill('email', 'root@example.com');
await fill('password', 'password one');
await fill('confirmPassword', 'password two');
await submit();
await waitFor(() => expect(screen.getByText('Passwords do not match.')).toBeTruthy());
expect(onSetup).not.toHaveBeenCalled();
});
it('passes the new account to onSetup when the passwords match', async () => {
const onSetup = vi.fn().mockResolvedValue(undefined);
render(AuthPage, { props: { setupRequired: true, onSetup } });
await fill('username', 'root');
await fill('email', 'root@example.com');
await fill('password', 'password one');
await fill('confirmPassword', 'password one');
await submit();
await waitFor(() =>
expect(onSetup).toHaveBeenCalledWith({ username: 'root', email: 'root@example.com', password: 'password one' }),
);
});
});
describe('AuthPage account reset', () => {
it('offers the reset link only when both handlers are given', () => {
render(AuthPage, { props: { onRequestReset: vi.fn() } });
expect(screen.queryByText('Reset admin account')).toBeNull();
cleanup();
render(AuthPage, { props: { onRequestReset: vi.fn(), onConfirmReset: vi.fn() } });
expect(screen.getByText('Reset admin account')).toBeTruthy();
});
it('requests a code, then confirms the trimmed code the user types', async () => {
const onRequestReset = vi.fn().mockResolvedValue(undefined);
const onConfirmReset = vi.fn().mockResolvedValue(undefined);
render(AuthPage, { props: { onRequestReset, onConfirmReset } });
await fireEvent.click(screen.getByText('Reset admin account'));
await waitFor(() => expect(onRequestReset).toHaveBeenCalledTimes(1));
expect(screen.getByText('A reset code has been printed to the server console.')).toBeTruthy();
await fireEvent.click(screen.getByText('Confirm reset'));
await waitFor(() => expect(screen.getByText('Enter the code printed in the server console.')).toBeTruthy());
expect(onConfirmReset).not.toHaveBeenCalled();
await fireEvent.input(screen.getByLabelText('Reset code'), { target: { value: ' ABCD1234 ' } });
await fireEvent.click(screen.getByText('Confirm reset'));
await waitFor(() => expect(onConfirmReset).toHaveBeenCalledWith('ABCD1234'));
});
it('shows the error when the reset request fails', async () => {
const onRequestReset = vi.fn().mockRejectedValue(new Error('AuthGuard is not reachable.'));
render(AuthPage, { props: { onRequestReset, onConfirmReset: vi.fn() } });
await fireEvent.click(screen.getByText('Reset admin account'));
await waitFor(() => expect(screen.getByText('AuthGuard is not reachable.')).toBeTruthy());
});
});
@@ -0,0 +1,38 @@
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/svelte';
import { afterEach, describe, expect, it, vi } from 'vitest';
import NotificationStack from '../src/lib/components/NotificationStack.svelte';
import { notifications, notify } from '../src/lib/notifications.svelte';
// The icon library compiles over a thousand components on import; the icons are not under test.
vi.mock('@lucide/svelte', () => {
const Icon = (): void => {};
return { CircleAlert: Icon, CircleCheck: Icon, Info: Icon, OctagonAlert: Icon, X: Icon };
});
afterEach(() => {
cleanup();
for (const entry of [...notifications.entries]) notifications.dismiss(entry.id);
});
describe('NotificationStack', () => {
it('renders each notification with its variant and message', async () => {
render(NotificationStack);
notify.success('Saved', 0);
notify.error('Failed', 0);
await waitFor(() => expect(screen.getByText('Saved')).toBeTruthy());
expect(screen.getByText('Failed')).toBeTruthy();
const variants = [...document.querySelectorAll('.sc-notification')].map((node) =>
node.getAttribute('data-variant'),
);
expect(variants).toEqual(['success', 'error']);
expect(screen.getByRole('status').getAttribute('aria-live')).toBe('polite');
});
it('dismisses a notification from its close button', async () => {
render(NotificationStack);
notify.info('Dismiss me', 0);
await waitFor(() => expect(screen.getByText('Dismiss me')).toBeTruthy());
await fireEvent.click(screen.getByLabelText('Dismiss notification'));
expect(notifications.entries).toHaveLength(0);
});
});
@@ -0,0 +1,59 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { notifications, notify } from '../src/lib/notifications.svelte';
function clear(): void {
for (const entry of [...notifications.entries]) notifications.dismiss(entry.id);
}
describe('notification store', () => {
beforeEach(() => {
vi.useFakeTimers();
clear();
});
afterEach(() => {
clear();
vi.useRealTimers();
});
it('adds an entry per variant with increasing ids', () => {
const ids = [notify.success('saved'), notify.error('failed'), notify.warning('careful'), notify.info('fyi')];
expect(new Set(ids).size).toBe(4);
expect([...ids].sort((a, b) => a - b)).toEqual(ids);
expect(notifications.entries.map((entry) => [entry.variant, entry.message])).toEqual([
['success', 'saved'],
['error', 'failed'],
['warning', 'careful'],
['info', 'fyi'],
]);
});
it('removes an entry once its duration has passed, and only that entry', () => {
notify.info('short', 1000);
notify.info('long', 5000);
vi.advanceTimersByTime(999);
expect(notifications.entries).toHaveLength(2);
vi.advanceTimersByTime(1);
expect(notifications.entries.map((entry) => entry.message)).toEqual(['long']);
vi.advanceTimersByTime(4000);
expect(notifications.entries).toHaveLength(0);
});
it('uses a five second default and keeps an entry with duration 0 until it is dismissed', () => {
const timed = notify.success('default duration');
const sticky = notify.error('sticky', 0);
expect(notifications.entries.find((entry) => entry.id === timed)?.duration).toBe(5000);
vi.advanceTimersByTime(60_000);
expect(notifications.entries.map((entry) => entry.id)).toEqual([sticky]);
notify.dismiss(sticky);
expect(notifications.entries).toHaveLength(0);
});
it('dismissing early cancels the timer, and dismissing an unknown id is harmless', () => {
const id = notify.info('dismissed early', 1000);
notifications.dismiss(id);
expect(vi.getTimerCount()).toBe(0);
expect(() => notifications.dismiss(9999)).not.toThrow();
expect(notifications.entries).toHaveLength(0);
});
});
@@ -0,0 +1,117 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import {
PRIMARY_COLOR_PALETTE,
applyPrimaryColor,
initPrimaryColor,
primaryColorByName,
setPrimaryColor,
setPrimaryColorUser,
storedPrimaryColor,
} from '../src/lib/primary-color.svelte';
const styleText = (): string => document.getElementById('sc-primary-color')?.textContent ?? '';
function reset(): void {
document.getElementById('sc-primary-color')?.remove();
document.documentElement.removeAttribute('data-primary-color-user');
localStorage.clear();
}
describe('primary color palette', () => {
it('has unique names and valid colors', () => {
const names = PRIMARY_COLOR_PALETTE.map((color) => color.name);
expect(new Set(names).size).toBe(names.length);
for (const color of PRIMARY_COLOR_PALETTE) {
for (const value of [color.dark, color.light, color.darkFg]) {
expect(value, `${color.name} ${value}`).toMatch(/^#[0-9a-f]{6}$/);
}
}
});
it('finds a color by name and nothing for an unknown name', () => {
expect(primaryColorByName('Vermilion')?.light).toBe('#db3e24');
expect(primaryColorByName('Not a color')).toBeUndefined();
});
});
describe('primary color', () => {
beforeEach(reset);
afterEach(reset);
it('writes the light and dark declarations into one stylesheet, and replaces them on a change', () => {
applyPrimaryColor('app', 'Vermilion');
const css = styleText();
expect(css).toContain('--color-primary: #db3e24 !important;');
expect(css).toContain("[data-theme='dark']");
expect(css).toContain('--color-primary: #f59080 !important;');
expect(css).toContain('--sc-primary-fg: #ffffff !important;');
expect(css).toContain('--sc-primary-fg: #2b110d !important;');
expect(css).toMatch(/--sc-primary-hover: #[0-9a-f]{6} !important;/);
applyPrimaryColor('app', 'Cyan');
expect(document.querySelectorAll('#sc-primary-color')).toHaveLength(1);
expect(styleText()).toContain('#249edb');
expect(styleText()).not.toContain('#db3e24');
});
it('makes the hover lighter on dark and darker on light', () => {
applyPrimaryColor('app', 'Clover');
const [light, dark] = styleText().split("[data-theme='dark']");
const hover = (css: string): number => {
const hex = /--sc-primary-hover: #([0-9a-f]{6})/.exec(css)?.[1] ?? '';
return [0, 2, 4].reduce((sum, start) => sum + parseInt(hex.slice(start, start + 2), 16), 0);
};
const base = (hexValue: string): number =>
[1, 3, 5].reduce((sum, start) => sum + parseInt(hexValue.slice(start, start + 2), 16), 0);
expect(hover(light)).toBeLessThan(base('#16a34a'));
expect(hover(dark)).toBeGreaterThan(base('#22c55e'));
});
it('removes the stylesheet for an unknown or empty color', () => {
applyPrimaryColor('app', 'Vermilion');
applyPrimaryColor('app', 'Not a color');
expect(document.getElementById('sc-primary-color')).toBeNull();
applyPrimaryColor('app', '');
expect(document.getElementById('sc-primary-color')).toBeNull();
});
it('stores the choice per project and user, and clears it', () => {
setPrimaryColorUser('Alice');
setPrimaryColor('My App', 'Violet');
expect(localStorage.getItem('primary-color:my%20app:alice')).toBe('Violet');
expect(storedPrimaryColor('my app')).toBe('Violet');
expect(styleText()).toContain('#6d24db');
setPrimaryColorUser('bob');
expect(storedPrimaryColor('my app')).toBe('');
setPrimaryColorUser('alice');
expect(storedPrimaryColor('my app')).toBe('Violet');
setPrimaryColor('my app', '');
expect(storedPrimaryColor('my app')).toBe('');
expect(localStorage.getItem('primary-color:my%20app:alice')).toBeNull();
expect(document.getElementById('sc-primary-color')).toBeNull();
});
it('ignores a stored name that is not in the palette', () => {
localStorage.setItem('primary-color:app:anonymous', 'Chartreuse-ish');
expect(storedPrimaryColor('app')).toBe('');
});
it('applies the stored color on init and re-applies it when the user changes', () => {
localStorage.setItem('primary-color:shop:carol', 'Rose');
initPrimaryColor('shop', 'Carol');
expect(styleText()).toContain('#db2474');
localStorage.setItem('primary-color:shop:dave', 'Lime');
setPrimaryColorUser('dave');
expect(styleText()).toContain('#72b814');
setPrimaryColorUser('someone-without-a-choice');
expect(document.getElementById('sc-primary-color')).toBeNull();
});
it('treats a blank user as anonymous', () => {
setPrimaryColor('app', 'Gold');
expect(localStorage.getItem('primary-color:app:anonymous')).toBe('Gold');
});
});
+19
View File
@@ -0,0 +1,19 @@
// jsdom has no Web Animations API, which Svelte's transitions call. This stand-in finishes at once,
// so an element that leaves with a transition is removed straight away.
if (typeof Element.prototype.animate !== 'function') {
Element.prototype.animate = function animate(): Animation {
const animation = {
currentTime: 0,
onfinish: null as (() => void) | null,
cancel() {},
finish() {
animation.onfinish?.();
},
pause() {},
play() {},
finished: Promise.resolve(),
};
queueMicrotask(() => animation.onfinish?.());
return animation as unknown as Animation;
};
}
+14
View File
@@ -0,0 +1,14 @@
import { svelte } from '@sveltejs/vite-plugin-svelte';
import { svelteTesting } from '@testing-library/svelte/vite';
import { defineConfig } from 'vitest/config';
// Component and store tests run in jsdom. They live in tests/, outside src/lib, so svelte-package
// never ships them.
export default defineConfig({
plugins: [svelte(), svelteTesting()],
test: {
environment: 'jsdom',
include: ['tests/**/*.test.ts'],
setupFiles: ['tests/setup.ts'],
},
});