Coverage for app / middleware / cors.py: 100%
25 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1"""
2CORS policy for svc-core — an *internal* service.
4svc-core is reachable only over the private backend network: svc-bff -> svc-core,
5server to server. No browser ever loads an origin that calls it directly, so the
6browser-enforced CORS allowlist is **empty by default**. Server-to-server calls
7carry no ``Origin`` header and are unaffected; any stray cross-origin browser
8request is simply denied. ``CORS_ALLOWED_ORIGINS`` (comma-separated) is an
9explicit escape hatch should a deployment ever expose this service to a browser.
11When an origin *is* configured, the same strict rules as the edge services apply
12(explicit methods/headers, no "*", credentials, cached preflight).
13"""
15from __future__ import annotations
17from urllib.parse import urlsplit
19from starlette.middleware.cors import CORSMiddleware as CORSMiddleware
21from app.common.settings import get_settings
23CORS_ALLOW_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"]
25CORS_ALLOW_HEADERS = [
26 "Accept",
27 "Accept-Language",
28 "Content-Language",
29 "Content-Type",
30 "Authorization",
31 "X-Requested-With",
32 "X-CSRF-Token",
33]
35CORS_MAX_AGE = 600
38def _normalise_origin(value: str | None) -> str | None:
39 if not value:
40 return None
41 parts = urlsplit(value.strip().rstrip("/"))
42 if not parts.scheme or not parts.netloc:
43 return None
44 return f"{parts.scheme}://{parts.netloc}"
47def _build_origins(raw: str | None) -> list[str]:
48 seen: set[str] = set()
49 out: list[str] = []
50 for part in (raw or "").split(","):
51 origin = _normalise_origin(part)
52 if origin and origin not in seen:
53 seen.add(origin)
54 out.append(origin)
55 return out
58# Empty by default — svc-core is not browser-facing.
59origins = _build_origins(get_settings().CORS_ALLOWED_ORIGINS)
61cors_middleware_args = {
62 "allow_origins": origins,
63 "allow_credentials": True,
64 "allow_methods": CORS_ALLOW_METHODS,
65 "allow_headers": CORS_ALLOW_HEADERS,
66 "max_age": CORS_MAX_AGE,
67}