"""Auth-Lite token, input and explicit storage validation helpers.""" from pathlib import Path import re from itsdangerous import BadData, URLSafeTimedSerializer from sqlalchemy import inspect from sqlalchemy.engine import make_url TOKEN_MAX_AGE = 28800 TOKEN_SALT = "auth-lite-session-v1" def normalize_username(value: str) -> str: if not isinstance(value, str): raise ValueError("username must be a string") value = value.strip().lower() if not re.fullmatch(r"[a-z0-9._-]{3,64}", value): raise ValueError("username must contain 3-64 characters from [a-z0-9._-]") return value def validate_password(value: str, minimum: int = 1) -> str: if not isinstance(value, str) or not minimum <= len(value) <= 128: raise ValueError(f"password must contain {minimum}-128 characters") return value def validate_auth_storage() -> None: from persistance.db import get_auth_engine from persistance.settings import settings try: url = make_url(settings.auth_database_url) if url.get_backend_name() != "sqlite": raise ValueError("SQLite required") if not url.database or url.database == ":memory:" or not Path(url.database).is_file(): raise ValueError("existing SQLite required") engine = get_auth_engine() if not {"user", "role", "user_role", "alembic_version"} <= set(inspect(engine).get_table_names()): raise ValueError("migration required") # Validate the columns needed by login/bootstrap, without creating schema. from sqlalchemy import text with engine.connect() as connection: connection.execute(text("SELECT id, username, password_hash, activo FROM user LIMIT 0")) connection.execute(text("SELECT code FROM role LIMIT 0")) connection.execute(text("SELECT user_id, role_code FROM user_role LIMIT 0")) except Exception: if get_auth_engine.cache_info().currsize: get_auth_engine().dispose() get_auth_engine.cache_clear() raise ValueError("Auth-Lite storage must be an accessible migrated SQLite database") from None def serializer(secret: str) -> URLSafeTimedSerializer: return URLSafeTimedSerializer(secret, salt=TOKEN_SALT) def issue_token(secret: str, user_id: int) -> str: return serializer(secret).dumps({"user_id": user_id, "v": 1}) def read_token(secret: str, token: str) -> int | None: try: payload = serializer(secret).loads(token, max_age=TOKEN_MAX_AGE) except BadData: return None if not isinstance(payload, dict) or set(payload) != {"user_id", "v"}: return None if type(payload["v"]) is not int or payload["v"] != 1: return None user_id = payload["user_id"] return user_id if type(user_id) is int and 0 < user_id <= 9223372036854775807 else None def user_dto(user, roles: list[str]) -> dict: return {"id": user.id, "username": user.username, "roles": sorted(roles)}