[Python] Flask appears to automatically add a nonce to my CSP directives. Can this be disabled?

Discussão em 'Python' iniciado por Stack, Março 21, 2025.

  1. Stack

    Stack Membro Participativo

    Goal:

    From a Flask server, I wish to use the url_for() function inside javascript files to calculate the proper URL.

    Problem:

    Flask.render_template() only touches the HTML template file, so Flask recommends you use inline <script> blocks (Flask Render Template Documenation) and call url_for() to save a script base variable which you can then access in other pure javascript modules that aren't processed by render_template().

    Unfortunately, without CSP enabled, modern browsers will completely ignore inline <script> tags. It is therefore necessary to create a Content Security Profile, which I did as follows, trying to make the most permissive policy ever:

    @app.after_request
    def add_csp(response):
    response.headers['Content-Security-Policy'] = ("default-src * data: blob: filesystem: about: "
    "ws: wss: 'unsafe-inline' 'unsafe-eval' 'unsafe-dynamic'; script-src * "
    "'unsafe-inline' 'unsafe-eval' 'unsafe-hash'; connect-src * 'unsafe-inline'; "
    "img-src * data: blob: "'unsafe-inline'; frame-src *; style-src * data: "
    "blob: 'unsafe-inline';font-src * data: blob: 'unsafe-inline';")
    return response


    That should work. I've allowed everything. (Everything I can find, anyway) Unfortunately, when running my script, I see this:

    Content-Security-Policy: The page’s settings blocked an inline script (script-src-elem) from being executed because it violates the following directive: “script-src * 'unsafe-inline' 'unsafe-eval' 'unsafe-hash' 'nonce-bW96LWV4dGVuc2lvbjovL2E0ZTMxZmFjLTI5NjQtNDUxMC1iNDhjLTExOTYyODdkMWMzZC8='” index.html:14:36


    This is the script it is complaining about:

    <script type="text/javascript">
    const GRAY_LIGHT = {{ url_for('static',filename='images/gray.png') }};
    const RED_LIGHT = {{ url_for('static',filename='images/red.png') }};
    console.log("RED_LIGHT = "+RED_LIGHT+", GRAY_LIGHT = "+GRAY_LIGHT);
    </script>


    How can something not match * and 'unsafe inline'? After struggling for many hours, I came upon this page: (Mozilla CSP documentation)


    If a directive contains a nonce and unsafe-inline, then the browser ignores unsafe-inline.
    ​

    Now, since I didn't add the nonce value that Firefox is complaining about, it seems that Flask must have put it there. But I can find no documentation that describes this behavior, nor how to disable it.

    Is anyone familiar with Flask and know how to prevent it from adding a nonce to my CSP?

    Or is Flask just no longer compatible with modern browsers? All I really wanted to do was use the url_for() function, and I've spent over 2 days trying to make that simple thing happen.

    Any advice appreciated. I've never dealt with CSP issues before.

    Continue reading...

Compartilhe esta Página