I'm getting the following error when trying to display a video preview on my React app.
Refused to load media from 'data:video/mp4;base64,...' because it violates the following Content Security Policy directive: "default-src ". Note that 'media-src' was not explicitly set, so 'default-src' is used as a fallback. Note that '' matches only URLs with network schemes ('http', 'https', 'ws', 'wss'), or URLs whose scheme matches self's scheme. The scheme 'data:' must be added explicitly.
The thing is, that I'm not getting the Data Url fom any server, just from a file that the user chooses, so I don't understand why CSP has a problem with that...?
Here is my JSX implementation:
img.type === "video" && (
<video controls>
<source type="video/mp4" src={img.file} />
</video>
And that's my Helmet configuration (in my Node.js server):
app.use(
helmet.contentSecurityPolicy({
useDefaults: true,
directives: {
"img-src": ["'self'", "https: data:"],
"media-src": ["*", "'self'", "https:", "data:"],
"connect-src": [
"'self'",
"https://countriesnow.space/api/v0.1/countries",
],
},
})
);
I'm not sure what's the problem here... Thanks for helping!
You could try to use the alternate way of defining the directives that they show in the docs: https://helmetjs.github.io/
A lot of the non-docs sites that I found when researching this also use this method of defining the directives:
app.use(
helmet.contentSecurityPolicy({
useDefaults: true,
imgSrc: ["'self'", "https: data:"],
mediaSrc: ["*", "'self", "https:", "data:"],
connectSrc: [...]
}));
Seems silly that that would make a difference, but stranger things...
OK, so just to update, I found the problem, and it was a very silly one.. Apparently when you create a react app with create-react-app, they set CSP as meta settings in the index.html file and I didn't set the media-src over there. when I did, it worked just fine...
Thank for the answers!
Related
I'm trying to get auth0 to work with heroku, but having some difficulties.
I can get it to work locally without issues, but it just wouldn't work with Heroku
My setup:
React app which is being server from express as a static resource
Code for auth0 provider:
const providerConfig = {
domain: process.env.AUTH0_DOMAIN,
clientId: process.env.AUTH0_CLIENT_ID,
redirectUri: window.location.origin,
};
ReactDOM.render(
<Auth0Provider {...providerConfig}>
<BrowserRouter history={history}>
<App />
</BrowserRouter>
</Auth0Provider>,
document.getElementById("root")
);
The error I get when I try to login:
Refused to connect to 'https://small-dust-7659.eu.auth0.com/oauth/token' because it violates the following Content Security Policy directive: "default-src 'self'". Note that 'connect-src' was not explicitly set, so 'default-src' is used as a fallback.
Any help is much appreciated, thanks!
Auth0 needs to know about your origin, so it can allow cross-origin (CORS) requests to be made from your site on Heroku.
There's a detailed description on how to set this up here.
Basically on your applications page you can set up your origins and URLs.
The issue was to do with helmet configuration..
I added the auth0 domain to connectSrc and it solved the issue
helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
objectSrc: ["'none'"],
scriptSrc: ["'self'", "unpkg.com", "polyfill.io"],
styleSrc: ["'self'", "https: 'unsafe-inline'"],
----> connectSrc: ["'self'", "xxxxxx.eu.auth0.com"],
upgradeInsecureRequests: [],
},
},
});
I am currently developing an SPA using react. In order to serve the SPA I simply have an express server which serves the build folder as a static folder.
But whenever I try to run the application nothing loads and I get the console error:
Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-1kri9uKG6Gd9VbixGzyFE/kaQIHihYFdxFKKhgz3b80='), or a nonce ('nonce-...') is required to enable inline execution.
I've done a lot of googling but I can't find anything that works.
I've tried disabling helmets CSP but I still get the error.
I've tried uninstalling helmet, nothing.
Stopping and restarting the server, nope.
stopping everything, restarting the server and reopening chrome, nope.
Currently this is my use statement
App.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'unsafe-inline'", 'https://ajax.googleapis.com', 'https://stackpath.bootstrapcdn.com'],
styleSrc: ["'self'"],
imgSrc: ["*", 'data:'],
connectSrc: ["'self'"],
frameSrc: ["'self'"],
},
}
}));
because it's the same error no matter what I'm assuming the CSP isn't updating but I don't know enough to test this theory or what I could even do to remedy it.
After reading the comment from the helmet maintainer Evan Hahn, I did a little googling to remember the shortcut then just went to the site and hit ctrl-F5 to refresh the page and clear the cache at the same time, worked like a charm.
I am working on a react/express project. I have generated my npm build folder, but when I try to run it in my html browser, the favicon changes, besides that, nothing else displays.
app.use(globalErrorHandler);
if (process.env.NODE_ENV === "production") {
app.use(express.static(path.join(__dirname, "..", "public/build")));
app.get("*", (req, res) =>
res.sendFile(path.resolve(__dirname, "..", "public", "build", "index.html"))
);
}
Is there something i'm missing?
I am getting this error on the console
Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-81wjRQUIesSdM31ZewxoTpdk1zPOVbB5yDbEGkTCGjE='), or a nonce ('nonce-...') is required to enable inline execution.
Looks like you use Helmet 4 middleware, it publishes a default Content Security Policy.
Switch it off for a while or tune CSP rules to allow inline scripts (<script>... </script> construct).
When using a nodejs express application using the NPM "Helmet" package to install protective Headers, errors occur when using fontawesome: "kit_fontawesomecom_78f8060be1.js: 2 Refused to connect to 'https://ka-f.fontawesome.com/releases/v5. 15.1 / css / free.min.css' because it violates the following Content Security Policy directive: "default-src 'self'". Note that 'connect-src' was not explicitly set, so 'default-src' is used as a fallback. "
Apparently security is being violated. Is there a solution to these problems?
Solved by toggling contentSecurityPolicy: false:
helmet({
contentSecurityPolicy: false,
})
);
But this is not a solution to the problem, it is ignoring it.
An example of one of the posts in full:
kit_fontawesomecom_78f8060be1.js:2 Refused to connect to 'https://ka-f.fontawesome.com/releases/v5.15.1/css/free.min.css' because it violates the following Content Security Policy directive: "default-src 'self'". Note that 'connect-src' was not explicitly set, so 'default-src' is used as a fallback.
Thank you so much!
This is how it works:
app.use(
helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'", 'https://ka-f.fontawesome.com', 'https://fonts.gstatic.com'],
scriptSrc: ["'self'", "'unsafe-inline'", 'https://ka-f.fontawesome.com'],
styleSrc: ["'self'","'unsafe-inline'", 'https://ka-f.fontawesome.com', 'https://fonts.googleapis.com'],
// connectSrc: ["'self'", 'https://ka-f.fontawesome.com'],
connectSrc: ["'self'", 'https://ka-f.fontawesome.com'],
// reportUri: '/report-violation', // endpoint to get violation reports
},
reportOnly: false, // true for nonblocking mode, just to see violations
safari5: false
}));
Yeah, by opt contentSecurityPolicy: false, you just switch Off the Content Security Policy(CSP).
If you wish to use CSP (to make your app more secure), it need to set some rules if the default ones is no suitable. As seen from the console error, your web app loads fonts via fetch(), therefore you need to add https://ka-f.fontawesome.com source to the connect-src directive.
Something like that:
app.use(helmet.contentSecurityPolicy({
defaultSrc: ["'self'"],
scriptSrc: ["'self'"],
styleSrc: ["'self'"],
connectSrc: ["'self'", 'https://ka-f.fontawesome.com'],
// reportUri: '/report-violation', // endpoint to get violation reports
reportOnly: false, // true for nonblocking mode, just to see violations
safari5: false
}));
and then look at console errors or CSP reports what else is blocked and add related sources to the directives accordingly. https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP can helps at first steps.
instead of redefining all the directives, you can use the below code to only reset specific ones. This code redefines script source to 'self' and 'example.com'. Rest all remain as default
app.use(
helmet.contentSecurityPolicy({
directives: {
...helmet.contentSecurityPolicy.getDefaultDirectives(),
"script-src": [
"'self'",
"https://ka-f.fontawesome.com",
"https://kit.fontawesome.com",
],
"connect-src": ["'self'", "https://ka-f.fontawesome.com"],
},
})
);
I have a NodeJS/NextJS app running at http://www.schandillia.com. The project has a robots.txt file accessible at http://www.schandillia.com/robots.txt. As of now, the file is bare-bones for testing purposes:
User-agent: *
Allow: /
However, when I run a Lighthouse audit on my site, it throws a Crawling and Indexing error saying it couldn't download a robots.txt file. I repeat, the file is available at http://www.schandillia.com/robots.txt.
The project's codebase, should you need to take a look, is up at https://github.com/amitschandillia/proost. The robots.txt file is located at proost/web/static/ but accessible at root thanks to the following in my Nginx config:
# ... the rest of your configuration
location = /robots.txt {
proxy_pass http://127.0.0.1:3000/static/robots.txt;
}
The complete config file is available for review on github at https://github.com/amitschandillia/proost/blob/master/.help_docs/configs/nginx.conf.
Please advice if there's something I'm overlooking.
TL;DR: Your robots.txt is served fine, but Lighthouse can not fetch it properly because its audit can currently not work with the connect-src directive of of your site’s Content Security Policy, due to a known limitation which is being tracked as issue #4386 was fixed in Chrome 92.
Explanation: Lighthouse attempts to fetch the robots.txt file by way of a script ran from the document served by the root of your site. Here is the code it uses to perform this request (found in lighthouse-core):
const response = await fetch(new URL('/robots.txt', location.href).href);
If you try to run this code from your site, you will notice that a “Refused to connect” error is thrown:
This error happens because the browser enforces the Content Security Policy restrictions from the headers served by your site (split on several lines for readability):
content-security-policy:
default-src 'self';
script-src 'self' *.google-analytics.com;
img-src 'self' *.google-analytics.com;
connect-src 'none';
style-src 'self' 'unsafe-inline' fonts.googleapis.com;
font-src 'self' fonts.gstatic.com;
object-src 'self';
media-src 'self';
frame-src 'self'
Notice the connect-src 'none'; part. Per the CSP spec, it means that no URL can be loaded using script interfaces from within the served document. In practice, any fetch is refused.
This header is explicitly sent by the server layer of your by Next.js application, because of the way you configured your Content Security Policy middleware (from commit a6aef0e):
import csp from 'helmet-csp';
server.use(csp({
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", '*.google-analytics.com'],
imgSrc: ["'self'", '*.google-analytics.com'],
connectSrc: ["'none'"],
styleSrc: ["'self'", "'unsafe-inline'", 'maxcdn.bootstrapcdn.com'], // Remove unsafe-inline for better security
fontSrc: ["'self'"],
objectSrc: ["'self'"],
mediaSrc: ["'self'"],
frameSrc: ["'self'"]
}
}));
Solution/Workaround: To solve the problem in the audit report, you can either:
wait for (or submit) a fix in Lighthouse
use the connect-src 'self' directive, which will have the side effect of allowing HTTP requests from the browser side of your Next.js app