Files
max/max/app.py
T
finnandClaude Opus 5.5 2fb357ae77 Set security headers on all responses
The app set no security headers at all, and the reverse proxy sets none
either.

- Content-Security-Policy: default-src 'none' with 'self' only for
  styles, images and fonts (MAX has no JavaScript), form-action 'self'
  (also blocks the http:// form action downgrade), frame-ancestors
  'none' and base-uri 'none'.
- X-Frame-Options: DENY, X-Content-Type-Options: nosniff,
  Referrer-Policy: same-origin.
- Strict-Transport-Security with max-age of 7 days, not in debug mode.

The headers are set in after_request, so they also apply to static
files, 404 and error responses.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 18:17:19 +00:00

73 lines
2.0 KiB
Python

import base64
import os
from flask import Flask
from werkzeug.routing import Rule as WerkzeugRule
from .auth import AuthMiddleware, init as init_auth
from .cli import register_cli
from .csrf import CsrfMiddleware
from .db import database
from .log import init_logging
from .middlewares import (
ExceptionMiddleware,
I18NMiddleware,
LoggingMiddleware,
add_middleware_stack,
)
from .routes import init_routes
from .security_headers import init_security_headers
from .sessions import SessionInterface
from .translations import TranslationHandler
class Rule(WerkzeugRule):
def __init__(self, *args, methods=None, **kwargs):
super().__init__(*args, **kwargs) # do not set methods
def main():
app = Flask(__name__)
init_logging(app)
app.logger.info("Max started.")
if app.debug:
app.logger.info("!! App is in debug mode !!")
else:
app.logger.info("App is in production mode")
TranslationHandler.init(app)
app.jinja_env.trim_blocks = True
app.jinja_env.lstrip_blocks = True
app.url_rule_class = Rule
max_origin = os.environ.get("MAX_ORIGIN")
if not max_origin and not app.debug:
raise RuntimeError(
"MAX_ORIGIN must be set to the public origin, e.g. https://max.example.com"
)
app.config.update(
MAX_ORIGIN=max_origin.rstrip("/") if max_origin else None,
SECRET_KEY=(
"123456" if app.debug else base64.b64encode(os.urandom(64)).decode("utf-8")
),
SESSION_COOKIE_NAME="session" if app.debug else "__Host-session",
SESSION_COOKIE_SECURE=not app.debug,
SESSION_COOKIE_SAMESITE="Lax",
)
add_middleware_stack(
app,
CsrfMiddleware,
AuthMiddleware,
I18NMiddleware,
LoggingMiddleware,
ExceptionMiddleware,
)
database.init(app)
app.session_interface = SessionInterface()
register_cli(app)
init_auth(app)
init_routes(app)
init_security_headers(app)
return app
app = main()