open-api-spex / open_api_spex

Open API Specifications for Elixir Plug applications
Mozilla Public License 2.0
681 stars 177 forks source link

Set nonces on <script> and <style> elements if configured #593

Closed nathanalderson closed 1 month ago

nathanalderson commented 5 months ago

We use a strict Content Security Policy (CSP) on our site which disallows inline scripts and inline styles unless they include the correct nonce value. This change allows the user to configure keys that, if given, will be used to look up nonces in the conn.assigns which are then used on the corresponding <script> and <style> elements.

Configuration looks like this:

get "/swaggerui", OpenApiSpex.Plug.SwaggerUI,
  ...
  csp_nonce_assign_key: %{script: :script_src_nonce, style: :style_src_nonce}

Or to use the same nonce for both:

get "/swaggerui", OpenApiSpex.Plug.SwaggerUI,
  ...
  csp_nonce_assign_key: :nonce

This configuration matches the way this is handled by phoenix_live_dashboard and Oban Web.

If no keys are configured the nonce property is omitted, so this should be entirely backward compatible.

nathanalderson commented 5 months ago

Converting to draft because I just realized I need to handle the script on the OAuth2Redirect Plug as well.

nathanalderson commented 5 months ago

Okay, I handled OpenApiSpex.Plug.SwaggerUIOAuth2Redirect as well. I had to change the inline script from:

<body onload="run()">
  <script>
    function run() {...}
  </script>
</body>

to:

<head>
  <script>
    (function run() {...})();
  </script>
</head>

Because from my reading, there's no way to set a nonce on an event handler. Setting a nonce value on both the <script> tag and the <body> tag did not work.