Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a customizable nonce attribute to injected style elements - CSP #26152

Open
mcm-ham opened this issue Sep 28, 2018 · 20 comments
Open

Add a customizable nonce attribute to injected style elements - CSP #26152

mcm-ham opened this issue Sep 28, 2018 · 20 comments
Labels
area: core Issues related to the framework runtime area: security Issues related to built-in security features, such as HTML sanitation core: stylesheets cross-cutting: CSP feature: under consideration Feature request for which voting has completed and the request is now under consideration feature Issue that requests a new feature freq2: medium security Issues that generally impact framework or application security
Milestone

Comments

@mcm-ham
Copy link

mcm-ham commented Sep 28, 2018

I'm submitting a...


[ ] Regression (a behavior that used to work and stopped working in a new release)
[ ] Bug report  
[ ] Performance issue
[x] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead see https://github.com/angular/angular/blob/master/CONTRIBUTING.md#question
[ ] Other... Please describe:

Current behavior

No ability to define nonce attribute on style tag.

Expected behavior

I would like the ability to define a nonce generated on the server that angular will add to the inline styles.

What is the motivation / use case for changing the behavior?

So that I can comply with business requirements not to use 'unsafe-inline' in CSP.

Environment


Angular version: 6.1.8

Browser:
- [x] Chrome (desktop) version 69
- [ ] Chrome (Android) version XX
- [ ] Chrome (iOS) version XX
- [ ] Firefox version XX
- [ ] Safari (desktop) version XX
- [ ] Safari (iOS) version XX
- [ ] IE version XX
- [ ] Edge version XX
 
For Tooling issues:
- Node version: 10.11.0
- Platform:  Windows 10

Others:

@mcm-ham
Copy link
Author

mcm-ham commented Sep 28, 2018

Note webpack already supports this:
https://webpack.js.org/guides/csp/
webpack-contrib/style-loader#319

Related:
#6361
angular/angular-cli#12378

@mcm-ham mcm-ham changed the title Add support for nonce to inline style tags - CSP Add a customizable nonce attribute to injected style elements - CSP Sep 28, 2018
@alxhub alxhub added feature Issue that requests a new feature area: core Issues related to the framework runtime labels Oct 3, 2018
@ngbot ngbot bot added this to the Backlog milestone Oct 3, 2018
@ExtraBB
Copy link

ExtraBB commented Mar 1, 2019

Any update on this? For a strict CSP this is essential.

@faran52000

This comment has been minimized.

@dbligh
Copy link

dbligh commented Aug 21, 2019

Very keen to see this implemented. Is there a workaround at the moment since webpack already supports the nonce approach?

@qortex
Copy link

qortex commented Dec 8, 2019

Any update on this? I can't see how to enable a strict CSP with Angular at the moment.

Will Angular 9 & Ivy / Bazel allow it?

Coming from angular/angular-cli#12378. @clydin , maybe you have a take on this?

To clarify: I still need "style-src" to include 'unsafe-inline' because styles are injected it seems. I don't know the internals, but that's what I see. And also "'self'" for scripts which is not recommended by Google's CSP inspector

@limitedmage
Copy link

limitedmage commented Dec 27, 2019

I'm having the same issue and can't seem to find a workaround (eg. by using __webpack_nonce__).

This is the offending code in platform-browser.js:

    _addStylesToHost(styles, host) {
        styles.forEach((/**
         * @param {?} style
         * @return {?}
         */
        (style) => {
            /** @type {?} */
            const styleEl = this._doc.createElement('style');
            styleEl.textContent = style;
            this._styleNodes.add(host.appendChild(styleEl));
        }));
    }

@fearx135

This comment has been minimized.

@bes1002t
Copy link

Still no progress? Angular is one of the leading Javascript frameworks, it should not hinder developers to use high security settings.

@angular-robot angular-robot bot added the feature: under consideration Feature request for which voting has completed and the request is now under consideration label Jun 4, 2021
@arrigod
Copy link

arrigod commented Jul 1, 2021

Hello, what is the plan for this? Will this ever be addressed?

@cyraid
Copy link
Contributor

cyraid commented Jul 11, 2021

For what I require I can't have inline style or javascript. Was really hoping Angular could be my go to, as I like Angular's templating and ease of use to get things done.. I guess I must use the manual approach.

@Splaktar Splaktar added freq2: medium area: security Issues related to built-in security features, such as HTML sanitation security Issues that generally impact framework or application security labels Jul 12, 2021
@jasperbosch
Copy link

