Code Monkey home page Code Monkey logo

ember-cli-content-security-policy's Introduction

ember-cli-content-security-policy

This addon makes it easy to use Content Security Policy (CSP) in your project. The policy can be delivered either via a Content-Security-Policy HTTP response header or as a meta tag in the index.html file.

If configured to deliver the CSP using a HTTP response header, the header is set automatically if served with Ember CLI's express server in development or via FastBoot in production. If FastBoot is not used to serve the app in production, the web server must be configured to set the CSP header. The configured CSP could be exported with a provided Ember CLI command.

If configured to deliver the CSP using the meta tag no additional configuration of the web server serving the application in production is needed.

In any case, using this addon helps keeping CSP in the forefront of your thoughts while developing an Ember application.

Compatibility

  • Ember.js v2.18 or above
  • Ember CLI v3.4 or above
  • Node.js v12 or above

Installation

ember install ember-cli-content-security-policy

Configuration

This addon is configured via config/content-security-policy.js file.

type directiveName =
  // Fetch Directives
  | 'child-src'
  | 'connect-src'
  | 'default-src'
  | 'font-src'
  | 'frame-src'
  | 'image-src'
  | 'manifest-src'
  | 'media-src'
  | 'object-src'
  | 'prefetch-src'
  | 'script-src'
  | 'script-src-elem'
  | 'script-src-attr'
  | 'style-src'
  | 'style-src-elem'
  | 'style-src-attr'
  | 'worker-src'
  // Document Directives
  | 'base-uri'
  | 'plugin-types'
  | 'sandbox'
  // Navigation Directives
  | 'form-action'
  | 'frame-ancestors'
  | 'navigate-to'
  // Reporting Directives
  | 'report-uri'
  | 'report-to'
  // Directives Defined in Other Documents
  | 'block-all-mixed-content'
  | 'upgrade-insecure-requests'
  | 'require-sri-for';

interface EmberCLIContentSecurityPolicyConfig {
  // CSP is delivered via HTTP Header if delivery includes `"header"` and via
  // meta element if it includes `"meta"`.
  delivery?: string;

  // Controls if addon is enabled at all.
  enabled?: boolean;

  // Controls if addon causes tests to fail if they violate configured CSP
  // policy.
  failTests: true;

  // A hash of options representing a Content Security Policy. The key must be
  // a CSP directive name as defined by spec. The value must be an array of
  // strings that form a CSP directive value, most likely a source list, e.g.
  // {
  //   'default-src': ["'none'"],
  //   'style-src': ["'self'", 'examples.com']
  // }
  // Please refer to CSP specification for details on valid CSP directives:
  // https://w3c.github.io/webappsec-csp/#framework-directives
  policy?: {[key: directiveName]: string[]};

  // Controls if CSP is used in report only mode. For delivery mode `"header"`
  // this causes `Content-Security-Policy-Report-Only` HTTP header to be used.
  // Can not be used together with delivery mode `"meta"` as this is not
  // supported by CSP spec.
  reportOnly?: boolean;
}

If you omit some or all of the keys, the default configuration will be used, which is:

// config/content-security-policy.js

module.exports = function (environment) {
  return {
    delivery: ['header'],
    enabled: true,
    failTests: true,
    policy: {
      'default-src': ["'none'"],
      'script-src': ["'self'"],
      'font-src': ["'self'"],
      'connect-src': ["'self'"],
      'img-src': ["'self'"],
      'style-src': ["'self'"],
      'media-src': ["'self'"],
    },
    reportOnly: true,
  };
};

