# SPDX-FileCopyrightText: 2026 Dennis Fink # # SPDX-License-Identifier: BSD-3-Clause """Test application configuration defaults, loading, and hardening.""" from pathlib import Path from flask import request from flask_limiter.util import get_remote_address import pytest from wtforms import Field, ValidationError from wtforms.form import BaseForm from webmentions_ssg import LIMITER, create_app from webmentions_ssg.config import ( DefaultConfig, DevelopmentConfig, ProductionConfig, TestingConfig, ) from webmentions_ssg.forms.validators import AllowedHostname @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_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="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_HOSTNAMES"] == set() def test_endpoint_limits_are_inherited_from_defaults() -> None: for config in (DefaultConfig, DevelopmentConfig, ProductionConfig, TestingConfig): assert config.MAX_REDIRECTS == 20 assert config.MAX_SOURCE_BYTES == 1_000_000 assert config.REQUEST_TIMEOUT == 5.0 assert config.REQUEST_TOTAL_TIMEOUT == 30.0 assert DefaultConfig.ALLOWED_HOSTNAMES == set() assert DefaultConfig.IGNORED_HOSTNAMES == () def test_allowed_hostnames_are_normalized_at_startup(tmp_path: Path) -> None: class MixedCaseConfig(TestingConfig): LOG_FILE = str(tmp_path / "test.log") ALLOWED_HOSTNAMES = [" DennisFink.Me ", "EXAMPLE.COM", "dennisfink.me"] app = create_app(MixedCaseConfig) assert app.config["ALLOWED_HOSTNAMES"] == {"dennisfink.me", "example.com"} assert isinstance(app.config["ALLOWED_HOSTNAMES"], set) # The form validator must compare complete hostnames, never substrings. target = Field() validator = AllowedHostname(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), ], ) 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_HOSTNAMES = hostnames with pytest.raises(expected_exception, match="ALLOWED_HOSTNAMES"): create_app(InvalidHostnameConfig) def test_ignored_hostnames_are_normalized_at_startup(tmp_path: Path) -> None: class MixedCaseConfig(TestingConfig): LOG_FILE = str(tmp_path / "test.log") IGNORED_HOSTNAMES = [" Example.COM. ", "*.EXAMPLE.com.", "example.com"] app = create_app(MixedCaseConfig) assert app.config["IGNORED_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_HOSTNAMES = hostnames with pytest.raises(expected_exception, match="IGNORED_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_HOSTNAMES"): create_app(EmptyHostnamesConfig) 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_HOSTNAMES = ["first.example"]\n') monkeypatch.setenv("WEBMENTIONS_SSG_ALLOWED_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_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_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_HOSTNAMES = {"example.com"} RATELIMIT_STORAGE_URI = "redis://localhost:6379" 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_HOSTNAMES = {"example.com"} RATELIMIT_STORAGE_URI = "redis://localhost:6379" 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_RETENTION_SCHEDULE == "0 3 * * *" @pytest.mark.parametrize( "key", ["MAX_CONTENT_LENGTH", "MAX_WEBMENTION_URL_BYTES", "RECEIVED_RETENTION_DAYS"] ) @pytest.mark.parametrize("value", [None, "100", 0, -1, True, 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_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, True, False, 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"