Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/smooth-baboons-move.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': patch
---

Fixes a bug where inline styles and scripts didn't work when CSP was enabled. Now when adding `<styles>` elements inside an Astro component, their hashes care correctly computed.
24 changes: 20 additions & 4 deletions packages/astro/src/core/render-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import { type Pipeline, Slots, getParams, getProps } from './render/index.js';
import { isRoute404or500, isRouteExternalRedirect, isRouteServerIsland } from './routing/match.js';
import { copyRequest, getOriginPathname, setOriginPathname } from './routing/rewrite.js';
import { AstroSession } from './session.js';
import { generateCspDigest } from './encryption.js';

export const apiContextRoutesSymbol = Symbol.for('context.routes');
/**
Expand Down Expand Up @@ -435,6 +436,21 @@ export class RenderContext {
const { clientDirectives, inlinedScripts, compressHTML, manifest, renderers, resolve } =
pipeline;
const { links, scripts, styles } = await pipeline.headElements(routeData);

const extraStyleHashes = [];
const extraScriptHashes = [];
const shouldInjectCspMetaTags = !!manifest.csp;
const cspAlgorithm = manifest.csp?.algorithm ?? 'SHA-256';
if (shouldInjectCspMetaTags) {
for (const style of styles) {
extraStyleHashes.push(await generateCspDigest(style.children, cspAlgorithm));
}

for (const script of scripts) {
extraScriptHashes.push(await generateCspDigest(script.children, cspAlgorithm));
}
}

const componentMetadata =
(await pipeline.componentMetadata(routeData)) ?? manifest.componentMetadata;
const headers = new Headers({ 'Content-Type': 'text/html' });
Expand Down Expand Up @@ -492,13 +508,13 @@ export class RenderContext {
hasRenderedServerIslandRuntime: false,
headInTree: false,
extraHead: [],
extraStyleHashes: [],
extraScriptHashes: [],
extraStyleHashes,
extraScriptHashes,
propagators: new Set(),
},
cspDestination: manifest.csp?.cspDestination ?? (routeData.prerender ? 'meta' : 'header'),
shouldInjectCspMetaTags: !!manifest.csp,
cspAlgorithm: manifest.csp?.algorithm ?? 'SHA-256',
shouldInjectCspMetaTags,
cspAlgorithm,
// The following arrays must be cloned, otherwise they become mutable across routes.
scriptHashes: manifest.csp?.scriptHashes ? [...manifest.csp.scriptHashes] : [],
scriptResources: manifest.csp?.scriptResources ? [...manifest.csp.scriptResources] : [],
Expand Down
18 changes: 18 additions & 0 deletions packages/astro/test/csp.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,24 @@ describe('CSP', () => {
assert.equal(meta.attr('content'), undefined, 'meta tag should not be present');
});

it('should generate hashes for inline styles', async () => {
fixture = await loadFixture({
root: './fixtures/csp/',
});
await fixture.build();
const html = await fixture.readFile('/inline/index.html');
const $ = cheerio.load(html);

const meta = $('meta[http-equiv="Content-Security-Policy"]');
// hash of the <style> content
assert.ok(
meta
.attr('content')
.toString()
.includes("'sha256-fP5hIETY85LoQH4mfn28a0KQgRZ3ZBI/WJOYJRKChes='"),
);
});

it('should return CSP header inside a hook', async () => {
let routeToHeaders;
fixture = await loadFixture({
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<style>
.text {
color: red;
text-transform: uppercase;
}
</style>
<p class="text">Powered By</p>

5 changes: 5 additions & 0 deletions packages/astro/test/fixtures/csp/src/pages/inline.astro
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
import InlineStuff from "../components/InlineStuff.astro";
---

<InlineStuff />