Keywords such as self, none, unsafe-inline, nonces and digests must be wrapped in single quotes (') as shown above. Please find more details about valid source expression in ยง 2.3.1. Source Lists of CSP specification.

Changes to the configuration require a restart of a running Ember development server instance.

Example

If your site uses Google Fonts, Mixpanel, a custom API at custom-api.local and you want to deliver the CSP using a meta element:

// config/content-security-policy.js

module.exports = function (environment) {
  return {
    delivery: ['meta'],
    policy: {
      // Deny everything by default
      'default-src': ["'none'"],
      // Allow scripts at https://cdn.mxpnl.com/libs/mixpanel-2-latest.min.js
      'script-src': ["'self'", 'https://cdn.mxpnl.com/libs/mixpanel-2-latest.min.js'],
      // Allow fonts to be loaded from http://fonts.gstatic.com
      'font-src': ["'self'", 'http://fonts.gstatic.com'],
      // Allow data (xhr/websocket) from api-js.mixpanel.com and custom-api.local
      'connect-src': ["'self'", 'https://api-js.mixpanel.com', 'https://custom-api.local'],
      // Allow images from the origin itself (i.e. current domain)
      'img-src': ["'self'"],
      // Allow CSS loaded from https://fonts.googleapis.com
      'style-src': ["'self'", 'https://fonts.googleapis.com'],
      // Omit `media-src` from policy
      // Browser will fallback to default-src for media resources (which is 'none', see above)
      'media-src': null,
    },
    reportOnly: false,
  };
};

FastBoot Integration

This addon sets the CSP HTTP response header in FastBoot if it's enabled for the used environment and delivery contains "header". It does not override existing CSP headers.

If using reportOnly mode you must provide a valid reportUri directive pointing to an endpoint that accepts violation reports. As reportUri directive is deprecated you should additionally provide a reportTo directive, even so it's only supported by Google Chrome so far.

If you don't want the addon to inject the CSP header in FastBoot on production (e.g. cause CSP header should be set by a reverse proxy in front of FastBoot App Server), you should either remove "header" from delivery option or disable the addon entirely.

// config/content-security-policy.js

module.exports = function (environment) {
  return {
    enabled: environment !== 'production',
    delivery: ['header'],
  };
};

External Configuration

In order to configure your production web server, you can use the csp-headers Ember CLI command to obtain the configured Content Security Policy:

$ ember csp-headers --environment production --report-uri /csp-report

# Content Security Policy Header Configuration
#
# for Apache: Header set Content-Security-Policy-Report-Only "..."
# for Nginx : add_header Content-Security-Policy-Report-Only "...";

default-src 'none'; script-src 'self'; connect-src 'self'; img-src 'self'; style-src 'self'; report-uri /csp-report;

Development Support

Ember CLI's live reload feature requires a Web Socket connection. If live reload is used with ember serve or ember test --server the URL used for that Web Socket connection is injected into connect-src and script-src directives automatically.

Test Support

The addon helps you to ensure that your app or addon is compliant with a specific Content Security Policy by providing test support. It causes tests to fail if the code triggers a violation of the configured CSP.

It's recommended to test your project for CSP compliance. But you could disable it nevertheless by setting enabled option to false for test environment:

// config/content-security-policy.js

module.exports = function (environment) {
  return {
    enabled: environment !== 'test',
  };
};

Compatibility with other addons

Some addons are not compatible with a strict Content Security Policy. If you face any CSP violations caused by a third-party addon please report at their side. Often it's only a small change to required to make it compliant with a strict CSP. You may want to suggest adding this addon to test for compliance with a strict CSP.

For some addons compliance with a strict CSP requires a custom configuration. This documentation lists required configuration for some famous once.

Ember Auto Import

Ember Auto Import uses the eval function by default in development builds. This violates the default CSP policy. It's recommended to set Ember Auto Import's forbidEval option to true if using Content Security Policy. You should not add 'unsafe-eval' to script-src directive as this disables main security provided by CSP.

Embroider

Webpack, which is used by Embroider, uses the eval function by default in development builds to generate a source map. This violates the default CSP policy. It's recommended to configure Webpack to use 'source-map' strategy to generate source maps. To do so, add the following Embroider configuration:

return require('@embroider/compat').compatBuild(app, Webpack, {
  packagerOptions: {
    // other configuration
    webpackConfig: {
      devtool: 'source-map',
    },
  },
});

For addons using maybeEmbroider utility provided by @embroider/test-setup the configuration looks like this:

const { maybeEmbroider } = require('@embroider/test-setup');
return maybeEmbroider(app, {
  // other configuration
  packagerOptions: {
    webpackConfig: {
      devtool: 'source-map',
    },
  },
});

ember-cli-code-coverage

Ember-cli-code-coverage uses Istanbul, which injects new Function('return this') by default into the app. This requires 'unsafe-eval' to be allowed by the script directive. Currently there isn't any other option than either adding 'unsafe-eval' to script directive if code coverage is enabled or disable CSP at all. Details could be found in this issue.

Deprecations

Please find detailed information about deprecations in deprecation guide.

ember-cli-content-security-policy's People

Contributors

aortbals avatar avdv avatar chbonser avatar csantero avatar dependabot-preview[bot] avatar dependabot[bot] avatar ember-tomster avatar exelord avatar gabrielcousin avatar guidojw avatar jayden-leuciuc avatar jelhan avatar joeybg avatar kratiahuja avatar loganrosen avatar michalbryxi avatar mwpastore avatar nicomihalich avatar reidab avatar runspired avatar rwjblue avatar sandstrom avatar snewcomer avatar stefanpenner avatar turbo87 avatar webark avatar yoranbrondsema avatar zebraflesh avatar zg3d avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

ember-cli-content-security-policy's Issues

Cannot use direct output from ember csp-headers command

In trying to configure my server for the CSP headers, I'd like to be able to run the ember csp-headers command to populate an environment variable with the correct header value.

However, because of the information text included at the beginning of the command output, I cannot use this output directly.

I believe a simple option, such as raw or direct when flagged to true, will simply output the policy result.

"script-src 'self'" causes CSP violation with Ember inspector

Setting contentSecurityPolicy: {'script-src': "'self'"} on an Ember-CLI app causes a CSP violation, if that app is accessed on Windows (maybe also other OS) via latest stable Firefox with Ember Inspector addon installed. Here are the steps to reproduce:

  • On Windows (7) generate a new Ember app (latest ember-cli) and start: ember serve --host localhost
  • Add contentSecurityPolicy: {'script-src': "'self'"} to your environment.js
  • On latest stable Firefox install addon Ember Inspector (make sure that its tab appears at the inspector pane)
  • browse to http://localhost:4200/
  • you will get the CSP report. If not, click the reload button

I know that adding contentSecurityPolicy: {'script-src': "'self'"} to environment.js doesn't really make sense, because that's the default setting anyway. But nevertheless I think that CSP violation shouldn't occur. By the way, it doesn't happen with Chrome + Ember Inspector. Here is the CSP report:

{"csp-report":{
  "blocked-uri":"self",
  "document-uri":"http://localhost:4200/",
  "line-number":58,
  "original-policy":
    "script-src http://localhost:4200 http://localhost:35729 http://0.0.0.0:35729; 
     default-src 'none'; 
     font-src http://localhost:4200; 
     connect-src http://localhost:4200 ws://localhost:35729 ws://0.0.0.0:35729 http://localhost:4200/csp-report; 
     img-src http://localhost:4200; 
     style-src http://localhost:4200; 
     media-src http://localhost:4200; 
     report-uri http://localhost:4200/csp-report",
  "referrer":"",
  "script-sample":"call to eval() or related function blocked by CSP",
  "source-file":"resource://gre/modules/commonjs/toolkit/loader.js ->
                 resource://gre/modules/commonjs/sdk/loader/sandbox.js ->
                 resource://ember-inspector-at-emberjs-dot-com/ember-inspector/data/content-script.js",
  "violated-directive":"script-src http://localhost:4200 http://localhost:35729 http://0.0.0.0:35729"
}}

If I remove contentSecurityPolicy: {'script-src': "'self'"}, the CSP violation doesn't occur any longer.

frame-src and object-src required for SVG images in Chrome

I'm not sure what it's like in other browsers, but Chrome's console looks like someone slaughtered a small goat when you try to add something like this to the source:

<object class="header-icon" data="images/my-svg-image.svg" width="40"  height="23" type="image/svg+xml"></object>

Looks like object-src and frame-src should also be set to self.

Ember crashing

WIth a simple project ember seems to crash when url is visited. I really don't know the reason for this this is the error I get. Thanks!

 client   | Error: connect EHOSTUNREACH
 client   |     at errnoException (net.js:904:11)
 client   |     at connect (net.js:766:19)
 client   |     at net.js:845:9
 client   |     at asyncCallback (dns.js:68:16)
 client   |     at Object.onanswer [as oncomplete] (dns.js:121:9)

Bad processing of pre-defined source-list values

I am running ember-cli-content-security-policy 0.4.0.

Just copy-pasted your example to my environment.js:

ENV.contentSecurityPolicy = {
  'default-src': "'none'",
  'script-src': ["'self'", "https://cdn.mxpnl.com"], // Allow scripts from https://cdn.mxpnl.com
  'font-src': ["'self'", "http://fonts.gstatic.com"], // Allow fonts to be loaded from http://fonts.gstatic.com
  'connect-src': ["'self'", "https://api.mixpanel.com", "http://custom-api.local"], // Allow data (ajax/websocket) from api.mixpanel.com and custom-api.local
  'img-src': "'self'",
  'style-src': ["'self'", "'unsafe-inline'", "http://fonts.googleapis.com"], // Allow inline styles and loaded CSS from http://fonts.googleapis.com
  'media-src': null // `media-src` will be omitted from policy, browser will fallback to default-src for media resources.
}

My headers are then:

Content-Security-Policy-Report-Only: default-src 'none'; script-src 'self',https://cdn.mxpnl.com,e,l,f,', ,',u,n,s,a,f,e,-,e,v,a,l,' localhost:49152 0.0.0.0:49152; font-src 'self',http://fonts.gstatic.com,e,l,f,'; connect-src 'self',https://api.mixpanel.com,http://custom-api.local,l,f,' ws://localhost:49152 ws://0.0.0.0:49152 http://undefined:16013/csp-report; img-src 'self'; style-src 'self','unsafe-inline',http://fonts.googleapis.com,l,f,'; media-src null; report-uri http://undefined:16013/csp-report;

Please note the:

,e,l,f,', ,',u,n,s,a,f,e,-,e,v,a,l,'

part, and other strange parts. It seems that the post-processing that is being performed on the user-configured csp (ot add livereload, etc) is breaking things.

SVG (or possibly all object tags) still cause report-uri error

The report-uri fix that is currently on master seems to only partially work.

When adding SVG images to the page via an object tag:

<object class="header-icon" data="images/my-svg-image.svg" width="40"  height="23" type="image/svg+xml"></object>

the following error is shown in console:

The Content Security Policy 'default-src 'none'; connect-src 'self' ws://localhost:35729 ws://0.0.0.0:35729; font-src 'self' https://fonts.gstatic.com; frame-src 'self'; img-src 'self'; media-src 'self'; object-src 'self'; script-src 'self' localhost:35729 0.0.0.0:35729; style-src 'self' http://fonts.googleapis.com https://fonts.googleapis.com;' was delivered in report-only mode, but does not specify a 'report-uri'; the policy will have no effect. Please either add a 'report-uri' directive, or deliver the policy via the 'Content-Security-Policy' header.

The source line for that error is:

images/my-svg-image.svg:1

Upgrade to ember-cli-babel@^6.0.0

This addon is outdated with the recent Ember versions

[email protected]:
  version "0.5.0"
  resolved "https://registry.yarnpkg.com/ember-cli-content-security-policy/-/ember-cli-content-security-policy-0.5.0.tgz#059ce3157bcdab65c29b1d26c31682410293f1c4"
  dependencies:
    body-parser "^1.12.3"
    chalk "^1.0.0"
    ember-cli-babel "^5.0.0"
$> ember -v

ember-cli: 2.14.1
node: 8.2.1
os: darwin x64

No CORS headers set on 404 responses

Normal request:
Request Method:GET
Status Code:200 OK

Response:
Access-Control-Allow-Origin: http://localhost:4300

404 request:
Request Method:GET
Status Code:404 Not Found

(no Access-Control-Allow-Origin here)

This makes it hard to debug 404 pages when developing locally. Any ideas on how to fix this?

Google fonts and YouTube API

Hi, I've just updated to ember-cli 0.1.1 which includes this addon. Now I'm getting tons of reports as I'm using both Google Fonts and the YouTube iframe API. How should I handle these? Thank you very much.

GET http://localhost:35729/livereload.js?snipver=1 net::ERR_NETWORK_ACCESS_DENIED
[Report Only] Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src 'self' https://www.youtube.com/iframe_api localhost:35729".
[Report Only] Refused to load the stylesheet 'http://fonts.googleapis.com/css?family=PT+Sans:400,700,400italic' because it violates the following Content Security Policy directive: "style-src 'self'".
[Report Only] Refused to load the font 'http://fonts.gstatic.com/s/ptsans/v7/fhNmDCnjccoUYyU4ZASaLQLUuEpTyoUstqEm5AMlJo4.woff2' because it violates the following Content Security Policy directive: "font-src 'self'".

I attempted to edit the ENV.contentSecurityPolicy inside config/environment.js as this:

contentSecurityPolicy: {
      'default-src': "'none'",
      'script-src': "'self' https://www.youtube.com/iframe_api",
      'font-src': "'self'; fonts.googleapis.com; http://fonts.gstatic.com",
      'connect-src': "'self'",
      'img-src': "'self'",
      'style-src': "'self'"
    }

Support serving csp_report from other domains than 0.0.0.0 and localhost

I'm writing an app that uses WebRTC, which I need to serve it via valid HTTPS and I'm using ngrok for this. Currently when loading my app through ngrok domain, I'm getting:

Mixed Content: The page at 'https://xxxxxx.ngrok.io/' was loaded over HTTPS, but requested an insecure hyperlink auditing endpoint 'http://0.0.0.0:4200/csp-report'. This request has been blocked; the content must be served over HTTPS.

It looks like it can be easily fixed by adding req.hostname to a list of hosts here.

Firefox Inspector violates directive style-src

Using the Inspector on Firefox causes a CSP violation. This might be related to #38. I already applied ZebraFlesh@b851c05, but that does only concern script-src. Steps to reproduce:

  • On Windows (7) generate a new Ember app (latest ember-cli) and start: ember serve --host localhost
  • With latest stable Firefox browse to http://localhost:4200/
  • Open the inspector and play around with the selector and page elements
  • you will get CSP reports. They might not be shown in the console, but they'll appear in the network tab and in the console output of ember serve
    The CSP reports will be similar to:
{"csp-report":{
  "blocked-uri":"self",
  "document-uri":"http://localhost:4200/",
  "original-policy":
    "default-src 'none'; 
     script-src http://localhost:4200 'unsafe-eval' http://localhost:35729 http://0.0.0.0:35729; 
     font-src http://localhost:4200; 
     connect-src http://localhost:4200 ws://localhost:35729 ws://0.0.0.0:35729 http://localhost:4200/csp-report; 
     img-src http://localhost:4200; 
     style-src http://localhost:4200; 
     media-src http://localhost:4200; 
     report-uri http://localhost:4200/csp-report",
  "referrer":"",
  "script-sample":"width:100%;height:100%;",
  "source-file":"http://localhost:4200/",
  "violated-directive":"style-src http://localhost:4200"
}}

ember-cli yelling can't load script because it violates csp though I followed the docs on this repo

I am using ember-cli version 0.1.2 and "ember-cli-content-security-policy": "0.3.0".

I am trying to use stripe but everytime I submit a request to stripe and get a response, Ember-cli will yell at me with:

 [Report Only] Refused to load the script 'https://api.stripe.com/v1/tokens?card[number]=76&card[cvc]=90&card[exp_montโ€ฆpk_test_omMgQGUbGqdvwpHDg2L2crpm&callback=sjsonp1416392279257&_method=POST' because it violates the following Content Security Policy directive: "script-src 'self' 'unsafe-eval' localhost:35729 0.0.0.0:35729".

my config.js has:

   contentSecurityPolicy: {
    'default-src': "'none'",
    'script-src': "'self' 'unsafe-eval' http://*:35729 https://api.stripe.com/v1 ",
    'font-src': "'self'",
    'connect-src': "'self' http://*:35729 https://api.stripe.com",
    'img-src': "'self'",
    'style-src': "'self'",
    'media-src': "'self'"
  }

What else do I need to get this working

CSP reporter does not work on windows

During normal local development, the report-uri is computed as http://0.0.0.0:4200/csp-report. On unix based systems (including OS X), this is not a problem and the 0.0.0.0 is properly resolved to localhost or some equivalent. On Windows, the POST fails completely and CSP report is never logged to the console. Windows just doesn't like this address.

Getting CSP violations with latest version

Using the latest revision (0.1.2) results in the following browser console errors and the application (foo4) failing to load:

Refused to load the stylesheet 'http://localhost:4200/assets/vendor.css' because it violates the following Content Security Policy directive: "style-src self".
 localhost/:13
Refused to load the stylesheet 'http://localhost:4200/assets/foo4.css' because it violates the following Content Security Policy directive: "style-src self".
 localhost/:14
Refused to load the script 'http://localhost:4200/assets/vendor.js' because it violates the following Content Security Policy directive: "script-src self".
 localhost/:1
Refused to load the script 'http://localhost:4200/assets/foo4.js' because it violates the following Content Security Policy directive: "script-src self".
 localhost/:1
Refused to connect to 'ws://127.0.0.1:35729/livereload' because it violates the following Content Security Policy directive: "connect-src self localhost:35729".
 livereload.js?ext=Chrome&extver=2.0.9:193
Uncaught SecurityError: Failed to construct 'WebSocket': Refused to connect to 'ws://127.0.0.1:35729/livereload' because it violates the document's Content Security Policy. livereload.js?ext=Chrome&extver=2.0.9:193

The actual headers reported by the browser are as follows:

HTTP/1.1 200 OK
X-Powered-By: Express
Content-Security-Policy: ; default-src none; ; script-src self; ; connect-src self localhost:35729; ; img-src self; ; style-src self;
X-Content-Security-Policy: ; default-src none; ; script-src self; ; connect-src self localhost:35729; ; img-src self; ; style-src self;
Last-Modified: Tue, 30 Sep 2014 08:04:31 GMT
Cache-Control: private, max-age=0, must-revalidate
Content-Length: 1100
Content-Type: text/html; charset=UTF-8
Date: Tue, 30 Sep 2014 08:04:37 GMT
Connection: keep-alive

refactor configuration

The configuration of this addon doesn't feel inline with the rest of the ecosystem. This gets even worse if new configuration option are needed as it's the case for #91.

I like to suggest to refactor the configuration API as the following:

ENV['ember-cli-content-security-policy'] = {
  enabled: true,
  metaTag: false,
  policies: {
    'default-src': ["'none'"],
    'script-src':  ["'self'"],
    'font-src':    ["'self'"],
    'connect-src': ["'self'"],
    'img-src':     ["'self'"],
    'style-src':   ["'self'"],
    'media-src':   ["'self'"]
  },
  reportOnly: true,
}

The values shown above are suggested defaults.

For a transition period we might want to support existing configuration API. In that case the defaults would look like:

ENV['ember-cli-content-security-policy'] = {
  enabled: true,
  metaTag: ENV.contentSecurityPoliyMeta,
  policies: ENV.contentSecurityPolicy || {
    'default-src': ["'none'"],
    'script-src':  ["'self'"],
    'font-src':    ["'self'"],
    'connect-src': ["'self'"],
    'img-src':     ["'self'"],
    'style-src':   ["'self'"],
    'media-src':   ["'self'"]
  },
  reportOnly: ENV.contentSecurityPolicyHeader === 'Content-Security-Policy-Report-Only',
}

If we consider disabling the addon by setting ENV.contentSecurityPolicy === {} as a public API as suggested in #77, we might want to change the default for enabled to !ENV.contentSecurityPolicy || Object.keys(ENV.contentSecurityPolicy).length !== 0. We should deprecate the old configuration API at the same time. In that case this wouldn't be a breaking change but add some additional maintenance costs.

Please note that this API wouldn't require a change for #91. It would allow to disable throwing in tests by setting enabled = environment !== 'test'. metaTag option would be forced to true if running tests.

Difficult to extract a usable CSP using csp-headers command

We are working on automating our CSP generation during deployment and ran into a couple of small usability issues that I wanted to report to see what your take is on this kind of thing.

  1. Since the ember csp-headers command writes the CSP to stderr, we end up having to strip out any potential deprecation warnings from the output in order to get a valid CSP extracted:

Sample output:

$ ember csp-headers
DEPRECATION: Overriding init without calling this._super is deprecated. Please call `this._super.init && this._super.init.apply(this, arguments);` addon: `ember-data`
    at Function.Addon.lookup (/Users/jasonr/FrontEnd/node_modules/ember-cli/lib/models/addon.js:1617:27)
# Content Security Policy Header Configuration
#
# for Apache: Header set Content-Security-Policy "..."
# for Nginx : add_header Content-Security-Policy "...";

default-src self;
  1. Additionally, even if the output was to be moved to stdout instead of stderr, we would still need to strip out the preceding instructional content:
# Content Security Policy Header Configuration
#
# for Apache: Header set Content-Security-Policy "..."
# for Nginx : add_header Content-Security-Policy "...";

Proposal:

  1. Ensure the resulting CSP content is written to stdout instead of stderr
  2. Add a flag to suppress the instructional content (or move the instructional content to --help instead of always outputting it during csp generation)

Perhaps something like this:

$ ember csp-headers --csp-only
default-src self;

This way the output is easily pipeable into other scripts, readable from childProcess.exec, and generally just ready to be used as soon as it is returned to the caller.

Thanks for looking :) I can probably take a stab at it sometime soon if you agree that a change like this is desirable.

