Skip to content

Commit

Permalink
update csp default config
Browse files Browse the repository at this point in the history
  • Loading branch information
vejja committed Nov 14, 2023
1 parent f75159d commit b2415a7
Show file tree
Hide file tree
Showing 10 changed files with 44 additions and 27 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -44,14 +44,15 @@ security: {
crossOriginOpenerPolicy: 'same-origin',
crossOriginEmbedderPolicy: 'require-corp',
contentSecurityPolicy: {
'base-uri': ["'self'"],
'base-uri': ["'none'"],
'font-src': ["'self'", 'https:', 'data:'],
'form-action': ["'self'"],
'frame-ancestors': ["'self'"],
'img-src': ["'self'", 'data:'],
'object-src': ["'none'"],
'script-src-attr': ["'none'"],
'style-src': ["'self'", 'https:', "'unsafe-inline'"],
'script-src': ["'self'", 'https:', "'unsafe-inline'", "'strict-dynamic'", "'nonce-{{nonce}}'"],
'upgrade-insecure-requests': true
},
originAgentCluster: '?1',
Expand Down Expand Up @@ -107,7 +108,7 @@ security: {
basicAuth: false,
enabled: true,
csrf: false,
nonce: false,
nonce: true,
removeLoggers: {
external: [],
consoleType: ['log', 'debug'],
Expand Down
36 changes: 23 additions & 13 deletions docs/content/1.documentation/2.headers/1.csp.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,10 @@ You can also disable this header by `contentSecurityPolicy: false`.

## Default value

By default, Nuxt Security will set following value for this header.
By default, Nuxt Security will set following value for this header:

```http
Content-Security-Policy: base-uri 'self'; font-src 'self' https: data:; form-action 'self'; frame-ancestors 'self'; img-src 'self' data:; object-src 'none'; script-src-attr 'none'; style-src 'self' https: 'unsafe-inline'; upgrade-insecure-requests
Content-Security-Policy: base-uri 'none'; font-src 'self' https: data:; form-action 'self'; frame-ancestors 'self'; img-src 'self' data:; object-src 'none'; script-src-attr 'none'; style-src 'self' https: 'unsafe-inline'; script-src 'self' https: 'unsafe-inline' 'strict-dynamic' 'nonce-{{nonce}}'; upgrade-insecure-requests
```

## Available values
Expand Down Expand Up @@ -125,14 +125,15 @@ type CSPSandboxValue =

## Strict CSP

Nuxt Security helps you increase the security of your site via **strict CSP** support for both SSR and SSG applications.
Nuxt Security helps you increase the security of your site by enabling **Strict CSP** support for both SSR and SSG applications.

For further reading about Strict CSP and how to handle specific cases, please consult our [Adanced Section about Strict CSP](/documentation/advanced/strict-csp)

- For SSR applications, Nuxt Security implements strict CSP via nonces. A one-time cryptographically-generated random nonce is generated at runtime by the server for each request of a page.
- For SSG applications, Nuxt Security implements strict CSP via hashes. At static build-time, Nuxt Security computes the SHA hashes of the elements that are allowed to execute on your site.

If you want to enable strict CSP, we recommend that you configure the `contentSecurityPolicy` header as follows:

By default, Strict CSP will be enabled on your site. The following default configuration options are used:

```ts
export default defineNuxtConfig({
Expand All @@ -152,24 +153,31 @@ export default defineNuxtConfig({
"'nonce-{{nonce}}'" // Enables CSP nonce support for scripts in SSR mode, supported by almost any browser (level 2)
],
'style-src': [
"'self'", // Enables loading of stylesheets hosted on your own domain
"'self'", // Enables loading of stylesheets hosted on same origin
"https:", // For increased security, replace by the specific hosting domain or file name of your external stylesheets
"'unsafe-inline'" // Recommended default for most Nuxt apps
]
],
'img-src': ["'self'", "data:"], // Add relevant https://... sources if you load images from external sources
'font-src': ["'self'", "https:", "data:"], // For increased security, replace by the specific sources for fonts
'base-uri': ["'none'"],
'object-src': ["'none'"],
'script-src-attr': ["'none'"],
'form-action': ["'self'"],
'frame-ancestors': ["'self'"],
'upgrade-insecure-requests': true
}
}
},
sri: true
}
})
```

These default values will enable Strict CSP in the majority of cases.


## Server Side Rendering (SSR)

Nuxt Security provides first-class support of SSR apps via 'strict-dynamic' and nonces.

To enable Strict CSP in SSR mode, you will need to set the `nonce` option and the `"'nonce-{{nonce}}'"` placeholders:
In SSR mode, Strict CSP is enabled when you set the `nonce` option and the `"'nonce-{{nonce}}'"` placeholders:

```ts
export default defineNuxtConfig({
Expand Down Expand Up @@ -218,7 +226,7 @@ This will result in following code being added to your static app `<head>` tag:
::


To enable Strict CSP for SSG apps, you will need to set the `ssg` option:
For SSG apps, Strict CSP is enabled when you set the `ssg` and `sri` options:

```ts
export default defineNuxtConfig({
Expand All @@ -227,6 +235,7 @@ export default defineNuxtConfig({
hashScripts: true, // Enables CSP hash support for scripts in SSG mode
hashStyles: false // Disables CSP hash support for styles in SSG mode (recommended)
},
sri: true,
headers: {
contentSecurityPolicy: {
'script-src': [
Expand All @@ -243,6 +252,7 @@ Nuxt Security will generate script hashes and style hashes for you according to
- `hashScripts`: Set this option to `true` to parse all inline scripts as well as all external scripts. Nuxt-Security will compute the hashes of inline scripts and find the `integrity` attributes of external scripts, and will add them to your `script-src` policy.
- `hashStyles`: Set this option to `true` to parse all inline styles as well as all external styles. Nuxt-Security will compute the hashes of inline styles and find the `integrity` attributes of external styles, and will add them to your `style-src` policy.


::alert{type="warning"}
Our default recommendation is to avoid setting the `ssg: hashStyles` option to `true`.
<br>
Expand All @@ -252,9 +262,9 @@ For further discussion and alternatives, please refer to our [Advanced Section o
::

::alert{type="info"}
For SSG apps with `'strict-dynamic'` mode, external scripts will only be allowed to execute if they carry an integrity attribute.
Nuxt Security will automatically calculate the `integrity` attributes of all your bundled assets if you set the `sri` option to `true`. For unbundled assets, you may need to set the `integrity` attribute manually.
<br>
Please see our section on Integrity Hashes [below](#integrity-hashes-for-ssg)
Please see below our section on [Integrity Hashes For SSG](#integrity-hashes-for-ssg)
::

_Note: Hashes only work for SSG. The `ssg` options are ignored when you build your app for SSR via `nuxi build`._
Expand Down
4 changes: 3 additions & 1 deletion docs/content/1.documentation/5.advanced/3.strict-csp.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ Useful links on CSP:
- MDN [documentation](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP)
- OWASP CSP [cheatsheet](https://cheatsheetseries.owasp.org/cheatsheets/Content_Security_Policy_Cheat_Sheet.html)
- Auth0 blog series on [CSP](https://auth0.com/blog/defending-against-xss-with-csp/), [SPAs](https://auth0.com/blog/deploying-csp-in-spa/) and [finetuning](https://auth0.com/blog/from-zero-to-hero-with-csp/)
- Google's [CSP Overview](https://csp.withgoogle.com/)
- Google's [CSP Evaluator](https://csp-evaluator.withgoogle.com)
::

Expand Down Expand Up @@ -199,6 +200,7 @@ However, there are many important details that you should know:
2. **Hashes and Nonces are primarily intended for inline elements**. External resources are still supposed to be whitelisted the old way, i.e. by including the domain name or file name in the policy. However, CSP Level 2 added the option to also whitelist external resources by nonce, _but not by hash_. So:
- If you use **nonce**: Inline and external elements can be whitelisted by nonce. External elements can also be whitelisted by name.
- If you use **hash**: Inline elements can be whitelisted by hash. External elements still need to be whitelisted by name.
3. **Hashes and Nonces only work on scripts and styles**. It is useless to use them on other tags (`<img>`, `<frame>`, `<object>` etc.), or to inlude them in any policy other than `script-src` and `style-src`.
A common mistake is to try to whitelist an external image by nonce via the `img-src` policy: this will not work.
Expand Down Expand Up @@ -250,7 +252,7 @@ CSP Level 3 was designed by folks at Google who were facing the problems describ
What `'strict-dynamic'` does, is it allows a pre-authorized parent script to insert any child script. If the parent script is approved by its nonce or hash, then all children scripts do not need to carry a nonce or hash anymore.
::alert{type="info"}
For Nuxt, this solves the hydration problem, because the Nuxt root script (the _entry_ script) is itself pre-authorized.
For Nuxt, this solves the hydration problem, because Nuxt Security pre-authorizes your root script (the _entry_ script).
::
So when hydration time comes, the Nuxt root script can now insert any inline or external script.
Expand Down
8 changes: 5 additions & 3 deletions src/defaultConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,15 @@ export const defaultSecurityConfig = (serverlUrl: string): ModuleOptions => ({
crossOriginOpenerPolicy: 'same-origin',
crossOriginEmbedderPolicy: 'require-corp',
contentSecurityPolicy: {
'base-uri': ["'self'"],
'base-uri': ["'none'"],
'font-src': ["'self'", 'https:', 'data:'],
'form-action': ["'self'"],
'frame-ancestors': ["'self'"],
'img-src': ["'self'", 'data:'],
'object-src': ["'none'"],
'script-src-attr': ["'none'"],
'style-src': ["'self'", 'https:', "'unsafe-inline'"],
'script-src': ["'self'", 'https:', "'unsafe-inline'", "'strict-dynamic'", "'nonce-{{nonce}}'"],
'upgrade-insecure-requests': true
},
originAgentCluster: '?1',
Expand Down Expand Up @@ -72,7 +73,7 @@ export const defaultSecurityConfig = (serverlUrl: string): ModuleOptions => ({
basicAuth: false,
enabled: true,
csrf: false,
nonce: false,
nonce: true,
// https://github.com/Talljack/unplugin-remove/blob/main/src/types.ts
removeLoggers: {
external: [],
Expand All @@ -83,5 +84,6 @@ export const defaultSecurityConfig = (serverlUrl: string): ModuleOptions => ({
ssg: {
hashScripts: true,
hashStyles: false
}
},
sri: true
})
4 changes: 2 additions & 2 deletions src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,7 @@ const registerSecurityNitroPlugins = (
config.plugins.push(
normalize(
fileURLToPath(
new URL('./runtime/nitro/plugins/01m-subresourceIntegrity', import.meta.url)
new URL('./runtime/nitro/plugins/02-subresourceIntegrity', import.meta.url)
)
)
)
Expand All @@ -287,7 +287,7 @@ const registerSecurityNitroPlugins = (
config.plugins.push(
normalize(
fileURLToPath(
new URL('./runtime/nitro/plugins/02-cspSsg', import.meta.url)
new URL('./runtime/nitro/plugins/03-cspSsg', import.meta.url)
)
)
)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { H3Event } from 'h3'
import { extname } from 'pathe'
import { useStorage } from '#imports'
import { useStorage, defineNitroPlugin } from '#imports'
import * as cheerio from 'cheerio'

export default defineNitroPlugin((nitroApp) => {
Expand Down
File renamed without changes.
3 changes: 1 addition & 2 deletions test/fixtures/nonce/nuxt.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,7 @@ export default defineNuxtConfig({
"'self'", // backwards compatibility for older browsers that don't support strict-dynamic
"'nonce-{{nonce}}'",
"'strict-dynamic'"
],
'script-src-attr': ["'self'", "'nonce-{{nonce}}'", "'strict-dynamic'"]
]
}
}
}
Expand Down
7 changes: 5 additions & 2 deletions test/headers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ describe('[nuxt-security] Headers', async () => {
await setup({
rootDir: fileURLToPath(new URL('./fixtures/basic', import.meta.url)),
})
let res
let res: Response

it ('fetches the homepage', async () => {
res = await fetch('/')
Expand All @@ -32,9 +32,12 @@ describe('[nuxt-security] Headers', async () => {
expect(headers.has('content-security-policy')).toBeTruthy()

const cspHeaderValue = headers.get('content-security-policy')
const nonceValue = cspHeaderValue?.match(/'nonce-(.*?)'/)?.[1]

expect(cspHeaderValue).toBeTruthy()
expect(cspHeaderValue).toBe("base-uri 'self'; font-src 'self' https: data:; form-action 'self'; frame-ancestors 'self'; img-src 'self' data:; object-src 'none'; script-src-attr 'none'; style-src 'self' https: 'unsafe-inline'; upgrade-insecure-requests")
expect(nonceValue).toBeDefined()
expect(nonceValue).toHaveLength(24)
expect(cspHeaderValue).toBe(`base-uri 'none'; font-src 'self' https: data:; form-action 'self'; frame-ancestors 'self'; img-src 'self' data:; object-src 'none'; script-src-attr 'none'; style-src 'self' https: 'unsafe-inline'; script-src 'self' https: 'unsafe-inline' 'strict-dynamic' 'nonce-${nonceValue}'; upgrade-insecure-requests`)
})

it('has `cross-origin-embedder-policy` header set with correct default value', async () => {
Expand Down
2 changes: 1 addition & 1 deletion test/nonce.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ describe('[nuxt-security] Nonce', async () => {
const noncesInCsp = cspHeaderValue?.match(/'nonce-(.*?)'/)?.length ?? 0

expect(noncesInCsp).toBe(0)
expect(cspHeaderValue).toBe("base-uri 'self'; font-src 'self' https: data:; form-action 'self'; frame-ancestors 'self'; img-src 'self' data:; object-src 'none'; script-src-attr 'self' 'strict-dynamic'; style-src 'self' ; upgrade-insecure-requests; script-src 'self' 'strict-dynamic'")
expect(cspHeaderValue).toBe("base-uri 'none'; font-src 'self' https: data:; form-action 'self'; frame-ancestors 'self'; img-src 'self' data:; object-src 'none'; script-src-attr 'none'; style-src 'self' ; script-src 'self' 'strict-dynamic'; upgrade-insecure-requests")
})

it('injects `nonce` attribute in style tags', async () => {
Expand Down

0 comments on commit b2415a7

Please sign in to comment.