Files
DeepTutor/tests/multi_user/test_users_store_unreadable.py
supermario_leo f8cf0224b9 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.
2026-11-30 06:49:38 +08:00

272 lines
9.4 KiB
Python

"""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"