liveReloadHost option is not whitelisted in meta tag

liveReloadHost option is whitelisted in CSP headers but not in meta tag.

It's whitelisted in CSP header here: https://github.com/rwjblue/ember-cli-content-security-policy/blob/v1.0.0/index.js#L115

Something similar is needed for meta tag here: https://github.com/rwjblue/ember-cli-content-security-policy/blob/v1.0.0/index.js#L170

It's not that easy to fix cause the life reload host option is not pushed on process.env as port and base url are by ember-cli-live-reload: https://github.com/ember-cli/ember-cli-inject-live-reload/blob/master/index.js#L63-L64

It's not that critical cause ember-cli-live-reload seems to ignore the host option currently.

CLI command is not using refactored configuration

ember csp-headers is not using refactored configuration. Needs to be updated accordingly to #94 and #97. Should reuse calculateConfig function introduced in #97 to avoid similar issues.

This bug only affects current master as there wasn't a release since #94.

Add "worker-src" to policies

Report ...because it violates the following Content Security Policy directive: "worker-src 'none'" is thrown.

Build hangs under iojs

It looks like this code doesn't build under any version of iojs; running ember build causes the process to hang (and peg the CPU depending on the version of iojs). I started with the latest (1.8.1) and then cherry picked my way back to 1.0.0, all with the same result. I used nvm so I was always getting the correct iojs/npm pair. I'm running on OS X 10.10.3.

