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
|
# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
#
# SPDX-License-Identifier: BSD-3-Clause
"""Initialize the Flask application and its shared extensions."""
import logging
import logging.handlers
import os
from pathlib import Path
from urllib.parse import urlsplit
import coloredlogs
from flask import Flask
from flask_bootstrap import Bootstrap5
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from flask_mail import Mail
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
from flask_wtf.csrf import CSRFProtect
from sqlalchemy.orm import DeclarativeBase
from werkzeug.middleware.proxy_fix import ProxyFix
from webmentions_ssg.config import (
DefaultConfig,
DevelopmentConfig,
ProductionConfig,
normalize_allowed_hostnames,
normalize_ignored_hostnames,
)
from .security import validate_secret_key
from .tasks import Huey
from .url_security import is_http_url
APP_NAME = "webmentions-ssg"
VERSION = "0.0.2"
class Base(DeclarativeBase):
pass
CSRF = CSRFProtect()
BOOTSTRAP = Bootstrap5()
DATABASE = SQLAlchemy(model_class=Base)
MIGRATE = Migrate()
HUEY = Huey()
MAIL = Mail()
LIMITER = Limiter(key_func=get_remote_address)
def create_app(config_class: type[DefaultConfig] | None = None) -> Flask:
"""
Create and configure the Flask application.
The application configuration is selected based on the development
environment unless an explicit configuration class is provided. Logging,
extensions, authentication, Huey, blueprints, and CLI commands are then
initialized.
:param config_class: Configuration class to use, or ``None`` to select the
development or production configuration automatically.
:return: Configured Flask application.
"""
development = os.environ.get("WEBMENTIONS_SSG_DEV", "").lower() in {
"1",
"true",
"yes",
"on",
}
if config_class is None:
config_class = DevelopmentConfig if development else ProductionConfig
app = Flask(
__name__,
instance_path=(
str(Path("testing").absolute())
if issubclass(config_class, DevelopmentConfig)
else None
),
)
app.config.from_object(config_class)
if not app.testing:
# Local development may omit its config file; production must not.
app.config.from_pyfile(app.config["CONFIG_FILE"], silent=app.debug)
app.config.from_prefixed_env(prefix="FLASK")
app.config.from_prefixed_env(prefix="WEBMENTIONS_SSG")
# A fixed key is convenient only for local debugging. All other
# deployments must supply their own persistent, random signing key.
using_local_dev_key = (
issubclass(config_class, DevelopmentConfig)
and app.debug
and app.config.get("SECRET_KEY") == DevelopmentConfig.SECRET_KEY
)
if not app.testing and not using_local_dev_key:
validate_secret_key(app.config.get("SECRET_KEY"))
app.config["ALLOWED_HOSTNAMES"] = normalize_allowed_hostnames(
app.config["ALLOWED_HOSTNAMES"]
)
app.config["IGNORED_HOSTNAMES"] = normalize_ignored_hostnames(
app.config["IGNORED_HOSTNAMES"]
)
proxy_hops = app.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.")
if proxy_hops:
# Trust only the configured number of proxies; never trust forwarded
# host, port or URL prefix headers for rate limiting.
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=proxy_hops, x_proto=proxy_hops)
for key in (
"MAX_CONTENT_LENGTH",
"MAX_WEBMENTION_URL_BYTES",
"RECEIVED_RETENTION_DAYS",
):
value = app.config[key]
if type(value) is not int or value <= 0:
raise ValueError(f"{key} must be a positive integer.")
if not app.testing and not app.debug and not app.config["ALLOWED_HOSTNAMES"]:
raise RuntimeError("Configure ALLOWED_HOSTNAMES before running in production.")
if (
not app.testing
and not app.debug
and app.config["RATELIMIT_STORAGE_URI"] == "memory://"
):
raise RuntimeError(
"Configure RATELIMIT_STORAGE_URI with shared storage before running in production."
)
if not app.testing and not app.debug:
# HUEY_URL overrides the legacy HUEY.url option; absent either, Huey
# falls back to an in-process queue that cannot serve a separate worker.
huey_url = app.config.get(
"HUEY_URL", app.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)."
)
# Local development and tests should start from a fresh checkout: their
# default log directory and development SQLite instance are generated.
if app.testing or app.debug:
Path(app.config["LOG_FILE"]).parent.mkdir(parents=True, exist_ok=True)
if app.debug:
Path(app.instance_path).mkdir(parents=True, exist_ok=True)
default_logging_formatter = logging.Formatter(app.config["LOG_FORMAT"])
log_file_handler = logging.handlers.RotatingFileHandler(
app.config["LOG_FILE"],
maxBytes=app.config["LOGFILE_MAX_BYTES"],
backupCount=app.config["LOGFILE_BACKUP_COUNT"],
)
log_file_handler.setLevel(app.config["LOG_LEVEL"])
log_file_handler.setFormatter(default_logging_formatter)
logging.basicConfig(level=logging.DEBUG, handlers=[logging.NullHandler()])
app.logger.handlers.clear()
app.logger.setLevel(app.config["LOG_LEVEL"])
app.logger.addHandler(log_file_handler)
werkzeug_logger = logging.getLogger("werkzeug")
werkzeug_logger.setLevel(app.config["LOG_LEVEL"])
werkzeug_logger.addHandler(log_file_handler)
coloredlogs.install(
level=app.config["LOG_LEVEL"], logger=app.logger, fmt=app.config["LOG_FORMAT"]
)
coloredlogs.install(
level=app.config["LOG_LEVEL"],
logger=werkzeug_logger,
fmt=app.config["LOG_FORMAT"],
)
DATABASE.init_app(app)
MIGRATE.init_app(
app,
db=DATABASE,
directory=str(Path(__file__).resolve().parent / "migrations"),
command="migrate",
)
CSRF.init_app(app)
LIMITER.init_app(app)
MAIL.init_app(app)
from .auth import AUTH
AUTH.init_app(app)
BOOTSTRAP.init_app(app)
HUEY.init_app(app)
@app.context_processor
def inject_version():
"""
Add the application version to the template context.
:return: Template context containing the application version.
"""
return {"VERSION": VERSION}
app.add_template_filter(is_http_url)
from .views import root_page
app.register_blueprint(root_page)
from .cli.users import USERS_CLI
app.cli.add_command(USERS_CLI)
from .cli.mail import MAIL_CLI
app.cli.add_command(MAIL_CLI)
from .cli.database import DB_CLI
app.cli.add_command(DB_CLI)
return app
|