ci: expand CI checks and make consumer sync opt-in
- Add Go, npm, Python, and Java validation to CI - Run Go tests against PostgreSQL - Record performance fixes in the report
This commit is contained in:
1 parent
199a5efaef
commit
22887fef03
100 files changed
+9740
-429
No files matched your search
@@ -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(
|
||||
|
||||
Reference in new issue
Block a user