This is totally weird and I've never seen this sort of thing before. The build works fine under node.js 0.12.2.

List policies in a list instead of a long string

Following the suggestion received on PR #15 I'm now opening this issue to track the development of this discussion.

@givanse suggested using an array of strings to represent the single CSP rule โ€” this allows to programmatically manipulate the various rules.

@rwjblue liked the idea and mentioned the fact that we'd probably better define a deprecation path.

I added that maybe we could use csp: schema-prefixed keywords so that there's no need to mix single quotes (') and double quotes (") and to allow, once more, programmability.

Policy object should not be merged but replaced by application configuration

Currently the default policy object is merged with application configuration. This is confusing and is likely causing misconfiguation.

Lets assume someone tries to forbid any external assets. So he aims for a CSP Header as following:

Content-Security-Policy: default-src 'none';

He would most likely try a configuration as following:

let app = new EmberApp(defaults, {
  'ember-cli-content-security-policy': {
     policy: {
       'default-src': ["'none'"]
     }
  }
});

But that would result in the following CSP Header as it's merged with default policy object:

Content-Security-Policy: default-src 'none'; script-src 'self'; font-src 'self'; connect-src 'self'; img-src 'self' data:; style-src 'self'; media-src 'none';

In order to achieve the goal this configuration is needed:

let app = new EmberApp(defaults, {
  'ember-cli-content-security-policy': {
     policy: {
       'default-src': ["'none'"],
       'script-src':  null,
       'font-src':    null,
       'connect-src': null,
       'img-src':     null,
       'style-src':   null,
       'media-src':   null,
     }
  }
});

This is mentioned in README but easy to be missed:

To clear a directive from the default policy, set it to null.

The general refactoring of configuration done in #94 and #97 is a perfect time to change this in my opinion.

Having the policy object been merged might not have been a clear decision but might likely be caused by implementation details of Ember CLI's config hook.

Please note that the merging described here is currently broken in master due to #94. It will be fixed with #97, which also adds tests for this one. We would still need to support it for legacy run time configuration option contentSecurityPolicy to not add a breaking change.

still getting CSP violation report-only warning even if contentSecurityPolicy is overridden

Hi,

I'm using ember-cli to receive data from REST API backed by express at http://localhost:3000".
I have my env settings as follows

    contentSecurityPolicy: {
      'connect-src' : "'self' http://localhost:3000"
    }

While I can get the data and render it without problem, I'm still seeing a report-only warning as below:

[Report Only] Refused to load plugin data from '' because it violates the following Content Security Policy directive: "default-src 'none'". Note that 'object-src' was not explicitly set, so 'default-src' is used as a fallback.

This warning keeps bumping up until I override default-src from 'none' to 'self' in addition to the 'connect-src':

'default-src': "'self'",
...

Is this the expected behavior?

Here's the versions:

[Debug] DEBUG: ------------------------------- (vendor.js, line 15931)
[Debug] DEBUG: Ember      : 1.13.3 (vendor.js, line 15931)
[Debug] DEBUG: Ember Data : 1.13.5 (vendor.js, line 15931)
[Debug] DEBUG: jQuery     : 1.11.3 (vendor.js, line 15931)
[Debug] DEBUG: ------------------------------- (vendor.js, line 15931)

I'm using safari to test the page, it this matters.

Thanks,
Gan

Setting style-src using array results in junk output

ENV.contentSecurityPolicy {
            'default-src': "'none'",
            'style-src': ["https://fonts.googleapis.com"],
}

$ ember csp-header:
default-src 'none'; style-src https://fonts.googleapis.com s e l f ' u n a - i;

ENV.contentSecurityPolicy {
            'default-src': "'none'",
            'style-src': "https://fonts.googleapis.com",
}

$ ember csp-header:
default-src 'none'; style-src https://fonts.googleapis.com;

Oddly, only does this for style-src, all the others are fine.

$ember -v
version: 1.13.15
node: 8.9.0
npm: 2.14.10
os: darwin x64

package.json

...
        "ember-cli-content-security-policy": "^1.0.0",
...

This is somewhat problematic if one wishes to add multiple entries...

Doing this on 0.4.0 doesn't seem to cause the problem (but then 0.4.0 doesn't seem to work at all... as it URL encodes the meta tags...)

