azure app insights throws a blocked:csp (content security policy) error - javascript

I am trying to use azure app insights in my react application. But when I am running this its failing to post events to azure server due to a csp error.
Refused to connect to 'https://eastus-8.in.applicationinsights.azure.com//v2/track' because it violates the document's Content Security Policy.
Refused to connect to '' because it violates the following Content Security Policy directive: "connect-src 'unsafe-inline' 'self'".
we are using these npm modules to setup insights
"#microsoft/applicationinsights-react-js": "^3.4.0",
"#microsoft/applicationinsights-web": "^2.8.9",
Below the configuration we are using:
import { ApplicationInsights } from '#microsoft/applicationinsights-web';
import { ReactPlugin } from '#microsoft/applicationinsights-react-js';
const { REACT_APP_INSIGHT_CONNECTION_STRING } = process.env;
export const reactPlugin = new ReactPlugin();
const appInsights = new ApplicationInsights({
config: {
connectionString: REACT_APP_INSIGHT_CONNECTION_STRING,
enableCorsCorrelation: true,
enableAutoRouteTracking: false,
extensions: [reactPlugin],
}
});
appInsights.loadAppInsights();
it should allow to post the events from our react app. please let me know if I am missing any configuration to fix this.

Related

Firebase Callable Cloud Function CORS Error using Firebase Emulator and Vite

