"""Explicit, transactional demo account provisioning; never suitable for production.""" import argparse import os from sqlalchemy import delete from sqlmodel import select from werkzeug.security import generate_password_hash from core.auth.models import Role, User, UserRole from persistance.db import get_auth_engine, get_auth_session from webapi import parse_auth_lite_enabled from webapi.auth_bootstrap import ALLOWED_ROLES from webapi.auth_token import normalize_username, validate_auth_storage, validate_password # DEMO-ONLY credentials. These credentials are intentionally simple and public # for demonstrations. Do not enable the demo seed in production. DEMO_USERS = ( {"username": "admin", "password": "Admin1234", "roles": ("ADMIN",)}, {"username": "cacu", "password": "Cacu1234", "roles": ("CACU",)}, {"username": "cama", "password": "Cama1234", "roles": ("CAMA",)}, {"username": "tea", "password": "Tea12345", "roles": ("TEA",)}, ) def validate_demo_users(): """Validate the entire editable definition, including skipped accounts.""" validated = [] usernames = set() if not DEMO_USERS: raise ValueError("demo configuration must contain accounts") for entry in DEMO_USERS: if not isinstance(entry, dict) or set(entry) != {"username", "password", "roles"}: raise ValueError("invalid demo account definition") username = normalize_username(entry["username"]) password = validate_password(entry["password"], minimum=8) roles = entry["roles"] if (not isinstance(roles, (tuple, list)) or not roles or any(not isinstance(role, str) or role not in ALLOWED_ROLES for role in roles) or len(set(roles)) != len(roles)): raise ValueError("demo roles must be unique and from ADMIN/CACU/CAMA/TEA") if username in usernames: raise ValueError("duplicate normalized demo username") usernames.add(username) validated.append({"username": username, "password": password, "roles": tuple(roles)}) return validated def seed_demo_users(*, replace_all: bool = False): """Complete missing accounts, or replace all, in one transaction. The explicit CLI requires Auth enabled. The internal function is also usable with migrated temporary storage in tests; it never creates/migrates storage. """ accounts = validate_demo_users() validate_auth_storage() results = [] with get_auth_session() as session: with session.begin(): required = {role for account in accounts for role in account["roles"]} if not required <= set(session.exec(select(Role.code))): raise ValueError("required demo roles are missing; apply Auth migration first") existing = set(session.exec(select(User.username))) missing = accounts if replace_all else [a for a in accounts if a["username"] not in existing] # Hash every new password before any delete/insert. No plaintext enters DB. hashes = {a["username"]: generate_password_hash(a["password"], method="scrypt") for a in missing} if replace_all: session.exec(delete(User)) # FK ON DELETE CASCADE clears user_role. for account in accounts: username, roles = account["username"], account["roles"] if username not in hashes: results.append((username, roles, "skipped")) continue user = User(username=username, password_hash=hashes[username]) session.add(user) session.flush() for role in roles: session.add(UserRole(user_id=user.id, role_code=role)) results.append((username, roles, "created")) return results def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description="DEMO ONLY: provision public Auth-Lite accounts") modes = parser.add_mutually_exclusive_group(required=True) modes.add_argument("--ensure", action="store_true", help="create only missing usernames") modes.add_argument("--replace-all", action="store_true", help="delete EVERY Auth user; requires REPLACE") args = parser.parse_args(argv) try: if not parse_auth_lite_enabled(os.environ.get("AUTH_LITE_ENABLED")): print("Auth-Lite is disabled; demo seed skipped.") return 0 if args.replace_all: print("WARNING: this will delete every Auth-Lite user.") try: confirmation = input("Type REPLACE to continue: ") except EOFError: confirmation = "" if confirmation != "REPLACE": print("Auth-Lite demo replacement cancelled; no changes.") return 0 results = seed_demo_users(replace_all=args.replace_all) print("Auth-Lite demo users replaced." if args.replace_all else "Auth-Lite demo seed:") for username, roles, status in results: print(f"{username} [{','.join(roles)}] -> {status}") return 0 except Exception: # Editable configuration and DB exceptions may include sensitive values. print("Auth-Lite demo seed failed; transaction rolled back. Check configuration and migrated storage.") return 1 finally: if get_auth_engine.cache_info().currsize: get_auth_engine().dispose() get_auth_engine.cache_clear() if __name__ == "__main__": raise SystemExit(main())