Hopefully I'm just being dense

how to handle data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=

I am not sure how to add this to my CSP. I have tried it in many forms and it always breaks my CSP rule when I add it.

My CSP:

contentSecurityPolicy: {
      'img-src': "'self' *.tile.osm.org data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=",
      'script-src': "'self' 'unsafe-eval' localhost:35729 0.0.0.0:35729 demo3.mysite.com",
      'connect-src': "'self' ws://localhost:35729 ws://0.0.0.0:35729 demo3.mysite.com"
    }

Console error (if I remove the data:image clause):

[Report Only] Refused to load the image 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=' because it violates the following Content Security Policy directive: "img-src 'self' *.tile.osm.org".

Add report-uri http://localhost:4200

Chrome throws additional errors when the CSP is active in Report-only mode but no report-uri is configured.

I think adding report-uri http://localhost:4200 to the CSP header would be fine for now.

Later on, we could add a blueprint for the server where we actually process the CSP reports.

Remove X- headers

From the http://content-security-policy.com/ website.

Note: It is known that having both Content-Security-Policy and X-Content-Security-Policy or X-Webkit-CSP causes unexpected behaviours on certain versions of browsers. Please avoid using deprecated X-* headers.

What do you make of this?

Docs don't match released version

The README currently refers to config/content-security-policy.js, but having recently installed this addon and having problems with config not being detected, I dug around and found that the installed version 1.1.1 doesn't include the new code required to read from the config file.