jasperbosch commented Jul 26, 2021

Out of sheer frustration that this issue hasn't been resolved yet, I've created a script that uses the nonce listed on the script tag to append the nonce to the style tag being injected.

First, the script queries the currentScript. This should be at the beginning of the script because later the value will be null (in FireFox) https://stackoverflow.com/questions/38769103/document-currentscript-is-null

Next, for each .createElement("style"), the nonce is placed on the element.

/**
 * This script adds nonce-functionality to the main.xxx.js file. This script should only be used if SCP-Headers requires
 * no `style-src "unsafe-inline"` is used. The script-tag for the "main.xxx.js"-file should have a "nonce"-attribute.
 *
 * https://stackoverflow.com/questions/38769103/document-currentscript-is-null
 */
const fs = require('fs');

const currentScript = 'var currentScript=document.currentScript;';
const addNonceScript = '.nonce=currentScript[\'nonce\'] || currentScript.getAttribute(\'nonce\');';
const styleRegexp = /[const|var] (?<varname>\w+)=([\w.]*?)\.createElement\("style"\);/ig;

/**
 * Add nonce to file.
 * @param filename
 */
function addNonce(filename) {
    let fileContent = fs.readFileSync(filename).toString('utf-8');

    if (!fileContent.startsWith(currentScript)) {
        fileContent = `${currentScript}${fileContent}`;

        // match is used for replace
        const match = fileContent.match(styleRegexp);
        // results is used for getting the correct variable-name.
        let results = styleRegexp.exec(fileContent);
        let index = 0;
        do {
            // replace (add) the nonce
            fileContent = fileContent.replace(match[index], `${match[index]}${results.groups.varname}${addNonceScript}`);
            index++;
        } while ((results = styleRegexp.exec(fileContent)));

        fs.writeFileSync(filename, fileContent, {encoding: 'utf-8'});
        console.log('Nonce added!')
    } else {
        console.log('\x1b[41m%s\x1b[0m', 'Nonce already added! No changes are made.')
    }
}

/**
 * Read folder recursive. If a file 'main.xxxx.js' is found, add nonce.
 *
 * @param folder
 */
function readDir(folder) {
    const foldercontent = fs.readdirSync(`${folder}`);
    foldercontent.forEach(filename => {
        if (fs.lstatSync(`${folder}/${filename}`).isDirectory()) {
            readDir(`${folder}/${filename}`);
        } else {
            if (filename.startsWith('main') && filename.endsWith('.js')) {
                console.log('found:', filename);
                addNonce(`${folder}/${filename}`);
            }
        }
    })
}


readDir('dist');

@Splaktar
Copy link
Member

Hello, what is the plan for this? Will this ever be addressed?

I proposed solving this and a set of other CSP issues to the team this month. The proposal wasn't prioritized, but I believe that the plan is to prioritize each of the related issues (this one included). Discussions between the Angular team and the Google Security team have already started. That said, I can't promise any kind of ETA.

@jessicajaniuk jessicajaniuk added this to Inbox in Feature Requests via automation Feb 15, 2022
@drewfreyling
Copy link

Any updates on this one?

@bes1002t
Copy link

Seems this is more or less prioritized low

@stephanie-dm
Copy link

Since our CSP also doesn't allow inline CSS, I currently disabled the inline CSS by putting the following in the production configuration of angular.json:

"optimization": {
     "scripts": true,
     "styles": {
            "minify": true,
            "inlineCritical": false
       },
      "fonts": true
},

@jkosmala87
Copy link

Any chance to put higher priority on it? Allowing inline scripts is not best practice from security perspective.

@drewfreyling
Copy link

Or at least providing context from a security perspective why it isn't a priority to the community.

@A-Fitz-Nelnet
Copy link

This issue is resolved by #49444. See docs in #49561.

@muuvmuuv
Copy link

muuvmuuv commented Jul 5, 2023

@A-Fitz-Nelnet yes, but does not seem to work well with inline critical option and CSP with only nonce and no unsafe-inline CSS.

@tomavic
Copy link

tomavic commented Aug 21, 2023

I've looked into many issues and seen that workaround of adding the optimization flag to angular.json

However, we need to know the official solution for such case as it is hard to find

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area: core Issues related to the framework runtime area: security Issues related to built-in security features, such as HTML sanitation core: stylesheets cross-cutting: CSP feature: under consideration Feature request for which voting has completed and the request is now under consideration feature Issue that requests a new feature freq2: medium security Issues that generally impact framework or application security
Projects
Development

No branches or pull requests