Coverage for app/cors.py: 88%

34 statements  

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

1""" 

2Centralised CORS policy for svc-bff. 

3 

4In the normal request path the SPA reaches svc-bff *same-origin*: the browser 

5loads ``app.<domain>`` and calls ``app.<domain>/api/*``, which nginx proxies to 

6svc-bff. Same-origin requests are not subject to CORS at all. This policy is 

7therefore defence-in-depth — correct headers for the (rare) genuinely 

8cross-origin call and a clean, auditable allowlist rather than reflected "*". 

9 

10Best-practice rules enforced here: 

11 * Strict origin allowlist — never "*" and never reflect an arbitrary Origin, 

12 which is mandatory alongside ``allow_credentials=True``. 

13 * Origins are derived from per-environment config (FRONTEND_URL / PUBLIC_URL), 

14 so the same code is correct in dev/staging/prod without hardcoded hosts/ports. 

15 * Explicit methods and headers (not "*"), so the emitted Access-Control-Allow-* 

16 headers are deterministic. "*" is also invalid with credentials per the spec. 

17 * Preflight responses are cached (``max_age``). 

18""" 

19 

20from __future__ import annotations 

21 

22from collections.abc import Iterable 

23from urllib.parse import urlsplit 

24 

25from starlette.middleware.cors import CORSMiddleware as CORSMiddleware 

26 

27from app.config import settings 

28 

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

30 

31CORS_ALLOW_HEADERS = [ 

32 "Accept", 

33 "Accept-Language", 

34 "Content-Language", 

35 "Content-Type", 

36 "Authorization", 

37 "X-Requested-With", 

38 "X-CSRF-Token", 

39] 

40 

41# Preflight cache lifetime (seconds). 

42CORS_MAX_AGE = 600 

43 

44 

45def normalise_origin(value: str | None) -> str | None: 

46 """Reduce a URL/origin string to a bare ``scheme://host[:port]`` origin. 

47 

48 Returns ``None`` for blanks or values lacking an absolute scheme + host, so 

49 malformed config never silently widens the allowlist. 

50 """ 

51 if not value: 

52 return None 

53 parts = urlsplit(value.strip().rstrip("/")) 

54 if not parts.scheme or not parts.netloc: 

55 return None 

56 return f"{parts.scheme}://{parts.netloc}" 

57 

58 

59def split_csv(value: str | None) -> list[str]: 

60 """Split a comma-separated env string into trimmed, non-empty parts.""" 

61 if not value: 

62 return [] 

63 return [part.strip() for part in value.split(",") if part.strip()] 

64 

65 

66def build_allowed_origins(*sources: str | Iterable[str] | None) -> list[str]: 

67 """Normalise, de-duplicate (order-preserving) and collect origin sources.""" 

68 seen: set[str] = set() 

69 out: list[str] = [] 

70 for source in sources: 

71 if source is None: 

72 continue 

73 items: Iterable[str] = [source] if isinstance(source, str) else source 

74 for item in items: 

75 origin = normalise_origin(item) 

76 if origin and origin not in seen: 

77 seen.add(origin) 

78 out.append(origin) 

79 return out 

80 

81 

82ALLOWED_ORIGINS = build_allowed_origins( 

83 settings.FRONTEND_URL, 

84 settings.PUBLIC_URL, 

85 split_csv(settings.CORS_ALLOWED_ORIGINS), 

86) 

87 

88cors_middleware_args = { 

89 "allow_origins": ALLOWED_ORIGINS, 

90 "allow_credentials": True, 

91 "allow_methods": CORS_ALLOW_METHODS, 

92 "allow_headers": CORS_ALLOW_HEADERS, 

93 "max_age": CORS_MAX_AGE, 

94}