Coverage for src/couchers/config.py: 55%

53 statements  

« prev     ^ index     » next       coverage.py v7.11.0, created at 2025-11-30 02:12 +0000

1""" 

2A simple config system 

3""" 

4 

5import os 

6from typing import Any 

7 

8CONFIG_T = list[tuple[str, type | list[str]] | tuple[str, type | list[str], str | int]] 

9 

10# Allowed config options, as tuples (name, type, default). 

11# All fields are required 

12CONFIG_OPTIONS: CONFIG_T = [ 

13 # Whether we're in dev mode 

14 ("DEV", bool), 

15 # Whether we're `api` mode (answering API queries) or `scheduler` (scheduling background jobs), or `worker` 

16 # (servicing background jobs). Can also be set to `all` to do all three simultaneously 

17 ("ROLE", ["api", "scheduler", "worker", "all"], "all"), 

18 # number of bg worker processes, requires worker or all above 

19 ("BACKGROUND_WORKER_COUNT", int, 2), 

20 # Version string 

21 ("VERSION", str, "unknown"), 

22 # Base URL of frontend, e.g. https://couchers.org 

23 ("BASE_URL", str), 

24 # URL of the backend, e.g. https://api.couchers.org 

25 ("BACKEND_BASE_URL", str), 

26 # URL of the console, e.g. https://console.couchers.org 

27 ("CONSOLE_BASE_URL", str), 

28 # URL of the merch shop, e.g. https://shop.couchershq.org 

29 ("MERCH_SHOP_URL", str), 

30 # Used to generate a variety of secrets 

31 ("SECRET", bytes), 

32 # Domain that cookies should set as their domain value 

33 ("COOKIE_DOMAIN", str), 

34 # SQLAlchemy database connection string 

35 ("DATABASE_CONNECTION_STRING", str), 

36 # OpenTelemetry endpoint to send traces to 

37 ("OPENTELEMETRY_ENDPOINT", str, ""), 

38 # Path to a GeoLite2-City.mmdb file for geocoding IPs in user session info 

39 ("GEOLITE2_CITY_MMDB_FILE_LOCATION", str, ""), 

40 ("GEOLITE2_ASN_MMDB_FILE_LOCATION", str, ""), 

41 # Whether to try adding dummy data 

42 ("ADD_DUMMY_DATA", bool), 

43 # Donations 

44 ("ENABLE_DONATIONS", bool), 

45 ("STRIPE_API_KEY", str), 

46 ("STRIPE_WEBHOOK_SECRET", str), 

47 ("STRIPE_RECURRING_PRODUCT_ID", str), 

48 # Strong verification through Iris ID 

49 ("ENABLE_STRONG_VERIFICATION", bool), 

50 ("IRIS_ID_PUBKEY", str), 

51 ("IRIS_ID_SECRET", str), 

52 ("VERIFICATION_DATA_PUBLIC_KEY", bytes), 

53 # Postal verification 

54 ("ENABLE_POSTAL_VERIFICATION", bool), 

55 # SMS 

56 ("ENABLE_SMS", bool), 

57 ("SMS_SENDER_ID", str), 

58 # Email 

59 ("ENABLE_EMAIL", bool), 

60 # Sender name for outgoing notification emails e.g. "Couchers.org" 

61 ("NOTIFICATION_EMAIL_SENDER", str), 

62 # Sender email, e.g. "notify@couchers.org" 

63 ("NOTIFICATION_EMAIL_ADDRESS", str), 

64 # An optional prefix for email subject, e.g. [STAGING] 

65 ("NOTIFICATION_PREFIX", str, ""), 

66 # Address to send emails about reported users 

67 ("REPORTS_EMAIL_RECIPIENT", str), 

68 # Address to send contributor forms when users sign up/fill the form 

69 ("CONTRIBUTOR_FORM_EMAIL_RECIPIENT", str), 

70 # Address to moderation notifications 

71 ("MODS_EMAIL_RECIPIENT", str), 

72 # SMTP settings 

73 ("SMTP_HOST", str), 

74 ("SMTP_PORT", int), 

75 ("SMTP_USERNAME", str), 

76 ("SMTP_PASSWORD", str), 

77 # Media server 

78 ("ENABLE_MEDIA", bool), 

79 ("MEDIA_SERVER_SECRET_KEY", bytes), 

80 ("MEDIA_SERVER_BEARER_TOKEN", str), 

81 ("MEDIA_SERVER_BASE_URL", str), 

82 ("MEDIA_SERVER_UPLOAD_BASE_URL", str), 

83 # Bug reporting tool 

84 ("BUG_TOOL_ENABLED", bool), 

85 ("BUG_TOOL_GITHUB_REPO", str), 

86 ("BUG_TOOL_GITHUB_USERNAME", str), 

87 ("BUG_TOOL_GITHUB_TOKEN", str), 

88 # Sentry 

89 ("SENTRY_ENABLED", bool), 

90 ("SENTRY_URL", str), 

91 # Push notifications 

92 ("PUSH_NOTIFICATIONS_ENABLED", bool), 

93 ("PUSH_NOTIFICATIONS_VAPID_PRIVATE_KEY", str), 

94 ("PUSH_NOTIFICATIONS_VAPID_SUBJECT", str), 

95 # Whether to initiate new activeness probes 

96 ("ACTIVENESS_PROBES_ENABLED", bool), 

97 # Listmonk (mailing list) 

98 ("LISTMONK_ENABLED", bool), 

99 ("LISTMONK_BASE_URL", str), 

100 ("LISTMONK_API_USERNAME", str), 

101 ("LISTMONK_API_KEY", str), 

102 ("LISTMONK_LIST_ID", int), 

103 # Google recaptcha antibot 

104 ("RECAPTHCA_ENABLED", bool), 

105 ("RECAPTHCA_PROJECT_ID", str), 

106 ("RECAPTHCA_API_KEY", str), 

107 ("RECAPTHCA_SITE_KEY", str), 

108 # Whether we're in test 

109 ("IN_TEST", bool, "0"), 

110] 