Thoughts on transferring to ember-cli org

Not a all required, if you are interested ember-cli org now exists now and as this repo provides core functionality you are welcome to transition it to that org.

I will be sure you continue to maintain existing commits + ownership.

If at this point in time you would prefer not to, this is fine. But if in the future you no-longer want to maintain this project, I will then gladly welcome it on the org.

Default settings don't work in Safari

Using ember-cli 1.13.6, generate a new application and run ember serve. Load the page in Chrome and Firefox, no CSP violations. Load the page in Safari 8.0.7 and you get: [Error] [Report Only] Refused to apply inline style because it violates the following Content Security Policy directive: "style-src 'self'". (localhost, line 0)

So far I haven't been able to crack this one. :(

Disable CSP

After installing the addon I noticed a slight delay in the Developer tools console. The page auto-loads as fast as usual, but the console remains in white-screen for about a second (maybe less).

It would be good to have an option, maybe in contentSecurityPolicyHeader, that turns it off.

Add command to output headers

It would be great if we could add a csp-headers command to ember to make copying the CSP-headers ridiculously easy. So I could just do:

ember csp-headers --environment production

And get the right headers for my production environment.

Reporter not logging reports from Firefox

The development reporter only accepts POSTs of type application/csp-report. Unfortunately it looks like the latest version of Firefox is doing POSTs with a mime type of application/json. The net result is that Firefox doesn't spit out any console logging for CSP violations, making it difficult to debug. Digging into CSP, it looks like Firefox correctly flags a lot of things that other browsers don't (specifically around SVG).