The following is the client-side code to call the cloud function:
// add a new post
addPostForm.addEventListener('click', (e) => {
e.preventDefault();
const addPost = httpsCallable(functions, 'addPost');
addPost({
title: addPostForm.postTitle.value,
description: addPostForm.postDescription.value,
})
.then(() => {
addPostForm.reset(),
addPostModal.classList.remove('open');
addPostForm.querySelector('.error').textContent = '';
})
.catch(error => {
addPostForm.querySelector('.error').textContent = error.message;
})
});
The cloud function:
exports.addPost = functions.https.onCall((data, context) => {
if(!context.auth){
throw new functions.https.HttpsError(
'unauthenticated',
'only authenticated users can post'
);
}
if(data.text.length > 140){
throw new functions.https.HttpsError(
'invalid-argument',
'description must be no more than 140 characters long'
);
}
return admin.firestore().collection('Posts').add({
title: data.title,
description: data.description,
likes: '',
bookmarks: '',
});
});
Firebase Setup:
import { initializeApp, getApp } from "firebase/app";
import { getAuth, connectAuthEmulator } from "firebase/auth";
import { getStorage, connectStorageEmulator } from "firebase/storage";
import { getFirestore, connectFirestoreEmulator } from "firebase/firestore";
import { getFunctions, connectFunctionsEmulator } from "firebase/functions";
const firebaseConfig = {
"config"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const db = getFirestore(app);
const storage = getStorage(app);
const functions = getFunctions(getApp(), app);
if (window.location.hostname.includes("localhost")) {
connectAuthEmulator(auth, "http://localhost:9099");
connectFirestoreEmulator(db, 'localhost', 8080);
connectStorageEmulator(storage, 'localhost', 9199);
connectFunctionsEmulator(functions, "localhost", 5001);
}
export { auth, db, storage, functions };
Error
Access to fetch at 'http://localhost:5001/app/object/addPost'
From origin 'http://localhost:5173' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
What's the problem here? Will I need to set up firebase admin to grant access rights, and if I turn CORS off in the browser will that present a security issue on production?
After over a week of learning and trying to find the right solution for this problem, I came across a video from one of my favorite YT creators Web Dev Simplified.
Here he elegantly explains the CORS error and provides a simple yet effective solution. Installing the Express and CORS library through NPM within my cloud functions folder and requiring them both in the index.js file. Writing a function that allows you to change the access origin should be enough to solve this error.
const express = require("express");
const app = express();
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const cors = require('cors');
app.use(
cors({
origin: "*",
})
);
Changing the origin to "*" allows the access request origin to be from any source. You can also change this to a specific URL if you needed.
CORS error occurs when the request from a certain origin (eg. abc.com) is restricted to access resources on another origin (eg. xyz.com). This is a security measure enforced at the browser level and this is not related to Firebase setup.
There are two ways through which this can be solved,
Disable CORS in the browser. This is NOT recommended and should not be done for most cases.
If you are in control of the server, then you can modify your application to receive requests from a certain source.
In this case, you are in control of both the server and the client.
you just have to configure the server application (Cloud Functions in this case) to accept requests from the client.
For this, in the CF code, you can set the header Access-Control-Allow-Origin to the value of the client origin (Eg. localhost:PORT_NUM) or simply set the value to * to receive requests from all client origins.
As mentioned in the Answer, you can follow the checklist for the firebase callable functions cors errors :
Ensure the function is deployed.
Ensure the function name is correct. I was calling recalculatY when it should have been recalculateY. Got a cors error for some
reason.
Ensure the function code itself is not throwing an error. Use the emulator to
help.
This didn't throw a cors error, still helpful to know.
Ensure your regions match - I am using europe-west2. I had to both deploy the function with that region, and call it using the
region. For a while, I assumed the client would infer the correct
region if the function name was correct.
you can refer to the Documentation which explains about how to connect your app to cloud function emulator.
For more information , you can refer to the Answer and git issue.

Electron / Chrome: CSP connect-src not working - Security issue?

I am building an electron client app which finds a server on the local network and then connects to this server with socket.io. I'd like to secure the client by preventing it to connect to others servers than my own using CSP. Funny thing is: Though Chrome throws a CSP violation, it still connects.
Here are the important parts of my code:
main.js
function createWindow() {
mainWindow = new BrowserWindow({
width: 1200,
height: 600,
webPreferences: {
preload: path.join(__dirname, "preload.js"),
nodeIntegration: false,
enableRemoteModule: false,
contextIsolation: true,
sandbox: false,
},
});
mainWindow.loadFile("src/index.html");
}
preload.js
const { ipcRenderer } = require("electron");
const io = require("socket.io-client");
process.once("loaded", () => {
ipcRenderer.on("connectSocket", (event, data) => {
connectSocket(data);
});
});
function connectSocket(ip) {
const socket = io("http://" + ip + ":3000");
socket.on("connect", () => {
console.log("connected");
});
}
index.html meta tags
<meta
http-equiv="Content-Security-Policy"
content=" default-src 'self'; connect-src https://example.com"
/>
<meta
http-equiv="X-Content-Security-Policy"
content="default-src 'self'; connect-src https://example.com"
/>
So if the server is discovered at 192.168.178.99 (client at 192.168.178.11) and I pass this from my main process to the preloader to the connectSocket function, Chrome/Electron throws a CSP violation such as:
websocket.js:124 Refused to connect to 'ws://192.168.178.99:3000/socket.io/?EIO=3&transport=websocket&sid=hrNlyFY6i7-S1fUTAAAK' because it violates the following Content Security Policy directive: "connect-src https://example.com".
Which is correct. But then it connects anyways. Why is that? Shouldn't it only be able to connect to https://example.com?
At least it says so in the documentation:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/connect-src
This is on Chrome 83.0.4103.104, Electron 9.0.4, Node 12.14.1
I think the jsonp option in the Socket IO client explains this. Probably, the Socket IO Client detects that it cannot connect via Web Socket it automatically falls back to JSONP polling, which does not fall under connect-src.

localhost:4200 has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource

I am calling 2 GitHub API's but i am getting above error when I am printing the response in the console. I googled the error and tried fixing it by creating proxy.json file and modifying package.json file but it doesn't fix the error.
export class HomeComponent implements OnInit {
pythonJD:any[];
javaJD:any[];
constructor(private service: GithubService) { }
ngOnInit() {
this.python()
this.java()
}
python() {
this.service.getPython().subscribe(res => {
this.pythonJD = res;
console.log(res)
});
}
java() {
this.service.getJava().subscribe(res => {
this.javaJD = res;
console.log(res)
});
}
}
export class GithubService {
constructor(private http:HttpClient) { }
getPython():Observable<any>{
return this.http.get('https://jobs.github.com/positions.json?description=python&location=new+york');
}
getJava():Observable<any>{
return this.http.get('https://jobs.github.com/positions.json?description=java&location=new+york');
}
}
CORS is fixed on the api side. https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
For security reasons, browsers restrict cross-origin HTTP requests initiated from scripts. For example, XMLHttpRequest and the Fetch API follow the same-origin policy. This means that a web application using those APIs can only request resources from the same origin the application was loaded from, unless the response from other origins includes the right CORS headers.
Since you don't control github, so you can't add the CORS header on the client side, you need to configure a proxy to fix that.
You can configure angular cli for local testing using this guide: https://juristr.com/blog/2016/11/configure-proxy-api-angular-cli/
Check also angular-cli server - how to proxy API requests to another server? for official documentation

Meteor BrowserPolicy enable 'blob:' origins

I have enabled Content Security Policy meteor package meteor/browser-policy-common
Now I'm getting this error from ostrio:files related to CSP
Refused to create a worker from
'blob:http://localhost:3000/ef628f55-736b-4b36-a32d-b1056adfaa8c'
because it violates the following Content Security Policy directive:
"default-src 'self' http://fonts.googleapis.com
https://fonts.googleapis.com http://fonts.gstatic.com
https://fonts.gstatic.com http://code.ionicframework.com
https://code.ionicframework.com". Note that 'worker-src' was not
explicitly set, so 'default-src' is used as a fallback.
My actual browser-policy-common config looks like this
import { BrowserPolicy } from 'meteor/browser-policy-common';
// e.g., BrowserPolicy.content.allowOriginForAll( 's3.amazonaws.com' );
// BrowserPolicy.content.allowFontOrigin("data:");
BrowserPolicy.framing.disallow();
BrowserPolicy.content.disallowInlineScripts();
BrowserPolicy.content.disallowEval();
BrowserPolicy.content.allowInlineStyles();
BrowserPolicy.content.allowFontDataUrl();
const trusted = [
'fonts.googleapis.com',
'fonts.gstatic.com',
'code.ionicframework.com',
];
_.each(trusted, (origin) => {
BrowserPolicy.content.allowOriginForAll(origin);
});
Can you tell me which config should I change to allow ostrio:files blob:http://localhost:3000/... to work?
Thanks a lot!
To allow blob: origins, you can add this:
BrowserPolicy.content.allowOriginForAll('blob:');
Meteor doesn’t provide a mechanism for more specifically allowing blob: just for worker-src.

Ember js Error: Adapter operation failed

As a beginner to Ember.js I tried fetching some data from my Rails Api server to Ember App. My Ember App is trying to get and show the categories name served from the rails api.
I am using
Ember version: 1.13.8
node: 0.12.7
npm: 2.13.4
app/router.js
Router.map(function() {
this.resource('categories',function(){
this.resource('category',{path: '/:category_id'});
});
});
routes/categories/index.js
export default Ember.Route.extend({
model() {
return this.store.findAll('category')
}
});
app/models/category.js
export default DS.Model.extend({
name: DS.attr('string')
});
app/adapters/application.js
export default DS.JSONAPIAdapter.extend({
shouldReloadAll: function() { return true; },
namespace: 'v1',
host: 'http://ip.address-to_rails_api'
});
app/templates/categories/index.hbs
<ul>
{{#each model as |category|}}
<li>{{category.name}}</li>
{{/each}}
</ul>
Now when I visit http://ip.address-to_rails_api in my browser I get response
{"categories":[{"id":1,"name":"Entertainment"}, {"id":2,"name":"Education"}]}
but when I visit /categories in my ember app i.e. http://localhost:4200/categories
Noting is displayed in browser and I get error in ember inspector
routeName: "categories.index_error"
context: Error: Adapter operation failed
currentModel: Error: Adapter operation failed
Also the ember server console reflects error
Content Security Policy violation: {}
I also tried changing JSONAPIAdapter to RESTAdapter but it gave deprecation error. Please help me understand the problem.
Finally resolved the issue
The problem was on both parts Rails API as well as Ember App
First Error
Content Security Policy violation: {}
was removed by adding content security policy to ember app
config/environment.js
contentSecurityPolicy: {
'default-src': "'none'",
'font-src': "'self'",
'img-src': "'self'",
'media-src': "'self'",
'style-src': "'self' 'unsafe-inline'",
'script-src': "'self' 'unsafe-eval' http://ip_to_rails_api",
'connect-src': "'self' ws://ip_to_rails_api"
}
Then I got an error
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 404.
This error was resolved by using Cross Origin Resource Sharing or CORS on rails api end. SO that for each request the browser sends an OPTIONS request first and the server returns a response with some extra headers. The browser is then able to make the original request.
For more on CORS refer How does Access-Control-Allow-Origin header work?

Categories