Skip to content

🛡️ Warracker is an open source, self-hostable warranty tracker to monitor expirations, store receipts, files. You own the data, your rules!

16.5 KB
Raw Blame
# backend/__init__.py
import ipaddress
import os
import logging
import psycopg2.errors
from flask import Flask, jsonify, current_app
from werkzeug.middleware.proxy_fix import ProxyFix

logger = logging.getLogger(__name__)

def _forwarded_headers_trusted(remote_addr):
    """Whether X-Forwarded-* headers from this peer may be believed.

    ProxyFix trusts forwarded headers from any peer, so with the app
    directly exposed a spoofed X-Forwarded-For is stored as the login
    IP (CFG-11). The shipped topology has nginx on loopback in front of
    the app, and split deployments sit behind a LAN proxy, so only
    loopback, private, and link-local peers are trusted by default.
    TRUST_PROXY_HEADERS=true restores trust-everything for operators
    behind a public-IP proxy; TRUST_PROXY_HEADERS=false trusts none.
    """
    override = os.environ.get('TRUST_PROXY_HEADERS', '').lower()
    if override == 'true':
        return True
    if override == 'false':
        return False
    try:
        addr = ipaddress.ip_address(remote_addr or '')
    except ValueError:
        return False
    # Explicit networks, not is_private: ipaddress counts documentation
    # ranges such as 203.0.113.0/24 as private, and those are not peers
    # a proxy would ever connect from.
    trusted = (
        ipaddress.ip_network('127.0.0.0/8'),
        ipaddress.ip_network('10.0.0.0/8'),
        ipaddress.ip_network('172.16.0.0/12'),
        ipaddress.ip_network('192.168.0.0/16'),
        ipaddress.ip_network('169.254.0.0/16'),
        ipaddress.ip_network('::1/128'),
        ipaddress.ip_network('fc00::/7'),
        ipaddress.ip_network('fe80::/10'),
    )
    return any(
        addr.version == net.version and addr in net for net in trusted
    )


class _ForwardedHeaderGuard:
    """Strip forwarded headers from untrusted peers, before ProxyFix.

    Runs outside ProxyFix so a spoofed header never reaches it. Peers
    trusted by _forwarded_headers_trusted pass through untouched.
    """
    _FORWARDED_HEADERS = (
        'HTTP_X_FORWARDED_FOR',
        'HTTP_X_FORWARDED_PROTO',
        'HTTP_X_FORWARDED_HOST',
        'HTTP_X_FORWARDED_PREFIX',
    )

    def __init__(self, app):
        self.app = app

    def __call__(self, environ, start_response):
        if not _forwarded_headers_trusted(environ.get('REMOTE_ADDR', '')):
            for header in self._FORWARDED_HEADERS:
                environ.pop(header, None)
        return self.app(environ, start_response)


def ensure_owner_exists():
    """
    Ensure that an application owner exists. This is a backup mechanism
    in case the migration failed. Runs automatically on app startup.
    """
    from .db_handler import get_db_connection, release_db_connection
    
    conn = None
    try:
        conn = get_db_connection()
        with conn.cursor() as cur:
            # First check if the is_owner column exists (handles migration timing issue)
            try:
                cur.execute("""
                    SELECT column_name FROM information_schema.columns 
                    WHERE table_name = 'users' AND column_name = 'is_owner'
                """)
                column_exists = cur.fetchone() is not None
                
                if not column_exists:
                    logger.info("is_owner column not yet created, skipping owner check (migrations may still be running)")
                    return
                
                # Check if any owner exists
                cur.execute("SELECT COUNT(*) FROM users WHERE is_owner = TRUE")
                owner_count = cur.fetchone()[0]
            except psycopg2.errors.UndefinedColumn:
                logger.info("is_owner column not yet created, skipping owner check (migrations may still be running)")
                return
            
            if owner_count == 0:
                logger.info("No application owner found, attempting to promote first user...")
                
                # Find the first user using multiple strategies
                first_user_id = None
                
                # Strategy 1: First user by created_at
                try:
                    cur.execute("""
                        SELECT id FROM users 
                        WHERE created_at IS NOT NULL 
                        ORDER BY created_at ASC, id ASC 
                        LIMIT 1
                    """)
                    result = cur.fetchone()
                    if result:
                        first_user_id = result[0]
                except Exception as e:
                    logger.warning(f"Strategy 1 (created_at) failed: {e}")
                
                # Strategy 2: First user by ID if Strategy 1 failed
                if first_user_id is None:
                    try:
                        cur.execute("SELECT id FROM users ORDER BY id ASC LIMIT 1")
                        result = cur.fetchone()
                        if result:
                            first_user_id = result[0]
                    except Exception as e:
                        logger.warning(f"Strategy 2 (lowest ID) failed: {e}")
                
                # Strategy 3: First admin user if other strategies failed
                if first_user_id is None:
                    try:
                        cur.execute("SELECT id FROM users WHERE is_admin = TRUE ORDER BY id ASC LIMIT 1")
                        result = cur.fetchone()
                        if result:
                            first_user_id = result[0]
                    except Exception as e:
                        logger.warning(f"Strategy 3 (first admin) failed: {e}")
                
                # Promote the user to owner if found
                if first_user_id is not None:
                    try:
                        cur.execute("UPDATE users SET is_owner = TRUE, is_admin = TRUE WHERE id = %s", (first_user_id,))
                        conn.commit()
                        logger.info(f"✅ Automatically promoted user ID {first_user_id} to application owner")
                        
                        # Log user info for confirmation
                        cur.execute("SELECT username, email FROM users WHERE id = %s", (first_user_id,))
                        user_info = cur.fetchone()
                        if user_info:
                            logger.info(f"Owner is now: {user_info[0]} ({user_info[1]})")
                    except Exception as e:
                        logger.error(f"Failed to promote user {first_user_id} to owner: {e}")
                        conn.rollback()
                else:
                    logger.warning("No users found in system. First registered user will become owner.")
            else:
                # Log current owner for confirmation
                cur.execute("SELECT id, username, email FROM users WHERE is_owner = TRUE")
                owners = cur.fetchall()
                logger.info(f"Application owner(s) confirmed: {[f'{o[1]} (ID:{o[0]})' for o in owners]}")
                
    except Exception as e:
        logger.error(f"Error in ensure_owner_exists: {e}")
        if conn:
            conn.rollback()
    finally:
        if conn:
            release_db_connection(conn)

