Commit Graph

380 Commits

Author SHA1 Message Date
Hartmut dc5bbdc47d feat: centralize app base URL — no localhost fallback in production
Introduce getAppBaseUrl() in packages/api/src/lib/app-base-url.ts:
- Reads NEXTAUTH_URL (trimmed, trailing slash stripped)
- production: throws if NEXTAUTH_URL is missing/empty so broken
  localhost links in emails are caught at runtime, not silently sent
- development/test: falls back to http://localhost:3100 with a
  one-time console.warn

Replace the duplicated inline fallback in:
- packages/api/src/router/invite.ts (invite email link)
- packages/api/src/router/auth.ts (password reset email link)

Extend GET /api/health to report:
  "baseUrl": { "configured": bool, "isLocalhost": bool }
so deployment checks can detect a misconfigured NEXTAUTH_URL.

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-04-02 14:19:19 +02:00
Hartmut fceceeee4b feat: SMTP full ENV override, password reset flow, and E2E email testing
- SMTP: SMTP_HOST/PORT/USER/FROM/TLS now all have ENV override support
  (previously only SMTP_PASSWORD was env-aware). ENV takes priority over DB.
- docker-compose.yml: forward all SMTP_* env vars to app container + add
  Mailhog service (ports 1025 SMTP / 8025 HTTP, always available in dev)
- Password reset: PasswordResetToken Prisma model + authRouter with
  requestPasswordReset (timing-safe, no email enumeration) + resetPassword
- UI: /auth/forgot-password, /auth/reset-password/[token] pages +
  "Forgot password?" link on sign-in page
- E2E: Mailhog helpers (getLatestEmailTo, clearMailhog, extractUrlFromEmail)
  + invite-flow.spec.ts + password-reset.spec.ts

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-04-02 08:55:39 +02:00
Hartmut e5ecea81c5 fix(auth): resolve MFA post-activation login failures — tickets #38 #40 #41
#41 (critical): Replace plain Error throws in authorize() with CredentialsSignin
subclasses (MfaRequiredError / MfaRequiredSetupError / InvalidTotpError).
Auth.js v5 forwards CredentialsSignin.code to the client via SignInResponse.code;
plain throws become CallbackRouteError and the message is never visible.
Signin page now checks result.code ?? result.error for exact code matching.

#38: MfaPromptBanner converted to fully client-side component via
trpc.user.getMfaStatus.useQuery() — disappears immediately after MFA enable
without requiring page reload. Snooze key remains userId-scoped via useSession().
Server-side prisma.user.findUnique call removed from (app)/layout.tsx.

#40: NEXTAUTH_URL default fallback removed from docker-compose.yml.
The variable is now required (:?) — docker compose up fails with a descriptive
error if the value is missing, preventing silent localhost redirect bugs.

Tests: auth.test.ts (5), MfaPromptBanner.test.ts (7), reset-password.test.ts (6)
All new tests green. pnpm --filter @capakraken/web exec tsc --noEmit clean.

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-04-02 00:20:47 +02:00
Hartmut 435c871e1f security: implement tickets #28-#35 + architecture decision #30
#28 - TOTP rate limiting (verifyTotp): added totpRateLimiter (10 req/30s),
  throws TOO_MANY_REQUESTS before DB hit; 16 unit tests including rate-limit
  exceeded + userId key isolation.

#29 - /api/reports/allocations role check: only ADMIN/MANAGER/CONTROLLER may
  access; returns 403 otherwise; 9 unit tests (401 unauthenticated, 403 for
  USER/VIEWER, 200 for allowed roles + xlsx format).

#31 - pgAdmin credentials moved out of docker-compose.yml into env vars;
  PGADMIN_PASSWORD is now required (:?) to prevent accidental plaintext
  exposure in committed files.

#34 - Server-side HTML sanitization for comment bodies via stripHtml():
  strips all tags + decodes safe entities before persistence; 16 unit tests
  covering passthrough, injection patterns, entity decoding.

#35 - MFA setup prompt banner (MfaPromptBanner): shown to ADMIN/MANAGER users
  without TOTP enabled; user-scoped localStorage snooze (7 days); links to
  /account/security; accessibility role=alert; 7 structural unit tests.

#33 - Auth anomaly alerting cron (/api/cron/auth-anomaly-check): detects
  HIGH_GLOBAL_FAILURE_RATE and CONCENTRATED_FAILURES in 30-minute window;
  CRITICAL notification to ADMINs; fail-closed via verifyCronSecret;
  10 unit tests.

#32 - MFA enforcement policy: added requireMfaForRoles field to SystemSettings
  schema + Prisma migration; auth.ts blocks login with MFA_REQUIRED_SETUP
  signal if role is enforced but TOTP not set up; signin page redirects to
  /account/security?mfa_required=1; settings schema + view model updated;
  11 unit tests.

