"""Anonymous visitors on the public site: no accounts, no login. Each browser gets a random token in an HttpOnly cookie on its first request (the page itself, before any API call). Songs belong to the hash of that token, so a visitor sees only their own library and nobody can guess another visitor's songs. Running locally (not public) everything belongs to LOCAL_OWNER and no cookie is set. """ from __future__ import annotations import hashlib import re import secrets from collections.abc import Awaitable, Callable, MutableMapping from typing import Any from fastapi import HTTPException, Request from starlette.requests import cookie_parser from stemdeck.models import LOCAL_OWNER from stemdeck.settings import get_config, get_settings COOKIE_NAME = "stemdeck_visitor" COOKIE_MAX_AGE_SEC = 365 * 24 * 3600 TOKEN = re.compile(r"[A-Za-z0-9_-]{43}") # secrets.token_urlsafe(32) OWNER_SCOPE_KEY = "stemdeck.owner" # Methods that change something: on the public site they must come from the site's own pages. UNSAFE_METHODS = frozenset({"POST", "PUT", "PATCH", "DELETE"}) CONTENT_SECURITY_POLICY = ( "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; " "media-src 'self' blob:; font-src 'self' data:; connect-src 'self'; worker-src 'self'; object-src 'none'; " "base-uri 'self'; form-action 'self'; frame-ancestors 'none'" ) SECURITY_HEADERS = ( (b"x-content-type-options", b"nosniff"), (b"referrer-policy", b"same-origin"), (b"x-frame-options", b"DENY"), (b"content-security-policy", CONTENT_SECURITY_POLICY.encode()), (b"strict-transport-security", b"max-age=31536000"), ) UPLOAD_PATH = "/api/songs/upload" MULTIPART_OVERHEAD = 1024 * 1024 MAX_OTHER_BODY = 1024 * 1024 # JSON bodies (mixes, links) are tiny Scope = MutableMapping[str, Any] Message = MutableMapping[str, Any] Receive = Callable[[], Awaitable[Message]] Send = Callable[[Message], Awaitable[None]] ASGIApp = Callable[[Scope, Receive, Send], Awaitable[None]] def owner_for(token: str) -> str: """The id songs are stored under: a hash, so the database never holds a usable cookie value.""" return hashlib.sha256(f"stemdeck-visitor:{token}".encode()).hexdigest()[:32] def _header(scope: Scope, name: bytes) -> str | None: for key, value in scope.get("headers", []): if key == name: return value.decode("latin-1") return None def _cookie_token(scope: Scope) -> str | None: raw = _header(scope, b"cookie") token = cookie_parser(raw).get(COOKIE_NAME) if raw else None return token if token and TOKEN.fullmatch(token) else None def _cookie_header(token: str) -> bytes: return (f"{COOKIE_NAME}={token}; Max-Age={COOKIE_MAX_AGE_SEC}; Path=/; HttpOnly; Secure; " f"SameSite=Lax").encode("latin-1") def _body_limit_error(scope: Scope) -> tuple[int, bytes] | None: """Refuse an oversized (or unsized) request body before any of it is read or spooled to disk.""" if scope.get("method") not in UNSAFE_METHODS: return None declared = _header(scope, b"content-length") if declared is None: if _header(scope, b"transfer-encoding"): return 411, b'{"detail":"Uploads must declare their size."}' return None # no body upload = scope.get("path") == UPLOAD_PATH max_mb = get_config().max_upload_mb limit = max_mb * 1024 * 1024 + MULTIPART_OVERHEAD if upload else MAX_OTHER_BODY try: size = int(declared) except ValueError: return 400, b'{"detail":"Invalid Content-Length."}' if size > limit: detail = f"File is larger than {max_mb} MB." if upload else "Request is too large." return 413, ('{"detail":"' + detail + '"}').encode() return None def _cross_site(scope: Scope) -> bool: """True for a state-changing request sent by another site's page (its Origin is not this host).""" if scope.get("method") not in UNSAFE_METHODS: return False origin = _header(scope, b"origin") if origin is None: return False # not sent by a browser page (or a same-origin form in an old browser) host = _header(scope, b"host") or "" return origin not in (f"https://{host}", f"http://{host}") class VisitorMiddleware: """Public site only (a pass-through locally): identifies the visitor, setting the cookie when missing, refuses cross-site writes and adds a few security headers. Pure ASGI, so streamed responses (job events, audio files) pass through untouched.""" def __init__(self, app: ASGIApp) -> None: self.app = app async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: if scope["type"] != "http" or not get_settings().public: await self.app(scope, receive, send) return if _cross_site(scope): await _reject(send, 403, b'{"detail":"Requests from other sites are not allowed."}') return too_big = _body_limit_error(scope) if too_big is not None: await _reject(send, *too_big) return token = _cookie_token(scope) issued = None if token is None: token = issued = secrets.token_urlsafe(32) scope[OWNER_SCOPE_KEY] = owner_for(token) async def send_with_headers(message: Message) -> None: if message["type"] == "http.response.start": extra = [*SECURITY_HEADERS, *([(b"set-cookie", _cookie_header(issued))] if issued else [])] message = {**message, "headers": [*message.get("headers", []), *extra]} await send(message) await self.app(scope, receive, send_with_headers) async def _reject(send: Send, status: int, body: bytes) -> None: await send({"type": "http.response.start", "status": status, "headers": [(b"content-type", b"application/json"), (b"content-length", str(len(body)).encode())]}) await send({"type": "http.response.body", "body": body}) def current_owner(request: Request) -> str: """FastAPI dependency: whose songs this request may see and change.""" if not get_settings().public: return LOCAL_OWNER owner = request.scope.get(OWNER_SCOPE_KEY) if not owner: # the middleware always sets it; reaching this means it isn't installed raise HTTPException(500, "Visitor identification is not set up.") return str(owner) def client_key(request: Request) -> str: """FastAPI dependency: a hash of the visitor's network address, for per-address limits on the public site. Behind the cloud proxy the address is the last X-Forwarded-For entry (the one the proxy added; earlier entries come from the client and can be forged).""" trusted_header = get_settings().client_ip_header if trusted_header: # set only when a proxy that overwrites this header sits in front (e.g. Cloudflare) address = request.headers.get(trusted_header, "").strip() else: forwarded = request.headers.get("x-forwarded-for", "") address = forwarded.split(",")[-1].strip() if forwarded else "" if not address and request.client is not None: address = request.client.host return hashlib.sha256(f"stemdeck-client:{address or 'unknown'}".encode()).hexdigest()[:24]