Search code examples
pythonflaskgoogle-cloud-platformswagger-uiflask-restplus

Flask-Talisman breaks flask-restplus' swagger documentation


I recently installed flask-talisman and after defining the default Content Security Policy, I realized my Swagger documentation page did not load.

The Swagger documentation page is automatically generated by flask-restplus and it simply stopped loading.

The Content Security Policy (CSP) I defined was like this:

csp = {
    'default-src': '\'self\''
}
talisman = Talisman(app, content_security_policy=csp)

Could this be simply solved by adding swagger to the trusted domains in the CSP, like so?

csp = {
    'default-src': ["'self'", "*.swagger.com"]
}
talisman = Talisman(app, content_security_policy=csp)

Or do I need to define other parameters?


Solution

  • No, it's because swagger-ui uses inline scripts and styles -- here's the open issue tracker for swagger-ui and here's the open issue for flask-restplus.

    flask-talisman allows control on a 'per-view' basis, so you could add the 'unsafe-inline' keyword to your CSP for that endpoint. If that's not possible with flask-restplus, you could also modify your CSP using before_request for whatever the swagger route prefix is, as outlined here.

    Edit:

    A workaround is to use a different CSP for the Swagger view that allows inline scripts and styles:

    # Swagger CSP needs to have 'unsafe-inline' in the script-src and style-src fields
    SWAGGER_CSP = {
        "script-src": ["'self'", "'unsafe-inline'"],
        "style-src": ["'self'", "'unsafe-inline'"]
    }
    
    # update the CSP for the Swagger view function
    app.view_functions["swagger_ui.show"].talisman_view_options = {
        "content_security_policy": SWAGGER_CSP
    }