hashed unsafe-inline support?

unsafe-inline isn't sufficient to allow <script>...</script> on the page. CSP 2 requires those tags to have a hash of their contents. See https://www.w3.org/TR/2015/CR-CSP2-20150721/#script-src-hash-usage

Is there a way for this library to automatically calculate the hashes? Or should addons that use contentFor do the hashing and add the results to config.contentSecurityPolicy['script-src']? If the latter, could this addon expose an API to make that easier?

See also pgrippi/ember-cli-google-analytics#21

Default policy

A couple of issues with the default policy:

  • The README should probably say the default policy in development includes 'unsafe-eval' and that if you override the security policy you need to manually specify that as well,
  • If you have fonts, the default policy doesn't actually work,
  • Is there a reason the default policy isn't simply contentSecurityPolicy: { default-src: "'self'" } ?

UPDATE: I've also found that in practice as soon as you want to use say google maps apis, its effectively "pants down" as you have to add 'unsafe-inline' in addition to a few google api urls.

If there is a known way to avoid using 'unsafe-inline' with google maps I'd love to know.

csp-report not working on https

When running ember serve with the --ssl the csp report is using http instead of https and the request is blocked by the browser.

MIT License copyright

Thanks for licensing ember-cli-content-security-policy under the MIT License. Very helpful.

