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:
+81
-45
@@ -1,14 +1,14 @@
|
||||
"""Printer CRUD API — POST /printers, DELETE /printers/{id}, PATCH /printers/{id}."""
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import defaultdict
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import APIRouter, Form, Request
|
||||
from fastapi.responses import HTMLResponse, RedirectResponse
|
||||
from fastapi.responses import HTMLResponse, RedirectResponse, Response
|
||||
from fastapi.templating import Jinja2Templates
|
||||
from peewee import JOIN
|
||||
|
||||
from imptune.api.pages import group_printers_by_client
|
||||
from imptune.db.models import Client, Driver, Printer
|
||||
|
||||
router = APIRouter(prefix="/printers")
|
||||
@@ -29,6 +29,59 @@ def _error_response(message: str, status_code: int = 400) -> HTMLResponse:
|
||||
)
|
||||
|
||||
|
||||
def _validate_fields(
|
||||
name: str, ip_address: str, port_name: str, duplex_mode: str, paper_size: str
|
||||
) -> HTMLResponse | None:
|
||||
"""Shared field validation for create and update — None when everything is valid."""
|
||||
if not name:
|
||||
return _error_response("Printer name is required.")
|
||||
if not ip_address:
|
||||
return _error_response("IP address is required.")
|
||||
if not port_name:
|
||||
return _error_response("Port name is required.")
|
||||
if duplex_mode not in _VALID_DUPLEX:
|
||||
return _error_response(f"Invalid duplex mode: {duplex_mode}.")
|
||||
if paper_size not in _VALID_PAPER:
|
||||
return _error_response(f"Invalid paper size: {paper_size}.")
|
||||
return None
|
||||
|
||||
|
||||
def _resolve_client(raw: str, owner) -> tuple[int | None, HTMLResponse | None]:
|
||||
"""Resolve the optional client_id form field to an owned Client id.
|
||||
|
||||
The form value is attacker-controlled text: a non-numeric value used to
|
||||
raise ValueError (HTTP 500) instead of the 400 the HTMX form can render.
|
||||
"""
|
||||
raw = raw.strip()
|
||||
if not raw:
|
||||
return None, None
|
||||
try:
|
||||
client_fk = int(raw)
|
||||
except ValueError:
|
||||
return None, _error_response(f"Invalid client id: {raw}.")
|
||||
if Client.get_or_none((Client.id == client_fk) & (Client.owner == owner)) is None:
|
||||
return None, _error_response(f"Client {client_fk} not found.", status_code=404)
|
||||
return client_fk, None
|
||||
|
||||
|
||||
def _resolve_driver(raw: str) -> tuple[int | None, HTMLResponse | None]:
|
||||
"""Resolve the optional driver_id form field. Drivers are global/shared.
|
||||
|
||||
Existence is checked here because an unknown id otherwise reaches SQLite as
|
||||
a FOREIGN KEY violation — an IntegrityError (HTTP 500) rather than a 404.
|
||||
"""
|
||||
raw = raw.strip()
|
||||
if not raw:
|
||||
return None, None
|
||||
try:
|
||||
driver_fk = int(raw)
|
||||
except ValueError:
|
||||
return None, _error_response(f"Invalid driver id: {raw}.")
|
||||
if Driver.get_or_none(Driver.id == driver_fk) is None:
|
||||
return None, _error_response(f"Driver {driver_fk} not found.", status_code=404)
|
||||
return driver_fk, None
|
||||
|
||||
|
||||
def _render_printer_list(request: Request) -> HTMLResponse:
|
||||
"""Query printers with LEFT JOIN on client and render grouped partial."""
|
||||
import json
|
||||
@@ -40,10 +93,7 @@ def _render_printer_list(request: Request) -> HTMLResponse:
|
||||
.where(Printer.owner == owner)
|
||||
.order_by(Client.name, Printer.name)
|
||||
)
|
||||
grouped: dict[str, list[Printer]] = defaultdict(list)
|
||||
for p in query:
|
||||
client_name = p.client.name if p.client_id else "Unassigned"
|
||||
grouped[client_name].append(p)
|
||||
grouped = group_printers_by_client(query)
|
||||
|
||||
clients = list(Client.select().where(Client.owner == owner).order_by(Client.name))
|
||||
all_drivers = list(Driver.select().order_by(Driver.uploaded_at.desc()))
|
||||
@@ -71,48 +121,39 @@ def create_printer(
|
||||
collate: str = Form(""),
|
||||
client_id: str = Form(""),
|
||||
driver_id: str = Form(""),
|
||||
) -> HTMLResponse:
|
||||
) -> Response:
|
||||
"""Create a new printer configuration.
|
||||
|
||||
Boolean fields (color_mode, collate) use HTML checkbox convention:
|
||||
"on" = True, absent/empty = False.
|
||||
Redirects to /printers on success; returns an inline HTMX error fragment
|
||||
(400/404) on validation failure.
|
||||
"""
|
||||
name = name.strip()
|
||||
ip_address = ip_address.strip()
|
||||
port_name = port_name.strip()
|
||||
|
||||
if not name:
|
||||
return _error_response("Printer name is required.")
|
||||
if not ip_address:
|
||||
return _error_response("IP address is required.")
|
||||
if not port_name:
|
||||
return _error_response("Port name is required.")
|
||||
if duplex_mode not in _VALID_DUPLEX:
|
||||
return _error_response(f"Invalid duplex mode: {duplex_mode}.")
|
||||
if paper_size not in _VALID_PAPER:
|
||||
return _error_response(f"Invalid paper size: {paper_size}.")
|
||||
|
||||
# Convert checkbox values
|
||||
color_mode_bool = color_mode == "on"
|
||||
collate_bool = collate == "on"
|
||||
invalid = _validate_fields(name, ip_address, port_name, duplex_mode, paper_size)
|
||||
if invalid is not None:
|
||||
return invalid
|
||||
|
||||
owner = request.state.owner
|
||||
|
||||
# Resolve optional FK IDs — client must belong to this owner
|
||||
client_fk = int(client_id) if client_id.strip() else None
|
||||
if client_fk is not None:
|
||||
if Client.get_or_none((Client.id == client_fk) & (Client.owner == owner)) is None:
|
||||
return _error_response(f"Client {client_fk} not found.", status_code=404)
|
||||
driver_fk = int(driver_id) if driver_id.strip() else None
|
||||
client_fk, error = _resolve_client(client_id, owner)
|
||||
if error is not None:
|
||||
return error
|
||||
driver_fk, error = _resolve_driver(driver_id)
|
||||
if error is not None:
|
||||
return error
|
||||
|
||||
Printer.create(
|
||||
name=name,
|
||||
ip_address=ip_address,
|
||||
port_name=port_name,
|
||||
duplex_mode=duplex_mode,
|
||||
color_mode=color_mode_bool,
|
||||
# HTML checkbox convention: "on" = True, absent/empty = False
|
||||
color_mode=color_mode == "on",
|
||||
paper_size=paper_size,
|
||||
collate=collate_bool,
|
||||
collate=collate == "on",
|
||||
owner=owner,
|
||||
client=client_fk,
|
||||
driver=driver_fk,
|
||||
@@ -161,21 +202,16 @@ def update_printer(
|
||||
ip_address = ip_address.strip() or printer.ip_address
|
||||
port_name = port_name.strip() or printer.port_name
|
||||
|
||||
if not name:
|
||||
return _error_response("Printer name is required.")
|
||||
if not ip_address:
|
||||
return _error_response("IP address is required.")
|
||||
if not port_name:
|
||||
return _error_response("Port name is required.")
|
||||
if duplex_mode not in _VALID_DUPLEX:
|
||||
return _error_response(f"Invalid duplex mode: {duplex_mode}.")
|
||||
if paper_size not in _VALID_PAPER:
|
||||
return _error_response(f"Invalid paper size: {paper_size}.")
|
||||
invalid = _validate_fields(name, ip_address, port_name, duplex_mode, paper_size)
|
||||
if invalid is not None:
|
||||
return invalid
|
||||
|
||||
client_fk = int(client_id) if client_id.strip() else None
|
||||
if client_fk is not None:
|
||||
if Client.get_or_none((Client.id == client_fk) & (Client.owner == owner)) is None:
|
||||
return _error_response(f"Client {client_fk} not found.", status_code=404)
|
||||
client_fk, error = _resolve_client(client_id, owner)
|
||||
if error is not None:
|
||||
return error
|
||||
driver_fk, error = _resolve_driver(driver_id)
|
||||
if error is not None:
|
||||
return error
|
||||
|
||||
printer.name = name
|
||||
printer.ip_address = ip_address
|
||||
@@ -185,7 +221,7 @@ def update_printer(
|
||||
printer.paper_size = paper_size
|
||||
printer.collate = collate == "on"
|
||||
printer.client = client_fk
|
||||
printer.driver = int(driver_id) if driver_id.strip() else None
|
||||
printer.driver = driver_fk
|
||||
printer.updated_at = datetime.now(UTC).replace(tzinfo=None)
|
||||
printer.save()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user