feat!: remove the shared demo account
The demo account — one shared user that whitelisted emails entered from the login page, reset on a schedule — goes end to end (owner decision, E34): demo.py and the reset job, users.is_demo and demo_whitelist (migration 0098 deletes the demo user, its audit rows, the reset job's override and notices, then drops the column and table; the downgrade restores the empty schema), the /auth/demo entry, the admin whitelist and reset, the Demo tab, the banner, the login page's "Try the demo", and every is_demo branch in routes, userscope, scheduler and the UI. require_human only ever refused the demo account, so its 87 uses become current_user (owner-approved); require_write_scope keeps its own check. The login page's "or" divider now shows only beside the Google button: without the demo entry under it, an instance without Google would have said "or" to nothing. A contract test (removedFeatures) fails on the word anywhere in the backend, frontend, e2e or scripts — seen red on a planted hit. Size ceilings tightened for the modules that shrank; admin.py is back under the limit.
This commit is contained in:
@@ -22,12 +22,6 @@ def test_clearing_the_audit_log_keeps_the_count_as_data(as_user, db, make_user):
|
||||
assert _after(db, "audit_clear") == {"cleared": 2}
|
||||
|
||||
|
||||
def test_a_demo_reset_keeps_the_count_as_data(as_user, db, make_user):
|
||||
admin = make_user(email="boss@example.com", role="admin")
|
||||
seeded = as_user(admin).post("/api/admin/demo/reset").json()["playlists_seeded"]
|
||||
assert _after(db, "demo_reset") == {"playlists_seeded": seeded}
|
||||
|
||||
|
||||
def test_a_discovery_purge_keeps_its_counts_as_data(as_user, db, make_user):
|
||||
admin = make_user(email="boss@example.com", role="admin")
|
||||
body = as_user(admin).post("/api/admin/purge-discovery").json()
|
||||
|
||||
@@ -120,7 +120,7 @@ def test_a_raised_ceiling_is_still_a_ceiling():
|
||||
"""The difference between this and an exemption, and the reason the list is a mapping: a route
|
||||
that needs more bytes does not thereby get unlimited bytes. Left uncounted, the upload route
|
||||
would let an ANONYMOUS caller stream without bound — FastAPI parses a declared body before the
|
||||
first dependency, so `require_human` has not run yet when the bytes land."""
|
||||
first dependency, so the auth dependency has not run yet when the bytes land."""
|
||||
over = b"x" * (BIG[("POST", "/api/things/{tid}/blob")] + 1)
|
||||
r = _client(routes=BIG).post("/api/things/abc/blob", content=over)
|
||||
assert r.status_code == 413
|
||||
@@ -514,7 +514,7 @@ def test_no_route_with_a_raised_ceiling_declares_a_body_parameter(method, templa
|
||||
A raised ceiling is only honest when the route's own cap applies to the bytes AS THEY ARRIVE.
|
||||
FastAPI reads and spools a DECLARED body (`= File(...)`, `= Form(...)`, a Pydantic model)
|
||||
BEFORE the first dependency resolves — so on such a route this middleware's ceiling is the only
|
||||
thing between an anonymous caller and the whole allowance, `require_human` never gets a say, and
|
||||
thing between an anonymous caller and the whole allowance, the auth dependency never gets a say, and
|
||||
the route's in-handler cap measures bytes that have already landed. That is exactly what P1
|
||||
closed on the upload route, which sat in `ROUTE_MAX_BODY_BYTES` with a 500 MiB ceiling and a
|
||||
`file: UploadFile = File(...)` body for one release.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
"""R14 backend coverage: the channel-detail Normal/Shorts/Live counts (moved off the manager table),
|
||||
the update_channel -> immediate-backfill wiring (incl. the demo guard), and the interactive
|
||||
the update_channel -> immediate-backfill wiring, and the interactive
|
||||
"get full history" guard that keeps it from racing the scheduler's cursor or draining the budget."""
|
||||
|
||||
from datetime import datetime, timezone
|
||||
@@ -89,7 +89,7 @@ def test_channel_detail_hidden_defaults_false_when_not_subscribed(db, monkeypatc
|
||||
assert resp.json()["hidden"] is False
|
||||
|
||||
|
||||
def _setup_channel_and_sub(db, *, email, is_demo=False):
|
||||
def _setup_channel_and_sub(db, *, email):
|
||||
ch = Channel(
|
||||
id="UC_wire",
|
||||
title="Wire",
|
||||
@@ -98,7 +98,7 @@ def _setup_channel_and_sub(db, *, email, is_demo=False):
|
||||
uploads_playlist_id="UU_wire",
|
||||
)
|
||||
db.add(ch)
|
||||
user = User(email=email, is_demo=is_demo)
|
||||
user = User(email=email)
|
||||
db.add(user)
|
||||
db.flush()
|
||||
db.add(Subscription(user_id=user.id, channel_id=ch.id, deep_requested=False))
|
||||
@@ -117,7 +117,7 @@ def _patch_deep_requested(db, monkeypatch, override_dep, user):
|
||||
return resp, calls
|
||||
|
||||
|
||||
def test_deep_request_schedules_immediate_backfill_for_non_demo(db, monkeypatch, override_dep):
|
||||
def test_deep_request_schedules_immediate_backfill(db, monkeypatch, override_dep):
|
||||
ch, me = _setup_channel_and_sub(db, email="wire@example.com")
|
||||
resp, calls = _patch_deep_requested(db, monkeypatch, override_dep, me)
|
||||
assert resp.status_code == 200, resp.text
|
||||
@@ -126,16 +126,6 @@ def test_deep_request_schedules_immediate_backfill_for_non_demo(db, monkeypatch,
|
||||
assert calls == [(ch.id, me.id)]
|
||||
|
||||
|
||||
def test_deep_request_does_not_schedule_immediate_backfill_for_demo(db, monkeypatch, override_dep):
|
||||
# The SHARED demo account must not be able to kick immediate full backfills (budget drain).
|
||||
_ch, demo = _setup_channel_and_sub(db, email="demo@example.com", is_demo=True)
|
||||
resp, calls = _patch_deep_requested(db, monkeypatch, override_dep, demo)
|
||||
assert resp.status_code == 200, resp.text
|
||||
assert calls == [], "demo must not schedule an immediate backfill"
|
||||
# …and deep_requested is not persisted on the shared demo subscription either.
|
||||
assert resp.json()["deep_requested"] is False
|
||||
|
||||
|
||||
class TestImmediateBackfillGuard:
|
||||
"""backfill_channel_now coordinates with the paced scheduler through _backfill_in_progress (per-
|
||||
channel mutual exclusion, both directions) + _immediate_running (a cap on interactive runs so a
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
Four parts:
|
||||
* the session's life: one open per user, a second Start joins it, a Stop ends it, the cap ends it
|
||||
on its own, the demo account cannot record, nobody reaches another user's session (DB lane);
|
||||
on its own, nobody reaches another user's session (DB lane);
|
||||
* the tag: a request naming the caller's own open session is logged at its level with every line
|
||||
tagged, while a header naming anything else is ignored (a real sign-in through `_session_user`);
|
||||
* the browser's batches: a session counts as consent to its level, and only its own events keep
|
||||
@@ -71,11 +71,6 @@ def test_only_the_two_raised_levels_can_be_recorded(db, make_user, as_user):
|
||||
assert client.post("/api/debug-sessions", json={"level": bogus}).status_code == 422
|
||||
|
||||
|
||||
def test_the_demo_account_cannot_record(db, make_user, as_user):
|
||||
r = as_user(make_user(is_demo=True)).post("/api/debug-sessions", json={"level": "DEBUG"})
|
||||
assert r.status_code == 403 and r.json()["detail"]["code"] == "demo"
|
||||
|
||||
|
||||
def test_stop_ends_it_and_me_stops_reporting_it(db, client, make_user):
|
||||
_signed_in(client, make_user)
|
||||
sid = _start(client)["id"]
|
||||
|
||||
@@ -1,92 +0,0 @@
|
||||
"""The shared demo account's refusal says WHY, in the reader's language (deep-review round 6).
|
||||
|
||||
`require_human` answered `403 "Not available in the demo account."` — a plain string. `req` leaves
|
||||
403 to the caller, and round 5 taught `notifyActionError` to discard a plain-string detail in favour
|
||||
of the caller's already-translated fallback, so from that commit on the demo user got a generic
|
||||
"couldn't do that" and no hint that the demo account was the reason. Not every affordance behind
|
||||
this gate is UI-gated on `is_demo` either — the comfort shelf is not, so the pin button is live.
|
||||
|
||||
A structured `{code: "demo"}` is what `localizeDetail` can turn into `errors.demo` in both locales.
|
||||
Pinned at every site: the shared dependency, the two auth routes that hand-roll the same check,
|
||||
the account-delete route in `routes/me.py` — which round 6 missed while its docstring claimed
|
||||
all the sites were covered, so the next reader had no reason to look (round 7). An asymmetric fix is
|
||||
the smell this repo bans, and a docstring asserting symmetry it does not have is worse than none.
|
||||
|
||||
The list is derived from the source, not typed out: `test_every_is_demo_refusal_is_on_the_list`
|
||||
below fails when a fifth `is_demo` 403 appears anywhere in `app/`, so this file cannot fall behind
|
||||
the code the way round 6's did. (E22 S5 added the fifth: raising the diagnostics level.) Needs the DB.
|
||||
"""
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
from app.models import User
|
||||
|
||||
|
||||
def test_every_demo_refusal_carries_the_same_structured_reason(db, make_user, as_user):
|
||||
demo = make_user(email="demo@example.com", is_demo=True)
|
||||
client = as_user(demo)
|
||||
for method, url, body in [
|
||||
# `require_human` itself, through an affordance the UI does NOT gate on is_demo.
|
||||
("post", "/api/discover/pins", {"kind": "video", "ref": "v1"}),
|
||||
# The three routes that repeat the check inline rather than depending on the gate.
|
||||
("post", "/auth/logout-others", None),
|
||||
("post", "/auth/set-password", {"password": "a long enough password"}),
|
||||
("delete", "/api/me/account", None),
|
||||
# E22 S5: the shared account's log would interleave every visitor's session.
|
||||
("put", "/api/me/diagnostics", {"level": "DEBUG"}),
|
||||
]:
|
||||
r = getattr(client, method)(url, **({"json": body} if body is not None else {}))
|
||||
assert r.status_code == 403, (url, r.text)
|
||||
detail = r.json()["detail"]
|
||||
# Every one of them is a dict whose `code` the frontend can localize; the delete route adds
|
||||
# a `reason` so its refusal can be worded specifically.
|
||||
assert isinstance(detail, dict), (url, detail)
|
||||
assert detail["code"] == "demo", (url, detail)
|
||||
|
||||
|
||||
def test_every_is_demo_refusal_is_on_the_list():
|
||||
"""A fifth site must not be able to appear unnoticed.
|
||||
|
||||
Round 6 converted three of four `is_demo` 403s and wrote a docstring saying it had converted
|
||||
them all; the fourth kept answering a bare English string for another round because nothing
|
||||
counted them. So count them here: every `is_demo`-guarded 403 in `app/` has to raise a
|
||||
structured detail, and the number of them has to match what this file exercises."""
|
||||
app_dir = Path(__file__).resolve().parents[1] / "app"
|
||||
sites = []
|
||||
for path in sorted(app_dir.rglob("*.py")):
|
||||
lines = path.read_text(encoding="utf-8").splitlines()
|
||||
for i, line in enumerate(lines):
|
||||
# `if user.is_demo:` / `if u.is_demo and …:` — the hand-rolled gate, not the ORM
|
||||
# filters (`User.is_demo.is_(False)`) and not the column definition.
|
||||
if not re.search(r"^\s*if\s+\w+\.is_demo\b[^:]*:", line):
|
||||
continue
|
||||
block = "\n".join(lines[i : i + 6])
|
||||
if "403" not in block:
|
||||
continue
|
||||
sites.append(f"{path.relative_to(app_dir)}:{i + 1}")
|
||||
assert 'detail={"code": "demo"' in block, (
|
||||
f"{path.relative_to(app_dir)}:{i + 1} refuses the demo account with an "
|
||||
f"unstructured detail — the frontend cannot localize it:\n{block}"
|
||||
)
|
||||
# auth.py's shared gate + routes/auth.py's two + routes/me.py's delete and diagnostics level. A
|
||||
# new one is welcome, but it has to be added to the loop above in the same commit.
|
||||
assert len(sites) == 5, sites
|
||||
|
||||
|
||||
def test_a_real_account_is_not_refused_by_the_gate(db, make_user, as_user):
|
||||
"""The other half: the structured detail must not come from having broken the gate open the
|
||||
other way. A non-demo account gets past `require_human` and fails (or succeeds) on its own
|
||||
merits — anything but a 403 demo refusal."""
|
||||
client = as_user(make_user(email="real@example.com"))
|
||||
r = client.post("/auth/logout-others")
|
||||
assert r.status_code == 200, r.text
|
||||
assert not isinstance(r.json().get("detail"), dict)
|
||||
|
||||
|
||||
def test_the_gate_reads_the_flag_and_not_the_email(db):
|
||||
"""`is_demo` is a column, not a convention about the address — a real account that happens to
|
||||
be called demo@ must not be refused."""
|
||||
from app.auth import require_human
|
||||
|
||||
assert require_human(User(email="demo@example.com", is_demo=False)) is not None
|
||||
@@ -1,8 +1,8 @@
|
||||
"""E22 S5 — a user's consented diagnostics level, and the browser log it lets in.
|
||||
|
||||
Three parts:
|
||||
* the level itself: the server computes its expiry, a lapsed one reads as the base, the demo
|
||||
account cannot raise it (DB lane, through the real routes);
|
||||
* the level itself: the server computes its expiry, a lapsed one reads as the base (DB lane,
|
||||
through the real routes);
|
||||
* `POST /api/diagnostics/events`: refused at the base level, and nothing in a batch is trusted —
|
||||
the account comes from the session, everything is redacted again, events under the consented
|
||||
level are dropped, sizes and pace are capped (DB lane);
|
||||
@@ -93,13 +93,6 @@ def test_only_the_three_levels_can_be_chosen(db, make_user, as_user):
|
||||
assert client.put("/api/me/diagnostics", json={"level": bogus}).status_code == 422
|
||||
|
||||
|
||||
def test_the_demo_account_can_return_to_the_base_but_never_raise_it(db, make_user, as_user):
|
||||
client = as_user(make_user(is_demo=True))
|
||||
r = client.put("/api/me/diagnostics", json={"level": "TRACE"})
|
||||
assert r.status_code == 403 and r.json()["detail"]["code"] == "demo"
|
||||
assert client.put("/api/me/diagnostics", json={"level": "INFO"}).status_code == 200
|
||||
|
||||
|
||||
def test_preferences_must_be_a_json_object(db, make_user, as_user):
|
||||
client = as_user(make_user())
|
||||
assert client.put("/api/me/preferences", json=["not", "an", "object"]).status_code == 422
|
||||
|
||||
@@ -2,14 +2,13 @@
|
||||
|
||||
The roadmap assumed stamping it in `_establish_session` would cover Google and password alike. It
|
||||
would not have: only password login called it, and the Google callback carried its own copy of the
|
||||
same four lines. So these pin BOTH doors through the real routes — plus the two that must not stamp
|
||||
(a refused password, the shared demo account) and the admin list that shows it.
|
||||
same four lines. So these pin BOTH doors through the real routes — plus the one that must not stamp
|
||||
(a refused password) and the admin list that shows it.
|
||||
"""
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from app.config import settings
|
||||
from app.models import DemoWhitelist
|
||||
from app.routes import auth as auth_routes
|
||||
|
||||
_PW = "correct horse battery"
|
||||
@@ -73,18 +72,6 @@ def test_a_google_sign_in_stamps_last_login(client, db, make_user, monkeypatch):
|
||||
assert client.get("/api/me").json()["id"] == user.id
|
||||
|
||||
|
||||
def test_the_demo_entry_does_not_stamp_the_shared_account(client, db):
|
||||
db.add(DemoWhitelist(email="visitor@example.com"))
|
||||
db.commit()
|
||||
|
||||
r = client.post("/auth/demo", json={"email": "visitor@example.com"})
|
||||
|
||||
assert r.json() == {"ok": True, "authenticated": True}
|
||||
demo = auth_routes.get_or_create_demo_user(db)
|
||||
db.refresh(demo)
|
||||
assert demo.last_login_at is None
|
||||
|
||||
|
||||
def test_the_admin_user_list_carries_last_login(as_user, db, make_user):
|
||||
admin = make_user(email="boss@example.com", role="admin")
|
||||
never = make_user(email="never@example.com")
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""The sliding-window limiter behind /auth/register, password-login, password-reset and demo.
|
||||
"""The sliding-window limiter behind /auth/register, password-login and password-reset.
|
||||
|
||||
Pure logic, no DB. `reset()` in particular is only ever called by a test fixture (conftest clears
|
||||
the module-level limiters between tests), so without a test here a refactor could turn it into a
|
||||
|
||||
@@ -46,9 +46,7 @@ SERIALIZERS = {
|
||||
"_collection_card",
|
||||
"_playlist_card",
|
||||
"_serialize",
|
||||
"_serialize_demo",
|
||||
"_serialize_job",
|
||||
"_serialize_msg",
|
||||
"_serialize_profile",
|
||||
"_serialize_user",
|
||||
"_summary",
|
||||
|
||||
@@ -16,7 +16,7 @@ def _client(db, user, monkeypatch, override_dep):
|
||||
state, "_configured_cache", True
|
||||
) # the request gate 503s an unconfigured app
|
||||
override_dep(get_db, db.info["request"])
|
||||
override_dep(current_user, lambda: user) # require_human resolves through this
|
||||
override_dep(current_user, lambda: user)
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
|
||||
@@ -104,7 +104,7 @@ def test_search_youtube_route_returns_422_when_ingest_fails(db, monkeypatch, ove
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
import app.state as state
|
||||
from app.auth import require_human
|
||||
from app.auth import current_user
|
||||
from app.db import get_db
|
||||
from app.main import app
|
||||
from app.routes import search as search_mod
|
||||
@@ -146,7 +146,7 @@ def test_search_youtube_route_returns_422_when_ingest_fails(db, monkeypatch, ove
|
||||
monkeypatch.setattr(search_mod, "_ingest_candidates", _boom)
|
||||
|
||||
override_dep(get_db, db.info["request"])
|
||||
override_dep(require_human, lambda: user)
|
||||
override_dep(current_user, lambda: user)
|
||||
resp = TestClient(app).get("/api/search/youtube?q=test+term")
|
||||
|
||||
assert resp.status_code == 422, resp.text
|
||||
|
||||
@@ -155,18 +155,6 @@ def test_only_an_admin_can_mint_one(db, as_user, make_user):
|
||||
assert db.query(AuthToken).filter(AuthToken.kind == "setpw").count() == 0
|
||||
|
||||
|
||||
def test_the_shared_demo_account_is_refused(db, as_user, make_user):
|
||||
"""The demo account is shared, so handing anyone a way to change its password hands them
|
||||
everyone else's session on it."""
|
||||
admin = make_user(role="admin")
|
||||
demo = make_user(is_demo=True)
|
||||
db.commit()
|
||||
|
||||
r = as_user(admin).post(f"/api/admin/users/{demo.id}/set-password-link")
|
||||
assert r.status_code == 400
|
||||
assert r.json()["detail"]["reason"] == "demo"
|
||||
|
||||
|
||||
def test_the_access_panel_reports_the_gates(db, as_user, make_user):
|
||||
admin = make_user(role="admin")
|
||||
target = make_user(email_verified=False, is_active=False)
|
||||
|
||||
@@ -31,12 +31,11 @@ BIG_MODULES: dict[str, int] = {
|
||||
"app/downloads/edit.py": 833,
|
||||
"app/downloads/pipeline.py": 870,
|
||||
"app/logs.py": 839,
|
||||
"app/models.py": 1607,
|
||||
"app/models.py": 1525,
|
||||
"app/plex/stream.py": 1128,
|
||||
"app/plex/subtitles.py": 1092,
|
||||
"app/routes/admin.py": 864,
|
||||
"app/routes/auth.py": 1353,
|
||||
"app/routes/downloads.py": 1237,
|
||||
"app/routes/auth.py": 1273,
|
||||
"app/routes/downloads.py": 1232,
|
||||
}
|
||||
|
||||
COMPLEX: dict[str, int] = {
|
||||
|
||||
@@ -186,7 +186,7 @@ def test_an_anonymous_upload_is_refused_before_a_byte_of_it_is_read(client):
|
||||
"""P1 — the defect E27 bounded but did not close.
|
||||
|
||||
While the route declared `file: UploadFile = File(...)`, FastAPI parsed and spooled the body
|
||||
BEFORE the first dependency ran, so `require_human` could not gate it: an unauthenticated
|
||||
BEFORE the first dependency ran, so the auth dependency could not gate it: an unauthenticated
|
||||
caller could make the server write the whole per-file allowance (500 MiB by default) to temp,
|
||||
per request. SEC-20's ceiling capped the number; it could not stop the writing.
|
||||
|
||||
@@ -532,7 +532,6 @@ def _display_write_sites() -> dict[tuple[str, str], set[str]]:
|
||||
# file has transferred — so each of these has to be bounded, and each one here has been read.
|
||||
#
|
||||
# Bounded by `display_text` unless noted:
|
||||
# auth.get_or_create_demo_user a literal.
|
||||
# service.redownload CLEARS the field so the fresh metadata wins — `None` is the
|
||||
# one value that needs no bound, and a clear is still a write.
|
||||
# service.enqueue / enqueue_edit `display_name` is already bounded by its caller; the fallback
|
||||
@@ -544,7 +543,6 @@ def _display_write_sites() -> dict[tuple[str, str], set[str]]:
|
||||
# `not []` and enforcing nothing, which is how a drift guard dies quietly (round 3). This one fails
|
||||
# when a site appears, when one disappears, and when one changes what it writes.
|
||||
DISPLAY_WRITE_SITES = {
|
||||
("auth.py", "get_or_create_demo_user"): {"'Demo'"},
|
||||
("downloads/service.py", "redownload"): {"None"},
|
||||
("downloads/service.py", "enqueue"): {
|
||||
"display_name or (asset.title[:DISPLAY_TEXT_MAX] "
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
"""is_messageable_user — the "real, active, non-suspended human" predicate reused by the messaging
|
||||
directory and the download share endpoints. A row must be non-demo AND active AND not-suspended."""
|
||||
"""is_messageable_user — the "active, non-suspended account" predicate reused by the download share
|
||||
endpoints. A row must be active AND not-suspended."""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.userscope import is_messageable_user
|
||||
|
||||
|
||||
def _user(is_demo=False, is_active=True, is_suspended=False):
|
||||
return SimpleNamespace(is_demo=is_demo, is_active=is_active, is_suspended=is_suspended)
|
||||
def _user(is_active=True, is_suspended=False):
|
||||
return SimpleNamespace(is_active=is_active, is_suspended=is_suspended)
|
||||
|
||||
|
||||
def test_a_real_active_human_is_messageable():
|
||||
def test_an_active_account_is_messageable():
|
||||
assert is_messageable_user(_user()) is True
|
||||
|
||||
|
||||
@@ -18,7 +18,6 @@ def test_none_is_not_messageable():
|
||||
assert is_messageable_user(None) is False
|
||||
|
||||
|
||||
def test_demo_suspended_or_inactive_are_not_messageable():
|
||||
assert is_messageable_user(_user(is_demo=True)) is False
|
||||
def test_suspended_or_inactive_are_not_messageable():
|
||||
assert is_messageable_user(_user(is_suspended=True)) is False
|
||||
assert is_messageable_user(_user(is_active=False)) is False
|
||||
|
||||
Reference in New Issue
Block a user