当没有内联样式时,为什么我的style-src'self'违反Content-Security-Policy?我在Go中有一个服务器,在Elm中有一个Web应用程序。这是一个最小的示例:
服务器(转到1.12版):
package main
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
)
const indexhtml = `
<!DOCTYPE HTML>
<html>
<head>
<script src="main.js"></script>
</head>
<body>
<div id="elm"></div>
<script src="elm.js"></script>
</body>
</html>`
const elmjs = `
var app = Elm.Main.init({
node: document.getElementById('elm')
})`
const csp = "style-src 'self'; report-uri http://localhost:3333/cspreport;"
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Security-Policy", csp)
io.WriteString(w, indexhtml)
})
http.HandleFunc("/elm.js", func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, elmjs)
})
http.HandleFunc("/main.js", func(w http.ResponseWriter, r *http.Request) {
f, _ := os.Open("main.js")
io.Copy(w, f)
})
http.HandleFunc("/cspreport", func(w http.ResponseWriter, r *http.Request) {
body, _ := ioutil.ReadAll(r.Body)
fmt.Println(string(body))
})
fmt.Println(http.ListenAndServe(":3333", nil))
}
Elm 0.19代码(编译为main.js):
module Main exposing (main)
import Element as E
main =
E.layout [] <|
E.row [] [ E.text "a", E.text "b" ]
然后服务器打印出此CSP违规行为(两次):
{
"csp-report":{
"blocked-uri":"inline",
"column-number":1,
"document-uri":"http://localhost:3333/",
"line-number":1,
"original-policy":"style-src 'self'; report-uri http://localhost:3333/cspreport",
"referrer":"",
"source-file":"http://localhost:3333/",
"violated-directive":"style-src"
}
}
如果我在CSP中将'unsafe-inline'添加到'style-src',问题就消失了,但是我真的不想这样做。如果我在Elm代码中不使用“行”,但是我需要它,它也会消失。
我认为this answer是相关的,但仍然不能解决问题。
(为方便起见,我将上面的代码放在了Github repo中。)