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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
|
# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
#
# SPDX-License-Identifier: BSD-3-Clause
"""Test application configuration defaults, loading, and hardening."""
from pathlib import Path
import pytest
from flask import request
from flask_limiter.util import get_remote_address
from wtforms import Field, ValidationError
from wtforms.form import BaseForm
from webmentions_ssg import create_app, limiter
from webmentions_ssg.config import (
DefaultConfig,
DevelopmentConfig,
ProductionConfig,
TestingConfig,
)
from webmentions_ssg.forms.validators import AllowedTargetHostname
@pytest.mark.parametrize(
("config_class", "expected_secure"),
[
(DefaultConfig, True),
(ProductionConfig, True),
(DevelopmentConfig, False),
(TestingConfig, False),
],
)
def test_session_cookie_defaults(
config_class: type[DefaultConfig], expected_secure: bool
) -> None:
assert config_class.SESSION_COOKIE_SECURE is expected_secure
assert config_class.SESSION_COOKIE_HTTPONLY is True
assert config_class.SESSION_COOKIE_SAMESITE == "Lax"
def test_source_allowlist_mode_requires_boolean_configuration(tmp_path: Path) -> None:
class BadSourceModeConfig(TestingConfig):
LOG_FILE = str(tmp_path / "mode-test.log")
ALLOWLIST_ENABLED = "yes"
with pytest.raises(ValueError, match="ALLOWLIST_ENABLED"):
create_app(BadSourceModeConfig)
def test_explicit_config_overrides_session_cookie_defaults() -> None:
class CookieOverrideConfig(TestingConfig):
SESSION_COOKIE_SECURE = True
SESSION_COOKIE_HTTPONLY = False
SESSION_COOKIE_SAMESITE = "Strict"
app = create_app(CookieOverrideConfig)
assert app.config["SESSION_COOKIE_SECURE"] is True
assert app.config["SESSION_COOKIE_HTTPONLY"] is False
assert app.config["SESSION_COOKIE_SAMESITE"] == "Strict"
def test_missing_production_configuration_is_fatal(tmp_path: Path) -> None:
class MissingProductionConfig(ProductionConfig):
CONFIG_FILE = str(tmp_path / "missing.cfg")
with pytest.raises(FileNotFoundError, match=r"missing.cfg"):
create_app(MissingProductionConfig)
def test_missing_development_configuration_is_optional(tmp_path: Path) -> None:
class LocalDevelopmentConfig(DevelopmentConfig):
CONFIG_FILE = str(tmp_path / "missing.cfg")
LOG_FILE = str(tmp_path / "development.log")
app = create_app(LocalDevelopmentConfig)
assert app.config["ALLOWED_TARGET_HOSTNAMES"] == set()
def test_development_creates_local_directory_on_first_start(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.chdir(tmp_path)
assert not (tmp_path / "testing").exists()
class FreshDevelopmentConfig(DevelopmentConfig):
pass
app = create_app(FreshDevelopmentConfig)
assert Path(app.instance_path) == tmp_path / "testing"
assert (tmp_path / "testing" / "webmentions-ssg.log").is_file()
def test_testing_creates_local_log_directory_on_first_start(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.chdir(tmp_path)
assert not (tmp_path / "testing").exists()
create_app(TestingConfig)
assert (tmp_path / "testing" / "webmentions-ssg-tests.log").is_file()
def test_endpoint_limits_are_inherited_from_defaults() -> None:
for config in (DefaultConfig, DevelopmentConfig, ProductionConfig, TestingConfig):
assert config.MAX_REDIRECTS == 20
assert config.MAX_RECEIVED_SOURCE_BYTES == 1_000_000
assert config.MAX_DISCOVERY_TARGET_BYTES == 1_000_000
assert config.REQUEST_TIMEOUT_SECONDS == 5.0
assert config.REQUEST_TOTAL_TIMEOUT_SECONDS == 30.0
assert set() == DefaultConfig.ALLOWED_TARGET_HOSTNAMES
assert DefaultConfig.IGNORED_TARGET_HOSTNAMES == ()
def test_allowed_hostnames_are_normalized_at_startup(tmp_path: Path) -> None:
class MixedCaseConfig(TestingConfig):
LOG_FILE = str(tmp_path / "test.log")
ALLOWED_TARGET_HOSTNAMES = [" DennisFink.Me ", "EXAMPLE.COM", "dennisfink.me"]
app = create_app(MixedCaseConfig)
assert app.config["ALLOWED_TARGET_HOSTNAMES"] == {"dennisfink.me", "example.com"}
assert isinstance(app.config["ALLOWED_TARGET_HOSTNAMES"], set)
# The form validator must compare complete hostnames, never substrings.
target = Field()
validator = AllowedTargetHostname(message="Hostname not allowed")
form = BaseForm({})
with app.app_context():
for url in ("https://dennisfink.me/post", "https://EXAMPLE.com/post"):
target.data = url
validator(form, target)
for url in ("https://fink/post", "https://evil-dennisfink.me/post"):
target.data = url
with pytest.raises(ValidationError, match="Hostname not allowed"):
validator(form, target)
@pytest.mark.parametrize(
"hostnames,expected_exception",
[
("dennisfink.me", TypeError),
(None, TypeError),
({"dennisfink.me": True}, TypeError),
(123, TypeError),
(["example.com", None], ValueError),
(["example.com", ""], ValueError),
(["example.com", " "], ValueError),
(["*.example.com"], ValueError),
],
)
def test_invalid_allowed_hostnames_fail_at_startup(
tmp_path: Path, hostnames: object, expected_exception: type[Exception]
) -> None:
class InvalidHostnameConfig(TestingConfig):
LOG_FILE = str(tmp_path / "test.log")
ALLOWED_TARGET_HOSTNAMES = hostnames
with pytest.raises(expected_exception, match="ALLOWED_TARGET_HOSTNAMES"):
create_app(InvalidHostnameConfig)
def test_hostname_config_shares_admin_canonicalization(tmp_path: Path) -> None:
class InternationalizedHosts(TestingConfig):
LOG_FILE = str(tmp_path / "idn.log")
ALLOWED_TARGET_HOSTNAMES = {"BÜCHER.example.", "EXAMPLE.COM"}
IGNORED_TARGET_HOSTNAMES = {"*.BÜCHER.example.", "EXAMPLE.COM."}
app = create_app(InternationalizedHosts)
assert app.config["ALLOWED_TARGET_HOSTNAMES"] == {
"xn--bcher-kva.example",
"example.com",
}
assert app.config["IGNORED_TARGET_HOSTNAMES"] == {
"*.xn--bcher-kva.example",
"example.com",
}
def test_ignored_hostnames_are_normalized_at_startup(tmp_path: Path) -> None:
class MixedCaseConfig(TestingConfig):
LOG_FILE = str(tmp_path / "test.log")
IGNORED_TARGET_HOSTNAMES = [" Example.COM. ", "*.EXAMPLE.com.", "example.com"]
app = create_app(MixedCaseConfig)
assert app.config["IGNORED_TARGET_HOSTNAMES"] == {"*.example.com", "example.com"}
@pytest.mark.parametrize(
"hostnames,expected_exception",
[
("example.com", TypeError),
(None, TypeError),
({"example.com": True}, TypeError),
(123, TypeError),
(["example.com", None], ValueError),
(["example.com", ""], ValueError),
(["example.com", " "], ValueError),
(["example.com", "..."], ValueError),
],
)
def test_invalid_ignored_hostnames_fail_at_startup(
tmp_path: Path, hostnames: object, expected_exception: type[Exception]
) -> None:
class InvalidHostnameConfig(TestingConfig):
LOG_FILE = str(tmp_path / "test.log")
IGNORED_TARGET_HOSTNAMES = hostnames
with pytest.raises(expected_exception, match="IGNORED_TARGET_HOSTNAMES"):
create_app(InvalidHostnameConfig)
def test_production_requires_nonempty_allowed_hostnames(tmp_path: Path) -> None:
config_path = tmp_path / "production.cfg"
config_path.write_text(
'RATELIMIT_STORAGE_URI = "redis://localhost:6379"\n'
'SECRET_KEY = "the-production-secret-key-for-this-test"\n'
)
class EmptyHostnamesConfig(ProductionConfig):
CONFIG_FILE = str(config_path)
with pytest.raises(RuntimeError, match="ALLOWED_TARGET_HOSTNAMES"):
create_app(EmptyHostnamesConfig)
@pytest.mark.parametrize(
"queue_settings",
[
{}, # missing URL silently selected Huey's memory:// fallback
{"HUEY_URL": "memory://"},
{"HUEY_URL": "MEMORY:///"},
{"HUEY_URL": "blackhole://"},
{"HUEY": {"url": "memory://"}},
{"HUEY": {"url": "blackhole://"}},
],
)
def test_production_rejects_ephemeral_or_discarding_huey_queue(
tmp_path: Path, queue_settings: dict[str, object]
) -> None:
config_path = tmp_path / "production.cfg"
config_path.write_text("# Valid options are provided by the config subclass.\n")
class ProductionWithQueue(ProductionConfig):
CONFIG_FILE = str(config_path)
SECRET_KEY = "a-long-secret-string-for-a-production-test"
ALLOWED_TARGET_HOSTNAMES = {"example.com"}
RATELIMIT_STORAGE_URI = "redis://localhost:6379/1"
LOG_FILE = str(tmp_path / "production.log")
for key, value in queue_settings.items():
setattr(ProductionWithQueue, key, value)
with pytest.raises(RuntimeError, match="HUEY_URL"):
create_app(ProductionWithQueue)
def test_production_prefers_explicit_huey_url_over_legacy_option(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr(limiter, "init_app", lambda app: None)
config_path = tmp_path / "production.cfg"
config_path.write_text("# Configuration inherited from subclass.\n")
class ProductionWithExplicitQueue(ProductionConfig):
CONFIG_FILE = str(config_path)
SECRET_KEY = "a-long-secret-string-for-a-production-test"
ALLOWED_TARGET_HOSTNAMES = {"example.com"}
RATELIMIT_STORAGE_URI = "redis://localhost:6379/1"
LOG_FILE = str(tmp_path / "production.log")
HUEY = {"url": "memory://"}
HUEY_URL = f"sqlite:///{tmp_path / 'huey.db'}"
app = create_app(ProductionWithExplicitQueue)
assert app.extensions["huey"].huey.__class__.__name__ == "SqliteHuey"
def test_environment_allowed_hostnames_override_config_file(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
config_path = tmp_path / "development.cfg"
config_path.write_text('ALLOWED_TARGET_HOSTNAMES = ["first.example"]\n')
monkeypatch.setenv("WEBMENTIONS_SSG_ALLOWED_TARGET_HOSTNAMES", '["SECOND.EXAMPLE"]')
class LocalDevelopmentConfig(DevelopmentConfig):
CONFIG_FILE = str(config_path)
LOG_FILE = str(tmp_path / "development.log")
app = create_app(LocalDevelopmentConfig)
assert app.config["ALLOWED_TARGET_HOSTNAMES"] == {"second.example"}
@pytest.mark.parametrize(
("secret", "expected_exception"),
[
(None, TypeError),
("", RuntimeError),
("short", RuntimeError),
("REPLACE_WITH_A_LONG_RANDOM_SECRET", RuntimeError),
("INSECURE_DEVELOPMENT_ONLY_SECRET_KEY", RuntimeError),
("change_me_to_a_new_strong_secret_key", RuntimeError),
(123, TypeError),
],
)
def test_production_refuses_missing_weak_or_example_secret_key(
tmp_path: Path, secret: object, expected_exception: type[Exception]
) -> None:
config_file = tmp_path / "production.cfg"
config_file.write_text("# This file intentionally has no signing key.\n")
class SecretKeyConfig(ProductionConfig):
CONFIG_FILE = str(config_file)
LOG_FILE = str(tmp_path / "production.log")
ALLOWED_TARGET_HOSTNAMES = {"example.com"}
RATELIMIT_STORAGE_URI = "redis://localhost:6379"
SECRET_KEY = secret
with pytest.raises(expected_exception, match="SECRET_KEY"):
create_app(SecretKeyConfig)
def test_production_uses_persistent_configured_secret(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
# The test concerns secret-key persistence, not Redis initialization.
monkeypatch.setattr(limiter, "init_app", lambda app: None)
config_file = tmp_path / "production.cfg"
key = "a-fixed-key-with-32-plus-random-characters"
config_file.write_text(f"SECRET_KEY = {key!r}\n")
class ConfiguredProduction(ProductionConfig):
CONFIG_FILE = str(config_file)
LOG_FILE = str(tmp_path / "production.log")
ALLOWED_TARGET_HOSTNAMES = {"example.com"}
RATELIMIT_STORAGE_URI = "redis://localhost:6379"
HUEY_URL = f"sqlite:///{tmp_path / 'huey.db'}"
first = create_app(ConfiguredProduction)
second = create_app(ConfiguredProduction)
assert first.secret_key == key == second.secret_key
def test_production_accepts_environment_secret_override(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
config_file = tmp_path / "production.cfg"
config_file.write_text('SECRET_KEY = "REPLACE_WITH_A_LONG_RANDOM_SECRET"\n')
key = "another-long-persistent-secret-for-a-deployment"
monkeypatch.setenv("WEBMENTIONS_SSG_SECRET_KEY", key)
# Avoid requiring the optional Redis dependency for this configuration test.
monkeypatch.setattr(limiter, "init_app", lambda app: None)
class EnvConfiguredProduction(ProductionConfig):
CONFIG_FILE = str(config_file)
LOG_FILE = str(tmp_path / "production.log")
ALLOWED_TARGET_HOSTNAMES = {"example.com"}
RATELIMIT_STORAGE_URI = "redis://localhost:6379"
HUEY_URL = f"sqlite:///{tmp_path / 'huey.db'}"
app = create_app(EnvConfiguredProduction)
assert app.secret_key == key
def test_development_rejects_placeholder_even_with_debug(tmp_path: Path) -> None:
config_file = tmp_path / "development.cfg"
config_file.write_text('SECRET_KEY = "REPLACE_WITH_A_LONG_RANDOM_SECRET"\n')
class LocalDevelopment(DevelopmentConfig):
CONFIG_FILE = str(config_file)
LOG_FILE = str(tmp_path / "development.log")
with pytest.raises(RuntimeError, match="SECRET_KEY"):
create_app(LocalDevelopment)
def test_resource_limits_have_safe_defaults() -> None:
assert DefaultConfig.MAX_CONTENT_LENGTH == 64 * 1024
assert DefaultConfig.MAX_WEBMENTION_URL_BYTES == 8192
assert DefaultConfig.RECEIVED_RETENTION_DAYS == 30
assert DefaultConfig.RECEIVED_MAX_PAGE_SIZE == 100
assert DefaultConfig.RECEIVED_RETENTION_SCHEDULE == "0 3 * * *"
@pytest.mark.parametrize(
"key",
[
"MAX_CONTENT_LENGTH",
"MAX_WEBMENTION_URL_BYTES",
"RECEIVED_RETENTION_DAYS",
"RECEIVED_MAX_PAGE_SIZE",
],
)
@pytest.mark.parametrize("value", [None, "100", 0, -1, 1.5])
def test_invalid_resource_limits_fail_at_startup(
tmp_path: Path, key: str, value: object
) -> None:
class InvalidResourceLimit(TestingConfig):
LOG_FILE = str(tmp_path / "invalid-resource.log")
setattr(InvalidResourceLimit, key, value)
with pytest.raises(ValueError, match=key):
create_app(InvalidResourceLimit)
def test_received_max_page_size_can_be_set_in_cfg(tmp_path: Path) -> None:
config_file = tmp_path / "development.cfg"
config_file.write_text("RECEIVED_MAX_PAGE_SIZE = 250\n")
class ConfiguredDevelopment(DevelopmentConfig):
CONFIG_FILE = str(config_file)
LOG_FILE = str(tmp_path / "development.log")
app = create_app(ConfiguredDevelopment)
assert app.config["RECEIVED_MAX_PAGE_SIZE"] == 250
def test_proxy_fix_disabled_by_default(tmp_path: Path) -> None:
class DirectConfig(TestingConfig):
LOG_FILE = str(tmp_path / "direct.log")
app = create_app(DirectConfig)
@app.get("/_proxy-check")
def proxy_check() -> dict[str, str]:
return {
"ip": get_remote_address(),
"scheme": request.scheme,
"host": request.host,
}
response = app.test_client().get(
"/_proxy-check",
environ_overrides={"REMOTE_ADDR": "192.0.2.50"},
headers={
"X-Forwarded-For": "198.51.100.99",
"X-Forwarded-Proto": "https",
"X-Forwarded-Host": "attacker.example",
},
)
assert response.json == {"ip": "192.0.2.50", "scheme": "http", "host": "localhost"}
def test_proxy_fix_trusts_only_configured_proxy_hops(tmp_path: Path) -> None:
class TwoProxyConfig(TestingConfig):
LOG_FILE = str(tmp_path / "proxy.log")
PROXY_FIX_TRUSTED_HOPS = 2
app = create_app(TwoProxyConfig)
@app.get("/_proxy-check")
def proxy_check() -> dict[str, str]:
return {
"ip": get_remote_address(),
"scheme": request.scheme,
"host": request.host,
}
response = app.test_client().get(
"/_proxy-check",
environ_overrides={"REMOTE_ADDR": "192.0.2.50"},
headers={
"X-Forwarded-For": "198.51.100.99, 203.0.113.4, 192.0.2.10",
"X-Forwarded-Proto": "http, https",
"X-Forwarded-Host": "attacker.example",
},
)
assert response.json == {"ip": "203.0.113.4", "scheme": "http", "host": "localhost"}
@pytest.mark.parametrize("hops", [-1, None, "1", 1.5])
def test_invalid_proxy_fix_hop_counts_fail_at_startup(
tmp_path: Path, hops: object
) -> None:
class InvalidProxyConfig(TestingConfig):
LOG_FILE = str(tmp_path / "invalid-proxy.log")
PROXY_FIX_TRUSTED_HOPS = hops
with pytest.raises(ValueError, match="PROXY_FIX_TRUSTED_HOPS"):
create_app(InvalidProxyConfig)
def test_proxy_fix_can_be_configured_via_environment(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
config_path = tmp_path / "development.cfg"
config_path.write_text("# proxy configuration supplied by environment\n")
monkeypatch.setenv("WEBMENTIONS_SSG_PROXY_FIX_TRUSTED_HOPS", "1")
class EnvProxyConfig(DevelopmentConfig):
CONFIG_FILE = str(config_path)
LOG_FILE = str(tmp_path / "development.log")
app = create_app(EnvProxyConfig)
assert app.config["PROXY_FIX_TRUSTED_HOPS"] == 1
assert app.wsgi_app.__class__.__name__ == "ProxyFix"
def test_sqlite_pragma_overrides_keep_default_settings(tmp_path: Path) -> None:
class PartialSQLiteConfig(TestingConfig):
LOG_FILE = str(tmp_path / "partial-sqlite-test.log")
SQLITE_PRAGMAS = {"busy_timeout": 10000, "synchronous": "normal"}
app = create_app(PartialSQLiteConfig)
assert app.config["SQLITE_PRAGMAS"] == {
"foreign_keys": True,
"journal_mode": "WAL",
"busy_timeout": 10000,
"trusted_schema": False,
"synchronous": "NORMAL",
"cache_size": None,
"wal_autocheckpoint": None,
"journal_size_limit": None,
}
# The default mapping must not be modified by individual app overrides.
assert TestingConfig.SQLITE_PRAGMAS["busy_timeout"] == 5000
@pytest.mark.parametrize(
"invalid",
[
"PRAGMA foreign_keys=OFF",
None,
{"foreign_keys": "OFF"},
{"journal_mode": "WAL; DROP TABLE users"},
{"journal_mode": "MEMORY"},
{"trusted_schema": 0},
{"busy_timeout": -1},
{"busy_timeout": True},
{"cache_size": 2**32},
{"wal_autocheckpoint": -1},
{"journal_size_limit": -2},
{"synchronous": "INVALID"},
{"unsupported_pragma": 42},
],
)
def test_invalid_sqlite_pragmas_fail_at_startup(
tmp_path: Path, invalid: object
) -> None:
class BadSQLiteConfig(TestingConfig):
LOG_FILE = str(tmp_path / "bad-sqlite-test.log")
SQLITE_PRAGMAS = invalid
with pytest.raises((TypeError, ValueError), match="SQLITE_PRAGMAS"):
create_app(BadSQLiteConfig)
def test_uppercase_sqlite_pragma_keys_support_environment_convention(
tmp_path: Path,
) -> None:
class EnvStyleSQLiteConfig(TestingConfig):
LOG_FILE = str(tmp_path / "env-style-sqlite-test.log")
SQLITE_PRAGMAS = {"CACHE_SIZE": -8192, "SYNCHRONOUS": "normal"}
app = create_app(EnvStyleSQLiteConfig)
assert app.config["SQLITE_PRAGMAS"]["cache_size"] == -8192
assert app.config["SQLITE_PRAGMAS"]["synchronous"] == "NORMAL"
|