Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: make nonce implementation strict CSP compliant #256

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 4 additions & 20 deletions docs/content/1.documentation/2.headers/1.csp.md
Original file line number Diff line number Diff line change
Expand Up @@ -194,35 +194,19 @@ The `nonce` value is generated per request and is added to the CSP header. This
export default defineNuxtConfig({
routeRules: {
'/api/custom-route': {
nonce: false // do not check nonce for this route (1)
nonce: false // do not generate and inject nonce for this route
},
'/api/other-route': {
nonce: { mode: 'check' } // do not generate a new nonce for this route, but check it against the existing one (2)
}
}
})
```

There are two ways to use `nonce` in your application. Check out both of them and decide which one suits your needs best:
The only way to use `nonce` in your application is through the **`useHead` composable** - If you are dynamically adding script or link tags in your application using the `useHead` composable, all nonce values will be automatically added.

1. **`useHead` composable** - If you are dynamically adding script or link tags in your application using the `useHead` composable, all nonce values will be automatically added.
However, take note that due to [a current bug in unjs/unhead](https://github.com/unjs/unhead/issues/136), you'll need to add a workaround **when using ssr** to prevent double loading and executing of your scripts when using nonce.

```ts
// workaround unjs/unhead bug for double injection when using nonce
// by setting the mode to 'server'
// by setting the mode to 'client' or 'server'
// see: https://github.com/unjs/unhead/issues/136
useHead({ script: [{ src: 'https://example.com/script.js' }] }, { mode: 'server' })
```

2. **Directly inserting tags into DOM** - If you are unable or unwilling to use `useHead` and are inserting directly into the DOM (e.g. `document.createElement`), you can get the current valid nonce value using the `useNonce` composable:

```ts
const nonce = useNonce()
```

You can then use it with Nuxt Image like following:

```html
<NuxtImg src="https://localhost:8000/api/image/xyz" :nonce="nonce" />
useHead({ script: [{ src: 'https://example.com/script.js' }] }, { mode: 'client' })
```
5 changes: 0 additions & 5 deletions src/runtime/composables/nonce.ts
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To be fair, you can keep the nonce composable server-side.
It could be useful to expose the nonce to third-party modules when they run server-side, such as NuxtImg as you rightly pointed out.

return useNuxtApp().ssrContext?.event?.context.nonce

and drop the useCookie part

Copy link
Contributor Author

@trijpstra-fourlights trijpstra-fourlights Oct 20, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMO, this would then be the best solution: https://github.com/trijpstra-fourlights/nuxt-security/pull/1

as it allows the useNonce, even on SPA mode (although it will use the cookie in that case).

Interestingly enough, the <img> element does not have a nonce attribute according to mdn. So it doesn't apply there.

This file was deleted.

23 changes: 2 additions & 21 deletions src/runtime/server/middleware/cspNonceHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import { getRouteRules } from '#imports'

export type NonceOptions = {
enabled: boolean;
mode: 'renew' | 'check';
value: undefined | (() => string);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure about giving the developper a way to override crypto primitives which are vetted to be safe

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMO that's out of scope of this PR

}

Expand All @@ -16,26 +15,8 @@ export default defineEventHandler((event) => {
if (routeRules.security.nonce !== false) {
const nonceConfig: NonceOptions = routeRules.security.nonce

// See if we are checking the nonce against the current value, or if we are renewing the nonce value
let nonce: string | undefined
switch (nonceConfig?.mode) {
case 'check': {
nonce = event.context.nonce ?? getCookie(event, 'nonce')

if (!nonce) {
return sendError(event, createError({ statusCode: 401, statusMessage: 'Nonce is not set' }))
}

break
}
case 'renew':
default: {
nonce = nonceConfig?.value ? nonceConfig.value() : Buffer.from(crypto.randomUUID()).toString('base64')
setCookie(event, 'nonce', nonce, { sameSite: true, secure: true })
event.context.nonce = nonce
break
}
}
const nonce = nonceConfig?.value ? nonceConfig.value() : Buffer.from(crypto.randomUUID()).toString('base64')
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd leave it to just the crypto primitive

event.context.nonce = nonce

// Set actual nonce value in CSP header
csp = csp.replaceAll('{{nonce}}', nonce as string)
Expand Down
5 changes: 0 additions & 5 deletions test/fixtures/nonce/nuxt.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,6 @@ export default defineNuxtConfig({
],

routeRules: {
'/api/generated-script': {
security: {
nonce: { mode: 'check' }
}
},
'/api/nonce-exempt': {
security: {
nonce: false
Expand Down
15 changes: 0 additions & 15 deletions test/nonce.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,21 +24,6 @@ describe('[nuxt-security] Nonce', async () => {
expect(elementsWithNonce).toBe(expectedNonceElements)
})

it('does not renew nonce if mode is `check`', async () => {
// Make sure a nonce exists by doing the initial request
const originalRes = await fetch('/')
const originalCsp = originalRes.headers.get('content-security-policy')
const originalCookie = originalRes.headers.get('set-cookie')

// Then simulate the second request from the page to the specified route
const res = await fetch('/api/generated-script', { headers: { cookie: originalCookie } })

expect(res).toBeDefined()
expect(res).toBeTruthy()
expect(res.ok).toBe(true)
expect(res.headers.get('content-security-policy')).toBe(originalCsp)
})

it('injects `nonce` attribute in response when using useHead composable', async () => {
const res = await fetch('/use-head')

Expand Down
Loading