Skip to content

Commit d483125

Browse files
Suppress CSP hashes when 'unsafe-inline' is present in a directive (#17664)
Co-authored-by: ematipico <[email protected]>
1 parent bd374b7 commit d483125

4 files changed

Lines changed: 124 additions & 7 deletions

File tree

‎.changeset/gold-roses-fetch.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'astro': patch
3+
---
4+
5+
Fixes an issue where Astro CSP support didn't correctly handle cases `"unsafe-inline"` resource. Now when `"unsafe-inline"`, Astro won't emit hashes for the directive specified.

‎packages/astro/src/runtime/server/render/csp.ts‎

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -66,13 +66,20 @@ export function renderCspContent(result: SSRResult): string {
6666
const styleElemActive = isEnabled(style.element);
6767
const strictDynamicSuffix = scriptDirective.strictDynamic ? ` 'strict-dynamic'` : '';
6868

69-
// On the baseline, omit the element hashes when the `-elem` directive will carry them instead.
69+
// Per the CSP spec, browsers ignore `'unsafe-inline'` when a hash or nonce is present in the
70+
// same directive. Suppress hashes on any directive whose resources include `'unsafe-inline'` so
71+
// the user's intent is preserved.
72+
const scriptDefaultHasUnsafeInline = hasUnsafeInline(script.default.resources);
73+
const styleDefaultHasUnsafeInline = hasUnsafeInline(style.default.resources);
74+
75+
// On the baseline, omit the element hashes when the `-elem` directive will carry them instead,
76+
// and omit all hashes when `'unsafe-inline'` is present.
7077
const scriptBaselineTokens = [
71-
...(scriptElemActive ? [] : [...finalScriptHashes]),
78+
...(scriptElemActive || scriptDefaultHasUnsafeInline ? [] : [...finalScriptHashes]),
7279
...(scriptDirective.strictDynamic ? [`'strict-dynamic'`] : []),
7380
];
7481
const scriptSrc = `script-src ${scriptResources} ${scriptBaselineTokens.join(' ')};`;
75-
const styleSrc = `style-src ${styleResources} ${(styleElemActive ? [] : [...finalStyleHashes]).join(' ')};`;
82+
const styleSrc = `style-src ${styleResources} ${(styleElemActive || styleDefaultHasUnsafeInline ? [] : [...finalStyleHashes]).join(' ')};`;
7683

7784
const scriptSrcElem = scriptElemActive
7885
? renderSpecificDirective(
@@ -125,6 +132,10 @@ export function renderCspContent(result: SSRResult): string {
125132
.join(' ');
126133
}
127134

135+
function hasUnsafeInline(resources: string[]): boolean {
136+
return resources.includes("'unsafe-inline'");
137+
}
138+
128139
/** A more specific directive is emitted only when the user scoped at least one source/hash to it. */
129140
function isEnabled(sources: CspDirectiveSources): boolean {
130141
return sources.resources.length > 0 || sources.hashes.length > 0;
@@ -149,9 +160,14 @@ function renderSpecificDirective(
149160
ownHashes: string[],
150161
suffix = '',
151162
): string {
152-
const hashes = new Set<string>(sharedHashes);
153-
for (const hash of ownHashes) {
154-
hashes.add(`'${hash}'`);
163+
// Per the CSP spec, browsers ignore `'unsafe-inline'` when a hash is present in the same
164+
// directive. Skip hashes entirely to preserve the user's `'unsafe-inline'` intent.
165+
const unsafeInline = hasUnsafeInline(resources);
166+
const hashes = new Set<string>(unsafeInline ? undefined : sharedHashes);
167+
if (!unsafeInline) {
168+
for (const hash of ownHashes) {
169+
hashes.add(`'${hash}'`);
170+
}
155171
}
156172
let finalResources: string;
157173
if (resources.length > 0) {

‎packages/astro/src/types/public/config.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -819,7 +819,7 @@ export interface AstroUserConfig<
819819
* - External scripts and external styles are not supported out of the box, but you can [provide your own hashes](https://docs.astro.build/en/reference/configuration-reference/#securitycspscriptdirectivehashes).
820820
* - [Astro's view transitions](https://docs.astro.build/en/guides/view-transitions/) using the `<ClientRouter />` are not supported, but you can [consider migrating to the browser native View Transition API](https://events-3bg.pages.dev/jotter/astro-view-transitions/) instead if you are not using Astro's enhancements to the native View Transitions and Navigation APIs.
821821
* - Shiki isn't currently supported. By design, Shiki functions use inline styles that cannot work with Astro CSP implementation. Consider [using `<Prism />`](https://docs.astro.build/en/guides/syntax-highlighting/#prism-) when your project requires both CSP and syntax highlighting.
822-
* - `unsafe-inline` directives are incompatible with Astro's CSP implementation. By default, Astro will emit hashes for all its bundled scripts (e.g. client islands) and all modern browsers will automatically reject `unsafe-inline` when it occurs in a directive with a hash or nonce.
822+
* - When `'unsafe-inline'` is included as a resource in a directive, Astro will not emit hashes on that directive. Per the CSP spec, browsers ignore `'unsafe-inline'` when a hash or nonce is present in the same directive, so Astro suppresses hashes to preserve `'unsafe-inline'` behavior. Note that this reduces the security of that directive to the level of `'unsafe-inline'`.
823823
*
824824
* :::note
825825
* Due to the nature of the Vite dev server, this feature isn't supported while working in `dev` mode. Instead, you can test this in your Astro project using `build` and `preview`.

‎packages/astro/test/units/csp/render-csp.test.ts‎

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,4 +211,100 @@ describe('renderCspContent', () => {
211211
"script-src 'self' 'sha256-default'; style-src 'self' ;",
212212
);
213213
});
214+
215+
it('suppresses hashes on style-src when unsafe-inline is present', () => {
216+
assert.equal(
217+
renderCspContent(
218+
createCspResult({
219+
styleDirective: {
220+
resources: ["'unsafe-inline'"],
221+
hashes: ['sha256-abc'],
222+
},
223+
}),
224+
),
225+
"script-src 'self' ; style-src 'unsafe-inline' ;",
226+
);
227+
});
228+
229+
it('suppresses hashes on script-src when unsafe-inline is present', () => {
230+
assert.equal(
231+
renderCspContent(
232+
createCspResult({
233+
scriptDirective: {
234+
resources: ["'unsafe-inline'"],
235+
hashes: ['sha256-abc'],
236+
strictDynamic: false,
237+
},
238+
}),
239+
),
240+
"script-src 'unsafe-inline' ; style-src 'self' ;",
241+
);
242+
});
243+
244+
it('suppresses hashes on style-src-elem when unsafe-inline is present', () => {
245+
assert.equal(
246+
renderCspContent(
247+
createCspResult({
248+
styleDirective: {
249+
resources: [{ resource: "'unsafe-inline'", kind: 'element' }],
250+
hashes: ['sha256-abc'],
251+
},
252+
}),
253+
),
254+
"script-src 'self' ; style-src 'self' ; style-src-elem 'unsafe-inline';",
255+
);
256+
});
257+
258+
it('suppresses hashes on script-src-elem when unsafe-inline is present', () => {
259+
assert.equal(
260+
renderCspContent(
261+
createCspResult({
262+
scriptDirective: {
263+
resources: [{ resource: "'unsafe-inline'", kind: 'element' }],
264+
hashes: ['sha256-abc'],
265+
strictDynamic: false,
266+
},
267+
}),
268+
),
269+
"script-src 'self' ; script-src-elem 'unsafe-inline'; style-src 'self' ;",
270+
);
271+
});
272+
273+
it('suppresses render-time extra hashes when unsafe-inline is on style-src', () => {
274+
assert.equal(
275+
renderCspContent(
276+
createCspResult({
277+
styleDirective: { resources: ["'unsafe-inline'"] },
278+
extraStyleHashes: ['sha256-extra'],
279+
}),
280+
),
281+
"script-src 'self' ; style-src 'unsafe-inline' ;",
282+
);
283+
});
284+
285+
it('suppresses render-time extra hashes when unsafe-inline is on script-src', () => {
286+
assert.equal(
287+
renderCspContent(
288+
createCspResult({
289+
scriptDirective: { resources: ["'unsafe-inline'"] },
290+
extraScriptHashes: ['sha256-extra'],
291+
}),
292+
),
293+
"script-src 'unsafe-inline' ; style-src 'self' ;",
294+
);
295+
});
296+
297+
it('keeps hashes on style-src when unsafe-inline is only on style-src-attr', () => {
298+
assert.equal(
299+
renderCspContent(
300+
createCspResult({
301+
styleDirective: {
302+
resources: [{ resource: "'unsafe-inline'", kind: 'attribute' }],
303+
hashes: ['sha256-abc'],
304+
},
305+
}),
306+
),
307+
"script-src 'self' ; style-src 'self' 'sha256-abc'; style-src-attr 'unsafe-inline';",
308+
);
309+
});
214310
});

0 commit comments

Comments
 (0)