CSP and GeoDjango

Hello everyone!

With the recent landing of CSP into Django core, I noticed that my “geodjango” test project now needs these directives in the CSP settings (since I enabled the CSP middleware) in order for the required resources for OpenLayersWidget to be loaded:

SECURE_CSP = {
    "default-src": [CSP.SELF],
    "script-src": [CSP.SELF, CSP.NONCE, "https://cdn.jsdelivr.net/npm/ol@v7.2.2/dist/ol.js"],
    "style-src": [CSP.SELF, CSP.NONCE, "https://cdn.jsdelivr.net/npm/ol@v7.2.2/ol.css"],
    "img-src": [CSP.SELF, "https:"],
}

Without these, I get CSP violations as follow:

Uncaught ReferenceError: ol is not defined <anonymous> http://localhost:9000/static/gis/js/OLMapWidget.js:3

Content-Security-Policy: The page’s settings blocked a style (style-src-elem) at https://cdn.jsdelivr.net/npm/ol@v7.2.2/ol.css from being applied because it violates the following directive: “style-src 'self'”

Content-Security-Policy: The page’s settings blocked a script (script-src-elem) at https://cdn.jsdelivr.net/npm/ol@v7.2.2/dist/ol.js from being executed because it violates the following directive: “script-src 'self'” change

OpenLayersWidget defines:

    class Media:
        css = {
            "all": (
                "https://cdn.jsdelivr.net/npm/ol@v7.2.2/ol.css",
                "gis/css/ol3.css",
            )
        }
        js = (
            "https://cdn.jsdelivr.net/npm/ol@v7.2.2/dist/ol.js",
            "gis/js/OLMapWidget.js",
        )

Questions:

  1. Could we do something better here instead of needing to tweak the CSP directives? cc/@robhudson
  2. If no, we should update the docs. Any objection or other concerns? cc/@claudep @smithdc1
  3. Side question is how/when the openlayers JS and CSS are updated in Django core?

I think I can at least answer 3.: when someone does the job :grin:

About the img-src value, I didn’t know you could use https: alone. In the project where I’m using CSP, I’m listing URLs like https://*.tile.openstreetmap.org… But I’m totally a novice regarding CSP, so probably not the best person to ask.

2 Likes

I created #36549 (OpenLayersWidget needs special rules when CSP is enabled) – Django to track this issue.