111 

112 

113def check_config(cfg: dict[str, Any]) -> None: 

114 for name, *_ in CONFIG_OPTIONS: 

115 if name not in cfg: 

116 raise ValueError(f"Required config value {name} not set") 

117 

118 if not cfg["DEV"]: 

119 # checks for prod 

120 if "https" not in cfg["BASE_URL"]: 

121 raise Exception("Production site must be over HTTPS") 

122 if not cfg["ENABLE_EMAIL"]: 

123 raise Exception("Production site must have email enabled") 

124 if not cfg["ENABLE_SMS"]: 

125 raise Exception("Production site must have SMS enabled") 

126 if cfg["IN_TEST"]: 

127 raise Exception("IN_TEST while not DEV") 

128 

129 if cfg["ENABLE_DONATIONS"]: 

130 if not cfg["STRIPE_API_KEY"] or not cfg["STRIPE_WEBHOOK_SECRET"] or not cfg["STRIPE_RECURRING_PRODUCT_ID"]: 

131 raise Exception("No Stripe API key/recurring donation ID but donations enabled") 

132 

133 if cfg["ENABLE_STRONG_VERIFICATION"]: 

134 if not cfg["IRIS_ID_PUBKEY"] or not cfg["IRIS_ID_SECRET"] or not cfg["VERIFICATION_DATA_PUBLIC_KEY"]: 

135 raise Exception("No Iris ID pubkey/secret or verification data pubkey but strong verification enabled") 

136 

137 

138def make_config() -> dict[str, Any]: 

139 cfg = {} 

140 

141 for config_option in CONFIG_OPTIONS: 

142 if len(config_option) == 2: 

143 name, type_ = config_option 

144 optional = False 

145 elif len(config_option) == 3: 

146 name, type_, default_value = config_option 

147 optional = True 

148 else: 

149 raise ValueError("Invalid CONFIG_OPTIONS") 

150 

151 value: str | int | bytes | None = os.getenv(name) 

152 

153 if not value: 

154 if not optional: 

155 # config value not set - will cause a KeyError when trying 

156 # to access it. 

157 continue 

158 else: 

159 value = default_value 

160 

161 if type_ is bool: 

162 # 1 is true, 0 is false, everything else is illegal 

163 if value not in ["0", "1"]: 

164 raise ValueError(f'Invalid bool for {name}, need "0" or "1"') 

165 value = value == "1" 

166 elif type_ is bytes: 

167 # decode from hex 

168 if not isinstance(value, str): 

169 raise RuntimeError(type(value)) 

170 value = bytes.fromhex(value) 

171 elif isinstance(type_, list): 

172 # list of allowed string values 

173 if value not in type_: 

174 raise ValueError(f"Invalid value for {name}, need one of {', '.join(type_)}") 

175 else: 

176 value = type_(value) 

177 

178 cfg[name] = value 

179 

180 return cfg 

181 

182 

183config = make_config()