diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8ffe77bb8f..15afae6f35 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: @@ -1256,7 +1255,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/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index c499397d2c..8bc0f84aba 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,13 +6,15 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +The shared-auth successor to #2929 carries the exact canonical non-nil Account UUID through ordinary JWT `sub`/`accountId` matching, session identity helpers and delegated gRPC context. Numeric, nil, noncanonical, whitespace-normalized and non-string identities are rejected; tenant, private-row, character and session identifiers retain their separate declared types. A genuinely account-free internal workload omits `accountId`; an internal flag cannot discard a present malformed identity. The focused Common Security full check passed 34 tasks with all 122 unit cases executed and no failures or skips, including callback-context cleanup and malformed internal-identity denial. This is local helper/interceptor proof, not fresh-image or live authentication proof. Game Session's legacy numeric presence-viewer self-service cannot establish Account UUID authority and is unavailable; its existing tenant-role boundary remains. Interim Social numeric self-service and sender-bound mail likewise remain unavailable pending the approved complete Social UUID storage/API/consumer child after [#2932](https://github.com/benhook1013/FireMUD/pull/2932). No retained rows or published migrations are rewritten, and this correction does not complete #2932's gameplay carriers or enable admission. + The known legacy realm-grant mutation boundary now fails closed: otherwise-valid authenticated privileged POST/DELETE requests return `AUTH_UNAVAILABLE` before service dispatch, and direct grant/revoke service calls reject before repository access. Malformed and unauthorized requests retain their existing denial checks. This preserves retained four-field grant rows rather than revising them without lifecycle authority or hard-deleting their history. On owning #2923, the Account full check, formatting/static analysis, service JAR and documentation passed70tasks(23executed/47up-to-date), with511unit cases executed without skips/failures/errors. Strict readback confirms the two HTTP and two direct-service denial cases each executed once, including changed payload under the same request ID and both verbs' unauthenticated/nonprivileged denial. All159PostgreSQL cases skipped without local Docker; this is unit/no-dispatch proof, not database or deployed runtime proof. It does not implement ADR 0138's lifecycle-qualified authorization, bounded expiry, idempotent mutation, tombstones, event delivery or active-binding ejection; those remain required pre-v1 owner work. No runtime path or Account ring mount is enabled. The normally composed management child passed full Account/Game Session/shared-support checks, both service JARs and docs164tasks(29executed/135up-to-date), with517Account unit cases newly executed without skips/failures/errors; Game Session and shared-support test tasks were up-to-date. All161Account PostgreSQL cases skipped locally. The following source-head reports retain their historical attribution, not current-head runner or activation proof. Exact corrected #2929 source `96fb1b803d4dd1c6a3cc8f39bda91ae537e25bb6` [CI36912843232](https://github.com/benhook1013/FireMUD/actions/runs/36912843232) completed aggregate FAILURE but strictly passed the V10 migration, changed-owner snapshot and two Account profile cases, each executed once with zero skips/failures/errors. The Account UUID suite14, snapshot suite4 and owner migration suite1 were clean. This proves the corrected PostgreSQL component behavior and recovery from the fixture username/binding failures below. Wider Game Session reached16CommunicationWebSocket behavioral assertions before cancellation; expected/actual values were absent from emitted logs and remain under bounded artifact diagnosis, not presumed fixed by the unpublished108-file carrier. Other aggregate jobs remain red; runtime activation and merge readiness are not established. See the dated runner readback and artifact-download safety follow-up in [AI observations](../ai-observations.md). Exact #2929 source `73e19d7f8e74f8fa684c56ca0139ddac0751d31e` [CI36909989685](https://github.com/benhook1013/FireMUD/actions/runs/36909989685) completed aggregate FAILURE. The new management-owner migration case executed once and passed strict PostgreSQL verification, as did the four-case retained snapshot suite including exact changed-owner digest binding. Both new Account profile cases executed but failed during creation because their generated usernames exceeded `accounts.username VARCHAR(50)`; the artifact proves that constraint violation, not an identity/readback assertion failure. The longer Game Session cross-service task failed34of35cases during shared fixture setup because PostgreSQL rejected a string JDBC bind for the UUID owner column. Those fixtures now keep the full random suffix with shorter usernames and use a typed UUID bind with a focused assertion. The affected full Account/Game Session/shared-support checks and both JARs passed162tasks(36executed/126up-to-date); local PostgreSQL cases remain skipped, so corrected-head runner recovery proof is still required. Python, shared dev-tool and other module failures remain separately open, and none of these results enables runtime paths. See the dated [JDBC UUID observation](../ai-observations.md). -The canonical Account-identity candidate is based on exact #2923 `b93efaedbaec8a36294a594a946a010641e345b4`. Game Session owner requests, storage, readback and owner-self comparison use canonical UUIDs while V10.1 retains numeric owner evidence unchanged and unmapped. The closed version-2 retained-tenant snapshot binds both truthful owner slots; source locks, exact approval and immutable association readback remain required. Before enablement, the owner must inventory deployed migration history and read back the exact retained numeric and UUID owner slots; deployed-history provenance and readback are not established here. Demo seeding no longer invents an Account owner without an authoritative source. This does not activate catalog enrollment, the membership RPC or credentials, nor implement Account operator-reference/digest authorization. The separate gameplay session/presence child remains unpublished at108files; overlapping paths do not prove its remaining unique hunks fit the ceiling. +The canonical profile/management-owner front is based on exact #2923 `699a25e022c9224d24b7a491ee4ab1d4a67f22f2`. Game Session owner requests, storage, readback and owner-self comparison use canonical UUIDs while V10.1 retains numeric owner evidence unchanged and unmapped. The closed version-2 retained-tenant snapshot binds both truthful owner slots; source locks, exact approval and immutable association readback remain required. Before enablement, the owner must inventory deployed migration history and read back the exact retained numeric and UUID owner slots; deployed-history provenance and readback are not established here. Demo seeding no longer invents an Account owner without an authoritative source. This does not activate catalog enrollment, the membership RPC or credentials, nor implement Account operator-reference/digest authorization. The shared-JWT successor and separate published [#2932 gameplay session/presence carriers](https://github.com/benhook1013/FireMUD/pull/2932) remain distinct proof boundaries; publication and overlapping paths do not prove end-to-end admission. Account profile responses, updates and local export now carry the exact provenance-checked Account UUID, not the private row key. Before profile access the service verifies the requested Account source/readback; it then checks exact profile Account/tenant ownership. REST rejects a body/path Account mismatch, malformed/numeric/nil selectors and unauthorized callers without dispatch. Profile IDs and the current numeric tenant selector remain distinct; retained rows are not rewritten. Tenant-qualified/delegated profile routes, membership-generation authorization, Social Groups' numeric profile/presence callers and complete export semantics remain open owner work, not completed by this carrier correction. 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 a9e4eeb0fc..6970fc04c1 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 @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for player-facing commands, commu ## Current Status +Shared ordinary Account JWT identity now uses the exact canonical Account UUID in the shared-auth successor to #2929. Legacy numeric Social self-service and sender-bound mail cannot prove that caller identity and remain unavailable; existing genuine tenant-role access and internal service/storage behavior are separate boundaries. The approved Social UUID child after [#2932](https://github.com/benhook1013/FireMUD/pull/2932) must converge all account-bearing storage, APIs and affected consumers without numeric aliases or guessed retained mappings. Local shared-helper proof is not positive Social delivery or authentication/activation proof. Preserve existing friend privacy/redaction and removed Gateway routes; this interim containment does not close EA-2.1/EA-2.2/EA-2.3 target gaps. + This tracker is the permanent reader-facing implementation record for player-facing commands, admission, presentation, communication, presence, and client behavior. Most bounded capabilities are live, including the stored game-authored HELP path; broader command interpretation, rich help authoring/discovery, elevated staff behavior, richer communication, and the independently released static frontend artifact/host boundary remain explicitly incomplete. The Vite frontend build now emits compiled assets under the reserved `frontend-assets` directory, but independently released hosting and browser proof remain absent. The output/reconnect lane remains partial where explicit structured schema versioning, strict complete-byte context bounds, durable post-logout episode fencing, and broader client consumption are not yet proven. Authenticated text `LOGOUT` returns `LOGOUT_UNAVAILABLE` before side effects. Focused Game Session proof asserts this negative/no-side-effect boundary and that fresh first-party `PLAY` does not read retained screen-buffer rows solely from connect-token context; neither proves successful logout or durable episode fencing; concurrent and delayed replay still require durable episode-fence proof. Packet 5 moderation/communication/social provenance is represented by [ADR 0146](../../architecture/decisions/adr-0146-owner-local-moderation-enforcement.md), [ADR 0147](../../architecture/decisions/adr-0147-explicit-communication-classes-and-owner-delivery.md), [ADR 0148](../../architecture/decisions/adr-0148-social-relationship-authority-and-entity-owned-value.md), [ADR 0149](../../architecture/decisions/adr-0149-communication-type-specific-history-and-retention.md), and [ADR 0150](../../architecture/decisions/adr-0150-closed-observer-views-and-profile-scoped-shout.md); Packet 6 P0 shared consequences are represented by [ADR 0151](../../architecture/decisions/adr-0151-event-scoped-automated-tier-a-credential-compliance.md), [ADR 0152](../../architecture/decisions/adr-0152-phased-environment-bound-deployment-preflight-and-expected-bindings.md), [ADR 0153](../../architecture/decisions/adr-0153-measured-online-backup-rpo-and-future-pitr-trigger.md), [ADR 0154](../../architecture/decisions/adr-0154-automated-recovery-proof-and-differentiated-traffic-open-gates.md), [ADR 0155](../../architecture/decisions/adr-0155-automated-event-classified-post-restore-trust-reset.md), [ADR 0156](../../architecture/decisions/adr-0156-risk-tiered-progressive-rollout-with-compatibility-bounded-rollback.md), [ADR 0157](../../architecture/decisions/adr-0157-dependency-classified-liveness-readiness-and-route-admission.md), [ADR 0158](../../architecture/decisions/adr-0158-simplified-observability-degradation-without-fallback-alert-authority.md), and [ADR 0159](../../architecture/decisions/adr-0159-profile-dependent-independent-deadman-and-public-path-monitoring.md) where player-facing delivery, history, or privacy boundaries are affected. These links do not upgrade any implementation or verification state. 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/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/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java index b03c405cc9..60740c8131 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java @@ -384,7 +384,12 @@ void concurrentEmailVerificationAttemptsConsumeTokenExactlyOnce() throws Excepti void exportAccountRejectsMalformedAccountIdWithInvalidArgumentEnvelope() throws Exception { String token = jwtUtil.generateToken( - "operator", java.util.Map.of("globalRoles", java.util.List.of("platformAdmin"))); + "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + java.util.Map.of( + "accountId", + "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + "globalRoles", + java.util.List.of("platformAdmin"))); HttpRequest request = HttpRequest.newBuilder( URI.create("http://localhost:" + port + "/accounts/not-a-number/export")) @@ -402,7 +407,8 @@ void exportAccountRejectsMalformedAccountIdWithInvalidArgumentEnvelope() throws @Test void linkExternalRouteIsUnavailableWithAuthenticatedRequest() throws Exception { - String token = jwtUtil.generateToken("2", java.util.Map.of("accountId", "2")); + String accountId = "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a"; + String token = jwtUtil.generateToken(accountId, java.util.Map.of("accountId", accountId)); HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/accounts/2/external")) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountConnectStorageUuidMigrationIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountConnectStorageUuidMigrationIntegrationTest.java index 0571e37599..283b1a3d3f 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountConnectStorageUuidMigrationIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountConnectStorageUuidMigrationIntegrationTest.java @@ -17,6 +17,7 @@ import java.util.Arrays; import java.util.Base64; import java.util.List; +import java.util.Map; import java.util.UUID; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; @@ -328,7 +329,7 @@ private static AccountRow insertAccount(Connection connection, Database database "INSERT INTO " + table(database, "accounts") + " (username, email, password_hash) VALUES (?, ?, ?) RETURNING id")) { - statement.setString(1, "migration-user-" + UUID.randomUUID()); + statement.setString(1, "migration-" + UUID.randomUUID()); statement.setString(2, UUID.randomUUID() + "@example.test"); statement.setString(3, "test-hash"); try (ResultSet result = statement.executeQuery()) { @@ -756,6 +757,7 @@ private static Flyway flyway(Database database, String target) { .schemas(database.schema()) .defaultSchema(database.schema()) .table(HISTORY_TABLE) + .placeholders(Map.of("serviceSchema", database.schema())) .locations("classpath:db/migration"); if (target != null) { configuration.target(MigrationVersion.fromVersion(target)); @@ -765,9 +767,12 @@ private static Flyway flyway(Database database, String target) { private static Database newDatabase() throws SQLException { String schema = "account_connect_uuid_" + UUID.randomUUID().toString().replace("-", ""); + String separator = postgres.getJdbcUrl().contains("?") ? "&" : "?"; DriverManagerDataSource dataSource = new DriverManagerDataSource( - postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + postgres.getJdbcUrl() + separator + "currentSchema=" + schema, + postgres.getUsername(), + postgres.getPassword()); dataSource.setDriverClassName("org.postgresql.Driver"); try (Connection connection = dataSource.getConnection(); Statement statement = connection.createStatement()) { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java index aa62dac48c..a29e8d54e4 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java @@ -92,7 +92,7 @@ class AccountJoinPostgresIntegrationTest { private static final UUID REALM_ID = UUID.fromString("4c4b57d8-e3a2-48fe-9977-e7df0fdce901"); private static final String WORLD_SLUG = "join-proof-world"; private static final String REALM_SLUG = "production"; - private static final String NAMESPACE_ID = "join-proof-namespace"; + private static final String NAMESPACE_ID = "65f23d2c-3b4f-4ec3-9b11-0c56a9a2a7d1"; private static final long GAME_INSTANCE_ID = 44L; private static final long CATALOG_REVISION = 23L; private static final long POINTER_VERSION = 17L; @@ -285,10 +285,11 @@ void failedJoinReplaysStoredOutcomeAndRejectsChangedPolicyDigest() { dsl.execute( "UPDATE subscription SET status = 'active', entitlement_version = 2 WHERE tenant_id = ?", fixture.tenantId()); - AuthenticationException conflict = - assertThrows(AuthenticationException.class, () -> join(fixture)); + JoinPublicProductionResult conflict = join(fixture); - assertThat(conflict.getCode()).isEqualTo("IDEMPOTENCY_CONFLICT"); + assertThat(conflict.success()).isFalse(); + assertThat(conflict.outcomeCode()).isEqualTo("IDEMPOTENCY_CONFLICT"); + assertThat(conflict.replayed()).isFalse(); assertThat( dsl.resultQuery( "SELECT request_digest FROM account_join_operations WHERE request_id = ?", @@ -1198,7 +1199,7 @@ void membershipTransitionReceiptsRejectMutationAndStillAllowAppendAndStreamAdvan assertMembershipTransitionReceipt(initialJoin, "MEMBERSHIP_JOINED", 1L); assertThrows( - org.jooq.exception.DataAccessException.class, + org.springframework.dao.DataIntegrityViolationException.class, () -> dsl.execute( "UPDATE account_membership_transition_receipts " @@ -1209,7 +1210,7 @@ void membershipTransitionReceiptsRejectMutationAndStillAllowAppendAndStreamAdvan assertMembershipTransitionReceipt(initialJoin, "MEMBERSHIP_JOINED", 1L); assertThrows( - org.jooq.exception.DataAccessException.class, + org.springframework.dao.DataIntegrityViolationException.class, () -> dsl.execute( "DELETE FROM account_membership_transition_receipts " @@ -1227,16 +1228,32 @@ void membershipTransitionReceiptsRejectMutationAndStillAllowAppendAndStreamAdvan .fetchOne(0, Long.class)) .isEqualTo(1L); - dsl.execute( - "UPDATE account_tenant_membership SET lifecycle_state = 'INACTIVE', " - + "gameplay_admission_allowed = FALSE WHERE account_id = ? AND tenant_id = ?", - initialJoin.accountId(), - initialJoin.tenantId()); + String leftRequestId = "leave-proof-" + UUID.randomUUID(); + MembershipTransitionReceipt left = leave(initialJoin, leftRequestId); + assertThat(left.transitionType()).isEqualTo("MEMBERSHIP_LEFT"); + assertThat(left.requestId()).isEqualTo(leftRequestId); + assertThat(left.receiptSequence()).isEqualTo(2L); + assertMembershipTransitionReceipt(initialJoin, "MEMBERSHIP_LEFT", 2L); + assertThat(membershipSnapshot(initialJoin)) + .containsEntry("lifecycle_state", "INACTIVE") + .containsEntry("gameplay_admission_allowed", false) + .containsEntry("membership_version", 3L) + .containsEntry("membership_authority_generation", 2L); + assertThat(countAuthorityMembershipEvents(initialJoin)).isEqualTo(2L); + assertLeftAuthorityMembershipEvent(initialJoin, leftRequestId, 2L, 3L); + JoinFixture reactivation = fixtureForMembership(initialJoin); assertThat(join(reactivation).success()).isTrue(); - assertMembershipTransitionReceipt(reactivation, "MEMBERSHIP_REACTIVATED", 2L); - assertThat(countMembershipTransitionReceipts(reactivation)).isEqualTo(2L); + assertMembershipTransitionReceipt(reactivation, "MEMBERSHIP_REACTIVATED", 3L); + assertThat(membershipSnapshot(reactivation)) + .containsEntry("lifecycle_state", "ACTIVE") + .containsEntry("gameplay_admission_allowed", true) + .containsEntry("membership_version", 4L) + .containsEntry("membership_authority_generation", 3L); + assertThat(countAuthorityMembershipEvents(reactivation)).isEqualTo(3L); + assertAuthorityMembershipEvent(reactivation, 3L, 4L, true); + assertThat(countMembershipTransitionReceipts(reactivation)).isEqualTo(3L); assertThat( dsl.resultQuery( "SELECT last_receipt_sequence " @@ -1245,7 +1262,7 @@ void membershipTransitionReceiptsRejectMutationAndStillAllowAppendAndStreamAdvan reactivation.accountId(), reactivation.tenantId()) .fetchOne(0, Long.class)) - .isEqualTo(2L); + .isEqualTo(3L); } @Test diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinReconciliationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinReconciliationPostgresIntegrationTest.java index b53ffa53b2..a8ae5e944e 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinReconciliationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinReconciliationPostgresIntegrationTest.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.accountservice; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.when; import java.nio.charset.StandardCharsets; @@ -74,7 +75,7 @@ class AccountJoinReconciliationPostgresIntegrationTest { private static final UUID REALM_ID = UUID.fromString("a825f7ef-0ea3-4e8c-bf7c-a20242b4c931"); private static final String WORLD_SLUG = "join-reconciliation-world"; private static final String REALM_SLUG = "production"; - private static final String NAMESPACE_ID = "join-reconciliation-namespace"; + private static final String NAMESPACE_ID = "9f1c6889-9e41-4d5d-86fb-8c75fc401a31"; private static final long GAME_INSTANCE_ID = 73L; private static final long CATALOG_REVISION = 29L; private static final long POINTER_VERSION = 11L; @@ -164,7 +165,7 @@ void exactPersistedEvidenceRecoversExpiredScopeAndSameRequestRetryWithoutDuplica Instant now = scopeExpiry.plusSeconds(1); reconciliationService.reconcileDueOperations(now); - assertOperation(fixture, "COMMITTED", "JOINED", 2, null); + assertOperation(fixture, "COMMITTED", "JOINED", 2, "PRIOR_RECONCILIATION_ATTEMPT"); assertThat( dsl.resultQuery( "SELECT COUNT(*) FROM account_join_operations WHERE request_id = ? AND status = 'COMMITTED' AND outcome = 'JOINED' AND membership_id = ? AND outcome_membership_version = 2 AND outcome_membership_authority_generation = 1", @@ -261,14 +262,43 @@ void retainedLegacyReceiptIdsWithoutProjectionVersionStayPending() { } @Test - void absentScopeAndExpiredScopeWithoutMembershipProofRemainPendingWithDiagnostics() { - JoinFixture absentScope = committedEvidencePendingFixture(); - dsl.execute( - "DELETE FROM account_connect_scope_records WHERE scope_token_hash = ?", - AccountJoinDigest.tokenHash(absentScope.connectScopeId())); - assertUnresolvedAtThreshold(absentScope, "JOIN_SCOPE_EVIDENCE_ABSENT"); - assertThat(countMemberships(absentScope)).isEqualTo(1L); - assertThat(countJoinOutbox(absentScope)).isEqualTo(1L); + void retainedScopeDeletionAndExpiredScopeWithoutMembershipProofRemainPendingWithDiagnostics() { + JoinFixture retainedScope = committedEvidencePendingFixture(); + String scopeTokenHash = AccountJoinDigest.tokenHash(retainedScope.connectScopeId()); + var originalScope = + dsl.resultQuery( + "SELECT * FROM account_connect_scope_records WHERE scope_token_hash = ?", + scopeTokenHash) + .fetchOne(); + var originalOperation = + dsl.resultQuery( + "SELECT * FROM account_join_operations WHERE request_id = ?", + retainedScope.requestId()) + .fetchOne(); + assertThat(originalScope).isNotNull(); + assertThat(originalOperation).isNotNull(); + assertThat(originalOperation.get("status", String.class)).isEqualTo("PENDING"); + + assertThatThrownBy( + () -> + dsl.execute( + "DELETE FROM account_connect_scope_records WHERE scope_token_hash = ?", + scopeTokenHash)) + .isInstanceOf(org.springframework.dao.DataIntegrityViolationException.class); + assertThat( + dsl.resultQuery( + "SELECT * FROM account_connect_scope_records WHERE scope_token_hash = ?", + scopeTokenHash) + .fetchOne()) + .isEqualTo(originalScope); + assertThat( + dsl.resultQuery( + "SELECT * FROM account_join_operations WHERE request_id = ?", + retainedScope.requestId()) + .fetchOne()) + .isEqualTo(originalOperation); + assertThat(countMemberships(retainedScope)).isEqualTo(1L); + assertThat(countJoinOutbox(retainedScope)).isEqualTo(1L); JoinFixture expiredWithoutMembership = committedEvidencePendingFixture(); deleteMembershipEvidence(expiredWithoutMembership); @@ -453,7 +483,7 @@ void twoWorkersRecoverThresholdPendingEvidenceWithoutDuplicatingMembershipOrAudi first.get(30, TimeUnit.SECONDS); second.get(30, TimeUnit.SECONDS); - assertOperation(fixture, "COMMITTED", "JOINED", 2, null); + assertOperation(fixture, "COMMITTED", "JOINED", 2, "PRIOR_RECONCILIATION_ATTEMPT"); assertMembershipAndAuditOnce(fixture, originalMembershipId(fixture)); } finally { executor.shutdownNow(); @@ -484,7 +514,7 @@ private void makeOperationPendingWithRetainedEvidence(JoinFixture fixture, int a assertThat(updated).isEqualTo(1); int auditUpdated = dsl.execute( - "UPDATE account_audit_outbox SET delivery_status = 'COMMITTED', receiver_audit_projection_version = 1, receiver_receipt_id = 'verified-receipt', receiver_log_event_id = 'verified-projection' WHERE audit_event_id = ? AND scope = 'tenant' AND tenant_id = ? AND producer_service = 'account-service' AND event_type = 'ACCOUNT_JOINED_PUBLIC_PRODUCTION'", + "UPDATE account_audit_outbox SET delivery_status = 'COMMITTED', next_attempt_at = NULL, receiver_audit_projection_version = 1, receiver_receipt_id = 'verified-receipt', receiver_log_event_id = 'verified-projection' WHERE audit_event_id = ? AND scope = 'tenant' AND tenant_id = ? AND producer_service = 'account-service' AND event_type = 'ACCOUNT_JOINED_PUBLIC_PRODUCTION'", joinAuditEventId(fixture.requestId()), fixture.tenantId()); assertThat(auditUpdated).isEqualTo(1); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java index 6293a1150b..1161427443 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java @@ -116,7 +116,10 @@ void createAccountRetainsMinimumPasswordLength() throws Exception { @Test void deleteAccountDeniesPlatformAdminBeforeServiceMutation() throws Exception { - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = + jwtUtil.generateToken( + ACCOUNT_UUID, + Map.of("accountId", ACCOUNT_UUID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -131,7 +134,13 @@ void deleteAccountDeniesPlatformAdminBeforeServiceMutation() throws Exception { @Test void deleteAccountRejectsScopedTenantAdminBecauseFullDeletionIsAccountScoped() throws Exception { String token = - jwtUtil.generateToken("user", Map.of("scopedRoles", Map.of("7", List.of("tenantAdmin")))); + jwtUtil.generateToken( + OTHER_ACCOUNT_UUID, + Map.of( + "accountId", + OTHER_ACCOUNT_UUID, + "scopedRoles", + Map.of("7", List.of("tenantAdmin")))); mockMvc .perform( @@ -140,6 +149,8 @@ void deleteAccountRejectsScopedTenantAdminBecauseFullDeletionIsAccountScoped() t .andExpect(status().isForbidden()) .andExpect(jsonPath("$.error.code").value("PERMISSION_DENIED")) .andExpect(jsonPath("$.error.message").value("Account access required")); + + verifyNoInteractions(accountService); } @Test @@ -160,15 +171,28 @@ void exportAccountAllowsCurrentAccountWithoutTenantScope() throws Exception { } @Test - void exportAccountRejectsNumericOrDifferentSubjectBeforeIdentityLookup() throws Exception { - for (String subject : List.of("42", OTHER_ACCOUNT_UUID)) { - String token = jwtUtil.generateToken(subject, Map.of("accountId", subject)); - mockMvc - .perform( - get("/accounts/" + ACCOUNT_UUID + "/export") - .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) - .andExpect(status().isForbidden()); - } + void exportAccountRejectsNumericSubjectBeforeIdentityLookup() throws Exception { + String token = jwtUtil.generateToken("42", Map.of("accountId", "42")); + + mockMvc + .perform( + get("/accounts/" + ACCOUNT_UUID + "/export") + .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + .andExpect(status().isUnauthorized()); + + verifyNoInteractions(accountService); + } + + @Test + void exportAccountRejectsDifferentSubjectBeforeIdentityLookup() throws Exception { + String token = + jwtUtil.generateToken(OTHER_ACCOUNT_UUID, Map.of("accountId", OTHER_ACCOUNT_UUID)); + + mockMvc + .perform( + get("/accounts/" + ACCOUNT_UUID + "/export") + .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + .andExpect(status().isForbidden()); verifyNoInteractions(accountService); } @@ -176,7 +200,9 @@ void exportAccountRejectsNumericOrDifferentSubjectBeforeIdentityLookup() throws @Test void exportTenantDataFailsClosedWithoutReadingAccountService() throws Exception { String token = - jwtUtil.generateToken("user", Map.of("scopedRoles", Map.of("7", List.of("moderator")))); + jwtUtil.generateToken( + ACCOUNT_UUID, + Map.of("accountId", ACCOUNT_UUID, "scopedRoles", Map.of("7", List.of("moderator")))); mockMvc .perform( @@ -190,7 +216,10 @@ void exportTenantDataFailsClosedWithoutReadingAccountService() throws Exception @Test void exportAccountRejectsMalformedAccountIdBeforeDispatch() throws Exception { - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = + jwtUtil.generateToken( + ACCOUNT_UUID, + Map.of("accountId", ACCOUNT_UUID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -204,7 +233,10 @@ void exportAccountRejectsMalformedAccountIdBeforeDispatch() throws Exception { @Test void exportTenantDataRejectsZeroTenantIdBeforeDispatch() throws Exception { - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = + jwtUtil.generateToken( + ACCOUNT_UUID, + Map.of("accountId", ACCOUNT_UUID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -235,7 +267,7 @@ void deleteAccountDeniesCurrentAccountBeforeServiceMutation() throws Exception { @Test void deleteAccountRejectsZeroAccountIdBeforeDispatch() throws Exception { - String token = jwtUtil.generateToken("1", Map.of("accountId", "1")); + String token = jwtUtil.generateToken(ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID)); mockMvc .perform(delete("/accounts/0").header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) @@ -297,7 +329,9 @@ void loginAuthModesAllowCurrentAccountWithoutTenantScope() throws Exception { @Test void updateLoginAuthModesRejectsPlatformAdminBeforeDispatch() throws Exception { String token = - jwtUtil.generateToken("operator", Map.of("globalRoles", List.of("platformAdmin"))); + jwtUtil.generateToken( + ACCOUNT_UUID, + Map.of("accountId", ACCOUNT_UUID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/InternalRuntimeControllerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/InternalRuntimeControllerTest.java index 24c466f293..0d927dd67e 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/InternalRuntimeControllerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/InternalRuntimeControllerTest.java @@ -28,6 +28,7 @@ @Import({CommonSecurityAutoConfiguration.class, CommonSecurityServletAutoConfiguration.class}) @WithFiremudPrivilegedHttpAuthTestProperties class InternalRuntimeControllerTest { + private static final String ACCOUNT_UUID = "550e8400-e29b-41d4-a716-446655440000"; @Autowired private MockMvc mockMvc; @Autowired private JwtUtil jwtUtil; @@ -45,7 +46,9 @@ void clear() { void grantRealmAccessRejectsZeroAccountIdBeforeDispatch() throws Exception { String token = jwtUtil.generateToken( - "user", java.util.Map.of("globalRoles", java.util.List.of("platformAdmin"))); + ACCOUNT_UUID, + java.util.Map.of( + "accountId", ACCOUNT_UUID, "globalRoles", java.util.List.of("platformAdmin"))); mockMvc .perform( @@ -75,7 +78,9 @@ void grantRealmAccessRejectsZeroAccountIdBeforeDispatch() throws Exception { void revokeRealmAccessRejectsMalformedAccountIdBeforeDispatch() throws Exception { String token = jwtUtil.generateToken( - "user", java.util.Map.of("globalRoles", java.util.List.of("platformAdmin"))); + ACCOUNT_UUID, + java.util.Map.of( + "accountId", ACCOUNT_UUID, "globalRoles", java.util.List.of("platformAdmin"))); mockMvc .perform( @@ -168,7 +173,9 @@ void missingOrNonprivilegedAuthenticationStillDeniesGrantMutations() throws Exce } private String jwtTokenWithGlobalRole(String role) { - return jwtUtil.generateToken("user", java.util.Map.of("globalRoles", java.util.List.of(role))); + return jwtUtil.generateToken( + ACCOUNT_UUID, + java.util.Map.of("accountId", ACCOUNT_UUID, "globalRoles", java.util.List.of(role))); } private String validGrantRequestBody() throws Exception { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java index 878c6f19ae..6bd5961d94 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java @@ -97,20 +97,33 @@ void updateProfileReturnsDto() throws Exception { @Test void getProfileRejectsCrossTenantScopedAdmin() throws Exception { String token = - jwtUtil.generateToken("user", Map.of("scopedRoles", Map.of("8", List.of("tenantAdmin")))); + jwtUtil.generateToken( + OTHER_ACCOUNT_UUID, + Map.of( + "accountId", + OTHER_ACCOUNT_UUID, + "scopedRoles", + Map.of("8", List.of("tenantAdmin")))); mockMvc .perform( get("/profiles/" + ACCOUNT_UUID) .param("tenantId", "1") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isForbidden()); + + verifyNoInteractions(accountService); } @Test void getProfileRejectsSameTenantAdminForAnotherAccount() throws Exception { String token = jwtUtil.generateToken( - OTHER_ACCOUNT_UUID, Map.of("scopedRoles", Map.of("1", List.of("tenantAdmin")))); + OTHER_ACCOUNT_UUID, + Map.of( + "accountId", + OTHER_ACCOUNT_UUID, + "scopedRoles", + Map.of("1", List.of("tenantAdmin")))); mockMvc .perform( @@ -125,7 +138,9 @@ void getProfileRejectsSameTenantAdminForAnotherAccount() throws Exception { @Test void getProfileRejectsGlobalAdminForAnotherAccount() throws Exception { String token = - jwtUtil.generateToken(OTHER_ACCOUNT_UUID, Map.of("globalRoles", List.of("platformAdmin"))); + jwtUtil.generateToken( + OTHER_ACCOUNT_UUID, + Map.of("accountId", OTHER_ACCOUNT_UUID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -146,7 +161,7 @@ void getProfileRejectsNumericSubjectBeforeIdentityLookup() throws Exception { get("/profiles/" + ACCOUNT_UUID) .param("tenantId", "1") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) - .andExpect(status().isForbidden()); + .andExpect(status().isUnauthorized()); verifyNoInteractions(accountService); } @@ -170,7 +185,9 @@ void getProfileRejectsUnmappedUuidBeforeProfileRead() throws Exception { @Test void getProfileRejectsMalformedAccountIdBeforeDispatch() throws Exception { String token = - jwtUtil.generateToken(OTHER_ACCOUNT_UUID, Map.of("globalRoles", List.of("platformAdmin"))); + jwtUtil.generateToken( + OTHER_ACCOUNT_UUID, + Map.of("accountId", OTHER_ACCOUNT_UUID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -187,7 +204,9 @@ void getProfileRejectsMalformedAccountIdBeforeDispatch() throws Exception { @Test void getProfileRejectsZeroTenantIdBeforeDispatch() throws Exception { String token = - jwtUtil.generateToken(OTHER_ACCOUNT_UUID, Map.of("globalRoles", List.of("platformAdmin"))); + jwtUtil.generateToken( + OTHER_ACCOUNT_UUID, + Map.of("accountId", OTHER_ACCOUNT_UUID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -310,7 +329,12 @@ void updateProfileRejectsSameTenantAdminForAnotherAccount() throws Exception { 1L, ACCOUNT_UUID, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); String token = jwtUtil.generateToken( - OTHER_ACCOUNT_UUID, Map.of("scopedRoles", Map.of("1", List.of("tenantAdmin")))); + OTHER_ACCOUNT_UUID, + Map.of( + "accountId", + OTHER_ACCOUNT_UUID, + "scopedRoles", + Map.of("1", List.of("tenantAdmin")))); mockMvc .perform( @@ -329,7 +353,9 @@ void updateProfileRejectsGlobalAdminForAnotherAccount() throws Exception { new UpdateProfileRequest( 1L, ACCOUNT_UUID, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); String token = - jwtUtil.generateToken(OTHER_ACCOUNT_UUID, Map.of("globalRoles", List.of("platformAdmin"))); + jwtUtil.generateToken( + OTHER_ACCOUNT_UUID, + Map.of("accountId", OTHER_ACCOUNT_UUID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -347,7 +373,10 @@ void updateProfileRejectsZeroAccountIdBeforeDispatch() throws Exception { UpdateProfileRequest req = new UpdateProfileRequest( 1L, ACCOUNT_UUID, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = + jwtUtil.generateToken( + ACCOUNT_UUID, + Map.of("accountId", ACCOUNT_UUID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/RemovedExternalAccountRouteHttpTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/RemovedExternalAccountRouteHttpTest.java index bf6c0b8ed9..8258865fe7 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/RemovedExternalAccountRouteHttpTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/RemovedExternalAccountRouteHttpTest.java @@ -59,7 +59,8 @@ void removedExternalRouteRequiresAuthenticationThenUsesDefaultNotFoundErrorPath( assertThat(unauthenticatedResponse.statusCode()).isEqualTo(401); - String token = jwtUtil.generateToken("2", Map.of("accountId", "2")); + String accountId = "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a"; + String token = jwtUtil.generateToken(accountId, Map.of("accountId", accountId)); HttpRequest authenticatedRequest = externalLinkRequest(route, token); HttpResponse authenticatedResponse = diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/GrpcJwtAuthInterceptorTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/GrpcJwtAuthInterceptorTest.java index ceb6732cb4..c355b6c773 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/GrpcJwtAuthInterceptorTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/GrpcJwtAuthInterceptorTest.java @@ -16,6 +16,7 @@ import org.junit.jupiter.api.Test; class GrpcJwtAuthInterceptorTest { + private static final String ACCOUNT_ID = "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a"; private JwtUtil jwtUtil; private AuthTokenInterceptor interceptor; @@ -35,7 +36,9 @@ void rejectsMissingToken() { @Test void allowsValidToken() { - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = + jwtUtil.generateToken( + ACCOUNT_ID, Map.of("accountId", ACCOUNT_ID, "globalRoles", List.of("platformAdmin"))); TestServerCall call = new TestServerCall(); Metadata headers = new Metadata(); headers.put( diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressServiceImpl.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressServiceImpl.java index 31b1d7f0d0..c7a5acb2a9 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressServiceImpl.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressServiceImpl.java @@ -1611,7 +1611,7 @@ private static String resolveSourceService() { } private static String dryRunPrincipalKey() { - Long accountId = SessionContext.currentAccountIdOrNull(); + String accountId = SessionContext.currentAccountIdOrNull(); if (accountId != null) { return "account:" + accountId; } diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/AutomationScriptingServiceApplicationIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/AutomationScriptingServiceApplicationIntegrationTest.java index eb6d23027a..e17e7068a3 100644 --- a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/AutomationScriptingServiceApplicationIntegrationTest.java +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/AutomationScriptingServiceApplicationIntegrationTest.java @@ -150,7 +150,12 @@ void unsupportedFormationRestRoutesAreNotReachable() throws Exception { void unsupportedFormationRestRoutesRejectCrossTenantSelectorsByBeingAbsent() throws Exception { String token = JWT_UTIL.generateToken( - "automation-test", Map.of("scopedRoles", Map.of("1", List.of("tenantAdmin")))); + "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + Map.of( + "accountId", + "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + "scopedRoles", + Map.of("1", List.of("tenantAdmin")))); HttpRequest request = HttpRequest.newBuilder( URI.create("http://localhost:" + port + "/formations/7/members?tenantId=2")) @@ -167,7 +172,12 @@ void unsupportedFormationRestRoutesRejectCrossTenantSelectorsByBeingAbsent() thr void removedFactionRestEndpointReturnsNotFound() throws Exception { String token = JWT_UTIL.generateToken( - "automation-test", Map.of("scopedRoles", Map.of("1", List.of("tenantAdmin")))); + "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + Map.of( + "accountId", + "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + "scopedRoles", + Map.of("1", List.of("tenantAdmin")))); HttpRequest request = HttpRequest.newBuilder( URI.create( diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressServiceImplTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressServiceImplTest.java index 7ba9937a36..c125fff8e8 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressServiceImplTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressServiceImplTest.java @@ -3182,7 +3182,12 @@ void quotaDeniedHandlerWritesAuditWithoutWorkItem() { @Test void dryRunBudgetDenialStopsBeforeHandlerResolution() { SessionContext.setContext( - "41", List.of("platformAdmin"), Map.of(), true, "game-session-service", "gs-1"); + "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + List.of("platformAdmin"), + Map.of(), + true, + "game-session-service", + "gs-1"); ScriptEventIngressAuditRepository repository = Mockito.mock(ScriptEventIngressAuditRepository.class); stubClaimRepository(repository); @@ -3202,7 +3207,9 @@ void dryRunBudgetDenialStopsBeforeHandlerResolution() { .setScriptPatchPinnedControlPlaneRequestId("pin-request-1") .build()) .build()); - when(dryRunQuotaService.tryAcquire("1", "script-1", "account:41")).thenReturn(false); + when(dryRunQuotaService.tryAcquire( + "1", "script-1", "account:018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a")) + .thenReturn(false); ScriptEventBindingRepository bindingRepository = Mockito.mock(ScriptEventBindingRepository.class); ScriptEventIngressService service = diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/GrpcClientAuth.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GrpcClientAuth.java index b39011f625..709e5c991f 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/GrpcClientAuth.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GrpcClientAuth.java @@ -53,19 +53,18 @@ public void start(Listener responseListener, Metadata headers) { } static String createBearerToken(JwtUtil jwtUtil, RuntimeIdentity runtimeIdentity) { - Long accountId = SessionContext.currentAccountIdOrNull(); + String accountId = SessionContext.currentAccountIdOrNull(); List globalRoles = SessionContext.getGlobalRoles(); Map> scopedRoles = SessionContext.getScopedRolesMap(); if (accountId == null) { return createInternalBearerToken(jwtUtil, runtimeIdentity); } - String accountIdText = Long.toString(accountId); Map claims = new HashMap<>(); - claims.put("accountId", accountIdText); + claims.put("accountId", accountId); claims.put("globalRoles", globalRoles == null ? List.of() : globalRoles); claims.put("scopedRoles", scopedRoles == null ? Map.of() : scopedRoles); - return jwtUtil.generateToken(accountIdText, claims); + return jwtUtil.generateToken(accountId, claims); } static String createInternalBearerToken(JwtUtil jwtUtil, RuntimeIdentity runtimeIdentity) { diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/JwtClaims.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/JwtClaims.java index adec1fad6a..2c3c5a3510 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/JwtClaims.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/JwtClaims.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.common.security; import io.jsonwebtoken.Claims; +import java.util.UUID; import org.springframework.util.StringUtils; /** Shared helpers for canonical JWT claim extraction and normalization. */ @@ -33,10 +34,32 @@ public static long requireLong(Object value, String claimName, boolean allowZero return parsed; } - public static long requireSignedActorAccountId(Claims claims, String mismatchMessage) { - long subjectAccountId = requireLong(claims.getSubject(), "sub", false); - long claimedAccountId = requireLong(claims.get("accountId"), "accountId", false); - if (subjectAccountId != claimedAccountId) { + /** Returns a canonical, non-nil Account UUID claim without changing its identity. */ + public static String requireAccountId(Object value, String claimName) { + if (!(value instanceof String text)) { + throw new IllegalArgumentException( + value == null ? "Missing claim: " + claimName : "Malformed claim: " + claimName); + } + if (!StringUtils.hasText(text) || "null".equalsIgnoreCase(text)) { + throw new IllegalArgumentException("Missing claim: " + claimName); + } + UUID parsed; + try { + parsed = UUID.fromString(text); + } catch (IllegalArgumentException ex) { + throw new IllegalArgumentException("Malformed claim: " + claimName); + } + if (!parsed.toString().equals(text) + || (parsed.getMostSignificantBits() == 0L && parsed.getLeastSignificantBits() == 0L)) { + throw new IllegalArgumentException("Invalid claim: " + claimName); + } + return text; + } + + public static String requireSignedActorAccountId(Claims claims, String mismatchMessage) { + String subjectAccountId = requireAccountId(claims.getSubject(), "sub"); + String claimedAccountId = requireAccountId(claims.get("accountId"), "accountId"); + if (!subjectAccountId.equals(claimedAccountId)) { throw new IllegalArgumentException(mismatchMessage); } return claimedAccountId; @@ -80,7 +103,7 @@ private static String firstNonBlank(Iterable values) { } public record SignedGameplayRoutingClaims( - long accountId, + String accountId, long tenantId, String worldSlug, String realmSlug, diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/SessionClaims.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/SessionClaims.java index f594d8e5cf..1a87653481 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/SessionClaims.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/SessionClaims.java @@ -17,6 +17,9 @@ public record SessionClaims( String serviceInstanceId) { public SessionClaims { + if (accountId != null) { + accountId = JwtClaims.requireAccountId(accountId, "accountId"); + } globalRoles = globalRoles == null ? List.of() : List.copyOf(globalRoles); scopedRoles = scopedRoles == null @@ -29,11 +32,18 @@ public record SessionClaims( public static SessionClaims fromJwt(Jws jwt) { Claims payload = jwt.getPayload(); + boolean internalService = Boolean.TRUE.equals(payload.get("internalService", Boolean.class)); + String accountId = null; + if (payload.containsKey("accountId")) { + accountId = JwtClaims.requireSignedActorAccountId(payload, "JWT subject/accountId mismatch"); + } else if (!internalService) { + throw new IllegalArgumentException("Missing claim: accountId"); + } return new SessionClaims( - JwtClaims.claimText(payload.get("accountId")), + accountId, extractGlobalRoles(payload.get("globalRoles")), extractScopedRoles(payload.get("scopedRoles")), - Boolean.TRUE.equals(payload.get("internalService", Boolean.class)), + internalService, JwtClaims.claimText(payload.get("serviceName")), JwtClaims.claimText(payload.get("serviceInstanceId"))); } diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/SessionContext.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/SessionContext.java index 5383df3e6f..7f2914bcb6 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/SessionContext.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/SessionContext.java @@ -107,16 +107,17 @@ public static boolean hasAuthenticatedCallerContext() { } /** - * Returns the current account id when present. + * Returns the current canonical account UUID when present. * - *

