Coverage for monitoring/auth_io.py: 100%
26 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""The users file behind `monitoring/auth.py` (V6.6.5, #350): `$AQ_USERS_FILE`, else `state/users.json` (gitignored).
3Auth is required when the file lists at least one user, or when `AQ_AUTH=required`; with neither, the API reads stay open
4exactly as before and nothing can write. The file holds salted hashes only, and is written owner-only where the OS allows.
5"""
7from __future__ import annotations
9import json
10import os
11from pathlib import Path
13from json_safety import atomic_write_text
14from monitoring.auth import User, parse_users, users_document
16__all__ = ["users_file", "load_users", "save_users", "auth_required"]
18ROOT_DIR = Path(__file__).resolve().parent.parent
21def users_file() -> Path:
22 return Path(os.environ.get("AQ_USERS_FILE") or (ROOT_DIR / "state" / "users.json"))
25def load_users() -> tuple[User, ...]:
26 """The users, or none when the file is missing. An unreadable or invalid file raises: a broken users file must not
27 quietly open the API."""
28 path = users_file()
29 if not path.exists():
30 return ()
31 return parse_users(json.loads(path.read_text(encoding="utf-8")))
34def save_users(users: tuple[User, ...]) -> Path:
35 path = users_file()
36 path.parent.mkdir(parents=True, exist_ok=True)
37 atomic_write_text(path, json.dumps(users_document(users), indent=1) + "\n")
38 try:
39 os.chmod(path, 0o600)
40 except OSError:
41 pass # Windows: the ACL of the user's profile applies
42 return path
45def auth_required(users: tuple[User, ...]) -> bool:
46 return bool(users) or os.environ.get("AQ_AUTH", "").lower() == "required"