webpacker和injectStylesIntoStyleTag.js破坏了CSP

问题描述

在我添加webpacker之前,我的ruby on rails应用程序的CSP运转良好。现在我明白了:

Content Security Policy: The page’s settings observed the loading of a resource at inline (“style-src”). A CSP report is being sent. injectStylesIntoStyleTag.js:117
Content Security Policy: The page’s settings observed the loading of a resource at inline (“style-src”). A CSP report is being sent. injectStylesIntoStyleTag.js:190

有问题的代码如下:

function insertStyleElement(options) {
  var style = document.createElement('style');
  
  ...

  if (typeof options.insert === 'function') {
    options.insert(style);
  } else {
    var target = getTarget(options.insert || 'head');

    if (!target) {
      throw new Error("@R_502_5285@n't find a style target. This probably means that the value for the 'insert' parameter is invalid.");
    }

    target.appendChild(style); //LINE 117//
  }

  return style;
}

并且:

function applyToTag(style,options,obj) {
  var css = obj.css;

  ...

  if (style.styleSheet) {
    style.styleSheet.csstext = css;
  } else {
    while (style.firstChild) {
      style.removeChild(style.firstChild);
    }

    style.appendChild(document.createTextNode(css)); //LINE 190//
  }
}

如何添加随机数? This表示将__webpack_nonce__ = 'random';添加到我的条目文件(在本例中为app/javascript/packs/application.js),但是将该随机添加到我的csp文件中对style-src违规没有影响。在这种情况下,看起来像这样:config.style_src :self,'https://fonts.googleapis.com','nonce-random'

解决方法

我某种程度上无法在源代码中找到注入的样式,但是答案是在Chrome中打开页面(我使用的是Firefox),并将控制台日志中的sha-256哈希值复制到应用程序的CSP中。 / p>