Blank or missing claims return {@code null}. Malformed or non-positive claims fail closed. + *

Blank or missing claims return {@code null}. Malformed, nil, or noncanonical claims fail + * closed. */ - public static Long currentAccountIdOrNull() { + public static String currentAccountIdOrNull() { ClaimsData data = currentData(); if (data == null || data.accountId == null || data.accountId.isBlank()) { return null; } - return JwtClaims.requireLong(data.accountId, "accountId", false); + return JwtClaims.requireAccountId(data.accountId, "accountId"); } /** Throws 403 when the current caller cannot act on the provided tenant. */ @@ -129,25 +130,25 @@ public static void requireTenantAccess(Long tenantId) { } } - /** Returns whether the current caller matches the provided account id. */ - public static boolean isCurrentAccount(Long accountId) { - if (accountId == null || accountId <= 0L) { + /** Returns whether the current caller exactly matches the provided canonical account UUID. */ + public static boolean isCurrentAccount(String accountId) { + if (accountId == null || accountId.isBlank()) { return false; } try { - return currentAccountId() == accountId; + return currentAccountId().equals(JwtClaims.requireAccountId(accountId, "accountId")); } catch (IllegalArgumentException ex) { return false; } } /** Returns whether the current caller can act on the provided tenant-owned account surface. */ - public static boolean hasAccountAccess(Long tenantId, Long accountId) { + public static boolean hasAccountAccess(Long tenantId, String accountId) { return isCurrentAccount(accountId) || hasTenantAccess(tenantId); } /** Throws 403 when the current caller cannot act on the provided account surface. */ - public static void requireAccountAccess(Long tenantId, Long accountId) { + public static void requireAccountAccess(Long tenantId, String accountId) { if (!hasAccountAccess(tenantId, accountId)) { throw new ResponseStatusException(HttpStatus.FORBIDDEN, "Account access required"); } @@ -173,12 +174,12 @@ private static boolean hasGlobalTenantAccess() { return data.globalRoles.contains("platformAdmin") || data.globalRoles.contains("moderator"); } - private static long currentAccountId() { + private static String currentAccountId() { ClaimsData data = currentData(); if (data == null || data.accountId == null || data.accountId.isBlank()) { throw new IllegalArgumentException("accountId is required"); } - return JwtClaims.requireLong(data.accountId, "accountId", false); + return JwtClaims.requireAccountId(data.accountId, "accountId"); } static Context grpcContextWith(SessionClaims claims) { diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/security/GrpcClientAuthTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/security/GrpcClientAuthTest.java index 31140c22c0..deac7511b5 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/security/GrpcClientAuthTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/security/GrpcClientAuthTest.java @@ -19,6 +19,7 @@ import org.junit.jupiter.api.Test; class GrpcClientAuthTest { + private static final String ACCOUNT_ID = "11111111-1111-4111-8111-111111111111"; private static final Metadata.Key AUTH_HEADER = Metadata.Key.of("Authorization", Metadata.ASCII_STRING_MARSHALLER); @@ -38,15 +39,21 @@ void attachUsesCurrentSessionContextPerCall() { TestStub stub = new TestStub(channel, CallOptions.DEFAULT); TestStub customized = GrpcClientAuth.attach(stub, jwtUtil, runtimeIdentity); - SessionContext.setContext("1", List.of("player"), Map.of()); + SessionContext.setContext(ACCOUNT_ID, List.of("player"), Map.of()); customized.invoke(); String firstToken = bearerToken(channel.lastAuthorization()); - assertThat(jwtUtil.parseToken(firstToken).getPayload().getSubject()).isEqualTo("1"); + assertThat(jwtUtil.parseToken(firstToken).getPayload().getSubject()).isEqualTo(ACCOUNT_ID); + assertThat(jwtUtil.parseToken(firstToken).getPayload().get("accountId", String.class)) + .isEqualTo(ACCOUNT_ID); - SessionContext.setContext("2", List.of("player"), Map.of()); + String secondAccountId = "22222222-2222-4222-8222-222222222222"; + SessionContext.setContext(secondAccountId, List.of("player"), Map.of()); customized.invoke(); String secondToken = bearerToken(channel.lastAuthorization()); - assertThat(jwtUtil.parseToken(secondToken).getPayload().getSubject()).isEqualTo("2"); + assertThat(jwtUtil.parseToken(secondToken).getPayload().getSubject()) + .isEqualTo(secondAccountId); + assertThat(jwtUtil.parseToken(secondToken).getPayload().get("accountId", String.class)) + .isEqualTo(secondAccountId); assertThat(secondToken).isNotEqualTo(firstToken); } @@ -77,7 +84,7 @@ void attachRejectsMalformedCurrentAccountClaim() { TestStub stub = new TestStub(channel, CallOptions.DEFAULT); TestStub customized = GrpcClientAuth.attach(stub, jwtUtil, runtimeIdentity); - SessionContext.setContext("not-a-long", List.of("player"), Map.of()); + SessionContext.setContext("not-a-uuid", List.of("player"), Map.of()); assertThrows(IllegalArgumentException.class, customized::invoke); assertThat(channel.lastAuthorization()).isNull(); diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/security/SessionClaimsTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/security/SessionClaimsTest.java index 238ea418ee..73cf6db1f8 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/security/SessionClaimsTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/security/SessionClaimsTest.java @@ -1,5 +1,8 @@ package net.firedevops.firemud.common.security; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; @@ -7,11 +10,12 @@ import org.junit.jupiter.api.Test; class SessionClaimsTest { + private static final String ACCOUNT_ID = "11111111-1111-4111-8111-111111111111"; @Test void privilegedRoleCheckStillRecognizesGlobalControlPlaneRoles() { SessionClaims claims = - new SessionClaims("11", List.of("platformAdmin"), Map.of(), false, null, null); + new SessionClaims(ACCOUNT_ID, List.of("platformAdmin"), Map.of(), false, null, null); assertTrue(claims.hasPrivilegedRole()); } @@ -20,8 +24,88 @@ void privilegedRoleCheckStillRecognizesGlobalControlPlaneRoles() { void privilegedRoleCheckStillRecognizesTenantScopedControlPlaneRoles() { SessionClaims claims = new SessionClaims( - "11", List.of(), Map.of("7", List.of("tenantAdmin", "moderator")), false, null, null); + ACCOUNT_ID, + List.of(), + Map.of("7", List.of("tenantAdmin", "moderator")), + false, + null, + null); assertTrue(claims.hasPrivilegedRole()); } + + @Test + void fromJwtPreservesCanonicalAccountSubjectAndClaim() { + JwtUtil jwtUtil = new JwtUtil("mysecretkey123456789012345678901", 30_000L); + SessionClaims claims = + SessionClaims.fromJwt( + jwtUtil.parseToken(jwtUtil.generateToken(ACCOUNT_ID, Map.of("accountId", ACCOUNT_ID)))); + + assertEquals(ACCOUNT_ID, claims.accountId()); + } + + @Test + void fromJwtRejectsNonUuidOrMismatchedAccountIdentity() { + JwtUtil jwtUtil = new JwtUtil("mysecretkey123456789012345678901", 30_000L); + String otherAccountId = "22222222-2222-4222-8222-222222222222"; + + assertThrows( + IllegalArgumentException.class, + () -> + SessionClaims.fromJwt( + jwtUtil.parseToken(jwtUtil.generateToken("42", Map.of("accountId", "42"))))); + assertThrows( + IllegalArgumentException.class, + () -> + SessionClaims.fromJwt( + jwtUtil.parseToken( + jwtUtil.generateToken(ACCOUNT_ID, Map.of("accountId", otherAccountId))))); + assertThrows( + IllegalArgumentException.class, + () -> SessionClaims.fromJwt(jwtUtil.parseToken(jwtUtil.generateToken("user", Map.of())))); + } + + @Test + void rejectsNumericAccountIdentityWhenClaimsAreConstructedDirectly() { + assertThrows( + IllegalArgumentException.class, + () -> new SessionClaims("42", List.of(), Map.of(), false, null, null)); + } + + @Test + void fromJwtAllowsInternalWorkloadWithoutAccountIdentity() { + JwtUtil jwtUtil = new JwtUtil("mysecretkey123456789012345678901", 30_000L); + SessionClaims claims = + SessionClaims.fromJwt( + jwtUtil.parseToken( + jwtUtil.generateToken( + "world-management-service", Map.of("internalService", true)))); + + assertNull(claims.accountId()); + assertTrue(claims.internalService()); + } + + @Test + void internalWorkloadFlagDoesNotDiscardMalformedOrMismatchedAccountIdentity() { + JwtUtil jwtUtil = new JwtUtil("mysecretkey123456789012345678901", 30_000L); + for (Object accountId : List.of("", " ", "null", "NULL", 42L, List.of(), ACCOUNT_ID)) { + assertThrows( + IllegalArgumentException.class, + () -> + SessionClaims.fromJwt( + jwtUtil.parseToken( + jwtUtil.generateToken( + "world-management-service", + Map.of("internalService", true, "accountId", accountId))))); + } + } + + @Test + void rejectsPresentBlankAccountIdentityWhenClaimsAreConstructedDirectly() { + for (String accountId : List.of("", " ", "null")) { + assertThrows( + IllegalArgumentException.class, + () -> new SessionClaims(accountId, List.of(), Map.of(), true, null, null)); + } + } } diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/security/SessionContextTenantAccessTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/security/SessionContextTenantAccessTest.java index 9ae1889a51..da79dac8a7 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/security/SessionContextTenantAccessTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/security/SessionContextTenantAccessTest.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.common.security; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -13,6 +14,8 @@ import org.springframework.web.server.ResponseStatusException; class SessionContextTenantAccessTest { + private static final String ACCOUNT_ID = "1111111a-1111-4111-8111-111111111111"; + private static final String OTHER_ACCOUNT_ID = "22222222-2222-4222-8222-222222222222"; @AfterEach void clear() { @@ -21,7 +24,8 @@ void clear() { @Test void allowsGlobalAdminAcrossTenants() { - SessionContext.setContext("1", List.of("platformAdmin"), Map.of("7", List.of("tenantAdmin"))); + SessionContext.setContext( + ACCOUNT_ID, List.of("platformAdmin"), Map.of("7", List.of("tenantAdmin"))); assertTrue(SessionContext.hasTenantAccess(42L)); assertDoesNotThrow(() -> SessionContext.requireTenantAccess(42L)); @@ -29,7 +33,7 @@ void allowsGlobalAdminAcrossTenants() { @Test void allowsMatchingScopedTenantOnly() { - SessionContext.setContext("1", List.of(), Map.of("7", List.of("moderator"))); + SessionContext.setContext(ACCOUNT_ID, List.of(), Map.of("7", List.of("moderator"))); assertTrue(SessionContext.hasTenantAccess(7L)); assertDoesNotThrow(() -> SessionContext.requireTenantAccess(7L)); @@ -39,39 +43,45 @@ void allowsMatchingScopedTenantOnly() { @Test void allowsCurrentAccountWithoutTenantRole() { - SessionContext.setContext("42", List.of(), Map.of()); - - assertTrue(SessionContext.hasAccountAccess(7L, 42L)); - assertTrue(SessionContext.isCurrentAccount(42L)); - assertDoesNotThrow(() -> SessionContext.requireAccountAccess(7L, 42L)); - assertFalse(SessionContext.hasAccountAccess(7L, 43L)); - assertFalse(SessionContext.isCurrentAccount(43L)); - assertThrows(ResponseStatusException.class, () -> SessionContext.requireAccountAccess(7L, 43L)); + SessionContext.setContext(ACCOUNT_ID, List.of(), Map.of()); + + assertTrue(SessionContext.hasAccountAccess(7L, ACCOUNT_ID)); + assertTrue(SessionContext.isCurrentAccount(ACCOUNT_ID)); + assertDoesNotThrow(() -> SessionContext.requireAccountAccess(7L, ACCOUNT_ID)); + assertFalse(SessionContext.hasAccountAccess(7L, OTHER_ACCOUNT_ID)); + assertFalse(SessionContext.isCurrentAccount(OTHER_ACCOUNT_ID)); + assertThrows( + ResponseStatusException.class, + () -> SessionContext.requireAccountAccess(7L, OTHER_ACCOUNT_ID)); } @Test - void currentAccountAccessRejectsNonPositiveAccountIds() { - SessionContext.setContext("0", List.of(), Map.of()); - - assertFalse(SessionContext.isCurrentAccount(0L)); - assertFalse(SessionContext.hasAccountAccess(7L, 0L)); - assertThrows(ResponseStatusException.class, () -> SessionContext.requireAccountAccess(7L, 0L)); + void currentAccountAccessRejectsNumericAndNilAccountIds() { + SessionContext.setContext(ACCOUNT_ID, List.of(), Map.of()); + + String nilAccountId = "00000000-0000-0000-0000-000000000000"; + assertFalse(SessionContext.isCurrentAccount("42")); + assertFalse(SessionContext.hasAccountAccess(7L, "42")); + assertFalse(SessionContext.isCurrentAccount(nilAccountId)); + assertThrows( + ResponseStatusException.class, () -> SessionContext.requireAccountAccess(7L, "42")); } @Test - void currentAccountAccessRejectsNonPositiveCurrentAccountClaim() { - SessionContext.setContext("-42", List.of(), Map.of()); + void currentAccountAccessRejectsNumericCurrentAccountClaim() { + SessionContext.setContext("42", List.of(), Map.of()); - assertFalse(SessionContext.isCurrentAccount(42L)); - assertFalse(SessionContext.hasAccountAccess(7L, 42L)); - assertThrows(ResponseStatusException.class, () -> SessionContext.requireAccountAccess(7L, 42L)); + assertFalse(SessionContext.isCurrentAccount(ACCOUNT_ID)); + assertFalse(SessionContext.hasAccountAccess(7L, ACCOUNT_ID)); + assertThrows( + ResponseStatusException.class, () -> SessionContext.requireAccountAccess(7L, ACCOUNT_ID)); } @Test - void currentAccountIdOrNullReturnsParsedAccountId() { - SessionContext.setContext("42", List.of(), Map.of()); + void currentAccountIdOrNullReturnsExactCanonicalUuid() { + SessionContext.setContext(ACCOUNT_ID, List.of(), Map.of()); - assertTrue(SessionContext.currentAccountIdOrNull() == 42L); + assertEquals(ACCOUNT_ID, SessionContext.currentAccountIdOrNull()); } @Test @@ -84,11 +94,17 @@ void currentAccountIdOrNullReturnsNullWhenClaimMissing() { } @Test - void currentAccountIdOrNullRejectsMalformedOrNonPositiveClaim() { - SessionContext.setContext("not-a-long", List.of(), Map.of()); + void currentAccountIdOrNullRejectsMalformedNumericNilAndNoncanonicalClaims() { + SessionContext.setContext("not-a-uuid", List.of(), Map.of()); + assertThrows(IllegalArgumentException.class, SessionContext::currentAccountIdOrNull); + + SessionContext.setContext("42", List.of(), Map.of()); + assertThrows(IllegalArgumentException.class, SessionContext::currentAccountIdOrNull); + + SessionContext.setContext("00000000-0000-0000-0000-000000000000", List.of(), Map.of()); assertThrows(IllegalArgumentException.class, SessionContext::currentAccountIdOrNull); - SessionContext.setContext("0", List.of(), Map.of()); + SessionContext.setContext(ACCOUNT_ID.toUpperCase(java.util.Locale.ROOT), List.of(), Map.of()); assertThrows(IllegalArgumentException.class, SessionContext::currentAccountIdOrNull); } @@ -108,7 +124,7 @@ void hasAuthenticatedCallerContextIgnoresBlankAccountWithoutRoles() { @Test void hasAuthenticatedCallerContextTreatsMalformedAccountClaimAsPresent() { - SessionContext.setContext("not-a-long", List.of(), Map.of()); + SessionContext.setContext("not-a-uuid", List.of(), Map.of()); assertTrue(SessionContext.hasAuthenticatedCallerContext()); } diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java index 7c41c48784..bb83f47a15 100644 --- a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java +++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java @@ -21,6 +21,7 @@ import org.mockito.Mockito; class AuthTokenInterceptorTest { + private static final String ACCOUNT_ID = "11111111-1111-4111-8111-111111111111"; private static final Metadata.Key AUTH_HEADER = Metadata.Key.of("Authorization", Metadata.ASCII_STRING_MARSHALLER); private static final MethodDescriptor METHOD = @@ -51,9 +52,9 @@ void rejectsMalformedJwtClaims() { Metadata headers = new Metadata(); String token = jwtUtil.generateToken( - "account", + ACCOUNT_ID, Map.of( - "accountId", "account", "globalRoles", "platformAdmin", "scopedRoles", Map.of())); + "accountId", ACCOUNT_ID, "globalRoles", "platformAdmin", "scopedRoles", Map.of())); headers.put(AUTH_HEADER, "Bearer " + token); interceptor.interceptCall(call, headers, next); @@ -67,6 +68,48 @@ void rejectsMalformedJwtClaims() { assertThat(SessionContext.getScopedRolesMap()).isEmpty(); } + @Test + void rejectsPresentBlankAccountIdOnInternalServiceTokenAndClearsPriorContext() { + AuthTokenInterceptor interceptor = new AuthTokenInterceptor(jwtUtil); + @SuppressWarnings({"rawtypes", "unchecked"}) + ServerCall call = Mockito.mock(ServerCall.class); + @SuppressWarnings({"rawtypes", "unchecked"}) + ServerCallHandler next = Mockito.mock(ServerCallHandler.class); + Mockito.when(call.getMethodDescriptor()).thenReturn(METHOD); + + seedThreadLocalInternalServiceState(); + assertThat(SessionContext.isInternalService()).isTrue(); + assertThat(SessionContext.getServiceName()).isEqualTo("seeded-service"); + + Metadata headers = new Metadata(); + String token = + jwtUtil.generateToken( + ACCOUNT_ID, + Map.of( + "accountId", + "", + "globalRoles", + java.util.List.of(), + "scopedRoles", + Map.of(), + "internalService", + true, + "serviceName", + "game-logic-service")); + headers.put(AUTH_HEADER, "Bearer " + token); + + interceptor.interceptCall(call, headers, next); + + ArgumentCaptor statusCaptor = ArgumentCaptor.forClass(Status.class); + Mockito.verify(call).close(statusCaptor.capture(), Mockito.any(Metadata.class)); + assertThat(statusCaptor.getValue().getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); + Mockito.verify(next, Mockito.never()).startCall(Mockito.eq(call), Mockito.any(Metadata.class)); + assertThat(SessionContext.getAccountId()).isNull(); + assertThat(SessionContext.isInternalService()).isFalse(); + assertThat(SessionContext.getServiceName()).isNull(); + assertThat(SessionContext.getServiceInstanceId()).isNull(); + } + @Test void appliesSessionContextDuringCallbacksAndClearsAfterCompletion() { AuthTokenInterceptor interceptor = new AuthTokenInterceptor(jwtUtil); @@ -96,8 +139,6 @@ public void onComplete() { jwtUtil.generateToken( "service:game-logic-service", Map.of( - "accountId", - "", "globalRoles", java.util.List.of(), "scopedRoles", @@ -198,7 +239,7 @@ public void onHalfClose() { private void seedThreadLocalInternalServiceState() { SessionContext.setContext( - "", java.util.List.of(), Map.of(), true, "seeded-service", "seeded-instance"); + null, java.util.List.of(), Map.of(), true, "seeded-service", "seeded-instance"); } private Metadata internalServiceHeaders() { @@ -207,8 +248,6 @@ private Metadata internalServiceHeaders() { jwtUtil.generateToken( "service:game-logic-service", Map.of( - "accountId", - "", "globalRoles", java.util.List.of(), "scopedRoles", diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/HttpJwtAuthInterceptorTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/HttpJwtAuthInterceptorTest.java index 72c80b55a2..75b16bdf16 100644 --- a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/HttpJwtAuthInterceptorTest.java +++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/HttpJwtAuthInterceptorTest.java @@ -19,6 +19,8 @@ import org.springframework.mock.web.MockHttpServletResponse; class HttpJwtAuthInterceptorTest { + private static final String ACCOUNT_ID = "11111111-1111-4111-8111-111111111111"; + private final JwtUtil jwtUtil = new JwtUtil("testsecretkeytestsecretkeytest1234", 3600000L); @AfterEach @@ -78,8 +80,8 @@ void populatesSessionForAuthenticatedRequest() throws Exception { new HttpJwtAuthInterceptor(jwtUtil, authenticatedProperties()); String token = jwtUtil.generateToken( - "user", - Map.of("accountId", "user", "scopedRoles", Map.of("7", List.of("tenantAdmin")))); + ACCOUNT_ID, + Map.of("accountId", ACCOUNT_ID, "scopedRoles", Map.of("7", List.of("tenantAdmin")))); MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader(HttpHeaders.AUTHORIZATION, "Bearer " + token); MockHttpServletResponse response = new MockHttpServletResponse(); @@ -87,7 +89,7 @@ void populatesSessionForAuthenticatedRequest() throws Exception { boolean result = interceptor.preHandle(request, response, new Object()); assertTrue(result); - assertEquals("user", SessionContext.getAccountId()); + assertEquals(ACCOUNT_ID, SessionContext.getAccountId()); assertEquals(List.of("tenantAdmin"), SessionContext.getScopedRoles("7")); interceptor.afterCompletion(request, response, new Object(), null); assertTrue(SessionContext.getGlobalRoles().isEmpty()); @@ -97,7 +99,7 @@ void populatesSessionForAuthenticatedRequest() throws Exception { void privilegedModeRejectsNonPrivilegedCaller() throws Exception { HttpJwtAuthInterceptor interceptor = new HttpJwtAuthInterceptor(jwtUtil, privilegedProperties()); - String token = jwtUtil.generateToken("user", Map.of("accountId", "user")); + String token = jwtUtil.generateToken(ACCOUNT_ID, Map.of("accountId", ACCOUNT_ID)); MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader(HttpHeaders.AUTHORIZATION, "Bearer " + token); MockHttpServletResponse response = new MockHttpServletResponse(); @@ -140,10 +142,10 @@ void rejectsMalformedGlobalRolesClaimShape() throws Exception { new HttpJwtAuthInterceptor(jwtUtil, authenticatedProperties()); String token = jwtUtil.generateToken( - "user", + ACCOUNT_ID, Map.of( "accountId", - "user", + ACCOUNT_ID, "globalRoles", "platformAdmin", "scopedRoles", diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/JwtClaimsTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/JwtClaimsTest.java index 97c999e90d..b86c3c053f 100644 --- a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/JwtClaimsTest.java +++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/JwtClaimsTest.java @@ -6,11 +6,15 @@ import io.jsonwebtoken.Claims; import java.util.List; import java.util.Map; +import java.util.UUID; import net.firedevops.firemud.common.security.JwtClaims; import net.firedevops.firemud.common.security.JwtUtil; import org.junit.jupiter.api.Test; class JwtClaimsTest { + private static final String ACCOUNT_ID = "1111111a-1111-4111-8111-111111111111"; + private static final String OTHER_ACCOUNT_ID = "22222222-2222-4222-8222-222222222222"; + @Test void requireLongParsesNumericTextAndRejectsInvalidValues() { assertEquals(7L, JwtClaims.requireLong("7", "accountId", false)); @@ -46,13 +50,16 @@ void requireSignedActorAccountIdRejectsMalformedOrMismatchedAccountClaims() { JwtUtil jwtUtil = new JwtUtil("mysecretkey123456789012345678901", 30_000L); Claims validClaims = - jwtUtil.parseToken(jwtUtil.generateToken("11", Map.of("accountId", "11"))).getPayload(); + jwtUtil + .parseToken(jwtUtil.generateToken(ACCOUNT_ID, Map.of("accountId", ACCOUNT_ID))) + .getPayload(); assertEquals( - 11L, JwtClaims.requireSignedActorAccountId(validClaims, "signed token account mismatch")); + ACCOUNT_ID, + JwtClaims.requireSignedActorAccountId(validClaims, "signed token account mismatch")); Claims malformedSubjectClaims = jwtUtil - .parseToken(jwtUtil.generateToken("not-a-number", Map.of("accountId", "11"))) + .parseToken(jwtUtil.generateToken("42", Map.of("accountId", ACCOUNT_ID))) .getPayload(); assertThrows( IllegalArgumentException.class, @@ -62,7 +69,7 @@ void requireSignedActorAccountIdRejectsMalformedOrMismatchedAccountClaims() { Claims malformedAccountClaims = jwtUtil - .parseToken(jwtUtil.generateToken("11", Map.of("accountId", "not-a-number"))) + .parseToken(jwtUtil.generateToken(ACCOUNT_ID, Map.of("accountId", "42"))) .getPayload(); assertThrows( IllegalArgumentException.class, @@ -70,8 +77,85 @@ void requireSignedActorAccountIdRejectsMalformedOrMismatchedAccountClaims() { JwtClaims.requireSignedActorAccountId( malformedAccountClaims, "signed token account mismatch")); + Claims numericAccountClaim = + jwtUtil + .parseToken(jwtUtil.generateToken(ACCOUNT_ID, Map.of("accountId", 42L))) + .getPayload(); + assertThrows( + IllegalArgumentException.class, + () -> + JwtClaims.requireSignedActorAccountId( + numericAccountClaim, "signed token account mismatch")); + + Claims accountIdArrayClaim = + jwtUtil + .parseToken(jwtUtil.generateToken(ACCOUNT_ID, Map.of("accountId", List.of(ACCOUNT_ID)))) + .getPayload(); + assertThrows( + IllegalArgumentException.class, + () -> + JwtClaims.requireSignedActorAccountId( + accountIdArrayClaim, "signed token account mismatch")); + + for (String whitespaceAccountId : List.of(" " + ACCOUNT_ID, ACCOUNT_ID + " ")) { + Claims whitespaceAccountClaim = + jwtUtil + .parseToken( + jwtUtil.generateToken(ACCOUNT_ID, Map.of("accountId", whitespaceAccountId))) + .getPayload(); + assertThrows( + IllegalArgumentException.class, + () -> + JwtClaims.requireSignedActorAccountId( + whitespaceAccountClaim, "signed token account mismatch")); + } + + for (String whitespaceSubject : List.of(" " + ACCOUNT_ID, ACCOUNT_ID + " ")) { + Claims whitespaceSubjectClaim = + jwtUtil + .parseToken(jwtUtil.generateToken(whitespaceSubject, Map.of("accountId", ACCOUNT_ID))) + .getPayload(); + assertThrows( + IllegalArgumentException.class, + () -> + JwtClaims.requireSignedActorAccountId( + whitespaceSubjectClaim, "signed token account mismatch")); + } + + assertThrows( + IllegalArgumentException.class, + () -> JwtClaims.requireAccountId(UUID.fromString(ACCOUNT_ID), "accountId")); + assertThrows( + IllegalArgumentException.class, + () -> JwtClaims.requireAccountId(new String[] {ACCOUNT_ID}, "accountId")); + + String nilAccountId = "00000000-0000-0000-0000-000000000000"; + Claims nilAccountClaims = + jwtUtil + .parseToken(jwtUtil.generateToken(nilAccountId, Map.of("accountId", nilAccountId))) + .getPayload(); + assertThrows( + IllegalArgumentException.class, + () -> + JwtClaims.requireSignedActorAccountId( + nilAccountClaims, "signed token account mismatch")); + + String uppercaseAccountId = ACCOUNT_ID.toUpperCase(java.util.Locale.ROOT); + Claims noncanonicalAccountClaims = + jwtUtil + .parseToken( + jwtUtil.generateToken(uppercaseAccountId, Map.of("accountId", uppercaseAccountId))) + .getPayload(); + assertThrows( + IllegalArgumentException.class, + () -> + JwtClaims.requireSignedActorAccountId( + noncanonicalAccountClaims, "signed token account mismatch")); + Claims mismatchedClaims = - jwtUtil.parseToken(jwtUtil.generateToken("11", Map.of("accountId", "12"))).getPayload(); + jwtUtil + .parseToken(jwtUtil.generateToken(ACCOUNT_ID, Map.of("accountId", OTHER_ACCOUNT_ID))) + .getPayload(); IllegalArgumentException mismatch = assertThrows( IllegalArgumentException.class, @@ -87,10 +171,10 @@ void requireSignedGameplayRoutingClaimsRejectsMalformedOrIncompleteRoutingBundle jwtUtil .parseToken( jwtUtil.generateToken( - "11", + ACCOUNT_ID, Map.of( "accountId", - "11", + ACCOUNT_ID, "tenantId", "7", "worldSlug", @@ -104,7 +188,7 @@ void requireSignedGameplayRoutingClaimsRejectsMalformedOrIncompleteRoutingBundle .getPayload(); JwtClaims.SignedGameplayRoutingClaims routingClaims = JwtClaims.requireSignedGameplayRoutingClaims(validClaims, "signed gameplay mismatch"); - assertEquals(11L, routingClaims.accountId()); + assertEquals(ACCOUNT_ID, routingClaims.accountId()); assertEquals(7L, routingClaims.tenantId()); assertEquals("demo", routingClaims.worldSlug()); assertEquals("production", routingClaims.realmSlug()); @@ -115,10 +199,10 @@ void requireSignedGameplayRoutingClaimsRejectsMalformedOrIncompleteRoutingBundle jwtUtil .parseToken( jwtUtil.generateToken( - "11", + ACCOUNT_ID, Map.of( "accountId", - "11", + ACCOUNT_ID, "tenantId", "7", "worldSlug", @@ -140,10 +224,10 @@ void requireSignedGameplayRoutingClaimsRejectsMalformedOrIncompleteRoutingBundle jwtUtil .parseToken( jwtUtil.generateToken( - "11", + ACCOUNT_ID, Map.of( "accountId", - "11", + ACCOUNT_ID, "tenantId", "7", "worldSlug", diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/EntityManagementApplicationIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/EntityManagementApplicationIntegrationTest.java index 4c2a349cb7..e2ac6a54a2 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/EntityManagementApplicationIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/EntityManagementApplicationIntegrationTest.java @@ -66,7 +66,12 @@ void listCharactersRejectsMalformedPlayableStateScopeWithInvalidArgumentEnvelope throws Exception { String token = JWT_UTIL.generateToken( - "entity-test", Map.of("globalRoles", java.util.List.of("platformAdmin"))); + "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + Map.of( + "accountId", + "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + "globalRoles", + java.util.List.of("platformAdmin"))); HttpRequest request = HttpRequest.newBuilder( URI.create( diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/controller/FriendControllerTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/controller/FriendControllerTest.java index 0bc1164abd..ba96b6db4c 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/controller/FriendControllerTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/controller/FriendControllerTest.java @@ -161,6 +161,11 @@ void addRejectsZeroFriendIdBeforeDispatch() throws Exception { private String tenantToken(String tenantId) { return jwtUtil.generateToken( - "test-account", Map.of("scopedRoles", Map.of(tenantId, List.of("tenantAdmin")))); + "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + Map.of( + "accountId", + "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + "scopedRoles", + Map.of(tenantId, List.of("tenantAdmin")))); } } diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/GameDesignApplicationIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/GameDesignApplicationIntegrationTest.java index dd1bb3959e..97cf3736f5 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/GameDesignApplicationIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/GameDesignApplicationIntegrationTest.java @@ -127,6 +127,8 @@ void uploadAssetRejectsMalformedTenantIdWithInvalidArgumentEnvelope() throws Exc } private String operatorToken() { - return JWT_UTIL.generateToken("operator", Map.of("globalRoles", List.of("platformAdmin"))); + String accountId = "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a"; + return JWT_UTIL.generateToken( + accountId, Map.of("accountId", accountId, "globalRoles", List.of("platformAdmin"))); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java index 20d52a312e..9bef851376 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java @@ -442,7 +442,7 @@ public void queryAccountPresence( long viewerAccountId = ControlPlaneRequestParser.parsePositiveLong( request.getViewerAccountId(), "viewerAccountId"); - requireTenantOrCurrentAccountAccess(tenantId, viewerAccountId); + requireNumericAccountPresenceAccess(tenantId); if (request.getAccountIdsCount() > 100) { throw new IllegalArgumentException("accountIds must contain at most 100 entries"); } @@ -862,11 +862,11 @@ private void requireTenantAccess(long tenantId) { throw new AuthorizationException("Tenant access required"); } - private void requireTenantOrCurrentAccountAccess(long tenantId, long accountId) { - if (SessionContext.hasTenantAccess(tenantId) || isCurrentAccount(accountId)) { + private void requireNumericAccountPresenceAccess(long tenantId) { + if (SessionContext.hasTenantAccess(tenantId)) { return; } - throw new AuthorizationException("Account access required"); + throw new AuthorizationException("Numeric account self-service is unavailable"); } private void requireInstanceAccess(long sessionId) { @@ -898,10 +898,6 @@ private boolean isCurrentAccount(String ownerAccountId) { && ownerAccountId.equals(currentAccountId); } - private boolean isCurrentAccount(long ownerAccountId) { - return SessionContext.isCurrentAccount(ownerAccountId); - } - private net.firedevops.firemud.gamesession.v1.GameplayRealm toGameplayRealm( String worldSlug, RealmView realm) { return net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java index 7dc13bd70a..50d80c77d0 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java @@ -350,6 +350,11 @@ private Map privilegedHeaders() { HttpHeaders.AUTHORIZATION, "Bearer " + JWT_UTIL.generateToken( - "game-session-test", Map.of("globalRoles", List.of("platformAdmin")))); + "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + Map.of( + "accountId", + "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + "globalRoles", + List.of("platformAdmin")))); } } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/controller/GameInstanceControllerTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/controller/GameInstanceControllerTest.java index e617ae2c6c..031d846ae0 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/controller/GameInstanceControllerTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/controller/GameInstanceControllerTest.java @@ -136,7 +136,13 @@ void startSessionRejectsScopedTenantAdmin() throws Exception { StartSessionRequest request = new StartSessionRequest(1L, 7L, "cp-1", "123e4567-e89b-12d3-a456-426614174000"); String token = - jwtUtil.generateToken("user", Map.of("scopedRoles", Map.of("1", List.of("tenantAdmin")))); + jwtUtil.generateToken( + "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + Map.of( + "accountId", + "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + "scopedRoles", + Map.of("1", List.of("tenantAdmin")))); mockMvc .perform( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/controller/PlatformAdminJwtTestSupport.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/controller/PlatformAdminJwtTestSupport.java index 5cc9f2006f..e9a50f176c 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/controller/PlatformAdminJwtTestSupport.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/controller/PlatformAdminJwtTestSupport.java @@ -8,6 +8,8 @@ final class PlatformAdminJwtTestSupport { private PlatformAdminJwtTestSupport() {} static String privilegedToken(JwtUtil jwtUtil) { - return jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String accountId = "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a"; + return jwtUtil.generateToken( + accountId, Map.of("accountId", accountId, "globalRoles", List.of("platformAdmin"))); } } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/controller/SessionRoleControllerTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/controller/SessionRoleControllerTest.java index 9a25c31569..bebb70142c 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/controller/SessionRoleControllerTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/controller/SessionRoleControllerTest.java @@ -55,7 +55,13 @@ void refreshRolesReturnsOk() throws Exception { @Test void refreshRolesRejectsScopedTenantAdmin() throws Exception { String token = - jwtUtil.generateToken("user", Map.of("scopedRoles", Map.of("1", List.of("tenantAdmin")))); + jwtUtil.generateToken( + "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + Map.of( + "accountId", + "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + "scopedRoles", + Map.of("1", List.of("tenantAdmin")))); mockMvc .perform( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/GameSessionGrpcAuthInterceptorTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/GameSessionGrpcAuthInterceptorTest.java index 108b0e86dc..6e00d59a26 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/GameSessionGrpcAuthInterceptorTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/GameSessionGrpcAuthInterceptorTest.java @@ -18,6 +18,7 @@ import org.junit.jupiter.api.Test; class GameSessionGrpcAuthInterceptorTest { + private static final String ACCOUNT_ID = "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a"; private JwtUtil jwtUtil; private AuthTokenInterceptor interceptor; @@ -81,7 +82,9 @@ void rejectsMissingTokenForAutomationHandoff() { @Test void allowsValidTokenForMutableMethods() { - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("player"))); + String token = + jwtUtil.generateToken( + ACCOUNT_ID, Map.of("accountId", ACCOUNT_ID, "globalRoles", List.of("player"))); TestServerCall call = new TestServerCall(GameSessionServiceGrpc.getStartSessionMethod().getFullMethodName()); Metadata headers = new Metadata(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java index 14e42f91eb..2e41d1f5cd 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java @@ -248,7 +248,7 @@ public void onCompleted() {} } @Test - void queryAccountPresenceReturnsMappedSnapshots() { + void queryAccountPresenceTenantRoleReturnsMappedSnapshots() { PingService pingService = Mockito.mock(PingService.class); GameInstanceService gameInstanceService = Mockito.mock(GameInstanceService.class); FeatureFlagService featureFlagService = Mockito.mock(FeatureFlagService.class); @@ -259,7 +259,7 @@ void queryAccountPresenceReturnsMappedSnapshots() { TickService tickService = Mockito.mock(TickService.class); IpConnectionLimiter ipLimiter = Mockito.mock(IpConnectionLimiter.class); SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - SessionContext.setContext("42", List.of(), Map.of()); + SessionContext.setContext(OWNER_ACCOUNT_UUID, List.of(), Map.of("1", List.of("tenantAdmin"))); Mockito.when(accountPresenceQueryService.queryAccountPresence(1L, 42L, List.of(7L))) .thenReturn( List.of( @@ -331,6 +331,58 @@ public void onCompleted() {} ref.get().getPresences(0).getRecentDisposition()); } + @Test + void queryAccountPresenceDeniesNumericSelfServiceForCanonicalAccountSubject() { + PingService pingService = Mockito.mock(PingService.class); + GameInstanceService gameInstanceService = Mockito.mock(GameInstanceService.class); + FeatureFlagService featureFlagService = Mockito.mock(FeatureFlagService.class); + TextCommandInterpreter textCommandInterpreter = Mockito.mock(TextCommandInterpreter.class); + GameInstanceRepository gameInstanceRepository = Mockito.mock(GameInstanceRepository.class); + AccountPresenceQueryService accountPresenceQueryService = + Mockito.mock(AccountPresenceQueryService.class); + TickService tickService = Mockito.mock(TickService.class); + IpConnectionLimiter ipLimiter = Mockito.mock(IpConnectionLimiter.class); + SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); + SessionContext.setContext(OWNER_ACCOUNT_UUID, List.of(), Map.of()); + GameSessionGrpcService service = + newService( + pingService, + gameInstanceService, + featureFlagService, + textCommandInterpreter, + gameInstanceRepository, + accountPresenceQueryService, + tickService, + meterRegistry, + ipLimiter); + + AtomicReference ref = new AtomicReference<>(); + service.queryAccountPresence( + QueryAccountPresenceRequest.newBuilder() + .setTenantId("1") + .setViewerAccountId("42") + .addAccountIds("42") + .build(), + new StreamObserver<>() { + @Override + public void onNext(QueryAccountPresenceResponse value) { + ref.set(value); + } + + @Override + public void onError(Throwable t) { + fail(t); + } + + @Override + public void onCompleted() {} + }); + + assertEquals("PERMISSION_DENIED", ref.get().getError().getCode()); + assertEquals("Numeric account self-service is unavailable", ref.get().getError().getMessage()); + Mockito.verifyNoInteractions(accountPresenceQueryService); + } + @Test void queryAccountPresenceRejectsMalformedAccountId() { PingService pingService = Mockito.mock(PingService.class); @@ -343,7 +395,7 @@ void queryAccountPresenceRejectsMalformedAccountId() { TickService tickService = Mockito.mock(TickService.class); IpConnectionLimiter ipLimiter = Mockito.mock(IpConnectionLimiter.class); SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - SessionContext.setContext("42", List.of(), Map.of()); + SessionContext.setContext(OWNER_ACCOUNT_UUID, List.of(), Map.of("1", List.of("tenantAdmin"))); GameSessionGrpcService service = newService( pingService, @@ -395,7 +447,7 @@ void queryAccountPresenceRejectsZeroAccountId() { TickService tickService = Mockito.mock(TickService.class); IpConnectionLimiter ipLimiter = Mockito.mock(IpConnectionLimiter.class); SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - SessionContext.setContext("42", List.of(), Map.of()); + SessionContext.setContext(OWNER_ACCOUNT_UUID, List.of(), Map.of("1", List.of("tenantAdmin"))); GameSessionGrpcService service = newService( pingService, @@ -447,7 +499,7 @@ void queryAccountPresenceRejectsTooManyAccountIdsBeforeParsing() { TickService tickService = Mockito.mock(TickService.class); IpConnectionLimiter ipLimiter = Mockito.mock(IpConnectionLimiter.class); SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - SessionContext.setContext("42", List.of(), Map.of()); + SessionContext.setContext(OWNER_ACCOUNT_UUID, List.of(), Map.of("1", List.of("tenantAdmin"))); GameSessionGrpcService service = newService( pingService, diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/SessionActorReaders.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/SessionActorReaders.java index 09d353edb4..8869c64ddc 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/SessionActorReaders.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/SessionActorReaders.java @@ -8,11 +8,11 @@ final class SessionActorReaders { private SessionActorReaders() {} static String actorPrincipalOrInternalService() { - Long accountId = currentAccountIdOrNull(); - return accountId == null ? "internal-service" : Long.toString(accountId); + String accountId = currentAccountIdOrNull(); + return accountId == null ? "internal-service" : accountId; } - static Long currentAccountIdOrNull() { + static String currentAccountIdOrNull() { try { return SessionContext.currentAccountIdOrNull(); } catch (IllegalArgumentException ex) { diff --git a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java index 307c481ee4..20da86ad93 100644 --- a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java +++ b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java @@ -79,6 +79,7 @@ class LoggingAdminApplicationIntegrationTest { private static final HttpClient HTTP_CLIENT = HttpClient.newHttpClient(); private static final Duration HTTP_REQUEST_TIMEOUT = Duration.ofSeconds(10); + private static final String ACCOUNT_UUID = "550e8400-e29b-41d4-a716-446655440000"; private static final JwtUtil JWT_UTIL = new JwtUtil("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 3600000L); @@ -975,7 +976,8 @@ private static String digest(byte[] payload) { void pingEndpointReturnsPong() throws Exception { String token = JWT_UTIL.generateToken( - "logging-admin-test", Map.of("globalRoles", java.util.List.of("platformAdmin"))); + ACCOUNT_UUID, + Map.of("accountId", ACCOUNT_UUID, "globalRoles", java.util.List.of("platformAdmin"))); HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/ping")) .timeout(HTTP_REQUEST_TIMEOUT) @@ -1116,9 +1118,9 @@ void remoteFollowupsRejectMalformedPointerVersionWithInvalidArgumentEnvelope() t private String tenantAdminToken(long tenantId) { return JWT_UTIL.generateToken( - "logging-admin-test", + ACCOUNT_UUID, Map.of( - "accountId", "42", + "accountId", ACCOUNT_UUID, "globalRoles", java.util.List.of("platformAdmin"), "scopedRoles", Map.of(Long.toString(tenantId), java.util.List.of("tenantAdmin")))); } diff --git a/services/logging-admin-service/src/test/java/net/firedevops/firemud/loggingadmin/AccountJwtTestTokens.java b/services/logging-admin-service/src/test/java/net/firedevops/firemud/loggingadmin/AccountJwtTestTokens.java new file mode 100644 index 0000000000..082c8373c8 --- /dev/null +++ b/services/logging-admin-service/src/test/java/net/firedevops/firemud/loggingadmin/AccountJwtTestTokens.java @@ -0,0 +1,21 @@ +package net.firedevops.firemud.loggingadmin; + +import java.util.HashMap; +import java.util.Map; +import net.firedevops.firemud.common.security.JwtUtil; + +/** Explicit ordinary Account JWT fixtures for Logging & Admin caller tests. */ +public final class AccountJwtTestTokens { + public static final String ACCOUNT_ID = "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a"; + + private AccountJwtTestTokens() {} + + public static String accountToken(JwtUtil jwtUtil, Map claims) { + if (claims.containsKey("accountId")) { + throw new IllegalArgumentException("accountToken claims must not provide accountId"); + } + Map accountClaims = new HashMap<>(claims); + accountClaims.put("accountId", ACCOUNT_ID); + return jwtUtil.generateToken(ACCOUNT_ID, accountClaims); + } +} diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/AdmissionPointerControllerTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/AdmissionPointerControllerTest.java index ce2a806be5..8bc6838ea5 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/AdmissionPointerControllerTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/AdmissionPointerControllerTest.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.loggingadmin.controller; +import static net.firedevops.firemud.loggingadmin.AccountJwtTestTokens.accountToken; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.Mockito.verifyNoInteractions; @@ -79,7 +80,7 @@ void listPointersReturnsVisibleEntries() throws Exception { "req-1", "pvu-1", Instant.parse("2026-04-18T00:00:00Z")))); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform(get("/admission-pointers").header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) @@ -100,7 +101,7 @@ void listPointersMapsUnavailableCurrentAuthorityToServiceUnavailable() throws Ex new ResponseStatusException( org.springframework.http.HttpStatus.SERVICE_UNAVAILABLE, "current pointer authority unavailable")); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform(get("/admission-pointers").header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) @@ -181,7 +182,7 @@ void auditReturnsEntries() throws Exception { "pvu-1", Instant.parse("2026-04-18T00:00:00Z")))); SessionContext.setContext("user", List.of("platformAdmin"), Map.of()); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -204,7 +205,7 @@ void auditMapsUnavailableAuthorityToServiceUnavailable() throws Exception { org.springframework.http.HttpStatus.SERVICE_UNAVAILABLE, "admission-pointer audit authority unavailable")); SessionContext.setContext("user", List.of("platformAdmin"), Map.of()); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -220,7 +221,7 @@ void auditMapsUnavailableAuthorityToServiceUnavailable() throws Exception { void auditRejectsCrossTenantScopedAdmin() throws Exception { SessionContext.setContext("user", List.of(), Map.of("8", List.of("tenantAdmin"))); String token = - jwtUtil.generateToken("user", Map.of("scopedRoles", Map.of("8", List.of("tenantAdmin")))); + accountToken(jwtUtil, Map.of("scopedRoles", Map.of("8", List.of("tenantAdmin")))); mockMvc .perform( @@ -232,7 +233,7 @@ void auditRejectsCrossTenantScopedAdmin() throws Exception { @Test void auditRejectsMalformedTenantIdBeforeDispatch() throws Exception { SessionContext.setContext("user", List.of("platformAdmin"), Map.of()); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -249,7 +250,7 @@ void auditRejectsMalformedTenantIdBeforeDispatch() throws Exception { void getRuntimeStateReturnsCanonicalRuntimeState() throws Exception { when(admissionPointerService.getRuntimeState(2L, 7L)).thenReturn(runtimeStateDto()); SessionContext.setContext("user", List.of("platformAdmin"), Map.of()); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -270,7 +271,7 @@ void getPreparedVersionUpgradeMapsUnavailableAuthorityToServiceUnavailable() thr org.springframework.http.HttpStatus.SERVICE_UNAVAILABLE, "prepared version-upgrade proof authority unavailable")); SessionContext.setContext("user", List.of("platformAdmin"), Map.of()); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -287,7 +288,7 @@ void getPreparedVersionUpgradeMapsUnavailableAuthorityToServiceUnavailable() thr void getRuntimeStateRejectsCrossTenantScopedAdmin() throws Exception { SessionContext.setContext("user", List.of(), Map.of("8", List.of("tenantAdmin"))); String token = - jwtUtil.generateToken("user", Map.of("scopedRoles", Map.of("8", List.of("tenantAdmin")))); + accountToken(jwtUtil, Map.of("scopedRoles", Map.of("8", List.of("tenantAdmin")))); mockMvc .perform( @@ -299,7 +300,7 @@ void getRuntimeStateRejectsCrossTenantScopedAdmin() throws Exception { @Test void getRuntimeStateRejectsZeroGameInstanceIdBeforeDispatch() throws Exception { SessionContext.setContext("user", List.of("platformAdmin"), Map.of()); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -316,7 +317,7 @@ void getRuntimeStateRejectsZeroGameInstanceIdBeforeDispatch() throws Exception { void getPreparedVersionUpgradeRejectsCrossTenantScopedAdmin() throws Exception { SessionContext.setContext("user", List.of(), Map.of("8", List.of("tenantAdmin"))); String token = - jwtUtil.generateToken("user", Map.of("scopedRoles", Map.of("8", List.of("tenantAdmin")))); + accountToken(jwtUtil, Map.of("scopedRoles", Map.of("8", List.of("tenantAdmin")))); mockMvc .perform( @@ -330,7 +331,7 @@ void validateInstanceCutoverCompatibilityReturnsBoundedCompatibilityProof() thro when(admissionPointerService.validateInstanceCutoverCompatibility(2L, 7L, 9L)) .thenReturn(cutoverCompatibility()); SessionContext.setContext("user", List.of("platformAdmin"), Map.of()); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -346,7 +347,7 @@ void validateInstanceCutoverCompatibilityReturnsBoundedCompatibilityProof() thro void validateInstanceCutoverCompatibilityRejectsCrossTenantScopedAdmin() throws Exception { SessionContext.setContext("user", List.of(), Map.of("8", List.of("tenantAdmin"))); String token = - jwtUtil.generateToken("user", Map.of("scopedRoles", Map.of("8", List.of("tenantAdmin")))); + accountToken(jwtUtil, Map.of("scopedRoles", Map.of("8", List.of("tenantAdmin")))); mockMvc .perform( @@ -359,7 +360,7 @@ void validateInstanceCutoverCompatibilityRejectsCrossTenantScopedAdmin() throws void validateInstanceCutoverCompatibilityRejectsMalformedTargetVersionIdBeforeDispatch() throws Exception { SessionContext.setContext("user", List.of("platformAdmin"), Map.of()); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform( diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/CommandRegistryControllerTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/CommandRegistryControllerTest.java index 4353f94852..34f9e7109c 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/CommandRegistryControllerTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/CommandRegistryControllerTest.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.loggingadmin.controller; +import static net.firedevops.firemud.loggingadmin.AccountJwtTestTokens.accountToken; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; @@ -44,7 +45,7 @@ void validateBuiltInCommandAliasReturnsCanonicalResolution() throws Exception { when(commandRegistryService.validateBuiltInCommandAlias("LoGoFf")) .thenReturn(new BuiltInCommandAliasValidationDto(true, "logout")); SessionContext.setContext("user", List.of("platformAdmin"), Map.of()); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -59,7 +60,7 @@ void validateBuiltInCommandAliasReturnsCanonicalResolution() throws Exception { void validateBuiltInCommandAliasRejectsTenantOnlyCaller() throws Exception { SessionContext.setContext("user", List.of(), Map.of("2", List.of("tenantAdmin"))); String token = - jwtUtil.generateToken("user", Map.of("scopedRoles", Map.of("2", List.of("tenantAdmin")))); + accountToken(jwtUtil, Map.of("scopedRoles", Map.of("2", List.of("tenantAdmin")))); mockMvc .perform( diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/FeatureFlagControllerTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/FeatureFlagControllerTest.java index 291f8b924f..e1966796b1 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/FeatureFlagControllerTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/FeatureFlagControllerTest.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.loggingadmin.controller; +import static net.firedevops.firemud.loggingadmin.AccountJwtTestTokens.accountToken; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -47,7 +48,7 @@ void clear() { @Test void toggleRejectsAuthorizedCallerWhileMutationGateIsUnavailable() throws Exception { ToggleFeatureFlagRequest request = new ToggleFeatureFlagRequest(1L, "demo", true); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -68,7 +69,7 @@ void toggleRejectsAuthorizedCallerWhileMutationGateIsUnavailable() throws Except void toggleRejectsCrossTenantScopedAdmin() throws Exception { ToggleFeatureFlagRequest request = new ToggleFeatureFlagRequest(1L, "demo", true); String token = - jwtUtil.generateToken("user", Map.of("scopedRoles", Map.of("8", List.of("tenantAdmin")))); + accountToken(jwtUtil, Map.of("scopedRoles", Map.of("8", List.of("tenantAdmin")))); mockMvc .perform( @@ -82,7 +83,7 @@ void toggleRejectsCrossTenantScopedAdmin() throws Exception { @Test void toggleRejectsZeroTenantIdBeforeDispatch() throws Exception { ToggleFeatureFlagRequest request = new ToggleFeatureFlagRequest(0L, "demo", true); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform( diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/GameSessionPinControllerTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/GameSessionPinControllerTest.java index b8f183acef..c04d6effbd 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/GameSessionPinControllerTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/GameSessionPinControllerTest.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.loggingadmin.controller; +import static net.firedevops.firemud.loggingadmin.AccountJwtTestTokens.accountToken; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @@ -45,9 +46,7 @@ void clear() { @Test void getPinnedScriptPatchVersionReturnsPinMetadata() throws Exception { when(gameSessionPinService.getPinnedScriptPatchVersion(1L, 7L)).thenReturn(pinnedVersionDto()); - String token = - jwtUtil.generateToken( - "42", Map.of("accountId", "42", "globalRoles", List.of("platformAdmin"))); + String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform(get("/game-session-pins/1/7").header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) @@ -60,9 +59,7 @@ void getPinnedScriptPatchVersionReturnsPinMetadata() throws Exception { void getGameSessionPinConvergenceReturnsConvergenceMetadata() throws Exception { when(gameSessionPinService.getGameSessionPinConvergence(1L, 7L)) .thenReturn(pinConvergenceDto()); - String token = - jwtUtil.generateToken( - "42", Map.of("accountId", "42", "globalRoles", List.of("platformAdmin"))); + String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -77,7 +74,7 @@ void getGameSessionPinConvergenceReturnsConvergenceMetadata() throws Exception { @Test void getPinnedScriptPatchVersionRejectsCrossTenantScopedAdmin() throws Exception { String token = - jwtUtil.generateToken("user", Map.of("scopedRoles", Map.of("8", List.of("tenantAdmin")))); + accountToken(jwtUtil, Map.of("scopedRoles", Map.of("8", List.of("tenantAdmin")))); mockMvc .perform(get("/game-session-pins/1/7").header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) @@ -86,9 +83,7 @@ void getPinnedScriptPatchVersionRejectsCrossTenantScopedAdmin() throws Exception @Test void getPinnedScriptPatchVersionRejectsMalformedTenantIdBeforeDispatch() throws Exception { - String token = - jwtUtil.generateToken( - "42", Map.of("accountId", "42", "globalRoles", List.of("platformAdmin"))); + String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -103,9 +98,7 @@ void getPinnedScriptPatchVersionRejectsMalformedTenantIdBeforeDispatch() throws @Test void getGameSessionPinConvergenceRejectsZeroGameInstanceIdBeforeDispatch() throws Exception { - String token = - jwtUtil.generateToken( - "42", Map.of("accountId", "42", "globalRoles", List.of("platformAdmin"))); + String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform( diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/GameplayCommandControllerTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/GameplayCommandControllerTest.java index 13874bfc53..cb11e04bc4 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/GameplayCommandControllerTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/GameplayCommandControllerTest.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.loggingadmin.controller; +import static net.firedevops.firemud.loggingadmin.AccountJwtTestTokens.accountToken; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @@ -46,7 +47,7 @@ void getGameplayCommandStatusReturnsCanonicalStatus() throws Exception { when(gameplayCommandStatusService.getGameplayCommandStatus(2L, 7L, "cmd-123")) .thenReturn(gameplayCommandStatusDto()); SessionContext.setContext("user", List.of("platformAdmin"), Map.of()); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -63,7 +64,7 @@ void getGameplayCommandStatusReturnsCanonicalStatus() throws Exception { void getGameplayCommandStatusRejectsCrossTenantScopedAdmin() throws Exception { SessionContext.setContext("user", List.of(), Map.of("8", List.of("tenantAdmin"))); String token = - jwtUtil.generateToken("user", Map.of("scopedRoles", Map.of("8", List.of("tenantAdmin")))); + accountToken(jwtUtil, Map.of("scopedRoles", Map.of("8", List.of("tenantAdmin")))); mockMvc .perform( @@ -75,7 +76,7 @@ void getGameplayCommandStatusRejectsCrossTenantScopedAdmin() throws Exception { @Test void getGameplayCommandStatusRejectsZeroTenantIdBeforeDispatch() throws Exception { SessionContext.setContext("user", List.of("platformAdmin"), Map.of()); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -91,7 +92,7 @@ void getGameplayCommandStatusRejectsZeroTenantIdBeforeDispatch() throws Exceptio @Test void getGameplayCommandStatusRejectsZeroGameInstanceIdBeforeDispatch() throws Exception { SessionContext.setContext("user", List.of("platformAdmin"), Map.of()); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform( diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/LogQueryControllerTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/LogQueryControllerTest.java index 42a0ea8083..91e39a4232 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/LogQueryControllerTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/LogQueryControllerTest.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.loggingadmin.controller; +import static net.firedevops.firemud.loggingadmin.AccountJwtTestTokens.accountToken; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; @@ -53,7 +54,7 @@ void clear() { void queryReturnsEntries() throws Exception { QueryLogsRequest request = new QueryLogsRequest(1L, "msg"); when(service.queryLogs(request)).thenReturn(List.of("hello")); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -69,7 +70,7 @@ void queryReturnsEntries() throws Exception { void queryRejectsCrossTenantScopedAdmin() throws Exception { QueryLogsRequest request = new QueryLogsRequest(1L, "msg"); String token = - jwtUtil.generateToken("user", Map.of("scopedRoles", Map.of("8", List.of("tenantAdmin")))); + accountToken(jwtUtil, Map.of("scopedRoles", Map.of("8", List.of("tenantAdmin")))); mockMvc .perform( @@ -83,7 +84,7 @@ void queryRejectsCrossTenantScopedAdmin() throws Exception { @Test void queryRejectsZeroTenantIdBeforeDispatch() throws Exception { QueryLogsRequest request = new QueryLogsRequest(0L, "msg"); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform( diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/ModerationActionControllerTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/ModerationActionControllerTest.java index c414923672..5bbf3e9517 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/ModerationActionControllerTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/ModerationActionControllerTest.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.loggingadmin.controller; +import static net.firedevops.firemud.loggingadmin.AccountJwtTestTokens.accountToken; import static org.mockito.Mockito.verifyNoInteractions; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; @@ -51,7 +52,7 @@ void clear() { @Test void applyRejectsAuthorizedCallerWhileMutationGateIsUnavailable() throws Exception { ApplyModerationActionRequest req = new ApplyModerationActionRequest(1L, 2L, 9L, "ban", ""); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -73,8 +74,7 @@ void applyRejectsAuthorizedCallerWhileMutationGateIsUnavailable() throws Excepti @Test void applyRejectsCrossTenantScopedAdmin() throws Exception { ApplyModerationActionRequest req = new ApplyModerationActionRequest(1L, 2L, 9L, "ban", ""); - String token = - jwtUtil.generateToken("user", Map.of("scopedRoles", Map.of("8", List.of("moderator")))); + String token = accountToken(jwtUtil, Map.of("scopedRoles", Map.of("8", List.of("moderator")))); mockMvc .perform( @@ -88,7 +88,7 @@ void applyRejectsCrossTenantScopedAdmin() throws Exception { @Test void applyRejectsZeroSessionIdBeforeDispatch() throws Exception { ApplyModerationActionRequest req = new ApplyModerationActionRequest(1L, 2L, 0L, "ban", ""); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform( diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/RemoteCommandCoordinatorControllerTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/RemoteCommandCoordinatorControllerTest.java index 84883006b9..651756155f 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/RemoteCommandCoordinatorControllerTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/RemoteCommandCoordinatorControllerTest.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.loggingadmin.controller; +import static net.firedevops.firemud.loggingadmin.AccountJwtTestTokens.accountToken; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @@ -46,7 +47,7 @@ void getRemoteCommandCoordinatorReturnsCanonicalStatus() throws Exception { when(remoteCommandCoordinatorService.getRemoteCommandCoordinator(2L, "coord-123")) .thenReturn(remoteCommandCoordinatorDto()); SessionContext.setContext("user", List.of("platformAdmin"), Map.of()); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -63,7 +64,7 @@ void getRemoteCommandCoordinatorReturnsCanonicalStatus() throws Exception { void getRemoteCommandCoordinatorRejectsCrossTenantScopedAdmin() throws Exception { SessionContext.setContext("user", List.of(), Map.of("8", List.of("tenantAdmin"))); String token = - jwtUtil.generateToken("user", Map.of("scopedRoles", Map.of("8", List.of("tenantAdmin")))); + accountToken(jwtUtil, Map.of("scopedRoles", Map.of("8", List.of("tenantAdmin")))); mockMvc .perform( @@ -77,7 +78,7 @@ void getRemoteCommandCoordinatorRejectsCrossTenantScopedAdmin() throws Exception @Test void getRemoteCommandCoordinatorRejectsMalformedTenantIdBeforeDispatch() throws Exception { SessionContext.setContext("user", List.of("platformAdmin"), Map.of()); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -96,7 +97,7 @@ void listRemoteCommandCoordinatorsReturnsBoundedRows() throws Exception { org.mockito.ArgumentMatchers.eq(2L), org.mockito.ArgumentMatchers.any())) .thenReturn(List.of(remoteCommandCoordinatorDto())); SessionContext.setContext("user", List.of("platformAdmin"), Map.of()); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -111,7 +112,7 @@ void listRemoteCommandCoordinatorsReturnsBoundedRows() throws Exception { @Test void listRemoteCommandCoordinatorsRejectsZeroTenantIdBeforeDispatch() throws Exception { SessionContext.setContext("user", List.of("platformAdmin"), Map.of()); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform( diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/RemoteFollowupControllerTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/RemoteFollowupControllerTest.java index e9a3a050a4..848063ea79 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/RemoteFollowupControllerTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/RemoteFollowupControllerTest.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.loggingadmin.controller; +import static net.firedevops.firemud.loggingadmin.AccountJwtTestTokens.accountToken; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @@ -45,7 +46,7 @@ void clear() { void getRemoteFollowupReturnsCanonicalRow() throws Exception { when(remoteFollowupService.getRemoteFollowup(2L, "rf-1")).thenReturn(remoteFollowupDto()); SessionContext.setContext("user", List.of("platformAdmin"), Map.of()); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -61,7 +62,7 @@ void getRemoteFollowupReturnsCanonicalRow() throws Exception { void getRemoteFollowupRejectsCrossTenantScopedAdmin() throws Exception { SessionContext.setContext("user", List.of(), Map.of("8", List.of("tenantAdmin"))); String token = - jwtUtil.generateToken("user", Map.of("scopedRoles", Map.of("8", List.of("tenantAdmin")))); + accountToken(jwtUtil, Map.of("scopedRoles", Map.of("8", List.of("tenantAdmin")))); mockMvc .perform( @@ -74,7 +75,7 @@ void getRemoteFollowupRejectsCrossTenantScopedAdmin() throws Exception { @Test void getRemoteFollowupRejectsMalformedTenantIdBeforeDispatch() throws Exception { SessionContext.setContext("user", List.of("platformAdmin"), Map.of()); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -101,7 +102,7 @@ void listRemoteFollowupsReturnsCanonicalRows() throws Exception { && Integer.valueOf(10).equals(request.getLimit())))) .thenReturn(List.of(remoteFollowupDto())); SessionContext.setContext("user", List.of("platformAdmin"), Map.of()); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -124,7 +125,7 @@ void listRemoteFollowupsReturnsCanonicalRows() throws Exception { void listRemoteFollowupsRejectsCrossTenantScopedAdmin() throws Exception { SessionContext.setContext("user", List.of(), Map.of("8", List.of("tenantAdmin"))); String token = - jwtUtil.generateToken("user", Map.of("scopedRoles", Map.of("8", List.of("tenantAdmin")))); + accountToken(jwtUtil, Map.of("scopedRoles", Map.of("8", List.of("tenantAdmin")))); mockMvc .perform(get("/remote-followups/2").header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) @@ -136,7 +137,7 @@ void listRemoteFollowupsRejectsCrossTenantScopedAdmin() throws Exception { @Test void listRemoteFollowupsRejectsZeroTenantIdBeforeDispatch() throws Exception { SessionContext.setContext("user", List.of("platformAdmin"), Map.of()); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform(get("/remote-followups/0").header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) @@ -150,7 +151,7 @@ void listRemoteFollowupsRejectsZeroTenantIdBeforeDispatch() throws Exception { @Test void listRemoteFollowupsRejectsZeroPointerVersionBeforeDispatch() throws Exception { SessionContext.setContext("user", List.of("platformAdmin"), Map.of()); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); when(remoteFollowupService.listRemoteFollowups( org.mockito.ArgumentMatchers.eq(2L), org.mockito.ArgumentMatchers.any())) .thenThrow(new IllegalArgumentException("pointerVersion must be positive")); diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/RemoteFollowupResultControllerTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/RemoteFollowupResultControllerTest.java index 1e2a8ea5e5..53a8ec7266 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/RemoteFollowupResultControllerTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/RemoteFollowupResultControllerTest.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.loggingadmin.controller; +import static net.firedevops.firemud.loggingadmin.AccountJwtTestTokens.accountToken; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @@ -46,7 +47,7 @@ void getRemoteFollowupResultReturnsCanonicalRow() throws Exception { when(remoteFollowupResultService.getRemoteFollowupResult(2L, "rr-1")) .thenReturn(remoteResultDto()); SessionContext.setContext("user", List.of("platformAdmin"), Map.of()); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -63,7 +64,7 @@ void getRemoteFollowupResultReturnsCanonicalRow() throws Exception { void getRemoteFollowupResultRejectsCrossTenantScopedAdmin() throws Exception { SessionContext.setContext("user", List.of(), Map.of("8", List.of("tenantAdmin"))); String token = - jwtUtil.generateToken("user", Map.of("scopedRoles", Map.of("8", List.of("tenantAdmin")))); + accountToken(jwtUtil, Map.of("scopedRoles", Map.of("8", List.of("tenantAdmin")))); mockMvc .perform( @@ -77,7 +78,7 @@ void getRemoteFollowupResultRejectsCrossTenantScopedAdmin() throws Exception { @Test void getRemoteFollowupResultRejectsMalformedTenantIdBeforeDispatch() throws Exception { SessionContext.setContext("user", List.of("platformAdmin"), Map.of()); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -96,7 +97,7 @@ void listRemoteFollowupResultsReturnsCanonicalRows() throws Exception { org.mockito.ArgumentMatchers.eq(2L), org.mockito.ArgumentMatchers.any())) .thenReturn(List.of(remoteResultDto())); SessionContext.setContext("user", List.of("platformAdmin"), Map.of()); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -119,7 +120,7 @@ void listRemoteFollowupResultsReturnsCanonicalRows() throws Exception { void listRemoteFollowupResultsRejectsCrossTenantScopedAdmin() throws Exception { SessionContext.setContext("user", List.of(), Map.of("8", List.of("tenantAdmin"))); String token = - jwtUtil.generateToken("user", Map.of("scopedRoles", Map.of("8", List.of("tenantAdmin")))); + accountToken(jwtUtil, Map.of("scopedRoles", Map.of("8", List.of("tenantAdmin")))); mockMvc .perform( @@ -132,7 +133,7 @@ void listRemoteFollowupResultsRejectsCrossTenantScopedAdmin() throws Exception { @Test void listRemoteFollowupResultsRejectsZeroTenantIdBeforeDispatch() throws Exception { SessionContext.setContext("user", List.of("platformAdmin"), Map.of()); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -147,7 +148,7 @@ void listRemoteFollowupResultsRejectsZeroTenantIdBeforeDispatch() throws Excepti @Test void listRemoteFollowupResultsRejectZeroPointerVersionBeforeDispatch() throws Exception { SessionContext.setContext("user", List.of("platformAdmin"), Map.of()); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); when(remoteFollowupResultService.listRemoteFollowupResults( org.mockito.ArgumentMatchers.eq(2L), org.mockito.ArgumentMatchers.any())) .thenThrow(new IllegalArgumentException("pointerVersion must be positive")); diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/SagaDashboardControllerTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/SagaDashboardControllerTest.java index a0fcdcfa44..b87b8bfa3b 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/SagaDashboardControllerTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/SagaDashboardControllerTest.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.loggingadmin.controller; +import static net.firedevops.firemud.loggingadmin.AccountJwtTestTokens.accountToken; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @@ -53,8 +54,8 @@ void listInstancesReturnsData() throws Exception { .header( HttpHeaders.AUTHORIZATION, "Bearer " - + jwtUtil.generateToken( - "user", + + accountToken( + jwtUtil, java.util.Map.of("globalRoles", java.util.List.of("platformAdmin"))))) .andExpect(status().isOk()) .andExpect(jsonPath("$.data[0].sagaName").value("demo")); @@ -71,8 +72,8 @@ void listStepsReturnsData() throws Exception { .header( HttpHeaders.AUTHORIZATION, "Bearer " - + jwtUtil.generateToken( - "user", + + accountToken( + jwtUtil, java.util.Map.of("globalRoles", java.util.List.of("platformAdmin"))))) .andExpect(status().isOk()) .andExpect(jsonPath("$.data[0].name").value("step")); @@ -86,8 +87,8 @@ void listStepsRejectsMalformedIdBeforeDispatch() throws Exception { .header( HttpHeaders.AUTHORIZATION, "Bearer " - + jwtUtil.generateToken( - "user", + + accountToken( + jwtUtil, java.util.Map.of("globalRoles", java.util.List.of("platformAdmin"))))) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.error.code").value("INVALID_ARGUMENT")) @@ -104,8 +105,8 @@ void listStepsRejectsZeroIdBeforeDispatch() throws Exception { .header( HttpHeaders.AUTHORIZATION, "Bearer " - + jwtUtil.generateToken( - "user", + + accountToken( + jwtUtil, java.util.Map.of("globalRoles", java.util.List.of("platformAdmin"))))) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.error.code").value("INVALID_ARGUMENT")) @@ -127,8 +128,8 @@ void listStepsReturnsNotFoundForUnknownSagaInstance() throws Exception { .header( HttpHeaders.AUTHORIZATION, "Bearer " - + jwtUtil.generateToken( - "user", + + accountToken( + jwtUtil, java.util.Map.of("globalRoles", java.util.List.of("platformAdmin"))))) .andExpect(status().isNotFound()) .andExpect(jsonPath("$.error.code").value("NOT_FOUND")) diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/TickRemediationControllerTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/TickRemediationControllerTest.java index 674a5aa069..ff7275df81 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/TickRemediationControllerTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/TickRemediationControllerTest.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.loggingadmin.controller; +import static net.firedevops.firemud.loggingadmin.AccountJwtTestTokens.accountToken; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; @@ -70,9 +71,7 @@ void getRuntimeOwnershipStatusReturnsStatusDto() throws Exception { 2L, 13L, 2000L)); - String token = - jwtUtil.generateToken( - "42", Map.of("accountId", "42", "globalRoles", List.of("platformAdmin"))); + String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -89,7 +88,7 @@ void getRuntimeOwnershipStatusReturnsStatusDto() throws Exception { @Test void getRuntimeOwnershipStatusRejectsCrossTenantScopedAdmin() throws Exception { String token = - jwtUtil.generateToken("user", Map.of("scopedRoles", Map.of("8", List.of("tenantAdmin")))); + accountToken(jwtUtil, Map.of("scopedRoles", Map.of("8", List.of("tenantAdmin")))); mockMvc .perform( @@ -102,9 +101,7 @@ void getRuntimeOwnershipStatusRejectsCrossTenantScopedAdmin() throws Exception { @Test void getRuntimeOwnershipStatusRejectsMalformedTenantIdBeforeDispatch() throws Exception { - String token = - jwtUtil.generateToken( - "42", Map.of("accountId", "42", "globalRoles", List.of("platformAdmin"))); + String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -121,9 +118,7 @@ void getRuntimeOwnershipStatusRejectsMalformedTenantIdBeforeDispatch() throws Ex @Test void getRuntimeOwnershipStatusRejectsMalformedGameInstanceIdBeforeDispatch() throws Exception { - String token = - jwtUtil.generateToken( - "42", Map.of("accountId", "42", "globalRoles", List.of("platformAdmin"))); + String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -141,9 +136,7 @@ void getRuntimeOwnershipStatusRejectsMalformedGameInstanceIdBeforeDispatch() thr @Test void pauseRejectsAuthorizedCallerWhileMutationGateIsUnavailable() throws Exception { TickRemediationRequest request = new TickRemediationRequest(1L, "7", null, "maintenance"); - String token = - jwtUtil.generateToken( - "42", Map.of("accountId", "42", "globalRoles", List.of("platformAdmin"))); + String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -165,9 +158,7 @@ void pauseRejectsAuthorizedCallerWhileMutationGateIsUnavailable() throws Excepti @Test void resumeRejectsAuthorizedCallerWhileMutationGateIsUnavailable() throws Exception { TickRemediationRequest request = new TickRemediationRequest(1L, "7", null, "maintenance"); - String token = - jwtUtil.generateToken( - "42", Map.of("accountId", "42", "globalRoles", List.of("platformAdmin"))); + String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -190,9 +181,7 @@ void resumeRejectsAuthorizedCallerWhileMutationGateIsUnavailable() throws Except void pauseRejectsRegionOnlyScopeBeforeUnavailableResponse() throws Exception { TickRemediationRequest request = new TickRemediationRequest(1L, null, "region-7", "maintenance"); - String token = - jwtUtil.generateToken( - "42", Map.of("accountId", "42", "globalRoles", List.of("platformAdmin"))); + String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -215,9 +204,7 @@ void pauseRejectsRegionOnlyScopeBeforeUnavailableResponse() throws Exception { void resumeRejectsRegionOnlyScopeBeforeUnavailableResponse() throws Exception { TickRemediationRequest request = new TickRemediationRequest(1L, null, "region-7", "maintenance"); - String token = - jwtUtil.generateToken( - "42", Map.of("accountId", "42", "globalRoles", List.of("platformAdmin"))); + String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -239,9 +226,7 @@ void resumeRejectsRegionOnlyScopeBeforeUnavailableResponse() throws Exception { @Test void pauseRejectsEmptyRegionIdBeforeUnavailableResponse() throws Exception { TickRemediationRequest request = new TickRemediationRequest(1L, "7", "", "maintenance"); - String token = - jwtUtil.generateToken( - "42", Map.of("accountId", "42", "globalRoles", List.of("platformAdmin"))); + String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -262,9 +247,7 @@ void pauseRejectsEmptyRegionIdBeforeUnavailableResponse() throws Exception { @Test void resumeRejectsBlankRegionIdBeforeUnavailableResponse() throws Exception { TickRemediationRequest request = new TickRemediationRequest(1L, "7", " ", "maintenance"); - String token = - jwtUtil.generateToken( - "42", Map.of("accountId", "42", "globalRoles", List.of("platformAdmin"))); + String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -286,7 +269,7 @@ void resumeRejectsBlankRegionIdBeforeUnavailableResponse() throws Exception { void resumeRejectsCrossTenantScopedAdmin() throws Exception { TickRemediationRequest request = new TickRemediationRequest(1L, "7", null, "maintenance"); String token = - jwtUtil.generateToken("user", Map.of("scopedRoles", Map.of("8", List.of("tenantAdmin")))); + accountToken(jwtUtil, Map.of("scopedRoles", Map.of("8", List.of("tenantAdmin")))); mockMvc .perform( @@ -300,9 +283,7 @@ void resumeRejectsCrossTenantScopedAdmin() throws Exception { @Test void pauseRejectsZeroGameInstanceIdBeforeDispatch() throws Exception { TickRemediationRequest request = new TickRemediationRequest(1L, "0", null, "maintenance"); - String token = - jwtUtil.generateToken( - "42", Map.of("accountId", "42", "globalRoles", List.of("platformAdmin"))); + String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -320,9 +301,7 @@ void pauseRejectsZeroGameInstanceIdBeforeDispatch() throws Exception { @Test void pauseRejectsZeroTenantIdBeforeDispatch() throws Exception { TickRemediationRequest request = new TickRemediationRequest(0L, "7", null, "maintenance"); - String token = - jwtUtil.generateToken( - "42", Map.of("accountId", "42", "globalRoles", List.of("platformAdmin"))); + String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform( diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java index 1da50d55ab..b060b413f8 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java @@ -271,7 +271,8 @@ void listPointerAuditRejectsMismatchedControlPlaneTenant() { @Test void setPointerUsesSessionAccountIdAsActorPrincipal() { - SessionContext.setContext("42", List.of("platformAdmin"), Map.of()); + SessionContext.setContext( + "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", List.of("platformAdmin"), Map.of()); when(gameSessionControlPlaneClient.setAdmissionPointer(any())) .thenReturn( SetAdmissionPointerResponse.newBuilder() @@ -304,7 +305,7 @@ void setPointerUsesSessionAccountIdAsActorPrincipal() { .setAdmissionPointer( org.mockito.ArgumentMatchers.argThat( request -> - request.getActorPrincipal().equals("42") + request.getActorPrincipal().equals("018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a") && request.getExpectedPointerVersion() == 3L && request.getExpectedCatalogRevision() == 4L && request.getPreparedVersionUpgradeId().equals("pvu-1"))); @@ -312,7 +313,8 @@ void setPointerUsesSessionAccountIdAsActorPrincipal() { @Test void setPointerMapsVersionMismatchToConflict() { - SessionContext.setContext("42", List.of("platformAdmin"), Map.of()); + SessionContext.setContext( + "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", List.of("platformAdmin"), Map.of()); when(gameSessionControlPlaneClient.setAdmissionPointer(any())) .thenReturn( SetAdmissionPointerResponse.newBuilder() @@ -382,7 +384,8 @@ void setPointerRejectsMalformedCurrentAccountClaimBeforeMutation() { @Test void executePreparedVersionCutoverUsesSessionAccountIdAsActorPrincipal() { - SessionContext.setContext("42", List.of("platformAdmin"), Map.of()); + SessionContext.setContext( + "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", List.of("platformAdmin"), Map.of()); when(gameSessionControlPlaneClient.executePreparedVersionCutover(any())) .thenReturn( ExecutePreparedVersionCutoverResponse.newBuilder() @@ -400,7 +403,7 @@ void executePreparedVersionCutoverUsesSessionAccountIdAsActorPrincipal() { .executePreparedVersionCutover( org.mockito.ArgumentMatchers.argThat( request -> - request.getActorPrincipal().equals("42") + request.getActorPrincipal().equals("018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a") && request.getPreparedVersionUpgradeId().equals("pvu-1") && request.getExpectedPointerVersion() == 3L && request.getExpectedCatalogRevision() == 4L)); diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/controller/MailController.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/controller/MailController.java index 941a3f7caf..13006867a6 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/controller/MailController.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/controller/MailController.java @@ -2,10 +2,8 @@ import jakarta.validation.Valid; import net.firedevops.firemud.common.ApiResponse; -import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.socialgroups.dto.MailMessageDto; import net.firedevops.firemud.socialgroups.dto.SendMailRequest; -import net.firedevops.firemud.socialgroups.security.SocialAccessGuard; import net.firedevops.firemud.socialgroups.service.MailService; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -19,22 +17,22 @@ @RequestMapping("/mail") public class MailController { private final MailService mailService; - private final SocialAccessGuard socialAccessGuard; - public MailController(MailService mailService, SocialAccessGuard socialAccessGuard) { + public MailController(MailService mailService) { this.mailService = mailService; - this.socialAccessGuard = socialAccessGuard; } @PostMapping public ResponseEntity> sendMail( @Valid @RequestBody SendMailRequest request) { - if (!SessionContext.isCurrentAccount(request.senderAccountId())) { - throw new ResponseStatusException( - HttpStatus.FORBIDDEN, "Sender must match authenticated account"); - } - socialAccessGuard.requireAccountAccess(request.tenantId(), request.senderAccountId()); + rejectUnmappedSenderIdentity(); MailMessageDto dto = mailService.sendMail(request); return ResponseEntity.ok(ApiResponse.success(dto)); } + + private static void rejectUnmappedSenderIdentity() { + throw new ResponseStatusException( + HttpStatus.SERVICE_UNAVAILABLE, + "Mail sender authorization is unavailable until Social account UUID migration is complete"); + } } diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/security/SocialAccessGuard.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/security/SocialAccessGuard.java index 3054782bf5..683f0359ce 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/security/SocialAccessGuard.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/security/SocialAccessGuard.java @@ -14,14 +14,13 @@ public void requireAccountAccess(long tenantId, long accountId) { } public boolean hasAccountAccess(long tenantId, long accountId) { - return SessionContext.hasTenantAccess(tenantId) || isCurrentAccount(accountId); + // Social still exposes legacy numeric account selectors. They cannot prove self access under + // the canonical Account UUID identity contract, so only the existing tenant-role gate applies + // until Social's account UUID migration is complete. + return accountId > 0L && SessionContext.hasTenantAccess(tenantId); } public void requireTenantAccess(long tenantId) { SessionContext.requireTenantAccess(tenantId); } - - private boolean isCurrentAccount(long accountId) { - return SessionContext.isCurrentAccount(accountId); - } } diff --git a/services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/SocialGroupsApplicationIntegrationTest.java b/services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/SocialGroupsApplicationIntegrationTest.java index 3709e0e975..54f54e73dd 100644 --- a/services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/SocialGroupsApplicationIntegrationTest.java +++ b/services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/SocialGroupsApplicationIntegrationTest.java @@ -68,6 +68,7 @@ }) @Import(NoGrpcServerTestConfiguration.class) class SocialGroupsApplicationIntegrationTest { + private static final String ACCOUNT_UUID = "c41744c9-285e-4ed0-9fb4-0f0acb7a0123"; private static final HttpClient HTTP_CLIENT = HttpClient.newHttpClient(); private static final JwtUtil JWT_UTIL = new JwtUtil("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 3600000L); @@ -141,7 +142,8 @@ void setUpClients() { void pingEndpointReturnsPong() throws Exception { String token = JWT_UTIL.generateToken( - "social-groups-test", Map.of("globalRoles", List.of("platformAdmin"))); + ACCOUNT_UUID, + Map.of("accountId", ACCOUNT_UUID, "globalRoles", List.of("platformAdmin"))); HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/ping")) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) @@ -154,7 +156,7 @@ void pingEndpointReturnsPong() throws Exception { @Test void friendRosterRejectsMalformedTenantIdAsInvalidArgument() throws Exception { - String token = privilegedAccountToken(2L); + String token = privilegedAccountToken(); HttpResponse response = send(authedGet(token, "http://localhost:" + port + "/friends?tenantId=bad&accountId=2")); @@ -166,7 +168,7 @@ void friendRosterRejectsMalformedTenantIdAsInvalidArgument() throws Exception { @Test void friendRosterRejectsMalformedFilterAsInvalidArgument() throws Exception { - String token = privilegedAccountToken(2L); + String token = privilegedAccountToken(); HttpResponse response = send( @@ -201,7 +203,7 @@ void duplicateEffectIdReturnsExistingChatMessageWithoutRepublishing() { @Test void friendRosterAndPresenceEndpointsReturnCanonicalEmbeddedPresence() throws Exception { - String token = privilegedAccountToken(2L); + String token = privilegedAccountToken(); HttpResponse addResponse = send( HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/friends")) @@ -278,7 +280,7 @@ void friendRosterAndPresenceEndpointsReturnCanonicalEmbeddedPresence() throws Ex @Test void friendRosterEndpointFallsBackToOfflineWhenPresenceIsUnavailable() throws Exception { - String token = privilegedAccountToken(2L); + String token = privilegedAccountToken(); send( HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/friends")) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) @@ -304,7 +306,7 @@ void friendRosterEndpointFallsBackToOfflineWhenPresenceIsUnavailable() throws Ex @Test void friendRosterEndpointSupportsCanonicalOnlineFilter() throws Exception { - String token = privilegedAccountToken(2L); + String token = privilegedAccountToken(); send( HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/friends")) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) @@ -353,7 +355,7 @@ void friendRosterEndpointSupportsCanonicalOnlineFilter() throws Exception { @Test void friendRosterEndpointSupportsCanonicalSharedScopeFilter() throws Exception { - String token = privilegedAccountToken(2L); + String token = privilegedAccountToken(); send( HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/friends")) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) @@ -414,7 +416,7 @@ void friendRosterEndpointSupportsCanonicalSharedScopeFilter() throws Exception { @Test void friendRosterSummaryEndpointReturnsCanonicalCounts() throws Exception { - String token = privilegedAccountToken(2L); + String token = privilegedAccountToken(); send( HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/friends")) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) @@ -470,7 +472,7 @@ void friendRosterSummaryEndpointReturnsCanonicalCounts() throws Exception { @Test void friendEndpointsRequireReciprocalActiveLinksWithinRequestedTenant() throws Exception { - String token = privilegedAccountToken(2L); + String token = privilegedAccountToken(); saveFriendLink(1L, 2L, 3L, "active"); saveFriendLink(1L, 2L, 4L, "active"); saveFriendLink(1L, 4L, 2L, "inactive"); @@ -548,7 +550,7 @@ void friendEndpointsRequireReciprocalActiveLinksWithinRequestedTenant() throws E @Test void addFriendIsIdempotentForExistingActiveAccountLink() throws Exception { - String token = privilegedAccountToken(2L); + String token = privilegedAccountToken(); HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/friends")) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) @@ -582,7 +584,7 @@ void addFriendIsIdempotentForExistingActiveAccountLink() throws Exception { @Test void addFriendRejectsSelfLink() throws Exception { - String token = privilegedAccountToken(2L); + String token = privilegedAccountToken(); HttpResponse response = send( HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/friends")) @@ -603,7 +605,7 @@ void addFriendRejectsSelfLink() throws Exception { @Test void removeFriendDeletesExistingActiveAccountLinkAndIsIdempotent() throws Exception { - String token = privilegedAccountToken(2L); + String token = privilegedAccountToken(); HttpRequest addRequest = HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/friends")) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) @@ -640,7 +642,7 @@ void removeFriendDeletesExistingActiveAccountLinkAndIsIdempotent() throws Except @Test void removeFriendByOrdinalDeletesCanonicalRosterEntry() throws Exception { - String token = privilegedAccountToken(2L); + String token = privilegedAccountToken(); send( HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/friends")) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) @@ -671,7 +673,7 @@ void removeFriendByOrdinalDeletesCanonicalRosterEntry() throws Exception { @Test void friendVisibilityEndpointsExposeCanonicalPolicyReadAndWrite() throws Exception { - String token = privilegedAccountToken(2L); + String token = privilegedAccountToken(); HttpResponse getResponse = send( @@ -732,11 +734,11 @@ private void saveFriendLink(long tenantId, long accountId, long friendAccountId, accountFriendLinkRepository.save(link); } - private static String privilegedAccountToken(long accountId) { + private static String privilegedAccountToken() { return JWT_UTIL.generateToken( - Long.toString(accountId), + ACCOUNT_UUID, Map.of( - "accountId", Long.toString(accountId), + "accountId", ACCOUNT_UUID, "globalRoles", List.of("platformAdmin"), "scopedRoles", Map.of("1", List.of("tenantAdmin")))); } diff --git a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/ChatControllerTest.java b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/ChatControllerTest.java index 996c931921..7d0797c978 100644 --- a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/ChatControllerTest.java +++ b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/ChatControllerTest.java @@ -31,6 +31,7 @@ }) @WithFiremudHttpAuthTestProperties class ChatControllerTest { + private static final String ACCOUNT_UUID = "c41744c9-285e-4ed0-9fb4-0f0acb7a0123"; @Autowired private MockMvc mockMvc; @Autowired private JwtUtil jwtUtil; @@ -40,7 +41,9 @@ class ChatControllerTest { @Test void sendMessageRejectsZeroTenantIdBeforeAccessCheckAndDispatch() throws Exception { - String token = jwtUtil.generateToken("2", Map.of("accountId", "2", "globalRoles", List.of())); + String token = + jwtUtil.generateToken( + ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID, "globalRoles", List.of())); String body = """ {"tenantId":0,"senderAccountId":2,"type":"SAY","content":"hello"} diff --git a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/FriendControllerTest.java b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/FriendControllerTest.java index af35da1c08..c14e80bd3a 100644 --- a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/FriendControllerTest.java +++ b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/FriendControllerTest.java @@ -44,6 +44,7 @@ }) @WithFiremudHttpAuthTestProperties class FriendControllerTest { + private static final String ACCOUNT_UUID = "c41744c9-285e-4ed0-9fb4-0f0acb7a0123"; @Autowired private MockMvc mockMvc; @Autowired private JwtUtil jwtUtil; @@ -58,7 +59,7 @@ void addFriendReturnsDto() throws Exception { FriendLinkDto response = new FriendLinkDto(1L, 1L, 2L, 3L, "active", null); when(friendService.addFriend(request)).thenReturn(response); - String token = jwtUtil.generateToken("2", Map.of("accountId", "2", "globalRoles", List.of())); + String token = accountToken(); mockMvc .perform( post("/friends") @@ -77,7 +78,7 @@ void addFriendRejectsSelfLinkAsBadRequest() throws Exception { .thenThrow( new IllegalArgumentException("Cannot add or remove your own account as a friend")); - String token = jwtUtil.generateToken("2", Map.of("accountId", "2", "globalRoles", List.of())); + String token = accountToken(); mockMvc .perform( post("/friends") @@ -94,7 +95,7 @@ void addFriendRejectsSelfLinkAsBadRequest() throws Exception { @Test void addFriendRejectsZeroTenantIdBeforeAccessCheck() throws Exception { AddFriendRequest request = new AddFriendRequest(0L, 2L, 3L); - String token = jwtUtil.generateToken("2", Map.of("accountId", "2", "globalRoles", List.of())); + String token = accountToken(); mockMvc .perform( @@ -112,7 +113,7 @@ void addFriendRejectsZeroTenantIdBeforeAccessCheck() throws Exception { @Test void removeFriendReturnsSuccess() throws Exception { - String token = jwtUtil.generateToken("2", Map.of("accountId", "2", "globalRoles", List.of())); + String token = accountToken(); mockMvc .perform( delete("/friends/3") @@ -125,7 +126,7 @@ void removeFriendReturnsSuccess() throws Exception { @Test void removeFriendRejectsSelfLinkAsBadRequest() throws Exception { - String token = jwtUtil.generateToken("2", Map.of("accountId", "2", "globalRoles", List.of())); + String token = accountToken(); org.mockito.Mockito.doThrow( new IllegalArgumentException("Cannot add or remove your own account as a friend")) .when(friendService) @@ -146,7 +147,7 @@ void removeFriendRejectsSelfLinkAsBadRequest() throws Exception { @Test void removeFriendRejectsMalformedFriendAccountIdBeforeAccessCheck() throws Exception { - String token = jwtUtil.generateToken("2", Map.of("accountId", "2", "globalRoles", List.of())); + String token = accountToken(); mockMvc .perform( @@ -190,7 +191,7 @@ void getFriendReturnsCanonicalRosterEntry() throws Exception { null, null)))); - String token = jwtUtil.generateToken("2", Map.of("accountId", "2", "globalRoles", List.of())); + String token = accountToken(); mockMvc .perform( get("/friends/3") @@ -233,7 +234,7 @@ void getFriendByOrdinalReturnsCanonicalRosterEntry() throws Exception { null, null)))); - String token = jwtUtil.generateToken("2", Map.of("accountId", "2", "globalRoles", List.of())); + String token = accountToken(); mockMvc .perform( get("/friends/entry/1") @@ -248,7 +249,7 @@ void getFriendByOrdinalReturnsCanonicalRosterEntry() throws Exception { @Test void getFriendByOrdinalRejectsMalformedOrdinalBeforeAccessCheck() throws Exception { - String token = jwtUtil.generateToken("2", Map.of("accountId", "2", "globalRoles", List.of())); + String token = accountToken(); mockMvc .perform( @@ -287,7 +288,7 @@ void listFriendPresenceReturnsPresenceList() throws Exception { null, null)))); - String token = jwtUtil.generateToken("2", Map.of("accountId", "2", "globalRoles", List.of())); + String token = accountToken(); mockMvc .perform( get("/friends/presence") @@ -311,7 +312,7 @@ void getFriendPresencePolicyReturnsCanonicalPolicy() throws Exception { when(friendService.getFriendPresencePolicy(1L, 2L)) .thenReturn(new FriendPresencePolicyViewDto(FriendPresenceVisibilityPolicyValue.PRIVATE)); - String token = jwtUtil.generateToken("2", Map.of("accountId", "2", "globalRoles", List.of())); + String token = accountToken(); mockMvc .perform( get("/friends/visibility") @@ -325,7 +326,7 @@ void getFriendPresencePolicyReturnsCanonicalPolicy() throws Exception { @Test void getFriendPresencePolicyRejectsMalformedAccountIdBeforeAccessCheck() throws Exception { - String token = jwtUtil.generateToken("2", Map.of("accountId", "2", "globalRoles", List.of())); + String token = accountToken(); mockMvc .perform( @@ -350,7 +351,7 @@ void updateFriendPresencePolicyReturnsCanonicalPolicy() throws Exception { .thenReturn( new FriendPresencePolicyViewDto(FriendPresenceVisibilityPolicyValue.FRIENDS_ONLY)); - String token = jwtUtil.generateToken("2", Map.of("accountId", "2", "globalRoles", List.of())); + String token = accountToken(); mockMvc .perform( put("/friends/visibility") @@ -373,7 +374,7 @@ void updateFriendPresencePolicyRejectsReservedHiddenStaff() throws Exception { new IllegalArgumentException( "Friend presence visibility policy HIDDEN_STAFF is reserved")); - String token = jwtUtil.generateToken("2", Map.of("accountId", "2", "globalRoles", List.of())); + String token = accountToken(); mockMvc .perform( put("/friends/visibility") @@ -421,7 +422,7 @@ void listFriendsReturnsRosterList() throws Exception { null, null))))); - String token = jwtUtil.generateToken("2", Map.of("accountId", "2", "globalRoles", List.of())); + String token = accountToken(); mockMvc .perform( get("/friends") @@ -442,7 +443,7 @@ void listFriendsReturnsRosterList() throws Exception { @Test void listFriendsRejectsZeroTenantIdBeforeAccessCheck() throws Exception { - String token = jwtUtil.generateToken("2", Map.of("accountId", "2", "globalRoles", List.of())); + String token = accountToken(); mockMvc .perform( @@ -462,7 +463,7 @@ void getFriendRosterSummaryReturnsCanonicalCounts() throws Exception { when(friendService.getFriendRosterSummary(1L, 2L)) .thenReturn(new FriendRosterSummaryDto(4, 1, 3, 2, 1, 2, 1, 0, 0, 2, 1, 1)); - String token = jwtUtil.generateToken("2", Map.of("accountId", "2", "globalRoles", List.of())); + String token = accountToken(); mockMvc .perform( get("/friends/summary") @@ -502,7 +503,7 @@ void removeFriendByOrdinalReturnsRemovedEntry() throws Exception { 3L, false, null, null, null, null, null, null, null, null, null, null, null, null, null)))); - String token = jwtUtil.generateToken("2", Map.of("accountId", "2", "globalRoles", List.of())); + String token = accountToken(); mockMvc .perform( delete("/friends/entry/1") @@ -516,7 +517,7 @@ void removeFriendByOrdinalReturnsRemovedEntry() throws Exception { @Test void removeFriendByOrdinalRejectsMalformedOrdinalBeforeAccessCheck() throws Exception { - String token = jwtUtil.generateToken("2", Map.of("accountId", "2", "globalRoles", List.of())); + String token = accountToken(); mockMvc .perform( @@ -530,4 +531,9 @@ void removeFriendByOrdinalRejectsMalformedOrdinalBeforeAccessCheck() throws Exce verifyNoInteractions(friendService, socialAccessGuard); } + + private String accountToken() { + return jwtUtil.generateToken( + ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID, "globalRoles", List.of())); + } } diff --git a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/GuildControllerTest.java b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/GuildControllerTest.java index ba64be1d59..323090b2b6 100644 --- a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/GuildControllerTest.java +++ b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/GuildControllerTest.java @@ -40,6 +40,7 @@ }) @WithFiremudHttpAuthTestProperties class GuildControllerTest { + private static final String ACCOUNT_UUID = "c41744c9-285e-4ed0-9fb4-0f0acb7a0123"; @Autowired private MockMvc mockMvc; private final ObjectMapper objectMapper = new ObjectMapper(); @@ -57,7 +58,10 @@ void createGuildAllowsScopedTenantAdmin() throws Exception { CreateGuildRequest request = new CreateGuildRequest(1L, 2L, "guild"); when(guildService.createGuild(request)) .thenReturn(new GuildDto(1L, 1L, "guild", 2L, Instant.now())); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = + jwtUtil.generateToken( + ACCOUNT_UUID, + Map.of("accountId", ACCOUNT_UUID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -74,7 +78,9 @@ void createGuildAllowsScopedTenantAdmin() throws Exception { void createGuildRejectsCrossTenantScopedAdmin() throws Exception { CreateGuildRequest request = new CreateGuildRequest(1L, 2L, "guild"); String token = - jwtUtil.generateToken("user", Map.of("scopedRoles", Map.of("8", List.of("tenantAdmin")))); + jwtUtil.generateToken( + ACCOUNT_UUID, + Map.of("accountId", ACCOUNT_UUID, "scopedRoles", Map.of("8", List.of("tenantAdmin")))); mockMvc .perform( @@ -88,7 +94,10 @@ void createGuildRejectsCrossTenantScopedAdmin() throws Exception { @Test void createGuildRejectsZeroTenantIdBeforeDispatch() throws Exception { CreateGuildRequest request = new CreateGuildRequest(0L, 2L, "guild"); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = + jwtUtil.generateToken( + ACCOUNT_UUID, + Map.of("accountId", ACCOUNT_UUID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -107,7 +116,10 @@ void createGuildRejectsZeroTenantIdBeforeDispatch() throws Exception { @Test void addMemberRejectsZeroGuildIdBeforeDispatch() throws Exception { AddGuildMemberRequest request = new AddGuildMemberRequest(1L, 0L, 2L, "member"); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = + jwtUtil.generateToken( + ACCOUNT_UUID, + Map.of("accountId", ACCOUNT_UUID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform( diff --git a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/MailControllerTest.java b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/MailControllerTest.java index 58c490577c..c481e99446 100644 --- a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/MailControllerTest.java +++ b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/MailControllerTest.java @@ -1,7 +1,6 @@ package net.firedevops.firemud.socialgroups.controller; import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -12,9 +11,7 @@ import net.firedevops.firemud.common.config.CommonSecurityAutoConfiguration; import net.firedevops.firemud.common.config.CommonSecurityServletAutoConfiguration; import net.firedevops.firemud.common.security.JwtUtil; -import net.firedevops.firemud.socialgroups.dto.MailMessageDto; import net.firedevops.firemud.socialgroups.dto.SendMailRequest; -import net.firedevops.firemud.socialgroups.security.SocialAccessGuard; import net.firedevops.firemud.socialgroups.service.MailService; import net.firedevops.firemud.test.WithFiremudHttpAuthTestProperties; import org.junit.jupiter.api.Test; @@ -35,34 +32,37 @@ }) @WithFiremudHttpAuthTestProperties class MailControllerTest { + private static final String ACCOUNT_UUID = "c41744c9-285e-4ed0-9fb4-0f0acb7a0123"; + @Autowired private MockMvc mockMvc; @Autowired private JwtUtil jwtUtil; private final ObjectMapper objectMapper = new ObjectMapper(); @MockitoBean private MailService mailService; - @MockitoBean private SocialAccessGuard socialAccessGuard; @Test - void sendMailReturnsDto() throws Exception { + void sendMailFailsClosedForCanonicalSubjectWithLegacyNumericSenderSelector() throws Exception { SendMailRequest request = new SendMailRequest(1L, 2L, 3L, "hello", "test body"); - MailMessageDto response = new MailMessageDto(1L, 1L, 2L, 3L, "hello", "test body", null, null); - when(mailService.sendMail(request)).thenReturn(response); - - String token = jwtUtil.generateToken("2", Map.of("accountId", "2", "globalRoles", List.of())); + String token = accountToken(); mockMvc .perform( post("/mail") .contentType(MediaType.APPLICATION_JSON) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) .content(objectMapper.writeValueAsString(request))) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.status").value("SUCCESS")) - .andExpect(jsonPath("$.data.subject").value("hello")); + .andExpect(status().isServiceUnavailable()) + .andExpect(jsonPath("$.status").value("ERROR")) + .andExpect( + jsonPath("$.error.message") + .value( + "Mail sender authorization is unavailable until Social account UUID migration is complete")); + + verifyNoInteractions(mailService); } @Test void sendMailRejectsZeroSenderAccountIdBeforeAccessCheckAndDispatch() throws Exception { - String token = jwtUtil.generateToken("2", Map.of("accountId", "2", "globalRoles", List.of())); + String token = accountToken(); mockMvc .perform( @@ -78,16 +78,16 @@ void sendMailRejectsZeroSenderAccountIdBeforeAccessCheckAndDispatch() throws Exc .andExpect(jsonPath("$.error.code").value("INVALID_ARGUMENT")) .andExpect(jsonPath("$.error.message").value("senderAccountId must be positive")); - verifyNoInteractions(mailService, socialAccessGuard); + verifyNoInteractions(mailService); } @Test - void sendMailRejectsSenderImpersonationBeforeAccessCheckAndDispatch() throws Exception { + void tenantRoleCannotEnableMailWhileSenderIdentityIsNumeric() throws Exception { String token = jwtUtil.generateToken( - "2", + ACCOUNT_UUID, Map.of( - "accountId", "2", + "accountId", ACCOUNT_UUID, "globalRoles", List.of(), "scopedRoles", Map.of("1", List.of("tenantAdmin")))); @@ -100,8 +100,17 @@ void sendMailRejectsSenderImpersonationBeforeAccessCheckAndDispatch() throws Exc """ {"tenantId":1,"senderAccountId":3,"recipientAccountId":4,"subject":"hello","content":"test body"} """)) - .andExpect(status().isForbidden()); + .andExpect(status().isServiceUnavailable()) + .andExpect( + jsonPath("$.error.message") + .value( + "Mail sender authorization is unavailable until Social account UUID migration is complete")); + + verifyNoInteractions(mailService); + } - verifyNoInteractions(mailService, socialAccessGuard); + private String accountToken() { + return jwtUtil.generateToken( + ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID, "globalRoles", List.of())); } } diff --git a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/PingControllerTest.java b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/PingControllerTest.java index 266b936cb8..ca11768236 100644 --- a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/PingControllerTest.java +++ b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/PingControllerTest.java @@ -24,6 +24,7 @@ @Import({CommonSecurityAutoConfiguration.class, CommonSecurityServletAutoConfiguration.class}) @WithFiremudHttpAuthTestProperties class PingControllerTest { + private static final String ACCOUNT_UUID = "c41744c9-285e-4ed0-9fb4-0f0acb7a0123"; @Autowired private MockMvc mockMvc; @Autowired private JwtUtil jwtUtil; @@ -34,7 +35,10 @@ class PingControllerTest { void pingEndpointReturnsPong() throws Exception { when(pingService.ping()).thenReturn("pong"); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = + jwtUtil.generateToken( + ACCOUNT_UUID, + Map.of("accountId", ACCOUNT_UUID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform(get("/ping").header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isOk()) diff --git a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/VoiceChatControllerTest.java b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/VoiceChatControllerTest.java index 5b867a965f..1d23fcb6d0 100644 --- a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/VoiceChatControllerTest.java +++ b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/VoiceChatControllerTest.java @@ -35,6 +35,7 @@ }) @WithFiremudHttpAuthTestProperties class VoiceChatControllerTest { + private static final String ACCOUNT_UUID = "c41744c9-285e-4ed0-9fb4-0f0acb7a0123"; @Autowired private MockMvc mockMvc; @Autowired private JwtUtil jwtUtil; @@ -45,7 +46,7 @@ class VoiceChatControllerTest { @Test void createTokenReturnsToken() throws Exception { when(service.createToken(any())).thenReturn(new VoiceTokenDto("abc", Instant.now())); - String token = jwtUtil.generateToken("2", Map.of("accountId", "2", "globalRoles", List.of())); + String token = accountToken(); String body = "{\"tenantId\":1,\"accountId\":2,\"channelId\":\"guild-1\"}"; mockMvc @@ -60,7 +61,7 @@ void createTokenReturnsToken() throws Exception { @Test void createTokenRejectsZeroAccountIdBeforeAccessCheckAndDispatch() throws Exception { - String token = jwtUtil.generateToken("2", Map.of("accountId", "2", "globalRoles", List.of())); + String token = accountToken(); String body = "{\"tenantId\":1,\"accountId\":0,\"channelId\":\"guild-1\"}"; mockMvc @@ -76,4 +77,9 @@ void createTokenRejectsZeroAccountIdBeforeAccessCheckAndDispatch() throws Except verifyNoInteractions(service, socialAccessGuard); } + + private String accountToken() { + return jwtUtil.generateToken( + ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID, "globalRoles", List.of())); + } } diff --git a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/security/SocialAccessGuardTest.java b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/security/SocialAccessGuardTest.java index 6afa0c3424..6c67a30275 100644 --- a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/security/SocialAccessGuardTest.java +++ b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/security/SocialAccessGuardTest.java @@ -11,6 +11,8 @@ import org.junit.jupiter.api.Test; class SocialAccessGuardTest { + private static final String ACCOUNT_UUID = "c41744c9-285e-4ed0-9fb4-0f0acb7a0123"; + private final SocialAccessGuard guard = new SocialAccessGuard(); @AfterEach @@ -26,8 +28,15 @@ void hasAccountAccessRejectsMalformedCurrentAccountClaim() { } @Test - void hasAccountAccessAcceptsMatchingCurrentAccountClaim() { - SessionContext.setContext("42", List.of(), Map.of()); + void canonicalCurrentAccountCannotAuthorizeLegacyNumericSelector() { + SessionContext.setContext(ACCOUNT_UUID, List.of(), Map.of()); + + assertFalse(guard.hasAccountAccess(1L, 42L)); + } + + @Test + void hasAccountAccessPreservesTenantAdminAuthorizationForLegacySelector() { + SessionContext.setContext(ACCOUNT_UUID, List.of(), Map.of("1", List.of("tenantAdmin"))); assertTrue(guard.hasAccountAccess(1L, 42L)); } diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java index 391e9ac1c9..356adc4dc1 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java @@ -29,6 +29,8 @@ class GameplayHandshakeFilterTest { private static final String SECRET = "testsecretkeytestsecretkeytest1234"; + private static final String ACCOUNT_ID = "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a"; + private static final String OTHER_ACCOUNT_ID = "018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f"; private static final RuntimeIdentity TEST_RUNTIME_IDENTITY = new RuntimeIdentity( "spring-cloud-gateway", "gateway-test", "localhost", Instant.EPOCH, null, null, null); @@ -84,10 +86,10 @@ void rejectsMatrixParameterGameplayRoutesEvenWithCookieCarrier() { String token = new JwtUtil(SECRET, 30_000L) .generateToken( - "7", + ACCOUNT_ID, Map.of( "aud", "gameplay-connect", - "accountId", "7", + "accountId", ACCOUNT_ID, "tenantId", "1", "worldSlug", "demo", "realmSlug", "production", @@ -180,10 +182,10 @@ void rejectsFirstPartyHandshakeWithMalformedNumericClaim() { String token = new JwtUtil(SECRET, 30_000L) .generateToken( - "7", + ACCOUNT_ID, Map.of( "aud", "gameplay-connect", - "accountId", "7", + "accountId", ACCOUNT_ID, "tenantId", "not-a-number", "worldSlug", "demo", "realmSlug", "production", @@ -219,7 +221,7 @@ void rejectsFirstPartyHandshakeWithZeroAccountIdClaim() { String token = new JwtUtil(SECRET, 30_000L) .generateToken( - "7", + ACCOUNT_ID, Map.of( "aud", "gameplay-connect", "accountId", "0", @@ -258,10 +260,10 @@ void rejectsFirstPartyHandshakeWhenSubjectDoesNotMatchAccountIdClaim() { String token = new JwtUtil(SECRET, 30_000L) .generateToken( - "8", + OTHER_ACCOUNT_ID, Map.of( "aud", "gameplay-connect", - "accountId", "7", + "accountId", ACCOUNT_ID, "tenantId", "1", "worldSlug", "demo", "realmSlug", "production", @@ -297,10 +299,10 @@ void rejectsFirstPartyHandshakeWithZeroPointerVersion() { String token = new JwtUtil(SECRET, 30_000L) .generateToken( - "7", + ACCOUNT_ID, Map.of( "aud", "gameplay-connect", - "accountId", "7", + "accountId", ACCOUNT_ID, "tenantId", "1", "worldSlug", "demo", "realmSlug", "production", @@ -334,10 +336,10 @@ void rejectsFirstPartyHandshakeWithMissingRequiredClaim() { String token = new JwtUtil(SECRET, 30_000L) .generateToken( - "7", + ACCOUNT_ID, Map.of( "aud", "gameplay-connect", - "accountId", "7", + "accountId", ACCOUNT_ID, "tenantId", "1", "realmSlug", "production", "gameInstanceId", "42", @@ -391,10 +393,10 @@ void rejectsScopeMismatchWhenRequestHeadersDisagreeWithTokenClaims() { String token = new JwtUtil(SECRET, 30_000L) .generateToken( - "7", + ACCOUNT_ID, Map.of( "aud", "gameplay-connect", - "accountId", "7", + "accountId", ACCOUNT_ID, "tenantId", "1", "worldSlug", "demo", "realmSlug", "production", @@ -429,10 +431,10 @@ void deniesFirstPartyHandshakeUntilGatewayContextSignerIsProvisioned() { String token = new JwtUtil(SECRET, 30_000L) .generateToken( - "7", + ACCOUNT_ID, Map.of( "aud", "gameplay-connect", - "accountId", "7", + "accountId", ACCOUNT_ID, "tenantId", "1", "worldSlug", "demo", "realmSlug", "production", @@ -471,10 +473,10 @@ void deniesBeforeMutatingMalformedCookieCarrierWithoutGatewayContextSigner() { String token = new JwtUtil(SECRET, 30_000L) .generateToken( - "7", + ACCOUNT_ID, Map.of( "aud", "gameplay-connect", - "accountId", "7", + "accountId", ACCOUNT_ID, "tenantId", "1", "worldSlug", "demo", "realmSlug", "production", @@ -509,10 +511,10 @@ void rejectsPublicHeaderCarrierEvenWhenCookieCarrierIsAlsoPresent() { String token = new JwtUtil(SECRET, 30_000L) .generateToken( - "7", + ACCOUNT_ID, Map.of( "aud", "gameplay-connect", - "accountId", "7", + "accountId", ACCOUNT_ID, "tenantId", "1", "worldSlug", "demo", "realmSlug", "production", @@ -573,10 +575,10 @@ void deniesValidFirstPartyTokenBeforeContextForwardingWithoutGatewaySigner() { String token = new JwtUtil(SECRET, 30_000L) .generateToken( - "7", + ACCOUNT_ID, Map.of( "aud", "gameplay-connect", - "accountId", "7", + "accountId", ACCOUNT_ID, "tenantId", "1", "worldSlug", "demo", "realmSlug", "production", @@ -964,10 +966,10 @@ void rejectsExpiredConnectToken() { JwtUtil expiredJwtUtil = new JwtUtil(SECRET, -1L); String token = expiredJwtUtil.generateToken( - "7", + ACCOUNT_ID, Map.of( "aud", "gameplay-connect", - "accountId", "7", + "accountId", ACCOUNT_ID, "tenantId", "1", "worldSlug", "demo", "realmSlug", "production", @@ -1007,10 +1009,10 @@ void deniesBeforeReplayMutationUntilGatewayContextSignerIsProvisioned() { String token = new JwtUtil(SECRET, 30_000L) .generateToken( - "7", + ACCOUNT_ID, Map.of( "aud", "gameplay-connect", - "accountId", "7", + "accountId", ACCOUNT_ID, "tenantId", "1", "worldSlug", "demo", "realmSlug", "production", @@ -1054,10 +1056,10 @@ void deniesBeforeReplayStorageCheckUntilGatewayContextSignerIsProvisioned() { String token = new JwtUtil(SECRET, 30_000L) .generateToken( - "7", + ACCOUNT_ID, Map.of( "aud", "gameplay-connect", - "accountId", "7", + "accountId", ACCOUNT_ID, "tenantId", "1", "worldSlug", "demo", "realmSlug", "production", diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/JwtAuthFilterTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/JwtAuthFilterTest.java index b07ee0746d..f120dce838 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/JwtAuthFilterTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/JwtAuthFilterTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.util.HashMap; import java.util.List; import java.util.Map; import net.firedevops.firemud.common.security.JwtUtil; @@ -14,6 +15,7 @@ import reactor.core.publisher.Mono; class JwtAuthFilterTest { + private static final String ACCOUNT_ID = "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a"; private final JwtUtil jwtUtil = new JwtUtil("testsecretkeytestsecretkeytest1234", 3600000L); private final JwtAuthFilter filter = new JwtAuthFilter(jwtUtil); @@ -27,7 +29,7 @@ void rejectsRequestWithoutToken() { @Test void rejectsRequestWithoutAdminRole() { - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("player"))); + String token = accountToken(Map.of("globalRoles", List.of("player"))); MockServerHttpRequest.BaseBuilder builder = MockServerHttpRequest.get("/routes/test") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token); @@ -38,7 +40,7 @@ void rejectsRequestWithoutAdminRole() { @Test void allowsRequestWithAdminRole() { - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = accountToken(Map.of("globalRoles", List.of("platformAdmin"))); MockServerHttpRequest.BaseBuilder builder = MockServerHttpRequest.get("/routes/test") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token); @@ -51,7 +53,7 @@ void allowsRequestWithAdminRole() { @Test void rejectsMalformedScopedRolesClaimShape() { - String token = jwtUtil.generateToken("user", Map.of("scopedRoles", List.of("tenantAdmin"))); + String token = accountToken(Map.of("scopedRoles", List.of("tenantAdmin"))); MockServerHttpRequest.BaseBuilder builder = MockServerHttpRequest.get("/routes/test") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token); @@ -61,4 +63,10 @@ void rejectsMalformedScopedRolesClaimShape() { assertEquals(HttpStatus.UNAUTHORIZED, exchange.getResponse().getStatusCode()); } + + private String accountToken(Map claims) { + Map accountClaims = new HashMap<>(claims); + accountClaims.put("accountId", ACCOUNT_ID); + return jwtUtil.generateToken(ACCOUNT_ID, accountClaims); + } } diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldManagementServiceApplicationIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldManagementServiceApplicationIntegrationTest.java index d7bade0c99..be9dd02290 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldManagementServiceApplicationIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldManagementServiceApplicationIntegrationTest.java @@ -88,8 +88,7 @@ void pingEndpointReturnsPong() { @Test void listRegionsRejectsMalformedTenantIdWithInvalidArgumentEnvelope() throws Exception { - String token = - jwtUtil.generateToken("operator", Map.of("globalRoles", List.of("platformAdmin"))); + String token = operatorToken(); HttpRequest request = HttpRequest.newBuilder( URI.create("http://localhost:" + port + "/regions?tenantId=bad-tenant")) @@ -106,8 +105,7 @@ void listRegionsRejectsMalformedTenantIdWithInvalidArgumentEnvelope() throws Exc @Test void moveRegionRejectsMalformedShardIdWithInvalidArgumentEnvelope() throws Exception { - String token = - jwtUtil.generateToken("operator", Map.of("globalRoles", List.of("platformAdmin"))); + String token = operatorToken(); HttpRequest request = HttpRequest.newBuilder( URI.create("http://localhost:" + port + "/regions/4/move?tenantId=1&shardId=bad")) @@ -124,8 +122,7 @@ void moveRegionRejectsMalformedShardIdWithInvalidArgumentEnvelope() throws Excep @Test void saveRuleRejectsMalformedBodyWithInvalidArgumentEnvelope() throws Exception { - String token = - jwtUtil.generateToken("operator", Map.of("globalRoles", List.of("platformAdmin"))); + String token = operatorToken(); HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/generation/rules")) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) @@ -301,4 +298,10 @@ private Long insertEvent( .returning(WORLD_EVENT.ID) .fetchOne(WORLD_EVENT.ID); } + + private String operatorToken() { + String accountId = "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a"; + return jwtUtil.generateToken( + accountId, Map.of("accountId", accountId, "globalRoles", List.of("platformAdmin"))); + } }