# SPDX-FileCopyrightText: 2026 Dennis Fink # # 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 MIN_SECRET_KEY_LENGTH = 32 class DefaultConfig: TESTING = False DEBUG = False # Production must provide a persistent, random key through configuration. SECRET_KEY = None BOOTSTRAP_SERVE_LOCAL = True # BOOTSTRAP_BOOTSWATCH_THEME = "Materia" # Secure by default; deployment configuration can override these values. SESSION_COOKIE_SECURE = True SESSION_COOKIE_HTTPONLY = True SESSION_COOKIE_SAMESITE = "Lax" LOG_FILE = "/var/log/webmentions-ssg.log" LOG_FORMAT = "[%(asctime)s]:%(levelname)s:%(name)s %(message)s" LOG_LEVEL = logging.INFO LOGFILE_MAX_BYTES = 20_000_000 LOGFILE_BACKUP_COUNT = 10 SQLALCHEMY_DATABASE_URI = "sqlite:///webmentions-ssg.db" # Empty by default: no target hostnames are accepted until configured. ALLOWED_HOSTNAMES = frozenset() # 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 # Purge terminal failed/deleted received Webmentions after 30 days. RECEIVED_RETENTION_DAYS = 30 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 # Requeue abandoned verification attempts after 15 minutes. VERIFICATION_TIMEOUT_SECONDS = 900 # Maximum automatic recoveries of a stale received/verifying row. VERIFICATION_MAX_RECOVERIES = 3 VERIFICATION_REAPER_SCHEDULE = "*/5 * * * *" SOURCE_DIRECTORY = None SOURCE_BASE_URL = None IGNORED_HOSTNAMES = () SCANNER_SCHEDULE = "0 * * * *" # Total send attempts per source revision (not additional retries). SEND_MAX_ATTEMPTS = 6 SEND_RETRY_BASE_SECONDS = 3600 SEND_RETRY_MAX_SECONDS = 86400 NOTIFICATION_EMAIL = None NOTIFICATION_SCHEDULE = "0 8 * * *" MAIL_SERVER = "localhost" MAIL_PORT = 25 MAIL_USE_TLS = False MAIL_USE_SSL = False MAIL_USERNAME = None MAIL_PASSWORD = None MAIL_DEFAULT_SENDER = None # Number of trusted reverse-proxy hops for X-Forwarded-For/Proto. # 0 (default) means forwarded headers are not trusted. PROXY_FIX_TRUSTED_HOPS = 0 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" 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 SESSION_COOKIE_SECURE = False SECRET_KEY = "testing-secret-key" WTF_CSRF_ENABLED = False LOG_FILE = "testing/webmentions-ssg-tests.log" LOG_LEVEL = logging.DEBUG SQLALCHEMY_DATABASE_URI = "sqlite:///:memory:" SQLALCHEMY_TRACK_MODIFICATIONS = False HUEY_URL = "memory://" ALLOWED_HOSTNAMES = frozenset({"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