Files
ImpTune/imptune/services/session.py
T
kawaandClaude Opus 5 b397d3dc3d feat: memory-only sessions on HTTP, streamed exports, UI refresh
Session

- COOKIE_SECURE=false no longer persists the owner key for ten years.
  services/session.cookie_kwargs() drops max_age in that mode, so the
  browser holds the key in memory and the session ends with the window.
  Everything still persists server-side; only the browser link is
  temporary. base.html shows a warning banner (FR/EN) and an extra
  paragraph in the onboarding modal, and the README explains the
  trade-off and the backup-key escape hatch.
- Both cookie writers (middleware, POST /session/restore) go through
  cookie_kwargs() so the policy cannot drift between them.
- The CSRF guard on /session/restore compared request.url.scheme against
  the Origin header. Behind a TLS-terminating proxy uvicorn sees http
  while the browser sends https, so every legitimate restore was
  rejected with 403. It now compares hosts only, including
  X-Forwarded-Host.
- /static/*, /favicon.ico and /robots.txt skip the middleware. Each
  cookieless hit was inserting an Owner row no browser could ever use.

Reliability

- Malformed printer-form FK fields no longer escape as HTTP 500:
  a non-numeric client_id/driver_id raised ValueError and an unknown
  driver_id hit a FOREIGN KEY constraint. Both are now 400/404 HTMX
  fragments, and the duplicated field checks moved into
  _validate_fields().
- Package exports stream. build_intunewin() encrypts the inner ZIP in
  1 MB chunks against temp files with a streaming HMAC and SHA256, and
  both endpoints serve the result with FileResponse plus a background
  cleanup task. A 100 MB driver used to be held in memory three or four
  times over per concurrent download. The byte layout is unchanged.
- FileResponse also escapes the download filename, which was previously
  interpolated raw into Content-Disposition.
- python-multipart >= 0.0.18 (CVE-2024-53981, reachable from
  /drivers/upload) and Pillow >= 10.3 (CVE-2024-28219, reachable from
  icon upload).
- icons.py reads cfg.ICONS_DIR instead of re-deriving the path from
  DATA_DIR, matching the .intunewin export.

UI

- Sidebar/topbar shell, inline SVG icon macros (partials/icons.html),
  card and data-table components, grouped printer list, and the
  dedicated /printers/new page replacing partials/printer_form.html.

Tests

- 194 pass with a bare `pytest tests/`: tests/conftest.py now forces
  cfg.COOKIE_SECURE = False like the e2e conftest already did, so the
  Secure cookie is no longer dropped over http://testserver.
- New coverage for the malformed-FK guards, the chunk-boundary cases in
  the encrypt loop (every residue mod _CHUNK plus a multi-megabyte
  payload), temp-dir cleanup after both exports, and the whole
  COOKIE_SECURE matrix.
- test_printer_edit.py located the Edit button by its translated label,
  so it only passed on English-locale machines. It now targets the
  showModal() hook, which also cuts the e2e run from 84s to 15s.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-04 17:58:49 +02:00

126 lines
4.9 KiB
Python

"""Cookie-scoped Owner session — opaque bearer key, no accounts."""
from __future__ import annotations
import secrets
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
import imptune.config as cfg
from imptune.db.models import Owner
COOKIE_NAME = "imptune_owner_key"
COOKIE_MAX_AGE = 10 * 365 * 24 * 60 * 60 # 10 years
# Paths that never need an Owner. Minting one for them means a DB write per
# request for any client that doesn't carry the cookie — asset fetches racing
# the first page load, health probes, crawlers, favicon hunts — and every row
# is dead weight, since only a browser holding the cookie can ever use it.
_UNSCOPED_PATHS = frozenset({"/health", "/favicon.ico", "/robots.txt"})
_UNSCOPED_PREFIXES = ("/static/",)
def generate_key() -> str:
return secrets.token_urlsafe(32)
def cookie_kwargs() -> dict:
"""`set_cookie` attributes for the owner key — persistent only when Secure.
With `COOKIE_SECURE=false` the key travels over plain HTTP, so persisting it
for ten years would leave a long-lived bearer credential on disk and in
cleartext traffic. Instead `max_age` is dropped: the browser holds the cookie
in memory only. The app stays fully usable and keeps remembering printers,
configs and clients for as long as the window is open — the session just
ends when the browser does, and the UI says so (see `ephemeral_session`).
The backup key remains the way to carry a session across browsers.
"""
kwargs: dict = {
"httponly": True,
"samesite": "lax",
"secure": cfg.COOKIE_SECURE,
}
if cfg.COOKIE_SECURE:
kwargs["max_age"] = COOKIE_MAX_AGE
return kwargs
def _request_hosts(request: Request) -> set[str]:
"""Every host spelling that legitimately identifies this deployment."""
hosts = {request.url.netloc}
for header in ("host", "x-forwarded-host"):
value = request.headers.get(header)
if value:
# X-Forwarded-Host may be a proxy chain: the client-facing host is first.
hosts.add(value.split(",")[0].strip())
return hosts
def is_same_origin(request: Request) -> bool:
"""Origin/Referer check — the CSRF guard for /session/restore.
Restoring a key re-points the cookie at a *different* Owner, so unlike
the rest of the app's unprotected POSTs (which only ever mutate the
caller's own data), a forged cross-site POST here is a login-CSRF /
session-fixation vector: an attacker who knows their own key can force
a victim's browser onto the attacker's Owner. Browsers always send
Origin (and usually Referer) on form POSTs, same-site or not, so
requiring a match — and rejecting when both are absent — blocks a plain
auto-submitting HTML form without needing a token.
Only the *host* is compared, not the scheme: behind a TLS-terminating
proxy the browser sends `Origin: https://host` while uvicorn sees
`http` (it only trusts X-Forwarded-Proto from `forwarded_allow_ips`,
which excludes a proxy in a sibling container), so a scheme comparison
rejected every legitimate restore in production. A same-host attacker
origin is not a capability the scheme check was buying.
"""
from urllib.parse import urlparse
hosts = _request_hosts(request)
origin = request.headers.get("origin")
if origin is not None:
return urlparse(origin).netloc in hosts
referer = request.headers.get("referer")
if referer:
return urlparse(referer).netloc in hosts
return False
class OwnerSessionMiddleware(BaseHTTPMiddleware):
"""Resolves request.state.owner from a cookie, creating one on first visit."""
async def dispatch(self, request: Request, call_next):
path = request.url.path
if path in _UNSCOPED_PATHS or path.startswith(_UNSCOPED_PREFIXES):
return await call_next(request)
key = request.cookies.get(COOKIE_NAME)
owner = Owner.get_or_none(Owner.key == key) if key else None
is_new = owner is None
if owner is None:
owner = Owner.create(key=generate_key(), is_permanent=False)
request.state.owner = owner
request.state.is_new_owner = is_new
# Templates warn about it; see cookie_kwargs().
request.state.ephemeral_session = not cfg.COOKIE_SECURE
response = await call_next(request)
# Routes like /session/restore intentionally set this cookie themselves
# (to a *different* owner than the one this middleware just minted) —
# don't clobber that with the auto-provisioned one.
route_already_set_cookie = any(
header.lower() == b"set-cookie" and value.startswith(f"{COOKIE_NAME}=".encode())
for header, value in response.raw_headers
)
if is_new and not route_already_set_cookie:
response.set_cookie(COOKIE_NAME, owner.key, **cookie_kwargs())
return response