"""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 import markupsafe from dotenv import load_dotenv from flask import ( Flask, current_app, flash, g, jsonify, redirect, render_template, request, url_for, ) from flask_babel import gettext as _ from flask_cors import CORS from sqlalchemy import text from werkzeug.exceptions import HTTPException from app import i18n from app.extensions import babel, csrf, db, limiter, login_manager load_dotenv() #: Fallback for requests that never reached a view: a 404 on an unrouted #: path has no endpoint to read a mark off, and `/users/api/typo` should #: still answer a fetch() in JSON. #: #: Not the primary mechanism. Seven error handlers each carried their own #: copy of a list like this (STD-09); the copies had drifted, and all seven #: were missing the same endpoints. Views now mark themselves — see #: `app/api.py` for why a prefix list could not have been made correct. JSON_URL_PREFIXES = ( '/users/disponibilities', '/users/coach-availability', '/users/api/', '/matches/api/', '/team-matches/api/', ) def wants_json_response(): """Whether this request must be answered with JSON rather than an HTML page. Three signals, in order of authority: the view said so (`@json_endpoint`), the path is under a JSON prefix (for requests that matched no view at all), or the caller asked for JSON and nothing else. """ view = current_app.view_functions.get(request.endpoint) if request.endpoint else None if getattr(view, 'returns_json', False): return True if request.path.startswith(JSON_URL_PREFIXES): return True accept = request.accept_mimetypes return accept.best == 'application/json' and not accept.accept_html 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 normalise_database_url(url): """Name the PostgreSQL driver explicitly in a connection URL. `postgresql://…` does not mean "whichever driver is installed": it means psycopg2, which SQLAlchemy imports at create_engine() time. requirements .txt pins psycopg 3 (`psycopg[binary]`) and no psycopg2, so a clean install starting against the URL Render hands out — and the one this project's own documentation shows — raises ModuleNotFoundError: No module named 'psycopg2' before the first request. Anything with a driver already spelled out (`postgresql+psycopg://`, `postgresql+psycopg2://`) is left alone, so naming psycopg2 stays possible for an environment that has it. `postgres://` is the legacy alias several hosts still emit; SQLAlchemy dropped it in 1.4. Args: url: Value of DATABASE_URL, or None. Returns: str | None: The URL, with a driver named when it was PostgreSQL. """ if not url: return url scheme, separator, rest = url.partition('://') if not separator or '+' in scheme: return url if scheme in ('postgres', 'postgresql'): return f'postgresql+psycopg://{rest}' return url 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__) # Cache-busting stamps for static files, filled lazily by the url_defaults # hook below. Per application instance, so the test suite does not carry # one app's mtimes into the next. _static_stamps = {} # --- 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