Skip to content

Commit bdd168f

Browse files
committedJun 18, 2024·
fix(@angular/build): add CSP nonce to script with src tags
Prior to this change, script tags with the `src` attribute were not being assigned a CSP nonce during the build process. This is useful strict-dynamic is a Content Security Policy (CSP) directive that simplifies the management of dynamically loaded scripts while maintaining a high level of security. It allows scripts that are initially trusted (through a nonce or hash) to load other scripts without additional restrictions. Closes #27874 (cherry picked from commit c0ceddf)
1 parent a0f7d15 commit bdd168f

File tree

2 files changed

+7
-8
lines changed

2 files changed

+7
-8
lines changed
 

Diff for: ‎packages/angular/build/src/utils/index-file/nonce.ts

+1-2
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,7 @@ export async function addNonce(html: string): Promise<string> {
2929

3030
rewriter.on('startTag', (tag) => {
3131
if (
32-
(tag.tagName === 'style' ||
33-
(tag.tagName === 'script' && !tag.attrs.some((attr) => attr.name === 'src'))) &&
32+
(tag.tagName === 'style' || tag.tagName === 'script') &&
3433
!tag.attrs.some((attr) => attr.name === 'nonce')
3534
) {
3635
tag.attrs.push({ name: 'nonce', value: nonce });

Diff for: ‎packages/angular/build/src/utils/index-file/nonce_spec.ts

+6-6
Original file line numberDiff line numberDiff line change
@@ -74,22 +74,22 @@ describe('addNonce', () => {
7474
expect(result).toContain('<style nonce="{% nonce %}">.a {color: red;}</style>');
7575
});
7676

77-
it('should to all inline script tags', async () => {
77+
it('should to all script tags', async () => {
7878
const result = await addNonce(`
7979
<html>
8080
<head>
8181
</head>
8282
<body>
8383
<app ngCspNonce="{% nonce %}"></app>
84-
<script>console.log('foo');</<script>
84+
<script>console.log('foo');</script>
8585
<script src="./main.js"></script>
86-
<script>console.log('bar');</<script>
86+
<script>console.log('bar');</script>
8787
</body>
8888
</html>
8989
`);
9090

91-
expect(result).toContain(`<script nonce="{% nonce %}">console.log('foo');</<script>`);
92-
expect(result).toContain('<script src="./main.js"></script>');
93-
expect(result).toContain(`<script nonce="{% nonce %}">console.log('bar');</<script>`);
91+
expect(result).toContain(`<script nonce="{% nonce %}">console.log('foo');</script>`);
92+
expect(result).toContain('<script src="./main.js" nonce="{% nonce %}"></script>');
93+
expect(result).toContain(`<script nonce="{% nonce %}">console.log('bar');</script>`);
9494
});
9595
});

0 commit comments

Comments
 (0)
Please sign in to comment.