-
Notifications
You must be signed in to change notification settings - Fork 4
feat(auth-service): nonce-based CSP and 5 security cucumber scenarios #100
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
Open
aspiers
wants to merge
1
commit into
main
Choose a base branch
from
hyper-security-scenarios
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| --- | ||
| 'ePDS': minor | ||
| --- | ||
|
|
||
| Auth service tightens its Content-Security-Policy and locks down the metrics endpoint. | ||
|
|
||
| **Affects:** Operators | ||
|
|
||
| **Operators:** the auth service's `Content-Security-Policy` response header now uses a per-response nonce on the `script-src` directive instead of `'unsafe-inline'`. The resulting policy looks like `default-src 'self'; script-src 'self' 'nonce-<base64url>'; style-src 'self' 'unsafe-inline'; img-src 'self' data: [client-origin]; connect-src 'self'`. All inline `<script>` tags that ePDS ships are already stamped with the matching nonce, so there is nothing to do on upgrade — but any operator-supplied HTML overlay or injected script that the auth service happens to serve inline will now be blocked by the browser unless it is updated to read `res.locals.cspNonce` and stamp `<script nonce="...">`. External scripts loaded via `src=` are unaffected. | ||
|
|
||
| The `/metrics` endpoint on the auth service is now deny-by-default: if `PDS_ADMIN_PASSWORD` is unset, the endpoint returns `401 Unauthorized` instead of serving metrics unauthenticated. Previously, unset meant "no auth required", which leaked process uptime, RSS memory, and database counters to anyone who could reach the auth service's `/metrics` path. Operators who relied on the open endpoint must set `PDS_ADMIN_PASSWORD` and send HTTP Basic auth as `admin:<password>` to continue scraping. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,210 @@ | ||
| /** | ||
| * Step definitions for security.feature. These scenarios run direct HTTP | ||
| * requests (no browser) because they assert on response headers, status | ||
| * codes, and raw HTML — not user interaction. | ||
| */ | ||
|
|
||
| import { When, Then } from '@cucumber/cucumber' | ||
| import type { DataTable } from '@cucumber/cucumber' | ||
| import type { EpdsWorld } from '../support/world.js' | ||
| import { testEnv } from '../support/env.js' | ||
|
|
||
| /** Response captured by the most recent direct-fetch step. */ | ||
| interface CapturedResponse { | ||
| status: number | ||
| headers: Headers | ||
| body: string | ||
| } | ||
|
|
||
| const capturedBySymbol = new WeakMap<EpdsWorld, CapturedResponse>() | ||
|
|
||
| function setCapturedResponse( | ||
| world: EpdsWorld, | ||
| response: CapturedResponse, | ||
| ): void { | ||
| capturedBySymbol.set(world, response) | ||
| world.lastHttpStatus = response.status | ||
| } | ||
|
|
||
| function getCapturedResponse(world: EpdsWorld): CapturedResponse { | ||
| const captured = capturedBySymbol.get(world) | ||
| if (!captured) { | ||
| throw new Error('No response has been captured by a prior step') | ||
| } | ||
| return captured | ||
| } | ||
|
|
||
| async function captureGet( | ||
| world: EpdsWorld, | ||
| url: string, | ||
| init?: RequestInit, | ||
| ): Promise<void> { | ||
| const res = await fetch(url, { redirect: 'manual', ...init }) | ||
| const body = await res.text() | ||
| setCapturedResponse(world, { status: res.status, headers: res.headers, body }) | ||
| } | ||
|
|
||
| // --------------------------------------------------------------------------- | ||
| // CSRF scenarios | ||
| // --------------------------------------------------------------------------- | ||
|
|
||
| When('the recovery page is loaded', async function (this: EpdsWorld) { | ||
| const recoveryUrl = `${testEnv.authUrl}/auth/recover?request_uri=urn:ietf:params:oauth:request_uri:req-security-probe` | ||
| await captureGet(this, recoveryUrl) | ||
| }) | ||
|
|
||
| Then('the response sets a CSRF cookie', function (this: EpdsWorld) { | ||
| const { headers } = getCapturedResponse(this) | ||
| const setCookie = headers.get('set-cookie') ?? '' | ||
| if (!/epds_csrf=/.test(setCookie)) { | ||
| throw new Error( | ||
| `Expected Set-Cookie to include epds_csrf=..., got: ${setCookie || '(none)'}`, | ||
| ) | ||
| } | ||
| }) | ||
|
|
||
| Then( | ||
| 'the HTML form contains a hidden CSRF token field', | ||
| function (this: EpdsWorld) { | ||
| const { body } = getCapturedResponse(this) | ||
| if (!/<input[^>]*type="hidden"[^>]*name="csrf"[^>]*>/.test(body)) { | ||
| throw new Error('HTML response has no hidden CSRF input field') | ||
| } | ||
| }, | ||
| ) | ||
|
|
||
| When( | ||
| 'a POST request is sent to the recovery endpoint without a CSRF token', | ||
| async function (this: EpdsWorld) { | ||
| const res = await fetch(`${testEnv.authUrl}/auth/recover`, { | ||
| method: 'POST', | ||
| headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, | ||
| body: new URLSearchParams({ | ||
| request_uri: 'urn:ietf:params:oauth:request_uri:req-security-probe', | ||
| email: 'noone@example.com', | ||
| }).toString(), | ||
| redirect: 'manual', | ||
| }) | ||
| const body = await res.text() | ||
| setCapturedResponse(this, { | ||
| status: res.status, | ||
| headers: res.headers, | ||
| body, | ||
| }) | ||
| }, | ||
| ) | ||
|
|
||
| Then('the response status is {int}', function (this: EpdsWorld, code: number) { | ||
| const { status } = getCapturedResponse(this) | ||
| if (status !== code) { | ||
| throw new Error(`Expected status ${code}, got ${status}`) | ||
| } | ||
| }) | ||
|
|
||
| // --------------------------------------------------------------------------- | ||
| // Security headers scenario | ||
| // --------------------------------------------------------------------------- | ||
|
|
||
| When( | ||
| 'any page is loaded from the auth service', | ||
| async function (this: EpdsWorld) { | ||
| await captureGet(this, `${testEnv.authUrl}/health`) | ||
| }, | ||
| ) | ||
|
|
||
| Then( | ||
| 'the response includes the following security headers:', | ||
| function (this: EpdsWorld, table: DataTable) { | ||
| const { headers } = getCapturedResponse(this) | ||
| const missing: string[] = [] | ||
| for (const row of table.hashes()) { | ||
| const expected = row.value | ||
| const actual = headers.get(row.header) | ||
| if (actual !== expected) { | ||
| missing.push( | ||
| `${row.header}: expected "${expected}", got "${actual ?? '(missing)'}"`, | ||
| ) | ||
| } | ||
| } | ||
| if (missing.length) { | ||
| throw new Error(`Security header mismatch:\n ${missing.join('\n ')}`) | ||
| } | ||
| }, | ||
| ) | ||
|
|
||
| // --------------------------------------------------------------------------- | ||
| // CSP scenario | ||
| // --------------------------------------------------------------------------- | ||
|
|
||
| When('the login page is loaded', async function (this: EpdsWorld) { | ||
| // /oauth/authorize on the PDS renders the auth-service login page via | ||
| // the epds-callback redirect chain, but hitting it without a valid | ||
| // request_uri triggers an error response before headers are set the | ||
| // way we want. The auth service exposes a preview route that renders | ||
| // the same login template, guarded by AUTH_PREVIEW_ROUTES. If preview | ||
| // is off, fall back to a probe of any auth-service page — the CSP | ||
| // header is applied globally by the security-headers middleware, so | ||
| // an auth-service /health response carries the same header. | ||
| const previewUrl = `${testEnv.authUrl}/preview/login` | ||
| let res = await fetch(previewUrl, { redirect: 'manual' }) | ||
| if (res.status === 404) { | ||
| res = await fetch(`${testEnv.authUrl}/health`, { redirect: 'manual' }) | ||
| } | ||
| const body = await res.text() | ||
| setCapturedResponse(this, { status: res.status, headers: res.headers, body }) | ||
| }) | ||
|
|
||
| Then( | ||
| 'the Content-Security-Policy header is present', | ||
| function (this: EpdsWorld) { | ||
| const { headers } = getCapturedResponse(this) | ||
| if (!headers.get('content-security-policy')) { | ||
| throw new Error('Content-Security-Policy header is not set') | ||
| } | ||
| }, | ||
| ) | ||
|
|
||
| function getScriptSrcDirective(csp: string): string { | ||
| const match = /(?:^|;\s*)script-src\s+([^;]+)/.exec(csp) | ||
| if (!match) { | ||
| throw new Error(`CSP is missing a script-src directive: "${csp}"`) | ||
| } | ||
| return match[1].trim() | ||
| } | ||
|
|
||
| Then( | ||
| 'the script-src directive does not allow unsafe-inline', | ||
| function (this: EpdsWorld) { | ||
| const { headers } = getCapturedResponse(this) | ||
| const csp = headers.get('content-security-policy') ?? '' | ||
| const scriptSrc = getScriptSrcDirective(csp) | ||
| if (/'unsafe-inline'/.test(scriptSrc)) { | ||
| throw new Error( | ||
| `script-src directive allows 'unsafe-inline': "${scriptSrc}"`, | ||
| ) | ||
| } | ||
| }, | ||
| ) | ||
|
|
||
| Then( | ||
| 'the script-src directive carries a per-response nonce', | ||
| function (this: EpdsWorld) { | ||
| const { headers } = getCapturedResponse(this) | ||
| const csp = headers.get('content-security-policy') ?? '' | ||
| const scriptSrc = getScriptSrcDirective(csp) | ||
| if (!/'nonce-[A-Za-z0-9_-]+'/.test(scriptSrc)) { | ||
| throw new Error(`script-src directive has no 'nonce-...': "${scriptSrc}"`) | ||
| } | ||
| }, | ||
| ) | ||
|
|
||
| // --------------------------------------------------------------------------- | ||
| // Metrics scenario | ||
| // --------------------------------------------------------------------------- | ||
|
|
||
| When( | ||
| 'GET \\/metrics is called on the auth service without credentials', | ||
|
Check warning on line 206 in e2e/step-definitions/security.steps.ts
|
||
| async function (this: EpdsWorld) { | ||
| await captureGet(this, `${testEnv.authUrl}/metrics`) | ||
| }, | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Use
timingSafeEqual()for the Basic auth secret comparison.authHeader !== expectedcompares a secret-derived value with a regular string comparison. Use the shared constant-time helper for this check. As per coding guidelines, "UsetimingSafeEqual()for all secret and token comparisons".🛡️ Proposed fix
📝 Committable suggestion
🤖 Prompt for AI Agents