"""Team Tryouts Application - Flask Application Factory.
This module provides the application factory for creating and configuring
the Flask application instance with comprehensive security hardening.
"""
import os
import secrets
from flask import Flask, g, request, redirect, jsonify, render_template, url_for
from flask_cors import CORS
from app.extensions import db, login_manager, csrf, limiter, babel
from sqlalchemy import text
from werkzeug.exceptions import HTTPException
import markupsafe
from dotenv import load_dotenv
from app import i18n
load_dotenv()
def nl2br(value):
"""Convert newlines to HTML line breaks.
Args:
value: String value to convert.
Returns:
Markup: HTML-safe string with line breaks.
"""
if value:
# Markup('
').join() escapes each segment before joining.
# Markup('
'.join(...)) would mark attacker-controlled text as safe.
return markupsafe.Markup('
').join(str(value).splitlines())
return ''
def build_csp(*, allow_inline_script, nonce=None):
"""Assemble the Content-Security-Policy header.
Two mutually exclusive modes, and they really are exclusive.
Under CSP level 3, a browser that understands nonces **ignores
'unsafe-inline' entirely as soon as a nonce is present**. Emitting both
would therefore not be a gentle transition: it would drop every inline
script and every onclick attribute at once, in modern browsers only.
The switch has to be atomic, which is why one flag drives it.
While allow_inline_script is true no nonce is emitted at all, so adding
nonce="{{ csp_nonce }}" to a template ahead of the switch is harmless.
Flipping the flag requires every inline event handler to be gone first.
A nonce cannot authorise an onclick attribute — nonces apply to script
elements, never to handler attributes. See tests/test_csp.py, which
tracks how many are left.
Args:
allow_inline_script: Keep 'unsafe-inline' in script-src.
nonce: Per-request nonce, used only when inline script is not allowed.
Returns:
str: The header value.
"""
if allow_inline_script:
script_src = "'self' 'unsafe-inline' https://cdn.jsdelivr.net"
else:
script_src = f"'self' 'nonce-{nonce}' https://cdn.jsdelivr.net"
return '; '.join([
"default-src 'self'",
f'script-src {script_src}',
# style-src is a separate migration: inline style="" attributes are
# spread across the templates and are not an XSS vector on their own.
"style-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com https://cdn.jsdelivr.net",
"font-src 'self' https://cdnjs.cloudflare.com",
"img-src 'self' data: https://cdn.discordapp.com",
"connect-src 'self'",
"frame-ancestors 'none'",
"base-uri 'self'",
"form-action 'self'",
])
def create_app(config=None):
"""Create and configure the Flask application.
Args:
config: Optional mapping of configuration overrides, applied after the
environment defaults and before validation. This is what makes the
factory usable from tests: pass a throwaway database URI, a dummy
secret, and turn off the Discord bot, without touching os.environ.
Initializes Flask with:
- Secret key for session security
- Database configuration
- CSRF protection
- CORS with restricted origins
- Login manager
- Rate limiting
- All route blueprints
- Security headers and HTTPS redirects
- Custom error handlers
- Health check endpoint
- Structured logging
Handles database initialization and seeding with sample data if empty.
Returns:
Flask: Configured Flask application instance.
"""
app = Flask(__name__)
# --- defaults from the environment ------------------------------------
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY')
app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv('DATABASE_URL')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['WTF_CSRF_ENABLED'] = True
app.config['CORS_ALLOWED_ORIGINS'] = os.getenv('CORS_ALLOWED_ORIGINS', '')
app.config['FORCE_HTTPS'] = os.getenv('FORCE_HTTPS', 'true').lower() == 'true'
# Now false: every inline event handler has been replaced by a
# data-action attribute dispatched from main.js, so script-src no longer
# needs 'unsafe-inline'. Inline