From f8cf0224b9cbfa34f822e676da2b37166e67989a Mon Sep 17 00:00:00 2001 From: supermario_leo Date: Mon, 30 Nov 2026 06:13:35 +0800 Subject: [PATCH] fix(multi_user): keep an unreadable account store instead of resetting it A users.json that exists but cannot be read as a JSON object was treated as an empty store, so the next write replaced every account with a single record promoted to admin, and is_first_user() reopened /register for anyone. Separate "no store yet" from "store is unusable": an absent, zero-byte, whitespace-only, byte-order-mark-only, null, [] or JSON-scalar document holds no accounts and still bootstraps; invalid JSON and a non-empty array are reported. load_users() reports the problem once a minute per path, and the single write funnel refuses to replace the operator's bytes, raising AccessError(503) for an unreadable store and for a write the volume rejects, including a first boot on an unwritable volume. The caller-facing detail names the bare file and the remedy; the parse failure and the absolute path stay in the operator log, because OS error text embeds the path in a repr-escaped form that cannot be redacted reliably. --- deeptutor/multi_user/identity.py | 114 +++++++- docs-for-dev/CONTAINERIZATION.md | 12 + .../multi_user/test_users_store_unreadable.py | 271 ++++++++++++++++++ 3 files changed, 393 insertions(+), 4 deletions(-) create mode 100644 tests/multi_user/test_users_store_unreadable.py diff --git a/deeptutor/multi_user/identity.py b/deeptutor/multi_user/identity.py index 64237b570..a91f999ab 100644 --- a/deeptutor/multi_user/identity.py +++ b/deeptutor/multi_user/identity.py @@ -9,9 +9,11 @@ import logging from pathlib import Path import secrets import threading +import time from typing import Any from uuid import uuid4 +from deeptutor.core.errors import AccessError from deeptutor.services.file_io import atomic_write_text from deeptutor.utils.secret_files import write_secret_text @@ -100,9 +102,109 @@ def _read_json(path: Path) -> dict[str, Any]: return {} +# ``load_users`` runs on every authenticated request, so a broken store must be +# reported at most once per interval per path rather than once per read. +_UNREADABLE_STORE_WARNING_INTERVAL_SECONDS = 60.0 +_unreadable_store_warned_at: dict[Path, float] = {} +_unreadable_store_warning_lock = threading.Lock() + + +def _warn_unreadable_store(path: Path, problem: str) -> None: + """Report an account store that cannot be parsed, once a minute per path.""" + now = time.monotonic() + with _unreadable_store_warning_lock: + last_warned_at = _unreadable_store_warned_at.get(path) + if ( + last_warned_at is not None + and now - last_warned_at < _UNREADABLE_STORE_WARNING_INTERVAL_SECONDS + ): + return + _unreadable_store_warned_at[path] = now + logger.warning( + "Ignoring unreadable account store %s (%s); using an empty in-memory view " + "and leaving the file untouched.", + path, + problem, + ) + + +def _read_users_document(path: Path) -> tuple[dict[str, Any], str]: + """Read the account store, reporting why it is not usable. + + Returns ``(document, problem)``. ``problem`` is empty for an absent, + zero-byte, whitespace-only, byte-order-mark-only, ``null``, ``[]`` or + JSON-scalar file, since none of them can hold account records, so the next + write bootstraps a new store. + A file that is not valid JSON, or that is a non-empty JSON array, is + reported instead of being flattened to ``{}``, so no write path can replace + the operator's accounts with a fresh single-admin store. + """ + if not path.exists() or path.stat().st_size == 0: + return {}, "" + try: + text = path.read_text(encoding="utf-8") + except Exception as exc: # noqa: BLE001 - the message is what we report + return {}, f"{type(exc).__name__}: {exc}" + # A byte-order mark is not a value: a file consisting only of one holds no + # accounts, which is the same case as a whitespace-only file. + if not text.lstrip("\ufeff").strip(): + return {}, "" + try: + loaded = json.loads(text) + except Exception as exc: # noqa: BLE001 - the message is what we report + return {}, f"{type(exc).__name__}: {exc}" + if isinstance(loaded, dict): + return loaded, "" + if isinstance(loaded, list) and loaded: + # A non-empty array can hold account records, so it is never replaced. + return {}, "expected a JSON object, found list" + # ``null``, ``[]`` and scalars cannot hold records: bootstrap a new store. + return {}, "" + + def _write_users(users: dict[str, dict[str, Any]]) -> None: - USERS_FILE.parent.mkdir(parents=True, exist_ok=True) - atomic_write_text(USERS_FILE, json.dumps(users, indent=2, ensure_ascii=False)) + # Every writer -- registration, admin provisioning, role/disable changes, + # legacy migration -- funnels through here, so this check is a backstop that + # any future writer inherits. Registration is the one existing writer that + # reaches it; the other mutators already fail closed on their own, because + # an unreadable store reads as an empty view and they return before writing. + # Refusing here keeps the operator's accounts on disk instead of replacing + # them with whatever this process managed to load (an empty dict, which also + # promotes the next account to admin). + _, problem = _read_users_document(USERS_FILE) + if problem: + # The reason and the absolute path belong in the operator log only: the + # detail below reaches unauthenticated /register callers, and OS error + # text embeds the path in a form string surgery cannot reliably redact + # (it is repr-escaped, and escaped differently per platform). + logger.warning( + "Refusing to overwrite unreadable account store %s (%s); " + "fix or restore the file, then retry.", + USERS_FILE, + problem, + ) + raise AccessError( + status_code=503, + detail=( + f"The account store {USERS_FILE.name} could not be read as a JSON " + "object. Refusing to overwrite it; fix or restore the file, then " + "retry." + ), + ) + try: + USERS_FILE.parent.mkdir(parents=True, exist_ok=True) + atomic_write_text(USERS_FILE, json.dumps(users, indent=2, ensure_ascii=False)) + except OSError as exc: + # A read-only volume or an unwritable directory reaches the same answer + # rather than a raw 500 carrying the server path. + logger.error("Failed to write account store %s: %s", USERS_FILE, exc) + raise AccessError( + status_code=503, + detail=( + f"The account store {USERS_FILE.name} could not be written. " + "Check the directory permissions and retry." + ), + ) from exc def _migrate_legacy_users() -> dict[str, dict[str, Any]] | None: @@ -183,7 +285,9 @@ def load_users( # nosec B107 - empty defaults mean "no env fallback supplied". migrate_legacy_multi_user_tree() users: dict[str, dict[str, Any]] | None = None if USERS_FILE.exists(): - users = _read_json(USERS_FILE) + users, problem = _read_users_document(USERS_FILE) + if problem: + _warn_unreadable_store(USERS_FILE, problem) else: users = _migrate_legacy_users() @@ -228,7 +332,9 @@ def save_user( role: Role = "user", preset: AccountPreset = "standard", ) -> dict[str, Any]: - USERS_FILE.parent.mkdir(parents=True, exist_ok=True) + # The parent directory is created by ``_write_users`` inside its guarded + # block, so a first boot on an unwritable volume answers the same 503 as any + # other write failure instead of raising a raw OSError from here. # Read-modify-write must be atomic so concurrent first-time registrations # cannot each see an empty store and each promote themselves to admin. with _USERS_WRITE_LOCK: diff --git a/docs-for-dev/CONTAINERIZATION.md b/docs-for-dev/CONTAINERIZATION.md index 44009cef7..7aa1daacb 100644 --- a/docs-for-dev/CONTAINERIZATION.md +++ b/docs-for-dev/CONTAINERIZATION.md @@ -281,6 +281,18 @@ auth enabled, add exact frontend origins: } ``` +### Unreadable account store (`users.json`) + +`data/system/auth/users.json` is never rewritten when it cannot be read as a +JSON object — a stray trailing comma, a truncated file, an unreadable file, or a +non-empty top-level array leaves the bytes exactly as they are. Registration and +admin provisioning then answer 503 until the file is repaired, while the log +records the full path and the reason. Because that file is the only copy of the +account password hashes, recovery is an operator action: fix the JSON or restore +the file from a backup, as nothing in the application replaces it. A store that +is absent, empty, whitespace-only, byte-order-mark-only, `null`, `[]` or a JSON +scalar holds no accounts and is treated as a new store instead. + ### Host LLM providers (Ollama / LM Studio / llama.cpp / vLLM / Lemonade) Inside Docker, `localhost` is the container itself, not your host diff --git a/tests/multi_user/test_users_store_unreadable.py b/tests/multi_user/test_users_store_unreadable.py new file mode 100644 index 000000000..8fa4ecc70 --- /dev/null +++ b/tests/multi_user/test_users_store_unreadable.py @@ -0,0 +1,271 @@ +"""An account store that cannot be read must never be overwritten. + +``_read_json`` used to flatten every failure to ``{}``, so one trailing comma in +``users.json`` made the store look empty: the next write replaced every account +with a single record, and that record was promoted to ``admin``. These tests pin +the replacement behaviour -- refuse the write, keep the bytes -- while leaving +the ordinary bootstrap case (no file yet) untouched. +""" + +from __future__ import annotations + +import json +import logging + +import pytest + +from deeptutor.core.errors import AccessError +from deeptutor.multi_user import identity + +HASH = "$2b$12$placeholder" + +UNREADABLE_STORES = [ + pytest.param(b'{"alice": {"hash": "h", "role": "admin"},}', id="trailing-comma"), + pytest.param(b'\xef\xbb\xbf{"alice": {"hash": "h"}}', id="utf8-bom"), + pytest.param(b'["alice"]', id="json-array"), + pytest.param(b'[{"alice": {"hash": "h"}}]', id="json-array-with-records"), +] + + +def assert_path_free(detail: str, store) -> None: + """The detail reaches unauthenticated /register callers: no server path. + + Checked structurally rather than by comparing against one spelling of the + path, because OS errors repr-escape it platform-dependently (on Windows + every backslash is doubled), so a string replacement is not a guarantee. + """ + assert "/" not in detail + assert "\\" not in detail + assert str(store) not in detail + assert str(store.parent) not in detail + + +@pytest.mark.parametrize("payload", UNREADABLE_STORES) +def test_write_refuses_to_replace_an_unreadable_store(mu_isolated_root, payload) -> None: + store = identity.USERS_FILE + store.parent.mkdir(parents=True, exist_ok=True) + store.write_bytes(payload) + + with pytest.raises(AccessError) as excinfo: + identity.save_user("newbie", HASH, role="user") + + error = excinfo.value + assert error.status_code == 503 + # The operator needs to know which file to fix; the reason is in the log. + assert "users.json" in error.detail + assert "Refusing to overwrite" in error.detail + assert_path_free(error.detail, store) + + # The bytes are the only copy of the accounts: nothing may rewrite them. + stored = store.read_bytes() + assert stored == payload + assert b"alice" in stored + # Unguarded, the refused write would have left a single-account admin + # document here instead of the operator's accounts. + assert b"newbie" not in stored + + +def test_write_refuses_a_store_that_is_a_directory(mu_isolated_root) -> None: + """A directory at the store path is an ordinary bad mount, unreadable for every uid.""" + store = identity.USERS_FILE + store.mkdir(parents=True) + + with pytest.raises(AccessError) as excinfo: + identity.save_user("newbie", HASH, role="user") + + error = excinfo.value + assert error.status_code == 503 + assert "could not be read as a JSON object" in error.detail + assert "users.json" in error.detail + assert_path_free(error.detail, store) + # Nothing was written: the store path is still the same empty directory. + assert list(store.iterdir()) == [] + + +@pytest.fixture +def chmod_denied_store(mu_isolated_root): + """A store whose bytes this uid cannot read; the mode is restored afterwards.""" + store = identity.USERS_FILE + store.parent.mkdir(parents=True, exist_ok=True) + payload = b'{"alice": {"hash": "h", "role": "admin"}}' + store.write_bytes(payload) + store.chmod(0o000) + try: + try: + store.read_bytes() + except PermissionError: + pass + else: + pytest.skip("this uid can read a mode-000 file") + yield store, payload + finally: + store.chmod(0o600) + + +def test_write_refuses_a_store_the_process_cannot_read(chmod_denied_store) -> None: + store, payload = chmod_denied_store + + with pytest.raises(AccessError) as excinfo: + identity.save_user("newbie", HASH, role="user") + + error = excinfo.value + assert error.status_code == 503 + assert "could not be read as a JSON object" in error.detail + assert "users.json" in error.detail + assert_path_free(error.detail, store) + + # Read access is restored only to prove the bytes survived; the fixture + # repeats the restore when an assertion above fails. + store.chmod(0o600) + stored = store.read_bytes() + assert stored == payload + assert b"newbie" not in stored + + +def test_write_refuses_when_the_directory_is_not_writable(mu_isolated_root, caplog) -> None: + """A read-only volume leaves the store readable but the write failing.""" + store = identity.USERS_FILE + store.parent.mkdir(parents=True, exist_ok=True) + payload = b'{"alice": {"hash": "h", "role": "admin"}}' + store.write_bytes(payload) + directory = store.parent + directory.chmod(0o500) + try: + try: + (directory / ".probe").write_bytes(b"") + except PermissionError: + pass + else: + (directory / ".probe").unlink() + pytest.skip("this uid can write to a mode-500 directory") + with caplog.at_level(logging.WARNING, logger="deeptutor.multi_user.identity"): + with pytest.raises(AccessError) as excinfo: + identity.save_user("newbie", HASH, role="user") + finally: + directory.chmod(0o700) + + error = excinfo.value + assert error.status_code == 503 + assert "could not be written" in error.detail + assert "users.json" in error.detail + assert_path_free(error.detail, store) + # The write failed before replacing anything. + assert store.read_bytes() == payload + # The operator still gets the absolute path, which the caller must not. + assert any(str(store) in record.getMessage() for record in caplog.records) + + +def test_write_refuses_when_the_auth_directory_cannot_be_entered(mu_isolated_root) -> None: + """First boot with an auth directory the process cannot enter.""" + store = identity.USERS_FILE + directory = store.parent + directory.mkdir(parents=True, exist_ok=True) + directory.chmod(0o000) + try: + try: + list(directory.iterdir()) + except PermissionError: + pass + else: + pytest.skip("this uid can enter a mode-000 directory") + with pytest.raises(AccessError) as excinfo: + identity.save_user("newbie", HASH, role="user") + finally: + directory.chmod(0o700) + + error = excinfo.value + assert error.status_code == 503 + assert "users.json" in error.detail + assert_path_free(error.detail, store) + # Nothing was created in the directory while it was unreachable. + assert list(directory.iterdir()) == [] + + +def test_write_funnel_itself_refuses_an_unreadable_store(mu_isolated_root) -> None: + """The backstop lives at the funnel, so any future writer inherits it.""" + store = identity.USERS_FILE + store.parent.mkdir(parents=True, exist_ok=True) + payload = b'{"alice": {"hash": "h", "role": "admin"},}' + store.write_bytes(payload) + + record = { + "id": "u_newbie", + "hash": HASH, + "role": "admin", + "created_at": "", + "disabled": False, + "avatar": "", + "preset": "standard", + } + with pytest.raises(AccessError) as excinfo: + identity._write_users({"newbie": record}) + + assert excinfo.value.status_code == 503 + assert store.read_bytes() == payload + assert b"newbie" not in store.read_bytes() + + +def test_unreadable_store_warns_once_per_path(mu_isolated_root, caplog) -> None: + store = identity.USERS_FILE + store.parent.mkdir(parents=True, exist_ok=True) + store.write_text('{"alice": {"hash": "h"},}', encoding="utf-8") + + with caplog.at_level(logging.WARNING, logger="deeptutor.multi_user.identity"): + identity.load_users() + identity.load_users() + + warnings = [ + record + for record in caplog.records + if record.name == "deeptutor.multi_user.identity" + and "unreadable account store" in record.getMessage() + ] + assert len(warnings) == 1 + + +@pytest.mark.parametrize( + "payload", + [ + pytest.param(None, id="absent"), + pytest.param(b"", id="zero-byte"), + pytest.param(b"\xef\xbb\xbf", id="bom-only"), + pytest.param(b"\n", id="whitespace-only"), + pytest.param(b"null", id="json-null"), + pytest.param(b"[]", id="empty-array"), + pytest.param(b"0", id="json-number"), + pytest.param(b"false", id="json-false"), + pytest.param(b'"x"', id="json-string"), + ], +) +def test_missing_or_empty_store_still_bootstraps_the_first_admin( + mu_isolated_root, payload: bytes | None +) -> None: + store = identity.USERS_FILE + if payload is not None: + store.parent.mkdir(parents=True, exist_ok=True) + store.write_bytes(payload) + + record = identity.save_user("alice", HASH, role="user") + + assert record["role"] == "admin" + on_disk = json.loads(store.read_text(encoding="utf-8")) + assert isinstance(on_disk, dict) + assert on_disk["alice"]["role"] == "admin" + + +def test_valid_store_round_trips_and_keeps_existing_accounts(mu_isolated_root) -> None: + store = identity.USERS_FILE + identity.save_user("alice", HASH, role="user") + identity.save_user("bob", HASH, role="user") + identity.load_users() # normalise the records once + + unchanged = store.read_bytes() + identity.load_users() + assert store.read_bytes() == unchanged + + identity.save_user("carol", HASH, role="user") + users = identity.load_users() + assert set(users) == {"alice", "bob", "carol"} + assert users["alice"]["role"] == "admin" + assert users["bob"]["role"] == "user" + assert users["carol"]["role"] == "user"