# Content-Security-Policy for every response Flask serves (CFG-07b).
# The frontend uses inline scripts, inline event handlers, and inline
# styles throughout, so script-src and style-src keep 'unsafe-inline';
# the policy still pins the fetchable origins, blocks plugins and
# foreign framing, and keeps form submissions and base URIs
# same-origin. The third-party allowances are load-bearing: Google
# Fonts serves stylesheet/font assets, version-checker.js fetches the
# latest release from api.github.com, and style.css uses an Unsplash
# photo as a page background.
# upgrade-insecure-requests is intentionally omitted: self-hosted
# installs on plain HTTP (LAN IP, localhost, Unraid, Proxmox, TrueNAS)
# would otherwise have browsers rewrite same-origin subresources to
# https:// and fail to load.
_CONTENT_SECURITY_POLICY = (
    "default-src 'self'; "
    "script-src 'self' 'unsafe-inline'; "
    "style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; "
    "img-src 'self' data: blob: https://images.unsplash.com; "
    "font-src 'self' data: https://fonts.gstatic.com; "
    "connect-src 'self' https://api.github.com; "
    "frame-src 'self'; "
    "object-src 'none'; "
    "base-uri 'self'; "
    "form-action 'self'; "
    "frame-ancestors 'self'"
)


def create_app(config_name=None):
    """Create and configure an instance of the Flask application."""
    # Configure logging FIRST
    logging.basicConfig(level=logging.INFO)
    logger.info("Starting application factory...")
    
    # Determine configuration
    if config_name is None:
        config_name = os.environ.get('FLASK_CONFIG', 'default')
    
    # Create Flask app instance
    app = Flask(__name__)
    
    # Apply ProxyFix middleware for reverse proxy support, guarded so
    # forwarded headers from untrusted (directly exposed) peers are
    # dropped before ProxyFix can act on them (CFG-11).
    app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_prefix=1)
    app.wsgi_app = _ForwardedHeaderGuard(app.wsgi_app)

    @app.after_request
    def _set_security_headers(response):
        # CFG-07a: never render framed by another origin. SAMEORIGIN
        # keeps any same-origin framing working while blocking the
        # cross-origin clickjacking case.
        response.headers.setdefault('X-Frame-Options', 'SAMEORIGIN')
        # CFG-07b: Content-Security-Policy, see the module constant.
        response.headers.setdefault(
            'Content-Security-Policy', _CONTENT_SECURITY_POLICY)
        # CFG-07d: send the full URL only to the same origin, the bare
        # origin cross-origin, and nothing on an HTTPS to HTTP drop.
        response.headers.setdefault(
            'Referrer-Policy', 'strict-origin-when-cross-origin')
        # Prevent MIME-type sniffing globally on all Flask responses.
        response.headers.setdefault('X-Content-Type-Options', 'nosniff')
        return response
    
    # Load configuration
    try:
        from .config import config
        app.config.from_object(config[config_name])
        config[config_name].init_app(app)
        logger.info(f"Configuration '{config_name}' loaded successfully")
    except ImportError:
        try:
            from config import config
            app.config.from_object(config[config_name])
            config[config_name].init_app(app)
            logger.info(f"Configuration '{config_name}' loaded successfully")
        except Exception as e:
            logger.error(f"Failed to load configuration: {e}")
            raise
    
    # Initialize extensions
    try:
        from .extensions import initialize_extensions
        initialize_extensions(app)
    except ImportError:
        from extensions import initialize_extensions
        initialize_extensions(app)
    
    # Register Blueprints within app context
    with app.app_context():
        try:
            # Import blueprints
            from .auth_routes import auth_bp
            from .oidc_handler import oidc_bp
            from .warranties_routes import warranties_bp
            from .admin_routes import admin_bp
            from .statistics_routes import statistics_bp
            from .tags_routes import tags_bp
            from .file_routes import file_bp
        except ImportError:
            # Fallback for development
            from auth_routes import auth_bp
            from oidc_handler import oidc_bp
            from warranties_routes import warranties_bp
            from admin_routes import admin_bp
            from statistics_routes import statistics_bp
            from tags_routes import tags_bp
            from file_routes import file_bp
        
        # Register blueprints
        app.register_blueprint(auth_bp, url_prefix='/api/auth')
        app.register_blueprint(oidc_bp, url_prefix='/api')
        app.register_blueprint(warranties_bp, url_prefix='/api')
        app.register_blueprint(admin_bp, url_prefix='/api/admin')
        app.register_blueprint(statistics_bp, url_prefix='/api')
        app.register_blueprint(tags_bp, url_prefix='/api')
        app.register_blueprint(file_bp, url_prefix='/api')

        logger.info("All blueprints registered successfully")

        # Serve the frontend directly when nginx is disabled (DISABLE_NGINX=true,
        # issue #190). In the normal setup nginx serves these paths and the
        # Flask app never sees them, so this is a no-op there.
        if os.environ.get('DISABLE_NGINX', 'false').lower() == 'true':
            from flask import send_from_directory
            frontend_dir = '/var/www/html'

            @app.route('/', defaults={'path': ''})
            @app.route('/<path:path>')
            def serve_frontend(path):
                if path.startswith('api/'):
                    return jsonify({'error': 'Not found'}), 404
                full = os.path.join(frontend_dir, path)
                if path and os.path.isfile(full):
                    return send_from_directory(frontend_dir, path)
                return send_from_directory(frontend_dir, 'index.html')

            logger.info("DISABLE_NGINX=true: Flask will serve the frontend directly")
        
        # Initialize OIDC client after extensions and blueprints
        try:
            from .db_handler import get_db_connection, release_db_connection
            from .oidc_handler import init_oidc_client
            init_oidc_client(app, get_db_connection, release_db_connection)
        except ImportError:
            from db_handler import get_db_connection, release_db_connection
            from oidc_handler import init_oidc_client
            init_oidc_client(app, get_db_connection, release_db_connection)
        
        # Ensure an owner exists on startup
        ensure_owner_exists()
        
        # Initialize the notification scheduler with the app context
        try:
            from .notifications import init_scheduler
            from .db_handler import get_db_connection, release_db_connection
            
            init_scheduler(app, get_db_connection, release_db_connection)
            logger.info("✅ Notification scheduler initialized successfully in factory")
        except ImportError:
            try:
                from notifications import init_scheduler
                from db_handler import get_db_connection, release_db_connection
                
                init_scheduler(app, get_db_connection, release_db_connection)
                logger.info("✅ Notification scheduler initialized successfully in factory (dev mode)")
            except Exception as e:
                logger.error(f"❌ Failed to initialize notification scheduler: {e}")
                # Continue without notifications - the app can still function
        except Exception as e:
            logger.error(f"❌ Failed to initialize notification scheduler: {e}")
            # Continue without notifications - the app can still function
        
        logger.info("Application factory completed successfully")

    @app.errorhandler(413)
    def request_entity_too_large(e):
        """Return a JSON 413 when an upload exceeds MAX_CONTENT_LENGTH.

        Without this, oversized uploads surface as HTML error pages or get
        swallowed into 500s by routes with generic except blocks.
        """
        limit_mb = current_app.config.get('MAX_CONTENT_LENGTH', 0) // (1024 * 1024)
        return jsonify({"error": f"File too large. Maximum upload size is {limit_mb}MB."}), 413

    @app.route('/api/health', methods=['GET'])
    def health_check():
        """Unauthenticated health check for Docker HEALTHCHECK / load balancers.

        Verifies the app can actually reach the database with a short timeout.
        Returns 503 when the DB is unreachable so a frozen backend is detected
        instead of the container reporting healthy (see issue #239).
        """
        try:
            from .db_handler import get_db_connection, release_db_connection
            conn = get_db_connection()
            try:
                with conn.cursor() as cur:
                    cur.execute("SET LOCAL statement_timeout = '5s'")
                    cur.execute("SELECT 1")
                    cur.fetchone()
            finally:
                # Roll back so SET LOCAL doesn't leak to the next pool borrower
                try:
                    conn.rollback()
                except Exception:
                    pass
                release_db_connection(conn)
            return jsonify({"status": "ok"}), 200
        except Exception as e:
            logger.warning(f"Health check failed: {e}")
            return jsonify({"status": "error"}), 503

    return app