Safari 17.6忽略style-src-elem指令,报错资源不在style-src/default-src
style-src-elem 指令的问题 仅在Safari 17.6版本中出现此问题,Chrome和Firefox使用相同的CSP配置完全正常。
问题详情
配置的完整Content-Security-Policy(分行展示便于阅读):
Content-Security-Policy: default-src 'none' ; base-uri 'self' ; connect-src 'self' ; font-src 'self' https://fonts.gstatic.com ; form-action 'self' ; frame-ancestors 'none' ; img-src 'self' data: ; script-src-attr 'unsafe-inline' ; script-src-elem 'self' ; style-src-attr 'unsafe-inline' ; style-src-elem 'self' 'unsafe-inline' https://fonts.googleapis.com
Safari控制台报错如下:
Refused to load https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined because it appears in neither the style-src directive nor the default-src directive of the Content Security Policy.
Refused to load https://fonts.googleapis.com/css2?family=Ubuntu:wght@300;400;500;700&display=swap because it appears in neither the style-src directive nor the default-src directive of the Content Security Policy.
Refused to load https://example.com/app/styles.css because it appears in neither the style-src directive nor the default-src directive of the Content Security Policy.
对应的资源加载代码:
<html> <head> <base href="/app/"/> ... <link href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined" rel="stylesheet"/> <link href="https://fonts.googleapis.com/css2?family=Ubuntu:wght@300;400;500;700&display=swap" rel="stylesheet"/> <link rel="stylesheet" href="styles.css"> </head> ... </html>
原因分析
根据CSP规范,style-src-elem指令专门用于控制<style>元素和<link rel="stylesheet">元素的合法资源来源,且Safari官方宣称从15.4版本开始完全支持该指令。但在17.6版本中存在兼容性bug:当未显式配置style-src时,Safari不会正确解析style-src-elem的规则,反而会强制检查style-src或default-src是否包含对应资源。
解决方案
- 临时兼容方案:在CSP中添加与
style-src-elem配置一致的style-src指令,虽然看似冗余,但能让Safari正常识别资源规则:; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com - 若不在意使用通用指令,也可以直接用
style-src替换style-src-elem,但这会同时覆盖内联样式属性(对应style-src-attr)的控制,不符合使用特定指令的初衷。
内容的提问来源于stack exchange,提问作者cueedee

