Repository navigation
fix: send security response headers - #120
Conversation
Krini sent no security headers, while any script in its origin can read the access token from /auth/api/token and the code editor loaded its workers from cdn.jsdelivr.net. - src/proxy.ts sends a Content Security Policy with a new nonce per request (script-src 'self' 'nonce-...' 'strict-dynamic', frame-ancestors 'none', object-src 'none', base-uri 'self', form-action 'self', worker-src 'self', connect-src 'self' https:); the root layout reads the nonce for next-themes, so all pages render per request - next.config.ts sends X-Content-Type-Options, X-Frame-Options, Referrer-Policy and Strict-Transport-Security with every response, and no X-Powered-By - the editor's workers are copied from ace-builds to public/ace/ before next dev and next build, and Ace loads them from there, so no script comes from a CDN; the privacy notice no longer names the CDN - e2e: the fixtures fail every test on a CSP violation or a CDN request; a new spec checks the headers, the nonces and the worker - docs: "Security headers" in deployment.md Co-Authored-By: Claude Opus 5.5 <[email protected]>
The image had LICENSE but not NOTICE, which carries the notices of shadcn/ui, the fonts and now Ace, whose workers Krini serves itself. The image check makes sure both files are there and that the image serves the editor's workers. Co-Authored-By: Claude Opus 5.5 <[email protected]>
- unit tests for the proxy matcher (pages and API routes match, static files don't), and that ACE_WORKERS are exactly the workers of the modes that @elixir-cloud/design imports - unstub globals after every test (vitest config) - dev docs: the copy of the editor's workers into public/ace/ Co-Authored-By: Claude Opus 5.5 <[email protected]>
- img-src allows https: origins: a login provider's logo may be an https URL, which the browser loads directly (unoptimized) - Strict-Transport-Security only in production builds, as it binds the whole host to HTTPS (e.g. next dev --experimental-https) - e2e: an image from the mock services' https origin breaks no policy Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
Reviewer's GuideAPIDefine and send the per-response CSP nonce and fixed security headers, and pass the nonce to Next.js so rendered scripts and next-themes comply with the policy.
Uses of the APIConfigure Ace workers after each Cloud Components module loads and pass the module through that configuration so editor workers use Krini’s origin.
ImplementationCopy the Ace worker files from the dependency version used by the design components into the directory Krini serves.
UIRemove the privacy notice’s disclosure of the Ace worker CDN now that the workers are self-hosted.
ConfigurationWire worker copying into development and production builds, include NOTICE in the image, and extend the image check for the notice and worker asset.
Ensure Vitest restores global stubs between tests.
DocumentationDocument the self-hosted editor workers for development and explain the response security headers and deployment considerations.
TestsTest the CSP and nonce generation, fixed headers, proxy matching and nonce forwarding, and the availability and configuration of the self-hosted Ace workers.
Fail end-to-end tests on CSP violations or CDN requests and verify the response headers, nonce propagation, static-file MIME handling, remote images, and self-hosted editor workers.
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## dev #120 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 20 23 +3
Lines 564 591 +27
Branches 160 163 +3
=========================================
+ Hits 564 591 +27 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Linked issuesChecked at commit 97754dc #112 fix: send security response headers · 6 of 6 met
|
There was a problem hiding this comment.
Hey - I've found 3 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="src/lib/ace-workers.ts" line_range="43" />
<code_context>
+ (event) => {
+ console.error(
+ `CSP violation: ${event.effectiveDirective} ${event.blockedURI}`,
+ );
+ },
+ );
</code_context>
<issue_to_address>
**Rolling upgrades mix worker versions**
When a browser keeps an editor page from the old build and requests its worker during or after a rollout to a build with an incompatible Ace worker protocol, the old page's worker request can reach a new replica and receive a worker built for a protocol-incompatible Ace version, so the editor's syntax checks fail.
Use build-versioned worker URLs and keep each build's workers available for pages still running that build.
</issue_to_address>
### Comment 2
<location path="src/lib/ace-worker-files.ts" line_range="35" />
<code_context>
+function copyAceWorkers(target: string): void {
+ mkdirSync(target, { recursive: true });
+ for (const worker of ACE_WORKERS) {
+ copyFileSync(
+ aceWorkerSource(worker),
+ join(target, `worker-${worker}.js`),
</code_context>
<issue_to_address>
**Concurrent builds corrupt worker files**
When a build or dev startup runs while another server in the same checkout is serving `public/ace/`, and a worker request overlaps the copy, `copyAceWorkers` copies directly into the directory an active server serves, so overlapping or interrupted copies expose empty or incomplete worker files and the editor's syntax checks fail.
Copy the complete worker set to a staging directory and publish it atomically so serving processes never see an in-progress set.
</issue_to_address>
### Comment 3
<location path="src/lib/security-headers.ts" line_range="37" />
<code_context>
+ // login providers' logos may be `https` URLs (`docs/operator-guide/login.md`)
+ "img-src 'self' https: data: blob:",
+ "font-src 'self'",
+ "connect-src 'self' https:",
+ // the syntax checks of the code editor (`src/lib/ace-workers.ts`)
+ "worker-src 'self'",
</code_context>
<issue_to_address>
**Development hot reload stops**
When the dev server runs over HTTP in a browser that treats WebSocket schemes separately from the page’s scheme, the `connect-src 'self' https:` directive blocks the dev server’s `ws://` or `wss://` HMR connection, so hot reload stops working.
Allow the dev server’s WebSocket schemes by adding `ws:` and `wss:` to `connect-src`.
</issue_to_address>Sourcery assessment
Needs a human reviewer. 3 findings to address first, and browsers cache the two-year HSTS policy and upgrade HTTP requests for this hostname on every port; if the host also serves an HTTP-only service, reverting the change will not immediately undo the resulting access failures for visitors who cached the policy. CSP-related breakage is otherwise reversible by correcting or removing the policy.
Blocking findings: src/lib/ace-workers.ts:43, src/lib/ace-worker-files.ts:35, src/lib/security-headers.ts:37
Browsers in which 'self' doesn't cover WebSockets would block the hot reload of next dev; production builds are unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
Krini sent no security response headers, although any script in its origin can read the user's access token from
/auth/api/token, and the code editor loaded its syntax-check workers fromcdn.jsdelivr.net. This PR covers finding M2 of the 0.1.0 pre-release review and the NOTICE line of L15.src/proxy.ts,src/lib/security-headers.ts): a new nonce for each request, following the Next.js guide:script-src 'self' 'nonce-…' 'strict-dynamic',frame-ancestors 'none',object-src 'none',base-uri 'self',form-action 'self',worker-src 'self',connect-src 'self' https:(the TES and WES origins are known only at runtime),style-src 'self' 'unsafe-inline'(React, the Cloud Components and Ace set styles at runtime),img-src 'self' https: data: blob:(a login provider'slogomay be anhttpsURL, which the browser loads directly),font-src 'self'.'unsafe-eval'andws:wss:(hot reload) only undernext dev.script-src 'self'inheaders(): Next.js renders inline scripts (RSC payload, bootstrap) and next-themes adds one, soscript-src 'self'alone breaks the app, and'unsafe-inline'would make the policy useless against injected scripts.headers()innext.config.ts, every response):X-Content-Type-Options: nosniff,X-Frame-Options: DENY,Referrer-Policy: strict-origin-when-cross-originand, in production builds only (notnext dev),Strict-Transport-Security: max-age=63072000, withoutincludeSubDomains. Browsers ignore HSTS over plain HTTP.poweredByHeader: false.@elixir-cloud/designhard-codes the CDN as Ace'sworkerPathand has nobasePathoption. Ace'ssetModuleUrltakes precedence overworkerPath, though. Sosrc/lib/ace-workers.tspoints the six workers of the modes that design loads to/ace/worker-<lang>.js, and starts them from their URL, not fromblob:. It runs in thethenof the dynamic imports of the Cloud Components.scripts/copy-ace-workers.tscopies the workers from theace-buildsthat design resolves, so the versions always match, intopublic/ace/(git-ignored) beforenext devandnext build. The privacy notice no longer names the CDN.COPY --from=build /app/LICENSE /app/NOTICE ./. NOTICE gains Ace's BSD notice, as Krini now serves Ace files itself.scripts/check-image.shchecks for LICENSE, NOTICE and/ace/worker-json.js.docs/operator-guide/deployment.md, which also notes that a proxy must not replace the CSP. "Network access" and "Production considerations" no longer mention the CDN.docs/development/index.mdexplains the copy intopublic/ace/.Verification
bun run lint: clean.bunx tsc --noEmit: clean.bun run test:coverage: 279 tests passed, 100 % statements, branches, functions and lines. New unit tests cover the policy, the nonce, the fixed headers, the proxy (new nonce per request, nonce passed on to the rendering), the proxy matcher (pages and API routes match, static files don't), the Ace configuration, that every worker exists inace-buildsand gets copied, and thatACE_WORKERSis exactly the set of workers of the modes that@elixir-cloud/designimports.CI=1 bun run test:e2e(Chromium and Firefox): 38 passed.securitypolicyviolationevent or any request tocdn.jsdelivr.net. So the whole journey (login and logout through the mock IdP, the TES and WES lists, submitting a workflow and a task, task details, the privacy notice) runs under the CSP without a violation.e2e/security-headers.spec.tschecks the headers on three pages, that each response gets a new nonce and that the page's scripts carry it, that an image from anhttpsorigin (as a remote provider logo) breaks no policy, nosniff on a static file, and that the editor starts its JSON worker from/ace/worker-json.js(200) under the policy.onerrorhandler was blocked and reported in both browsers.scripts/check-image.sh. The CI jobsBuild imageandEnd-to-end tests (image)cover them.CI passed,Build image(withcheck-image.sh),End-to-end tests (image), Chromium, Firefox,Scan imageand CodeQL. There are no open code scanning alerts. TheVercel – krinipreview fails, as it does ondev(30c7e34); it is not required.Notes
text, which has no worker. So today the CDN was contacted only by editors with JSON, YAML, XML, HTML, CSS or JavaScript. The e2e test switches an editor to JSON to exercise the worker path.'strict-dynamic'lets scripts that trusted scripts create through DOM APIs run. That is the trade-off Next.js recommends; markup injection (inline scripts and event handlers) is blocked.Declined review findings
Two review rounds (adversarial and quality). Fixed in round 1:
next devtooACE_WORKERSlist were untestedpublic/ace/Declined:
headers()innext.config.tsis fixed at build time, so a switch would need a new setting read by the proxy. It is documented instead: don't serve Krini on a host that serves other services over plain HTTP, and don't send the header twice from an ingress.upgrading.md: that file belongs to another open PR for this release (session handling). The new behaviour is in "Security headers" indeployment.md, and the release notes can point to it.https:loads (images, TES and WES) are wanted.directives()test helper for the unit and e2e tests: the two run in different runners (vitest, Playwright), so sharing the helper would couple them for 10 lines.loadEcc()helper for the six wrappers: a comment insrc/lib/ace-workers.tssays every dynamic import of the Cloud Components must usewithSelfHostedAce, and the e2e fixtures fail on any CDN request.Round 2 found nothing high or medium. These lows are declined:
@elixir-cloud/*/reactuseswithSelfHostedAce: all six do. The comment insrc/lib/ace-workers.tsstates the rule, and the e2e fixtures fail on any CDN request.@elixir-cloud/designchanges its layout: the test fails either way and names the file it read.public/ace/: answered in the threads. Old pages lose their_next/staticchunks on a rollout anyway, and the copy runs once per image build.http:provider logos inparseProvider: the docs already require anhttpsURL or a path. Checking the settings at start belongs to the follow-up for settings checks (finding L12-L14 of the review, fix: check the settings when Krini starts #103), not to this PR.Open questions
None.
Closes #112
🤖 Generated with Claude Code
Summary by Sourcery
Protect application responses with nonce-based security headers and serve code-editor workers from the application origin.
New Features:
Bug Fixes:
Enhancements:
Build:
Deployment:
Documentation:
Tests:
Chores: