Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

7.3 KB
Raw Blame

CSP + CSRF hardening, repo-wide

Branch feat/authz-manifest (same branch as the file-serving XSS fixes). Inventory done 2026-09-28 (two read-only sweeps; findings summarised here, file:line in the session log).

Where we are

  • CSP: object-src 'none'; base-uri 'self'; frame-ancestors 'self' only, set in apps/{erp,mes}/app/entry.server.tsx for DOCUMENT responses. No script-src, so it does nothing against XSS. Resource and .data responses get no security headers at all.
  • CSRF: nothing. The only defence is the carbon session cookie's SameSite=Lax, which (a) is None in the Test edition (and sent without Secure, which browsers reject), and (b) is scoped to the parent domain, so every *.carbon.ms host (docs, marketing, rest, learn, mes) is "same-site" to the ERP.
  • GET loaders that write — CSRF-able through Lax top-level navigation: kanban QR flow (api+/kanban.$id.tsx creates jobs/POs/transfers, redirects into MES x+/start / x+/end which start production events, issue material, finish operations), sales- and purchase-invoice new.tsx (create invoices), api+/settings.sequence.next.ts (increments a sequence), stock-transfer pick/unpick loaders, stripe-connect connect/dashboard.

Design

1. CSRF: one cross-origin check, no token (Go 1.25 CrossOriginProtection algorithm)

securityMiddleware (packages/auth/src/middleware/security.server.ts; the rules are pure in lib/security.ts), added to the root middleware of erp, mes, academy, starter. For POST/PUT/PATCH/DELETE:

  1. Path (with a trailing .data stripped) in the exemption list → allow. The list is only the endpoints browsers call cross-origin by design: /token, /register, /api/mcp.
  2. Sec-Fetch-Site is same-origin or none → allow; any other value → 403. same-site is refused on purpose (parent-domain cookie).
  3. No Sec-Fetch-Site: no Origin → allow (not a browser: webhooks, Inngest, the Rust assembler, the MES→ERP proxy, the stock-transfer self-POST, API-key clients). Origin equal to the request's host (x-forwarded-host ?? host, never request.url, which is the internal origin behind portless/Vercel) → allow; else 403.

Webhooks need no exemption: they send neither header. Unit-tested as a pure function of (method, path, headers).

2. GET writes

A rejectCrossSiteNavigation(request) guard (same file) at the top of each loader listed above: 403 when Sec-Fetch-Site: cross-site. none (QR scan, typed URL, bookmark), same-origin and same-site (the ERP→MES kanban redirect) pass, so no UX changes. api+/link.ts (company switch from notification emails) is left alone: webmail clicks are cross-site and it only switches between the user's own companies. Stripe-connect connect is left alone too: Stripe's refresh_url → callback → connect chain starts on stripe.com, and the worst a forged link does is open Stripe onboarding for the user.

3. CSP: nonce + strict-dynamic

  • A middleware makes a per-request nonce and puts it in router context; entry.server passes it to vercelHandleRequest(…, { nonce }). React Router's <Links>, <Scripts> and <ScrollRestoration> read it from framework context (also on error pages); the inline window.env script reads UNSAFE_FrameworkContext.

  • The policy is built by one pure function (buildContentSecurityPolicy, @carbon/auth lib/security.ts, tested) from config:

    default-src 'self';
    script-src 'nonce-…' 'strict-dynamic' 'wasm-unsafe-eval' [erp: 'unsafe-eval'] https: 'unsafe-inline';
    style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net;
    img-src 'self' data: blob: https:;
    font-src 'self' data: https://cdn.jsdelivr.net;
    connect-src 'self' <SUPABASE https + wss> <PostHog ingest + assets> https://places.googleapis.com https://cdn.jsdelivr.net;
    frame-src 'self' blob: data: https://www.youtube.com https://www.youtube-nocookie.com https://www.loom.com https://challenges.cloudflare.com;
    worker-src 'self' blob: data:;
    media-src 'self';
    object-src 'none'; base-uri 'self'; frame-ancestors 'self'
    

    Why each exception: wasm-unsafe-eval (HEIC/jSquash upload, meshopt, CAD import), unsafe-eval (ERP configurator runs new Function + TypeScript from unpkg), style-src 'unsafe-inline' (sonner, Radix, tiptap, <html style>), img-src https: (agent markdown images, Google favicons), jsdelivr (Monaco). form-action is omitted on purpose: Chrome applies it to the redirect after the OAuth /authorize consent POST. Academy adds Google Fonts.

  • Rollout: Content-Security-Policy-Report-Only + a same-origin /api/csp-report that logs (body capped), then flip to enforcing.

4. Headers on every response

nosniff, X-Frame-Options, Referrer-Policy, HSTS move from entry.server into a middleware so resource and .data responses get them too (routes that set their own CSP, like the file preview routes, keep it).

5. Cookies

Test edition: Secure whenever SameSite=None (session, oauth-state, console-pin). companyId gets the session cookie's SameSite/Secure rules.

Tasks

  • Decisions confirmed 2026-09-28: block cross-site only for GET writes; report-only first; keep ERP unsafe-eval, follow-up to remove
  • middleware/security.server.ts (pure rules in lib/security.ts + tests); wired into 4 roots
  • rejectCrossSiteNavigation in the GET-writing loaders
  • CSP builder + tests; nonce middleware; entry.server + root.tsx for 4 apps
  • /api/csp-report (all 4 apps)
  • security-headers middleware; trim applySecurityHeaders
  • cookie fixes
  • typecheck erp/mes/academy/starter/auth/utils (one at a time), tests, biome
  • Browser check (2026-09-28, local stack, agent-browser — it enforces CSP, verified with an injected handler → report → server WRN): login, 14 ERP module pages, MES login + operation page, PDF, image preview (XSS payload inert), thumbnail upload (wasm), same-site POST MES→ERP /logout + /api/* → 403 and session kept, cross-site link → kanban / MES start → 403 with nothing written, typed URL → kanban creates the PO, ERP→MES link starts the operation, real same-origin form POST passes. Found + fixed: zod's JIT new Function probe reported on every MES page → app/zod.client.ts (z.config({ jitless: true })), imported FIRST by each root.tsx (React Router's hydration script loads route modules before entry.client, so entry.client was too late). Not covered: MFA, OAuth consent, configurator (no demo data), PostHog (no key locally)
  • .claude/rules/authentication-system.md + packages/auth/AGENTS.md

Follow-ups (not in this change)

  • Drop 'unsafe-eval': bundle Monaco + TypeScript and run configurator code in a worker.
  • api+/webhook.onshape.$companyId.ts has no signature check (capability URL only).
  • Turnstile script-src-elem was reported twice on the ERP login page, both right after a dev server reload; four normal loads reported nothing. If production reports show it, pass the nonce to the widget (scriptOptions.nonce, react-turnstile supports it).
  • Pre-existing, found while testing: /file/model/$id fetches bundled demo models (_templates/…) through the public model route, which only serves <companyId>/models/… → 404 (on main too); $bucket preview throws a 500 (not 404) for a malformed path.