Astra: security review, left-on-pod ledger, chosen scenarios all run, GL navigation and Create Order popup on 26D, health check (ed9256cd4029)
348eedc verified Download coworker/api/middleware.py from EnergyVenom/patchwise-agent-studio: direct link, hf CLI and curl.
- Browser
- Download file 8.14 kB
-
https://huggingface.co/spaces/EnergyVenom/patchwise-agent-studio/resolve/main/coworker/api/middleware.py
- Command line
-
hf download hf://spaces/EnergyVenom/patchwise-agent-studio/coworker/api/middleware.py
-
curl -L -o middleware.py https://huggingface.co/spaces/EnergyVenom/patchwise-agent-studio/resolve/main/coworker/api/middleware.py
8.14 kB
| """Request IDs + structured JSON access logs + security headers (CSP, frame/sniff/referrer policies, HSTS on https).""" | |
| from __future__ import annotations | |
| import json | |
| import logging | |
| import re | |
| import secrets | |
| import sys | |
| import time | |
| from starlette.middleware.base import BaseHTTPMiddleware | |
| from starlette.requests import Request | |
| CSP_APP = ("default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; " | |
| "font-src 'self' data:; connect-src 'self'; frame-src 'self'; frame-ancestors 'self'; object-src 'none'; " | |
| "base-uri 'self'; form-action 'self'") | |
| # Swagger UI (/api/docs) loads its assets from jsDelivr; relaxed only on the docs pages. | |
| CSP_DOCS = ("default-src 'self'; script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; style-src 'self' 'unsafe-inline' " | |
| "https://cdn.jsdelivr.net; img-src 'self' data: https://fastapi.tiangolo.com; connect-src 'self'; frame-ancestors 'self'") | |
| # Reports are generated by generate_report.py with inline styles; served sandboxed inside the app. | |
| CSP_REPORT = "default-src 'none'; style-src 'unsafe-inline'; img-src data:; frame-ancestors 'self'; sandbox" | |
| class JsonFormatter(logging.Formatter): | |
| def format(self, record: logging.LogRecord) -> str: | |
| d = {"ts": time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(record.created)) + "Z", "level": record.levelname, | |
| "logger": record.name, "msg": record.getMessage()} | |
| for k in ("request_id", "method", "path", "status", "ms", "user"): | |
| if hasattr(record, k): | |
| d[k] = getattr(record, k) | |
| if record.exc_info: | |
| d["exc"] = self.formatException(record.exc_info)[-2000:] | |
| return json.dumps(d, default=str) | |
| class _HideTokens(logging.Filter): | |
| """Personal access tokens (pwt_...) never reach a log line, whatever logged them.""" | |
| _RE = re.compile(r"pwt_[A-Za-z0-9_-]{8,}") | |
| def filter(self, record: logging.LogRecord) -> bool: | |
| if isinstance(record.msg, str) and "pwt_" in record.msg: | |
| record.msg = self._RE.sub("pwt_(hidden)", record.msg) | |
| if record.args: | |
| args = record.args if isinstance(record.args, tuple) else (record.args,) | |
| if any(isinstance(x, str) and "pwt_" in x for x in args): | |
| record.args = tuple(self._RE.sub("pwt_(hidden)", x) if isinstance(x, str) else x for x in args) | |
| return True | |
| def setup_logging(level: str = "INFO", logfile=None) -> None: | |
| root = logging.getLogger() | |
| if getattr(root, "_fpt_configured", False): | |
| return | |
| h = logging.StreamHandler(sys.stderr) | |
| h.setFormatter(JsonFormatter()) | |
| h.addFilter(_HideTokens()) | |
| root.handlers = [h] | |
| if logfile: | |
| # rotated: 10 MB per file, 5 kept (the log volume is part of the saved state on hosts without a disk) | |
| from logging.handlers import RotatingFileHandler | |
| fh = RotatingFileHandler(logfile, maxBytes=10 * 1024 * 1024, backupCount=5, encoding="utf-8") | |
| fh.setFormatter(JsonFormatter()) | |
| fh.addFilter(_HideTokens()) | |
| root.addHandler(fh) | |
| root.setLevel(level) | |
| root._fpt_configured = True # type: ignore[attr-defined] | |
| access = logging.getLogger("fpt.access") | |
| class _TooLarge(Exception): | |
| pass | |
| class BodyLimit: | |
| """Refuses a request body over `limit` bytes with 413: at once from Content-Length, or while streaming when the sender | |
| gives no length (chunked), so nothing buffers an endless body. Plain ASGI so it sees the raw stream. 0 = no limit.""" | |
| def __init__(self, app, limit: int): | |
| self.app, self.limit = app, limit | |
| async def __call__(self, scope, receive, send): | |
| if scope["type"] != "http" or self.limit <= 0: | |
| return await self.app(scope, receive, send) | |
| try: | |
| declared = int(dict(scope["headers"]).get(b"content-length") or 0) | |
| except ValueError: | |
| declared = 0 | |
| started, seen, exceeded = False, 0, False | |
| def refusal() -> tuple[dict, dict]: | |
| body = json.dumps({"detail": f"the request is larger than the {self.limit:,} bytes this server accepts", "code": "TOO_LARGE"}).encode() | |
| return ({"type": "http.response.start", "status": 413, "headers": [ | |
| (b"content-type", b"application/json"), (b"content-length", str(len(body)).encode()), (b"connection", b"close")]}, | |
| {"type": "http.response.body", "body": body}) | |
| async def wrapped_send(msg): | |
| nonlocal started | |
| if exceeded: # whatever the app made of the cut-off body (a 400 for "could not parse it") becomes the 413 | |
| if msg["type"] == "http.response.start" and not started: | |
| started = True | |
| for m in refusal(): | |
| await send(m) | |
| return | |
| started = started or msg["type"] == "http.response.start" | |
| await send(msg) | |
| async def wrapped_receive(): | |
| nonlocal seen, exceeded | |
| msg = await receive() | |
| if msg["type"] == "http.request": | |
| seen += len(msg.get("body") or b"") | |
| if seen > self.limit: | |
| exceeded = True | |
| raise _TooLarge | |
| return msg | |
| if declared > self.limit: | |
| for m in refusal(): | |
| await send(m) | |
| return | |
| try: | |
| await self.app(scope, wrapped_receive, wrapped_send) | |
| except _TooLarge: | |
| if not started: | |
| for m in refusal(): | |
| await send(m) | |
| class RequestContext(BaseHTTPMiddleware): | |
| async def dispatch(self, request: Request, call_next): | |
| rid = request.headers.get("x-request-id", "")[:64] or secrets.token_hex(8) | |
| request.state.request_id = rid | |
| t0 = time.time() | |
| resp = await call_next(request) | |
| path = request.url.path | |
| resp.headers["X-Request-ID"] = rid | |
| resp.headers["X-Content-Type-Options"] = "nosniff" | |
| resp.headers["Referrer-Policy"] = "no-referrer" | |
| resp.headers["Permissions-Policy"] = "camera=(), microphone=(), geolocation=()" | |
| resp.headers["Cross-Origin-Opener-Policy"] = "same-origin" | |
| if "/report/" in path and path.endswith(("/html", "/bundle")): | |
| resp.headers["Content-Security-Policy"] = CSP_REPORT | |
| resp.headers["X-Frame-Options"] = "SAMEORIGIN" | |
| elif path.startswith("/api/docs") or path.startswith("/api/redoc"): | |
| resp.headers["Content-Security-Policy"] = CSP_DOCS | |
| resp.headers["X-Frame-Options"] = "DENY" | |
| else: | |
| resp.headers.setdefault("Content-Security-Policy", CSP_APP) | |
| resp.headers.setdefault("X-Frame-Options", "SAMEORIGIN") | |
| svc = getattr(request.app.state, "svc", None) | |
| embed = svc.cfg.embed_origin if svc is not None else "" | |
| if embed and not path.startswith(("/api/docs", "/api/redoc")): | |
| # shown inside the configured site's page: that site joins the allowed frame ancestors | |
| resp.headers["Content-Security-Policy"] = resp.headers["Content-Security-Policy"].replace( | |
| "frame-ancestors 'self'", f"frame-ancestors 'self' {embed}") | |
| del resp.headers["X-Frame-Options"] | |
| # https as the browser sees it: directly, or through a trusted proxy (FPT_TRUST_PROXY), or a server that always | |
| # uses secure cookies (FPT_COOKIE_SECURE=always, which only makes sense behind https) | |
| if request.url.scheme == "https" or (svc is not None and svc.cfg.cookie_secure == "always"): | |
| resp.headers["Strict-Transport-Security"] = "max-age=31536000" | |
| if path.startswith("/api/"): | |
| resp.headers.setdefault("Cache-Control", "no-store") | |
| user = getattr(getattr(request.state, "user", None), "username", None) | |
| if not path.endswith("/stream"): | |
| access.info("request", extra={"request_id": rid, "method": request.method, "path": path, | |
| "status": resp.status_code, "ms": int((time.time() - t0) * 1000), "user": user}) | |
| return resp | |