feat(auth): implement TOTP setup and management
Lint / Lint (Node/Svelte) (push) Successful in 24s
Lint / Lint (Go) (push) Successful in 28s
Lint / Lint (Python) (push) Failing after 14s
Tests / Test (Node/Svelte) (push) Successful in 18s
Tests / Test (Go) (push) Successful in 25s
Tests / Test (Python) (push) Successful in 12s
Lint / Lint (Node/Svelte) (push) Successful in 24s
Lint / Lint (Go) (push) Successful in 28s
Lint / Lint (Python) (push) Failing after 14s
Tests / Test (Node/Svelte) (push) Successful in 18s
Tests / Test (Go) (push) Successful in 25s
Tests / Test (Python) (push) Successful in 12s
- Added TOTP support for two-factor authentication in the auth module. - Introduced new types and interfaces for TOTP setup and token actions in the web UI. - Created backend logic for generating and verifying TOTP secrets and tokens. - Implemented user management features including role assignments and user CRUD operations. - Enhanced UI components for managing users and TOTP settings. - Added styles for optional labels and authentication reset links. - Implemented reset code generation and validation for admin accounts.
This commit is contained in:
1 parent
2f57554154
commit
da97fd4fb1
30 files changed
+2145
-27
No files matched your search
@@ -5,6 +5,7 @@ Shared Python backend infrastructure for services using `asyncpg`:
|
||||
- validated `DATABASE_URL` and pool settings;
|
||||
- one async pool owner with ping and graceful shutdown;
|
||||
- bcrypt password 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.
|
||||
|
||||
HTTP framework adapters stay in each service. Install this package from the
|
||||
|
||||
@@ -1,18 +1,43 @@
|
||||
"""Shared PostgreSQL and authentication primitives for Python services."""
|
||||
|
||||
from .auth import AuthStore, AuthUser, hash_password, verify_password
|
||||
from .auth import (
|
||||
ROLE_ADMIN,
|
||||
ROLE_SUPERADMIN,
|
||||
ROLE_USER,
|
||||
RESET_CODE_TTL,
|
||||
AuthStore,
|
||||
AuthUser,
|
||||
ResetManager,
|
||||
can_assign_role,
|
||||
can_manage_users,
|
||||
hash_password,
|
||||
normalize_role,
|
||||
verify_password,
|
||||
)
|
||||
from .config import DatabaseConfig, database_url_from_env
|
||||
from .postgres import Database
|
||||
from .totp import generate_totp_secret, totp_provisioning_uri, verify_totp
|
||||
from .tokens import hash_token, new_session_token
|
||||
|
||||
__all__ = [
|
||||
"AuthStore",
|
||||
"AuthUser",
|
||||
"ROLE_ADMIN",
|
||||
"ROLE_SUPERADMIN",
|
||||
"ROLE_USER",
|
||||
"RESET_CODE_TTL",
|
||||
"ResetManager",
|
||||
"can_assign_role",
|
||||
"can_manage_users",
|
||||
"Database",
|
||||
"DatabaseConfig",
|
||||
"database_url_from_env",
|
||||
"generate_totp_secret",
|
||||
"hash_password",
|
||||
"hash_token",
|
||||
"new_session_token",
|
||||
"normalize_role",
|
||||
"totp_provisioning_uri",
|
||||
"verify_password",
|
||||
"verify_totp",
|
||||
]
|
||||
@@ -2,8 +2,10 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import secrets
|
||||
import threading
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import asyncpg
|
||||
import bcrypt
|
||||
@@ -16,12 +18,21 @@ CREATE TABLE IF NOT EXISTS auth_users (
|
||||
username TEXT NOT NULL UNIQUE,
|
||||
email TEXT NOT NULL DEFAULT '',
|
||||
password_hash TEXT NOT NULL,
|
||||
role TEXT NOT NULL DEFAULT 'user',
|
||||
totp_secret TEXT NOT NULL DEFAULT '',
|
||||
totp_enabled BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS email TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS role TEXT NOT NULL DEFAULT 'user';
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_secret TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_enabled BOOLEAN NOT NULL DEFAULT FALSE;
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS 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 (
|
||||
@@ -35,6 +46,61 @@ 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);
|
||||
"""
|
||||
|
||||
RESET_CODE_TTL = timedelta(minutes=5)
|
||||
|
||||
ROLE_SUPERADMIN = "superadmin"
|
||||
ROLE_ADMIN = "admin"
|
||||
ROLE_USER = "user"
|
||||
|
||||
|
||||
def normalize_role(value: str | None) -> str:
|
||||
normalized = str(value or "").strip().lower()
|
||||
return normalized if normalized in {ROLE_SUPERADMIN, ROLE_ADMIN} else ROLE_USER
|
||||
|
||||
|
||||
def can_manage_users(role: str | None) -> bool:
|
||||
return normalize_role(role) in {ROLE_SUPERADMIN, ROLE_ADMIN}
|
||||
|
||||
|
||||
def can_assign_role(actor_role: str | None, target_role: str | None) -> bool:
|
||||
return normalize_role(actor_role) == ROLE_SUPERADMIN and normalize_role(target_role) != ROLE_SUPERADMIN
|
||||
|
||||
|
||||
class ResetManager:
|
||||
"""Creates and validates the short-lived, one-time admin reset code."""
|
||||
|
||||
def __init__(self, *, ttl: timedelta = RESET_CODE_TTL, log=print) -> None:
|
||||
self._ttl = ttl
|
||||
self._log = log
|
||||
self._code: str | None = None
|
||||
self._expires_at: datetime | None = None
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def request(self) -> str:
|
||||
code = secrets.token_hex(4).upper()
|
||||
with self._lock:
|
||||
self._code = code
|
||||
self._expires_at = datetime.now().astimezone() + self._ttl
|
||||
self._log(
|
||||
f"\n{'=' * 50}\nADMIN RESET CODE: {code}\n"
|
||||
f"Expires in 5 minutes. Enter it on the login page.\n{'=' * 50}\n"
|
||||
)
|
||||
return code
|
||||
|
||||
def confirm(self, candidate: str) -> bool:
|
||||
with self._lock:
|
||||
if self._code is None or self._expires_at is None:
|
||||
return False
|
||||
if datetime.now().astimezone() > self._expires_at:
|
||||
self._code = None
|
||||
self._expires_at = None
|
||||
return False
|
||||
valid = secrets.compare_digest(self._code, str(candidate or "").strip().upper())
|
||||
if valid:
|
||||
self._code = None
|
||||
self._expires_at = None
|
||||
return valid
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class AuthUser:
|
||||
@@ -42,6 +108,7 @@ class AuthUser:
|
||||
username: str
|
||||
email: str
|
||||
password_hash: str
|
||||
role: str = ROLE_USER
|
||||
created_at: datetime | None = None
|
||||
updated_at: datetime | None = None
|
||||
|
||||
@@ -74,6 +141,8 @@ class AuthStore:
|
||||
await self.database.execute(
|
||||
"CREATE UNIQUE INDEX IF NOT EXISTS auth_users_singleton_idx ON auth_users ((true))"
|
||||
)
|
||||
else:
|
||||
await self.database.execute("DROP INDEX IF EXISTS auth_users_singleton_idx")
|
||||
|
||||
async def count_users(self) -> int:
|
||||
return int(await self.database.fetchval("SELECT count(*) FROM auth_users"))
|
||||
@@ -82,9 +151,11 @@ class AuthStore:
|
||||
try:
|
||||
row = await self.database.fetchrow(
|
||||
"""
|
||||
INSERT INTO auth_users (username, email, password_hash, updated_at)
|
||||
VALUES ($1, $2, $3, now())
|
||||
RETURNING id, username, email, password_hash, created_at, updated_at
|
||||
INSERT INTO auth_users (username, email, password_hash, role, updated_at)
|
||||
VALUES ($1, $2, $3,
|
||||
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
|
||||
""",
|
||||
username,
|
||||
email,
|
||||
@@ -98,7 +169,7 @@ class AuthStore:
|
||||
async def find_by_identifier(self, identifier: str) -> AuthUser | None:
|
||||
row = await self.database.fetchrow(
|
||||
"""
|
||||
SELECT id, username, email, password_hash, created_at, updated_at
|
||||
SELECT id, username, email, password_hash, role, created_at, updated_at
|
||||
FROM auth_users
|
||||
WHERE username = $1 OR lower(email) = lower($1)
|
||||
""",
|
||||
@@ -132,7 +203,7 @@ class AuthStore:
|
||||
async def find_session_user(self, token_hash: str) -> AuthUser | None:
|
||||
row = await self.database.fetchrow(
|
||||
"""
|
||||
SELECT u.id, u.username, u.email, u.password_hash, u.created_at, u.updated_at
|
||||
SELECT u.id, u.username, u.email, u.password_hash, u.role, u.created_at, u.updated_at
|
||||
FROM auth_sessions s
|
||||
JOIN auth_users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = $1 AND s.expires_at > now()
|
||||
@@ -147,5 +218,89 @@ class AuthStore:
|
||||
async def delete_sessions_for_user(self, user_id: int) -> None:
|
||||
await self.database.execute("DELETE FROM auth_sessions WHERE user_id = $1", user_id)
|
||||
|
||||
async def list_users(self) -> list[AuthUser]:
|
||||
rows = await self.database.fetch(
|
||||
"SELECT id, username, email, role, password_hash, created_at, updated_at "
|
||||
"FROM auth_users ORDER BY created_at, id"
|
||||
)
|
||||
return [AuthUser(**dict(row)) for row in rows]
|
||||
|
||||
async def create_managed_user(
|
||||
self, username: str, email: str, password_hash: str, role: str = ROLE_USER
|
||||
) -> AuthUser:
|
||||
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
|
||||
""",
|
||||
username,
|
||||
email,
|
||||
password_hash,
|
||||
normalize_role(role),
|
||||
)
|
||||
except asyncpg.UniqueViolationError as exc:
|
||||
raise UserExistsError from exc
|
||||
assert row is not None
|
||||
return AuthUser(**dict(row))
|
||||
|
||||
async def update_user(
|
||||
self,
|
||||
user_id: int,
|
||||
*,
|
||||
username: str | None = None,
|
||||
email: str | None = None,
|
||||
password_hash: str | None = None,
|
||||
role: str | None = None,
|
||||
) -> None:
|
||||
fields: list[str] = []
|
||||
values: list[object] = []
|
||||
for column, value in (("username", username), ("email", email), ("password_hash", password_hash), ("role", normalize_role(role) if role is not None else None)):
|
||||
if value is not None:
|
||||
fields.append(f"{column} = ${len(values) + 1}")
|
||||
values.append(value)
|
||||
if not fields:
|
||||
return
|
||||
values.append(user_id)
|
||||
await self.database.execute(
|
||||
f"UPDATE auth_users SET {', '.join(fields)}, updated_at = now() WHERE id = ${len(values)}",
|
||||
*values,
|
||||
)
|
||||
|
||||
async def delete_user(self, user_id: int) -> None:
|
||||
await self.database.execute("DELETE FROM auth_users WHERE id = $1", user_id)
|
||||
|
||||
async def delete_all_users(self) -> None:
|
||||
await self.database.execute("DELETE FROM auth_users")
|
||||
|
||||
async def get_totp_state(self, user_id: int) -> dict[str, object]:
|
||||
row = await self.database.fetchrow(
|
||||
"SELECT COALESCE(totp_secret, '') AS secret, COALESCE(totp_enabled, false) AS enabled "
|
||||
"FROM auth_users WHERE id = $1",
|
||||
user_id,
|
||||
)
|
||||
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(
|
||||
"UPDATE auth_users SET totp_secret = $1, totp_enabled = false, updated_at = now() WHERE id = $2",
|
||||
secret,
|
||||
user_id,
|
||||
)
|
||||
|
||||
async def enable_totp(self, user_id: int) -> None:
|
||||
await self.database.execute(
|
||||
"UPDATE auth_users SET totp_enabled = true, updated_at = now() "
|
||||
"WHERE id = $1 AND totp_secret <> ''",
|
||||
user_id,
|
||||
)
|
||||
|
||||
async def disable_totp(self, user_id: int) -> None:
|
||||
await self.database.execute(
|
||||
"UPDATE auth_users SET totp_secret = '', totp_enabled = false, updated_at = now() WHERE id = $1",
|
||||
user_id,
|
||||
)
|
||||
|
||||
async def prune_expired_sessions(self) -> None:
|
||||
await self.database.execute("DELETE FROM auth_sessions WHERE expires_at < now()")
|
||||
@@ -0,0 +1,75 @@
|
||||
"""RFC 6238 TOTP helpers shared by Python auth services."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import binascii
|
||||
import hashlib
|
||||
import hmac
|
||||
import secrets
|
||||
import struct
|
||||
import time
|
||||
from urllib.parse import quote, urlencode
|
||||
|
||||
TOTP_PERIOD_SECONDS = 30
|
||||
TOTP_DIGITS = 6
|
||||
TOTP_WINDOW = 1
|
||||
|
||||
|
||||
def generate_totp_secret() -> str:
|
||||
return base64.b32encode(secrets.token_bytes(20)).decode("ascii").rstrip("=")
|
||||
|
||||
|
||||
def totp_provisioning_uri(issuer: str, account: str, secret: str) -> str:
|
||||
normalized_issuer = str(issuer or "").strip()
|
||||
normalized_account = str(account or "").strip()
|
||||
label = f"{normalized_issuer}:{normalized_account}" if normalized_issuer else normalized_account
|
||||
params = {
|
||||
"secret": _normalize_secret(secret),
|
||||
"algorithm": "SHA1",
|
||||
"digits": str(TOTP_DIGITS),
|
||||
"period": str(TOTP_PERIOD_SECONDS),
|
||||
}
|
||||
if normalized_issuer:
|
||||
params["issuer"] = normalized_issuer
|
||||
return f"otpauth://totp/{quote(label, safe='')}?{urlencode(params)}"
|
||||
|
||||
|
||||
def verify_totp(secret: str, token: str, now: float | None = None) -> bool:
|
||||
normalized_secret = _normalize_secret(secret)
|
||||
normalized_token = _normalize_token(token)
|
||||
if not normalized_secret or len(normalized_token) != TOTP_DIGITS:
|
||||
return False
|
||||
try:
|
||||
key = base64.b32decode(normalized_secret + "=" * ((8 - len(normalized_secret) % 8) % 8))
|
||||
except (ValueError, binascii.Error):
|
||||
return False
|
||||
if not key:
|
||||
return False
|
||||
|
||||
period = int((time.time() if now is None else now) // TOTP_PERIOD_SECONDS)
|
||||
for offset in range(-TOTP_WINDOW, TOTP_WINDOW + 1):
|
||||
counter = period + offset
|
||||
if counter < 0:
|
||||
continue
|
||||
digest = hmac.new(key, struct.pack(">Q", counter), hashlib.sha1).digest()
|
||||
index = digest[-1] & 0x0F
|
||||
value = (
|
||||
((digest[index] & 0x7F) << 24)
|
||||
| (digest[index + 1] << 16)
|
||||
| (digest[index + 2] << 8)
|
||||
| digest[index + 3]
|
||||
)
|
||||
candidate = f"{value % 1_000_000:06d}"
|
||||
if hmac.compare_digest(candidate, normalized_token):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _normalize_secret(value: str) -> str:
|
||||
return str(value or "").strip().upper().replace(" ", "").rstrip("=")
|
||||
|
||||
|
||||
def _normalize_token(value: str) -> str:
|
||||
token = str(value or "").strip()
|
||||
return token if len(token) == TOTP_DIGITS and token.isdigit() else ""
|
||||
@@ -1,8 +1,11 @@
|
||||
import os
|
||||
import unittest
|
||||
|
||||
from shared_backend.auth import hash_password, verify_password
|
||||
from datetime import timedelta
|
||||
|
||||
from shared_backend.auth import ResetManager, hash_password, verify_password
|
||||
from shared_backend.config import DatabaseConfig
|
||||
from shared_backend.totp import totp_provisioning_uri, verify_totp
|
||||
from shared_backend.tokens import hash_token, new_session_token
|
||||
|
||||
|
||||
@@ -17,6 +20,38 @@ class SharedBackendTests(unittest.TestCase):
|
||||
self.assertNotEqual(token, token_hash)
|
||||
self.assertEqual(hash_token(token), token_hash)
|
||||
|
||||
def test_reset_manager_round_trip_and_one_time_use(self):
|
||||
messages = []
|
||||
manager = ResetManager(log=messages.append)
|
||||
code = manager.request()
|
||||
|
||||
self.assertEqual(len(code), 8)
|
||||
self.assertIn(f"ADMIN RESET CODE: {code}", messages[0])
|
||||
self.assertTrue(manager.confirm(f" {code.lower()} "))
|
||||
self.assertFalse(manager.confirm(code))
|
||||
|
||||
def test_reset_manager_expires(self):
|
||||
manager = ResetManager(ttl=timedelta(seconds=-1), log=lambda _message: None)
|
||||
code = manager.request()
|
||||
self.assertFalse(manager.confirm(code))
|
||||
|
||||
def test_totp_rfc6238_sha1_vectors(self):
|
||||
secret = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"
|
||||
vectors = [
|
||||
(59, "287082"),
|
||||
(1111111109, "081804"),
|
||||
(1111111111, "050471"),
|
||||
(1234567890, "005924"),
|
||||
(2000000000, "279037"),
|
||||
]
|
||||
for timestamp, code in vectors:
|
||||
self.assertTrue(verify_totp(secret, code, timestamp))
|
||||
self.assertTrue(
|
||||
totp_provisioning_uri("Example App", "admin@example.com", secret).startswith(
|
||||
"otpauth://totp/"
|
||||
)
|
||||
)
|
||||
|
||||
def test_database_config_from_environment(self):
|
||||
config = DatabaseConfig.from_env(
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user