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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
|
# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
#
# SPDX-License-Identifier: BSD-3-Clause
"""Define application settings for production, development, and testing."""
import logging
from urllib.parse import urlsplit
from flask.config import Config
from .hostname import normalize_hostname
MIN_SECRET_KEY_LENGTH = 32
# Only supported, validated PRAGMAs may be passed to SQLite's connect event.
# None means "leave SQLite's own default unchanged". Override individual
# entries through SQLITE_PRAGMAS in the deployment config.
DEFAULT_SQLITE_PRAGMAS: dict[str, bool | int | str | None] = {
"foreign_keys": True,
"journal_mode": "WAL",
"busy_timeout": 5000, # Milliseconds; matches sqlite3's default timeout.
"trusted_schema": False,
"synchronous": None, # Keep SQLite's durability default unless requested.
"cache_size": None, # Positive = pages; negative = approximate KiB.
"wal_autocheckpoint": None, # Pages; SQLite defaults to 1000.
"journal_size_limit": None, # Bytes; -1 removes the size limit.
}
SQLITE_JOURNAL_MODES = frozenset({"DELETE", "TRUNCATE", "PERSIST", "WAL"})
SQLITE_SYNCHRONOUS_MODES = frozenset({"OFF", "NORMAL", "FULL", "EXTRA"})
SQLITE_INT_MAX = 2**31 - 1
SQLITE_INT64_MAX = 2**63 - 1
class DefaultConfig:
# Application
TESTING = False
DEBUG = False
BOOTSTRAP_SERVE_LOCAL = True
# BOOTSTRAP_BOOTSWATCH_THEME = "Materia"
# Security and reverse proxy
# Production must provide a persistent, random key through configuration.
SECRET_KEY = None
# Secure by default; deployment configuration can override these values.
SESSION_COOKIE_SECURE = True
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_SAMESITE = "Lax"
# Number of trusted reverse-proxy hops for X-Forwarded-For/Proto.
# 0 (default) means forwarded headers are not trusted.
PROXY_FIX_TRUSTED_HOPS = 0
# Database
SQLALCHEMY_DATABASE_URI = "sqlite:///webmentions-ssg.db"
SQLITE_PRAGMAS = DEFAULT_SQLITE_PRAGMAS
# Logging
LOG_FILE = "/var/log/webmentions-ssg.log"
LOG_LEVEL = logging.INFO
LOG_FORMAT = "[%(asctime)s]:%(levelname)s:%(name)s %(message)s"
LOG_FILE_MAX_BYTES = 20_000_000
LOG_FILE_BACKUP_COUNT = 10
# Background tasks (Huey)
# HUEY_URL is intentionally unset; production must configure a persistent queue.
# Outbound HTTP requests (shared by receiver and sender)
REQUEST_TIMEOUT_SECONDS = 5.0
# Absolute wall-clock budget for each verification or delivery attempt.
REQUEST_TOTAL_TIMEOUT_SECONDS = 30.0
MAX_REDIRECTS = 20
# Receiver
# Empty by default: no target hostnames are accepted until configured.
ALLOWED_TARGET_HOSTNAMES = frozenset()
# When enabled, only source domains listed in AllowedDomain are accepted.
# Entries in BlockedDomain always take precedence.
ALLOWLIST_ENABLED = False
# Cap incoming HTTP request bodies (also applies to other Flask routes).
MAX_CONTENT_LENGTH = 64 * 1024
# Independent UTF-8 byte limit for each submitted source/target URL.
MAX_WEBMENTION_URL_BYTES = 8192
MAX_RECEIVED_SOURCE_BYTES = 1_000_000
# Requeue abandoned verification attempts after 15 minutes.
VERIFICATION_STALE_AFTER_SECONDS = 900
# Maximum automatic recoveries of a stale received/verifying row.
VERIFICATION_MAX_RECOVERIES = 3
VERIFICATION_RECOVERY_SCHEDULE = "*/5 * * * *"
# Purge terminal failed/source-removed received Webmentions after 30 days.
RECEIVED_RETENTION_DAYS = 30
# Maximum rows that an admin can request per received Webmentions page.
RECEIVED_MAX_PAGE_SIZE = 100
# Maximum rows that an admin can request per source document page.
SOURCES_MAX_PAGE_SIZE = 100
RECEIVED_RETENTION_SCHEDULE = "0 3 * * *"
# Scanner
SITE_OUTPUT_DIRECTORY = None
SITE_BASE_URL = None
SOURCE_SCAN_SCHEDULE = "0 * * * *"
# Sender
IGNORED_TARGET_HOSTNAMES = ()
MAX_DISCOVERY_TARGET_BYTES = 1_000_000
# Total send attempts per source revision (not additional retries).
SEND_MAX_ATTEMPTS = 6
SEND_RETRY_BASE_SECONDS = 3600
SEND_RETRY_MAX_SECONDS = 86400
# Rate limiting
RATELIMIT_STORAGE_URI = "memory://"
RATELIMIT_HEADERS_ENABLED = True
ENDPOINT_RATE_LIMIT = "10/minute;100/hour"
ENDPOINT_GLOBAL_RATE_LIMIT = "1000/hour"
ENDPOINT_REVERIFY_COOLDOWN_SECONDS = 600
LOGIN_RATE_LIMIT = "5/minute;30/hour"
# Separate cross-IP limit for each submitted username (hashed in storage).
LOGIN_USERNAME_RATE_LIMIT = "20/minute;100/hour"
# Email notifications
DIGEST_EMAIL = None
DIGEST_SCHEDULE = "0 8 * * *"
# Mail (SMTP)
MAIL_SERVER = "localhost"
MAIL_PORT = 25
MAIL_USE_TLS = False
MAIL_USE_SSL = False
MAIL_USERNAME = None
MAIL_PASSWORD = None
MAIL_DEFAULT_SENDER = None
class DevelopmentConfig(DefaultConfig):
DEBUG = True
# Only for local debug use; production rejects this as an insecure value.
SECRET_KEY = "INSECURE_DEVELOPMENT_ONLY_SECRET_KEY"
SESSION_COOKIE_SECURE = False
LOG_FILE = "testing/webmentions-ssg.log"
LOG_LEVEL = logging.DEBUG
CONFIG_FILE = "testing/webmentions-ssg.cfg"
class ProductionConfig(DefaultConfig):
CONFIG_FILE = "/etc/webmentions-ssg.cfg"
class TestingConfig(DefaultConfig):
TESTING = True
WTF_CSRF_ENABLED = False
SECRET_KEY = "testing-secret-key"
SESSION_COOKIE_SECURE = False
SQLALCHEMY_DATABASE_URI = "sqlite:///:memory:"
SQLALCHEMY_TRACK_MODIFICATIONS = False
LOG_FILE = "testing/webmentions-ssg-tests.log"
LOG_LEVEL = logging.DEBUG
HUEY_URL = "memory://"
ALLOWED_TARGET_HOSTNAMES = frozenset({"dennisfink.me"})
def validate_secret_key(value: object) -> str | bytes:
"""Require a non-placeholder, sufficiently long deployment signing key.
:param value: Configured Flask signing key to validate.
:returns: The original validated signing key.
:raises TypeError: If the configured key is neither text nor bytes.
:raises RuntimeError: If the key is too short, blank, or a known placeholder.
"""
if not isinstance(value, (str, bytes)):
raise TypeError(
"Configure a persistent SECRET_KEY of at least 32 random bytes "
"before starting."
)
# Flask accepts either text or bytes as its signing key. Reject common
# example/development values even when their lengths look sufficient.
key = value.encode("utf-8") if isinstance(value, str) else value
if len(key) < MIN_SECRET_KEY_LENGTH or not key.strip():
raise RuntimeError(
"Configure a persistent SECRET_KEY of at least 32 random bytes "
"before starting."
)
normalized = key.strip().lower()
if normalized.startswith(
(b"replace_with", b"changeme", b"change_me", b"your_", b"insecure_")
):
raise RuntimeError(
"SECRET_KEY is an example/development placeholder; "
"generate and configure a real random key."
)
return value
def validated_config_overrides(
config: Config, *, config_class: type[DefaultConfig]
) -> dict[str, object]:
"""Validate runtime configuration and return normalized values.
The caller applies the returned values once; validation does not mutate
the Flask application or install extensions.
:param config: Current Flask configuration to check.
:param config_class: Configuration class selected for the application.
:returns: Normalized settings for the caller to apply.
:raises TypeError: If a hostname setting has an invalid collection type.
:raises ValueError: If a hostname or a numeric setting is invalid.
:raises RuntimeError: If production security or shared-storage configuration is
unsafe.
"""
normalized: dict[str, object] = {}
normalized["SQLITE_PRAGMAS"] = validate_sqlite_pragmas(config["SQLITE_PRAGMAS"])
for key in ("ALLOWED_TARGET_HOSTNAMES", "IGNORED_TARGET_HOSTNAMES"):
try:
value = config[key]
if not isinstance(value, (list, tuple, set, frozenset)):
raise TypeError("Expected a list, tuple, or set of hostnames.")
hostnames: set[str] = set()
for hostname in value:
if not isinstance(hostname, str) or not hostname.strip():
raise ValueError("Hostnames must be non-empty strings.")
hostnames.add(
normalize_hostname(
hostname.strip(),
allow_patterns=key == "IGNORED_TARGET_HOSTNAMES",
)
)
normalized[key] = hostnames
except (TypeError, ValueError) as exc:
raise type(exc)(f"{key}: {exc}") from exc
# Digests are rendered from a background worker without a request host.
# Require a public hostname at startup instead of silently omitting links.
if config.get("DIGEST_EMAIL") and not (
isinstance(config.get("SERVER_NAME"), str) and config["SERVER_NAME"].strip()
):
raise RuntimeError(
"Configure SERVER_NAME for the Webmentions SSG admin interface "
"when DIGEST_EMAIL is enabled."
)
if type(config["ALLOWLIST_ENABLED"]) is not bool:
raise ValueError("ALLOWLIST_ENABLED must be a boolean.")
proxy_hops = config["PROXY_FIX_TRUSTED_HOPS"]
if type(proxy_hops) is not int or proxy_hops < 0:
raise ValueError("PROXY_FIX_TRUSTED_HOPS must be a non-negative integer.")
for key in (
"MAX_CONTENT_LENGTH",
"MAX_WEBMENTION_URL_BYTES",
"RECEIVED_RETENTION_DAYS",
"RECEIVED_MAX_PAGE_SIZE",
"SOURCES_MAX_PAGE_SIZE",
):
value = config[key]
if type(value) is not int or value <= 0:
raise ValueError(f"{key} must be a positive integer.")
if not config["TESTING"] and not (
issubclass(config_class, DevelopmentConfig)
and config["DEBUG"]
and config.get("SECRET_KEY") == DevelopmentConfig.SECRET_KEY
):
normalized["SECRET_KEY"] = validate_secret_key(config.get("SECRET_KEY"))
if not config["DEBUG"] and not config["TESTING"]:
if not normalized["ALLOWED_TARGET_HOSTNAMES"]:
raise RuntimeError(
"Configure ALLOWED_TARGET_HOSTNAMES before running in production."
)
if config["RATELIMIT_STORAGE_URI"] == "memory://":
raise RuntimeError(
"Configure RATELIMIT_STORAGE_URI with shared storage before running in production."
)
huey_url = config.get(
"HUEY_URL", config.get("HUEY", {}).get("url", "memory://")
)
if isinstance(huey_url, str) and urlsplit(huey_url).scheme.lower() in {
"memory",
"blackhole",
}:
raise RuntimeError(
"Configure HUEY_URL with a shared, persistent queue before "
"running in production (memory:// and blackhole:// are unsafe)."
)
return normalized
def validate_sqlite_pragmas(value: object) -> dict[str, bool | int | str | None]:
"""Merge user overrides with safe defaults and reject invalid PRAGMAs.
SQLite doesn't accept bind parameters in PRAGMA assignments. A strict
allowlist and type checks ensure only known values enter the SQL statements.
"""
if not isinstance(value, dict):
raise TypeError("SQLITE_PRAGMAS must be a dictionary.")
pragmas = DEFAULT_SQLITE_PRAGMAS.copy()
for raw_name, setting in value.items():
# Flask's from_prefixed_env uses the casing in environment variable
# names, usually upper case. Accept both forms without exposing SQL.
if not isinstance(raw_name, str):
raise ValueError(f"SQLITE_PRAGMAS: unsupported PRAGMA {raw_name!r}.")
if (name := raw_name.lower()) not in pragmas:
raise ValueError(f"SQLITE_PRAGMAS: unsupported PRAGMA {raw_name!r}.")
if name in {"foreign_keys", "trusted_schema"}:
if type(setting) is not bool and setting is not None:
raise ValueError(f"SQLITE_PRAGMAS[{name!r}] must be a boolean or None.")
elif name in {"journal_mode", "synchronous"}:
allowed = (
SQLITE_JOURNAL_MODES
if name == "journal_mode"
else SQLITE_SYNCHRONOUS_MODES
)
if setting is not None:
if not isinstance(setting, str) or setting.upper() not in allowed:
raise ValueError(
f"SQLITE_PRAGMAS[{name!r}] must be one of "
f"{', '.join(sorted(allowed))}, or None."
)
setting = setting.upper()
elif setting is not None:
if type(setting) is not int:
raise ValueError(
f"SQLITE_PRAGMAS[{name!r}] must be an integer or None."
)
if name == "cache_size":
valid = -SQLITE_INT_MAX <= setting <= SQLITE_INT_MAX
elif name == "journal_size_limit":
valid = -1 <= setting <= SQLITE_INT64_MAX
else:
valid = 0 <= setting <= SQLITE_INT_MAX
if not valid:
raise ValueError(f"SQLITE_PRAGMAS[{name!r}] is out of range.")
pragmas[name] = setting
return pragmas
|