Coverage for app / middleware / cors.py: 100%

25 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-10-31 11:23 +0000

1""" 

2CORS policy for svc-ai — an *internal* service. 

3 

4svc-ai is reachable only over the private backend network: svc-core -> svc-ai, 

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 denied. ``CORS_ALLOWED_ORIGINS`` (comma-separated) is an explicit 

9escape hatch should a deployment ever expose this service to a browser. 

10 

11When an origin *is* configured, the same strict rules as the edge services apply 

12(explicit methods/headers, no "*", credentials, cached preflight). 

13""" 

14 

15from __future__ import annotations 

16 

17from urllib.parse import urlsplit 

18 

19from starlette.middleware.cors import CORSMiddleware as CORSMiddleware 

20 

21from app.common.settings import get_settings 

22 

23CORS_ALLOW_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"] 

24 

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] 

34 

35CORS_MAX_AGE = 600 

36 

37 

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}" 

45 

46 

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 

56 

57 

58# Empty by default — svc-ai is not browser-facing. 

59origins = _build_origins(get_settings().CORS_ALLOWED_ORIGINS) 

60 

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}