-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathconfig.py
More file actions
286 lines (232 loc) · 11.4 KB
/
Copy pathconfig.py
File metadata and controls
286 lines (232 loc) · 11.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
import logging
import os
from datetime import timedelta
from dotenv import load_dotenv
basedir = os.path.abspath(os.path.dirname(__file__))
load_dotenv()
def parse_email_allowlist(raw_string):
"""Parse EMAIL_ALLOWLIST from comma-separated string.
Args:
raw_string: Raw string from environment variable (may contain leading/trailing whitespace)
Returns:
List of lowercase email addresses if raw_string is non-empty after stripping, otherwise None.
Empty entries (from extra commas or whitespace-only tokens) are filtered out.
Emails are normalized to lowercase for case-insensitive comparison.
"""
stripped = raw_string.strip() if raw_string else ""
if not stripped:
return None
return [email.strip().lower() for email in stripped.split(",") if email.strip()]
def parse_server_name(raw_string):
"""Parse SERVER_NAME to extract domain and URL scheme.
Args:
raw_string: Raw SERVER_NAME from environment variable (may include scheme)
Returns:
Tuple of (server_name, scheme) where:
- server_name is the domain/host part (or None if empty)
- scheme is 'http' or 'https' (defaults to 'https' if not specified)
Examples:
>>> parse_server_name('https://example.com')
('example.com', 'https')
>>> parse_server_name('http://localhost:5000')
('localhost:5000', 'http')
>>> parse_server_name('example.com')
('example.com', 'https')
"""
if not raw_string:
return None, "https"
if raw_string.startswith("http://"):
return raw_string.replace("http://", ""), "http"
elif raw_string.startswith("https://"):
return raw_string.replace("https://", ""), "https"
else:
# No scheme provided, assume https for safety
return raw_string, "https"
def parse_bool_env(raw_value, default=False):
"""Parse a boolean environment variable with a safe default."""
if raw_value is None:
return default
return str(raw_value).strip().lower() in ("1", "true", "yes", "on")
def parse_int_env(raw_value, default):
"""Parse an integer environment variable with a safe default."""
if raw_value is None or str(raw_value).strip() == "":
return default
return int(raw_value)
class Config:
SECRET_KEY = os.environ.get("SECRET_KEY")
if not SECRET_KEY:
if os.environ.get("FLASK_ENV") == "development":
SECRET_KEY = "dev-key-change-this"
else:
raise ValueError(
"SECRET_KEY environment variable must be set for production. "
"Please set it in your deployment platform's environment variables. "
"You can generate one with: python -c 'import secrets; print(secrets.token_hex(32))'"
)
SQLALCHEMY_DATABASE_URI = os.environ.get("DATABASE_URL")
SQLALCHEMY_TRACK_MODIFICATIONS = False
# File Storage Configuration
# STORAGE_BACKEND must be set to either "local" or "digitalocean"
# - "local": Uses local file system (app/static/uploads/)
# - "digitalocean": Uses DigitalOcean Spaces (requires all DO_SPACES_* variables)
# Defaults to "local" in development, must be explicitly set in production/staging
STORAGE_BACKEND = os.environ.get("STORAGE_BACKEND", "").lower()
# DigitalOcean Spaces configuration (required when STORAGE_BACKEND="digitalocean")
DO_SPACES_REGION = os.environ.get("DO_SPACES_REGION")
DO_SPACES_KEY = os.environ.get("DO_SPACES_KEY")
DO_SPACES_SECRET = os.environ.get("DO_SPACES_SECRET")
DO_SPACES_BUCKET = os.environ.get("DO_SPACES_BUCKET")
def validate_storage_config(self):
"""Validate storage backend configuration."""
flask_env = os.environ.get("FLASK_ENV", "production")
# In development, default to local storage if not specified
if flask_env == "development" and not self.STORAGE_BACKEND:
self.STORAGE_BACKEND = "local"
# In production/staging, STORAGE_BACKEND must be explicitly set
if flask_env in ("production", "staging") and not self.STORAGE_BACKEND:
raise ValueError(
f"STORAGE_BACKEND must be explicitly set in {flask_env} environment. "
"Set to 'local' or 'digitalocean'."
)
# Validate STORAGE_BACKEND value
if self.STORAGE_BACKEND not in ("local", "digitalocean"):
raise ValueError(
f"Invalid STORAGE_BACKEND: '{self.STORAGE_BACKEND}'. "
"Must be 'local' or 'digitalocean'."
)
# If DigitalOcean is selected, validate all credentials are present
if self.STORAGE_BACKEND == "digitalocean":
missing_vars = []
if not self.DO_SPACES_REGION:
missing_vars.append("DO_SPACES_REGION")
if not self.DO_SPACES_KEY:
missing_vars.append("DO_SPACES_KEY")
if not self.DO_SPACES_SECRET:
missing_vars.append("DO_SPACES_SECRET")
if not self.DO_SPACES_BUCKET:
missing_vars.append("DO_SPACES_BUCKET")
if missing_vars:
raise ValueError(
f"STORAGE_BACKEND is set to 'digitalocean' but the following "
f"required environment variables are missing: {', '.join(missing_vars)}"
)
if flask_env in ("production", "staging") and not os.environ.get("DATABASE_URL"):
raise ValueError("DATABASE_URL must be set in production and staging environments.")
if flask_env in ("production", "staging") and not os.environ.get("JWT_SECRET_KEY"):
raise ValueError(
"JWT_SECRET_KEY must be explicitly set in production and staging environments "
"and must be a different value in each. Unlike session cookies, JWTs are bearer "
"tokens with no domain binding — a shared key lets tokens issued in one "
"environment authenticate against the other. "
"Generate with: python -c 'import secrets; print(secrets.token_hex(32))'"
)
# Mailgun configuration
MAILGUN_API_KEY = os.environ.get("MAILGUN_API_KEY")
MAILGUN_DOMAIN = os.environ.get("MAILGUN_DOMAIN")
MAILGUN_API_URL = (
f"https://api.mailgun.net/v3/{os.environ.get('MAILGUN_DOMAIN')}/messages"
if os.environ.get("MAILGUN_DOMAIN")
else None
)
# Email allowlist (for staging/testing - restricts who can receive emails)
# Comma-separated list of email addresses. If set, only these addresses receive emails.
# Leave empty or unset in production to send to all users.
_email_allowlist_raw = os.environ.get("EMAIL_ALLOWLIST", "").strip()
EMAIL_ALLOWLIST = parse_email_allowlist(_email_allowlist_raw)
# URL building configuration for url_for() outside request context (CLI, scheduled jobs)
# SERVER_NAME should include the scheme (http:// or https://) and domain
# Examples: https://meutch.com or http://localhost:5000
_server_name_raw = os.environ.get("SERVER_NAME", "")
SERVER_NAME, PREFERRED_URL_SCHEME = parse_server_name(_server_name_raw)
# Digest scheduler timezone (single app timezone for cadence boundaries)
TZ = os.environ.get("TZ")
DIGEST_TIMEZONE = os.environ.get("DIGEST_TIMEZONE", "UTC")
# Environment-based configuration
DEBUG = os.environ.get("FLASK_ENV") == "development"
LOG_LEVEL = logging.DEBUG if DEBUG else logging.INFO
LOG_FORMAT = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
LOG_FILE = "app.log"
# Session and persistent-login cookie configuration
_flask_env = os.environ.get("FLASK_ENV", "production").lower()
_secure_cookie_default = _flask_env in ("production", "staging")
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_SECURE = parse_bool_env(
os.environ.get("SESSION_COOKIE_SECURE"), _secure_cookie_default
)
SESSION_COOKIE_SAMESITE = os.environ.get("SESSION_COOKIE_SAMESITE", "Lax")
PERMANENT_SESSION_LIFETIME = timedelta(days=31)
REMEMBER_COOKIE_HTTPONLY = True
REMEMBER_COOKIE_SECURE = parse_bool_env(
os.environ.get("REMEMBER_COOKIE_SECURE"), _secure_cookie_default
)
REMEMBER_COOKIE_SAMESITE = os.environ.get("REMEMBER_COOKIE_SAMESITE", "Lax")
REMEMBER_COOKIE_DURATION = timedelta(days=30)
REMEMBER_COOKIE_REFRESH_EACH_REQUEST = False
API_V1_ENABLED = parse_bool_env(os.environ.get("API_V1_ENABLED"), True)
API_V1_WRITE_ENABLED = parse_bool_env(os.environ.get("API_V1_WRITE_ENABLED"), True)
API_V1_RATE_LIMITS_ENABLED = parse_bool_env(os.environ.get("API_V1_RATE_LIMITS_ENABLED"), True)
RATELIMIT_ENABLED = parse_bool_env(os.environ.get("RATELIMIT_ENABLED"), True)
RATELIMIT_HEADERS_ENABLED = True
RATELIMIT_STORAGE_URI = os.environ.get("RATELIMIT_STORAGE_URI", "memory://")
API_V1_AUTH_LOGIN_RATE_LIMIT = os.environ.get("API_V1_AUTH_LOGIN_RATE_LIMIT", "10 per minute")
API_V1_AUTH_REGISTER_RATE_LIMIT = os.environ.get(
"API_V1_AUTH_REGISTER_RATE_LIMIT", "5 per hour"
)
API_V1_AUTH_RECOVERY_RATE_LIMIT = os.environ.get(
"API_V1_AUTH_RECOVERY_RATE_LIMIT", "5 per hour"
)
API_V1_AUTH_SESSION_RATE_LIMIT = os.environ.get(
"API_V1_AUTH_SESSION_RATE_LIMIT", "60 per minute"
)
API_V1_WRITE_RATE_LIMIT = os.environ.get("API_V1_WRITE_RATE_LIMIT", "30 per minute")
API_V1_IMAGE_WRITE_RATE_LIMIT = os.environ.get("API_V1_IMAGE_WRITE_RATE_LIMIT", "10 per minute")
JWT_SECRET_KEY = os.environ.get("JWT_SECRET_KEY") or SECRET_KEY
JWT_ACCESS_TOKEN_EXPIRES = timedelta(
minutes=parse_int_env(os.environ.get("JWT_ACCESS_TOKEN_EXPIRES_MINUTES"), 15)
)
JWT_REFRESH_TOKEN_EXPIRES = timedelta(
days=parse_int_env(os.environ.get("JWT_REFRESH_TOKEN_EXPIRES_DAYS"), 30)
)
JWT_TOKEN_LOCATION = ["headers"]
JWT_HEADER_NAME = "Authorization"
JWT_HEADER_TYPE = "Bearer"
JWT_ERROR_MESSAGE_KEY = "message"
class TestingConfig(Config):
"""Configuration for testing environment"""
TESTING = True
WTF_CSRF_ENABLED = False # Disable CSRF for testing
SQLALCHEMY_DATABASE_URI = "sqlite:///:memory:"
SECRET_KEY = "test-secret-key"
STORAGE_BACKEND = "local" # Tests always use local storage
SERVER_NAME = "localhost:5000"
PREFERRED_URL_SCHEME = "http"
SESSION_COOKIE_SECURE = False
REMEMBER_COOKIE_SECURE = False
API_V1_RATE_LIMITS_ENABLED = True
API_V1_AUTH_LOGIN_RATE_LIMIT = "1000 per minute"
API_V1_AUTH_REGISTER_RATE_LIMIT = "1000 per minute"
API_V1_AUTH_RECOVERY_RATE_LIMIT = "1000 per minute"
API_V1_AUTH_SESSION_RATE_LIMIT = "1000 per minute"
API_V1_WRITE_RATE_LIMIT = "1000 per minute"
API_V1_IMAGE_WRITE_RATE_LIMIT = "1000 per minute"
class StagingConfig(Config):
"""Configuration for staging environment"""
DEBUG = False
SQLALCHEMY_DATABASE_URI = os.environ.get("DATABASE_URL")
LOG_LEVEL = logging.INFO
# SERVER_NAME and PREFERRED_URL_SCHEME inherited from base Config (parsed from SERVER_NAME env var)
class ProductionConfig(Config):
"""Configuration for production environment"""
DEBUG = False
LOG_LEVEL = logging.WARNING
# Production should always use specific environment variables
SQLALCHEMY_DATABASE_URI = os.environ.get("DATABASE_URL")
# SERVER_NAME and PREFERRED_URL_SCHEME inherited from base Config (parsed from SERVER_NAME env var)
# Configuration mapping
config = {
"development": Config,
"testing": TestingConfig,
"staging": StagingConfig,
"production": ProductionConfig,
"default": Config,
}