hotwired / turbo-rails

Use Turbo in your Ruby on Rails app
https://turbo.hotwired.dev
MIT License
2.07k stars 320 forks source link

Progress bar is triggering CSP violation #341

Closed computer-smile closed 2 years ago

computer-smile commented 2 years ago

The .turbo-progress-bar style tags are inserted into the head of the document on initial page loads. This is triggering a CSP violation by default.

When script elements are created there's a check if the csp nonce tags are present in the head. If they are add them to the head script tags.

// turbo-rails/app/assets/javascripts/turbo.js
// ...
  createScriptElement(element) {
    if (element.getAttribute("data-turbo-eval") == "false") {
      return element;
    } else {
      const createdScriptElement = document.createElement("script");
//  check for a <meta name="csp-nonce" content="..." />
      if (this.cspNonce) {
        createdScriptElement.nonce = this.cspNonce;
      }
      createdScriptElement.textContent = element.textContent;
      createdScriptElement.async = false;
      copyElementAttributes(createdScriptElement, element);
      return createdScriptElement;
    }
  }

https://github.com/hotwired/turbo-rails/blob/37be2c6c39c417ddd5f12dcd494fb232220b0d08/app/assets/javascripts/turbo.js#L1052

The same CSP check is not applied to the insertion of the turbo progress bar style tags.

///...
  createStylesheetElement() {
    const element = document.createElement("style");
    element.type = "text/css";
// no check for for a <meta name="csp-nonce" content="..." />
    element.textContent = ProgressBar.defaultCSS;
    return element;
  }

https://github.com/hotwired/turbo-rails/blob/37be2c6c39c417ddd5f12dcd494fb232220b0d08/app/assets/javascripts/turbo.js#L1246

<head>
<style type="text/css">.turbo-progress-bar {
  position: fixed;
  display: block;
  top: 0;
  left: 0;
  height: 3px;
  background: #0076ff;
  z-index: 9999;
  transition:
    width 300ms ease-out,
    opacity 150ms 150ms ease-in;
  transform: translate3d(0, 0, 0);
}
</style>
</head>

This triggers a CSP violation by default. Should the same check be made for the creation of turbo progress bar style tag?

dhh commented 2 years ago

That sounds right. Please do investigate making the style tag respect the csp nonce as well 👍

computer-smile commented 2 years ago

I believe this has actually been resolved and looked at here https://github.com/hotwired/turbo/pull/501