Coverage for app/config.py: 84%

82 statements  

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

1# svc-bff/config.py (advanced version) 

2from pydantic_settings import BaseSettings 

3from typing import Optional, Literal 

4from functools import lru_cache 

5 

6 

7class BaseConfig(BaseSettings): 

8 """Base configuration shared across all environments.""" 

9 

10 # Redis 

11 REDIS_URL: str = "redis://redis:6379" 

12 REDIS_PASSWORD: Optional[str] = None 

13 

14 # Backend API 

15 BACKEND_API_URL: str = "http://svc-core:8080" 

16 

17 # Session 

18 SESSION_SECRET: str 

19 SESSION_MAX_AGE: int = 86400 

20 SESSION_COOKIE_NAME: str = "sid" 

21 

22 # Application 

23 ENVIRONMENT: Literal["development", "staging", "production"] = "development" 

24 # Browser origins of the web apps. In practice the SPA reaches svc-bff 

25 # same-origin via nginx (/api/* on app.<domain>), so CORS rarely fires here; 

26 # these are still honoured for defence-in-depth and any direct cross-origin 

27 # call. Set per-environment (dev defaults below; SSM/dotenv in staging/prod). 

28 FRONTEND_URL: str = "http://app.dev.datachainr.com:8000" 

29 PUBLIC_URL: str = "http://dev.datachainr.com:8000" 

30 

31 # Proxy 

32 PROXY_TIMEOUT: int = 120 # generous for file uploads (multipart can be slow) 

33 # LLM-backed routes (agent generation, prompts) legitimately run for 

34 # minutes — see _proxy_timeout_for() in main.py. Kept >= the frontend's 

35 # 180s per-request timeout so the browser times out first. 

36 PROXY_TIMEOUT_LONG: int = 180 

37 MAX_UPLOAD_SIZE: int = 52428800 # 50 MB 

38 

39 # CORS: additional browser origins allowed to call this service with 

40 # credentials, beyond FRONTEND_URL / PUBLIC_URL. Comma-separated string so it 

41 # round-trips cleanly through env/SSM (see app/cors.py). 

42 CORS_ALLOWED_ORIGINS: str = "" 

43 

44 # Security 

45 COOKIE_SECURE: bool = False 

46 COOKIE_SAMESITE: Literal["lax", "strict", "none"] = "lax" 

47 COOKIE_DOMAIN: Optional[str] = ".dev.datachainr.com" 

48 

49 # Internal service-to-service auth (audience-bound short-lived JWTs). 

50 # When INTERNAL_JWT_SECRET is set, svc-bff mints a signed token per 

51 # downstream request so svc-core can verify the caller rather than 

52 # blindly trusting forwarded identity headers. 

53 INTERNAL_JWT_SECRET: Optional[str] = None 

54 INTERNAL_JWT_ISSUER: str = "svc-bff" 

55 INTERNAL_JWT_AUDIENCE: str = "svc-core" 

56 INTERNAL_JWT_TTL: int = 120 # seconds — short-lived 

57 

58 @property 

59 def internal_auth_active(self) -> bool: 

60 return bool(self.INTERNAL_JWT_SECRET) 

61 

62 # Logging 

63 LOG_LEVEL: str = "INFO" 

64 

65 class Config: 

66 env_file = ".env" 

67 case_sensitive = True 

68 

69 

70class DevelopmentConfig(BaseConfig): 

71 """Development-specific configuration.""" 

72 

73 ENVIRONMENT: Literal["development"] = "development" 

74 COOKIE_SECURE: bool = False 

75 LOG_LEVEL: str = "DEBUG" 

76 

77 

78class StagingConfig(BaseConfig): 

79 """Staging-specific configuration.""" 

80 

81 ENVIRONMENT: Literal["staging"] = "staging" 

82 COOKIE_SECURE: bool = True 

83 COOKIE_SAMESITE: Literal["lax"] = "lax" 

84 LOG_LEVEL: str = "INFO" 

85 SESSION_MAX_AGE: int = 43200 # 12 hours 

86 

87 

88class ProductionConfig(BaseConfig): 

89 """Production-specific configuration.""" 

90 

91 ENVIRONMENT: Literal["production"] = "production" 

92 COOKIE_SECURE: bool = True 

93 COOKIE_SAMESITE: Literal["lax"] = "lax" 

94 LOG_LEVEL: str = "WARNING" 

95 SESSION_MAX_AGE: int = 43200 # 12 hours 

96 MAX_UPLOAD_SIZE: int = 10485760 # 10MB 

97 PROXY_TIMEOUT: int = 20 

98 

99 

100@lru_cache() 

101def get_settings() -> BaseConfig: 

102 """ 

103 Get settings based on ENVIRONMENT variable. 

104 Cached for performance. 

105 """ 

106 import os 

107 

108 env = os.getenv("ENVIRONMENT", "development").lower() 

109 

110 config_map = { 

111 "development": DevelopmentConfig, 

112 "staging": StagingConfig, 

113 "production": ProductionConfig, 

114 } 

115 

116 config_class = config_map.get(env, DevelopmentConfig) 

117 return config_class() 

118 

119 

120# Export settings 

121settings = get_settings() 

122 

123 

124# Environments where service-to-service auth is mandatory and a misconfiguration 

125# must hard-fail startup rather than silently degrade. 

126STRICT_ENVIRONMENTS = {"staging", "production"} 

127 

128 

129# Validation 

130def validate_settings(): 

131 """Validate settings on startup.""" 

132 if settings.ENVIRONMENT in STRICT_ENVIRONMENTS: 

133 # Internal service-to-service auth is mandatory outside dev. 

134 if not settings.INTERNAL_JWT_SECRET: 

135 raise ValueError( 

136 f"INTERNAL_JWT_SECRET must be set in {settings.ENVIRONMENT} for " 

137 "service-to-service authentication" 

138 ) 

139 

140 if len(settings.INTERNAL_JWT_SECRET) < 32: 

141 raise ValueError("INTERNAL_JWT_SECRET must be at least 32 characters") 

142 

143 if settings.ENVIRONMENT == "production": 

144 if not settings.COOKIE_SECURE: 

145 raise ValueError("COOKIE_SECURE must be True in production") 

146 

147 if len(settings.SESSION_SECRET) < 32: 

148 raise ValueError("SESSION_SECRET must be at least 32 characters") 

149 

150 if "localhost" in str(settings.COOKIE_DOMAIN): 

151 raise ValueError("COOKIE_DOMAIN cannot be localhost in production") 

152 

153 if settings.PROXY_TIMEOUT < 1: 

154 raise ValueError("PROXY_TIMEOUT must be at least 1 second") 

155 

156 if settings.MAX_UPLOAD_SIZE < 1024: 

157 raise ValueError("MAX_UPLOAD_SIZE must be at least 1KB") 

158 

159 

160# Run validation 

161try: 

162 validate_settings() 

163except ValueError as e: 

164 import logging 

165 

166 logging.error(f"Configuration validation failed: {e}") 

167 # Hard-fail in any environment that mandates secure config. 

168 if settings.ENVIRONMENT in STRICT_ENVIRONMENTS: 

169 raise