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>
This commit is contained in:
@@ -173,7 +173,11 @@ def parse_inf(inf_text: str, inf_filename: str, zip_names: list[str]) -> ParsedI
|
||||
for key, _val in parser.items(section):
|
||||
if key.startswith("__bare_"):
|
||||
continue
|
||||
resolved = _resolve_tokens(key, strings)
|
||||
# DriverDesc keys are sometimes quoted directly in the INF
|
||||
# (e.g. `"Canon Generic PCL6" = SectionName, HardwareID`)
|
||||
# instead of via %TOKEN%; configparser keeps those quotes as
|
||||
# part of the key, so strip them same as [Strings] values.
|
||||
resolved = _resolve_tokens(key, strings).strip('"')
|
||||
# Skip empty, purely numeric, or clearly non-driver-name entries
|
||||
if resolved and not resolved.isdigit():
|
||||
driver_names.add(resolved)
|
||||
|
||||
+56
-15
@@ -12,11 +12,50 @@ 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.
|
||||
|
||||
@@ -28,19 +67,25 @@ def is_same_origin(request: Request) -> bool:
|
||||
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.
|
||||
"""
|
||||
expected = f"{request.url.scheme}://{request.url.netloc}"
|
||||
from urllib.parse import urlparse
|
||||
|
||||
hosts = _request_hosts(request)
|
||||
|
||||
origin = request.headers.get("origin")
|
||||
if origin is not None:
|
||||
return origin == expected
|
||||
return urlparse(origin).netloc in hosts
|
||||
|
||||
referer = request.headers.get("referer")
|
||||
if referer:
|
||||
from urllib.parse import urlparse
|
||||
|
||||
parsed = urlparse(referer)
|
||||
return f"{parsed.scheme}://{parsed.netloc}" == expected
|
||||
return urlparse(referer).netloc in hosts
|
||||
|
||||
return False
|
||||
|
||||
@@ -49,7 +94,8 @@ class OwnerSessionMiddleware(BaseHTTPMiddleware):
|
||||
"""Resolves request.state.owner from a cookie, creating one on first visit."""
|
||||
|
||||
async def dispatch(self, request: Request, call_next):
|
||||
if request.url.path == "/health":
|
||||
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)
|
||||
@@ -60,6 +106,8 @@ class OwnerSessionMiddleware(BaseHTTPMiddleware):
|
||||
|
||||
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)
|
||||
|
||||
@@ -72,13 +120,6 @@ class OwnerSessionMiddleware(BaseHTTPMiddleware):
|
||||
)
|
||||
|
||||
if is_new and not route_already_set_cookie:
|
||||
response.set_cookie(
|
||||
COOKIE_NAME,
|
||||
owner.key,
|
||||
max_age=COOKIE_MAX_AGE,
|
||||
httponly=True,
|
||||
samesite="lax",
|
||||
secure=cfg.COOKIE_SECURE,
|
||||
)
|
||||
response.set_cookie(COOKIE_NAME, owner.key, **cookie_kwargs())
|
||||
|
||||
return response
|
||||
|
||||
Reference in New Issue
Block a user