So we can give proper credit, would it be possible to provide who the copyright under the MIT License belongs to in your LICENSE.md?

Roadmap for v2.0

Disclaimer: This is only a proposal as I'm not the maintainer of this repo.

As you might have noticed I'm working on an incremental refactoring of the configuration of this addon. It makes sense to ship all changes in one release to avoid unnecessary noice.

I would suggest that next release includes these features:

  • Move configuration to ember-cli-content-security-policy namespace, introduce an explicit enabled option and reword other options. (#92, #94)
  • Move configuration to config/content-security-policy.js. (#30, #97, #104)
  • Policy object should be replaced by application configuration not merged. (#99, #101)

There are some pending feature requests that could be implemented having sensitive defaults without introducing a breaking change if shiped together with configuration changes:

  • Add an assertion to fail tests if CSP is violated. (#91)
  • Add CSP header in FastBoot if addon is enabled and delivery includes header. (#113)

I suggest shipping all of them with the next release.

Also there are some bugs/regressions introduced by refactoring that must be fixed before release:

  • CLI command is not using refactored configuration. (#98, #103)
  • Runtime configuration should not be injected if not needed (#116, #121)
  • Throws in FastBoot if disabled or delivery does not include header (#117, #118)
  • Ensure consistent test results by always using test environment for CSP affecting tests (#119, #122)

Steps to be done after release:

This would be a great foundation for jelhan/ember-style-modifier#11.

Example for development options

Maybe it would be useful to include in the README a open to all development example, something like:

if (environment === 'development') {
    ENV.contentSecurityPolicy = {
      'default-src': ["*"],
      'script-src':  null,
      'font-src':    null,
      'connect-src': null,
      'img-src':     null,
      'style-src':   null,
      'media-src':   null
    };
}

'self' not included despite being set

I'm using version 0.4.0 of this in ember-cli 0.2.3. In my environment.js I have included under contentSecurityPolicy:

'script-src': "'self'",

Now I get a CSP resport, comlaining about loading a ressource from "self" while there is specified:

("script-src http://localhost:4200 http://localhost:35729 http://0.0.0.0:35729")

I understand that these sources are added automatically, but why is "self" gone? if I do:

'script-src': "'self' http://localhost:3000",

I receive the same complaint, but stating:

("script-src http://localhost:4200 http://localhost:3000 http://localhost:35729 http://0.0.0.0:35729")

So the setting works, accept regarding "self".

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.