flask-talisman

repository·master·Indexed 21 days ago

https://github.com/googlecloudplatform/flask-talisman

A Flask extension that automates the setting of security-related HTTP headers to protect against common web vulnerabilities such as XSS, clickjacking, and sniffing. It provides configuration options for HTTPS redirection, HSTS, frame options, session cookie security, Feature Policy, and Content Security Policy (CSP), including support for per-view overrides via the @talisman decorator and dynamic script nonces.

Tokens
1.3K
Snippets
6
Records
6
Agent score
26%

What's inside flask-talisman

  1. Initialize Talisman in a Flask app

    master

    To use Talisman, import the Talisman class and wrap your Flask application instance with it. This applies the default security headers to your entire application.

    from flask import Flask
    from flask_talisman import Talisman
    
    app = Flask(__name__)
    Talisman(app)
  2. Configure Content Security Policy (CSP)

    master

    The default CSP is default-src: 'self', which is very strict. Most applications require a custom policy. You can provide the policy as a Python dictionary or a semicolon-separated string (useful for environment variables).

    Using a Dictionary

    # Allow content from self and a trusted domain
    csp = {
        'default-src': ["'self'", "*.trusted.com"]
    }
    talisman = Talisman(app, content_security_policy=csp)

    Using a String (e.g., from Environment Variables)

    import os
    from flask_talisman import Talisman, DEFAULT_CSP_POLICY
    
    # CSP_DIRECTIVES="default-src 'self'; image-src *"
    talisman = Talisman(
        app, 
        content_security_policy=os.environ.get("CSP_DIRECTIVES", DEFAULT_CSP_POLICY)
    )

    Using Nonces for Dynamic Scripts

    To allow specific dynamic scripts, use content_security_policy_nonce_in to specify which CSP directives should include the nonce, and then use the csp_nonce() function in your templates.

    Python Setup:

    csp = {
        'default-src': "'self'",
        'script-src': "'self'",
    }
    talisman = Talisman(app, content_security_policy=csp, content_security_policy_nonce_in=['script-src'])

    Template Usage:

    <script nonce="{{ csp_nonce() }}">
        //... your script
    </script>
    # Example: Allowing images from anywhere and media from specific providers
    csp = {
        'default-src': "'self'",
        'img-src': '*',
        'media-src': ['media1.com', 'media2.com'],
        'script-src': 'userscripts.example.com'
    }
    talisman = Talisman(app, content_security_policy=csp)
  3. Configure Talisman options

    master

    You can customize the security headers by passing various options to the Talisman constructor. Key options include:

    • force_https (bool, default True): Forces all non-debug connections to https.
    • force_https_permanent (bool, default False): Uses 301 instead of 302 for HTTPS redirects.
    • frame_options (str, default SAMEORIGIN): Can be SAMEORIGIN, DENY, or ALLOWFROM.
    • frame_options_allow_from (str, default None): Domains allowed to embed the site via iframe.
    • strict_transport_security (bool, default True): Whether to send HSTS headers.
    • strict_transport_security_max_age (int, default ONE_YEAR_IN_SECS): Duration the browser respects HSTS.
    • content_security_policy (dict or str, default default-src: 'self'): The CSP policy.
    • content_security_policy_nonce_in (list, default []): Adds a per-request nonce to specified CSP sections (e.g., ['script-src', 'style-src']).
    • session_cookie_secure (bool, default True): Sets the session cookie to secure.
    • session_cookie_http_only (bool, default True): Sets the session cookie to httponly.
    • feature_policy (dict, default {}): Configures the Feature-Policy header.
    # Example of custom configuration
    Talisman(app, force_https=True, frame_options='DENY')
  4. Configure Feature Policy

    master

    Feature Policy (now often referred to as Permissions Policy) allows you to enable or disable browser features like geolocation. Talisman uses the feature_policy option to set this header.

    Example: Disabling geolocation access:

    feature_policy = {
        'geolocation': "'none'"
    }
    talisman = Talisman(app, feature_policy=feature_policy)
  5. Apply per-view Talisman configurations

    master

    You can override the global Talisman policy for specific routes using the @talisman decorator. Supported options for per-view overrides are force_https, frame_options, frame_options_allow_from, and content_security_policy.

    from flask import Flask
    from flask_talisman import Talisman, ALLOW_FROM
    
    app = Flask(__name__)
    talisman = Talisman(app)
    
    @app.route('/normal')
    def normal():
        return 'Normal'
    
    @app.route('/embeddable')
    @talisman(frame_options=ALLOW_FROM, frame_options_allow_from='*')
    def embeddable():
        return 'Embeddable'