Files
akyldash/backend/search/auth.py
T

161 lines
7.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""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
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
);
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
);
""")
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.commit()
return token, self._public(current)
@staticmethod
def _public(user: sqlite3.Row) -> dict:
return {"username": user["username"], "role": "Администратор", "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 | None, new_password: str) -> None:
self._validate(username, new_password)
salt = secrets.token_bytes(16)
password_hash = self._hash(new_password, salt)
with self._lock:
user = self.connection.execute("SELECT * FROM users WHERE username = ?", (username,)).fetchone()
if not user:
raise AuthError("account not found")
if old_password is not None and not hmac.compare_digest(self._hash(old_password, user["password_salt"]), user["password_hash"]):
raise AuthError("current password is incorrect")
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 username.casefold() == "admin":
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 WHERE username=?", (password_hash, salt, 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:
return [self._public(row) for row in self.connection.execute("SELECT * FROM users ORDER BY username COLLATE NOCASE")]