diff options
| author | Dennis Fink | 2026-11-12 19:57:08 +0100 |
|---|---|---|
| committer | Dennis Fink | 2026-11-12 19:57:08 +0100 |
| commit | 4bd1d9e348918b2e55db47a1ac3489d035cf55e2 (patch) | |
| tree | f7ed41a374a8a4136792039a262dc62aa8cf8c59 /webmentions_ssg/config.py | |
| parent | 7035e9f9467684cccae2b7ff3faaa62e6a9f91aa (diff) | |
| download | webmentions-ssg-4bd1d9e348918b2e55db47a1ac3489d035cf55e2.tar.gz webmentions-ssg-4bd1d9e348918b2e55db47a1ac3489d035cf55e2.zip | |
refactor(core): split modules by responsibility
Break up monolithic views, task helpers, networking, CLI, and
application extension setup so each module owns a focused concern.
Reorganize the test suite around the new boundaries while preserving
existing Webmention behavior and coverage.
Diffstat (limited to 'webmentions_ssg/config.py')
| -rw-r--r-- | webmentions_ssg/config.py | 139 |
1 files changed, 108 insertions, 31 deletions
diff --git a/webmentions_ssg/config.py b/webmentions_ssg/config.py index 8a3e58d..8251da3 100644 --- a/webmentions_ssg/config.py +++ b/webmentions_ssg/config.py @@ -5,39 +5,11 @@ """Define application settings for production, development, and testing.""" import logging +from urllib.parse import urlsplit +from flask.config import Config -def normalize_allowed_hostnames(value: object) -> set[str]: - """Validate and normalize the configured collection of allowed hostnames.""" - if not isinstance(value, (list, tuple, set, frozenset)): - raise TypeError( - "ALLOWED_HOSTNAMES must be a list, tuple, or set of hostnames, not a string." - ) - - hostnames: set[str] = set() - for hostname in value: - if not isinstance(hostname, str) or not hostname.strip(): - raise ValueError("ALLOWED_HOSTNAMES must contain non-empty strings only.") - hostnames.add(hostname.strip().lower()) - return hostnames - - -def normalize_ignored_hostnames(value: object) -> tuple[str, ...]: - """Validate and normalize hostname patterns ignored by the source scanner.""" - if not isinstance(value, (list, tuple, set, frozenset)): - raise TypeError( - "IGNORED_HOSTNAMES must be a list, tuple, or set of hostname patterns, " - "not a string." - ) - - patterns: set[str] = set() - for pattern in value: - if not isinstance(pattern, str) or not ( - normalized := pattern.strip().lower().rstrip(".") - ): - raise ValueError("IGNORED_HOSTNAMES must contain non-empty strings only.") - patterns.add(normalized) - return tuple(sorted(patterns)) +MIN_SECRET_KEY_LENGTH = 32 class DefaultConfig: @@ -69,6 +41,7 @@ class DefaultConfig: RECEIVED_RETENTION_SCHEDULE = "0 3 * * *" MAX_REDIRECTS = 20 MAX_SOURCE_BYTES = 1_000_000 + MAX_TARGET_BYTES = 1_000_000 REQUEST_TIMEOUT = 5.0 # Absolute wall-clock budget for each verification or delivery attempt. REQUEST_TOTAL_TIMEOUT = 30.0 @@ -144,3 +117,107 @@ class TestingConfig(DefaultConfig): HUEY_URL = "memory://" ALLOWED_HOSTNAMES = {"dennisfink.me"} + + +def normalize_hostnames(value: object) -> set[str]: + """Validate and normalize a collection of hostnames.""" + 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 ( + normalized := hostname.strip().lower().rstrip(".") + ): + raise ValueError("Hostnames must be non-empty strings.") + + hostnames.add(normalized) + + return hostnames + + +def validate_secret_key(value: object) -> str | bytes: + """Require a non-placeholder, sufficiently long deployment signing key.""" + 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 validate_config( + 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. + """ + normalized: dict[str, object] = {} + for key in ("ALLOWED_HOSTNAMES", "IGNORED_HOSTNAMES"): + try: + normalized[key] = normalize_hostnames(config[key]) + except (TypeError, ValueError) as exc: + raise type(exc)(f"{key}: {exc}") from exc + + 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", + ): + 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_HOSTNAMES"]: + raise RuntimeError( + "Configure ALLOWED_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 |
