microsoft / ApplicationInsights-JS

Microsoft Application Insights SDK for JavaScript
MIT License
650 stars 240 forks source link

[BUG] Since release 3.2.0 there are CSP violations attempting to connect to js.monitor.azure.com (using npm not snippet) #2341

Open adrian-heath opened 6 months ago

adrian-heath commented 6 months ago

Description/Screenshot

Since updating to 3.2.0 we are now getting CSP violations connecting to js.monitor.azure.com. This was not happening in 3.1.2. We are using npm and the javascript initialization, not the snippet because we have a policy of not loading scripts from external domains.

image

Steps to Reproduce

using npm package

const appInsights = new ApplicationInsights({
    config: { instrumentationKey: appInsightsKey, disableCookiesUsage: true },
})
appInsights.addTelemetryInitializer((envelope) => {
    if (envelope.tags) {
        envelope.tags['ai.cloud.role'] = 'ui'
    }
})
appInsights.loadAppInsights()

Expected behavior

applicationinsights-web implemented via npm will not load javascript from an external site

Additional context We have a very strict CSP that blocks loading of scripts from external sites. This cause a production showstopper for us since it was not listed as a breaking change that external scripts would now be loaded

MSNev commented 6 months ago

Its not actually a script that it's loading, but it is reaching out to download a json file, we documented this process here https://github.com/microsoft/ApplicationInsights-JS?tab=readme-ov-file#service-notification as we have been preparing for this for the last few versions.

Adn we have documented how to disable this capability here https://github.com/microsoft/ApplicationInsights-JS/blob/main/docs/WebConfig.md#basic-usage

Karlie-777 commented 6 months ago

please try disable downloading the script by following https://github.com/microsoft/ApplicationInsights-JS/blob/main/docs/WebConfig.md#disable-fetching-from-cdn please let us know if it works!

ad-eg-dk commented 5 months ago

I'm seeing the same issue. I must say that after reading the documentation it is not at all clear to me what these plugins are.

A couple of questions:

  1. What is cfgSync plugin? Readme file says "Application Insights CfgSync Plugin enables configuration change communication among mutiple instances." and then links to the main page of AppInsights repository. What are multiple instances? This is the JS SDK, so are instances people's browsers? Are they communicating among each other now?
  2. What does throttle manager do? Seems needed if I use instrumentation key (? but somehow wasn't in <3.2). What if I'm using a connection string only?
  3. If cfgSync's "fetching from cdn" fails (due to CSP or other reasons), does the rest of AppInsights (sending telemetry) still works (assuming it's allowed by CSP and nothing else blocks it)?
  4. What do I lose if I disable "fetching from cdn"? Do I disable it separately for cfgSync and throttle manager?
  5. Is http://js.monitor.azure.com the only location for that json configuration file? In other words, is it a constant I can add to CSP to connect-src or does it change? If it changes, how do I know what url to add to CSP?
Karlie-777 commented 5 months ago

