Fixing CSP errors related to Internet Identity on NextJS

Has anyone resolved these CSP errors on a NextJS app?

I run into these errors when I navigate to Internet Identity on my local application.

:4943/?canisterId=rdmx6-jaaaa-aaaaa-aaadq-cai#authorize:1 Refused to load the stylesheet 'https://gilroy-web-fonts.s3.amazonaws.com/web-fonts/gilroy.css' because it violates the following Content Security Policy directive: "style-src-elem 'self' 'unsafe-inline'".

Refused to load the stylesheet 'https://gilroy-web-fonts.s3.amazonaws.com/web-fonts/gilroy.css' because it violates the following Content Security Policy directive: "style-src-elem 'self' 'unsafe-inline'".

Here is my II component on NextJS:

import { AuthClient } from "@dfinity/auth-client";
import { HttpAgent } from "@dfinity/agent";

export default function IIButton() {

    async function InternetIdentityLogin() {
        let authClient = await AuthClient.create();
        await new Promise((resolve) => {
            authClient.login({
                identityProvider:
                    process.env.DFX_NETWORK === "ic"
                        ? "https://identity.ic0.app"
                        : `http://127.0.0.1:4943/?canisterId=rdmx6-jaaaa-aaaaa-aaadq-cai`
            });
        });
        const identity = authClient.getIdentity();
        const agent = new HttpAgent({ identity });
    }

    return (
        <div className="w-1/2 mb-4">
            <button onClick={async () => await InternetIdentityLogin()} className="btn btn-primary">Login</button>
        </div>
    );
};

I attempted to update the next.config.js file to this but to no avail.

const cspHeader = `
    default-src 'self' fonts.googleapis.com;
    script-src 'self' 'unsafe-eval' 'unsafe-inline';
    style-src 'self' fonts.googleapis.com gilroy-web-fonts.s3.amazonaws.com;
    style-src-elem 'self' fonts.googleapis.com gilroy-web-fonts.s3.amazonaws.com;
    img-src 'self' blob: data:;
    font-src 'self';
    object-src 'none';
    base-uri 'self';
    form-action 'self';
    frame-ancestors 'none';
    block-all-mixed-content;
    upgrade-insecure-requests;
`
 
module.exports = {
  async headers() {
    return [
      {
        source: '/(.*)',
        headers: [
          {
            key: 'Content-Security-Policy',
            value: cspHeader.replace(/\n/g, ''),
          },
        ],
      },
    ]
  },
}

I also tried to create a similar middleware.ts as suggested in the documentation provided by NextJS.

Hi @princess_eth :wave:

The issue is suprising because II, at least in recent versions, does not fetch any fonts from another platform. In the past it might have used google fonts directly from the css but, so far I know never fetched a fonts from aws so I’m really unsure the issue comes from II.

Are you sure the gilroy font is not used in your app?

Anyway given the fact that I notice the port 4943 in your error message, I assume the issue comes from the configuration of DFX, given that 4943 is the default port of dfx.

For the above reason, I don’t think that setting a CSP value in your next.config.js will have any effect unless this configuration becomes pre-rendered in the bundles.

Anyway, to try to solve or debug the issue can you have a look if you find a .ic-assets.json file (or .json5) in your project? Does it contains a CSP that would restrains the usage of those fonts? Can you try to adapt and redeploy and see if the issues persists?

Thank you for the response.

Here are the steps that I have taken. I’m still getting the errors.

  1. I did not have an .ic-assets.json. However, I did add a similar one to this one under src/assets:
[
    {
        "match": "**/*",
        "headers": {
            "Content-Security-Policy": "default-src 'self';script-src 'self' 'unsafe-eval';connect-src 'self' https://icp0.io https://*.icp0.io https://icp-api.io;img-src 'self' data:;style-src * 'unsafe-inline';style-src-elem * fonts.googleapis.com gilroy-web-fonts.s3.amazonaws.com;font-src *;object-src 'none';base-uri 'self';frame-ancestors 'none';form-action 'self';upgrade-insecure-requests;",
            "Permissions-Policy": "accelerometer=(), ambient-light-sensor=(), autoplay=(), battery=(), camera=(), cross-origin-isolated=(), display-capture=(), document-domain=(), encrypted-media=(), execution-while-not-rendered=(), execution-while-out-of-viewport=(), fullscreen=(), geolocation=(), gyroscope=(), keyboard-map=(), magnetometer=(), microphone=(), midi=(), navigation-override=(), payment=(), picture-in-picture=(), publickey-credentials-get=(), screen-wake-lock=(), sync-xhr=(), usb=(), web-share=(), xr-spatial-tracking=(), clipboard-read=(), clipboard-write=(), gamepad=(), speaker-selection=(), conversion-measurement=(), focus-without-user-activation=(), hid=(), idle-detection=(), interest-cohort=(), serial=(), sync-script=(), trust-token-redemption=(), window-placement=(), vertical-scroll=()",
            "X-Frame-Options": "DENY",
            "Referrer-Policy": "same-origin",
            "Strict-Transport-Security": "max-age=31536000; includeSubDomains",
            "X-Content-Type-Options": "nosniff",
            "X-XSS-Protection": "1; mode=block"
        }
    }
]

I added src/assets as a source under my frontend canister, and then ran the following commands:

dfx canister uninstall-code frontend
dfx deploy --upgrade-unchanged frontend
  1. I still receive the error upon navigating to II.

I’ll have to put some thought into this and troubleshoot a bit more.

2 Likes

I resolved the CSP errors by specifying using localhost:4943 instead of using the default 127.0.0.1:4943. I updated my dfx.json to this:

"networks": {
      "local": {
          "bind": "localhost:4943",
          "type": "ephemeral"
      }
  }

Do you know why using localhost:4943 matters for Internet Identity?

This error comes from AWS not from the IC. IC has no say in the matter. It’s the AWS server that is sending headers that make your browser reject the request. Probably the localhost and port 4943 is not allowed inside AWS configs. You could just download the fonts if you have a licence and put them in your app so everything gets served from the IC. No need for AWS at all.

I am actually not using these fonts in my project. I think these might be default to the Chrome browser because even the NNS dapp has these errors.

Neither NNS dapp nor II use the front gilroy nor fetch a font from amazon, period.

I think the issue is on your side, not in those dapps.

Given that the stacktrace you shared above mention an error chrome-extension, I would bet your problem root cause is a plugin you installed and used in your browser.

1 Like