"""Serving what was kept at signed links (ADR-0004). Every route checks the link's signature against the path it was made for; anything else is refused.""" from __future__ import annotations from starlette.requests import Request from starlette.responses import JSONResponse, Response from starlette.routing import Route from orchestration.delivery import Delivery def kept_routes(delivery: Delivery) -> list[Route]: store = delivery.store def signed(request: Request) -> bool: # The path as the link carried it: a name is signed as it was quoted. raw = request.scope.get("raw_path") path = raw.decode("latin-1") if isinstance(raw, bytes) else request.url.path return delivery.signer.verify( path, request.query_params.get("exp"), request.query_params.get("sig") ) def refused() -> JSONResponse: return JSONResponse({"error": "This link is not valid."}, status_code=403) def missing() -> JSONResponse: return JSONResponse({"error": "Nothing is kept here."}, status_code=404) async def case(request: Request) -> Response: if not signed(request): return refused() tenant, name = request.path_params["tenant"], request.path_params["case"] return JSONResponse( { "tenant": tenant, "customer_case": name, "executions": [delivery.shown(r) for r in store.case(tenant, name)], } ) async def execution(request: Request) -> Response: if not signed(request): return refused() p = request.path_params record = store.record(p["tenant"], p["case"], p["execution_id"]) return JSONResponse(delivery.shown(record)) if record else missing() async def file(request: Request) -> Response: if not signed(request): return refused() p = request.path_params found = store.file(p["tenant"], p["case"], p["execution_id"], p["name"]) if found is None: return missing() content, media_type = found return Response(content, media_type=media_type) async def latest(request: Request) -> Response: if not signed(request): return refused() p = request.path_params record = store.latest(p["tenant"], p["case"], p["work"]) return JSONResponse(delivery.shown(record)) if record else missing() case_path = "/tenants/{tenant}/cases/{case}" return [ Route(case_path, case, methods=["GET"]), Route(f"{case_path}/executions/{{execution_id}}", execution, methods=["GET"]), Route( f"{case_path}/executions/{{execution_id}}/files/{{name:path}}", file, methods=["GET"], ), Route(f"{case_path}/latest/{{work}}", latest, methods=["GET"]), ]