jliAce
jliAce

Reputation: 11

Is there a way to incorporate CSP into flask admin for its generated inline js?

I'm trying to incorporate CSP (Content Security Policy) into the flask admin framework and keep running into issues. Due to the js being generated, I was wondering if there was a simple way to attach a nonce to all generated scripts without having to manually overwrite every template.

I currently have the following nonce code in the system:

@app.before_request
    def renew_nonce():
        nonce = secrets.token_hex(32)
        g.nonce = nonce


    @app.context_processor
    def get_nonce():
        # Return a dictionary containing the nonce value
        nonce = g.nonce
        return {'nonce': nonce}
    
    @app.after_request
    def apply_security_headers(response):
        """Setting security headers"""
        # Generate a random nonce value
        nonce = g.nonce
        print("nonce after request: ", nonce)
        response.headers['Strict-Transport-Security'] = 'max-age=63072000; includeSubDomains'
        response.headers['Content-Security-Policy'] = f"default-src 'self'; \
            script-src 'self' https://cdnjs.cloudflare.com https://ajaxorg.github.io 'nonce-{nonce}'; \
            style-src 'self' 'unsafe-inline'; \
            img-src 'self' api.mapbox.com data:; \
            connect-src 'self'; \
            worker-src 'self' blob:;"
        response.headers['X-Content-Type-Options'] = 'nosniff'
        response.headers['X-Frame-Options'] = 'SAMEORIGIN'
        response.headers['X-XSS-Protection'] = '1; mode=block'
        return response

This generates the nonce for me to use in the templates for the code that I overwrite. However, is there anyway to attach the nonce to the js generated by the flask admin framework?

Example of how I use the nonce in the jinja2 framework:

<script nonce = "{{ nonce }}">
        //Does stuff
    </script>

Upvotes: 1

Views: 237

Answers (0)

Related Questions