diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7031ff3417..4fd2de55b9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,7 +4,6 @@ on: push: branches: [ main, develop ] pull_request: - branches: [ main, develop ] types: [opened, synchronize, reopened, edited] workflow_dispatch: @@ -830,6 +829,7 @@ jobs: run: | npm run lint npm run format -- -c + npm run test working-directory: web-client - name: Install pinned Chrome for Testing and ChromeDriver @@ -1011,7 +1011,7 @@ jobs: contents: read pull-requests: write needs: [buf-check, docker-lint, shellcheck, python-script-validation, dev-tool-contract-checks, dev-tools-readme-contract, yaml-lint, metrics-cardinality-check, flyway-migration-sanity-checks, grpc-transport-config-sanity-checks, workflow-lint, helm-lint, helm-render-validation, helm-transaction-proof, docs-check, frontend-checks, build-and-test, validation-gate] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 diff --git a/.github/workflows/publish-pr-runtime-images.yml b/.github/workflows/publish-pr-runtime-images.yml index 19c5fa387a..412f34e874 100644 --- a/.github/workflows/publish-pr-runtime-images.yml +++ b/.github/workflows/publish-pr-runtime-images.yml @@ -179,8 +179,8 @@ jobs: fail("source workflow run API id does not match the event") if source_run.get("workflow_id") != int(workflow_id_text): fail("source workflow identity changed between event and API") - if source_run.get("name") != source_title: - fail("source workflow API name differs from its exact run title") + if source_run.get("name") not in {"Build Runtime Images", source_title}: + fail("source workflow API name is neither its owning name nor exact run title") if source_run.get("path") != SOURCE_WORKFLOW_PATH: fail("source workflow API path is not the trusted runtime-images workflow") if source_run.get("event") != source_event: diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index 67013db104..df21260621 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -113,6 +113,7 @@ jobs: uses: ./.github/actions/setup-trivy - name: 🔍 Run Trivy and Save Report + shell: bash run: | echo "::group::Run Trivy" trivy fs --config config/security/trivy.yaml . | tee trivy-report.txt @@ -207,7 +208,7 @@ jobs: contents: read pull-requests: write # Publishes the consolidated security result on the PR. needs: [changes, trivy-scan, secret-compliance, security-gate] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index c65b36fb4f..b7e861e41a 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -88,6 +88,7 @@ jobs: ".github/actions/load-workflow-tool-versions/", ".github/actions/setup-python/", "dev-tools/smoke/", + "dev-tools/minio/", ]; const fullRelevantFiles = new Set([ "build.gradle.kts", @@ -145,7 +146,7 @@ jobs: contents: read pull-requests: write needs: [changes] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 @@ -198,6 +199,26 @@ jobs: `- ${statusIcon(fullResult)} PR Full-Stack Smoke: \`${fullResult}\``, ].join("\n"); + const expectedHeadSha = context.payload.pull_request.head.sha; + const expectedBaseRef = context.payload.pull_request.base.ref; + const expectedBaseSha = context.payload.pull_request.base.sha; + const { data: currentPullRequest } = await github.rest.pulls.get({ + ...context.repo, + pull_number: context.issue.number, + }); + if ( + currentPullRequest.state !== "open" || + currentPullRequest.head.sha !== expectedHeadSha || + currentPullRequest.base.ref !== expectedBaseRef || + currentPullRequest.base.sha !== expectedBaseSha + ) { + core.info( + `Skipping stale smoke summary for ${expectedBaseRef}@${expectedBaseSha}...${expectedHeadSha}; ` + + `current PR state/base/head is ${currentPullRequest.state}/${currentPullRequest.base.ref}@${currentPullRequest.base.sha}/${currentPullRequest.head.sha}` + ); + return; + } + const comments = await github.paginate( github.rest.issues.listComments, { @@ -277,7 +298,7 @@ jobs: contents: read pull-requests: write needs: [changes, smoke-gate, smoke-summary-pending] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 @@ -334,6 +355,26 @@ jobs: `- ${statusIcon(fullResult)} PR Full-Stack Smoke: \`${fullResult}\``, ].join("\n"); + const expectedHeadSha = context.payload.pull_request.head.sha; + const expectedBaseRef = context.payload.pull_request.base.ref; + const expectedBaseSha = context.payload.pull_request.base.sha; + const { data: currentPullRequest } = await github.rest.pulls.get({ + ...context.repo, + pull_number: context.issue.number, + }); + if ( + currentPullRequest.state !== "open" || + currentPullRequest.head.sha !== expectedHeadSha || + currentPullRequest.base.ref !== expectedBaseRef || + currentPullRequest.base.sha !== expectedBaseSha + ) { + core.info( + `Skipping stale smoke summary for ${expectedBaseRef}@${expectedBaseSha}...${expectedHeadSha}; ` + + `current PR state/base/head is ${currentPullRequest.state}/${currentPullRequest.base.ref}@${currentPullRequest.base.sha}/${currentPullRequest.head.sha}` + ); + return; + } + const comments = await github.paginate( github.rest.issues.listComments, { @@ -476,7 +517,11 @@ jobs: const eventMergeSha = context.sha; const prNumber = String(context.payload.pull_request.number); const started = Date.now(); - const timeoutMs = 25 * 60 * 1000; + // Contract-checked against pr-local-smoke; bounded overhead covers metadata, + // runner scheduling and API convergence, not unbounded queue delays. + const producerTimeoutMinutes = 45; + const prerequisiteAndQueueAllowanceMinutes = 45; + const timeoutMs = (producerTimeoutMinutes + prerequisiteAndQueueAllowanceMinutes) * 60 * 1000; const cancelledReplacementTimeoutMs = 5 * 60 * 1000; const sleepMs = 15000; const pullRequestCheckInterval = 4; diff --git a/.github/workflows/static-analysis-summary.yml b/.github/workflows/static-analysis-summary.yml index 4a89119f45..b4c906f7b3 100644 --- a/.github/workflows/static-analysis-summary.yml +++ b/.github/workflows/static-analysis-summary.yml @@ -65,7 +65,8 @@ jobs: if ( currentPullRequest.state !== "open" || !sourceWorkflowName || - context.payload.workflow_run.name !== expectedSourceTitle || + (context.payload.workflow_run.name !== sourceWorkflowName && + context.payload.workflow_run.name !== expectedSourceTitle) || context.payload.workflow_run.display_title !== expectedSourceTitle ) { core.info("The source run is not bound to the current open pull-request base and head."); diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index da785e641a..fece21cedd 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -166,7 +166,7 @@ These RPCs and schemas are accepted target state but are not present in the curr | `POST` | `/auth/request-password-reset` | Request account-scoped password reset by normalized email with a neutral known/unknown response | | `POST` | `/auth/complete-password-reset` | Complete account-scoped password reset | | `POST` | `/auth/request-email-verification` | Send an account-scoped verification email selected by normalized email with a neutral known/unknown response; the public route accepts no numeric account selector | -| `POST` | `/auth/verify-email` | **Target public route; current bearer exception.** Verify an account-scoped email token. The current HTTP configurations allowlist only `GET /auth/verify-email` (which has no controller mapping), so the implemented `POST` route inherits bearer authentication until the public-route configuration is deliberately converged and proved. | +| `POST` | `/auth/verify-email` | Public token-confirmation operation. The email link targets the separate first-party, non-mutating `/verify-email` browser landing; only this explicit POST consumes the token. The Account configurations now allowlist this POST, not a state-changing GET. Site-router and deployed browser-to-Gateway proof remain open. | | `POST` | `/auth/recover-username` | Send an account-scoped username reminder by normalized email with a neutral known/unknown response | | `POST` | `/accounts` | Create a global Account identity and platform-scoped audit outbox row; tenant membership and profile creation are separate operations. Legacy tenant input is not registration authority. | | `GET` | `/accounts/{accountId}/export` | **Current legacy route.** Returns an Account/profile-local export and does not satisfy ADR 0050. | @@ -204,7 +204,7 @@ These RPCs and schemas are accepted target state but are not present in the curr | `GET` | `/support/tenants/{tenantId}/entitlements` | Cross-tenant support-safe entitlement view with redacted fields | | `GET` | `/.well-known/jwks.json` | JWKS for verifying issued JWTs | -Current verification routing/auth status: `POST /auth/verify-email` inherits bearer authentication because both HTTP configurations allowlist only `GET /auth/verify-email`, while that allowlisted GET has no controller mapping; see the existing [verification-routing gap in Runtime and Data](./runtime-and-data.md#email-and-notification-design). +Current verification routing/auth status: both HTTP configurations allowlist `POST /auth/verify-email` as public and do not allowlist the state-changing GET form. Emailed links target the separate first-party `/verify-email` landing; only an explicit POST consumes the token. The site-router/deployed browser handoff and Account-owned trusted-source and distributed abuse controls remain incomplete; see [Email and Notification Design](./runtime-and-data.md#email-and-notification-design). Current recovery/verification response and delivery behavior: password-reset, username-recovery, and public email-verification initiation retain the same neutral HTTP success for known and unknown normalized email addresses, including when a known-account post-commit SMTP send throws and is caught/logged; unknown addresses create no token or delivery attempt. This equal outcome does not remove the timing oracle: known-account sends still run synchronously after commit. Durable asynchronous delivery is absent, and focused service-level exception tests do not prove HTTP-level timing parity or timing resistance. This is not full account-enumeration resistance. @@ -238,7 +238,7 @@ Every tenant-targeted request identifies its tenant in the route or request cont | Surface | Examples | Required auth path | Notes | | --- | --- | --- | --- | -| Public auth/bootstrap | `/auth/login`, `/auth/request-password-reset`, `/auth/complete-password-reset`, `/auth/request-email-verification`, `/auth/recover-username`, `/.well-known/jwks.json` | No pre-existing user JWT; endpoint-specific validation and abuse controls | Intended for initial auth/bootstrap flows. `POST /auth/verify-email` is target-public but is excluded from the current public allowlist and therefore requires a bearer under the current configuration; the allowlisted `GET` has no controller mapping. | +| Public auth/bootstrap | `/auth/login`, `/auth/request-password-reset`, `/auth/complete-password-reset`, `/auth/request-email-verification`, `/auth/verify-email`, `/auth/recover-username`, `/.well-known/jwks.json` | No pre-existing user JWT; endpoint-specific validation and abuse controls | The verification and reset email landings are separate read-only first-party browser routes, not Account GET mutations. Current shared Account-owned trusted-source/throttling and deployed link-to-completion proof remain incomplete. | | Player bootstrap issuance | `/auth/player-bootstrap` | First-party player account authentication bootstrap | **Target state:** issues the `player-bootstrap` token profile only after atomically creating its one active `session:auth:token:` registry record; registry failure fails issuance before exposure. It must not return a `control-ui` JWT or perform tenant-scoped admission checks. It may share Account's credential verification, abuse controls, and account-state checks with `/auth/login`, but the endpoint, audience, claims, lifetime, and allowed surfaces remain distinct. **Current implementation:** uses the legacy `session:auth:account::` Account session key rather than the ADR 0035 registry shape. | | Player bootstrap | `/auth/bootstrap/worlds`, `/auth/bootstrap/worlds/{world}/realms`, `/auth/bootstrap/join`, `/auth/bootstrap/worlds/{world}/realms/{realm}/characters`, `/auth/connect-token` | Target first-party flow: short-lived, memory-only `player-bootstrap` token in `Authorization: Bearer ...` | The implemented bootstrap derives caller identity before tenant selection, then resolves tenant scope through realm discovery. World and realm discovery may show a public production target before membership exists; character discovery now requires the caller's current membership to exist and permit gameplay admission, and `/auth/bootstrap/join` has a local Account controller/operation for the explicit first-party open-enrollment writer. Character discovery and connect-token issuance consume the opaque server-issued `connectScopeId`, verify the route matches it, and revalidate its tenant/runtime target against current admission state. The target character-creation route is not currently routable or implemented: it requires that exact `connectScopeId`, derives `playableStateScope` from the realm catalog/pointer snapshot, and delegates the scoped write to Entity Management `CreateCharacter`; it does not persist character state or accept a caller-selected scope. Later character and connect-token surfaces must require live membership plus applicable grant, entitlement, and pointer checks. `POST /auth/connect-token` must obtain the exact current caller-bound runtime membership snapshot at its issuance commit gate, including lifecycle state, independent membership version, and opaque authority generation; cached or bootstrap evidence cannot substitute even when its generation appears current. Account delivers the connect token only through the protected `Firemud-Connect-Token` `Set-Cookie` field; the HTTP response body and custom response-header fields are metadata-only. First-party browser/mobile-browser and first-party native-mobile or other first-party non-browser cookie-jar clients remain cookie-only. A separately registered route for explicitly classified public/non-first-party native-mobile and other non-browser clients returns the token once for protected secure storage and permits only the dedicated handshake header; it is not a browser endpoint or a cookie fallback. PostgreSQL exact-final-head, recovery/reconciliation, direct text end-to-end, and membership-generation proof remain open. | diff --git a/design/architecture/microservices/account-service/configuration.md b/design/architecture/microservices/account-service/configuration.md index 892a793ebe..3e5345d5e8 100644 --- a/design/architecture/microservices/account-service/configuration.md +++ b/design/architecture/microservices/account-service/configuration.md @@ -37,8 +37,8 @@ Additional variables configure outbound email delivery, payment behavior, and Ac | `SMTP_USERNAME` | Username for SMTP auth | *(empty)* | | `SMTP_PASSWORD` | Password for SMTP auth | *(empty)* | | `SMTP_FROM` | From address for transactional emails | `no-reply@firemud.local` | -| `FIREMUD_MAIL_VERIFICATION_URL` | Public URL for email verification links | `http://localhost:8080/auth/verify-email?token=%s` | -| `FIREMUD_MAIL_RESET_URL` | Public URL for password reset links | `http://localhost:8080/reset-password?token=%s` | +| `FIREMUD_MAIL_VERIFICATION_URL` | First-party, non-reserved browser landing URL for email verification links; `%s` is the single-use token in the fragment, not an API query | `http://localhost:5173/verify-email#token=%s` | +| `FIREMUD_MAIL_RESET_URL` | First-party, non-reserved browser landing URL for password reset links; `%s` is the single-use token in the fragment, not an API query | `http://localhost:5173/reset-password#token=%s` | | `FIREMUD_PAYMENT_STRIPE_API_KEY` | Stripe API key used for payments | *(none)* | | `FIREMUD_PAYMENT_PLATFORM_FEE_PERCENT` | Unsupported creator-share substrate; implementations must ignore this variable and it cannot enable provider mutation. No legacy value is an approved fee policy. Any future FireMUD-managed creator-player fee remains target-only under [ADR 0179](../../decisions/adr-0179-firemud-managed-creator-commerce-boundary.md). | *(unsupported; unset)* | | `FIREMUD_AUTH_JWT_SECRET` | Inline JWT signing key material for local/dev or explicitly ephemeral stacks only (legacy compatibility; not for player-facing environments) | *(none)* | diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 373617be72..ebf246331e 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -320,4 +320,4 @@ Account owns the sole supported v1 Stripe integration for FireMUD hosting-plan b This service sends verification and password reset emails using a configured SMTP provider. Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when a known-account post-commit SMTP send throws; those exceptions are caught and logged, while unknown requests create no token and schedule no email. **Current gap:** these sends still run synchronously after commit, so SMTP latency remains a timing oracle; durable asynchronous delivery is absent. Focused service tests prove exception containment, not timing resistance, HTTP-level timing parity, or durable delivery, so this is not full account-enumeration resistance. Public email-verification initiation no longer accepts a numeric account selector, while the internal gRPC method remains account-ID based. Notifications for suspicious logins or account events are queued for asynchronous delivery via a gRPC `NotificationService`. Sample templates live under `resources/templates/` and environment variables configure `spring.mail.*` along with `firemud.mail.from`, `firemud.mail.verification-url`, and `firemud.mail.reset-url`. The Account-owned trusted-source context, distributed candidate/source throttles, and limiter-outage behavior from [ADR 0034](../../decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md) remain unimplemented, so neutral responses do not by themselves complete the abuse-control boundary. The gRPC API is defined in [`notification_service.proto`](../../../../protos/account/v1/notification_service.proto). -The configured default verification URL is a `GET /auth/verify-email` link while Account exposes verification as `POST /auth/verify-email`; the default reset URL points to `/reset-password`, for which no Account route exists. The canonical Gateway forwards Account auth under `/api/account/auth/**` ([Gateway client behavior](../spring-cloud-gateway/client-behavior.md)). The shipped defaults therefore do not route users to the canonical POST APIs ([Account API Contracts](./api-contracts.md#rest-apis)); deployment must provide an explicit web-client/edge handoff or matching handler, with link reachability proof, before recovery and verification are treated as end-to-end live. +The configured defaults now point to first-party fragment landings, `/verify-email#token=%s` and `/reset-password#token=%s`, rather than putting tokens in API query strings. The browser landing captures the token in memory and requires an explicit `POST /auth/verify-email` or `POST /auth/complete-password-reset`; only Account consumes the token. The canonical Gateway forwards those Account APIs under `/api/account/auth/**` ([Gateway client behavior](../spring-cloud-gateway/client-behavior.md)). These defaults and the source-level browser handoff do not establish deployed reachability: deployment must provide the first-party origin override, static host, site-router handoff, and link-to-completion proof before recovery and verification are treated as end-to-end live. diff --git a/design/architecture/system-architecture-frontend.md b/design/architecture/system-architecture-frontend.md index 42855b4488..82507533ce 100644 --- a/design/architecture/system-architecture-frontend.md +++ b/design/architecture/system-architecture-frontend.md @@ -18,7 +18,9 @@ The first-party browser consumes the existing Account/Gateway APIs and the versi ## Implementation Status -The current Vite build emits the `web-client` artifact and its reserved `frontend-assets` output, but the independently released static host, public-site routing and delivery (including the target `/auth/**` rewrite), health/security/cache behavior, rollback, and bounded end-to-end browser proof are not implemented or proved. Those gaps remain target implementation obligations rather than evidence that the supported frontend boundary is live. +The current Vite build emits the `web-client` artifact and its reserved `frontend-assets` output. A non-root read-only static-container definition and opt-in preview Helm Deployment, Service, and Traefik path split now prepare the host boundary, including an `/auth/**` rewrite to Gateway's existing Account route. They are disabled in hosted values until an independently versioned frontend image is published and selected; no static image has been built or deployed by this slice. Public-site delivery, runtime configuration, independent rollback, security/cache behavior at a running host, and the bounded end-to-end browser journey remain unproved. These source and render preparations are not evidence that the supported frontend boundary is live. + +The browser source now has non-mutating `/verify-email` and `/reset-password` link landings that capture a fragment token in memory and require an explicit Account API POST. Account's default mail URLs point at those non-reserved client routes, while the opt-in host/router remains disabled and preview Account has no preview-origin mail URL overrides or generated-link delivery proof. Gateway's generic retry no longer replays POST after an ambiguous response, but Account's own distributed credential-abuse policy remains absent. This is a prepared presentation/edge handoff, not a claim that current email links work. Gateway opaque rate-limit subject migration remains a separate gate. The protected-cookie `/ws/game/**` handshake and bootstrap-backed bare `LOGIN` are implemented but non-promotable until Gateway carrier requirements, replay-marker durability, replay-quarantine continuity, and Account planned-rotation/compromise-cutover evidence are complete. Returning members and grant-backed private/playtest flows remain eligible only when the live membership/grant/entitlement/routing checks pass; current connect-token private/playtest grant validation remains incomplete. Gateway `POST /ws/game/connect-token/revoke` and Account `POST /auth/logout` and `/auth/logout-all` are target-only and unavailable. The current logout fallback clears local reconnect state and relies on bounded credential expiry; it does not establish Account revocation or generation advancement, Gateway revocation or an edge deny/replay fence, Game Session binding termination, or downstream reconciliation. Edge replay/deny enforcement is claimed only when the Gateway revoke path is implemented and reachable. @@ -244,7 +246,7 @@ WebSocket interactions for real-time gameplay are handled by `src/websocket.ts`, ## Hosting and Release Boundary -The target first-party static frontend boundary is required by the supported baseline. When implemented, preview and hobby/self-hosted deployments will serve the immutable `web-client` artifact from an unprivileged static host; production may use that host directly or place an approved CDN/object-store origin in front of the same artifact. The public site router keeps frontend documents and `/frontend-assets/**` separate from Gateway ingress, rewrites public `/auth/**` to Gateway's existing `/api/account/auth/**` route, preserves explicitly allowlisted `/api/{service}/**` and `/ws/game/**` ingress, and keeps the published `/assets/**` family separate; the reserved compiled-asset prefix does not SPA-fallback. The router/rewrite and end-to-end browser proof remain unimplemented. +The target first-party static frontend boundary is required by the supported baseline. Source and opt-in preview preparation now provides an unprivileged static host, reserved-asset handling, and the public `/auth/**` rewrite, but hosted values leave it disabled until an independently versioned image and trusted preview wiring exist; no frontend image is deployed by this slice. Preview and hobby/self-hosted deployments will serve the immutable `web-client` artifact from that host; production may use the host directly or place an approved CDN/object-store origin in front of the same artifact. The public site router keeps frontend documents and `/frontend-assets/**` separate from Gateway ingress, rewrites public `/auth/**` to Gateway's existing `/api/account/auth/**` route, preserves explicitly allowlisted `/api/{service}/**` and `/ws/game/**` ingress, and keeps the published `/assets/**` family separate; the reserved compiled-asset prefix does not SPA-fallback. Running-host security/cache behavior, trusted preview activation, and end-to-end browser proof remain unproved. The Telnet `LOGIN -> PLAY -> LOOK` hosted proof remains useful protocol evidence, but it is not a reason to defer the frontend boundary. The browser journey, static-host health/security/cache checks, independent frontend rollback, and versioned `PlayerOutput` consumer are separate implementation/proof obligations. A browser application may begin as a terminal-style client and grow richer UX without changing the static-host authority boundary. @@ -255,7 +257,7 @@ The frontend uses **Vite** for fast development and production builds: - `npm run dev` starts the local development server with hot module replacement. - `npm run build` produces an optimized bundle under `dist/`, with compiled assets under `dist/frontend-assets/` and the existing public base preserved in generated references. - `npm run preview` serves the production bundle locally for verification. -- `npm run test` runs unit tests with Jest and React Testing Library. The script runs the test suite. +- `npm run test` runs the TypeScript-aware Node built-in test suite under `tests/`. - `npm run lint` and `npm run format` ensure consistent code style. - `npm run format:fix` writes formatting changes back to disk. - `npm run accessibility` audits the compiled site with axe-core. See [Developer Setup](../../DEVELOPER_SETUP.md#frontend-lint--accessibility) for Chrome requirements. diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 94a1859297..fb84ad8fdf 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -43,7 +43,7 @@ Unit 1A's 29-source broad discovery closed by Overseer judgment after Cycle 23, | Direct Account gRPC runtime/profile/presence/export/link/verification reads and mutations | Account `AA-1.1`–`AA-1.3`, current #2848 correction | Exact workload and caller-subject guards, or explicit method denial before read/mutation; negative missing-peer/cross-account proof and composed certificate/CI proof. Game Session runtime read consumers remain unavailable until Unit 1B supplies the typed caller/target contract. | | Generic payment, donation, refund and deferred virtual-currency RPCs | Account `AA-1.4`, current #2848 containment; later Account billing/economy successor | Unsupported methods deny before service/provider/balance work. Re-enable only for a supported product operation with exact workload authority, provider identity and negative mutation proof; a future economy requires its own accepted product contract. | | Recovery-token reuse and JOIN abandoned `PENDING` intents | Account `AA-1.2`/`AA-1.3`, current #2848 correction | Atomic single-use reset/verification claims and bounded JOIN readback reconciler require executed PostgreSQL concurrency, lost-acknowledgement, no-duplicate and unresolved-outcome proof. Expiry or absent evidence never terminalizes a pending JOIN. | -| Verification and password-reset email-link reachability | Account `AA-1.3` delivery/confirmation successor and Platform edge handoff | Shipped verification links use GET while Account implements bearer-protected POST completion; shipped reset links point to a non-Account route. Token claims remain guarded, but email-based recovery/verification is not end-to-end proved. Before treating these flows as usable, provide an explicit web-client/edge confirmation handoff or matching handler, align public-route authentication without a state-changing GET shortcut, and execute link-to-completion proof; deployment-specific URL overrides alone need reachability proof. | +| Verification and password-reset email-link reachability | Account `AA-1.3` and Platform edge successor #2861, stacked after #2857 | The draft now prepares non-mutating first-party GET landings with fragment-only token capture, explicit public Account POST completion, aligned mail defaults, and exact Gateway method routes. A source-level, opt-in static host and Traefik site-route split are prepared but disabled until the immutable frontend image and hosted values are wired. Gateway's generic retry is GET-only so an ambiguous email completion POST is not automatically replayed. Preview-origin mail URL overrides and SMTP delivery, deployed browser-to-Gateway-to-Account positive/negative proof, and Account-owned distributed abuse/outage policy remain open. Current emailed links must not be described as working, and #2856's gap remains open until those gates pass. | | Account deletion and retained financial/provider data | Account `AA-1.3` plus `DATA-01`, named pre-v1 pending-deletion/retention successor after this containment | Every current `DeleteAccount` entry denies before mutation. Enable only after the full ADR 0043 pending-deletion, provider/transfer clearance, cross-service erasure, retained-data registry, approved finite schedules, restore/replay and no-mutation/terminal proof exist; no partial synchronous substitute or invented TTL. | | Portable account export and tenant-admin export | Account `AA-1.3`/ADR 0050 pre-v1 export successor | The legacy account/profile read is explicitly local and not a complete portable export; the account-targeted tenant export is disabled because it exposes global fields. Enable canonical asynchronous subject export and tenant-only admin export only with owner contributions, live authority, redaction, audit and retry proof. | | Profile tenant qualification; membership lifecycle/generation, grants, roles, delegation and JOIN abuse limits | Account `AA-1.1`/`AA-1.2` authority successor, then Unit 1B consumer | Current profile route is self-bound and membership-checked; no tenant-qualified or delegated route activates until live generation/role/grant authority, caller binding and audit proof. Unit 1B must consume the exact snapshot and prove stale-generation/private-grant/character negatives before admission readiness. | diff --git a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md index e52d8699a4..714d5cbaf5 100644 --- a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md +++ b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md @@ -26,7 +26,7 @@ Packet 5 moderation/communication/social provenance is represented by [ADR 0146] | EA-2.2 Friends, groups, guilds, and social relationships | `partial` - the `FRIENDS` command plus friend, guild, and relationship APIs/storage are live. | `drift-found` - focused Game Session, Social friend, guild, and integration tests cover the bounded command and service paths, including tenant-scoped reciprocal-active reads, but this is legacy tenant-scoped proof and does not establish the target account-pair relationship contract. | [Social Groups Service](../../architecture/microservices/social-groups-service/README.md); [Social Groups API contracts](../../architecture/microservices/social-groups-service/api-contracts.md) | [FriendsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandler.java); [FriendServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImpl.java); [GuildServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/GuildServiceImpl.java); [Social Groups proto](../../../protos/social-groups/v1/social_groups_service.proto); [social relationship schema](../../../services/social-groups-service/src/main/resources/db/migration/V7__account_friend_links.sql) | [FriendsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java); [FriendServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImplTest.java); [GuildServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/GuildServiceImplTest.java); [FriendControllerTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/FriendControllerTest.java); [SocialGroupsApplicationIntegrationTest.java](../../../services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/SocialGroupsApplicationIntegrationTest.java) | [EA-2.3](./player-experience-commands-and-communication.md); [AA-1.1](./player-access-and-session.md); [PO-1.2](./platform-operations-and-delivery.md); [SF-2.1](./shared-runtime-contracts-and-persistence.md) | Current direct service-local reads require tenant-scoped reciprocal `active` links; one-way, inactive-reciprocal, and wrong-tenant endpoint cases are covered by integration proof. The player-facing Gateway `/api/social/friends` route is removed/unavailable; the direct service residual retains reciprocal-active filtering for future/non-edge use. Tenant-free migration/disposition and broader social client integration remain target gaps. | | EA-2.3 Presence, visibility, and availability | `partial` - live/recent canonical presence, AFK state, filtered friend presence, account visibility, and `WHO` substrate are live. | `drift-found` - focused tests cover the shipped bounded substrate, and the gameplay-role classifier no longer treats global `platformAdmin` or legacy global `god` inputs as gameplay grants, while payload/policy surfaces still retain `HIDDEN_STAFF` and player-facing disconnect disposition contrary to ADR 0046. | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Social Groups runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md); [ADR 0026](../../architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md); [ADR 0046](../../architecture/decisions/adr-0046-bounded-friend-presence-with-private-by-failure-redaction.md) | [DefaultGameplayPresenceLifecycleService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleService.java); [GameplayPresenceRoleClassifier.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifier.java); [AccountPresenceQueryServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImpl.java); [GameplayPresenceActivityResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayPresenceActivityResolver.java); [PresenceProperties.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/PresenceProperties.java); [profile visibility schema](../../../services/account-service/src/main/resources/db/migration/V16__profile_presence_visibility.sql); [Game Session proto](../../../protos/game-session/v1/game_session_service.proto) | [DefaultGameplayPresenceLifecycleServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleServiceTest.java); [GameplayPresenceRoleClassifierTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifierTest.java); [AccountPresenceQueryServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImplTest.java); [GameplayPresenceActivityResolverTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayPresenceActivityResolverTest.java); [RedisGameplayPresenceServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java); [FriendsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java) | [AA-2.2](./player-access-and-session.md); [AA-1.1](./player-access-and-session.md); [EA-2.2](./player-experience-commands-and-communication.md); [PO-1.2](./platform-operations-and-delivery.md) | Complete caller-bound role proof, remove `HIDDEN_STAFF` from account-profile presence policy, suppress disconnect disposition from player responses, add private-by-failure and bounded-page proof, and keep in-world concealment under gameplay policy before calling this capability proven. | | EA-2.4 Player blocking, reporting, and safety controls | `partial` - bounded internal report persistence and the live synchronous moderation-policy evaluation seam used at enforcement boundaries exist, but owner-local fixed-category restriction state, moderation cases, appeals, and caller-bound player submission remain incomplete; unsafe public administrative report persistence is disabled. | `drift-found` - focused tests prove the bounded internal gRPC persistence and live policy-evaluation seam, plus fail-closed absence of the former public route, not the canonical player-authenticated reporting boundary or target owner-local controls. | [Moderation policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [ADR 0146](../../architecture/decisions/adr-0146-owner-local-moderation-enforcement.md); [Authorization route matrix](../../architecture/system-architecture-authz-route-matrix.md); [Social Groups runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md) | [ReportGrpcService.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/ReportGrpcService.java); [ReportServiceImpl.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/ReportServiceImpl.java); [ModerationServiceImpl.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/ModerationServiceImpl.java); [report proto](../../../protos/logging-admin/v1/report_service.proto); [Logging & Admin V1__baseline.sql](../../../services/logging-admin-service/src/main/resources/db/migration/V1__baseline.sql) | [LoggingAdminApplicationIntegrationTest.java](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java); [ReportGrpcServiceTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/ReportGrpcServiceTest.java); [ModerationServiceImplTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/ModerationServiceImplTest.java); [ChatServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImplTest.java) | [PO-1.2](./platform-operations-and-delivery.md); [EA-2.1](./player-experience-commands-and-communication.md); [AA-1.3](./player-access-and-session.md) | The live `BLOCK` command is a combat action-state effect, not social blocking. Player block/mute/ignore and safety UI remain absent; reporting needs canonical administrative authorization/live reference checks before public operator ingress and a distinct player route deriving reporter and tenant identity from authenticated caller context. | -| EA-3.1 Player browser application | `partial` - a React/Vite/MUI/TanStack Query starter and generic WebSocket envelope/JSON consumer that parses payloads as `unknown` exist; Vite now emits the compiled production bundle under the reserved `frontend-assets` asset directory, but this is not the independently released static player application boundary. Native mobile is deferred pending a later product and compatibility decision. | `audited` - `npm run lint` and `npm run build` passed; the build emitted `dist/frontend-assets/react-*.svg`, `index-*.css`, and `index-*.js`. No independently released static host/public-site routing or browser proof was found. | [Frontend architecture](../../architecture/system-architecture-frontend.md); [FRONT-01](../../architecture/decisions/adr-0144-stateless-first-party-frontend-application-boundary.md) | [App.tsx](../../../web-client/src/App.tsx); [main.tsx](../../../web-client/src/main.tsx); [websocket.ts](../../../web-client/src/websocket.ts); [queryClient.ts](../../../web-client/src/api/queryClient.ts); [vite.config.ts](../../../web-client/vite.config.ts); [web-client package](../../../web-client/package.json) | No focused executable proof: `npm run lint` and `npm run build` from the [web-client package](../../../web-client/package.json) passed as general frontend validation and emitted the `dist/frontend-assets/` bundle, but no focused browser or independently released host proof exists. | [EA-1.2](./player-experience-commands-and-communication.md); [EA-3.4](./player-experience-commands-and-communication.md); [AA-2.1](./player-access-and-session.md); [PO-2.1](./platform-operations-and-delivery.md) | Independent immutable artifact/release metadata, unprivileged static host and deployment, reserved-path routing, non-secret runtime configuration, bootstrap/connect-token flow, richer player UX, mobile surface, independent rollback, and browser automation remain absent. | +| EA-3.1 Player browser application | `partial` - a React/Vite/MUI/TanStack Query starter and generic WebSocket envelope/JSON consumer that parses payloads as `unknown` exist; Vite now emits the compiled production bundle under the reserved `frontend-assets` asset directory, and an opt-in unprivileged static-host/preview-route slice is prepared but disabled; this is not an independently released player application. Native mobile is deferred pending a later product and compatibility decision. | `audited` - `npm run lint` and `npm run build` passed; the build emitted `dist/frontend-assets/react-*.svg`, `index-*.css`, and `index-*.js`. Opt-in Helm chart lint/render passed; no static image has been published, deployed, or browser-proved. | [Frontend architecture](../../architecture/system-architecture-frontend.md); [FRONT-01](../../architecture/decisions/adr-0144-stateless-first-party-frontend-application-boundary.md) | [App.tsx](../../../web-client/src/App.tsx); [main.tsx](../../../web-client/src/main.tsx); [websocket.ts](../../../web-client/src/websocket.ts); [queryClient.ts](../../../web-client/src/api/queryClient.ts); [vite.config.ts](../../../web-client/vite.config.ts); [web-client package](../../../web-client/package.json); [static host Dockerfile](../../../web-client/Dockerfile); [preview frontend template](../../../k8s/helm/firemud/templates/frontend.yaml) | `npm run lint` and `npm run build` passed and emitted `dist/frontend-assets/`; opt-in Helm lint/render passed, but no image build, running-host checks, or deployed browser journey executed. | [EA-1.2](./player-experience-commands-and-communication.md); [EA-3.4](./player-experience-commands-and-communication.md); [AA-2.1](./player-access-and-session.md); [PO-2.1](./platform-operations-and-delivery.md) | Independent immutable artifact/release metadata, enabled static-host deployment and public routing, non-secret runtime configuration, bootstrap/connect-token flow, richer player UX, mobile surface, independent rollback, and browser automation remain absent. | | EA-3.4 Shared navigation, accessibility, client state, and interaction foundations | `partial` - shared QueryClient, local feature state, and basic socket lifecycle are present. | `audited` - production scaffolding was inspected; no focused navigation, accessibility, or client-state executable proof was found. | [Frontend architecture](../../architecture/system-architecture-frontend.md); [Input, output, and presentation](../../architecture/system-architecture-input-output-and-presentation.md) | [main.tsx](../../../web-client/src/main.tsx); [queryClient.ts](../../../web-client/src/api/queryClient.ts); [websocket.ts](../../../web-client/src/websocket.ts); [App.tsx](../../../web-client/src/App.tsx) | No focused executable proof: the [web-client package](../../../web-client/package.json) exposes general lint, build, formatting, preview, and accessibility scripts, but no focused navigation, accessibility, or client-state test exists. | [EA-1.2](./player-experience-commands-and-communication.md); [AA-2.2](./player-access-and-session.md); [SF-1.1](./shared-runtime-contracts-and-persistence.md) | Shared navigation, accessibility coverage, semantic structured gameplay client integration, reconnect/error state, and durable interaction foundations remain absent. | ## Canonical Design Sources @@ -72,7 +72,7 @@ The Account JOIN RPC/controller, browser bootstrap facade, and direct-text REALM ### First-Party Frontend -- Current implementation: `web-client` is a React/Vite/MUI/TanStack Query baseline with a generic WebSocket envelope/JSON consumer that parses payloads as `unknown`, plus local feature/form state. Its Vite production build now emits compiled assets under `dist/frontend-assets/`; semantic structured `PlayerOutput` consumption, the complete admitted runtime-bundle asset bootstrap, independent immutable frontend artifact/release metadata, unprivileged static host, richer player UX, admin/design-tool integration, and end-to-end browser proof are not implemented. The target boundary and independent-release proof requirements remain in [FRONT-01](../../architecture/decisions/adr-0144-stateless-first-party-frontend-application-boundary.md). +- Current implementation: `web-client` is a React/Vite/MUI/TanStack Query baseline with a generic WebSocket envelope/JSON consumer that parses payloads as `unknown`, plus local feature/form state. Its Vite production build now emits compiled assets under `dist/frontend-assets/`; source and opt-in preview preparation now includes an unprivileged static host and public-route split, but hosted values leave it disabled and no frontend image is published or deployed by this slice. Semantic structured `PlayerOutput` consumption, the complete admitted runtime-bundle asset bootstrap, independent immutable frontend artifact/release metadata, richer player UX, admin/design-tool integration, and end-to-end browser proof remain unimplemented or unproved. The target boundary and independent-release proof requirements remain in [FRONT-01](../../architecture/decisions/adr-0144-stateless-first-party-frontend-application-boundary.md). ### Validation and Proof diff --git a/dev-tools/hosted/preview/resolve-preview-image-tag.sh b/dev-tools/hosted/preview/resolve-preview-image-tag.sh index f9d00f5fd6..442eb9e33c 100644 --- a/dev-tools/hosted/preview/resolve-preview-image-tag.sh +++ b/dev-tools/hosted/preview/resolve-preview-image-tag.sh @@ -33,7 +33,7 @@ runtime_relevant() { .github/workflows/runtime-images.yml | .github/workflows/publish-pr-runtime-images.yml | .github/workflows/smoke.yml | .github/workflows/smoke-full.yml | .dockerignore) return 0 ;; - .github/actions/setup-python/* | .github/actions/load-workflow-tool-versions/* | buildSrc/* | gradle/* | protos/* | docker/* | services/* | dev-tools/smoke/*) + .github/actions/setup-python/* | .github/actions/load-workflow-tool-versions/* | buildSrc/* | gradle/* | protos/* | docker/* | services/* | dev-tools/smoke/* | dev-tools/minio/*) return 0 ;; config/python/smoke-requirements.txt | config/python/smoke-requirements.in | \ diff --git a/dev-tools/hosted/preview/validate-preview-artifact.py b/dev-tools/hosted/preview/validate-preview-artifact.py index 3045ce83b9..95ec5fc97e 100644 --- a/dev-tools/hosted/preview/validate-preview-artifact.py +++ b/dev-tools/hosted/preview/validate-preview-artifact.py @@ -45,6 +45,7 @@ def _expected_chart_label(chart_metadata_path: Path) -> str: ("batch/v1", "Job"), ("networking.k8s.io/v1", "Ingress"), ("networking.k8s.io/v1", "NetworkPolicy"), + ("traefik.io/v1alpha1", "Middleware"), } SERVICE_IMAGES = { "account-service", @@ -76,9 +77,17 @@ def _expected_chart_label(chart_metadata_path: Path) -> str: | SOCIAL_GROUPS_GRPC_WORKLOADS ) EXPECTED_NAMES = { - "Deployment": SERVICE_IMAGES | {"postgres", "redis-coord", "redis-cache", "minio"}, + "Deployment": SERVICE_IMAGES + | {"postgres", "redis-coord", "redis-cache", "minio", "frontend"}, "Service": SERVICE_IMAGES - | {"spring-cloud-gateway-mtls", "postgres", "redis-coord", "redis-cache", "minio"}, + | { + "spring-cloud-gateway-mtls", + "postgres", + "redis-coord", + "redis-cache", + "minio", + "frontend", + }, "ConfigMap": {"firemud-config", "firemud-seed-sql"}, "PersistentVolumeClaim": {"postgres-data", "redis-coord-data", "redis-cache-data", "minio-data"}, "Job": {"firemud-seed"}, @@ -92,7 +101,15 @@ def _expected_chart_label(chart_metadata_path: Path) -> str: "spring-cloud-gateway-ingress", "spring-cloud-gateway-egress", "tcp-proxy-service-egress", + "frontend-static-host", }, + "Middleware": {"firemud-preview-auth-path-rewrite"}, +} +FRONTEND_EXPECTED_NAMES = { + "Deployment": {"frontend"}, + "Service": {"frontend"}, + "NetworkPolicy": {"frontend-static-host"}, + "Middleware": {"firemud-preview-auth-path-rewrite"}, } EXPECTED_PVC_SPECS = { "postgres-data": { @@ -132,6 +149,7 @@ def walk(value: object, path: str = "object"): (kind, name) for kind, names in EXPECTED_NAMES.items() for name in names + if name not in FRONTEND_EXPECTED_NAMES.get(kind, set()) } INFRASTRUCTURE_IMAGES = { "postgres:16", @@ -168,6 +186,58 @@ def walk(value: object, path: str = "object"): "account-service", "social-groups-service", ) +FRONTEND_IMAGE_REPOSITORIES = { + "ghcr.io/benhook1013/web-client", +} +FRONTEND_MIDDLEWARE_NAME = "firemud-preview-auth-path-rewrite" +FRONTEND_MIDDLEWARE_ANNOTATION = "traefik.ingress.kubernetes.io/router.middlewares" +FRONTEND_MIDDLEWARE_REFERENCE = re.compile( + rf"^pr-[1-9][0-9]{{0,50}}-{re.escape(FRONTEND_MIDDLEWARE_NAME)}@kubernetescrd$" +) +FRONTEND_MIDDLEWARE_SPEC = { + "replacePathRegex": { + "regex": r"^/auth(/.*)?$", + "replacement": r"/api/account/auth$1", + } +} +FRONTEND_SERVICE_SPEC = { + "selector": {"app": "frontend"}, + "ports": [ + { + "name": "http", + "port": 80, + "targetPort": "http", + "protocol": "TCP", + } + ], + "type": "ClusterIP", +} +FRONTEND_NETWORK_POLICY_SPEC = { + "podSelector": {"matchLabels": {"app": "frontend"}}, + "policyTypes": ["Ingress", "Egress"], + "ingress": [ + { + "from": [ + { + "namespaceSelector": { + "matchLabels": { + "kubernetes.io/metadata.name": "kube-system" + } + }, + "podSelector": { + "matchLabels": {"app.kubernetes.io/name": "traefik"} + }, + } + ], + "ports": [{"protocol": "TCP", "port": 8080}], + } + ], + "egress": [], +} +FRONTEND_RESOURCES = { + "requests": {"cpu": "10m", "memory": "32Mi"}, + "limits": {"cpu": "250m", "memory": "128Mi"}, +} EXPECTED_TOP_LEVEL_LABELS = { "app.kubernetes.io/name": "firemud", "app.kubernetes.io/managed-by": "Helm", @@ -230,11 +300,17 @@ def _exposure_mode_for_service_type(service_type: object) -> str: fail("validated TCP Proxy Service has no canonical exposure mode") -def _expected_names_for_mode(certificate_identity_mode: str) -> dict[str, set[str]]: +def _expected_names_for_mode( + certificate_identity_mode: str, + frontend_enabled: bool = False, +) -> dict[str, set[str]]: _validate_certificate_identity_mode(certificate_identity_mode) expected_names = { kind: set(names) for kind, names in EXPECTED_NAMES.items() } + if not frontend_enabled: + for kind, names in FRONTEND_EXPECTED_NAMES.items(): + expected_names.setdefault(kind, set()).difference_update(names) if certificate_identity_mode == "standalone": expected_names["NetworkPolicy"].difference_update( { @@ -246,6 +322,63 @@ def _expected_names_for_mode(certificate_identity_mode: str) -> dict[str, set[st return expected_names +def _frontend_render_enabled(documents: list[object]) -> bool: + """Detect the explicit frontend opt-in without trusting arbitrary objects.""" + + frontend_objects = { + (kind, name) + for kind, names in FRONTEND_EXPECTED_NAMES.items() + for name in names + } + frontend_paths = { + "/frontend-assets", + "/auth", + "/api", + "/ws/game", + "/assets", + } + for document in documents: + if not isinstance(document, dict): + continue + metadata = document.get("metadata") + name = metadata.get("name") if isinstance(metadata, dict) else None + if (document.get("kind"), name) in frontend_objects: + return True + if document.get("kind") != "Ingress": + continue + if ( + isinstance(metadata, dict) + and isinstance(metadata.get("annotations"), dict) + and FRONTEND_MIDDLEWARE_ANNOTATION in metadata["annotations"] + ): + return True + spec = document.get("spec") + if not isinstance(spec, dict): + continue + rules = spec.get("rules", []) + if not isinstance(rules, list): + continue + for rule in rules: + if not isinstance(rule, dict): + continue + http = rule.get("http") + if not isinstance(http, dict): + continue + paths = http.get("paths") + if isinstance(paths, list) and any( + isinstance(path, dict) and path.get("path") in frontend_paths + for path in paths + ): + return True + return False + + +def _expected_frontend_middleware_reference(expected_namespace: str) -> str: + if re.fullmatch(r"pr-[1-9][0-9]{0,50}", expected_namespace) is None: + fail(f"runtime namespace is not canonical: {expected_namespace!r}") + return f"{expected_namespace}-{FRONTEND_MIDDLEWARE_NAME}@kubernetescrd" + + def _is_tcp_proxy_identity_object(document: dict) -> bool: return document.get("kind") in {"Deployment", "Service"} and ( isinstance(document.get("metadata"), dict) @@ -830,6 +963,7 @@ def _validate_image_reference( location: str, value: str, expected_image_tag: str, + allow_frontend: bool = False, ) -> None: if value in INFRASTRUCTURE_IMAGES: return @@ -840,6 +974,14 @@ def _validate_image_reference( if not separator or not repository or not tag: fail(f"{location} uses an untagged image") service = repository.rsplit("/", 1)[-1] + if service == "web-client": + if not allow_frontend: + fail(f"{location} uses an unapproved service image repository") + if repository not in FRONTEND_IMAGE_REPOSITORIES: + fail(f"{location} uses an unapproved frontend image repository") + if tag != expected_image_tag: + fail(f"{location} uses image tag {tag!r}, expected {expected_image_tag!r}") + return if service in SERVICE_IMAGES: if repository != f"ghcr.io/benhook1013/{service}": fail(f"{location} uses an unapproved service image repository") @@ -1176,6 +1318,161 @@ def validate_extra_security_fields(security: dict, security_path: str) -> None: fail(f"{path}.securityContext.windowsOptions.hostProcess is forbidden") +def _validate_frontend_image( + image: object, path: str, expected_image_tag: str | None = None +) -> None: + if not isinstance(image, str) or "@" in image: + fail(f"{path} must be an immutable tagged frontend image") + repository, separator, tag = image.rpartition(":") + if ( + not separator + or repository not in FRONTEND_IMAGE_REPOSITORIES + or not tag + ): + fail(f"{path} uses an unapproved frontend image") + if expected_image_tag is not None and tag != expected_image_tag: + fail(f"{path} uses image tag {tag!r}, expected {expected_image_tag!r}") + + +def validate_frontend_deployment( + document: dict, expected_image_tag: str | None = None +) -> None: + """Require the exact unprivileged static-host Deployment contract.""" + + name = document.get("metadata", {}).get("name", "frontend") + spec = _require_mapping(document.get("spec"), f"Deployment/{name}.spec") + if set(spec) != {"replicas", "selector", "template"}: + fail(f"Deployment/{name} has an unsafe frontend spec") + if spec.get("replicas") != 1: + fail(f"Deployment/{name} must have exactly one replica") + if spec.get("selector") != {"matchLabels": {"app": "frontend"}}: + fail(f"Deployment/{name} has an unsafe frontend selector") + template = _require_mapping( + spec.get("template"), f"Deployment/{name}.spec.template" + ) + if template.get("metadata") != {"labels": {"app": "frontend"}}: + fail(f"Deployment/{name} has unsafe frontend pod-template metadata") + pod = _require_mapping( + template.get("spec"), f"Deployment/{name}.spec.template.spec" + ) + expected_pod_security = { + "runAsNonRoot": True, + "runAsUser": 101, + "runAsGroup": 101, + "fsGroup": 101, + "fsGroupChangePolicy": "OnRootMismatch", + "seccompProfile": {"type": "RuntimeDefault"}, + } + expected_pod_fields = { + "automountServiceAccountToken", + "securityContext", + "containers", + "volumes", + "imagePullSecrets", + } + if set(pod) - expected_pod_fields: + fail(f"Deployment/{name} has unsupported frontend pod fields") + if pod.get("automountServiceAccountToken") is not False: + fail(f"Deployment/{name} must disable the ServiceAccount token") + if pod.get("securityContext") != expected_pod_security: + fail(f"Deployment/{name} has unsafe frontend pod security") + if "imagePullSecrets" in pod and pod["imagePullSecrets"] != [ + {"name": "ghcr-preview-pull"} + ]: + fail(f"Deployment/{name} has an unsafe frontend imagePullSecret") + containers = _require_mapping_list( + pod.get("containers"), f"Deployment/{name}.spec.template.spec.containers" + ) + if len(containers) != 1: + fail(f"Deployment/{name} must contain exactly one frontend container") + container = containers[0] + container_path = f"Deployment/{name}.spec.template.spec.containers[0]" + expected_container_fields = { + "name", + "image", + "imagePullPolicy", + "securityContext", + "ports", + "readinessProbe", + "livenessProbe", + "resources", + "volumeMounts", + } + if set(container) != expected_container_fields: + fail(f"{container_path} has an unsafe frontend container shape") + if container.get("name") != "frontend": + fail(f"{container_path} has an unexpected name") + _validate_frontend_image( + container.get("image"), f"{container_path}.image", expected_image_tag + ) + if container.get("imagePullPolicy") != "Always": + fail(f"{container_path}.imagePullPolicy must be Always") + if container.get("securityContext") != { + "allowPrivilegeEscalation": False, + "readOnlyRootFilesystem": True, + "runAsNonRoot": True, + "runAsUser": 101, + "runAsGroup": 101, + "capabilities": {"drop": ["ALL"]}, + }: + fail(f"{container_path} has unsafe frontend container security") + if container.get("ports") != [ + {"name": "http", "containerPort": 8080, "protocol": "TCP"} + ]: + fail(f"{container_path} has an unsafe HTTP port") + expected_probe = { + "httpGet": {"path": "/healthz", "port": "http"}, + "initialDelaySeconds": 2, + "periodSeconds": 10, + } + if container.get("readinessProbe") != expected_probe: + fail(f"{container_path} has an unsafe readiness probe") + expected_liveness_probe = { + "httpGet": {"path": "/healthz", "port": "http"}, + "initialDelaySeconds": 5, + "periodSeconds": 20, + } + if container.get("livenessProbe") != expected_liveness_probe: + fail(f"{container_path} has an unsafe liveness probe") + if container.get("resources") != FRONTEND_RESOURCES: + fail(f"{container_path} has unsafe resource limits") + if container.get("volumeMounts") != [ + {"name": "nginx-tmp", "mountPath": "/tmp"} + ]: + fail(f"{container_path} has an unsafe temporary volume mount") + if pod.get("volumes") != [ + {"name": "nginx-tmp", "emptyDir": {"sizeLimit": "16Mi"}} + ]: + fail(f"Deployment/{name} has an unsafe temporary volume") + + +def validate_frontend_middleware(document: dict, expected_namespace: str) -> None: + name = document.get("metadata", {}).get("name", FRONTEND_MIDDLEWARE_NAME) + if document.get("apiVersion") != "traefik.io/v1alpha1": + fail(f"Middleware/{name} has an unsupported apiVersion") + if document.get("kind") != "Middleware": + fail(f"Middleware/{name} has an unexpected kind") + if document.get("spec") != FRONTEND_MIDDLEWARE_SPEC: + fail(f"Middleware/{name} has an unsafe spec") + if name != FRONTEND_MIDDLEWARE_NAME: + fail(f"Middleware/{name} is not the trusted frontend middleware") + _expected_frontend_middleware_reference(expected_namespace) + + +def _frontend_ingress_paths() -> list[dict]: + gateway = { + "service": {"name": "spring-cloud-gateway", "port": {"number": 80}} + } + frontend = {"service": {"name": "frontend", "port": {"number": 80}}} + return [ + {"path": "/frontend-assets", "pathType": "Prefix", "backend": frontend}, + {"path": "/auth", "pathType": "Prefix", "backend": gateway}, + {"path": "/api", "pathType": "Prefix", "backend": gateway}, + {"path": "/ws/game", "pathType": "Prefix", "backend": gateway}, + {"path": "/", "pathType": "Prefix", "backend": frontend}, + ] + + def _strip_annotations(value: object) -> None: if isinstance(value, dict): metadata = value.get("metadata") @@ -1203,12 +1500,22 @@ def _validate_no_annotations(value: object, path: str = "object") -> None: def sanitize(source: Path, destination: Path) -> None: """Produce the credential-free artifact consumed by the trusted workflow.""" + raw_documents = [ + raw + for raw in yaml.safe_load_all(source.read_text(encoding="utf-8")) + if raw is not None + ] + if any(not isinstance(raw, dict) for raw in raw_documents): + fail("render contains a non-object document") + frontend_enabled = _frontend_render_enabled(raw_documents) + expected_names = { + kind: set(names) for kind, names in EXPECTED_NAMES.items() + } + if not frontend_enabled: + for kind, names in FRONTEND_EXPECTED_NAMES.items(): + expected_names.setdefault(kind, set()).difference_update(names) documents = [] - for raw in yaml.safe_load_all(source.read_text(encoding="utf-8")): - if raw is None: - continue - if not isinstance(raw, dict): - fail("render contains a non-object document") + for raw in raw_documents: api_version = raw.get("apiVersion") kind = raw.get("kind") if kind in SANITIZER_FORBIDDEN_KINDS: @@ -1219,7 +1526,7 @@ def sanitize(source: Path, destination: Path) -> None: if not isinstance(metadata, dict) or not metadata.get("name"): fail(f"{kind} has no metadata.name") name = metadata["name"] - if not isinstance(name, str) or name not in EXPECTED_NAMES[kind]: + if not isinstance(name, str) or name not in expected_names.get(kind, set()): fail(f"{kind}/{name} is not an approved preview object") if metadata.get("namespace") in {"firemud-system", "kube-system"}: fail(f"{kind}/{metadata['name']} targets a control namespace") @@ -1236,6 +1543,42 @@ def sanitize(source: Path, destination: Path) -> None: pod, f"{kind}/{metadata['name']}.spec.template.spec", ) + if frontend_enabled and kind == "Deployment" and name == "frontend": + validate_frontend_deployment(raw) + if ( + frontend_enabled + and kind == "Middleware" + and name == FRONTEND_MIDDLEWARE_NAME + and raw.get("spec") != FRONTEND_MIDDLEWARE_SPEC + ): + fail(f"Middleware/{name} has an unsafe spec") + trusted_frontend_annotation = None + if frontend_enabled and kind == "Ingress" and name == "firemud-preview": + annotations = metadata.get("annotations") + if annotations is not None: + if not isinstance(annotations, dict): + fail("Ingress/firemud-preview annotations are not an object") + unexpected_annotations = set(annotations) - { + "cert-manager.io/cluster-issuer", + FRONTEND_MIDDLEWARE_ANNOTATION, + } + if unexpected_annotations: + fail( + "Ingress/firemud-preview has unsupported frontend annotations: " + f"{sorted(unexpected_annotations)}" + ) + trusted_frontend_annotation = annotations.get( + FRONTEND_MIDDLEWARE_ANNOTATION + ) + if trusted_frontend_annotation is not None and ( + not isinstance(trusted_frontend_annotation, str) + or not FRONTEND_MIDDLEWARE_REFERENCE.fullmatch( + trusted_frontend_annotation + ) + ): + fail( + "Ingress/firemud-preview has an unsafe frontend middleware reference" + ) sanitized = _clean_config_map(copy.deepcopy(raw)) if sanitized.get("kind") == "Service": name = sanitized["metadata"]["name"] @@ -1246,6 +1589,10 @@ def sanitize(source: Path, destination: Path) -> None: for port in ports: port.pop("nodePort", None) _strip_annotations(sanitized) + if trusted_frontend_annotation is not None: + sanitized.setdefault("metadata", {})["annotations"] = { + FRONTEND_MIDDLEWARE_ANNOTATION: trusted_frontend_annotation + } _validate_sanitized_secret_refs(sanitized) documents.append(sanitized) if not documents: @@ -1280,6 +1627,7 @@ def inject_telnet_port( if exposure_mode is not None and exposure_mode not in EXPOSURE_MODES: fail("preview exposure mode is not canonical") documents = list(yaml.safe_load_all(source.read_text(encoding="utf-8"))) + frontend_enabled = _frontend_render_enabled(documents) matches = [] ingress_matches = 0 for document in documents: @@ -1288,6 +1636,12 @@ def inject_telnet_port( metadata = _validate_object_metadata( document, expected_namespace, + allow_trusted_ingress_annotation=( + frontend_enabled + and document.get("kind") == "Ingress" + and isinstance(document.get("metadata"), dict) + and document["metadata"].get("name") == "firemud-preview" + ), certificate_identity_mode=certificate_identity_mode, ) namespace = metadata.get("namespace") @@ -1295,15 +1649,28 @@ def inject_telnet_port( fail( f"{document.get('kind')}/{metadata.get('name')} targets namespace {namespace!r}" ) - if "annotations" in metadata: + if "annotations" in metadata and not ( + frontend_enabled + and document.get("kind") == "Ingress" + and metadata.get("name") == "firemud-preview" + and metadata.get("annotations") == { + FRONTEND_MIDDLEWARE_ANNOTATION: _expected_frontend_middleware_reference( + expected_namespace + ) + } + ): fail("validated preview render retains untrusted annotations") metadata["namespace"] = expected_namespace if document.get("kind") == "Ingress" and metadata.get("name") == "firemud-preview": ingress_matches += 1 if certificate_identity_mode == "standalone": metadata["annotations"] = { - "cert-manager.io/cluster-issuer": CANONICAL_INGRESS_ISSUER + "cert-manager.io/cluster-issuer": CANONICAL_INGRESS_ISSUER, } + if frontend_enabled: + metadata["annotations"][FRONTEND_MIDDLEWARE_ANNOTATION] = ( + _expected_frontend_middleware_reference(expected_namespace) + ) if document.get("kind") != "Service": continue if metadata.get("name") != "tcp-proxy-service": @@ -1379,6 +1746,7 @@ def validate_runtime_target( documents = list(yaml.safe_load_all(path.read_text(encoding="utf-8"))) if not documents: fail("prepared preview render is empty") + frontend_enabled = _frontend_render_enabled(documents) node_ports: list[tuple[str, object, object]] = [] ingress_matches = 0 for index, document in enumerate(documents): @@ -1388,10 +1756,12 @@ def validate_runtime_target( document, expected_namespace, allow_trusted_ingress_annotation=( - certificate_identity_mode == "standalone" - and document.get("kind") == "Ingress" + document.get("kind") == "Ingress" and isinstance(document.get("metadata"), dict) and document["metadata"].get("name") == "firemud-preview" + and ( + certificate_identity_mode == "standalone" or frontend_enabled + ) ), allow_trusted_allocated_telnet_port=( document.get("kind") == "Service" @@ -1410,8 +1780,23 @@ def validate_runtime_target( if document.get("kind") == "Ingress" and name == "firemud-preview": ingress_matches += 1 expected_annotations = ( - {"cert-manager.io/cluster-issuer": CANONICAL_INGRESS_ISSUER} - if certificate_identity_mode == "standalone" + { + **( + {"cert-manager.io/cluster-issuer": CANONICAL_INGRESS_ISSUER} + if certificate_identity_mode == "standalone" + else {} + ), + **( + { + FRONTEND_MIDDLEWARE_ANNOTATION: _expected_frontend_middleware_reference( + expected_namespace + ) + } + if frontend_enabled + else {} + ), + } + if certificate_identity_mode == "standalone" or frontend_enabled else None ) if annotations != expected_annotations: @@ -1721,16 +2106,24 @@ def validate_service_consumers( def validate_services( - documents: list[dict], certificate_identity_mode: str = "standalone" + documents: list[dict], + certificate_identity_mode: str = "standalone", + frontend_enabled: bool | None = None, ) -> None: """Require the exact trusted preview Service specs.""" _validate_certificate_identity_mode(certificate_identity_mode) + if frontend_enabled is None: + frontend_enabled = _frontend_render_enabled(documents) for document in documents: if document.get("kind") != "Service": continue name = document.get("metadata", {}).get("name") spec = _require_mapping(document.get("spec"), f"Service/{name}.spec") + if name == "frontend": + if not frontend_enabled or spec != FRONTEND_SERVICE_SPEC: + fail(f"Service/{name} has an unsafe frontend spec") + continue expected_spec = EXPECTED_SERVICE_SPECS.get(name) if expected_spec is None: fail(f"Service/{name} is not an approved preview Service") @@ -1781,13 +2174,25 @@ def _validate_gateway_egress_policy(policy: dict) -> None: fail("NetworkPolicy/spring-cloud-gateway-egress has an unsafe spec") +def validate_frontend_network_policy(document: dict) -> None: + name = document.get("metadata", {}).get("name", "frontend-static-host") + spec = _require_mapping( + document.get("spec"), f"NetworkPolicy/{name}.spec" + ) + if name != "frontend-static-host" or spec != FRONTEND_NETWORK_POLICY_SPEC: + fail(f"NetworkPolicy/{name} has an unsafe spec") + + def validate_network_policies( documents: list[dict], certificate_identity_mode: str = "hosted-controller", + frontend_enabled: bool | None = None, ) -> None: """Keep the runtime policy set and every allowed traffic exception exact.""" _validate_certificate_identity_mode(certificate_identity_mode) + if frontend_enabled is None: + frontend_enabled = _frontend_render_enabled(documents) raw_policies = [ document for document in documents if document.get("kind") == "NetworkPolicy" ] @@ -1795,7 +2200,9 @@ def validate_network_policies( document.get("metadata", {}).get("name"): document for document in raw_policies } - expected_names = _expected_names_for_mode(certificate_identity_mode)[ + expected_names = _expected_names_for_mode( + certificate_identity_mode, frontend_enabled + )[ "NetworkPolicy" ] if len(raw_policies) != len(policies) or set(policies) != expected_names: @@ -1806,6 +2213,9 @@ def validate_network_policies( ) _validate_internal_network_policies(policies) + if frontend_enabled: + validate_frontend_network_policy(policies["frontend-static-host"]) + expected_from = { "namespaceSelector": { "matchLabels": {"kubernetes.io/metadata.name": "firemud-system"} @@ -1954,6 +2364,7 @@ def validate_ingress( document: dict, expected_namespace: str, expected_hostname: str, + frontend_enabled: bool = False, ) -> None: """Require the complete trusted preview Ingress routing contract.""" @@ -1973,29 +2384,57 @@ def validate_ingress( paths = _require_mapping_list( http.get("paths"), f"{ingress_path}.rules[0].http.paths" ) - if len(paths) != 1: + if len(paths) != (5 if frontend_enabled else 1): fail("Ingress/firemud-preview has an unexpected route set") - route = paths[0] - backend = _require_mapping( - route.get("backend"), - f"{ingress_path}.rules[0].http.paths[0].backend", - ) - service_backend = _require_mapping( - backend.get("service"), - f"{ingress_path}.rules[0].http.paths[0].backend.service", - ) - service_port = _require_mapping( - service_backend.get("port"), - f"{ingress_path}.rules[0].http.paths[0].backend.service.port", - ) - if ( - route.get("path") != "/" - or route.get("pathType") != "Prefix" - or service_backend.get("name") != "spring-cloud-gateway" - or service_port.get("number") != 80 - ): - fail("Ingress/firemud-preview has an unsafe backend") + if frontend_enabled: + if paths != _frontend_ingress_paths(): + fail("Ingress/firemud-preview has an unsafe frontend route set") + else: + route = paths[0] + backend = _require_mapping( + route.get("backend"), + f"{ingress_path}.rules[0].http.paths[0].backend", + ) + service_backend = _require_mapping( + backend.get("service"), + f"{ingress_path}.rules[0].http.paths[0].backend.service", + ) + service_port = _require_mapping( + service_backend.get("port"), + f"{ingress_path}.rules[0].http.paths[0].backend.service.port", + ) + if ( + route.get("path") != "/" + or route.get("pathType") != "Prefix" + or service_backend.get("name") != "spring-cloud-gateway" + or service_port.get("number") != 80 + ): + fail("Ingress/firemud-preview has an unsafe backend") + if frontend_enabled: + annotations = document.get("metadata", {}).get("annotations") + if annotations != { + FRONTEND_MIDDLEWARE_ANNOTATION: _expected_frontend_middleware_reference( + expected_namespace + ) + }: + fail("Ingress/firemud-preview has an unsafe frontend middleware reference") + expected_paths = ( + _frontend_ingress_paths() + if frontend_enabled + else [ + { + "path": "/", + "pathType": "Prefix", + "backend": { + "service": { + "name": "spring-cloud-gateway", + "port": {"number": 80}, + } + }, + } + ] + ) expected_spec = { "ingressClassName": "traefik", "tls": [ @@ -2009,16 +2448,7 @@ def validate_ingress( "host": expected_hostname, "http": { "paths": [ - { - "path": "/", - "pathType": "Prefix", - "backend": { - "service": { - "name": "spring-cloud-gateway", - "port": {"number": 80}, - } - }, - } + *expected_paths, ] }, } @@ -2036,15 +2466,18 @@ def validate_manifest( certificate_identity_mode: str = "hosted-controller", ) -> None: _validate_certificate_identity_mode(certificate_identity_mode) - expected_names = _expected_names_for_mode(certificate_identity_mode) + documents = list(yaml.safe_load_all(path.read_text(encoding="utf-8"))) + if not documents: + fail("manifest is empty") + frontend_enabled = _frontend_render_enabled(documents) + expected_names = _expected_names_for_mode( + certificate_identity_mode, frontend_enabled + ) expected_objects = { (kind, name) for kind, names in expected_names.items() for name in names } - documents = list(yaml.safe_load_all(path.read_text(encoding="utf-8"))) - if not documents: - fail("manifest is empty") seen: set[tuple[str, str]] = set() for index, document in enumerate(documents): if not isinstance(document, dict): @@ -2055,6 +2488,9 @@ def validate_manifest( metadata = _validate_object_metadata( document, expected_namespace, + allow_trusted_ingress_annotation=( + frontend_enabled and document.get("kind") == "Ingress" + ), certificate_identity_mode=certificate_identity_mode, ) name = metadata.get("name") @@ -2076,13 +2512,27 @@ def validate_manifest( pod, f"{document['kind']}/{name}.spec.template.spec", ) + if frontend_enabled and document["kind"] == "Deployment" and name == "frontend": + validate_frontend_deployment(document, expected_image_tag) if document["kind"] == "Ingress": - validate_ingress(document, expected_namespace, expected_hostname) + validate_ingress( + document, + expected_namespace, + expected_hostname, + frontend_enabled, + ) + if frontend_enabled and document["kind"] == "Middleware": + validate_frontend_middleware(document, expected_namespace) object_key = (document["kind"], name) if object_key in seen: fail(f"manifest contains duplicate {document['kind']}/{name}") seen.add(object_key) - _validate_no_annotations(document) + if frontend_enabled and document["kind"] == "Ingress": + without_annotations = copy.deepcopy(document) + without_annotations.get("metadata", {}).pop("annotations", None) + _validate_no_annotations(without_annotations) + else: + _validate_no_annotations(document) for location, value in walk(document): if location.endswith(".nodePort"): fail(f"{location} retains a PR-selected nodePort") @@ -2104,7 +2554,14 @@ def validate_manifest( fail(f"{location} contains an unapproved Secret reference") for location, value in walk(document): if location.endswith(".image") and isinstance(value, str): - _validate_image_reference(location, value, expected_image_tag) + _validate_image_reference( + location, + value, + expected_image_tag, + allow_frontend=( + document["kind"] == "Deployment" and name == "frontend" + ), + ) if document["kind"] in {"Deployment", "Job"}: _validate_workload_selector_metadata(document) if document["kind"] == "PersistentVolumeClaim": @@ -2113,8 +2570,10 @@ def validate_manifest( missing = sorted(expected_objects - seen) extra = sorted(seen - expected_objects) fail(f"manifest object set is not closed (missing={missing}, extra={extra})") - validate_services(documents, certificate_identity_mode) - validate_network_policies(documents, certificate_identity_mode) + validate_services(documents, certificate_identity_mode, frontend_enabled) + validate_network_policies( + documents, certificate_identity_mode, frontend_enabled + ) validate_infrastructure_deployments(documents) if ("Service", "tcp-proxy-service") in expected_objects: tcp_proxy_service = next( diff --git a/dev-tools/tests/ci-validation-summary-contract.sh b/dev-tools/tests/ci-validation-summary-contract.sh index fdb265d732..3bf11d75f7 100644 --- a/dev-tools/tests/ci-validation-summary-contract.sh +++ b/dev-tools/tests/ci-validation-summary-contract.sh @@ -41,6 +41,18 @@ if script.index("github.rest.pulls.get") > script.index("github.paginate(github. raise SystemExit("validation-summary must verify the current PR before listing comments") PY +python3 - "$ROOT_DIR/.github/workflows/ci.yml" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +condition = workflow["jobs"]["validation-summary"]["if"] +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +if condition != expected: + raise SystemExit("Optional summary must preserve cancellation, native-PR trust and substantive-event predicates") +PYTHON + script_b64="$({ python3 - "$CI_WORKFLOW" <<'PY' import base64 diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 926cb684a4..fd063f377b 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -498,6 +498,89 @@ grep -Fq "name: \${{ github.event_name == 'pull_request' && github.event.action tmp_dir="$(mktemp -d)" trap 'rm -rf "$tmp_dir"' EXIT + +# The Smoke consumer must outlive its producer and still terminate fail closed. +smoke_clock_fixture="$tmp_dir/smoke-clock.js" +python3 - "$ROOT_DIR" "$smoke_clock_fixture" <<'PY' +from pathlib import Path +import re +import sys +import yaml + +root = Path(sys.argv[1]) +smoke = yaml.load((root / ".github/workflows/smoke.yml").read_text(), Loader=yaml.BaseLoader) +producer = yaml.load((root / ".github/workflows/runtime-images.yml").read_text(), Loader=yaml.BaseLoader) +job = smoke["jobs"]["smoke-gate"] +script = next(step["with"]["script"] for step in job["steps"] if step.get("name") == "Track full-stack smoke result from Build Runtime Images") +producer_minutes = int(re.search(r"const producerTimeoutMinutes = ([0-9]+);", script)[1]) +overhead_minutes = int(re.search(r"const prerequisiteAndQueueAllowanceMinutes = ([0-9]+);", script)[1]) +if producer_minutes != int(producer["jobs"]["pr-local-smoke"]["timeout-minutes"]): + raise SystemExit("Smoke polling producer budget must match the actual full-stack producer timeout") +if overhead_minutes != 45 or int(job["timeout-minutes"]) < producer_minutes + overhead_minutes + 5: + raise SystemExit("Smoke polling must retain bounded scheduling overhead and five-minute job margin") +if "const timeoutMs = (producerTimeoutMinutes + prerequisiteAndQueueAllowanceMinutes) * 60 * 1000;" not in script: + raise SystemExit("Smoke polling deadline must use the checked producer and overhead authorities") +Path(sys.argv[2]).write_text(script) +PY + +node - "$smoke_clock_fixture" <<'NODE' +const assert = require("node:assert/strict"); +const script = require("node:fs").readFileSync(process.argv[2], "utf8"); +const head = "a".repeat(40), base = "b".repeat(40), merge = "c".repeat(40); +const title = `Build Runtime Images secure-pr-artifact pr-42 base-${base} head-${head} merge-${merge} mode-required`; +const context = { repo: { owner: "example", repo: "firemud" }, sha: merge, + payload: { pull_request: { number: 42, head: { sha: head }, base: { ref: "develop", sha: base }, created_at: "2026-09-01T00:00:00Z" } } }; +const execute = new Function("github", "context", "core", "Date", "setTimeout", `return (async () => {\n${script}\n})()`); +async function scenario(outcome, completedAtMinutes) { + let now = 1000; + const start = now; + const failures = []; + const listRuns = async () => {}, listJobs = async () => {}; + const github = { rest: { + pulls: { get: async () => ({ data: { state: "open", head: { sha: head }, base: { ref: "develop", sha: base }, merge_commit_sha: merge } }) }, + repos: { getCommit: async () => ({ data: { sha: merge, parents: [{ sha: base }, { sha: head }] } }) }, + actions: { listWorkflowRuns: listRuns, listJobsForWorkflowRun: listJobs }, + }, paginate: async (method, input) => { + assert.equal(method, listJobs); + assert.equal(input.run_id, 42); + return [{ name: "PR Full-Stack Smoke", status: "completed", conclusion: "success", + steps: [{ name: "Run credential-free full-stack smoke", status: "completed", conclusion: "success" }] }]; + } }; + github.paginate.iterator = async function* (method, input) { + assert.equal(method, listRuns); + assert.equal(input.workflow_id, "runtime-images.yml"); + if (input.event === "repository_dispatch") { yield { data: [] }; return; } + assert.equal(input.head_sha, head); + const complete = now - start >= completedAtMinutes * 60 * 1000; + yield { data: [{ id: 42, event: "pull_request", head_sha: head, display_title: title, pull_requests: [], + status: complete ? "completed" : "in_progress", conclusion: complete ? outcome : null }] }; + }; + const core = { info: () => {}, warning: () => {}, setFailed: message => failures.push(message) }; + const clock = { now: () => now, parse: Date.parse }; + const sleep = (callback, duration) => { now += duration; queueMicrotask(callback); }; + await execute(github, context, core, clock, sleep); + return { failures, minutes: (now - start) / 60000 }; +} +(async () => { + const success = await scenario("success", 30); + assert.deepEqual(success.failures, [], "exact producer success after 25 minutes must be admitted"); + assert.equal(success.minutes, 30); + const failed = await scenario("failure", 30); + assert.equal(failed.failures.length, 1); + assert.match(failed.failures[0], /did not complete successfully/); + assert.equal(failed.minutes, 30, "terminal failure must stop polling promptly"); + const cancelled = await scenario("cancelled", 0); + assert.equal(cancelled.failures.length, 1); + assert.match(cancelled.failures[0], /cancelled/i); + assert.ok(cancelled.minutes <= 5.25, "cancelled source without an exact replacement remains bounded"); + const deadline = await scenario("success", Infinity); + assert.equal(deadline.failures.length, 1); + assert.match(deadline.failures[0], /Timed out waiting for the exact/); + assert.equal(deadline.minutes, 90, "active producers cannot escape the total deadline"); + console.log("Smoke clock contract passed: late success, prompt failure, bounded cancellation and deadline"); +})().catch(error => { console.error(error); process.exitCode = 1; }); +NODE + cat >"$tmp_dir/gh" <<'EOF' #!/usr/bin/env bash set -euo pipefail diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index e27cbf79e0..affc4ae136 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -334,6 +334,44 @@ for path in "$ci_path" "$security_path" "$smoke_path"; do require_contains "$path" 'types: [opened, synchronize, reopened, edited]' done +# Optional native-PR comments cannot delay cancellation or require fork/bot write tokens. +python3 - "$ROOT_DIR" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +root = Path(sys.argv[1]) +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +for filename, jobs in { + "ci.yml": ("validation-summary",), + "security.yml": ("security-summary",), + "smoke.yml": ("smoke-summary-pending", "smoke-summary"), +}.items(): + workflow = yaml.load((root / ".github/workflows" / filename).read_text(), Loader=yaml.BaseLoader) + for job in jobs: + condition = workflow["jobs"][job]["if"] + if condition != expected: + raise SystemExit(f"{filename}/{job} must retain the cancellation, trust and substantive-event condition") + def eligible(cancelled=False, event="pull_request", head_repo="example/repo", actor="contributor", action="synchronize", base_ref=None): + expression = condition[3:-3].replace("!cancelled()", str(not cancelled)) + values = { + "github.event.pull_request.head.repo.full_name": head_repo, + "github.event.changes.base.ref": base_ref, + "github.event_name": event, + "github.repository": "example/repo", + "github.actor": actor, + "github.event.action": action, + } + for key, value in values.items(): + expression = expression.replace(key, repr(value)) + return eval(expression.replace("&&", "and").replace("||", "or").replace("null", "None"), {"__builtins__": {}}) + if not eligible() or not eligible(action="edited", base_ref="develop"): + raise SystemExit(f"{job} must report ordinary results and base retargets") + for arguments in ({"cancelled": True}, {"head_repo": "fork/repo"}, {"actor": "dependabot[bot]"}, {"action": "edited"}, {"event": "push"}): + if eligible(**arguments): + raise SystemExit(f"{job} permits an ineligible comment mutation: {arguments}") +PYTHON + # Metadata-only edits get distinct optional summary contexts; substantive events # retain each summary's canonical name. # shellcheck disable=SC2016 # Assert literal GitHub expression syntax. @@ -1503,6 +1541,15 @@ runtime_service = "services/account-service/src/Main.java" assert run_scope([controller_service]) == {"run_smoke_full": "false"} assert run_scope([controller_smoke_script]) == {"run_smoke_full": "false"} +# Source-built MinIO helpers must require runtime proof even when no Dockerfile changes. +root = Path(sys.argv[1]).resolve().parents[2] +preview_resolver = (root / "dev-tools/hosted/preview/resolve-preview-image-tag.sh").read_text() +preview_predicate = preview_resolver[preview_resolver.index("runtime_relevant() {"):preview_resolver.index('\nif [[ -n "${pr_number}"')] +for helper in ("dev-tools/minio/base_image_refs.py", "dev-tools/minio/build-and-smoke-images.sh"): + assert run_scope([helper]) == {"run_smoke_full": "true"}, helper + preview = subprocess.run(["bash", "-c", preview_predicate + '\nruntime_relevant "$1"', "preview-scope", helper], check=False) + assert preview.returncode == 0, helper +assert subprocess.run(["bash", "-c", preview_predicate + '\nruntime_relevant "$1"', "preview-scope", "design/example.md"], check=False).returncode != 0 assert run_scope([runtime_service]) == {"run_smoke_full": "true"} assert run_scope([controller_service, runtime_service]) == {"run_smoke_full": "true"} PY @@ -1973,6 +2020,7 @@ const scripts = JSON.parse(process.env.SMOKE_SUMMARY_SCRIPTS); const context = { repo: { owner: "example", repo: "firemud" }, issue: { number: 42 }, + payload: { pull_request: { head: { sha: "h" }, base: { ref: "develop", sha: "b" } } }, }; async function checkSummary(jobName, script) { @@ -2005,13 +2053,16 @@ async function checkSummary(jobName, script) { created_at: "2026-08-01T00:00:00Z", }, ]; - const calls = { paginate: [], operations: [], creates: [] }; + const calls = { paginate: [], operations: [], creates: [], bodies: [] }; + let currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request) }; + let readError = null; const listComments = async () => undefined; const github = { rest: { + pulls: { get: async () => { if (readError) throw readError; return { data: currentPullRequest }; } }, issues: { listComments, - updateComment: async ({ comment_id }) => calls.operations.push(`update:${comment_id}`), + updateComment: async ({ comment_id, body }) => { calls.operations.push(`update:${comment_id}`); calls.bodies.push(body); }, deleteComment: async ({ comment_id }) => calls.operations.push(`delete:${comment_id}`), createComment: async (request) => calls.creates.push(request), }, @@ -2025,8 +2076,24 @@ async function checkSummary(jobName, script) { process.env.CHANGES_RESULT = "success"; process.env.RUN_SMOKE_FULL = "true"; process.env.SMOKE_GATE_RESULT = "success"; - const run = new Function("github", "context", `return (async () => {\n${script}\n})()`); - await run(github, context); + const run = new Function("github", "context", "core", `return (async () => {\n${script}\n})()`); + const core = { info: () => {} }; + for (const changed of [ + { state: "closed" }, { head: { sha: "new" } }, + { base: { ref: "main", sha: "b" } }, { base: { ref: "develop", sha: "new" } }, + ]) { + currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request), ...changed }; + await run(github, context, core); + assert.deepEqual(calls.paginate, [], `${jobName} must not list stale comments`); + assert.deepEqual(calls.operations, [], `${jobName} must not mutate stale comments`); + assert.deepEqual(calls.creates, [], `${jobName} must not create stale comments`); + } + readError = new Error("PR guard unavailable"); + await assert.rejects(run(github, context, core), /PR guard unavailable/); + assert.deepEqual(calls.paginate, [], `${jobName} guard errors must fail closed`); + readError = null; + currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request) }; + await run(github, context, core); assert.equal(calls.paginate.length, 1, `${jobName} must paginate once`); assert.equal(calls.paginate[0].method, listComments, `${jobName} must paginate issue comments`); @@ -2037,6 +2104,10 @@ async function checkSummary(jobName, script) { `${jobName} must update the oldest bot summary before deleting later duplicates`, ); assert.deepEqual(calls.creates, [], `${jobName} must not create another summary`); + process.env.CHANGES_RESULT = "failure"; + process.env.SMOKE_GATE_RESULT = "failure"; + await run(github, context, core); + assert.ok(calls.bodies.at(-1).includes("failure"), `${jobName} must report failed dependencies`); } (async () => { diff --git a/dev-tools/tests/pr-runtime-image-publication-contract.sh b/dev-tools/tests/pr-runtime-image-publication-contract.sh index 1bbb114fab..c8a2009a3c 100644 --- a/dev-tools/tests/pr-runtime-image-publication-contract.sh +++ b/dev-tools/tests/pr-runtime-image-publication-contract.sh @@ -159,7 +159,7 @@ cat > "$artifact_dir/pr-runtime-provenance.json" < "$fixture_dir/source-run.json" < "$fixture_dir/pull-request.json" <&2 + exit 1 + fi + python3 - "$fixture_dir/source-run.json" "$source_title" <<'PY' +import json +import sys +from pathlib import Path +p = Path(sys.argv[1]); data = json.loads(p.read_text()); data["name"] = "Build Runtime Images"; data["display_title"] = sys.argv[2]; p.write_text(json.dumps(data)) +PY +done run_validation grep -Fxq "IMAGE_TAG=pr-merge-$merge_sha" "$fixture_dir/github-env" grep -Fxq "PR_RUNTIME_ARTIFACT_DIR=$artifact_dir" "$fixture_dir/github-env" diff --git a/dev-tools/tests/security-summary-contract.sh b/dev-tools/tests/security-summary-contract.sh index 1164ed55ee..56120dc56b 100644 --- a/dev-tools/tests/security-summary-contract.sh +++ b/dev-tools/tests/security-summary-contract.sh @@ -15,6 +15,18 @@ grep -Fq 'currentPullRequest.head.sha !== expectedHeadSha' "$workflow" grep -Fq 'currentPullRequest.base.ref !== expectedBaseRef' "$workflow" grep -Fq 'currentPullRequest.base.sha !== expectedBaseSha' "$workflow" +python3 - "$repo_root/.github/workflows/security.yml" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +condition = workflow["jobs"]["security-summary"]["if"] +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +if condition != expected: + raise SystemExit("Optional summary must preserve cancellation, native-PR trust and substantive-event predicates") +PYTHON + test_root="$(mktemp -d)" trap 'rm -rf -- "$test_root"' EXIT script_path="$test_root/security-summary.js" @@ -164,4 +176,43 @@ run(github, context, core).then(async () => { }); NODE +# Execute the checked-in scanner step using the explicit Actions Bash shell. +# The fake scanner and reports stay in one disposable directory; no scan/network occurs. +python3 - "$workflow" "$repo_root/config/security/trivy.yaml" <<'PYTHON' +from pathlib import Path +import os +import subprocess +import sys +import tempfile +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +steps = workflow["jobs"]["trivy-scan"]["steps"] +scanner = next(step for step in steps if step.get("name") == "🔍 Run Trivy and Save Report") +upload = next(step for step in steps if step.get("name") == "📤 Upload Trivy Report") +if scanner.get("shell") != "bash" or upload.get("if") != "always()": + raise SystemExit("Trivy must use explicit pipefail Bash and retain always-uploaded reports") +settings = yaml.safe_load(Path(sys.argv[2]).read_text()) +if settings.get("exit-code") != 1 or settings.get("severity") != ["CRITICAL", "HIGH"] or settings.get("ignore-unfixed") is not True: + raise SystemExit("Trivy failure policy and filters must remain intact") +with tempfile.TemporaryDirectory(prefix="firemud-trivy-pipeline-") as directory: + root = Path(directory) + scanner_path = root / "trivy" + scanner_path.write_text('#!/bin/sh\nprintf "scanner-result-%s\\n" "$FAKE_TRIVY_EXIT"\nexit "$FAKE_TRIVY_EXIT"\n') + scanner_path.chmod(0o755) + for exit_status in (0, 1, 2): + environment = dict(os.environ, PATH=str(root) + os.pathsep + os.environ["PATH"], FAKE_TRIVY_EXIT=str(exit_status)) + # actions/runner explicit shell:bash -> bash --noprofile --norc -e -o pipefail {0}. + script = root / "step.sh" + script.write_text(scanner["run"]) + result = subprocess.run(["bash", "--noprofile", "--norc", "-e", "-o", "pipefail", str(script)], cwd=root, env=environment, capture_output=True, text=True) + if result.returncode != exit_status: + raise SystemExit(f"Trivy exit {exit_status} was masked: {result.returncode}") + if (root / "trivy-report.txt").read_text() != f"scanner-result-{exit_status}\n": + raise SystemExit("tee must retain the report even when the scanner fails") + if ("::endgroup::" in result.stdout) != (exit_status == 0): + raise SystemExit("Failed scanner pipelines must stop the step") +print("Trivy pipeline contract passed: scanner success/vulnerability/error with reports retained") +PYTHON + echo "security summary contract passed" diff --git a/dev-tools/tests/static-analysis-summary-contract.sh b/dev-tools/tests/static-analysis-summary-contract.sh index 14165090c5..17edc16a3a 100644 --- a/dev-tools/tests/static-analysis-summary-contract.sh +++ b/dev-tools/tests/static-analysis-summary-contract.sh @@ -262,7 +262,7 @@ const context = { payload: { workflow_run: { event: "pull_request", - name: `CodeQL Analysis pr-42 base-${baseSha} head-${headSha}`, + name: "CodeQL Analysis", path: ".github/workflows/codeql.yml", head_sha: headSha, head_branch: "feature", @@ -273,7 +273,7 @@ const context = { }; const core = { info: () => {} }; const run = new Function("github", "context", "core", `return (async () => {\n${script}\n})()`); -run(github, context, core).then(() => { +run(github, context, core).then(async () => { if (calls.paginate.length !== 4) throw new Error(`expected four paginated calls, got ${calls.paginate.length}`); if (!calls.paginate.every(({ input }) => input.per_page === 100)) throw new Error("all API listings must request page size 100"); if (calls.updated.length !== 1 || calls.updated[0].comment_id !== 2) throw new Error("oldest bot summary was not updated"); @@ -281,6 +281,12 @@ run(github, context, core).then(() => { if (calls.created.length !== 0) throw new Error("existing bot summary should be updated"); if (!calls.updated[0].body.includes("❌ Static analysis checks failed")) throw new Error("new failure was masked by the older success"); if (!calls.updated[0].body.includes("CodeQL gate: `failure`")) throw new Error("latest CodeQL gate result was not selected"); + context.payload.workflow_run.name = "Forged workflow name"; + await run(github, context, core); + if (calls.paginate.length !== 4 || calls.updated.length !== 1 || calls.deleted.length !== 1) { + throw new Error("unrelated source names must not query runs or alter comments"); + } + context.payload.workflow_run.name = "CodeQL Analysis"; currentHeadSha = "d".repeat(40); return run(github, context, core).then(() => { if (calls.paginate.length !== 4 || calls.updated.length !== 1 || calls.deleted.length !== 1) { @@ -316,6 +322,7 @@ run(github, context, core).then(() => { calls.deleted.length = 0; calls.updated.length = 0; calls.created.length = 0; + context.payload.workflow_run.name = `CodeQL Analysis pr-42 base-${baseSha} head-${headSha}`; deleteStatus = 404; return run(github, context, core).then(() => { if (calls.deleted.length !== 1 || calls.deleted[0] !== 3) { diff --git a/dev-tools/validation/test_validate_preview_artifact.py b/dev-tools/validation/test_validate_preview_artifact.py index 98f8eb8404..20bc33d0ee 100644 --- a/dev-tools/validation/test_validate_preview_artifact.py +++ b/dev-tools/validation/test_validate_preview_artifact.py @@ -2053,57 +2053,70 @@ def test_identity_labels_survive_sanitize_injection_and_runtime_target(self): def test_mode_specific_policy_sets_and_rules_are_closed(self): hosted = self._policy_documents("hosted-controller") standalone = self._policy_documents("standalone") - with self.assertRaisesRegex(ValueError, "runtime NetworkPolicy set is not closed"): - self.validator.validate_network_policies( - standalone - + [ - self._policy_document( - "account-service-controller-ingress", {} - ) - ], - "standalone", - ) - missing_account = [ - document - for document in hosted - if document["metadata"]["name"] != "account-service-controller-ingress" - ] - with self.assertRaisesRegex(ValueError, "runtime NetworkPolicy set is not closed"): - self.validator.validate_network_policies(missing_account, "hosted-controller") - - missing_game_session = [ - document - for document in hosted - if document["metadata"]["name"] - != "game-session-service-controller-ingress" - ] - with self.assertRaisesRegex(ValueError, "runtime NetworkPolicy set is not closed"): - self.validator.validate_network_policies( - missing_game_session, "hosted-controller" - ) - - for field, value, message in ( - ( - "podSelector", - {"matchLabels": {"app": "account-service"}}, - "selects an unsafe workload", - ), - ("policyTypes", ["Ingress", "Egress"], "must only govern ingress"), - ("ingress", [], "has an unsafe exception"), + for workload in ( + "account-service", + "game-session-service", + "social-groups-service", ): - with self.subTest(mode="hosted-controller", game_session_field=field): - malformed = copy.deepcopy(hosted) - policy = next( - document - for document in malformed - if document["metadata"]["name"] - == "game-session-service-controller-ingress" + with self.subTest(mode="standalone", workload=workload), self.assertRaisesRegex( + ValueError, "runtime NetworkPolicy set is not closed" + ): + self.validator.validate_network_policies( + standalone + + [ + self._policy_document( + f"{workload}-controller-ingress", {} + ) + ], + "standalone", ) - policy["spec"][field] = value - with self.assertRaisesRegex(ValueError, message): - self.validator.validate_network_policies( - malformed, "hosted-controller" + for workload in ( + "account-service", + "game-session-service", + "social-groups-service", + ): + missing_policy = [ + document + for document in hosted + if document["metadata"]["name"] + != f"{workload}-controller-ingress" + ] + with self.subTest(mode="hosted-controller", missing=workload), self.assertRaisesRegex( + ValueError, "runtime NetworkPolicy set is not closed" + ): + self.validator.validate_network_policies( + missing_policy, "hosted-controller" + ) + + for workload in ( + "account-service", + "game-session-service", + "social-groups-service", + ): + for field, value, message in ( + ( + "podSelector", + {"matchLabels": {"app": f"{workload}-other"}}, + "selects an unsafe workload", + ), + ("policyTypes", ["Ingress", "Egress"], "must only govern ingress"), + ("ingress", [], "has an unsafe exception"), + ): + with self.subTest( + mode="hosted-controller", workload=workload, field=field + ): + malformed = copy.deepcopy(hosted) + policy = next( + document + for document in malformed + if document["metadata"]["name"] + == f"{workload}-controller-ingress" ) + policy["spec"][field] = value + with self.assertRaisesRegex(ValueError, message): + self.validator.validate_network_policies( + malformed, "hosted-controller" + ) for mode in ("standalone", "hosted-controller"): with self.subTest(mode=mode, case="missing gateway egress"): @@ -2638,6 +2651,370 @@ def test_gateway_rejects_extra_env_from_reference(self): self.validator.validate_service_consumers([document], "pr-42") +class PreviewArtifactFrontendValidationTest(unittest.TestCase): + validator = VALIDATOR + + def _frontend_deployment(self): + return { + "apiVersion": "apps/v1", + "kind": "Deployment", + "metadata": {"name": "frontend"}, + "spec": { + "replicas": 1, + "selector": {"matchLabels": {"app": "frontend"}}, + "template": { + "metadata": {"labels": {"app": "frontend"}}, + "spec": { + "automountServiceAccountToken": False, + "securityContext": { + "runAsNonRoot": True, + "runAsUser": 101, + "runAsGroup": 101, + "fsGroup": 101, + "fsGroupChangePolicy": "OnRootMismatch", + "seccompProfile": {"type": "RuntimeDefault"}, + }, + "imagePullSecrets": [{"name": "ghcr-preview-pull"}], + "containers": [ + { + "name": "frontend", + "image": "ghcr.io/benhook1013/web-client:pr-42-head-42", + "imagePullPolicy": "Always", + "securityContext": { + "allowPrivilegeEscalation": False, + "readOnlyRootFilesystem": True, + "runAsNonRoot": True, + "runAsUser": 101, + "runAsGroup": 101, + "capabilities": {"drop": ["ALL"]}, + }, + "ports": [ + { + "name": "http", + "containerPort": 8080, + "protocol": "TCP", + } + ], + "readinessProbe": { + "httpGet": {"path": "/healthz", "port": "http"}, + "initialDelaySeconds": 2, + "periodSeconds": 10, + }, + "livenessProbe": { + "httpGet": {"path": "/healthz", "port": "http"}, + "initialDelaySeconds": 5, + "periodSeconds": 20, + }, + "resources": copy.deepcopy( + self.validator.FRONTEND_RESOURCES + ), + "volumeMounts": [ + {"name": "nginx-tmp", "mountPath": "/tmp"} + ], + } + ], + "volumes": [ + { + "name": "nginx-tmp", + "emptyDir": {"sizeLimit": "16Mi"}, + } + ], + }, + }, + }, + } + + def _frontend_service(self): + return { + "apiVersion": "v1", + "kind": "Service", + "metadata": {"name": "frontend"}, + "spec": copy.deepcopy(self.validator.FRONTEND_SERVICE_SPEC), + } + + def _frontend_policy(self): + return { + "apiVersion": "networking.k8s.io/v1", + "kind": "NetworkPolicy", + "metadata": {"name": "frontend-static-host"}, + "spec": copy.deepcopy(self.validator.FRONTEND_NETWORK_POLICY_SPEC), + } + + def _frontend_middleware(self): + return { + "apiVersion": "traefik.io/v1alpha1", + "kind": "Middleware", + "metadata": {"name": "firemud-preview-auth-path-rewrite"}, + "spec": copy.deepcopy(self.validator.FRONTEND_MIDDLEWARE_SPEC), + } + + def _frontend_ingress(self): + return { + "apiVersion": "networking.k8s.io/v1", + "kind": "Ingress", + "metadata": { + "name": "firemud-preview", + "annotations": { + self.validator.FRONTEND_MIDDLEWARE_ANNOTATION: ( + "pr-42-firemud-preview-auth-path-rewrite@kubernetescrd" + ) + }, + }, + "spec": { + "ingressClassName": "traefik", + "tls": [ + { + "hosts": ["pr-42.preview.example.test"], + "secretName": "pr-42-tls", + } + ], + "rules": [ + { + "host": "pr-42.preview.example.test", + "http": {"paths": self.validator._frontend_ingress_paths()}, + } + ], + }, + } + + def test_opt_in_frontend_contract_is_exact_and_default_is_closed(self): + self.validator.validate_frontend_deployment( + self._frontend_deployment(), "pr-42-head-42" + ) + self.validator.validate_services( + [self._frontend_service()], "hosted-controller", True + ) + self.validator.validate_frontend_middleware( + self._frontend_middleware(), "pr-42" + ) + self.validator.validate_ingress( + self._frontend_ingress(), "pr-42", "pr-42.preview.example.test", True + ) + enabled = self.validator._expected_names_for_mode("hosted-controller", True) + disabled = self.validator._expected_names_for_mode("hosted-controller", False) + for kind, names in self.validator.FRONTEND_EXPECTED_NAMES.items(): + self.assertTrue(names <= enabled[kind]) + self.assertTrue(names.isdisjoint(disabled.get(kind, set()))) + + def test_sanitize_accepts_named_opt_in_objects_and_preserves_middleware(self): + documents = [ + self._frontend_deployment(), + self._frontend_service(), + self._frontend_policy(), + self._frontend_middleware(), + self._frontend_ingress(), + ] + with tempfile.TemporaryDirectory() as directory: + source = Path(directory) / "render.yaml" + destination = Path(directory) / "sanitized.yaml" + source.write_text(yaml.safe_dump_all(documents), encoding="utf-8") + self.validator.sanitize(source, destination) + sanitized = list(yaml.safe_load_all(destination.read_text(encoding="utf-8"))) + ingress = next(document for document in sanitized if document["kind"] == "Ingress") + self.assertEqual( + ingress["metadata"]["annotations"], + { + self.validator.FRONTEND_MIDDLEWARE_ANNOTATION: ( + "pr-42-firemud-preview-auth-path-rewrite@kubernetescrd" + ) + }, + ) + self.assertEqual( + {(document["kind"], document["metadata"]["name"]) for document in sanitized}, + { + ("Deployment", "frontend"), + ("Service", "frontend"), + ("NetworkPolicy", "frontend-static-host"), + ("Middleware", "firemud-preview-auth-path-rewrite"), + ("Ingress", "firemud-preview"), + }, + ) + + def test_validate_manifest_accepts_complete_opt_in_closed_set(self): + documents = [ + self._frontend_deployment(), + self._frontend_service(), + self._frontend_policy(), + self._frontend_middleware(), + self._frontend_ingress(), + ] + labels = self.validator._expected_object_labels("pr-42") + for document in documents: + document["metadata"]["labels"] = copy.deepcopy(labels) + expected_names = { + "Deployment": {"frontend"}, + "Service": {"frontend"}, + "NetworkPolicy": {"frontend-static-host"}, + "Middleware": {"firemud-preview-auth-path-rewrite"}, + "Ingress": {"firemud-preview"}, + } + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "manifest.yaml" + path.write_text(yaml.safe_dump_all(documents), encoding="utf-8") + with ( + patch.object(self.validator, "EXPECTED_NAMES", expected_names), + patch.object(self.validator, "validate_services"), + patch.object(self.validator, "validate_network_policies"), + patch.object(self.validator, "validate_infrastructure_deployments"), + patch.object(self.validator, "validate_service_consumers"), + ): + self.validator.validate_manifest( + path, + "pr-42", + "pr-42-head-42", + "pr-42.preview.example.test", + ) + + def test_validate_manifest_rejects_missing_opt_in_object(self): + documents = [ + self._frontend_deployment(), + self._frontend_service(), + self._frontend_policy(), + self._frontend_ingress(), + ] + labels = self.validator._expected_object_labels("pr-42") + for document in documents: + document["metadata"]["labels"] = copy.deepcopy(labels) + expected_names = { + "Deployment": {"frontend"}, + "Service": {"frontend"}, + "NetworkPolicy": {"frontend-static-host"}, + "Middleware": {"firemud-preview-auth-path-rewrite"}, + "Ingress": {"firemud-preview"}, + } + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "manifest.yaml" + path.write_text(yaml.safe_dump_all(documents), encoding="utf-8") + with ( + patch.object(self.validator, "EXPECTED_NAMES", expected_names), + self.assertRaisesRegex(ValueError, "object set is not closed"), + ): + self.validator.validate_manifest( + path, + "pr-42", + "pr-42-head-42", + "pr-42.preview.example.test", + ) + def test_frontend_deployment_rejects_mutated_security_or_image(self): + cases = ( + ( + "root filesystem", + lambda document: document["spec"]["template"]["spec"]["containers"][0][ + "securityContext" + ].__setitem__("readOnlyRootFilesystem", False), + ), + ( + "image repository", + lambda document: document["spec"]["template"]["spec"]["containers"][0].__setitem__( + "image", "ghcr.io/attacker/web-client:pr-42-head-42" + ), + ), + ( + "image digest", + lambda document: document["spec"]["template"]["spec"]["containers"][0].__setitem__( + "image", "ghcr.io/benhook1013/web-client@sha256:abc" + ), + ), + ) + for case, mutate in cases: + with self.subTest(case=case): + document = self._frontend_deployment() + mutate(document) + with self.assertRaises(ValueError): + self.validator.validate_frontend_deployment( + document, "pr-42-head-42" + ) + + def test_frontend_service_policy_and_middleware_reject_shape_changes(self): + service = self._frontend_service() + service["spec"]["ports"][0]["targetPort"] = 8081 + with self.assertRaisesRegex(ValueError, "unsafe frontend spec"): + self.validator.validate_services([service], "hosted-controller", True) + + policy = self._frontend_policy() + policy["spec"]["egress"] = [ + {"to": [{"ipBlock": {"cidr": "0.0.0.0/0"}}]} + ] + with self.assertRaisesRegex(ValueError, "frontend-static-host has an unsafe spec"): + self.validator.validate_frontend_network_policy(policy) + + middleware = self._frontend_middleware() + middleware["spec"]["replacePathRegex"]["replacement"] = "/api/account/login$1" + with self.assertRaisesRegex(ValueError, "unsafe spec"): + self.validator.validate_frontend_middleware(middleware, "pr-42") + + def test_frontend_ingress_rejects_missing_extra_and_misrouted_paths(self): + cases = ( + ( + "missing route", + lambda ingress: ingress["spec"]["rules"][0]["http"]["paths"].pop(), + ), + ( + "misrouted auth", + lambda ingress: ingress["spec"]["rules"][0]["http"]["paths"][1][ + "backend" + ]["service"].__setitem__("name", "frontend"), + ), + ( + "extra route", + lambda ingress: ingress["spec"]["rules"][0]["http"]["paths"].append( + { + "path": "/admin", + "pathType": "Prefix", + "backend": { + "service": { + "name": "spring-cloud-gateway", + "port": {"number": 80}, + } + }, + } + ), + ), + ( + "published assets routed through gateway", + lambda ingress: ingress["spec"]["rules"][0]["http"]["paths"].insert( + -1, + { + "path": "/assets", + "pathType": "Prefix", + "backend": { + "service": { + "name": "spring-cloud-gateway", + "port": {"number": 80}, + } + }, + }, + ), + ), + ) + for case, mutate in cases: + with self.subTest(case=case): + ingress = self._frontend_ingress() + mutate(ingress) + with self.assertRaisesRegex(ValueError, "route"): + self.validator.validate_ingress( + ingress, "pr-42", "pr-42.preview.example.test", True + ) + + def test_frontend_policy_closed_set_rejects_missing_and_extra_objects(self): + expected = self.validator._expected_names_for_mode( + "hosted-controller", True + )["NetworkPolicy"] + for case, names in ( + ("missing", expected - {"frontend-static-host"}), + ("extra", expected | {"frontend-extra"}), + ): + with self.subTest(case=case): + documents = [ + {"kind": "NetworkPolicy", "metadata": {"name": name}} + for name in names + ] + with self.assertRaisesRegex(ValueError, "set is not closed"): + self.validator.validate_network_policies( + documents, "hosted-controller", True + ) + + class PreviewArtifactNetworkPolicyTest(unittest.TestCase): validator = VALIDATOR diff --git a/k8s/helm/firemud/templates/frontend.yaml b/k8s/helm/firemud/templates/frontend.yaml new file mode 100644 index 0000000000..4a02d32014 --- /dev/null +++ b/k8s/helm/firemud/templates/frontend.yaml @@ -0,0 +1,124 @@ +{{- $frontend := .Values.previewStack.frontend | default dict }} +{{- if and .Values.previewStack.enabled ($frontend.enabled | default false) }} +{{- $frontendImage := $frontend.image | default dict }} +{{- $imageRepository := required "previewStack.frontend.image.repository is required when the frontend is enabled" (get $frontendImage "repository" | default "") }} +{{- $imageTag := required "previewStack.frontend.image.tag or previewStack.defaultImageTag is required when the frontend is enabled" (default $.Values.previewStack.defaultImageTag (get $frontendImage "tag")) }} +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: frontend + labels: +{{ include "firemud.commonLabels" . | indent 4 }} +spec: + replicas: {{ default 1 $frontend.replicaCount }} + selector: + matchLabels: + app: frontend + template: + metadata: + labels: + app: frontend + spec: + automountServiceAccountToken: false + securityContext: + runAsNonRoot: true + runAsUser: 101 + runAsGroup: 101 + fsGroup: 101 + fsGroupChangePolicy: OnRootMismatch + seccompProfile: + type: RuntimeDefault + {{- with $.Values.previewStack.imagePullSecrets }} + imagePullSecrets: + {{- range $secret := . }} + {{- if kindIs "string" $secret }} + - name: {{ $secret }} + {{- else }} +{{ toYaml (list $secret) | indent 8 }} + {{- end }} + {{- end }} + {{- end }} + containers: + - name: frontend + image: "{{ $imageRepository }}:{{ $imageTag }}" + imagePullPolicy: Always + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + runAsNonRoot: true + runAsUser: 101 + runAsGroup: 101 + capabilities: + drop: + - ALL + ports: + - name: http + containerPort: 8080 + protocol: TCP + readinessProbe: + httpGet: + path: /healthz + port: http + initialDelaySeconds: 2 + periodSeconds: 10 + livenessProbe: + httpGet: + path: /healthz + port: http + initialDelaySeconds: 5 + periodSeconds: 20 + resources: +{{ toYaml $frontend.resources | indent 12 }} + volumeMounts: + - name: nginx-tmp + mountPath: /tmp + volumes: + - name: nginx-tmp + emptyDir: + sizeLimit: 16Mi +--- +apiVersion: v1 +kind: Service +metadata: + name: frontend + labels: +{{ include "firemud.commonLabels" . | indent 4 }} +spec: + type: ClusterIP + selector: + app: frontend + ports: + - name: http + port: 80 + targetPort: http + protocol: TCP +{{- if .Values.previewStack.networkPolicies.enabled }} +--- +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: frontend-static-host + labels: +{{ include "firemud.commonLabels" . | indent 4 }} +spec: + podSelector: + matchLabels: + app: frontend + policyTypes: + - Ingress + - Egress + ingress: + - from: + - namespaceSelector: + matchLabels: + kubernetes.io/metadata.name: kube-system + podSelector: + matchLabels: + app.kubernetes.io/name: traefik + ports: + - protocol: TCP + port: 8080 + egress: [] +{{- end }} +{{- end }} diff --git a/k8s/helm/firemud/templates/ingress.yaml b/k8s/helm/firemud/templates/ingress.yaml index 5e96c81f61..4496ee99a2 100644 --- a/k8s/helm/firemud/templates/ingress.yaml +++ b/k8s/helm/firemud/templates/ingress.yaml @@ -1,3 +1,5 @@ +{{- $frontend := .Values.previewStack.frontend | default dict }} +{{- $frontendEnabled := $frontend.enabled | default false }} {{- if and .Values.previewStack.enabled .Values.previewStack.ingress.enabled }} {{- $hostedControllerMode := include "firemud.hostedControllerMode" . | trim }} apiVersion: networking.k8s.io/v1 @@ -6,9 +8,14 @@ metadata: name: firemud-preview labels: {{ include "firemud.commonLabels" . | indent 4 }} - {{- if ne $hostedControllerMode "true" }} + {{- if or (ne $hostedControllerMode "true") $frontendEnabled }} annotations: + {{- if ne $hostedControllerMode "true" }} cert-manager.io/cluster-issuer: {{ .Values.previewStack.ingress.clusterIssuer | quote }} + {{- end }} + {{- if $frontendEnabled }} + traefik.ingress.kubernetes.io/router.middlewares: {{ printf "%s-firemud-preview-auth-path-rewrite@kubernetescrd" .Release.Namespace | quote }} + {{- end }} {{- end }} spec: ingressClassName: {{ .Values.previewStack.ingress.className | quote }} @@ -20,6 +27,43 @@ spec: - host: {{ .Values.preview.hostname | quote }} http: paths: + {{- if $frontendEnabled }} + - path: /frontend-assets + pathType: Prefix + backend: + service: + name: frontend + port: + number: 80 + - path: /auth + pathType: Prefix + backend: + service: + name: spring-cloud-gateway + port: + number: 80 + - path: /api + pathType: Prefix + backend: + service: + name: spring-cloud-gateway + port: + number: 80 + - path: /ws/game + pathType: Prefix + backend: + service: + name: spring-cloud-gateway + port: + number: 80 + - path: / + pathType: Prefix + backend: + service: + name: frontend + port: + number: 80 + {{- else }} - path: / pathType: Prefix backend: @@ -27,4 +71,18 @@ spec: name: spring-cloud-gateway port: number: 80 + {{- end }} +{{- end }} +{{- if and .Values.previewStack.enabled .Values.previewStack.ingress.enabled $frontendEnabled }} +--- +apiVersion: traefik.io/v1alpha1 +kind: Middleware +metadata: + name: firemud-preview-auth-path-rewrite + labels: +{{ include "firemud.commonLabels" . | indent 4 }} +spec: + replacePathRegex: + regex: ^/auth(/.*)?$ + replacement: /api/account/auth$1 {{- end }} diff --git a/k8s/helm/firemud/values.yaml b/k8s/helm/firemud/values.yaml index 880ddb6e8b..f1e838a333 100644 --- a/k8s/helm/firemud/values.yaml +++ b/k8s/helm/firemud/values.yaml @@ -14,3 +14,17 @@ previewStack: clusterIssuer: firemud-ca-issuer # Hosted preview and dev-demo values must select their canonical trust environment explicitly. trustEnvironment: pr-preview + # Keep the static host and its public routes disabled until its image is + # published and the hosted preview values select that immutable release. + frontend: + enabled: false + image: + repository: "" + tag: "" + resources: + requests: + cpu: 10m + memory: 32Mi + limits: + cpu: 250m + memory: 128Mi diff --git a/services/account-service/src/main/resources/application-prod.yml b/services/account-service/src/main/resources/application-prod.yml index 4357cb661a..c0d416506c 100644 --- a/services/account-service/src/main/resources/application-prod.yml +++ b/services/account-service/src/main/resources/application-prod.yml @@ -54,7 +54,7 @@ firemud: path-pattern: /auth/complete-password-reset - method: POST path-pattern: /auth/request-email-verification - - method: GET + - method: POST path-pattern: /auth/verify-email - method: POST path-pattern: /auth/recover-username @@ -99,8 +99,8 @@ firemud: connect-token-expiration-ms: ${FIREMUD_ACCOUNT_TOKENS_CONNECT_TOKEN_EXPIRATION_MS:30000} mail: from: ${SMTP_FROM:no-reply@firemud.com} - verification-url: ${FIREMUD_MAIL_VERIFICATION_URL:https://firemud.com/auth/verify-email?token=%s} - reset-url: ${FIREMUD_MAIL_RESET_URL:https://firemud.com/reset-password?token=%s} + verification-url: ${FIREMUD_MAIL_VERIFICATION_URL:https://firemud.com/verify-email#token=%s} + reset-url: ${FIREMUD_MAIL_RESET_URL:https://firemud.com/reset-password#token=%s} management: health: diff --git a/services/account-service/src/main/resources/application.yml b/services/account-service/src/main/resources/application.yml index 2ddcadc3bf..c3317a7215 100644 --- a/services/account-service/src/main/resources/application.yml +++ b/services/account-service/src/main/resources/application.yml @@ -61,8 +61,8 @@ firemud: connect-token-expiration-ms: 30000 mail: from: no-reply@firemud.local - verification-url: http://localhost:8080/auth/verify-email?token=%s - reset-url: http://localhost:8080/reset-password?token=%s + verification-url: http://localhost:5173/verify-email#token=%s + reset-url: http://localhost:5173/reset-password#token=%s payment: stripe-api-key: test-key platform-fee-percent: 5 @@ -85,7 +85,7 @@ firemud: path-pattern: /auth/complete-password-reset - method: POST path-pattern: /auth/request-email-verification - - method: GET + - method: POST path-pattern: /auth/verify-email - method: POST path-pattern: /auth/recover-username diff --git a/services/account-service/src/main/resources/openapi.yaml b/services/account-service/src/main/resources/openapi.yaml index 8411c88db4..0bcd50ad58 100644 --- a/services/account-service/src/main/resources/openapi.yaml +++ b/services/account-service/src/main/resources/openapi.yaml @@ -264,6 +264,8 @@ components: type: string newPassword: type: string + minLength: 6 + maxLength: 100 required: [token, newPassword] UsernameRecoveryRequest: type: object @@ -550,13 +552,11 @@ paths: summary: Verify email token operationId: verifyEmail description: >- - Target state is a public token-verification endpoint. In the current - deployment the POST route is not in the public-route allowlist and - therefore requires bearer authentication; the allowlisted GET route - has no controller mapping. Do not treat this operation as publicly - reachable until the HTTP configuration and link handoff converge. - security: - - bearerAuth: [] + Public token-verification completion. Emailed links land on the + first-party read-only /verify-email page; only an explicit POST to + this API consumes the token. Complete site-router and browser proof + remains required before the email journey is declared reachable. + security: [] requestBody: required: true content: diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/EmailLinkConfigurationTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/EmailLinkConfigurationTest.java new file mode 100644 index 0000000000..b38790fbf5 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/EmailLinkConfigurationTest.java @@ -0,0 +1,113 @@ +package net.firedevops.firemud.accountservice.config; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; +import net.firedevops.firemud.common.security.HttpAuthProperties; +import net.firedevops.firemud.common.security.HttpJwtAuthInterceptor; +import net.firedevops.firemud.common.security.JwtUtil; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.springframework.beans.factory.config.YamlPropertiesFactoryBean; +import org.springframework.core.io.FileSystemResource; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; + +class EmailLinkConfigurationTest { + @Test + void localAndProductionLinksUseReadOnlyFrontendLandingsAndPublicPostCompletion() { + assertProfile( + "application.yml", + "http://localhost:5173/verify-email#token=%s", + "http://localhost:5173/reset-password#token=%s"); + assertProfile( + "application-prod.yml", + "${FIREMUD_MAIL_VERIFICATION_URL:https://firemud.com/verify-email#token=%s}", + "${FIREMUD_MAIL_RESET_URL:https://firemud.com/reset-password#token=%s}"); + } + + @Test + void configuredPublicPostIsAcceptedWithoutBearerButGetAndNeighborsAreDenied() throws Exception { + for (String resource : List.of("application.yml", "application-prod.yml")) { + Properties properties = load(resource); + HttpAuthProperties auth = new HttpAuthProperties(); + List routes = new ArrayList<>(); + for (int index = 0; index < 32; index++) { + String prefix = "firemud.auth.http.public-routes[" + index + "]"; + String method = properties.getProperty(prefix + ".method"); + String path = properties.getProperty(prefix + ".path-pattern"); + if (method == null || path == null) { + continue; + } + HttpAuthProperties.HttpPublicRoute route = new HttpAuthProperties.HttpPublicRoute(); + route.setMethod(method); + route.setPathPattern(path); + routes.add(route); + } + auth.setPublicRoutes(routes); + HttpJwtAuthInterceptor interceptor = + new HttpJwtAuthInterceptor(Mockito.mock(JwtUtil.class), auth); + + assertThat( + interceptor.preHandle( + request("POST", "/auth/verify-email"), new MockHttpServletResponse(), null)) + .as(resource) + .isTrue(); + assertThat( + interceptor.preHandle( + request("POST", "/auth/complete-password-reset"), + new MockHttpServletResponse(), + null)) + .as(resource) + .isTrue(); + for (MockHttpServletRequest denied : + List.of( + request("GET", "/auth/verify-email"), + request("GET", "/auth/reset-password"), + request("POST", "/auth/verify-email/internal"))) { + MockHttpServletResponse response = new MockHttpServletResponse(); + assertThat(interceptor.preHandle(denied, response, null)).as(resource).isFalse(); + assertThat(response.getStatus()).isEqualTo(401); + } + } + } + + private static MockHttpServletRequest request(String method, String path) { + return new MockHttpServletRequest(method, path); + } + + private static void assertProfile(String resource, String verificationUrl, String resetUrl) { + Properties properties = load(resource); + assertThat(properties.getProperty("firemud.mail.verification-url")).isEqualTo(verificationUrl); + assertThat(properties.getProperty("firemud.mail.reset-url")).isEqualTo(resetUrl); + + boolean publicVerificationPost = false; + boolean publicVerificationGet = false; + for (int index = 0; index < 32; index++) { + String prefix = "firemud.auth.http.public-routes[" + index + "]"; + if (!"/auth/verify-email".equals(properties.getProperty(prefix + ".path-pattern"))) { + continue; + } + publicVerificationPost |= "POST".equals(properties.getProperty(prefix + ".method")); + publicVerificationGet |= "GET".equals(properties.getProperty(prefix + ".method")); + } + assertThat(publicVerificationPost).isTrue(); + assertThat(publicVerificationGet).isFalse(); + } + + private static Properties load(String resource) { + YamlPropertiesFactoryBean loader = new YamlPropertiesFactoryBean(); + Path moduleLocal = Path.of("src", "main", "resources", resource); + Path repositoryLocal = + Path.of("services", "account-service", "src", "main", "resources", resource); + loader.setResources( + new FileSystemResource(Files.exists(moduleLocal) ? moduleLocal : repositoryLocal)); + Properties properties = loader.getObject(); + assertThat(properties).isNotNull(); + return properties; + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java index 316a813e0e..2969ddafd3 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java @@ -353,4 +353,16 @@ void verifyEmailReturnsSuccess() throws Exception { .andExpect(status().isOk()) .andExpect(jsonPath("$.status").value("SUCCESS")); } + + @Test + void emailedGetRequestsNeverConsumeTokens() throws Exception { + mockMvc + .perform(get("/auth/verify-email").param("token", "tok")) + .andExpect(status().is4xxClientError()); + mockMvc + .perform(get("/auth/reset-password").param("token", "tok")) + .andExpect(status().is4xxClientError()); + + verifyNoInteractions(accountService); + } } diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/CanonicalGatewayRoutesConfiguration.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/CanonicalGatewayRoutesConfiguration.java index 1eb72e99dd..4b35bf4759 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/CanonicalGatewayRoutesConfiguration.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/CanonicalGatewayRoutesConfiguration.java @@ -84,11 +84,89 @@ public GatewayProperties canonicalGatewayProperties(Environment environment) { 2, "GET"), route( - "account-auth", + "account-auth-login", environment.getProperty( "FIREMUD_GATEWAY_ROUTE_ACCOUNT_URI", "http://account-service:8080"), - "/api/account/auth/**", - 2), + "/api/account/auth/login", + 2, + "POST"), + route( + "account-auth-player-bootstrap", + environment.getProperty( + "FIREMUD_GATEWAY_ROUTE_ACCOUNT_URI", "http://account-service:8080"), + "/api/account/auth/player-bootstrap", + 2, + "POST"), + route( + "account-auth-bootstrap-worlds", + environment.getProperty( + "FIREMUD_GATEWAY_ROUTE_ACCOUNT_URI", "http://account-service:8080"), + "/api/account/auth/bootstrap/worlds", + 2, + "GET"), + route( + "account-auth-bootstrap-realms", + environment.getProperty( + "FIREMUD_GATEWAY_ROUTE_ACCOUNT_URI", "http://account-service:8080"), + "/api/account/auth/bootstrap/worlds/{worldSlug}/realms", + 2, + "GET"), + route( + "account-auth-bootstrap-characters", + environment.getProperty( + "FIREMUD_GATEWAY_ROUTE_ACCOUNT_URI", "http://account-service:8080"), + "/api/account/auth/bootstrap/worlds/{worldSlug}/realms/{realmSlug}/characters", + 2, + "GET"), + route( + "account-auth-bootstrap-join", + environment.getProperty( + "FIREMUD_GATEWAY_ROUTE_ACCOUNT_URI", "http://account-service:8080"), + "/api/account/auth/bootstrap/join", + 2, + "POST"), + route( + "account-auth-connect-token", + environment.getProperty( + "FIREMUD_GATEWAY_ROUTE_ACCOUNT_URI", "http://account-service:8080"), + "/api/account/auth/connect-token", + 2, + "POST"), + route( + "account-auth-request-password-reset", + environment.getProperty( + "FIREMUD_GATEWAY_ROUTE_ACCOUNT_URI", "http://account-service:8080"), + "/api/account/auth/request-password-reset", + 2, + "POST"), + route( + "account-auth-complete-password-reset", + environment.getProperty( + "FIREMUD_GATEWAY_ROUTE_ACCOUNT_URI", "http://account-service:8080"), + "/api/account/auth/complete-password-reset", + 2, + "POST"), + route( + "account-auth-request-email-verification", + environment.getProperty( + "FIREMUD_GATEWAY_ROUTE_ACCOUNT_URI", "http://account-service:8080"), + "/api/account/auth/request-email-verification", + 2, + "POST"), + route( + "account-auth-verify-email", + environment.getProperty( + "FIREMUD_GATEWAY_ROUTE_ACCOUNT_URI", "http://account-service:8080"), + "/api/account/auth/verify-email", + 2, + "POST"), + route( + "account-auth-recover-username", + environment.getProperty( + "FIREMUD_GATEWAY_ROUTE_ACCOUNT_URI", "http://account-service:8080"), + "/api/account/auth/recover-username", + 2, + "POST"), route( "account-accounts", environment.getProperty( diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/GatewayRateLimiterConfig.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/GatewayRateLimiterConfig.java index 9f787ce081..fd41146136 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/GatewayRateLimiterConfig.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/GatewayRateLimiterConfig.java @@ -4,14 +4,12 @@ import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpHeaders; import org.springframework.web.server.ServerWebExchange; import reactor.core.publisher.Mono; /** Canonical low-cardinality key resolution for gateway-wide request rate limiting. */ @Configuration public class GatewayRateLimiterConfig { - private static final String X_FORWARDED_FOR = "X-Forwarded-For"; private static final String UNKNOWN_CLIENT_KEY = "unknown-client"; @Bean @@ -25,28 +23,10 @@ private String resolveClientKey(ServerWebExchange exchange) { return clientIp.trim(); } - clientIp = firstForwardedFor(exchange.getRequest().getHeaders()); - if (clientIp != null) { - return clientIp; - } - InetSocketAddress remoteAddress = exchange.getRequest().getRemoteAddress(); if (remoteAddress != null && remoteAddress.getAddress() != null) { return remoteAddress.getAddress().getHostAddress(); } return UNKNOWN_CLIENT_KEY; } - - private String firstForwardedFor(HttpHeaders headers) { - String xff = headers.getFirst(X_FORWARDED_FOR); - if (xff == null || xff.isBlank()) { - return null; - } - String[] segments = xff.split(","); - if (segments.length == 0) { - return null; - } - String candidate = segments[0].trim(); - return candidate.isEmpty() ? null : candidate; - } } diff --git a/services/spring-cloud-gateway/src/main/resources/application.yml b/services/spring-cloud-gateway/src/main/resources/application.yml index 42aaef600d..8fa3fc5fcc 100644 --- a/services/spring-cloud-gateway/src/main/resources/application.yml +++ b/services/spring-cloud-gateway/src/main/resources/application.yml @@ -31,7 +31,9 @@ spring: retries: 3 statuses: BAD_GATEWAY,GATEWAY_TIMEOUT series: SERVER_ERROR - methods: GET,POST + # One-use Account recovery and verification POSTs have no replay receipt. + # An ambiguous upstream response must not trigger an automatic second claim. + methods: GET backoff: firstBackoff: 50ms maxBackoff: 500ms diff --git a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationProdTest.java b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationProdTest.java index 989f145e1b..ef5a960e9f 100644 --- a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationProdTest.java +++ b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationProdTest.java @@ -51,7 +51,18 @@ class GatewayRoutesConfigurationProdTest { "admin-tick-remediation", "design-ping", "design-templates-read", - "account-auth", + "account-auth-login", + "account-auth-player-bootstrap", + "account-auth-bootstrap-worlds", + "account-auth-bootstrap-realms", + "account-auth-bootstrap-characters", + "account-auth-bootstrap-join", + "account-auth-connect-token", + "account-auth-request-password-reset", + "account-auth-complete-password-reset", + "account-auth-request-email-verification", + "account-auth-verify-email", + "account-auth-recover-username", "account-accounts", "account-profiles", "account-ping", @@ -131,13 +142,44 @@ void restEdgeRoutesStripExternalServicePrefixBeforeForwarding() { assertNoConfiguredPath(gatewayProperties, "/api/design/assets"); assertNoRouteWithPathAndMethod(gatewayProperties, "/api/design/templates", "POST"); assertNoRouteWithPathAndMethod(gatewayProperties, "/api/design/assets", "POST"); - assertHasPath(gatewayProperties, "account-auth", "/api/account/auth/**"); + assertAccountAuthRoutesAreExactAndMethodBound(gatewayProperties); assertHasStripPrefixTwo(gatewayProperties, "admin-ping"); assertHasStripPrefixTwo(gatewayProperties, "admin-admission-pointers"); assertHasStripPrefixTwo(gatewayProperties, "admin-remote-followups"); assertHasStripPrefixTwo(gatewayProperties, "admin-tick-remediation"); assertHasStripPrefixTwo(gatewayProperties, "design-ping"); assertHasStripPrefixTwo(gatewayProperties, "design-templates-read"); - assertHasStripPrefixTwo(gatewayProperties, "account-auth"); + assertHasStripPrefixTwo(gatewayProperties, "account-auth-verify-email"); + } + + private static void assertAccountAuthRoutesAreExactAndMethodBound( + GatewayProperties gatewayProperties) { + assertHasPath(gatewayProperties, "account-auth-verify-email", "/api/account/auth/verify-email"); + assertHasMethod(gatewayProperties, "account-auth-verify-email", "POST"); + assertHasPath( + gatewayProperties, + "account-auth-complete-password-reset", + "/api/account/auth/complete-password-reset"); + assertHasMethod(gatewayProperties, "account-auth-complete-password-reset", "POST"); + assertHasMethod(gatewayProperties, "account-auth-login", "POST"); + assertHasMethod(gatewayProperties, "account-auth-player-bootstrap", "POST"); + assertHasMethod(gatewayProperties, "account-auth-bootstrap-worlds", "GET"); + assertHasMethod(gatewayProperties, "account-auth-bootstrap-realms", "GET"); + assertHasMethod(gatewayProperties, "account-auth-bootstrap-characters", "GET"); + assertHasMethod(gatewayProperties, "account-auth-bootstrap-join", "POST"); + assertHasMethod(gatewayProperties, "account-auth-connect-token", "POST"); + assertHasMethod(gatewayProperties, "account-auth-request-password-reset", "POST"); + assertHasMethod(gatewayProperties, "account-auth-request-email-verification", "POST"); + assertHasMethod(gatewayProperties, "account-auth-recover-username", "POST"); + assertNoConfiguredPath(gatewayProperties, "/api/account/auth/**"); + assertNoRouteWithPathAndMethod(gatewayProperties, "/api/account/auth/verify-email", "GET"); + assertNoRouteWithPathAndMethod( + gatewayProperties, "/api/account/auth/complete-password-reset", "GET"); + assertNoRouteWithPathAndMethod( + gatewayProperties, "/api/account/auth/verify-email/extra", "POST"); + assertNoRouteWithPathAndMethod(gatewayProperties, "/api/account/auth/internal/runtime", "POST"); + assertNoConfiguredPathStartsWith(gatewayProperties, "/api/account/internal/"); + assertNoConfiguredPathStartsWith(gatewayProperties, "/verify-email"); + assertNoConfiguredPathStartsWith(gatewayProperties, "/reset-password"); } } diff --git a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationTest.java b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationTest.java index 519c031387..24e0f07084 100644 --- a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationTest.java +++ b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationTest.java @@ -10,7 +10,10 @@ import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.route; import static org.assertj.core.api.Assertions.assertThat; +import java.io.IOException; import java.net.URI; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.Set; import java.util.stream.Collectors; import net.firedevops.firemud.springcloudgateway.SpringCloudGatewayApplication; @@ -50,7 +53,18 @@ class GatewayRoutesConfigurationTest { "admin-tick-remediation", "design-ping", "design-templates-read", - "account-auth", + "account-auth-login", + "account-auth-player-bootstrap", + "account-auth-bootstrap-worlds", + "account-auth-bootstrap-realms", + "account-auth-bootstrap-characters", + "account-auth-bootstrap-join", + "account-auth-connect-token", + "account-auth-request-password-reset", + "account-auth-complete-password-reset", + "account-auth-request-email-verification", + "account-auth-verify-email", + "account-auth-recover-username", "account-accounts", "account-profiles", "account-ping", @@ -79,6 +93,18 @@ void publicRouteAllowlistExposesOnlyCuratedEdgeRoutes() { .containsExactlyInAnyOrderElementsOf(ROUTE_IDS); } + @Test + void genericGatewayRetryNeverReplaysOneUseAccountPosts() throws IOException { + // The test classpath has its own application.yml, so inspect the shipped + // configuration rather than asserting the test profile's default filters. + Path source = Path.of("src/main/resources/application.yml"); + String config = Files.readString(source); + assertThat(config).containsPattern("(?s)- name: Retry\\s+args:.*?methods: GET(?:\\s|$)"); + assertThat(config).doesNotContain("methods: GET,POST"); + assertHasMethod(gatewayProperties, "account-auth-verify-email", "POST"); + assertHasMethod(gatewayProperties, "account-auth-complete-password-reset", "POST"); + } + @Test void socialChatAndFriendsAreEdgeGated() { assertSocialChatAndFriendsAreEdgeGated(gatewayProperties); @@ -144,13 +170,34 @@ void restEdgeRoutesStripExternalServicePrefixBeforeForwarding() { assertNoRouteWithPathAndMethod(gatewayProperties, "/api/design/templates", "POST"); assertNoRouteWithPathAndMethod(gatewayProperties, "/api/design/assets", "POST"); - assertHasPath(gatewayProperties, "account-auth", "/api/account/auth/**"); + assertHasPath(gatewayProperties, "account-auth-verify-email", "/api/account/auth/verify-email"); + assertHasMethod(gatewayProperties, "account-auth-verify-email", "POST"); + assertHasPath( + gatewayProperties, + "account-auth-complete-password-reset", + "/api/account/auth/complete-password-reset"); + assertHasMethod(gatewayProperties, "account-auth-complete-password-reset", "POST"); + assertHasMethod(gatewayProperties, "account-auth-bootstrap-worlds", "GET"); + assertHasMethod(gatewayProperties, "account-auth-bootstrap-realms", "GET"); + assertHasMethod(gatewayProperties, "account-auth-bootstrap-characters", "GET"); + assertHasMethod(gatewayProperties, "account-auth-request-email-verification", "POST"); + assertHasMethod(gatewayProperties, "account-auth-request-password-reset", "POST"); + assertNoConfiguredPath(gatewayProperties, "/api/account/auth/**"); + assertNoRouteWithPathAndMethod(gatewayProperties, "/api/account/auth/verify-email", "GET"); + assertNoRouteWithPathAndMethod( + gatewayProperties, "/api/account/auth/complete-password-reset", "GET"); + assertNoRouteWithPathAndMethod( + gatewayProperties, "/api/account/auth/verify-email/extra", "POST"); + assertNoRouteWithPathAndMethod(gatewayProperties, "/api/account/auth/internal/runtime", "POST"); + assertNoConfiguredPathStartsWith(gatewayProperties, "/api/account/internal/"); + assertNoConfiguredPathStartsWith(gatewayProperties, "/verify-email"); + assertNoConfiguredPathStartsWith(gatewayProperties, "/reset-password"); assertHasPath(gatewayProperties, "account-accounts", "/api/account/accounts/**"); assertHasPath(gatewayProperties, "account-profiles", "/api/account/profiles/**"); assertHasPath(gatewayProperties, "account-ping", "/api/account/ping"); assertHasPath(gatewayProperties, "account-jwks", "/api/account/.well-known/jwks.json"); - assertHasStripPrefixTwo(gatewayProperties, "account-auth"); + assertHasStripPrefixTwo(gatewayProperties, "account-auth-verify-email"); assertHasStripPrefixTwo(gatewayProperties, "account-accounts"); assertHasStripPrefixTwo(gatewayProperties, "account-profiles"); assertHasStripPrefixTwo(gatewayProperties, "account-ping"); diff --git a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationTestProfileTest.java b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationTestProfileTest.java index e6dec07fda..0a1690adfd 100644 --- a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationTestProfileTest.java +++ b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationTestProfileTest.java @@ -50,7 +50,18 @@ class GatewayRoutesConfigurationTestProfileTest { "admin-tick-remediation", "design-ping", "design-templates-read", - "account-auth", + "account-auth-login", + "account-auth-player-bootstrap", + "account-auth-bootstrap-worlds", + "account-auth-bootstrap-realms", + "account-auth-bootstrap-characters", + "account-auth-bootstrap-join", + "account-auth-connect-token", + "account-auth-request-password-reset", + "account-auth-complete-password-reset", + "account-auth-request-email-verification", + "account-auth-verify-email", + "account-auth-recover-username", "account-accounts", "account-profiles", "account-ping", @@ -125,7 +136,14 @@ void testProfileRestRoutesStripExternalServicePrefix() { assertHasPath(gatewayProperties, "session-ping", "/api/session/ping"); - assertHasPath(gatewayProperties, "account-auth", "/api/account/auth/**"); + assertHasPath(gatewayProperties, "account-auth-verify-email", "/api/account/auth/verify-email"); + assertHasMethod(gatewayProperties, "account-auth-verify-email", "POST"); + assertHasPath( + gatewayProperties, + "account-auth-complete-password-reset", + "/api/account/auth/complete-password-reset"); + assertHasMethod(gatewayProperties, "account-auth-complete-password-reset", "POST"); + assertNoConfiguredPath(gatewayProperties, "/api/account/auth/**"); assertHasPath(gatewayProperties, "account-accounts", "/api/account/accounts/**"); assertHasPath(gatewayProperties, "account-profiles", "/api/account/profiles/**"); assertHasPath(gatewayProperties, "account-ping", "/api/account/ping"); @@ -145,7 +163,8 @@ void testProfileRestRoutesStripExternalServicePrefix() { assertHasStripPrefix(gatewayProperties, "admin-tick-remediation", "2"); assertHasStripPrefix(gatewayProperties, "design-ping", "2"); assertHasStripPrefix(gatewayProperties, "design-templates-read", "2"); - assertHasStripPrefix(gatewayProperties, "account-auth", "2"); + assertHasStripPrefix(gatewayProperties, "account-auth-verify-email", "2"); + assertHasStripPrefix(gatewayProperties, "account-auth-complete-password-reset", "2"); assertHasStripPrefix(gatewayProperties, "account-accounts", "2"); assertHasStripPrefix(gatewayProperties, "account-profiles", "2"); assertHasStripPrefix(gatewayProperties, "account-ping", "2"); diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/GatewayRateLimiterConfigTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/GatewayRateLimiterConfigTest.java index 775ef74caf..89f137e132 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/GatewayRateLimiterConfigTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/GatewayRateLimiterConfigTest.java @@ -8,8 +8,6 @@ import org.springframework.mock.web.server.MockServerWebExchange; class GatewayRateLimiterConfigTest { - private static final String X_FORWARDED_FOR = "X-Forwarded-For"; - @Test void prefersGatewayOwnedClientIpHeader() { KeyResolver resolver = new GatewayRateLimiterConfig().gatewayClientIpKeyResolver(); @@ -17,7 +15,7 @@ void prefersGatewayOwnedClientIpHeader() { MockServerWebExchange.from( MockServerHttpRequest.get("/api/account/auth/player-bootstrap") .header("X-Client-IP", "198.51.100.10") - .header(X_FORWARDED_FOR, "203.0.113.99") + .header("X-Forwarded-For", "203.0.113.99") .build()); String key = resolver.resolve(exchange).block(); @@ -26,16 +24,17 @@ void prefersGatewayOwnedClientIpHeader() { } @Test - void fallsBackToForwardedForWhenGatewayOwnedHeaderMissing() { + void ignoresUncanonicalizedForwardedForWhenGatewayOwnedHeaderMissing() { KeyResolver resolver = new GatewayRateLimiterConfig().gatewayClientIpKeyResolver(); MockServerWebExchange exchange = MockServerWebExchange.from( - MockServerHttpRequest.get("/api/account/auth/player-bootstrap") - .header(X_FORWARDED_FOR, "203.0.113.77, 10.0.0.1") + MockServerHttpRequest.get("/api/account/auth/verify-email") + .header("X-Forwarded-For", "203.0.113.77, 10.0.0.1") + .remoteAddress(new java.net.InetSocketAddress("192.0.2.44", 0)) .build()); String key = resolver.resolve(exchange).block(); - assertThat(key).isEqualTo("203.0.113.77"); + assertThat(key).isEqualTo("192.0.2.44"); } } diff --git a/web-client/.dockerignore b/web-client/.dockerignore new file mode 100644 index 0000000000..7bfeeef467 --- /dev/null +++ b/web-client/.dockerignore @@ -0,0 +1,21 @@ +# Dependencies and generated output are installed or produced inside the image. +node_modules +dist +dist-ssr + +# Local-only configuration, logs, and editor state. +logs +*.log +*.local +.env +.env.* +.vscode +.idea +.DS_Store + +# Package-manager debug output. +npm-debug.log* +yarn-debug.log* +yarn-error.log* +pnpm-debug.log* +lerna-debug.log* diff --git a/web-client/Dockerfile b/web-client/Dockerfile new file mode 100644 index 0000000000..c3b3c5f88a --- /dev/null +++ b/web-client/Dockerfile @@ -0,0 +1,19 @@ +# Build with web-client as the Docker context because the repository-root +# .dockerignore deliberately excludes frontend source from service images. +FROM node:24.21.0-alpine@sha256:ebfe2f90462722a7a4de65e91990e97fe0d401c70e0e762c5b53302f905ec1c1 AS build + +WORKDIR /app +COPY package.json package-lock.json ./ +RUN npm ci +COPY . . +# Type checking runs in the frontend CI lane; the Docker context intentionally +# stays self-contained and does not include the shared TypeScript config. +RUN npm exec -- vite build + +FROM ghcr.io/nginx/nginx-unprivileged:1.30.5-alpine3.24@sha256:daa17b944bac2b578e962da4c61ad72a59233b3c63abea17113acaf4e6b9aea4 + +COPY nginx.conf /etc/nginx/conf.d/default.conf +COPY --from=build /app/dist/ /usr/share/nginx/html/ + +USER 101 +EXPOSE 8080 diff --git a/web-client/README.md b/web-client/README.md index 53f3b5b7bc..752524fa85 100644 --- a/web-client/README.md +++ b/web-client/README.md @@ -22,7 +22,9 @@ See: - [Frontend Architecture](../design/architecture/system-architecture-frontend.md) - [Player Experience, Commands, and Communication implementation tracker](../design/project-management/implementation-tracking/player-experience-commands-and-communication.md) -The Vite production build writes compiled assets to `dist/frontend-assets/`, so generated compiled JavaScript/CSS references use `/frontend-assets/**`. The prefix is reserved for first-party compiled files, does not SPA-fallback, and is not a Gateway route. The static host/Ingress, origin separation, and full browser proof remain target-state work under [ADR 0144](../design/architecture/decisions/adr-0144-stateless-first-party-frontend-application-boundary.md). +The Vite production build writes compiled assets to `dist/frontend-assets/`, so generated compiled JavaScript/CSS references use `/frontend-assets/**`. The prefix is reserved for first-party compiled files, does not SPA-fallback, and is not a Gateway route. `Dockerfile` and `nginx.conf` prepare an unprivileged read-only static host, and the preview Helm chart can opt into a separate frontend Deployment/Service and public path split. The hosted values leave it disabled: image publication, origin/mail wiring, running-host proof, independent release/rollback, and the full browser journey remain open under [ADR 0144](../design/architecture/decisions/adr-0144-stateless-first-party-frontend-application-boundary.md). + +The `/verify-email` and `/reset-password` browser routes are non-mutating email-link landings. They accept the link token only in a URL fragment, remove it from the visible address, and require an explicit submit before POSTing to Account through Gateway. This source-level flow does not make mailed links reachable in a deployed environment until the opt-in static host and route split are deployed with a published image, mail URLs target that HTTPS origin, and live browser-to-Gateway-to-Account proof passes. The existing Account token-consumption transaction remains the mutation authority. ## Local Development @@ -36,6 +38,7 @@ Common commands: ```bash npm run dev +npm run test npm run build npm run preview npm run lint @@ -43,6 +46,8 @@ npm run format -- -c npm run accessibility ``` +The development server proxies `/api/**` to a locally running Gateway on port `8080`; its own landing pages are served on port `5173`. The mail URL defaults for local development point to that browser origin. A production deployment must configure the published static-site origin and preserve the fragment token without routing the browser GET to Account. + The accessibility audit depends on Google Chrome. See [Developer Setup](../DEVELOPER_SETUP.md#frontend-lint--accessibility) for the expected local toolchain and installation notes. ## Notes diff --git a/web-client/index.html b/web-client/index.html index 04e161d1d3..53d0537182 100644 --- a/web-client/index.html +++ b/web-client/index.html @@ -2,6 +2,7 @@ + FireMUD diff --git a/web-client/nginx.conf b/web-client/nginx.conf new file mode 100644 index 0000000000..0d62b731ed --- /dev/null +++ b/web-client/nginx.conf @@ -0,0 +1,93 @@ +log_format firemud_safe '$remote_addr [$time_local] "$request_method $uri $server_protocol" $status $body_bytes_sent "$http_user_agent"'; + +server { + listen 8080 default_server; + server_name _; + + root /usr/share/nginx/html; + index index.html; + server_tokens off; + + include /etc/nginx/mime.types; + default_type application/octet-stream; + + access_log /dev/stdout firemud_safe; + + gzip on; + gzip_vary on; + gzip_min_length 1024; + gzip_types text/plain text/css application/json application/javascript application/xml image/svg+xml; + + add_header Content-Security-Policy "default-src 'self'; base-uri 'self'; connect-src 'self' wss:; font-src 'self' data:; form-action 'self'; frame-ancestors 'none'; img-src 'self' data: blob: https:; object-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; upgrade-insecure-requests" always; + add_header Referrer-Policy "no-referrer" always; + add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; + add_header X-Content-Type-Options "nosniff" always; + add_header X-Frame-Options "DENY" always; + add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always; + + location = /healthz { + access_log off; + default_type text/plain; + return 200 "ok\n"; + } + + location = /frontend-assets { + return 404; + } + + location ^~ /frontend-assets/ { + if ($request_method !~ ^(GET|HEAD)$) { + return 405; + } + + try_files $uri =404; + add_header Cache-Control "public, max-age=31536000, immutable"; + add_header Content-Security-Policy "default-src 'self'; base-uri 'self'; connect-src 'self' wss:; font-src 'self' data:; form-action 'self'; frame-ancestors 'none'; img-src 'self' data: blob: https:; object-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; upgrade-insecure-requests" always; + add_header Referrer-Policy "no-referrer" always; + add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; + add_header X-Content-Type-Options "nosniff" always; + add_header X-Frame-Options "DENY" always; + add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always; + } + + location = /assets { + return 404; + } + + location ^~ /assets/ { + return 404; + } + + location = /auth { + return 404; + } + + location ^~ /auth/ { + return 404; + } + + location = /api { + return 404; + } + + location ^~ /api/ { + return 404; + } + + location = /ws/game { + return 404; + } + + location ^~ /ws/game/ { + return 404; + } + + location / { + if ($request_method !~ ^(GET|HEAD)$) { + return 405; + } + + expires -1; + try_files $uri $uri/ /index.html; + } +} diff --git a/web-client/package.json b/web-client/package.json index d94ca5c183..5c416b7b9c 100644 --- a/web-client/package.json +++ b/web-client/package.json @@ -6,10 +6,11 @@ "scripts": { "dev": "vite", "build": "tsc -b && vite build", + "test": "node --experimental-strip-types --test tests/*.test.mjs", "lint": "node ./node_modules/eslint/bin/eslint.js .", "preview": "vite preview", - "format": "prettier --check \"src/**/*.{ts,tsx}\"", - "format:fix": "prettier --write \"src/**/*.{ts,tsx}\"", + "format": "prettier --check \"src/**/*.{ts,tsx}\" \"tests/**/*.mjs\"", + "format:fix": "prettier --write \"src/**/*.{ts,tsx}\" \"tests/**/*.mjs\"", "accessibility": "npm run build && npx serve dist -l 5000 & npx wait-on http://localhost:5000/index.html && npx axe http://localhost:5000/index.html --chrome-options=\"--no-sandbox\" --exit" }, "dependencies": { diff --git a/web-client/src/App.css b/web-client/src/App.css index f4b43e332a..bda7272355 100644 --- a/web-client/src/App.css +++ b/web-client/src/App.css @@ -41,6 +41,78 @@ color: #333; } +.email-link-page { + box-sizing: border-box; + display: grid; + min-height: 100vh; + place-items: center; + padding: 1.5rem; + text-align: left; +} + +.email-link-panel { + width: min(100%, 32rem); + padding: clamp(1.5rem, 5vw, 2.5rem); + border: 1px solid #d7dce2; + border-radius: 0.75rem; + background: #fff; + color: #18212b; + box-shadow: 0 1rem 3rem rgb(20 32 44 / 10%); +} + +.email-link-panel h1 { + margin-top: 0; + font-size: clamp(1.75rem, 5vw, 2.25rem); + line-height: 1.2; +} + +.email-link-panel p { + line-height: 1.6; +} + +.email-link-panel form { + display: grid; + gap: 1rem; + margin-top: 1.5rem; +} + +.email-link-field { + display: grid; + gap: 0.5rem; + font-weight: 600; +} + +.email-link-field input { + box-sizing: border-box; + width: 100%; + min-height: 2.75rem; + padding: 0.65rem 0.75rem; + border: 1px solid #778391; + border-radius: 0.35rem; + color: #18212b; + font: inherit; +} + +.email-link-panel button { + min-height: 2.75rem; + border: 0; + border-radius: 0.35rem; + background: #184f80; + color: #fff; + font: inherit; + font-weight: 650; +} + +.email-link-panel button:disabled { + cursor: wait; + opacity: 0.7; +} + +.email-link-panel :focus-visible { + outline: 3px solid #e59a22; + outline-offset: 3px; +} + @media (prefers-color-scheme: dark) { .read-the-docs { color: #ccc; diff --git a/web-client/src/App.tsx b/web-client/src/App.tsx index 1941b252ea..7ca0383aa3 100644 --- a/web-client/src/App.tsx +++ b/web-client/src/App.tsx @@ -4,9 +4,11 @@ import GameEditor from './GameEditor'; import ScriptEditor from './ScriptEditor'; import reactLogo from './assets/react.svg'; import viteLogo from '/vite.svg'; +import EmailLinkLanding from './EmailLinkLanding'; +import { emailLinkLanding } from './emailLinkLanding'; import './App.css'; -function App() { +function DemoApp() { const [count, setCount] = useState(0); const [mode, setMode] = useState<'demo' | 'game' | 'script'>('demo'); @@ -64,4 +66,12 @@ function App() { ); } +function App() { + return emailLinkLanding ? ( + + ) : ( + + ); +} + export default App; diff --git a/web-client/src/EmailLinkLanding.tsx b/web-client/src/EmailLinkLanding.tsx new file mode 100644 index 0000000000..f572a7baeb --- /dev/null +++ b/web-client/src/EmailLinkLanding.tsx @@ -0,0 +1,114 @@ +import { useEffect, useState, type FormEvent } from 'react'; +import { + completeEmailLink, + emailLinkFailureMessage, + EmailLinkCompletionError, + type EmailLinkLandingRoute, +} from './emailLinkLanding'; + +interface EmailLinkLandingProps { + route: Exclude; +} + +function installNoReferrerPolicy(): void { + let policy = document.head.querySelector( + 'meta[name="referrer"]' + ); + if (!policy) { + policy = document.createElement('meta'); + policy.name = 'referrer'; + document.head.append(policy); + } + policy.content = 'no-referrer'; +} + +export default function EmailLinkLanding({ route }: EmailLinkLandingProps) { + const [password, setPassword] = useState(''); + const [submitting, setSubmitting] = useState(false); + const [complete, setComplete] = useState(false); + const [failure, setFailure] = useState(null); + + useEffect(() => { + installNoReferrerPolicy(); + }, []); + + const token = route.token; + const isVerification = route.kind === 'verify-email'; + const title = isVerification ? 'Verify your email' : 'Choose a new password'; + + async function submit(event: FormEvent) { + event.preventDefault(); + if (!token || submitting || complete) return; + + setSubmitting(true); + setFailure(null); + try { + await completeEmailLink(route, isVerification ? undefined : password); + setComplete(true); + setPassword(''); + } catch (error) { + setFailure( + error instanceof EmailLinkCompletionError + ? error + : new EmailLinkCompletionError('network', null) + ); + } finally { + setSubmitting(false); + } + } + + return ( +
+
+