#30 - API keys architecture decision documented in LEARNINGS.md; no code
  written — product decision required before implementation.

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-04-01 23:25:06 +02:00
Hartmut f8550110eb security: fix 4 OWASP quick-wins from audit round 2
A04-1 (High): docker-compose E2E_TEST_MODE now defaults to "false"
  via ${E2E_TEST_MODE:-false} — prevents accidental security bypass in
  non-test deployments. runtime-env.ts throws at startup if
  E2E_TEST_MODE=true in production.

A05-3 (Medium): all 4 cron routes now fail-closed when CRON_SECRET
  is unset. Extracted shared verifyCronSecret() helper to
  apps/web/src/lib/cron-auth.ts.

A02-1 (Low): verifyCronSecret uses crypto.timingSafeEqual for
  constant-time Bearer token comparison.

A10-1 (Medium): Slack webhook routing uses strict hostname check
  (parsedUrl.hostname === "hooks.slack.com") instead of .includes()
  to prevent bypass via subdomain confusion.

Tickets created for remaining findings: #28 (TOTP rate limit),
#29 (allocations role check), #30 (API keys in DB), #31 (pgAdmin
creds), #32 (MFA enforcement), #33 (auth anomaly alerting),
#34 (comment server-side sanitization).

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-04-01 22:57:51 +02:00
Hartmut d3bfa8ca98 test(mfa): full MFA test coverage — unit + E2E
Unit tests (packages/api — 13 tests):
- generateTotpSecret: DB write, returns secret + uri
- verifyAndEnableTotp: valid token enables; invalid/already-enabled/no-secret guards
- verifyTotp (login): valid → ok; invalid → UNAUTHORIZED; not-enabled → BAD_REQUEST
- getCurrentMfaStatus: reads totpEnabled flag

E2E tests (apps/web/e2e/dev-system/mfa.spec.ts — 7 scenarios):
- Setup flow: generate secret, enable with valid code, reject invalid code, UI QR check
- Login flow: MFA prompt appears, valid code logs in, wrong code shows error + stays on prompt
- Login without MFA: no TOTP prompt for users without MFA enabled

Also: start.sh health-check timeout 30s → 90s (container startup can exceed 30s)

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-04-01 22:30:36 +02:00
Hartmut bfdf0a82da security/platform: close audit findings #19–#26
Tests, CSP nonce middleware, SSRF guard, perf-route hardening,
Docker env isolation, migration runbook, RBAC E2E coverage.

Tickets resolved:
- #19: MfaSetup.test.ts — static source tests confirming local QR rendering
- #20: ssrf-guard.test.ts (16 tests) + webhook-procedure-support mock fix
- #21: /api/perf route.test.ts (5 tests) — header-only auth, fail-closed
- #22: middleware.ts (nonce-based CSP) + middleware.test.ts (6 tests);
       layout.tsx async + nonce prop; CSP removed from next.config.ts
- #23: Active-session registry enforcement verified (already in codebase)
- #24: docker-compose.yml REDIS_URL hardcoded (no host-env substitution)
- #25: docker-compose.yml REDIS_URL + docs/developer-runbook.md created
- #26: e2e/dev-system/rbac-data-access.spec.ts (12 tests, 3 roles × 4 procedures)

Quality gates: tsc clean, api 1447/1447, web 189/189 passing.
Turbo concurrency capped at 2 (package.json) to prevent OOM under
parallel test runs.

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-04-01 22:14:20 +02:00
Hartmut 0e119cfe73 security: close audit findings #19–#23 and harden Docker setup (#24)
#19 MFA QR code: render locally via qrcode package, remove external qrserver.com request
#20 Webhook SSRF: add ssrf-guard.ts with DNS-verified IP blocklist; enforce on create/update/test/dispatch
#21 /api/perf: fail-closed when CRON_SECRET missing; remove query-string token auth
#22 CSP: remove unsafe-eval and unsafe-inline from script-src in production builds
#23 Active session registry: forward jti into session object; validate against ActiveSession on every tRPC request

#24 Docker: add missing packages/application to Dockerfile.dev; fix pnpm-lock.yaml glob;
    run db:migrate:deploy on container start so a fresh checkout boots without manual steps

