"""Local user accounts and cookie sessions for the internal search workspace.""" from __future__ import annotations import hashlib import hmac import os import re import secrets import sqlite3 import threading import time from pathlib import Path USERNAME = re.compile(r"^[A-Za-z0-9._-]{3,64}$") PASSWORD_ITERATIONS = 310_000 SESSION_TTL = 60 * 60 * 12 class AuthError(ValueError): pass def can_manage_users(username: str) -> bool: return isinstance(username, str) and username.casefold() == "admin" class AuthStore: def __init__(self, path: Path | str): if path != ":memory:": database = Path(path) database.parent.mkdir(parents=True, exist_ok=True) try: descriptor = os.open(database, os.O_CREAT | os.O_EXCL | os.O_RDWR, 0o600) os.close(descriptor) except FileExistsError: pass self.connection = sqlite3.connect(path, check_same_thread=False) self.connection.row_factory = sqlite3.Row self._lock = threading.RLock() self.connection.executescript(""" CREATE TABLE IF NOT EXISTS users ( username TEXT PRIMARY KEY COLLATE NOCASE, password_hash BLOB NOT NULL, password_salt BLOB NOT NULL, must_change_password INTEGER NOT NULL DEFAULT 1, created_at INTEGER NOT NULL, first_login_at INTEGER, last_login_at INTEGER, password_reset_at INTEGER ); CREATE TABLE IF NOT EXISTS sessions ( token_hash BLOB PRIMARY KEY, username TEXT NOT NULL REFERENCES users(username) ON DELETE CASCADE, expires_at INTEGER NOT NULL ); """) user_columns = {row["name"] for row in self.connection.execute("PRAGMA table_info(users)")} for column in ("first_login_at", "last_login_at", "password_reset_at"): if column not in user_columns: self.connection.execute(f"ALTER TABLE users ADD COLUMN {column} INTEGER") self.connection.execute("PRAGMA foreign_keys = ON") self.connection.commit() @staticmethod def _validate(username: str, password: str) -> tuple[str, str]: if not isinstance(username, str) or not USERNAME.fullmatch(username): raise AuthError("login must be 3–64 letters, numbers, dots, underscores or hyphens") if not isinstance(password, str) or not 12 <= len(password) <= 256: raise AuthError("password must be between 12 and 256 characters") return username, password @staticmethod def _hash(password: str, salt: bytes) -> bytes: return hashlib.pbkdf2_hmac("sha256", password.encode(), salt, PASSWORD_ITERATIONS) def create_admin(self, password: str) -> None: self._validate("admin", password) salt = secrets.token_bytes(16) with self._lock: if self.connection.execute("SELECT 1 FROM users LIMIT 1").fetchone(): raise AuthError("accounts already exist") self.connection.execute("INSERT INTO users(username,password_hash,password_salt,must_change_password,created_at) VALUES('admin',?,?,0,?)", (self._hash(password, salt), salt, int(time.time()))) self.connection.commit() # shortcut: login throttling belongs to the HTTPS reverse proxy; add local limits before direct public exposure. def login(self, username: str, password: str) -> tuple[str, dict]: if not isinstance(username, str) or not isinstance(password, str): raise AuthError("invalid login or password") with self._lock: user = self.connection.execute("SELECT * FROM users WHERE username = ? COLLATE NOCASE", (username,)).fetchone() salt = user["password_salt"] if user else b"\0" * 16 expected_hash = user["password_hash"] if user else b"\0" * 32 valid = hmac.compare_digest(self._hash(password, salt), expected_hash) if not user or not valid: raise AuthError("invalid login or password") with self._lock: current = self.connection.execute("SELECT * FROM users WHERE username=?", (user["username"],)).fetchone() if not current or not hmac.compare_digest(current["password_hash"], expected_hash): raise AuthError("invalid login or password") token = secrets.token_urlsafe(32) now = int(time.time()) self.connection.execute("DELETE FROM sessions WHERE expires_at <= ?", (now,)) self.connection.execute("INSERT INTO sessions(token_hash,username,expires_at) VALUES(?,?,?)", (hashlib.sha256(token.encode()).digest(), user["username"], now + SESSION_TTL)) self.connection.execute("UPDATE users SET first_login_at=COALESCE(first_login_at,?),last_login_at=? WHERE username=?", (now, now, user["username"])) self.connection.commit() current = self.connection.execute("SELECT * FROM users WHERE username=?", (user["username"],)).fetchone() return token, self._public(current) @staticmethod def _public(user: sqlite3.Row) -> dict: can_manage = can_manage_users(user["username"]) return {"username": user["username"], "role": "Администратор" if can_manage else "Пользователь", "can_manage_users": can_manage, "must_change_password": bool(user["must_change_password"]), "created_at": user["created_at"]} def user_for_token(self, token: str | None) -> dict | None: if not token: return None with self._lock: user = self.connection.execute("SELECT users.* FROM sessions JOIN users USING(username) WHERE token_hash = ? AND expires_at > ?", (hashlib.sha256(token.encode()).digest(), int(time.time()))).fetchone() return self._public(user) if user else None def logout(self, token: str | None) -> None: if token: with self._lock: self.connection.execute("DELETE FROM sessions WHERE token_hash = ?", (hashlib.sha256(token.encode()).digest(),)) self.connection.commit() def change_password(self, username: str, old_password: str, new_password: str) -> None: if not isinstance(old_password, str): raise AuthError("current password is required") self._validate(username, new_password) with self._lock: user = self.connection.execute("SELECT * FROM users WHERE username = ?", (username,)).fetchone() if not user: raise AuthError("account not found") if not hmac.compare_digest(self._hash(old_password, user["password_salt"]), user["password_hash"]): raise AuthError("current password is incorrect") if hmac.compare_digest(self._hash(new_password, user["password_salt"]), user["password_hash"]): raise AuthError("new password must be different") salt = secrets.token_bytes(16) password_hash = self._hash(new_password, salt) self.connection.execute("UPDATE users SET password_hash=?,password_salt=?,must_change_password=0 WHERE username=?", (password_hash, salt, username)) self.connection.execute("DELETE FROM sessions WHERE username=?", (username,)) self.connection.commit() def create_user(self, username: str, password: str) -> None: self._validate(username, password) salt = secrets.token_bytes(16) password_hash = self._hash(password, salt) try: with self._lock: self.connection.execute("INSERT INTO users(username,password_hash,password_salt,must_change_password,created_at) VALUES(?,?,?,1,?)", (username, password_hash, salt, int(time.time()))) self.connection.commit() except sqlite3.IntegrityError as error: raise AuthError("login already exists") from error def delete_user(self, username: str) -> None: if can_manage_users(username): raise AuthError("admin account cannot be deleted") with self._lock: self.connection.execute("DELETE FROM users WHERE username=?", (username,)) self.connection.commit() def reset_password(self, username: str, password: str) -> None: self._validate(username, password) salt = secrets.token_bytes(16) password_hash = self._hash(password, salt) with self._lock: cursor = self.connection.execute("UPDATE users SET password_hash=?,password_salt=?,must_change_password=1,password_reset_at=? WHERE username=?", (password_hash, salt, int(time.time()), username)) if not cursor.rowcount: raise AuthError("account not found") self.connection.execute("DELETE FROM sessions WHERE username=?", (username,)) self.connection.commit() def list_users(self) -> list[dict]: with self._lock: users = [] for row in self.connection.execute("SELECT * FROM users ORDER BY username COLLATE NOCASE"): account = self._public(row) account.update(first_login_at=row["first_login_at"], last_login_at=row["last_login_at"], password_reset_at=row["password_reset_at"]) users.append(account) return users