{title}

+ {complete ? ( +

+ {isVerification + ? 'Your email address is verified.' + : 'Your password has been updated.'} +

+ ) : !token ? ( +

+ This link is invalid or has expired. Request a new email and try + again. +

+ ) : ( + <> +

+ {isVerification + ? 'Select the button below to verify this email address.' + : 'Enter a new password, then select the button to finish resetting it.'} +

+
+ {!isVerification && ( + + )} + +
+ {failure && ( +

{emailLinkFailureMessage(route.kind, failure)}

+ )} + + )} +
+
+ ); +} diff --git a/web-client/src/emailLinkLanding.ts b/web-client/src/emailLinkLanding.ts new file mode 100644 index 0000000000..f597b28f63 --- /dev/null +++ b/web-client/src/emailLinkLanding.ts @@ -0,0 +1,120 @@ +export type EmailLinkLandingRoute = + | { kind: 'verify-email'; token: string | null } + | { kind: 'reset-password'; token: string | null } + | null; + +export type EmailLinkCompletionFailureKind = + 'missing-token' | 'http' | 'network'; + +export class EmailLinkCompletionError extends Error { + readonly kind: EmailLinkCompletionFailureKind; + readonly status: number | null; + + constructor( + kind: EmailLinkCompletionFailureKind, + status: number | null, + message = 'The request could not be completed.' + ) { + super(message); + this.name = 'EmailLinkCompletionError'; + this.kind = kind; + this.status = status; + } +} + +function tokenFromFragment(hash: string): string | null { + const values = new URLSearchParams( + hash.startsWith('#') ? hash.slice(1) : hash + ); + const token = values.get('token'); + return token && token.trim().length > 0 ? token : null; +} + +export function captureEmailLinkLanding( + location: Location, + history: History +): EmailLinkLandingRoute { + const path = location.pathname.replace(/\/$/, '') || '/'; + if (path !== '/verify-email' && path !== '/reset-password') { + return null; + } + + const token = tokenFromFragment(location.hash); + // The token is consumed from memory only. Replacing the address also keeps + // it out of copied URLs and any subsequent same-page navigation metadata. + history.replaceState(null, '', location.pathname); + + return path === '/verify-email' + ? { kind: 'verify-email', token } + : { kind: 'reset-password', token }; +} + +export async function completeEmailLink( + route: Exclude, + newPassword?: string, + request: typeof fetch = fetch +): Promise { + if (!route.token) { + throw new EmailLinkCompletionError( + 'missing-token', + null, + 'The link is invalid.' + ); + } + const verification = route.kind === 'verify-email'; + try { + const response = await request( + verification + ? '/api/account/auth/verify-email' + : '/api/account/auth/complete-password-reset', + { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify( + verification + ? { token: route.token } + : { token: route.token, newPassword } + ), + } + ); + if (!response.ok) { + throw new EmailLinkCompletionError('http', response.status ?? null); + } + } catch (error) { + if (error instanceof EmailLinkCompletionError) { + throw error; + } + throw new EmailLinkCompletionError('network', null); + } +} + +export function emailLinkFailureMessage( + routeKind: Exclude['kind'], + failure: Pick +): string { + if (failure.kind === 'missing-token') { + return 'This link is invalid or has expired. Request a new email and try again.'; + } + + if (failure.kind === 'http' && failure.status === 400) { + return 'We could not accept this request. Check the submitted details and request a new email if needed.'; + } + + if ( + failure.kind === 'network' || + (failure.kind === 'http' && + (failure.status === 429 || (failure.status ?? 0) >= 500)) + ) { + return routeKind === 'reset-password' + ? 'We could not confirm whether the password reset completed. Try signing in with your intended new password before requesting another reset email.' + : 'We could not confirm whether email verification completed. Check your account after signing in before requesting another verification email.'; + } + + return 'We could not accept this request. Check the submitted details and try again.'; +} + +// Capture and scrub before React mounts or any route can issue a request. +export const emailLinkLanding = + typeof window === 'undefined' + ? null + : captureEmailLinkLanding(window.location, window.history); diff --git a/web-client/tests/email-link.test.mjs b/web-client/tests/email-link.test.mjs new file mode 100644 index 0000000000..7a3a6f95d7 --- /dev/null +++ b/web-client/tests/email-link.test.mjs @@ -0,0 +1,246 @@ +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import test from 'node:test'; +import { + captureEmailLinkLanding, + completeEmailLink, + emailLinkFailureMessage, + EmailLinkCompletionError, +} from '../src/emailLinkLanding.ts'; + +test('format check and fix cover the same source and test globs', async () => { + const { scripts } = JSON.parse( + await readFile(new URL('../package.json', import.meta.url), 'utf8') + ); + const getGlobs = (command) => + Array.from(command.matchAll(/"([^"]+)"/g), (match) => match[1]); + const expectedGlobs = ['src/**/*.{ts,tsx}', 'tests/**/*.mjs']; + + assert.deepEqual(getGlobs(scripts.format), expectedGlobs); + assert.deepEqual(getGlobs(scripts['format:fix']), expectedGlobs); +}); + +test('reset form and API schema retain the Account password bounds', async () => { + const form = await readFile( + new URL('../src/EmailLinkLanding.tsx', import.meta.url), + 'utf8' + ); + const dto = await readFile( + new URL( + '../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/CompletePasswordResetRequest.java', + import.meta.url + ), + 'utf8' + ); + const schema = await readFile( + new URL( + '../../services/account-service/src/main/resources/openapi.yaml', + import.meta.url + ), + 'utf8' + ); + assert.match(dto, /@Size\(min = 6, max = 100\) String newPassword/); + assert.match( + form, + /]*maxLength=\{100\}[^>]*minLength=\{6\}[^>]*name="newPassword"/ + ); + const resetSchema = schema + .split(' CompletePasswordResetRequest:')[1] + ?.split(' UsernameRecoveryRequest:')[0]; + assert.ok(resetSchema, 'CompletePasswordResetRequest must exist'); + assert.match( + resetSchema, + /newPassword:\s+type: string\s+minLength: 6\s+maxLength: 100/ + ); +}); + +test('verification GET captures a fragment token without dispatching an API mutation', () => { + const changes = []; + const landing = captureEmailLinkLanding( + { + pathname: '/verify-email', + search: '', + hash: '#token=verification%2Dtoken', + }, + { replaceState: (...args) => changes.push(args) } + ); + + assert.deepEqual(landing, { + kind: 'verify-email', + token: 'verification-token', + }); + assert.deepEqual(changes, [[null, '', '/verify-email']]); +}); + +test('reset GET captures a fragment token and never sends it in the landing URL', () => { + const changes = []; + const landing = captureEmailLinkLanding( + { + pathname: '/reset-password', + search: '', + hash: '#token=reset-token', + }, + { replaceState: (...args) => changes.push(args) } + ); + + assert.deepEqual(landing, { kind: 'reset-password', token: 'reset-token' }); + assert.deepEqual(changes, [[null, '', '/reset-password']]); +}); + +test('landing removes query parameters without accepting them as a token', () => { + const changes = []; + const landing = captureEmailLinkLanding( + { + pathname: '/verify-email', + search: '?token=legacy-query-secret', + hash: '', + }, + { replaceState: (...args) => changes.push(args) } + ); + + assert.deepEqual(landing, { kind: 'verify-email', token: null }); + assert.deepEqual(changes, [[null, '', '/verify-email']]); +}); + +test('only explicit verification completion sends a public POST', async () => { + const calls = []; + await completeEmailLink( + { kind: 'verify-email', token: 'verification-token' }, + undefined, + async (...args) => { + calls.push(args); + return { ok: true }; + } + ); + + assert.deepEqual(calls, [ + [ + '/api/account/auth/verify-email', + { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ token: 'verification-token' }), + }, + ], + ]); +}); + +test('reset completion submits the new password only in the POST body', async () => { + const calls = []; + await completeEmailLink( + { kind: 'reset-password', token: 'reset-token' }, + 'new-secret', + async (...args) => { + calls.push(args); + return { ok: true }; + } + ); + + assert.deepEqual(calls, [ + [ + '/api/account/auth/complete-password-reset', + { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + token: 'reset-token', + newPassword: 'new-secret', + }), + }, + ], + ]); +}); + +test('missing token and failed completion never report success', async () => { + let calls = 0; + const request = async () => { + calls += 1; + return { ok: false }; + }; + + await assert.rejects( + completeEmailLink({ kind: 'verify-email', token: null }, undefined, request) + ); + assert.equal(calls, 0); + await assert.rejects( + completeEmailLink( + { kind: 'verify-email', token: 'bad-token' }, + undefined, + request + ) + ); + assert.equal(calls, 1); +}); + +test('completion preserves HTTP failure categories without exposing the token', async () => { + for (const status of [400, 429, 503]) { + await assert.rejects( + completeEmailLink( + { kind: 'verify-email', token: 'secret-token' }, + undefined, + async () => ({ ok: false, status }) + ), + (error) => { + assert.ok(error instanceof EmailLinkCompletionError); + assert.equal(error.kind, 'http'); + assert.equal(error.status, status); + assert.doesNotMatch(error.message, /secret-token/); + return true; + } + ); + } +}); + +test('completion preserves network failures without retrying the POST', async () => { + let calls = 0; + await assert.rejects( + completeEmailLink( + { kind: 'verify-email', token: 'secret-token' }, + undefined, + async () => { + calls += 1; + throw new Error('offline'); + } + ), + (error) => { + assert.ok(error instanceof EmailLinkCompletionError); + assert.equal(error.kind, 'network'); + assert.equal(error.status, null); + assert.doesNotMatch(error.message, /secret-token|offline/); + return true; + } + ); + assert.equal(calls, 1); +}); + +test('failure messages distinguish rejected input from uncertain completion', () => { + const rejected = emailLinkFailureMessage( + 'verify-email', + new EmailLinkCompletionError('http', 400) + ); + assert.match(rejected, /could not accept this request/i); + assert.doesNotMatch(rejected, /invalid|expired/i); + + for (const failure of [ + new EmailLinkCompletionError('http', 429), + new EmailLinkCompletionError('http', 503), + new EmailLinkCompletionError('network', null), + ]) { + const verification = emailLinkFailureMessage('verify-email', failure); + assert.match(verification, /could not confirm/i); + assert.match(verification, /check your account after signing in/i); + + const reset = emailLinkFailureMessage('reset-password', failure); + assert.match(reset, /could not confirm/i); + assert.match(reset, /try signing in with your intended new password/i); + assert.doesNotMatch(reset, /invalid|expired/i); + } + + assert.match( + emailLinkFailureMessage( + 'verify-email', + new EmailLinkCompletionError('missing-token', null) + ), + /invalid or has expired/i + ); +}); diff --git a/web-client/vite.config.ts b/web-client/vite.config.ts index d3c32aaf22..d459658c1d 100644 --- a/web-client/vite.config.ts +++ b/web-client/vite.config.ts @@ -4,6 +4,11 @@ import react from '@vitejs/plugin-react' // https://vite.dev/config/ export default defineConfig({ plugins: [react()], + server: { + proxy: { + '/api': 'http://localhost:8080', + }, + }, build: { assetsDir: 'frontend-assets', },