"""MariaDB user accounts, registration codes, and VM ownership. The panel's public registration code is only six digits, so its stored fingerprint is keyed with the database master key. A stolen database alone cannot check guesses offline. Every SQL value is passed as a parameter. """ from __future__ import annotations import hashlib import hmac import re import secrets import time import uuid from typing import Any from .auth import hash_password from .database import DatabaseError, DatabaseStore, pymysql from .panel_state import _USERNAME _DOMAIN_LABEL = re.compile(r"[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\Z") _LOCAL_PART = re.compile(r"[A-Za-z0-9_+%-](?:[A-Za-z0-9._+%-]{0,62}[A-Za-z0-9_+%-])?\Z") _CODE = re.compile(r"[0-9]{6}\Z") _HOST_SCOPE = re.compile(r"[0-9a-f]{64}\Z") _MAX_CODE_ATTEMPTS = 5 class UserError(Exception): def __init__(self, message: str, status: int = 400) -> None: super().__init__(message) self.status = status def normalize_email(email: str) -> str: """Reject addresses that cannot be safely used in SMTP headers.""" if not isinstance(email, str) or not 3 <= len(email) <= 254 or email != email.strip(): raise UserError("邮箱地址格式无效") try: email.encode("ascii") except UnicodeEncodeError as exc: raise UserError("邮箱地址格式无效") from exc if email.count("@") != 1: raise UserError("邮箱地址格式无效") local, domain = email.split("@") if (len(local) > 64 or len(domain) > 253 or ".." in email or not _LOCAL_PART.fullmatch(local) or not all(_DOMAIN_LABEL.fullmatch(label) for label in domain.split(".")) or "." not in domain): raise UserError("邮箱地址格式无效") return email.lower() def _validate_username(username: str) -> str: if not isinstance(username, str) or not _USERNAME.fullmatch(username): raise UserError("用户名应为 3 至 32 位字母、数字、点、下划线或连字符") return username def _validate_password(password: str) -> str: if not isinstance(password, str) or not 12 <= len(password) <= 1024: raise UserError("密码长度须在 12 至 1024 位之间") return password def _validate_clock(now: int | None) -> int: value = int(time.time()) if now is None else now if isinstance(value, bool) or not isinstance(value, int) or value < 0: raise ValueError("Invalid registration time") return value def _vm_identity(host_scope: str, vm_uuid: str) -> tuple[str, str]: if not isinstance(host_scope, str) or not _HOST_SCOPE.fullmatch(host_scope): raise ValueError("Invalid host scope") try: canonical_uuid = str(uuid.UUID(vm_uuid)) except (ValueError, TypeError, AttributeError) as exc: raise ValueError("Invalid VM UUID") from exc return host_scope, canonical_uuid def _user_row(row: dict[str, Any] | None) -> dict[str, Any] | None: if row is None: return None return { "id": int(row["id"]), "username": row["username"], "email": row["email"], "password_hash": row["password_hash"], "admin": bool(row["admin"]), "approved": bool(row["approved"]), "email_verified": bool(row["email_verified"]), "created_at": int(row["created_at"]), } class DatabaseUserStore: """Users are plain SQL rows; password hashes and code digests are one-way.""" def __init__(self, store: DatabaseStore, code_key: bytes) -> None: if not isinstance(code_key, bytes) or len(code_key) != 32: raise ValueError("Registration code key must be 32 bytes") self._store = store self._code_key = code_key def _connect(self): return self._store._connect() def _code_digest(self, email: str, code: str) -> str: message = b"virsh-panel-registration-v1\x00" + email.encode("ascii") + b"\x00" + code.encode("ascii") return hmac.new(self._code_key, message, hashlib.sha256).hexdigest() @staticmethod def generate_code() -> str: return f"{secrets.randbelow(1_000_000):06d}" def has_users(self) -> bool: connection = self._connect() try: with connection.cursor() as cursor: cursor.execute("SELECT id FROM users LIMIT 1") return cursor.fetchone() is not None except pymysql.MySQLError as exc: raise DatabaseError("无法读取用户数据") from exc finally: connection.close() def get_by_username(self, username: str) -> dict[str, Any] | None: if not isinstance(username, str) or not _USERNAME.fullmatch(username): return None connection = self._connect() try: with connection.cursor() as cursor: cursor.execute( "SELECT id, username, email, password_hash, admin, approved, " "email_verified, created_at " "FROM users WHERE username=%s", (username,), ) return _user_row(cursor.fetchone()) except pymysql.MySQLError as exc: raise DatabaseError("无法读取用户数据") from exc finally: connection.close() def get_by_email(self, email: str) -> dict[str, Any] | None: try: normalized_email = normalize_email(email) except UserError: return None connection = self._connect() try: with connection.cursor() as cursor: cursor.execute( "SELECT id, username, email, password_hash, admin, approved, " "email_verified, created_at " "FROM users WHERE email=%s", (normalized_email,), ) return _user_row(cursor.fetchone()) except pymysql.MySQLError as exc: raise DatabaseError("无法读取用户数据") from exc finally: connection.close() def get_by_id(self, user_id: int) -> dict[str, Any] | None: if isinstance(user_id, bool) or not isinstance(user_id, int) or user_id < 1: return None connection = self._connect() try: with connection.cursor() as cursor: cursor.execute( "SELECT id, username, email, password_hash, admin, approved, " "email_verified, created_at " "FROM users WHERE id=%s", (user_id,), ) return _user_row(cursor.fetchone()) except pymysql.MySQLError as exc: raise DatabaseError("无法读取用户数据") from exc finally: connection.close() def create_initial_user(self, username: str, password: str, email: str | None = None, *, now: int | None = None) -> dict[str, Any]: """Insert the first account as a regular user, never as admin. The setup-token file lock held by DatabasePanelState serializes this check/insert across web workers on the same panel server. """ username = _validate_username(username) password_hash = hash_password(_validate_password(password)) email = normalize_email(email) if email is not None else None timestamp = _validate_clock(now) connection = self._connect() try: with connection.cursor() as cursor: cursor.execute("SELECT id FROM users LIMIT 1 FOR UPDATE") if cursor.fetchone() is not None: raise UserError("初始用户已创建", 409) cursor.execute( "INSERT INTO users (username, email, password_hash, admin, " "approved, email_verified, created_at) VALUES (%s, %s, %s, 0, 1, 1, %s)", (username, email, password_hash, timestamp), ) user_id = cursor.lastrowid connection.commit() return { "id": user_id, "username": username, "email": email, "password_hash": password_hash, "admin": False, "approved": True, "email_verified": True, "created_at": timestamp, } except UserError: connection.rollback() raise except pymysql.err.IntegrityError as exc: connection.rollback() if exc.args and exc.args[0] == 1062: raise UserError("用户名或邮箱已存在", 409) from exc raise DatabaseError("无法创建初始用户") from exc except pymysql.MySQLError as exc: connection.rollback() raise DatabaseError("无法创建初始用户") from exc finally: connection.close() def issue_registration_code(self, email: str, code: str, *, now: int | None = None, ttl_seconds: int = 600, cooldown_seconds: int = 60) -> bool: """Store a code and enforce resend cooldown; False means email already used. The caller should return the same public response for existing and new email addresses, and send email only when this method returns True. """ email = normalize_email(email) if not isinstance(code, str) or not _CODE.fullmatch(code): raise ValueError("Invalid registration code") if (isinstance(ttl_seconds, bool) or not isinstance(ttl_seconds, int) or not 60 <= ttl_seconds <= 3600 or isinstance(cooldown_seconds, bool) or not isinstance(cooldown_seconds, int) or not 1 <= cooldown_seconds <= ttl_seconds): raise ValueError("Invalid code lifetime or cooldown") timestamp = _validate_clock(now) digest = self._code_digest(email, code) connection = self._connect() try: with connection.cursor() as cursor: cursor.execute("SELECT id FROM users WHERE email=%s", (email,)) if cursor.fetchone() is not None: connection.rollback() return False cursor.execute( "SELECT sent_at FROM registration_codes WHERE email=%s FOR UPDATE", (email,), ) existing = cursor.fetchone() if existing is not None and timestamp - int(existing["sent_at"]) < cooldown_seconds: raise UserError("验证码发送过于频繁,请稍后重试", 429) if existing is None: cursor.execute( "INSERT INTO registration_codes " "(email, code_hash, sent_at, expires_at, failed_attempts) " "VALUES (%s, %s, %s, %s, 0)", (email, digest, timestamp, timestamp + ttl_seconds), ) else: cursor.execute( "UPDATE registration_codes SET code_hash=%s, sent_at=%s, " "expires_at=%s, failed_attempts=0 WHERE email=%s", (digest, timestamp, timestamp + ttl_seconds, email), ) connection.commit() return True except UserError: connection.rollback() raise except pymysql.err.IntegrityError as exc: connection.rollback() if exc.args and exc.args[0] == 1062: raise UserError("验证码发送过于频繁,请稍后重试", 429) from exc raise DatabaseError("无法保存注册验证码") from exc except pymysql.MySQLError as exc: connection.rollback() raise DatabaseError("无法保存注册验证码") from exc finally: connection.close() def revoke_registration_code(self, email: str, code: str) -> bool: """Remove only the still-current challenge after SMTP delivery fails.""" email = normalize_email(email) if not isinstance(code, str) or not _CODE.fullmatch(code): raise ValueError("Invalid registration code") digest = self._code_digest(email, code) connection = self._connect() try: with connection.cursor() as cursor: cursor.execute( "SELECT code_hash FROM registration_codes WHERE email=%s FOR UPDATE", (email,), ) row = cursor.fetchone() if row is None or not hmac.compare_digest(row["code_hash"], digest): connection.rollback() return False cursor.execute( "DELETE FROM registration_codes WHERE email=%s AND code_hash=%s", (email, digest), ) connection.commit() return True except pymysql.MySQLError as exc: connection.rollback() raise DatabaseError("无法撤销注册验证码") from exc finally: connection.close() def register_with_code(self, username: str, email: str, password: str, code: str, *, now: int | None = None) -> dict[str, Any]: username = _validate_username(username) email = normalize_email(email) password = _validate_password(password) if not isinstance(code, str) or not _CODE.fullmatch(code): raise UserError("验证码格式无效") timestamp = _validate_clock(now) connection = self._connect() try: with connection.cursor() as cursor: cursor.execute( "SELECT code_hash, expires_at, failed_attempts " "FROM registration_codes WHERE email=%s FOR UPDATE", (email,), ) challenge = cursor.fetchone() if challenge is None: raise UserError("验证码无效或已过期") if timestamp >= int(challenge["expires_at"]): cursor.execute("DELETE FROM registration_codes WHERE email=%s", (email,)) connection.commit() raise UserError("验证码无效或已过期") digest = self._code_digest(email, code) if not hmac.compare_digest(digest, challenge["code_hash"]): attempts = int(challenge["failed_attempts"]) + 1 if attempts >= _MAX_CODE_ATTEMPTS: cursor.execute("DELETE FROM registration_codes WHERE email=%s", (email,)) else: cursor.execute( "UPDATE registration_codes SET failed_attempts=%s WHERE email=%s", (attempts, email), ) connection.commit() raise UserError("验证码无效或已过期") password_hash = hash_password(password) cursor.execute( "INSERT INTO users (username, email, password_hash, admin, " "approved, email_verified, created_at) VALUES (%s, %s, %s, 0, 0, 1, %s)", (username, email, password_hash, timestamp), ) user_id = cursor.lastrowid cursor.execute("DELETE FROM registration_codes WHERE email=%s", (email,)) connection.commit() return { "id": user_id, "username": username, "email": email, "password_hash": password_hash, "admin": False, "approved": False, "email_verified": True, "created_at": timestamp, } except UserError: connection.rollback() raise except pymysql.err.IntegrityError as exc: connection.rollback() if exc.args and exc.args[0] == 1062: raise UserError("用户名或邮箱已存在", 409) from exc raise DatabaseError("无法创建用户") from exc except pymysql.MySQLError as exc: connection.rollback() raise DatabaseError("无法创建用户") from exc finally: connection.close() def list_pending_users(self) -> list[dict[str, Any]]: """Return registered accounts awaiting operator approval, no hashes.""" connection = self._connect() try: with connection.cursor() as cursor: cursor.execute( "SELECT id, username, email, admin, approved, email_verified, " "created_at FROM users WHERE approved=0 ORDER BY created_at ASC, id ASC" ) rows = cursor.fetchall() return [{ "id": int(row["id"]), "username": row["username"], "email": row["email"], "admin": bool(row["admin"]), "approved": bool(row["approved"]), "email_verified": bool(row["email_verified"]), "created_at": int(row["created_at"]), } for row in rows] except pymysql.MySQLError as exc: raise DatabaseError("无法读取待审核用户") from exc finally: connection.close() def approve_user(self, user_id: int) -> dict[str, Any] | None: """Approve an account; only the admin-authorized HTTP route may call this.""" if isinstance(user_id, bool) or not isinstance(user_id, int) or user_id < 1: raise ValueError("Invalid user ID") connection = self._connect() try: with connection.cursor() as cursor: cursor.execute("UPDATE users SET approved=1 WHERE id=%s", (user_id,)) connection.commit() except pymysql.MySQLError as exc: connection.rollback() raise DatabaseError("无法审核用户") from exc finally: connection.close() return self.get_by_id(user_id) def assign_vm(self, host_scope: str, vm_uuid: str, user_id: int, *, now: int | None = None) -> None: host_scope, vm_uuid = _vm_identity(host_scope, vm_uuid) if isinstance(user_id, bool) or not isinstance(user_id, int) or user_id < 1: raise ValueError("Invalid user ID") timestamp = _validate_clock(now) connection = self._connect() try: with connection.cursor() as cursor: cursor.execute( "INSERT INTO vm_ownership (host_scope, vm_uuid, user_id, created_at) " "VALUES (%s, %s, %s, %s)", (host_scope, vm_uuid, user_id, timestamp), ) connection.commit() except pymysql.err.IntegrityError as exc: connection.rollback() if exc.args and exc.args[0] == 1062: if self.owner_of_vm(host_scope, vm_uuid) == user_id: return raise UserError("此虚拟机已归属于其他用户", 409) from exc raise DatabaseError("无法记录虚拟机归属") from exc except pymysql.MySQLError as exc: connection.rollback() raise DatabaseError("无法记录虚拟机归属") from exc finally: connection.close() def owner_of_vm(self, host_scope: str, vm_uuid: str) -> int | None: host_scope, vm_uuid = _vm_identity(host_scope, vm_uuid) connection = self._connect() try: with connection.cursor() as cursor: cursor.execute( "SELECT user_id FROM vm_ownership WHERE host_scope=%s AND vm_uuid=%s", (host_scope, vm_uuid), ) row = cursor.fetchone() return None if row is None else int(row["user_id"]) except pymysql.MySQLError as exc: raise DatabaseError("无法读取虚拟机归属") from exc finally: connection.close() def owns_vm(self, host_scope: str, vm_uuid: str, user_id: int) -> bool: if isinstance(user_id, bool) or not isinstance(user_id, int) or user_id < 1: return False return self.owner_of_vm(host_scope, vm_uuid) == user_id def list_owned_vm_ids(self, host_scope: str, user_id: int) -> set[str]: if not isinstance(host_scope, str) or not _HOST_SCOPE.fullmatch(host_scope): raise ValueError("Invalid host scope") if isinstance(user_id, bool) or not isinstance(user_id, int) or user_id < 1: raise ValueError("Invalid user ID") connection = self._connect() try: with connection.cursor() as cursor: cursor.execute( "SELECT vm_uuid FROM vm_ownership WHERE host_scope=%s AND user_id=%s", (host_scope, user_id), ) return {row["vm_uuid"] for row in cursor.fetchall()} except pymysql.MySQLError as exc: raise DatabaseError("无法读取虚拟机归属") from exc finally: connection.close() def delete_vm_owner(self, host_scope: str, vm_uuid: str) -> None: host_scope, vm_uuid = _vm_identity(host_scope, vm_uuid) connection = self._connect() try: with connection.cursor() as cursor: cursor.execute( "DELETE FROM vm_ownership WHERE host_scope=%s AND vm_uuid=%s", (host_scope, vm_uuid), ) connection.commit() except pymysql.MySQLError as exc: connection.rollback() raise DatabaseError("无法删除虚拟机归属") from exc finally: connection.close()