forked from ChelseaKR/queer-the-stacks
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
586 lines (494 loc) · 20.1 KB
/
Copy pathserver.py
File metadata and controls
586 lines (494 loc) · 20.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
"""The self-hosted FastAPI app — serves the dashboard, only behind auth.
Every content route depends on :func:`require_auth`, which rejects any request
without a valid bearer token *or* a valid signed session cookie (401). There is
no unauthenticated path to reading content: even ``/`` is gated, because a
reading history can out a reader (privacy guardrail). The only routes served
without credentials are the health/readiness probes, ``/version``, and the
login/logout pair — none of which carry reading content or name a private route.
Auth is applied per route rather than app-wide, so
``tests/test_auth.py::test_every_registered_route_is_authed_or_explicitly_public``
enumerates the whole route table and fails the build on any route that is
neither gated nor on the explicit public list. The app is single-user and binds
to localhost by default (``make dev``); deployment puts it behind the seedbox's
auth next to Calibre-Web.
Browser session auth (FIX-04): a phone/desktop browser can't attach an
``Authorization`` header on plain navigation, so ``GET /login`` renders a form
and ``POST /login`` exchanges the same bearer token for a signed, HttpOnly,
``SameSite=Strict``, ``Secure`` cookie (see :mod:`app.auth` for the signing and
TTL). ``GET /logout`` clears it. The ``Secure`` attribute means the cookie is
only ever sent by the browser over HTTPS — deployment must terminate TLS in
front of this app (the seedbox's reverse proxy) or otherwise ensure the
browser reaches it only over a secure/loopback channel, or the cookie flow
simply won't work (by design: no session ever traverses plain HTTP).
Every other route stays GET-only, so CSRF exposure elsewhere stays nil.
``POST /login`` is the one deliberate exception: putting the bearer token in a
``GET`` query string would leak it into browser history, referrers, and access
logs, which is worse than the (nil, since it only ever *creates* a session
using a secret the client already proved knowledge of, and SameSite=Strict
blocks cross-site delivery of any ambient cookie) CSRF exposure of a POST form.
Coverage note: this thin wiring is omitted from the unit-coverage gate and
verified instead by the auth access test in ``tests/test_auth.py`` via FastAPI's
TestClient.
"""
from __future__ import annotations
import hashlib
import os
import time
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from dataclasses import dataclass
from html import escape
from importlib.metadata import PackageNotFoundError
from importlib.metadata import version as _package_version
from pathlib import Path
from typing import Optional
from fastapi import Cookie, Depends, FastAPI, Form, Header, HTTPException, Request
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse, Response
from ingest.config import Config, load_config
from ingest.store import Store
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
from app import opds
from app.auth import (
SESSION_TTL_SECONDS,
LoginLockoutTracker,
check_credentials,
sign_session,
verify_session,
)
from app.logging_config import RequestLoggingMiddleware, configure_logging, get_logger
from app.security_headers import LOGIN_STYLE, SECURITY_HEADERS
from app.view import DashboardView, render_view, view_from_store
SESSION_COOKIE = "stacks_session" # noqa: S105 - cookie name, not a secret
@dataclass(frozen=True)
class _ViewCacheKey:
"""Every input that can change the process-local ``DashboardView``."""
store_path: str
refreshed_at: Optional[int]
view_revision: int
config_fields: tuple[object, ...]
hide_sensitive: bool
lens_fingerprint: tuple[str, Optional[str]]
authored_lists: tuple[object, ...]
_ViewCacheEntry = tuple[_ViewCacheKey, DashboardView]
class ConfigInvalid(Exception):
"""Raised at startup when the app configuration cannot be resolved."""
class StoreUnavailable(Exception):
"""Raised at startup when the app-state store cannot be opened or probed."""
class SecurityHeadersMiddleware(BaseHTTPMiddleware):
"""Attach the fixed defense-in-depth header set to every response.
Runs on ALL routes — dashboard, ``/browse``, ``/share``, and the
health/ready probes — including 401s from :func:`require_auth`, since
headers are applied to whatever ``call_next`` returns regardless of
status code.
"""
async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:
response = await call_next(request)
for name, value in SECURITY_HEADERS.items():
response.headers[name] = value
return response
# Process-local: single-user, single-process self-hosted app. A restart resets
# any in-progress lockouts.
_lockout = LoginLockoutTracker()
def require_auth(
authorization: Optional[str] = Header(default=None),
stacks_session: Optional[str] = Cookie(default=None),
) -> None:
"""Require a valid bearer token or signed session cookie."""
token: Optional[str] = None
if authorization and authorization.lower().startswith("bearer "):
token = authorization[len("bearer ") :].strip()
if check_credentials(token):
return
if verify_session(stacks_session, int(time.time())):
return
raise HTTPException(
status_code=401,
detail="authentication required",
headers={"WWW-Authenticate": "Bearer"},
)
def _client_ip(request: Request) -> str:
return request.client.host if request.client else "unknown"
def _render_login_page(error: Optional[str] = None) -> str:
"""Render the minimal sign-in form (same escaping + a11y discipline as the
dashboard renderer: lang, viewport, one h1, a main landmark, a skip link,
and a label linked to its input).
"""
error_html = (
f'<p id="login-error" role="alert" class="error">{escape(error)}</p>' if error else ""
)
error_attrs = ' aria-invalid="true" aria-describedby="login-error"' if error else ""
return (
"<!doctype html>"
'<html lang="en"><head><meta charset="utf-8">'
'<meta name="viewport" content="width=device-width, initial-scale=1">'
"<title>Queer the Stacks — sign in</title>"
f"<style>{LOGIN_STYLE}</style></head><body>"
'<a class="skip" href="#main">Skip to the sign-in form</a>'
'<main id="main">'
"<h1>Queer the Stacks</h1>"
"<p>Sign in with your access token to reach your private reading "
"dashboard.</p>"
f"{error_html}"
'<form method="post" action="/login">'
'<label for="token">Access token</label>'
'<input id="token" name="token" type="password" autocomplete="current-password" '
f"required autofocus{error_attrs}>"
'<button type="submit">Sign in</button>'
"</form>"
"</main></body></html>"
)
def _file_fingerprint(path: Optional[Path]) -> tuple[str, Optional[str]]:
"""Return a content-based cache stamp, including missing/error state."""
if path is None:
return ("", None)
try:
digest = hashlib.sha256(path.read_bytes()).hexdigest()
except FileNotFoundError:
digest = "missing"
except OSError as exc:
digest = f"unreadable:{type(exc).__name__}"
return (str(path), digest)
def _cache_key(
config: Config,
stamp: Optional[int],
*,
view_revision: int = 0,
hide_sensitive: bool = False,
authored_lists: tuple[object, ...] = (),
) -> _ViewCacheKey:
"""Key a view by persisted state, presentation config, and local inputs."""
return _ViewCacheKey(
store_path=str(config.store_path),
refreshed_at=stamp,
view_revision=view_revision,
config_fields=config.view_cache_fields(),
hide_sensitive=config.hide_sensitive_descriptors or hide_sensitive,
lens_fingerprint=_file_fingerprint(config.lens_config),
authored_lists=authored_lists,
)
def _load_view(app: FastAPI, *, hide_sensitive: bool = False) -> DashboardView:
"""Build or reuse the dashboard view; never run ingest inside a request."""
from recommender.lists_store import list_store_path, load_stored_lists
config = load_config()
store = Store(config.store_path)
try:
stamp = store.refreshed_at()
if stamp is None:
raise HTTPException(
status_code=503,
detail="dashboard not yet populated — run `stacks refresh` first",
)
authored_lists = load_stored_lists(list_store_path(config))
key = _cache_key(
config,
stamp,
view_revision=store.view_revision(),
hide_sensitive=hide_sensitive,
authored_lists=authored_lists,
)
cached: Optional[_ViewCacheEntry] = app.state.view_cache
if cached is not None and cached[0] == key:
return cached[1]
view = view_from_store(
store,
user="demo" if config.demo else "you",
aperture_strength=config.aperture_strength,
use_embeddings=config.embeddings_enabled,
dnf_signals=config.dnf_signals,
goal_books=config.goal_books,
goal_pages=config.goal_pages,
goal_hours=config.goal_hours,
goal_streak_days=config.goal_streak_days,
lens_config=config.lens_config,
hide_sensitive_descriptors=config.hide_sensitive_descriptors or hide_sensitive,
authored_lists=authored_lists,
demo_mode=config.demo,
)
app.state.view_cache = (key, view)
return view
finally:
store.close()
def _calibre_web_url() -> Optional[str]:
"""The optional, config-driven base URL of a sibling Calibre-Web instance.
Never hardcoded: read from ``STACKS_CALIBRE_WEB_URL`` only, and omitted
from OPDS entries entirely when unset. Used only as link text in rendered
XML — never fetched, so it introduces no egress.
"""
return os.environ.get("STACKS_CALIBRE_WEB_URL") or None
def readiness_probe() -> dict[str, str]:
"""Probe the derived-state store dependency; raise if it is unavailable.
Fail-closed: any failure to resolve config or open/query the app-state store
means the service is NOT ready to serve traffic. On success returns a
component-status map. It never returns (or lets ``/readyz`` return) a path,
an exception message, or any reading content.
"""
config = load_config()
store = Store(config.store_path)
try:
store.refreshed_at() # exercises a real SELECT against the app-state DB
finally:
store.close()
return {"store": "ok"}
@asynccontextmanager
async def _lifespan(app: FastAPI) -> AsyncIterator[None]:
"""Validate configuration and store access before accepting traffic."""
try:
config = load_config()
except Exception as exc:
raise ConfigInvalid("failed to resolve app configuration at startup") from exc
try:
store = Store(config.store_path)
try:
populated = store.refreshed_at() is not None
finally:
store.close()
except Exception as exc:
raise StoreUnavailable("app-state store is unavailable at startup") from exc
if not populated:
get_logger().warning("startup_store_unpopulated")
yield
# Route handlers are module-level (not nested inside create_app) and wired up
# via add_api_route below — the mccabe/C90 complexity gate (QW-10) counts a
# closure's branches against its enclosing function, and create_app() itself
# should stay a flat, low-complexity list of route registrations regardless of
# how many probe/route handlers exist.
def _healthz() -> dict[str, str]:
return {"status": "ok"}
def _livez() -> dict[str, str]:
"""Liveness: process is up and not deadlocked. No dependency calls."""
return {"status": "ok"}
def _version() -> dict[str, str]:
"""Report the installed package version (REL-19). No internal detail beyond semver."""
try:
return {"version": _package_version("queer-the-stacks")}
except PackageNotFoundError: # pragma: no cover - only if installed non-editable/unnamed
return {"version": "unknown"}
def _readyz() -> Response:
"""Readiness: fail closed with 503 if the app-state store is unavailable."""
try:
checks = readiness_probe()
except Exception as exc: # fail closed on ANY dependency error
# Log the failure type only — never the exception text or a path.
get_logger().warning("readyz_unavailable", extra={"error_type": type(exc).__name__})
return JSONResponse(status_code=503, content={"status": "unavailable"})
return JSONResponse(status_code=200, content={"status": "ok", "checks": checks})
def _login_form() -> HTMLResponse:
"""Render the sign-in form. Unauthenticated by necessity (it's the entry
point), but it reveals no reading content — just an empty form."""
return HTMLResponse(content=_render_login_page())
def _login_submit(request: Request, token: str = Form(...)) -> Response:
"""Exchange the bearer token for a signed session cookie.
The lone POST route in an otherwise GET-only app — see the module
docstring for why a GET-with-query-param login was rejected. Failed
attempts are rate-limited per client IP (5 / 15min) to blunt brute force.
"""
now = int(time.time())
ip = _client_ip(request)
if _lockout.is_locked_out(ip, now):
return HTMLResponse(
content=_render_login_page("Too many attempts. Try again later."),
status_code=429,
)
if not check_credentials(token):
_lockout.record_failure(ip, now)
return HTMLResponse(
content=_render_login_page("Incorrect token."),
status_code=401,
)
_lockout.reset(ip)
response = RedirectResponse(url="/", status_code=303)
response.set_cookie(
SESSION_COOKIE,
sign_session(now),
max_age=SESSION_TTL_SECONDS,
httponly=True,
secure=True,
samesite="strict",
path="/",
)
return response
def _logout() -> Response:
"""Clear the session cookie and send the browser back to /login."""
response = RedirectResponse(url="/login", status_code=303)
response.delete_cookie(
SESSION_COOKIE,
path="/",
httponly=True,
secure=True,
samesite="strict",
)
return response
def _dashboard(request: Request, hide_sensitive: bool = False) -> HTMLResponse:
return HTMLResponse(content=render_view(_load_view(request.app, hide_sensitive=hide_sensitive)))
def _browse(
request: Request,
theme: Optional[str] = None,
author: Optional[str] = None,
series: Optional[str] = None,
status: Optional[str] = None,
q: Optional[str] = None,
) -> HTMLResponse:
import dataclasses
from app.browse import filter_states
view = _load_view(request.app)
filtered = filter_states(
list(view.library),
theme=theme,
author=author,
series=series,
status=status,
q=q,
)
return HTMLResponse(
content=render_view(
dataclasses.replace(
view,
library=tuple(filtered),
browse_query=q or "",
browse_theme=theme or "",
browse_author=author or "",
browse_series=series or "",
browse_status=status or "",
)
)
)
def _share(request: Request) -> HTMLResponse:
"""Locally-composed share cards. Nothing is posted; the user copies them."""
from app.share import build_share_cards, render_share_page
view = _load_view(request.app)
cards = build_share_cards(view)
return HTMLResponse(
content=render_share_page(cards, user=view.user, fixture_states=view.fixture_states)
)
def _share_card_svg(request: Request, kind: str = "year") -> Response:
"""Serve a single share card as a self-contained SVG image for download."""
from app.share import build_share_cards
view = _load_view(request.app)
cards = build_share_cards(view)
chosen = next((c for c in cards if c.kind == kind), cards[0] if cards else None)
if chosen is None:
raise HTTPException(status_code=404, detail="no share card available")
from app.share import render_share_svg
return Response(content=render_share_svg(chosen), media_type="image/svg+xml")
def _opds_root(request: Request) -> Response:
"""Root OPDS navigation feed, browsable from KOReader/Readest."""
return Response(
content=opds.build_root_navigation(_load_view(request.app)), media_type=opds.NAV_TYPE
)
def _opds_shelf(shelf_id: str, request: Request) -> Response:
view = _load_view(request.app)
entries = opds.entries_for_shelf(shelf_id, view)
feed = opds.build_shelf_acquisition(
shelf_id,
opds.SHELF_TITLES[shelf_id],
entries,
calibre_web_url=_calibre_web_url(),
subtitle=opds.fixture_subtitle(view, shelf_id),
)
return Response(content=feed, media_type=opds.ACQ_TYPE)
def _opds_to_read(request: Request) -> Response:
return _opds_shelf("to-read", request)
def _opds_currently_reading(request: Request) -> Response:
return _opds_shelf("currently-reading", request)
def _opds_series_next(request: Request) -> Response:
return _opds_shelf("series-next", request)
def _opds_recommendations(request: Request) -> Response:
return _opds_shelf("recommendations", request)
def create_app() -> FastAPI:
# ``openapi_url=None`` belongs with ``docs_url``/``redoc_url``: without it
# FastAPI still serves ``/openapi.json``, and that document is the app's
# whole route inventory — every private path, each route's query-parameter
# names, and the session cookie name — to an anonymous caller. No reading
# content, but on a host whose contents can out its owner, publishing what
# the application *is* is itself the disclosure. The API-documentation
# surface is closed, not partly closed.
app = FastAPI(
title="Queer the Stacks",
docs_url=None,
redoc_url=None,
openapi_url=None,
lifespan=_lifespan,
)
app.state.view_cache = None
configure_logging()
app.add_middleware(RequestLoggingMiddleware)
app.add_middleware(SecurityHeadersMiddleware)
app.add_api_route("/healthz", _healthz, methods=["GET"])
app.add_api_route("/livez", _livez, methods=["GET"])
app.add_api_route("/version", _version, methods=["GET"])
app.add_api_route("/readyz", _readyz, methods=["GET"])
app.add_api_route(
"/login",
_login_form,
methods=["GET"],
response_class=HTMLResponse,
)
app.add_api_route(
"/login",
_login_submit,
methods=["POST"],
)
app.add_api_route(
"/logout",
_logout,
methods=["GET"],
)
app.add_api_route(
"/",
_dashboard,
methods=["GET"],
response_class=HTMLResponse,
dependencies=[Depends(require_auth)],
)
app.add_api_route(
"/browse",
_browse,
methods=["GET"],
response_class=HTMLResponse,
dependencies=[Depends(require_auth)],
)
app.add_api_route(
"/opds",
_opds_root,
methods=["GET"],
dependencies=[Depends(require_auth)],
)
app.add_api_route(
"/opds/to-read",
_opds_to_read,
methods=["GET"],
dependencies=[Depends(require_auth)],
)
app.add_api_route(
"/opds/currently-reading",
_opds_currently_reading,
methods=["GET"],
dependencies=[Depends(require_auth)],
)
app.add_api_route(
"/opds/series-next",
_opds_series_next,
methods=["GET"],
dependencies=[Depends(require_auth)],
)
app.add_api_route(
"/opds/recommendations",
_opds_recommendations,
methods=["GET"],
dependencies=[Depends(require_auth)],
)
app.add_api_route(
"/share",
_share,
methods=["GET"],
response_class=HTMLResponse,
dependencies=[Depends(require_auth)],
)
app.add_api_route(
"/share/card.svg",
_share_card_svg,
methods=["GET"],
dependencies=[Depends(require_auth)],
)
return app
app = create_app()