Coverage for app/cors.py: 97%

35 statements  

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

1""" 

2Centralised CORS policy for svc-auth. 

3 

4CORS is a *browser* control: it only matters for origins a browser has loaded 

5and then makes cross-origin, credentialed requests from. For svc-auth that is 

6the CHAIN-R web apps — the authenticated app (FRONTEND_URL) and the public site 

7(PUBLIC_URL) — which call `auth.<domain>` from a different subdomain with the 

8session cookie attached. 

9 

10Best-practice rules enforced here: 

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

12 This is mandatory whenever `allow_credentials=True`, because the browser 

13 refuses to send cookies to a wildcard origin and reflecting any Origin would 

14 defeat the protection entirely. 

15 * Origins are *derived from per-environment configuration* (FRONTEND_URL / 

16 PUBLIC_URL, already set in dev/staging/prod), so the same code is correct in 

17 every environment without hardcoded hosts or ports. 

18 * Explicit methods and request headers (not "*"), so the emitted 

19 Access-Control-Allow-* headers are deterministic and auditable. "*" is also 

20 invalid alongside credentials per the Fetch spec. 

21 * Preflight responses are cached (`max_age`) to cut preflight round-trips. 

22""" 

23 

24from __future__ import annotations 

25 

26from collections.abc import Iterable 

27from urllib.parse import urlsplit 

28 

29from starlette.middleware.cors import CORSMiddleware as CORSMiddleware 

30 

31from app.config import settings 

32 

33# Methods the web apps actually use. OPTIONS is implicit for preflight but is 

34# listed for clarity/auditability. 

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

36 

37# Request headers the browser / axios may send on credentialed calls. 

38CORS_ALLOW_HEADERS = [ 

39 "Accept", 

40 "Accept-Language", 

41 "Content-Language", 

42 "Content-Type", 

43 "Authorization", 

44 "X-Requested-With", 

45 "X-CSRF-Token", 

46] 

47 

48# Response headers the SPA is permitted to read off the response. 

49CORS_EXPOSE_HEADERS = ["X-User-Id", "X-Session-Id"] 

50 

51# Preflight cache lifetime (seconds). 

52CORS_MAX_AGE = 600 

53 

54 

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

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

57 

58 Returns ``None`` for blanks or values lacking an absolute scheme + host — a 

59 CORS origin must be absolute, so anything else is dropped rather than 

60 silently widening the allowlist. 

61 """ 

62 if not value: 

63 return None 

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

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

66 return None 

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

68 

69 

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

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

72 if not value: 

73 return [] 

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

75 

76 

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

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

79 seen: set[str] = set() 

80 out: list[str] = [] 

81 for source in sources: 

82 if source is None: 

83 continue 

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

85 for item in items: 

86 origin = normalise_origin(item) 

87 if origin and origin not in seen: 

88 seen.add(origin) 

89 out.append(origin) 

90 return out 

91 

92 

93# The browser origins allowed to call svc-auth. Derived from per-environment 

94# config; CORS_ALLOWED_ORIGINS is an explicit escape hatch for extras. 

95ALLOWED_ORIGINS = build_allowed_origins( 

96 settings.FRONTEND_URL, 

97 settings.PUBLIC_URL, 

98 split_csv(settings.CORS_ALLOWED_ORIGINS), 

99) 

100 

101cors_middleware_args = { 

102 "allow_origins": ALLOWED_ORIGINS, 

103 "allow_credentials": True, 

104 "allow_methods": CORS_ALLOW_METHODS, 

105 "allow_headers": CORS_ALLOW_HEADERS, 

106 "expose_headers": CORS_EXPOSE_HEADERS, 

107 "max_age": CORS_MAX_AGE, 

108}