[go: nahoru, domu]

Skip to content

Commit

Permalink
fix(@angular/build): add CSP nonce to script with src tags
Browse files Browse the repository at this point in the history
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)
  • Loading branch information
alan-agius4 committed Jun 18, 2024
1 parent a0f7d15 commit bdd168f
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 8 deletions.
3 changes: 1 addition & 2 deletions packages/angular/build/src/utils/index-file/nonce.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,7 @@ export async function addNonce(html: string): Promise<string> {

rewriter.on('startTag', (tag) => {
if (
(tag.tagName === 'style' ||
(tag.tagName === 'script' && !tag.attrs.some((attr) => attr.name === 'src'))) &&
(tag.tagName === 'style' || tag.tagName === 'script') &&
!tag.attrs.some((attr) => attr.name === 'nonce')
) {
tag.attrs.push({ name: 'nonce', value: nonce });
Expand Down
12 changes: 6 additions & 6 deletions packages/angular/build/src/utils/index-file/nonce_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,22 +74,22 @@ describe('addNonce', () => {
expect(result).toContain('<style nonce="{% nonce %}">.a {color: red;}</style>');
});

it('should to all inline script tags', async () => {
it('should to all script tags', async () => {
const result = await addNonce(`
<html>
<head>
</head>
<body>
<app ngCspNonce="{% nonce %}"></app>
<script>console.log('foo');</<script>
<script>console.log('foo');</script>
<script src="./main.js"></script>
<script>console.log('bar');</<script>
<script>console.log('bar');</script>
</body>
</html>
`);

expect(result).toContain(`<script nonce="{% nonce %}">console.log('foo');</<script>`);
expect(result).toContain('<script src="./main.js"></script>');
expect(result).toContain(`<script nonce="{% nonce %}">console.log('bar');</<script>`);
expect(result).toContain(`<script nonce="{% nonce %}">console.log('foo');</script>`);
expect(result).toContain('<script src="./main.js" nonce="{% nonce %}"></script>');
expect(result).toContain(`<script nonce="{% nonce %}">console.log('bar');</script>`);
});
});

0 comments on commit bdd168f

Please sign in to comment.