Hi @ad-eg-dk

  1. Usages: a. when one application has multiple appInsights SDKs initialized, the plugin allows those SDKs to communicate their configuration changes through web events. (not used now) b. the plugin also allows an Initialized SDK to communication with a remote cfgsync CDN endpoint (default one is https://js.monitor.azure.com/scripts/b/ai.config.1.cfg.json) and this is enabled by default.
  2. If your SDK is initialized with instrumentation key not a connection string, "iKey deprecation" messages will be sent during initialization process. Currently those messages are thrown at a very low sampling rate and the rate will be higher gradually, since iKey support will end soon. If your SDK is initialized with connection string, no messages will be sent out.
  3. It won't block other process/functions.
  4. If fetching from CDN is disabled, the communication between the cfgSync CDN and SDK will be disconnected. Throttle Mgr will throttle messages at sampling rate returned from cfgSync CDN. If fetching is disabled, the message will not be sent unless the config disableIkeyDeprecationMessage (https://github.com/microsoft/ApplicationInsights-JS#:~:text=disableIkeyDeprecationMessage) is set to false
  5. http://js.monitor.azure.com is the default one, you can set cfgUrl to your own endpoint https://github.com/microsoft/ApplicationInsights-JS/tree/main/extensions/applicationinsights-cfgsync-js#:~:text=configuration%20change%20details.-,cfgUrl,-string%0A%5BOptional%5D
cleverer commented 4 months ago

Hi There

After probably 1h of 2 devs struggling with this, we understood the following:

For users like us, who already switched to connection strings after the first deprecation notice, this creates a load of unnecessary complexity, which is not needed and very badly documented. We get warnings about access to the cdn, as we have a very strict Content-Security Policy set on our app, which does not allow connecting to random new endpoints, which are not documented in any release notes.

I would wish for release notes to not only contain technical changes ("feature opt in is now default for config sync and throttlemanager") which are very cryptic and not understandable at all, but also a high level description like: "hey, we now enable this so we can make others aware of the deprecation. If you already migrated, you can ignore the warnings/turn off the features."

lmarquinez commented 3 months ago

How can I desactivate the functions so that I don't get this error with https://js.monitor.azure.com/scripts/b/ai.config.1.cfg.json ? Im using the connection strings.

Karlie-777 commented 3 months ago

https://github.com/microsoft/ApplicationInsights-JS/blob/main/docs/WebConfig.md#disable-fetching-from-cdn

babakamyljanovssw commented 2 weeks ago

Hi @Karlie-777

Thanks for looking at this issue, we have tried your suggestion but it is not working.

We are seeing many occurrences of GET https://js.monitor.azure.com/scripts/b/ai.config.1.cfg.json dependency failures in our logs. I provided code of app insights implementation in our gatsby site. Could you please look at this if I missed something?

Image Figure: 608 occurrences for last 24 hours

gatsby-node.js - is used to log when building app

const appInsights = require('applicationinsights');

if (process.env.APPLICATIONINSIGHTS_CONNECTION_STRING) {
  // Log build time stats to appInsights
  appInsights
    .setup()
    .setAutoCollectConsole(true, true) // Enable logging of console.xxx
    .start();
} else {
  // eslint-disable-next-line no-console
  console.warn(
    'Missing APPLICATIONINSIGHTS_CONNECTION_STRING, this build will not be logged to Application Insights'
  );
}

useAppInsights.js - hook that implements app insights methods and used in pages

export default function useAppInsights() {
  const ai =
    typeof window !== 'undefined' &&
    process.env.APPLICATIONINSIGHTS_CONNECTION_STRING &&
    new ApplicationInsights({
      config: {
        connectionString: process.env.APPLICATIONINSIGHTS_CONNECTION_STRING,
        extensionConfig: {
          // below config was added to avoid "https://js.monitor.azure.com/scripts/b/ai.config.1.cfg.json" errors
          // issue - https://github.com/microsoft/ApplicationInsights-JS/issues/2341
          ['AppInsightsCfgSyncPlugin']: {
            cfgUrl: '',
          },
        },
      },
    });

  if (ai) {
    ai.loadAppInsights();
    ai.addTelemetryInitializer((item) => {
      item.tags['ai.cloud.role'] = 'SSW.Rules-StaticClientPage';
    });
  }

// other functions .....

  const appInsights = {
    trackPage,
    trackException,
    trackEvent,
    trackTrace,
  };

  // store instance
  if (typeof window !== 'undefined') {
    window['appInsights'] = appInsights;
  }

  return appInsights;
}

gatsby-browser.js - here tracking pages

export const onRouteUpdate = () => {
  if (window.appInsights && window.appInsights.trackPage) {
    window.appInsights.trackPage();
  }
};
Karlie-777 commented 1 week ago

@babakamyljanovssw Is the number of occurrences decreased? It is possible that some cached resources are still being used

babakamyljanovssw commented 1 week ago

Hey @Karlie-777 Yep, it has decreased a lot. 🤞 that it will go away eventually. Thanks!