Also: fix pre-existing TS error in e2e/allocations.spec.ts (args.length literal type overlap)

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-04-01 18:19:21 +02:00
Hartmut 7277e60691 test(api): widen resource capacity edge coverage 2026-04-01 07:52:40 +02:00
Hartmut 071ea13cc4 test(api): stabilize chargeability stats regression 2026-04-01 07:45:02 +02:00
Hartmut 8c5be51251 feat(platform): checkpoint current implementation state 2026-04-01 07:42:03 +02:00
Hartmut 3e53471f05 refactor(api): split resource read models 2026-04-01 07:38:03 +02:00
Hartmut 41916a4e46 refactor(api): share owned resource read access 2026-04-01 07:35:34 +02:00
Hartmut a0c98cf24d test(api): close assistant split regression gaps 2026-04-01 07:33:00 +02:00
Hartmut f2d65d3cd4 test(api): add assistant split regression runner 2026-04-01 00:51:23 +02:00
Hartmut 254f2caa94 test(api): cover assistant timeline resource selection 2026-04-01 00:44:53 +02:00
Hartmut 3d9d3dd5a7 test(api): cover assistant system role configs 2026-04-01 00:44:42 +02:00
Hartmut 9c58952170 test(api): cover assistant import export tools 2026-04-01 00:44:29 +02:00
Hartmut 67f57e2791 test(api): cover ai client helpers 2026-04-01 00:44:16 +02:00
Hartmut ef282e5e00 test(api): add assistant master data mutation helpers 2026-04-01 00:42:49 +02:00
Hartmut ed021947ad test(api): add assistant timeline allocation mutation helpers 2026-04-01 00:42:43 +02:00
Hartmut 0039a9997a test(api): cover assistant project computation views 2026-04-01 00:42:02 +02:00
Hartmut 22ead3ca3d test(api): cover assistant project cover tools 2026-04-01 00:41:55 +02:00
Hartmut 30b202c391 test(api): cover assistant change history queries 2026-04-01 00:41:46 +02:00
Hartmut 740ef0ecdb test(api): cover assistant master data rate lookup 2026-04-01 00:41:40 +02:00
Hartmut 43c4ad37f3 test(api): cover assistant auth guard 2026-04-01 00:41:31 +02:00
Hartmut f52380dc53 test(api): cover assistant chargeability report 2026-04-01 00:41:26 +02:00
Hartmut 95940f005b test(api): cover assistant budget status 2026-04-01 00:41:17 +02:00
Hartmut 1d4e5c62b0 test(api): cover assistant insights and scenarios 2026-04-01 00:41:09 +02:00
Hartmut 38a7826326 test(api): cover assistant advanced timeline views 2026-04-01 00:38:55 +02:00
Hartmut 8349c5e0b3 test(api): cover assistant advanced resource ranking 2026-04-01 00:38:49 +02:00
Hartmut 248973c87d test(api): cover assistant estimate version status errors 2026-04-01 00:38:15 +02:00
Hartmut c65ae132d3 test(api): cover assistant estimate revision export errors 2026-04-01 00:38:10 +02:00
Hartmut f1427a3f85 test(api): cover assistant estimate planning handoff errors 2026-04-01 00:38:03 +02:00
Hartmut a07057438e test(api): cover assistant estimate weekly phasing errors 2026-04-01 00:37:59 +02:00
Hartmut 7b6a4f6436 test(api): cover assistant estimate commercial term errors 2026-04-01 00:37:45 +02:00
Hartmut 276751c4ca test(api): cover assistant estimate draft errors 2026-04-01 00:37:45 +02:00
Hartmut 0b535a6a5f test(api): cover assistant estimate clone paths 2026-04-01 00:37:45 +02:00
Hartmut 80c31cc53f test(api): cover assistant estimate reads 2026-04-01 00:37:38 +02:00
Hartmut c510eeae37 test(api): cover assistant dispo import tools 2026-04-01 00:36:26 +02:00
Hartmut ef9ec798ed test(api): cover assistant dispo staged resolution 2026-04-01 00:36:22 +02:00
Hartmut 542d61bed3 test(api): cover assistant dispo staged reads 2026-04-01 00:36:17 +02:00
Hartmut e76b4b2cfe test(api): cover assistant timeline project shifts 2026-04-01 00:35:28 +02:00
Hartmut 7949aeb2e4 test(api): cover assistant timeline inline allocation update 2026-04-01 00:35:16 +02:00
Hartmut 3607d73b84 test(api): cover assistant timeline allocation shifts 2026-04-01 00:35:16 +02:00
Hartmut adf25f328f test(api): cover assistant timeline batch quick assign 2026-04-01 00:34:25 +02:00
Hartmut 705b570684 test(api): cover assistant timeline quick assign 2026-04-01 00:34:18 +02:00
Hartmut 2b8e1a1bf1 test(api): cover assistant allocation mutations 2026-04-01 00:33:28 +02:00
Hartmut 3a82a52897 test(api): cover assistant allocation reads 2026-04-01 00:31:51 +02:00
Hartmut 53158dc60d test(api): cover assistant comment tools 2026-04-01 00:30:23 +02:00