diff --git a/.github/scripts/run-gradle-module-checks.sh b/.github/scripts/run-gradle-module-checks.sh index 51a4be02ec..4523c4344f 100644 --- a/.github/scripts/run-gradle-module-checks.sh +++ b/.github/scripts/run-gradle-module-checks.sh @@ -56,6 +56,7 @@ CHECK_LOG="$(mktemp "${RUNNER_TEMP:-${TMPDIR:-/tmp}}/firemud-module-check.XXXXXX readonly CHECK_LOG trap 'rm -f -- "$CHECK_LOG"' EXIT if [[ -z "$CHECK_LOG" ]]; then + printf 'FIREMUD_STALL_ACTIVATION status=disabled-capture-unavailable\n' >&2 echo "Compile-failure log unavailable; running the original check without capture" >&2 exec bash "$ROOT_DIR/dev-tools/validation/run-gradle-with-dependency-recovery.sh" \ --runner "$ROOT_DIR/gradlew" -- \ @@ -63,6 +64,20 @@ if [[ -z "$CHECK_LOG" ]]; then '-Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8' \ ":${MODULE}:check" "${CHECK_ARGS[@]}" --profile fi +declare -a CAPTURE_ARGS=() +stall_activation=disabled-scope +# Observe Account's stalled forks only on an isolated hosted Linux runner. +if [[ "$MODULE" == "account-service" && "$PARTITION" != "full" && + "${GITHUB_ACTIONS:-}" == true && "${RUNNER_ENVIRONMENT:-}" == github-hosted && + "${RUNNER_OS:-}" == Linux ]]; then + CAPTURE_ARGS+=(--root "$ROOT_DIR" --stall-output + "$ROOT_DIR/build/reports/gradle-stall/$MODULE/partition-$PARTITION") + stall_activation=enabled +elif [[ "$MODULE" == "account-service" && "$PARTITION" != "full" ]]; then + stall_activation=disabled-runner-guard +fi +# Fixed reason only: do not print environment values or invocation arguments. +printf 'FIREMUD_STALL_ACTIVATION status=%s\n' "$stall_activation" >&2 set +e bash "$ROOT_DIR/dev-tools/validation/run-gradle-with-dependency-recovery.sh" \ --runner "$ROOT_DIR/gradlew" -- \ @@ -72,7 +87,7 @@ bash "$ROOT_DIR/dev-tools/validation/run-gradle-with-dependency-recovery.sh" \ "${CHECK_ARGS[@]}" \ --profile --info --console=plain 2>&1 | \ ( - python3 "$ROOT_DIR/dev-tools/validation/collect-gradle-compile-failure.py" --capture-log "$CHECK_LOG" + python3 "$ROOT_DIR/dev-tools/validation/collect-gradle-compile-failure.py" --capture-log "$CHECK_LOG" "${CAPTURE_ARGS[@]}" capture_status=$? if (( capture_status != 0 )); then cat >/dev/null diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ad3a195196..0389908fe9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1225,6 +1225,7 @@ jobs: path: | build/reports/profile/ build/reports/compile-failure/${{ matrix.module }}/ + build/reports/gradle-stall/${{ matrix.module }}/ if-no-files-found: warn retention-days: 14 diff --git a/.github/workflows/publish-pr-runtime-images.yml b/.github/workflows/publish-pr-runtime-images.yml index e0f6e6c322..06ac261cdd 100644 --- a/.github/workflows/publish-pr-runtime-images.yml +++ b/.github/workflows/publish-pr-runtime-images.yml @@ -97,6 +97,16 @@ jobs: } if (run.status === "completed") { if (run.conclusion !== "success") throw new Error("publication source run did not succeed"); + const jobs = await github.paginate(github.rest.actions.listJobsForWorkflowRun, { + ...context.repo, run_id: sourceId, per_page: 100, + }); + if (jobs.some(job => job.name === "PR Full-Stack Smoke (runtime-required=true)" && + (job.steps ?? []).some(step => + step.name === "Known canonical transition PLAY failure with successful authenticated cleanup" && + step.status === "completed" && step.conclusion === "success"))) { + core.notice("CI passed under the canonical PLAY transition exception; no runtime images are eligible for publication."); + return; + } core.setOutput("source", JSON.stringify(run)); core.setOutput("title", run.display_title); core.setOutput("artifact_name", `pr-runtime-images-pr-merge-${title[4]}`); @@ -112,6 +122,7 @@ jobs: publish: name: Publish Fixed PR Merge Image Tags needs: [source] + if: ${{ needs.source.outputs.source != '' }} concurrency: group: publish-pr-merge-images-${{ needs.source.outputs.title }} cancel-in-progress: false diff --git a/.github/workflows/runtime-images.yml b/.github/workflows/runtime-images.yml index 0fca72688d..ea2804fecd 100644 --- a/.github/workflows/runtime-images.yml +++ b/.github/workflows/runtime-images.yml @@ -74,6 +74,7 @@ jobs: image_tag: ${{ steps.meta.outputs.image_tag }} candidate_tag: ${{ steps.meta.outputs.candidate_tag }} base_image: ${{ steps.meta.outputs.base_image }} + canonical_play_transition: ${{ steps.meta.outputs.canonical_play_transition }} runtime_smoke_required: ${{ steps.smoke_scope.outputs.runtime_smoke_required }} controller_smoke_required: ${{ steps.smoke_scope.outputs.controller_smoke_required }} permissions: @@ -117,6 +118,7 @@ jobs: BASE_REF="" BASE_SHA="" MERGE_SHA="" + CANONICAL_PLAY_TRANSITION=false if [ "$EVENT_NAME" = "pull_request" ]; then PR_NUMBER="$EVENT_PR_NUMBER" BASE_REF="$EVENT_BASE_REF" @@ -218,6 +220,12 @@ jobs: echo "Runtime PR refresh merge commit does not have the exact current base/head parents." >&2 exit 1 } + # Only the verified live same-repository PR can authorize this + # diagnostic marker; dispatch payload labels carry no authority. + if jq -e '(.labels | type) == "array" and any(.labels[]; .name == "canonical-play-transition")' \ + <<<"$pull_request_json" >/dev/null; then + CANONICAL_PLAY_TRANSITION=true + fi elif [ "${{ github.event_name }}" = "workflow_run" ]; then [[ "${{ github.event.workflow_run.event }}" == "push" ]] || { echo "Runtime branch publication requires a CI push workflow run." >&2 @@ -270,6 +278,7 @@ jobs: echo "image_tag=${IMAGE_TAG}" echo "candidate_tag=${CANDIDATE_TAG}" echo "base_image=${BASE_IMAGE}" + echo "canonical_play_transition=${CANONICAL_PLAY_TRANSITION}" } >> "$GITHUB_OUTPUT" - name: Verify successful CI push for manual publication @@ -1522,6 +1531,8 @@ jobs: create-storage-record: false pr-local-smoke: + outputs: + publishable: ${{ steps.runtime-artifact.outcome == 'success' }} name: PR Full-Stack Smoke (runtime-required=${{ needs.image-meta.outputs.runtime_smoke_required }}) needs: [image-meta] if: ${{ (github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null)) || github.event_name == 'repository_dispatch' }} @@ -1633,6 +1644,8 @@ jobs: - name: Run credential-free full-stack smoke id: runtime-smoke + # The terminal guard admits only the classified, labeled transition failure. + continue-on-error: true if: ${{ needs.image-meta.outputs.runtime_smoke_required == 'true' }} env: FIREMUD_SMOKE_ADMISSION_QUALIFICATION: held @@ -1643,6 +1656,7 @@ jobs: run: bash ./dev-tools/verify-smoke-images.sh --keep-running - name: Export fixed-tag preview image artifact + if: ${{ success() && (needs.image-meta.outputs.runtime_smoke_required == 'false' || steps.runtime-smoke.outcome == 'success') }} run: | service_manifest=/tmp/pr-runtime-services.txt provenance=/tmp/pr-runtime-provenance.json @@ -1708,6 +1722,8 @@ jobs: docker save "${images[@]}" | gzip -1 > /tmp/pr-runtime-images.tar.gz - name: Upload preview image artifact + id: runtime-artifact + if: ${{ success() && (needs.image-meta.outputs.runtime_smoke_required == 'false' || steps.runtime-smoke.outcome == 'success') }} uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: name: pr-runtime-images-${{ needs.image-meta.outputs.image_tag }} @@ -1719,6 +1735,7 @@ jobs: retention-days: 1 - name: Summarize secure PR runtime artifact + if: ${{ success() && (needs.image-meta.outputs.runtime_smoke_required == 'false' || steps.runtime-smoke.outcome == 'success') }} env: PR_NUMBER: ${{ needs.image-meta.outputs.pr_number }} BASE_SHA: ${{ needs.image-meta.outputs.base_sha }} @@ -1741,7 +1758,7 @@ jobs: - name: Dump Docker Compose logs on failure if: >- - ${{ failure() && + ${{ always() && steps.runtime-smoke.outcome == 'failure' && needs.image-meta.outputs.runtime_smoke_required == 'true' && steps.minio-source.outputs.server_image_id != '' && steps.minio-source.outputs.client_image_id != '' }} @@ -1781,6 +1798,26 @@ jobs: exit 1 fi + # Canonical-transition diagnostic evidence, not runtime qualification. The + # native smoke outcome remains failed; only the bounded CI exception may pass. + - name: Known canonical transition PLAY failure with successful authenticated cleanup + id: canonical-play-transition + if: >- + ${{ always() && + github.repository == 'benhook1013/FireMUD' && + ((github.event_name == 'pull_request' && + contains(github.event.pull_request.labels.*.name, 'canonical-play-transition')) || + (github.event_name == 'repository_dispatch' && + github.event.action == 'pr-runtime-base-refresh' && + needs.image-meta.outputs.canonical_play_transition == 'true')) && + needs.image-meta.outputs.runtime_smoke_required == 'true' && + steps.runtime-smoke.outcome == 'failure' && + steps.runtime-smoke.outputs.known_play_failure == 'direct-backend-play-entitlement-unavailable-after-login' && + steps.runtime-cleanup.outcome == 'success' }} + run: | + echo '### Canonical PLAY transition exception evidence' >> "$GITHUB_STEP_SUMMARY" + echo 'LOGIN succeeded; direct backend PLAY failed: ERROR ENTITLEMENT_UNAVAILABLE. Held-admission qualification and authenticated cleanup passed. No runtime qualification, image export, or publication.' >> "$GITHUB_STEP_SUMMARY" + - name: Require successful runtime smoke and authenticated cleanup if: ${{ always() }} uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 @@ -1788,16 +1825,22 @@ jobs: RUNTIME_SMOKE_REQUIRED: ${{ needs.image-meta.outputs.runtime_smoke_required }} RUNTIME_SMOKE_OUTCOME: ${{ steps.runtime-smoke.outcome }} RUNTIME_CLEANUP_OUTCOME: ${{ steps.runtime-cleanup.outcome }} + KNOWN_PLAY_EXCEPTION_OUTCOME: ${{ steps.canonical-play-transition.outcome }} with: script: | const required = process.env.RUNTIME_SMOKE_REQUIRED; if (required !== "true" && required !== "false") { core.setFailed("Runtime smoke scope is unavailable or invalid."); } else if (required === "true" && ( - process.env.RUNTIME_SMOKE_OUTCOME !== "success" || - process.env.RUNTIME_CLEANUP_OUTCOME !== "success" + process.env.RUNTIME_CLEANUP_OUTCOME !== "success" || + (process.env.RUNTIME_SMOKE_OUTCOME !== "success" && !( + process.env.RUNTIME_SMOKE_OUTCOME === "failure" && + process.env.KNOWN_PLAY_EXCEPTION_OUTCOME === "success" + )) )) { - core.setFailed("Required runtime smoke and authenticated cleanup must both execute successfully."); + core.setFailed("Required runtime smoke and authenticated cleanup must both execute successfully, unless the exact canonical PLAY transition exception is attested."); + } else if (required === "true" && process.env.RUNTIME_SMOKE_OUTCOME === "failure") { + core.warning("CI passed under the canonical PLAY transition exception. Runtime qualification and image publication remain blocked."); } pr-controller-smoke: @@ -1870,7 +1913,7 @@ jobs: dispatch-pr-runtime-publication: name: Dispatch Trusted PR Runtime Publication needs: [image-meta, pr-local-smoke, pr-controller-smoke] - if: ${{ always() && !cancelled() && github.event_name == 'repository_dispatch' && github.event.action == 'pr-runtime-base-refresh' && github.ref == format('refs/heads/{0}', github.event.repository.default_branch) && needs.image-meta.result == 'success' && needs.pr-local-smoke.result == 'success' && (needs.pr-controller-smoke.result == 'success' || (needs.image-meta.outputs.controller_smoke_required == 'false' && needs.pr-controller-smoke.result == 'skipped')) }} + if: ${{ always() && !cancelled() && github.event_name == 'repository_dispatch' && github.event.action == 'pr-runtime-base-refresh' && github.ref == format('refs/heads/{0}', github.event.repository.default_branch) && needs.image-meta.result == 'success' && needs.pr-local-smoke.result == 'success' && needs.pr-local-smoke.outputs.publishable == 'true' && (needs.pr-controller-smoke.result == 'success' || (needs.image-meta.outputs.controller_smoke_required == 'false' && needs.pr-controller-smoke.result == 'skipped')) }} runs-on: ubuntu-latest timeout-minutes: 5 permissions: diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index 5e22468fea..a4bc626f22 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -176,7 +176,7 @@ jobs: : "skipped (run_smoke_full=false)"; const statusIcon = (value) => { if (value === "success") return "✅"; - if (value === "failure") return "❌"; + if (value === "failure" || value.startsWith("failure (")) return "❌"; if (value === "cancelled") return "⚪"; if (value === "pending") return "⏳"; if (value === "unavailable") return "⚠️"; @@ -313,6 +313,7 @@ jobs: CHANGES_RESULT: ${{ needs.changes.result }} RUN_SMOKE_FULL: ${{ needs.changes.outputs.run_smoke_full }} SMOKE_GATE_RESULT: ${{ needs.smoke-gate.result }} + KNOWN_PLAY_EXCEPTION: ${{ needs.smoke-gate.outputs.known_play_exception }} with: script: | const rawChangesResult = process.env.CHANGES_RESULT || ""; @@ -325,14 +326,17 @@ jobs: const smokeGateStatus = ["success", "failure", "cancelled", "skipped"].includes(rawSmokeGateResult) ? rawSmokeGateResult : "unavailable"; - const fullResult = !changesHealthy + const knownPlayException = process.env.KNOWN_PLAY_EXCEPTION === "true" && smokeGateStatus === "success"; + const fullResult = knownPlayException + ? "failure (known PLAY exception accepted; no runtime qualification or publication)" + : !changesHealthy ? `not-evaluated (${changesStatus} changes detection)` : fullEnabled ? smokeGateStatus : "skipped (run_smoke_full=false)"; const statusIcon = (value) => { if (value === "success") return "✅"; - if (value === "failure") return "❌"; + if (value === "failure" || value.startsWith("failure (")) return "❌"; if (value === "cancelled") return "⚪"; if (value === "skipped") return "⏭️"; if (value === "unavailable") return "⚠️"; @@ -343,6 +347,8 @@ jobs: let headline = "⏭️ Runtime smoke is not required"; if (!changesHealthy) { headline = `${statusIcon(smokeGateStatus)} Smoke Gate completed with ${smokeGateStatus}; scope detection was ${changesStatus}`; + } else if (knownPlayException) { + headline = "⚠️ Known PLAY failed: ERROR ENTITLEMENT_UNAVAILABLE after LOGIN. Canonical PLAY transition exception accepted; no runtime qualification or publication."; } else if (fullEnabled) { headline = `${statusIcon(smokeGateStatus)} Full-stack smoke completed with Smoke Gate: ${smokeGateStatus}`; } @@ -449,6 +455,8 @@ jobs: } smoke-gate: + outputs: + known_play_exception: ${{ steps.track-runtime-smoke.outputs.known_play_exception }} name: Smoke Gate runs-on: ubuntu-latest permissions: @@ -536,6 +544,7 @@ jobs: run: echo "No runtime-stack smoke proof is required for this change." - name: Track full-stack smoke result from Build Runtime Images + id: track-runtime-smoke if: ${{ steps.smoke_gate_context.outputs.execute == 'true' && needs.changes.outputs.run_smoke_full == 'true' }} uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 with: @@ -599,7 +608,26 @@ jobs: } // One canonical producer definition; the contract test reports fingerprint upkeep. - const canonicalRuntimeWorkflowSha256 = "e939f7a6205e9626fdb6fbe1ab6b908bc8eb9f8912b919a1f5c5491ac6804936"; + const canonicalRuntimeWorkflowSha256 = "520407ce97e1ffbe1db824264f0a64e95887f36df2dc07d5738bed4448759ae2"; + // Retain the exact fail-red producer still executed by trusted base refreshes. + const canonicalLegacyRuntimeWorkflowSha256 = "db0acb4e51630b729eb92362ea3e748f3f96b06d8ef5ca466a718ded67725804"; + // Include held-admission proof, authenticated cleanup, and their executed inputs. + const canonicalPlayClassifierSha256 = { + "dev-tools/verify-smoke-images.sh": "559e0713cc86ab533cc23214e56ece2e7cf4e069d1bb7541a1e09bff36ad4c67", + "dev-tools/smoke/smoke_common.py": "a1e36948b500ac796295560cb8c22321ebe47eab78be9e1f4d58837053547534", + "services/game-session-service/websocket-login-look-smoke.sh": "0a6fbc66f7bf16aaf065bf1228d5190be340ce25543112e39482b9325ad9a90b", + "dev-tools/smoke/demo-smoke-defaults.sh": "8c9aae1abf005b47af3f313e0d635a666c74776733bcf5278a2e11ac9c8a18fb", + "dev-tools/smoke/held-admission-qualification.sh": "b548a773f1786b72d40a3728052a336cb249257a3f40735f005b060812184ed3", + "dev-tools/smoke/held_admission_qualification.py": "2d118d7ba6a19dac7d8c717dbbbe25df6f04a3c186a3185135d1bdc5fc75b557", + "dev-tools/smoke/run-owned-compose.sh": "c2a0590c98d39a8c8ec22c20e692948136a5ec53ca2dfc0b29db7323a3e1b6be", + "dev-tools/certs/ensure-dev-certs.sh": "30f4ab5c9cb7af7f9d4a477ce923cfad19a319a85b6e05957f7d24eae9baddd2", + ".env.sample": "d19cecadde844c77b8e1d366b5a2ff8fae1a5c181fad450f3fc1c407be70752d", + "docker/docker-compose.yml": "f43581c67747dfb732742ecc1c4de631a71a2a41ae535663fb3872a90b68e2f1", + "docker/docker-compose.override.yml": "2e720be03f942fd4456d46cea5a127f16106a1056aec6ddaaf52b2bb31b51d75", + "docker/docker-compose.smoke-images.override.yml": "7717be8b49a1dc548a47fba852c181feeb4dbe9a21fc201a7f8e74b992801fd6", + "docker/docker-compose.pr-local-minio.override.yml": "d975ce211afcb73079a21c70fda358e3a8f3366b83fe0302907c9d7149ce965e", + "docker/docker-compose.grpc-mtls.override.yml": "dcee047f1492392035d57153ba8dfd6d38de33ca932d327f377440d5813577f0" + }; const canonicalSmokeJobName = "PR Full-Stack Smoke (runtime-required=true)"; const workflowPath = ".github/workflows/runtime-images.yml"; const repositoryName = `${owner}/${repo}`; @@ -745,6 +773,9 @@ jobs: job.head_sha !== source.head_sha || job.status !== "completed" || job.conclusion !== "success" || job.check_run_url !== `https://api.github.com/repos/${repositoryName}/check-runs/${job.id}` ) return false; + const markers = (job.steps ?? []).filter((step) => + step.name === "Known canonical transition PLAY failure with successful authenticated cleanup" + ); // PR workflows execute their test merge definition; typed refreshes execute the // immutable default-branch revision recorded by their native run attempt. const workflowSha = source.event === "pull_request" ? identity.mergeSha : source.head_sha; @@ -756,8 +787,11 @@ jobs: definition.encoding !== "base64" || typeof definition.content !== "string") return false; const bytes = Buffer.from(definition.content, "base64"); if (definition.size !== bytes.length) return false; - if (require("node:crypto").createHash("sha256").update(bytes).digest("hex") !== - canonicalRuntimeWorkflowSha256) return false; + const definitionHash = require("node:crypto").createHash("sha256").update(bytes).digest("hex"); + if (definitionHash === canonicalRuntimeWorkflowSha256) { + if (markers.length !== 1 || markers[0].status !== "completed" || + markers[0].conclusion !== "skipped") return false; + } else if (definitionHash !== canonicalLegacyRuntimeWorkflowSha256) return false; const { data: latest } = await withTransientGitHubRetry( "current runtime attempt lookup", () => github.rest.actions.getWorkflowRun({ owner, repo, run_id: source.id }) @@ -766,6 +800,127 @@ jobs: latest.status === "completed" && latest.conclusion === "success"; } + // Canonical-transition diagnostic acceptance never becomes passing producer proof. + async function verifyKnownPlayFailure(run, candidate, identity) { + if (repositoryName !== "benhook1013/FireMUD" || + !["pull_request", "repository_dispatch"].includes(run.event)) return false; + if (!positiveInteger(run.id) || !positiveInteger(run.run_attempt)) return false; + const { data: source } = await withTransientGitHubRetry( + "exact runtime workflow attempt lookup", + () => github.request("GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}", { + owner, repo, run_id: run.id, attempt_number: run.run_attempt, + }) + ); + const expectedTitle = `Build Runtime Images secure-pr-artifact pr-${prNumber} ` + + `base-${identity.baseSha} head-${identity.headSha} merge-${identity.mergeSha} mode-required`; + if ( + source.id !== run.id || source.run_attempt !== run.run_attempt || + source.status !== "completed" || !["success", "failure"].includes(source.conclusion) || + source.path !== workflowPath || source.repository?.full_name !== repositoryName || + !positiveInteger(source.workflow_id) || source.display_title !== expectedTitle || + source.event !== run.event + ) return false; + const expectedHeadRepository = context.payload.pull_request.head.repo?.full_name; + if (typeof expectedHeadRepository !== "string" || + expectedHeadRepository !== repositoryName || + source.head_repository?.full_name !== expectedHeadRepository) return false; + if (source.event === "pull_request" && source.head_sha !== identity.headSha) return false; + if (source.event === "repository_dispatch" && ( + source.head_branch !== context.payload.repository.default_branch || + !/^[0-9a-f]{40}$/.test(source.head_sha ?? "") + )) return false; + const { data: workflow } = await withTransientGitHubRetry( + "runtime workflow identity lookup", + () => github.rest.actions.getWorkflow({ owner, repo, workflow_id: source.workflow_id }) + ); + if (workflow.id !== source.workflow_id || workflow.path !== workflowPath || + workflow.name !== "Build Runtime Images") return false; + const jobs = await withTransientGitHubRetry( + "exact runtime attempt jobs lookup", + () => github.paginate( + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", + { owner, repo, run_id: source.id, attempt_number: source.run_attempt, per_page: 100 } + ) + ); + const producers = jobs.filter((job) => job.name === canonicalSmokeJobName); + if (producers.length !== 1) return false; + const job = producers[0]; + if ( + !positiveInteger(job.id) || job.id !== candidate.id || + job.run_id !== source.id || job.run_attempt !== source.run_attempt || + job.head_sha !== source.head_sha || job.status !== "completed" || job.conclusion !== source.conclusion || + job.check_run_url !== `https://api.github.com/repos/${repositoryName}/check-runs/${job.id}` + ) return false; + const expectedSuccessfulSteps = [ + "Run credential-free full-stack smoke", + "Require successful runtime smoke and authenticated cleanup", + ]; + const markerName = "Known canonical transition PLAY failure with successful authenticated cleanup"; + const steps = job.steps ?? []; + const exactlyOne = (name, conclusion) => steps.filter((step) => + step.name === name && step.status === "completed" && step.conclusion === conclusion + ).length === 1; + if (!exactlyOne(markerName, "success") || !exactlyOne("Stop smoke stack", "success") || + !exactlyOne("Export fixed-tag preview image artifact", "skipped") || + !exactlyOne("Upload preview image artifact", "skipped") || + expectedSuccessfulSteps.some((name) => !exactlyOne(name, source.conclusion)) || + steps.some((step) => step.status !== "completed" || + !["success", "skipped", "failure"].includes(step.conclusion) || + (step.conclusion === "failure" && !(source.conclusion === "failure" && expectedSuccessfulSteps.includes(step.name)))) || + jobs.some((other) => other.id !== job.id && + (other.status !== "completed" || !["success", "skipped"].includes(other.conclusion)))) return false; + // Typed refresh workflow authority is its native default-branch revision; + // the executed classifier source still belongs to the verified PR merge. + const workflowSha = source.event === "pull_request" ? identity.mergeSha : source.head_sha; + for (const [path, expectedSha256] of Object.entries({ + [workflowPath]: source.conclusion === "failure" + ? canonicalLegacyRuntimeWorkflowSha256 : canonicalRuntimeWorkflowSha256, + ...canonicalPlayClassifierSha256, + })) { + const { data: definition } = await withTransientGitHubRetry( + `immutable PLAY classifier definition lookup: ${path}`, + () => github.rest.repos.getContent({ + owner, repo, path, ref: path === workflowPath ? workflowSha : identity.mergeSha, + }) + ); + if (definition.type !== "file" || definition.path !== path || + definition.encoding !== "base64" || typeof definition.content !== "string") return false; + const bytes = Buffer.from(definition.content, "base64"); + if (definition.size !== bytes.length) return false; + if (require("node:crypto").createHash("sha256").update(bytes).digest("hex") !== + expectedSha256) return false; + } + const { data: latest } = await withTransientGitHubRetry( + "current runtime attempt lookup", + () => github.rest.actions.getWorkflowRun({ owner, repo, run_id: source.id }) + ); + if (latest.id !== source.id || latest.run_attempt !== source.run_attempt || + latest.status !== "completed" || latest.conclusion !== source.conclusion) return false; + // The fingerprinted marker attests the PR event label or the typed + // refresh's verified live PR label. Removal closes either exception. + const { data: currentPullRequest } = await withTransientGitHubRetry( + "current canonical transition label lookup", + () => github.rest.pulls.get({ owner, repo, pull_number: Number(prNumber) }) + ); + if (!(currentPullRequest.state === "open" && + currentPullRequest.head?.repo?.full_name === repositoryName && + currentPullRequest.base?.repo?.full_name === repositoryName && + currentPullRequest.head?.sha === identity.headSha && + currentPullRequest.base?.ref === identity.baseRef && + Array.isArray(currentPullRequest.labels) && + currentPullRequest.labels.some((label) => label?.name === "canonical-play-transition"))) return false; + if (source.event === "repository_dispatch") { + if (currentPullRequest.merge_commit_sha !== identity.mergeSha) return false; + const { data: currentBase } = await withTransientGitHubRetry( + "current canonical transition base ref lookup", + () => github.rest.git.getRef({ owner, repo, ref: `heads/${identity.baseRef}` }) + ); + if (currentBase.ref !== `refs/heads/${identity.baseRef}` || + currentBase.object?.sha !== identity.baseSha) return false; + } + return true; + } + // Commit objects are immutable; mutable PR/base reads stay fresh. const immutableCommits = new Map(); async function immutableCommit(ref, label) { @@ -1067,6 +1222,37 @@ jobs: if (await isCurrentPullRequestObsolete("Stopping obsolete failed smoke gate for")) { return; } + if (matching.conclusion === "failure" && repositoryName === "benhook1013/FireMUD" && + ["pull_request", "repository_dispatch"].includes(matching.event)) { + let knownPlayVerified = false; + try { + const jobs = await withTransientGitHubRetry("canonical transition PLAY failure jobs lookup", () => + github.paginate("GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", { + owner, repo, run_id: matching.id, attempt_number: matching.run_attempt, per_page: 100, + }) + ); + const candidate = jobs.find((job) => job.name === canonicalSmokeJobName); + knownPlayVerified = Boolean(candidate) && + await verifyKnownPlayFailure(matching, candidate, currentIdentity); + } catch (error) { + if (error instanceof TerminalGitHubRequestError) throw error; + core.warning(`Canonical PLAY transition exception proof is unavailable: ${error?.message ?? String(error)}`); + } + if (knownPlayVerified) { + const freshIdentity = await resolveCurrentIdentity("Stopping stale canonical transition PLAY exception"); + if (freshIdentity?.obsolete) return; + if (!freshIdentity || identityKey(freshIdentity) !== identityKey(currentIdentity)) { + currentIdentity = freshIdentity; + continue smokeGatePolling; + } + core.setOutput("known_play_exception", "true"); + core.warning("Canonical PLAY transition exception accepted: LOGIN succeeded, direct backend PLAY failed ERROR ENTITLEMENT_UNAVAILABLE. No runtime qualification or image publication."); + await core.summary.addHeading("Canonical PLAY transition exception accepted") + .addRaw("Known PLAY failed: ERROR ENTITLEMENT_UNAVAILABLE after LOGIN. Held-admission qualification and authenticated cleanup passed. No runtime qualification, image export, or publication.") + .write(); + return; + } + } core.setFailed( `Runtime images run ${matching.id} did not complete successfully: run=${matching.conclusion}` ); @@ -1181,6 +1367,45 @@ jobs: return; } + // A continued probe has API conclusion=success even when its native + // outcome failed. The immutable marker distinguishes that exception. + if (fullSmokeJob?.name === canonicalSmokeJobName) { + const markers = (fullSmokeJob.steps ?? []).filter((step) => + step.name === "Known canonical transition PLAY failure with successful authenticated cleanup" + ); + if (markers.length === 1 && markers[0].status === "completed" && + markers[0].conclusion === "success") { + let knownPlayVerified = false; + try { + knownPlayVerified = await verifyKnownPlayFailure(matching, fullSmokeJob, currentIdentity); + } catch (error) { + if (error instanceof TerminalGitHubRequestError) throw error; + core.warning(`Canonical PLAY transition exception proof is unavailable: ${error?.message ?? String(error)}`); + } + if (!knownPlayVerified) { + core.setFailed("Canonical PLAY transition exception could not be verified; runtime qualification remains blocked."); + return; + } + const freshIdentity = await resolveCurrentIdentity("Stopping stale canonical transition PLAY exception"); + if (freshIdentity?.obsolete) return; + if (!freshIdentity || identityKey(freshIdentity) !== identityKey(currentIdentity)) { + currentIdentity = freshIdentity; + continue smokeGatePolling; + } + core.setOutput("known_play_exception", "true"); + core.warning("Canonical PLAY transition exception accepted: LOGIN succeeded, direct backend PLAY failed ERROR ENTITLEMENT_UNAVAILABLE. No runtime qualification or image publication."); + await core.summary.addHeading("Canonical PLAY transition exception accepted") + .addRaw("Known PLAY failed: ERROR ENTITLEMENT_UNAVAILABLE after LOGIN. Held-admission qualification and authenticated cleanup passed. CI passed under exception; no runtime qualification, image export, or publication.") + .write(); + return; + } + if (!canonicalProducerVerified && (markers.length !== 1 || + markers[0].status !== "completed" || markers[0].conclusion !== "skipped")) { + core.setFailed("Runtime smoke proof is missing its unambiguous transition-exception disposition."); + return; + } + } + if (fullSmokeJob?.conclusion !== "success") { if (await isCurrentPullRequestObsolete("Stopping obsolete failed full-smoke gate for")) { return; diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index e240d5d39a..ee10b7d2a6 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -99,15 +99,17 @@ At effective expiry or revocation, Account publishes the monotonic grant-authori ### Public bootstrap WORLDS discovery -`ListBootstrapWorlds` returns the complete set of unambiguous visible public-production worlds whose current Account entitlement says gameplay is available. Account verifies the existing browser-bootstrap credential against its persisted account identity, obtains the complete canonical target collection from Game Session, evaluates current entitlement once for each represented canonical tenant, and revalidates the caller and checks each original entitlement observation deadline before returning a deterministic `worldSlug` ordering. The Account owner fails the whole request when the target collection changes, is ambiguous, or cannot be read completely, or when any required entitlement is unavailable or expired; it never returns a partial list. The canonical target collection contract and limits are owned by [Game Session's public-production target collection read](../game-session-service/api-contracts.md#public-production-bootstrap-target-collection-read). +Each visible world returns its stable `tenantSlug` and tenant-scoped `worldSlug` with its display name. Different tenants may expose the same world slug; clients retain both selectors and pass `tenantSlug` as the required query parameter to `GET /auth/bootstrap/worlds/{worldSlug}/realms`. Account resolves the pair against one complete current discovery collection. A bare or globally inferred world selector is not a supported browser request. The resulting opaque `connectScopeId` binds the exact tenant and realm for subsequent character discovery and admission; the character route still verifies its world/realm path against that scope. + +`ListBootstrapWorlds` returns the complete set of visible public-production tenant-qualified world selectors whose current Account entitlement says gameplay is available. The whole request fails if the collection represents one canonical tenant more than once; shared world slugs across different tenants remain valid. Account verifies the existing browser-bootstrap credential against its persisted account identity, obtains the complete canonical target collection from Game Session, evaluates current entitlement once for each represented canonical tenant, and revalidates the caller and checks each original entitlement observation deadline before returning a deterministic `worldSlug`, then `tenantSlug`, ordering. The Account owner fails the whole request when the target collection changes, is ambiguous, or cannot be read completely, or when any required entitlement is unavailable or expired; it never returns a partial list. The canonical target collection contract and limits are owned by [Game Session's public-production target collection read](../game-session-service/api-contracts.md#public-production-bootstrap-target-collection-read). Independent tenant entitlement evaluations run outside ambient SQL with at most eight concurrent workers per discovery request. A shared fair eight-permit bound also limits active evaluations across all discovery requests and owner instances in the Account process. Waiting for a permit occurs outside SQL and lasts at most five seconds; contention expiry fails the whole discovery request as `ENTITLEMENT_UNAVAILABLE`. Success, source failure and interruption return acquired permits. This bounds this owner’s aggregate connection demand without resizing the Account pool or guaranteeing production capacity. Each tenant is evaluated once and retains its owner’s independent transaction/isolation checks; caller and SQL context are not propagated to workers. The owner waits for the complete set, validates every returned tenant identity and returns no partial result on failure or interruption. Original observation deadlines remain unchanged and are checked after the second complete target read and final caller check. This bound reduces serialized latency; it is not a production capacity guarantee or permission to extend expired evidence, and slow or large collections can still refuse when their original observations expire. An unreachable Game Session authority maps to `AUTH_UNAVAILABLE`; a reachable malformed, ambiguous, or changed collection maps to `ADMISSION_POINTER_UNAVAILABLE`; and an unavailable or expired entitlement maps to `ENTITLEMENT_UNAVAILABLE`. Bootstrap-caller verification retains its authentication failure. None of these failures produces an empty or partial success. -`gameplayAvailable` controls discovery visibility; `allowPublicJoin` does not. This pre-scope result contains only world slug and display name and creates no membership, JOIN, connect scope, or gameplay-admission authority. Public bootstrap discovery does not resolve private playtest realms or substitute for later target selection, current entitlement, membership, grant, or admission checks. +`gameplayAvailable` controls discovery visibility; `allowPublicJoin` does not. This pre-scope result contains only tenant slug, world slug and display name and creates no membership, JOIN, connect scope, or gameplay-admission authority. Public bootstrap discovery does not resolve private playtest realms or substitute for later target selection, current entitlement, membership, grant, or admission checks. -The manually composed `AccountCanonicalPublicRealmScopeOwner` uses the same public source collection for UUID-bearing V2 selector scopes. It rechecks Account identity, fresh tenant provenance, current membership and billing-head observations in short Account transactions, retains the exact signed scope preimage and verifies its immutable readback. Protected Game Session, registry and provider reads stay outside those transactions. Scope expiry follows the configured scope lifetime capped by the original verified bootstrap expiry; a later check cannot restamp an expired observation. Public visibility remains membership-independent, while current membership and `allowPublicJoin` are facts for subsequent fresh selection and JOIN checks. The scope grants neither membership repair nor gameplay admission. This source remains unregistered and separate from the existing numeric facade and private-realm path; its proof and receiving gaps are recorded in [Player Access](../../../project-management/implementation-tracking/player-access-and-session.md#public-bootstrap-worlds-source-preparation). +The manually composed `AccountCanonicalPublicRealmScopeOwner` uses the same public source collection for UUID-bearing V2 selector scopes. It rechecks Account identity, fresh tenant provenance, current membership and billing-head observations in short Account transactions, retains the exact signed scope preimage and verifies its immutable readback. Protected Game Session, registry and provider reads stay outside those transactions. Scope expiry follows the configured scope lifetime capped by the original verified bootstrap expiry; a later check cannot restamp an expired observation. Public visibility remains membership-independent, while current membership and `allowPublicJoin` are facts for subsequent fresh selection and JOIN checks. The scope grants neither membership repair nor gameplay admission. This source is manually composed by the public UUID facades but remains unregistered and separate from the private-realm path; its proof and receiving gaps are recorded in [Player Access](../../../project-management/implementation-tracking/player-access-and-session.md#public-bootstrap-worlds-source-preparation). ### Account-Owned Safety Restriction Contract @@ -125,11 +127,11 @@ Fresh-enrollment certification is internal Account owner work, not a public regi ## Implementation Status -The public bootstrap WORLDS source is prepared as an unregistered Account owner and is not yet wired into the existing `ListBootstrapWorlds` facade. Its current schema-backed source is the canonical Account DEMO entitlement; paid-hosting discovery remains unavailable until the subscription schema and retained facade consumers migrate together. Current source and proof status are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#public-bootstrap-worlds-source-preparation). +The UUID billing foundation archives numeric subscription rows as immutable, non-authorizing retained evidence and supplies canonical intent, provisioning, lifecycle and cancellation-recovery storage. It also prepares the distinct [`TENANT_OPERATION` source and protected transport](#private-tenant-operation-entitlement-read); these owners remain manually composed and unregistered. Detailed receiving proof and unfinished authority boundaries belong to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). -Additional unregistered source prepares separate World Management [`TENANT_OPERATION` entitlement reads](#private-tenant-operation-entitlement-read) and Game Session [player-admission entitlement reads](#private-player-admission-entitlement-read), held hosting provisioning and terminal-resolution owners, a signed canonical V2 scope reader, and an Account client for Entity-owned persisted bootstrap-roster discovery. These sources do not replace the existing public discovery/JOIN facade or runtime entitlement RPC, register a receiver, or enable player admission. The scope reader verifies an existing selector rather than authenticating its caller; the roster read supplies transient persisted discovery rather than a selection, actor allocation, session, or admission result. Exact source boundaries and pending proof are recorded in [local source-foundation preparation](../../../project-management/implementation-tracking/player-access-and-session.md#local-source-foundation-preparation). +The public WORLDS/REALMS, browser/direct JOIN and CHARS facades now delegate to explicitly composed canonical UUID owners and the retained V2 reader; absent composition returns `AUTH_UNAVAILABLE` before legacy sources. JOIN captures actual Account intent/member/pair/role/event/audit state, reads protected Game Session/World and provider sources outside SQL, then revalidates in its final Account transaction. Existing ACTIVE membership returns its truthful snapshot without repair; INACTIVE restoration advances its membership version/event. `gameplayAdmissionAllowed` is an explicit result and a successful membership response cannot grant gameplay when false. -The opaque `bootstrap-connect-scope` artifact uses canonical non-nil Account UUID subject/claim equality. Both browser discovery and the existing direct-text Account producer obtain that identity from Account persistence; the dedicated reader resolves it back to Account-local storage before existing binding checks. Numeric scopes have no compatibility parser: clients obtain fresh scope evidence through bounded rediscovery, while retained rows/receipts are not rewritten and existing retained-replay guards remain. Caller authentication, public-join policy and the held connect-token issuer are unchanged. Detailed receiving proof belongs to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#bootstrap-connect-scope-uuid-artifact). +CHARS requires the verified browser bootstrap caller and exact retained target, fresh membership and entitlement before the purpose-specific [Entity persisted discovery read](../entity-management-service/api-contracts.md#account-bootstrap-persisted-actor-discovery), followed by fresh caller/member/entitlement/target checks. Only supported SHARED/PRESEEDED_ONLY targets may return actual persisted actors or a valid empty result. Unsupported private/isolated/player-created/auto-provisioned discovery is unavailable rather than an empty success. Discovery creates no selection, actor, retention or admission authority. Complete source protection through a later commit, default registration and canonical runtime cutover remain unfinished; [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-public-account-facade-receiving) owns proof and remaining scope. The prepared selected gameplay-rule intake authorization, source-reservation/recovery, read and terminal-settlement owners are standalone and unregistered. Their typed transports add no available API or caller authority. Before enabling any standalone intake receiver (authorization, source read, HELD read, or settlement), its inbound message limit must accommodate the applicable 24 MiB codec bound: authorization and HELD read use `GameLogicIntakeAuthorizationGrpcCodec.MAX_WIRE_BYTES`; source read uses `GameLogicIntakeSourceReadProtoCodec.MAX_WIRE_BYTES`; settlement uses `AccountGameLogicIntakeSettlementEvidence.MAX_WIRE_BYTES`. The authorization receiver also carries the unchanged protected creator credential in binary metadata, so its inbound metadata limit must accommodate `AccountGameLogicIntakeAuthorizationCredentials.MAX_METADATA_BYTES`, which includes base64 wire encoding of the existing 16 KiB credential maximum plus metadata overhead. Binding a service configures neither limit. These are required receiver configurations, not claims about current deployment. The [Account prerequisite tracker](../../../project-management/implementation-tracking/player-access-and-session.md#selected-gameplay-rule-intake-authorization-prerequisite) records qualification and receiving pipeline gaps. @@ -141,8 +143,6 @@ Account UUID generation currently has three established provenances: `ACCOUNT_RE This Account source-currentness and first-JOIN persistence prerequisite builds on the authority-storage and retention-safety stage. V40 adds owner-proven fresh issuer/Account source baselines and complete transactional source-event hooks; the owner-local first-JOIN producer/coordinator composes immutable membership, event, audit, and terminal operation evidence. These primitives do not authenticate callers, supply the cross-service target-through-commit gate, add a public route, or wire current LOGIN/public JOIN/Game Session text JOIN. Validation of the reconciled source-currentness stage remains pending; inherited storage proof is not proof of these additions. #2898 and #2848 retain their runtime and recovery gaps. -Current explicit JOIN status: the local `/auth/bootstrap/join` controller and operation are implemented, but the exact Gateway path is blocked by its route guard and the route is absent from `publicOpenAPI`. Local policy-digest revalidation does not prove that the exact target remains valid through Account commit; the strict ADR 0025 commit gate remains incomplete. The canonical owner is [Runtime & Data](./runtime-and-data.md#membership-and-entitlement-authority), with the target contract in [ADR 0025](../../decisions/adr-0025-explicit-open-enrollment-membership.md). - `ResolveRuntimeAccountIdentity` is implemented as an authenticated Account-owner provenance read. The isolated producer extraction passes 31 focused unit tests, Account integration-source compilation, and formatting/documentation checks. These are handler, codec, and interceptor-wiring proofs, not PostgreSQL execution or a live mTLS handshake. The exact RPC is listed in `public-methods` in both base and production Account configuration to bypass bearer-token validation for this workload-only method; the gRPC listener still requires mTLS and the handler authorizes only the exact same-namespace Game Session and Entity Management workload identities. This result establishes neither Account UUID authentication nor membership, grants, actor ownership, namespace selection, or gameplay admission. Explicit playtest grants remain partial: registered Account persistence and internal lookup retain the legacy four-field identity. Unregistered lifecycle-bound storage and its current-lifecycle read retain explicit expiry bounded by fork expiry, request-idempotent outcomes and revocation tombstones. Registered management and consumer entry points, tenant-admin create/extend/list/revoke, distinct audited platform break-glass mutation, qualified actor authorization and active-binding ejection remain incomplete or unproved. The [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#lifecycle-bound-private-realm-grant-source-preparation) records the local proof and remaining gaps. The target owner contract is [Account-Owned Playtest Grant Contract](#account-owned-playtest-grant-contract); the links in authentication, session behavior, journeys, and trackers retain only their local consequences. @@ -151,7 +151,17 @@ Account has unregistered individual Creator Party, hosted-terms catalog, and ind `CommitTenantCapacityAdmission` is target-only. Its canonical request contract requires the stable identity, expected complete applicable `authorityTuple`, separate expected `entitlementVersion`, exact expected billing stream/checkpoint evidence, capacity delta, and versioned `mutationDigest`, but no proto RPC, durable authority/usage ledger, caller integration, or reservation-finalization path is implemented. The target replay rule is exact identity-and-payload replay with any changed tuple, entitlement, checkpoint, delta, or digest producing an idempotency conflict; implementation and focused proof remain future capability work rather than a nonfunctional service seam. -The account lifecycle API, export surfaces, and deletion-precondition contracts are defined at the current Account Service boundary, but lifecycle state-transition execution remains partial as recorded in [Runtime & Data](./runtime-and-data.md). Account is the authority and transaction boundary for the committed transition, authority-generation/version advance, and durable event/outbox evidence. Downstream revocation, projection, cleanup, and provider reconciliation are ordered transition execution; partial downstream completion must be reported separately and must not be mistaken for a rolled-back lifecycle state or completed enforcement outcome. The current `GET /accounts/{accountId}/export` implementation is Account/profile-local, with identity projections governed by [Account UUID response and REST selector identity](#account-uuid-response-and-rest-selector-identity). This is partial data, not the canonical target portable-data export lifecycle, which is `POST /accounts/{accountId}/exports` followed by the stable status and content resources defined below. `ExportTenantData` targets the separate tenant-admin route `GET /tenant-admin/tenants/{tenantId}/export`, which is tenant-wide and selects no account subject; the current account-targeted gRPC and legacy tenant-export wiring remain implementation drift. Password reset, username reminder, and email-verification tokens are account-scoped rather than tenant-keyed. Profiles are tenant-scoped under ADR 0042, so the current account-only `/profiles/{accountId}` route and policy remain implementation drift pending direct convergence on tenant-qualified routes. The legacy profile selector and authorization consequences are recorded under [REST APIs](#rest-apis); membership-authority-generation validation remains unimplemented. Public registration follows the response identity contract below and writes that same public identity in its platform audit outbox row; it creates only global Account state and does not create a profile or tenant membership. Explicit public-production `JOIN` / `Join & Play` is implemented locally through `JoinPublicProductionMembership`. Account first persists a policy-independent request-intent digest and `PENDING` operation, then evaluates current public-join entitlement. Only an authoritative `AVAILABLE` evaluation creates the versioned policy-bound operation digest and stores the exact `allowPublicJoin` and `entitlementVersion`; an unavailable attempt records its failure and availability and leaves the operation `PENDING` without invented policy evidence. A matching retry can re-evaluate that pending operation, and the membership commit gate revalidates the same digest and policy evidence. The operation, membership transition, and tenant audit outbox evidence are committed together. Focused local PostgreSQL retry/rollback proof is recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#account-email-verification-and-deferred-currency-containment); original-outcome observation after retry authority expires and direct-text end-to-end proof remain open. The current runtime membership response carries `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`, with `accountId` and `tenantId` context. Current `/auth/connect-token` issuance returns `AUTH_UNAVAILABLE` after bootstrap and scope validation, before replay or admission-authority reads, token minting, or replay/session mutation; cached-success replay and current membership, entitlement, grant, and pointer checks do not execute on this path. Current text `PLAY` validates the emitted `membershipLifecycleState` and independent `membershipAuthorityGeneration` and requires coherent `ACTIVE` admitting membership. Missing or `INACTIVE` public-production membership yields `JOIN_REQUIRED` only when fresh enrollment policy permits repair; an existing active but non-admitting response is not a join fallback. The implemented consumer limits remain in [Account runtime status](./runtime-and-data.md#implementation-status); these checks do not establish the complete caller-target and atomic-freshness contract. Current non-public or non-visible target handling remains split across existing discovery, membership, and grant surfaces; the complete grant/entitlement admission predicate at connect-token issuance remains target-only. The obsolete implicit membership-writer surface has been removed and is not a compatibility operation. `/auth/player-bootstrap` is account-first and factor-aware. The browser connect-token body and OpenAPI response are defined as metadata-only; any issued raw token is carried only in the HttpOnly cookie. The registry-backed issuance, refresh, revocation, durable retry, and authority-generation behaviors below are target state, including the contracts for `Authenticate`, `RefreshGameplayServiceToken`, `/auth/player-bootstrap`, `/auth/logout`, and `/auth/logout-all`; `/auth/login` is currently routable but still lacks the complete registry-backed target behavior. Current Account sessions use the legacy `session:auth:account::` key and, for tenant-scoped sessions, the companion `session:auth:tenant::` key rather than the canonical single `session:auth:token:` registry record. The `player-bootstrap` credential/result profile uses the persisted Account UUID in its result `accountId` and matching JWT subject/Account claim; its Account-owned reader rejects noncanonical, numeric or mismatched identity before resolving the private storage row. The final ordinary receiving composition also carries UUID ordinary login results/credentials, UUID shared intake and forwarding, UUID internal selectors and UUID Account references in downstream consumers; tenant identifiers remain numeric. Full token-profile/registry qualification remains held. Derived `bootstrap-connect-scope` artifacts use the persisted Account UUID in their signed subject/Account claim, through the shared browser/direct-text producer and dedicated Account reader. Profile self-binding and REST caller identity use UUID `SessionContext`; private Account SQL rows remain numeric. The legacy GameInstance owner/StartSession boundary remains separately numeric and unqualified. The bounded response and REST selector identity contract is defined below. Scoped-role population and tenant-switching proof remain target-state work: current `authenticate` issuance provides `globalRoles` but does not yet populate or prove `scopedRoles[tenantId]` as authorization evidence. +The account lifecycle API, export surfaces, and deletion-precondition contracts are defined at the current Account Service boundary, but lifecycle state-transition execution remains partial as recorded in [Runtime & Data](./runtime-and-data.md). Account is the authority and transaction boundary for the committed transition, authority-generation/version advance, and durable event/outbox evidence. Downstream revocation, projection, cleanup, and provider reconciliation are ordered transition execution; partial downstream completion must be reported separately and must not be mistaken for a rolled-back lifecycle state or completed enforcement outcome. The current `GET /accounts/{accountId}/export` implementation is Account/profile-local, with identity projections governed by [Account UUID response and REST selector identity](#account-uuid-response-and-rest-selector-identity). This is partial data, not the canonical target portable-data export lifecycle, which is `POST /accounts/{accountId}/exports` followed by the stable status and content resources defined below. `ExportTenantData` targets the separate tenant-admin route `GET /tenant-admin/tenants/{tenantId}/export`, which is tenant-wide and selects no account subject; the current account-targeted gRPC and legacy tenant-export wiring remain implementation drift. Password reset, username reminder, and email-verification tokens are account-scoped rather than tenant-keyed. Profiles are tenant-scoped under ADR 0042, so the current account-only `/profiles/{accountId}` route and policy remain implementation drift pending direct convergence on tenant-qualified routes. The legacy profile selector and authorization consequences are recorded under [REST APIs](#rest-apis); membership-authority-generation validation remains unimplemented. Public registration follows the response identity contract below and writes that same public identity in its platform audit outbox row; it creates only global Account state and does not create a profile or tenant membership. JOIN receiver availability and its blocked Gateway route are recorded under [Current Receiver Composition](#current-receiver-composition). Target JOIN operation, digest, retry, and commit semantics remain owned by [ADR 0025](../../decisions/adr-0025-explicit-open-enrollment-membership.md) and the linked [Authentication contract](../../system-architecture-authentication.md). The current runtime membership response carries `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`, with `accountId` and `tenantId` context. Connect-token receiver availability is recorded under [Current Receiver Composition](#current-receiver-composition). Current text `PLAY` validates the emitted `membershipLifecycleState` and independent `membershipAuthorityGeneration` and requires coherent `ACTIVE` admitting membership. Missing or `INACTIVE` public-production membership yields `JOIN_REQUIRED` only when fresh enrollment policy permits repair; an existing active but non-admitting response is not a join fallback. The implemented consumer limits remain in [Account runtime status](./runtime-and-data.md#implementation-status); these checks do not establish the complete caller-target and atomic-freshness contract. Current non-public or non-visible target handling remains split across existing discovery, membership, and grant surfaces; the complete grant/entitlement admission predicate at connect-token issuance remains target-only. The obsolete implicit membership-writer surface has been removed and is not a compatibility operation. `/auth/player-bootstrap` is account-first and factor-aware. The browser connect-token body and OpenAPI response are defined as metadata-only; any issued raw token is carried only in the HttpOnly cookie. The registry-backed issuance, refresh, revocation, durable retry, and authority-generation behaviors below are target state, including the contracts for `Authenticate`, `RefreshGameplayServiceToken`, `/auth/player-bootstrap`, `/auth/logout`, and `/auth/logout-all`; `/auth/login` is currently routable but still lacks the complete registry-backed target behavior. Current Account sessions use the legacy `session:auth:account::` key and, for tenant-scoped sessions, the companion `session:auth:tenant::` key rather than the canonical single `session:auth:token:` registry record. The `player-bootstrap` credential/result profile uses the persisted Account UUID in its result `accountId` and matching JWT subject/Account claim; its Account-owned reader rejects noncanonical, numeric or mismatched identity before resolving the private storage row. The final ordinary receiving composition also carries UUID ordinary login results/credentials, UUID shared intake and forwarding, UUID internal selectors and UUID Account references in downstream consumers. Tenant representations follow the [Account tenant identifier boundary](#account-tenant-identifier-boundary). Full token-profile/registry qualification remains held. Derived `bootstrap-connect-scope` artifacts use the persisted Account UUID in their signed subject/Account claim, through the shared browser/direct-text producer and dedicated Account reader. Profile self-binding and REST caller identity use UUID `SessionContext`; private Account SQL rows remain numeric. The legacy GameInstance owner/StartSession boundary remains separately numeric and unqualified. The bounded response and REST selector identity contract is defined below. Scoped-role population and tenant-switching proof remain target-state work: current `authenticate` issuance provides `globalRoles` but does not yet populate or prove `scopedRoles[tenantId]` as authorization evidence. + +### Current Receiver Composition + +Current explicit JOIN status: with the default composition absent, Account's `JoinPublicProductionMembership` service method returns `AUTH_UNAVAILABLE` because canonical scope consumers are unavailable. When manually configured, the service method proceeds into scope/target validation and authority reads; the gRPC adapter can still refuse peer or request-shape failures before the service call. This does not establish default runtime exposure or qualified live JOIN. The Gateway route remains blocked by its guard and absent from `publicOpenAPI`. The held boundary, preserved positive obligations, and proof history are in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving); target JOIN authority and commit requirements remain in [ADR 0025](../../decisions/adr-0025-explicit-open-enrollment-membership.md). + +With canonical scope consumers absent, current `/auth/connect-token` issuance returns `AUTH_UNAVAILABLE` before bootstrap/scope validation. When consumers are manually configured, it validates bootstrap identity and reads the connect scope, then returns `AUTH_UNAVAILABLE` before cached-success replay, membership/entitlement/grant/pointer reads, token minting, or replay/session mutation. + +### Account Tenant Identifier Boundary + +Public bootstrap realm projections (`BootstrapRealmDto`), direct-text caller/target scopes (`DirectTextCallerContext` and `DirectTextJoinTarget`), and explicit public-production JOIN results (`JoinPublicProductionResult` and `JoinPublicProductionMembershipResponse.tenant_id`) carry the canonical non-nil tenant UUID. Bootstrap realm and direct-text target game-instance identifiers likewise carry canonical non-nil UUIDs. The legacy runtime membership, entitlement and realm-grant reads still use the numeric tenant ID, including `GetTenantMembershipForRuntimeResponse.tenant_id`; the legacy Account tenant-export and profile tenant selectors, including the profile DTO tenant identifier, also remain numeric. These representations are specific to their contracts and must not be interchanged or inferred from Account UUID identity. Canonical facade inputs do not establish default runtime wiring or gameplay admission. ### Account UUID Response and REST Selector Identity @@ -161,7 +171,7 @@ The implemented legacy profile REST handlers and five global Account REST handle First-party bootstrap character discovery sends the authenticated bootstrap context's canonical Account UUID to Entity Management; Account's private storage key remains local. Entity's [ordinary ownership contract](../entity-management-service/api-contracts.md#ordinary-account-ownership) owns the receiver's same-namespace workload authorization and UUID-selected roster predicates. -The final ordinary receiving composition carries UUID ordinary JWT subjects/Account claims, UUID shared forwarding and UUID internal Account selectors, keeping numeric SQL rows private to Account. Profile `SessionContext` self-binding and global REST caller proof use that same UUID identity. Tenant identifiers remain numeric. Full token-profile/registry qualification, canonical tenant-scoped profile routes, complete portable or tenant-wide exports, production credential custody, public JOIN exposure and gameplay activation remain unqualified. Implementation and focused proof limits belong to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#ordinary-uuid-issuer-and-receiving). +The final ordinary receiving composition carries UUID ordinary JWT subjects/Account claims, UUID shared forwarding and UUID internal Account selectors, keeping numeric SQL rows private to Account. Profile `SessionContext` self-binding and global REST caller proof use that same UUID identity. Tenant representations follow the [Account tenant identifier boundary](#account-tenant-identifier-boundary). Full token-profile/registry qualification, canonical tenant-scoped profile routes, complete portable or tenant-wide exports, production credential custody, public JOIN exposure and gameplay activation remain unqualified. Implementation and focused proof limits belong to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#ordinary-uuid-issuer-and-receiving). ### Tenant-Creation Current Authorization Read @@ -197,7 +207,7 @@ Ordinary Account gRPC methods use canonical Account UUID text for Account-valued - `CreateAccount` – registers a global Account identity and returns its canonical UUID as REST `AccountDto.id` and gRPC `CreateAccountResponse.account_id`; its platform audit outbox payload carries the same UUID. It does not select a tenant or create membership/profile state. - `SendNotification` – deliver account notifications asynchronously. - `Authenticate` – verifies one account-selected ordinary credential mode, either `PASSWORD` or verified-email `EMAIL_OTP`, using a required, typed `CredentialSourceContext` and, only for the approved Game Session-to-Account control path, issues the receiver-specific private `game-session-account-delegation` JWT with exact audience `account-service`. Gameplay credential and email-code authentication are global Account-identity operations: their current wire requests reserve the former `tenant_id` fields, and Account neither selects nor requires membership before returning identity. The pre-v1 wire convergence also reserves the former `username` field number and places `email` on a new field number, so mixed old/new Account and Game Session versions fail closed instead of reinterpreting identifiers; the two services must be deployed as one compatibility cohort for uninterrupted gameplay login. The target registry-backed flow stores one `session:auth:token:` record; current gameplay issuance uses the legacy account-scoped session key and defers tenant membership/grant/entitlement to `JOIN`/`PLAY`. Generic `Service JWT` and `aud=internal` profiles are forbidden; workload-only authorization uses mTLS. The context contains a server-derived canonical client address and transport class; Account rejects absent or untrusted context in player-facing environments, and public callers cannot assert it. -- `JoinPublicProductionMembership` – implemented local internal Account RPC for explicit public-production membership creation/restoration. It accepts the Account-issued `connectScopeId`, operation `requestId`, and authenticated caller context; it revalidates the exact stored target and fresh `allowPublicJoin` entitlement evidence, binds a v1 digest to that caller/scope/policy snapshot, and commits membership/version, durable operation outcome, and tenant audit outbox evidence together. The digest's canonical grammar remains owned by [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). A `PENDING` operation after an unknown database commit outcome still requires recovery/reconciliation implementation and exact-final-head PostgreSQL proof; no implicit membership writer or production end-to-end completion is claimed. +- `JoinPublicProductionMembership` – prepared internal Account interface for explicit public-production membership creation/restoration; the canonical consumer is explicitly composed and refuses absent source composition before any legacy authority read. It accepts the Account-issued `connectScopeId`, operation `requestId`, and authenticated caller context; it revalidates the exact stored target and fresh `allowPublicJoin` entitlement evidence, binds the versioned digest to that caller/scope/policy snapshot, and commits membership/version, durable operation outcome, and tenant audit outbox evidence together. The digest's canonical grammar remains owned by [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). A `PENDING` operation after an unknown database commit outcome still requires recovery/reconciliation implementation and exact-final-head PostgreSQL proof; no implicit membership writer or production end-to-end completion is claimed. - `ResolveEffectiveSecurityPolicy` – **Target-state internal Account contract.** Resolve the effective policy for the exact account, optional tenant-scoped action, and action class from the versioned platform baseline, deployment policy, and applicable tenant policy using the tightening precedence in ADR 0045. Return the contributing policy versions, resolved values, and opaque `effectivePolicyVersion`/digest from one Account-owned resolution. Callers must not merge inputs or use cached/default policy; missing, invalid, contradictory, stale, or unavailable resolution fails the sensitive action closed. No other service is a policy authority. - `ApplyAccountSafetyRestriction` / `GetAccountSafetyRestrictions` – target Account-owned owner-command and safe projection contracts for `account_security_lock` and `platform_access_ban`. The command carries one exact category, global account scope, source case/security-event identity, a distinct `ownerEnforcementRequestId`, owner-enforcement digest, and owner authorization evidence; `controlPlaneRequestId` remains correlation-only and never carries or aliases the owner identity. Account validates and atomically commits its monotonic revision, account authority-generation effects, and idempotent result. The current proto/transport mapping does not yet expose the distinct owner request field; that is implementation drift, not proof that the target command is implemented. These contracts do not create a moderation appeal case, and current proto/implementation/proof do not yet provide the complete lifecycle. - `RefreshGameplayServiceToken` – Account-local RPC for the token refresh/replacement operation defined in [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md). Account validates the declared receiver binding and current authority, while Game Session supplies the binding-refresh installation/reconciliation consequence; the current proto and implementation do not yet prove the target registry-backed operation. @@ -222,11 +232,11 @@ Ordinary Account gRPC methods use canonical Account UUID text for Account-valued - External identity binding and lifecycle are owned by [Account Runtime and Data](./runtime-and-data.md). Provider-specific linking is planned but not currently routable. The obsolete caller-asserted `POST /accounts/{accountId}/external` controller route is removed and denied at the public edge; the persistence and internal service scaffold remains unsupported implementation drift and is not evidence of an available provider integration. The legacy `LinkExternalAccount` gRPC adapter returns `FAILED_PRECONDITION` before parsing, lookup or mutation. No provider route may become routable until the target globally bound flow is implemented and proved. - `IssuePlayerBootstrapToken` – authenticate a first-party player account and issue the short-lived `player-bootstrap` token profile used only for gameplay bootstrap. - `ListBootstrapWorlds` – list caller-visible worlds for first-party gameplay bootstrap. -- `ListBootstrapRealms` – list caller-visible realms for a selected world during first-party gameplay bootstrap. -- `IssueDirectTextConnectScope` – implemented local internal Account RPC for issuing a direct-text connect scope. Game Session text `REALMS` dispatch to this RPC remains pending under #2898. The request carries typed `PlayerExecutionContext` scope data plus the server-resolved target. The certificate-derived Game Session mTLS workload identity authenticates the caller; Account validates the context against that trusted caller and Account-owned records separately from the short-lived scope, and returns an opaque `connectScopeId` with its expiry. After routing and entitlement validation, Account samples its own immutable `evaluatedAt` and binds it into the issued scope snapshot; this timestamp is not supplied by or inherited from the retained routing snapshot. Game Session retains the returned timestamp rather than deriving one from its clock or the expiry. Missing, ambiguous, or unavailable entitlement records fail as `ENTITLEMENT_UNAVAILABLE`, distinct from reachable missing or invalid routing evidence (`ADMISSION_POINTER_UNAVAILABLE`), a changed exact routing pair (`CONNECT_SCOPE_MISMATCH`), or unavailable routing authority (`AUTH_UNAVAILABLE`). An authoritative entitlement that denies gameplay returns `TENANT_BILLING_BLOCKED`. This RPC is distinct from `ListBootstrapRealms`, which is first-party discovery, and `JoinPublicProductionMembership`, which is the membership mutation. Fresh Account membership checks remain required separately at applicable admission gates. The canonical scope and transport requirements remain owned by [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative); this local status does not claim direct text-client end-to-end proof. +- `ListBootstrapRealms` – list caller-visible realms for a tenant-qualified world selected by `tenantSlug` and `worldSlug` during first-party gameplay bootstrap. +- `IssueDirectTextConnectScope` – prepared internal Account API; with the default scope producer absent, the receiving method returns `AUTH_UNAVAILABLE`. When manually configured, it delegates to the scope owner for caller/target validation and scope issuance. Game Session text `REALMS` dispatch remains pending under #2898. Current held status, preserved source obligations, and proof history are in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving); the target scope and transport contract remains owned by [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). - `ListBootstrapCharacters` – list caller-visible characters for the selected opaque server-issued `connectScopeId` target during first-party gameplay bootstrap. The exact realm snapshot resolves and carries `playableStateScope` to the character-query boundary; neither clients nor Account derive a physical storage key, and the route world/realm must match the resolved scope. - Bootstrap discovery and join use the canonical realm catalog and admission-pointer contract in [Multi-Tenancy](../../system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract). The existing canonical resolver for the exact-snapshot `stateScope` to `playableStateScope` projection is owned there. REST bootstrap character discovery/creation and direct-text `CHARS`/creation are transport-local producers of that same server-derived projection; neither path accepts a caller-selected value, derives a storage key, or carries the projection through `JOIN` or connect-token issuance. Missing or mismatched proof that the REST and direct-text producers apply the same resolver is implementation drift, not a second resolver contract. Character-query input remains owned by the [Entity Management API contract](../entity-management-service/api-contracts.md#grpc). -- `JoinPublicProductionMembership` – implemented local internal Account API for explicit public-production `JOIN`; the canonical membership lifecycle and freshness contract are owned by [Authentication](../../system-architecture-authentication.md) and its local persistence/transaction consequences by [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority). It accepts the server-issued scope and request identity, and does not expose the removed implicit membership writer. Durable recovery/reconciliation for an operation left `PENDING` after an unknown database commit outcome, exact-final-head PostgreSQL runtime proof, direct text-client end-to-end proof, and membership-generation snapshot proof remain open. + - `GetCallerTenantMembership` – caller-bound membership read for billing-safe mutation checks; freshness and sequence semantics follow [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority). - `GetTenantMembershipForAccount` – cross-tenant membership lookup for billing/reporting workflows (`billingAdmin`/`platformAdmin` only). - `GetTenantMembershipForRuntime(accountId, tenantId, requestId)` – internal membership read for gameplay admission, reconnect/resume, and membership-gap reconciliation. **Current implementation:** the proto and Account producer emit lifecycle state and `membershipAuthorityGeneration` alongside the independent `membershipVersion`, but Game Session does not enforce those fields. **Local unregistered preparation:** `AccountCanonicalRuntimeMembershipSnapshotRepository` and its explicit transaction service assemble the existing shared content carrier from canonical Account and fresh-tenant provenance, current owner generations/fence, role and membership-pair records, and exact committed source events/checkpoints in one owner transaction. Current tenant cutoff fields bind exactly to the verified current tenant source; unequal historical tenant generations fail closed without an Account-owned reconciliation result. This kernel neither authenticates a caller nor grants gameplay or entitlement authority, and the runtime RPC is not wired to it. **Target gap:** the authenticated runtime producer and consumers must carry and enforce the complete fresh snapshot at their admission boundaries. @@ -247,22 +257,6 @@ Ordinary Account gRPC methods use canonical Account UUID text for Account-valued - `AddCurrency` – deferred virtual-currency substrate; unavailable as a supported v1 monetization API and not entitlement authority. - `SpendCurrency` – deferred virtual-currency substrate; unavailable as a supported v1 monetization API and not entitlement authority. -### Private tenant-operation entitlement read - -`AccountTenantOperationEntitlementReadService/ReadTenantOperationEntitlement` is a distinct private `TENANT_OPERATION` evidence read defined by the [purpose-specific protobuf](../../../../protos/account/v1/tenant_operation_entitlement_read.proto). Only the exact same-namespace World Management workload may call it over mTLS; method authorization precedes request decoding, and bearer tokens, ambient caller context and caller-supplied workload values cannot replace transport identity. Account derives the evidence's `callerWorkload` from the authenticated peer, never request data. - -The request carries schema version 1, `targetNamespace` matching Account's configured workload namespace, canonical non-nil `tenantId` and `requestId` UUIDs, and an explicit `sourceKind` of exactly `PAID_HOSTING` or `NON_PAID_DEMO`. There is no default, inference or fallback between sources. The paid branch requires a fresh current Account hosting receipt for the exact tenant and matching current tenant-authority evidence; the DEMO branch reads Account's canonical current DEMO entitlement. Account captures complete entitlement facts, tenant-authority/billing-cutoff evidence and outbox checkpoints in the selected owner source transaction. Missing, stale, mismatched or unavailable selected-source authority supplies no success evidence. The response echoes the exact request and carries strict canonical evidence bound to its tenant, request, source kind and authenticated World workload. Repeated transport members each require exactly one value, and unknown fields fail closed. The [closed codec](../../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementGrpcCodec.java) owns the 1 KiB request bound, response wire allowance of 64 KiB + 1 KiB + 32 bytes, five-second deadline and exact response comparisons; the [evidence codec](../../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementEvidence.java) owns the 64 KiB canonical content bound. - -This held source preparation supplies point-in-time eligibility evidence, not capacity commitment, durable evaluation replay, player admission or runtime activation. The receiver and World client remain manually composed and unregistered, and the owner of a later lifecycle action must enforce currentness at use. Source dependencies and proof limits belong to the [local source-foundation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#local-source-foundation-preparation). - -### Private player-admission entitlement read - -`AccountPlayerAdmissionEntitlementReadService/ReadPlayerAdmissionEntitlement` is a distinct private `PLAYER_ADMISSION` evidence read defined by the [purpose-specific protobuf](../../../../protos/account/v1/player_admission_entitlement_read.proto). Only the exact same-namespace Game Session workload may call it over mTLS; method authorization precedes request decoding, and ambient bearer or caller-supplied workload context cannot replace transport identity. The request carries schema version 1, the complete retained canonical target selector, Account-issued connect scope and explicit initial `game-session-account-delegation` credential. Repeated transport members each require exactly one value, and unknown fields fail closed. The credential is disclosed only to the verified Account peer on this method and must never be logged or persisted as request evidence. - -Account verifies the credential subject and current committed issuance, retained scope, current membership including explicit absence, and Account-selected paid-or-DEMO source. Callers cannot select a source family or convert missing paid authority into DEMO. The response echoes only the closed selectors and carries exact canonical `PLAYER_ADMISSION` evidence, never the credential. The [closed codec](../../../../services/common-security/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodec.java) owns wire bounds, the call deadline and exact response comparisons; the [evidence codec](../../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidence.java) owns the canonical content. `scopeDigest` preserves the retained V2 `sha256:`-prefixed digest, distinct from raw-hex token/registry hashes. Unavailable, changed or expired authority produces no positive or empty-success evidence. Account validates `evaluatedAt` against its own source and scope ordering. The receiving Game Session clock independently requires `now < validUntil`; it does not treat Account's evaluation timestamp as a cross-host not-before bound. No numerical skew allowance or expiry extension is applied. - -This read supports only public-production `SHARED`/`PRESEEDED_ONLY` targets. Broader WORLDS discovery does not widen that restriction. It supplies point-in-time evidence, not membership repair, actor selection, capacity commitment, a World hold through Account commit or later admission, or gameplay admission. The receiver and Game Session client remain manually composed and unregistered; genuine scope/LOGIN custody, runtime integration and proof limits belong to the [player-admission source tracker](../../../project-management/implementation-tracking/player-access-and-session.md#player-admission-entitlement-source-preparation). - ### Runtime account identity owner read `RuntimeAccountIdentityService/ResolveRuntimeAccountIdentity` reads Account's already-persisted canonical UUID and provenance for Account's own row. The protobuf in [`runtime_account_identity_service.proto`](../../../../protos/account/v1/runtime_account_identity_service.proto) is the wire authority; Account does not derive an identity from another owner's key or row. @@ -355,7 +349,7 @@ The disabled `ExportAccount`, `ExportTenantData`, `LinkExternalAccount`, `Reques ## REST APIs -Implemented Account-valued REST selectors and response fields use canonical Account UUID text. `AuthenticationResult.accountId`, `PlayerBootstrapResult.accountId`, and `ProfileDto.accountId` serialize as JSON strings; Account-issued login and bootstrap tokens carry the same UUID in `sub` and `accountId`. Current `/accounts/{accountId}` and profile handlers resolve those identities through Account's persisted UUID/provenance boundary before using private local rows. Tenant identifiers retain their existing representation. The Account identity contract is owned here with [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md); this paragraph records the local wire and storage boundary. +Implemented Account-valued REST selectors and response fields use canonical Account UUID text. `AuthenticationResult.accountId`, `PlayerBootstrapResult.accountId`, and `ProfileDto.accountId` serialize as JSON strings; Account-issued login and bootstrap tokens carry the same UUID in `sub` and `accountId`. Current `/accounts/{accountId}` and profile handlers resolve those identities through Account's persisted UUID/provenance boundary before using private local rows. Tenant representations follow the [Account tenant identifier boundary](#account-tenant-identifier-boundary). The Account identity contract is owned here with [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md); this paragraph records the local wire and storage boundary. | Method | Path | Description | | --- | --- | --- | @@ -384,10 +378,10 @@ Implemented Account-valued REST selectors and response fields use canonical Acco | Provider-specific callback route (future) | Not yet routable | Link one server-verified provider identity after that provider's complete contract and proof exist; the caller-asserted `/accounts/{accountId}/external` route is unsupported | | `POST` | `/auth/player-bootstrap` | Current endpoint; **target registry-backed behavior:** return a short-lived `player-bootstrap` token for gameplay bootstrap only after Account has atomically established exactly one active issued-token registry record; registry failure fails issuance before the token is exposed, and the token is not the `/auth/login` control-ui session | | `GET` | `/auth/bootstrap/worlds` | List caller-visible worlds for first-party gameplay bootstrap | -| `GET` | `/auth/bootstrap/worlds/{world}/realms` | List caller-visible realms for a selected world during first-party gameplay bootstrap | +| `GET` | `/auth/bootstrap/worlds/{world}/realms?tenantSlug={tenant}` | List caller-visible realms for a tenant-qualified world during first-party gameplay bootstrap; see [Public bootstrap WORLDS discovery](#public-bootstrap-worlds-discovery). | | `GET` | `/auth/bootstrap/worlds/{world}/realms/{realm}/characters?connectScopeId={scope}` | List caller-visible characters for the signed realm-discovery target during first-party gameplay bootstrap. The REST producer applies the canonical realm-snapshot mapping to `playableStateScope` before passing it to Entity Management; callers cannot select or provide it. | | `POST` | `/auth/bootstrap/worlds/{world}/realms/{realm}/characters` | **Target; not currently routable or implemented.** Account-owned player-bootstrap facade for scoped character creation; retains the target delegation contract to Entity Management `CreateCharacter` after signed-scope and membership/grant checks. The REST producer applies the same canonical mapping, and `playableStateScope` is server-derived rather than an accepted request field. Account's local creation protection covers the current authenticated player's membership, applicable realm grant, and entitlement authority; see Entity's [character creation owner protection](../entity-management-service/api-contracts.md#character-creation-owner-protection) for the cross-owner terminal boundary. | -| `POST` | `/internal/runtime/public-production-join` | **Target REST adapter; not currently routable.** The local Account `JoinPublicProductionMembership` RPC implements explicit public-production membership creation; Game Session text `JOIN` dispatch to this RPC remains pending under #2898. No implicit membership-writer route is exposed. | +| `POST` | `/internal/runtime/public-production-join` | **Target REST adapter; not currently routable.** A prepared Account `JoinPublicProductionMembership` component implements explicit public-production membership creation. See [Current Receiver Composition](#current-receiver-composition) for receiver availability. Game Session text `JOIN` dispatch to this RPC remains pending under #2898. No implicit membership-writer route is exposed. | | `GET` | `/internal/runtime/realm-access-grants/{tenantId}/{worldSlug}/{realmSlug}/{playtestLifecycleId}/{accountId}` | Internal-only authoritative lookup for one non-public realm-access grant; the lifecycle ID is part of the exact target | | `GET` | `/internal/runtime/accounts/{accountId}/realm-access-grants/{tenantId}/{worldSlug}/{realmSlug}/{playtestLifecycleId}` | Internal-only authoritative lookup/list for the account's exact non-public world/realm/lifecycle target used by discovery/admission filtering | | `POST` | `/tenant-admin/tenants/{tenantId}/realm-access-grants/{worldSlug}/{realmSlug}/{playtestLifecycleId}` | **Target-state only; not currently routable.** Target duplicate-safe create-or-extend surface. The body carries the exact `accountId`, `operation`, requested `grantExpiresAt`, stable `requestId`, and conditional `expectedGrantRevision` (absent-grant precondition for `CREATE`, required current revision for `EXTEND`); exact `mutationDigest/v1` retries replay the stored outcome and changed intent or revision returns `IDEMPOTENCY_CONFLICT` or `GRANT_REVISION_CONFLICT` as defined above. | @@ -398,8 +392,8 @@ Implemented Account-valued REST selectors and response fields use canonical Acco | `PUT` | `/tenants/{tenantId}/profiles/{accountId}` | **Canonical target, `tenant_regular`.** `accountId` is the canonical lowercase non-nil Account UUID. Account live membership authority supplies current membership lifecycle, `membershipAuthorityGeneration`, and independent `membershipVersion`; caller subject and scoped role checks apply. The legacy `/profiles/{accountId}` route remains implementation drift and has no `platformAdmin` override. | | `GET` | `/tenants/{tenantId}/memberships/me` | Authoritative caller-bound membership and roles for billing-safe mutation guards | | `GET` | `/tenants/{tenantId}/memberships/{accountId}` | Cross-tenant membership lookup for billing/reporting roles (`billingAdmin`/`platformAdmin`) | -| `POST` | `/auth/connect-token` | **Target behavior, not current compatibility behavior:** issue a short-lived gameplay connect token for one discovery-selected realm target using caller-bound player-bootstrap identity after one fresh atomic caller-bound runtime membership snapshot, including lifecycle state, independent membership version, and membership authority generation, plus the applicable grant, entitlement, and admission-pointer validation. The complete first-party sequence and private/playtest grant-and-entitlement predicate are owned by [ADR 0021](../../decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md#first-party-browser-flow); this local row records only the Account issuance consequence. Account must reread that exact membership on every issuance, including the first issuance after explicit join, at the issuance commit gate and compare both the independent membership version and opaque authority generation before issuing; stale or cached bootstrap/discovery membership evidence cannot substitute. For a selected public-production target, `allowPublicJoin` gates the required join/repair only when membership is missing or `INACTIVE`: a closed joining policy returns `PUBLIC_PRODUCTION_ADMISSION_DENIED`, and `JOIN_REQUIRED` is returned only when that policy permits joining and fresh target evidence passes. An existing `ACTIVE` member is not denied issuance solely because `allowPublicJoin=false`; fresh gameplay entitlement and every other applicable membership, routing, grant, and binding check still apply. An exact duplicate whose compact receipt remains after response-envelope recovery expiry returns typed `RESPONSE_RECOVERY_EXPIRED` and requires a fresh authorized request with a new `requestId`; a changed digest remains `IDEMPOTENCY_CONFLICT`. **Current implementation:** after bootstrap and connect-scope authentication, the endpoint returns `AUTH_UNAVAILABLE` before cached-success replay, membership/entitlement/target reads, minting, or replay/session mutation while the canonical producer is unavailable. `ConnectTokenResponse` retains a dormant `jti` field; no current successful response or cookie delivery is reachable. **Target delivery:** HTTP response delivery uses only the protected `Set-Cookie` field: the response body and custom response headers never expose the raw token or provide a header fallback. First-party browser/mobile-browser clients and first-party native-mobile or other first-party non-browser clients using a cookie jar remain cookie-only. A separately registered and proven route for explicitly classified public/non-first-party native-mobile and other non-browser clients may later return the token once for protected secure storage and permit only the dedicated handshake header; that route and header are target-only/unavailable now and are not a browser endpoint or a cookie fallback. | -| `POST` | `/auth/bootstrap/join` | **Local Account controller and operation; complete production proof incomplete.** The local `JoinPublicProductionMembership` operation implements explicit caller-bound JOIN using the exact `connectScopeId` and `requestId`. Account first persists a policy-independent request-intent digest and `PENDING` operation, then reads entitlement authority. Only an `AVAILABLE` authoritative result produces the versioned policy-bound request digest and stored `allowPublicJoin` / `entitlementVersion` evidence. An unavailable authority attempt records its failure and availability while keeping the operation `PENDING`, without a fabricated policy result, entitlement version, or final request digest; a matching retry can re-evaluate it. For a retained `PENDING` operation, an expired scope fails terminally with `CONNECT_SCOPE_INVALID` before entitlement evaluation or membership mutation. Account revalidates the exact policy digest at the membership commit gate. The request accepts no caller-selected `playableStateScope`, storage key, or independently supplied runtime target. A changed scope, intent, or available policy returns the applicable deterministic error, including `CONNECT_SCOPE_MISMATCH` or `IDEMPOTENCY_CONFLICT`, without silently retargeting the join; an `ACTIVE` retry remains event-free. The Account route exists locally, but its exact public Gateway path is currently denied by the explicit route guard; this is an exposure restriction, not target-only controller status. Exact-final-head PostgreSQL proof and membership-generation snapshot proof remain open. Game Session text JOIN dispatch remains with #2898; recovery/reconciliation after an unknown commit outcome and Logging receipt receiver/readback remain #2848. Direct text-client proof remains open; the canonical JOIN contract remains with [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). | +| `POST` | `/auth/connect-token` | **Target behavior, not current compatibility behavior:** issue a short-lived gameplay connect token for one discovery-selected realm target using caller-bound player-bootstrap identity after one fresh atomic caller-bound runtime membership snapshot, including lifecycle state, independent membership version, and membership authority generation, plus the applicable grant, entitlement, and admission-pointer validation. The complete first-party sequence and private/playtest grant-and-entitlement predicate are owned by [ADR 0021](../../decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md#first-party-browser-flow); this local row records only the Account issuance consequence. Account must reread that exact membership on every issuance, including the first issuance after explicit join, at the issuance commit gate and compare both the independent membership version and opaque authority generation before issuing; stale or cached bootstrap/discovery membership evidence cannot substitute. For a selected public-production target, `allowPublicJoin` gates the required join/repair only when membership is missing or `INACTIVE`: a closed joining policy returns `PUBLIC_PRODUCTION_ADMISSION_DENIED`, and `JOIN_REQUIRED` is returned only when that policy permits joining and fresh target evidence passes. An existing `ACTIVE` member is not denied issuance solely because `allowPublicJoin=false`; fresh gameplay entitlement and every other applicable membership, routing, grant, and binding check still apply. An exact duplicate whose compact receipt remains after response-envelope recovery expiry returns typed `RESPONSE_RECOVERY_EXPIRED` and requires a fresh authorized request with a new `requestId`; a changed digest remains `IDEMPOTENCY_CONFLICT`. See [Current Receiver Composition](#current-receiver-composition) for the current held issuance boundary. `ConnectTokenResponse` retains a dormant `jti` field; no current successful response or cookie delivery is reachable. **Target delivery:** HTTP response delivery uses only the protected `Set-Cookie` field: the response body and custom response headers never expose the raw token or provide a header fallback. First-party browser/mobile-browser clients and first-party native-mobile or other first-party non-browser clients using a cookie jar remain cookie-only. A separately registered and proven route for explicitly classified public/non-first-party native-mobile and other non-browser clients may later return the token once for protected secure storage and permit only the dedicated handshake header; that route and header are target-only/unavailable now and are not a browser endpoint or a cookie fallback. | +| `POST` | `/auth/bootstrap/join` | **Target JOIN behavior; current receiver unavailable.** The Gateway path remains blocked; see [Current Receiver Composition](#current-receiver-composition) for the service and adapter boundary. The target operation uses the exact caller-bound `connectScopeId` and `requestId`, first persisting a policy-independent request-intent digest and `PENDING` operation, then reading entitlement authority. Only an `AVAILABLE` authoritative result produces the versioned policy-bound request digest and stored `allowPublicJoin` / `entitlementVersion` evidence. An unavailable authority attempt records its failure and availability while keeping the operation `PENDING`, without a fabricated policy result, entitlement version, or final request digest; a matching retry can re-evaluate it. For a retained `PENDING` operation, an expired scope fails terminally with `CONNECT_SCOPE_INVALID` before entitlement evaluation or membership mutation. This terminates the call while preserving the existing `PENDING` or terminal receipt state; it does not authorize rewriting that state or retrying with expired authority. Account revalidates the exact policy digest at the membership commit gate. The request accepts no caller-selected `playableStateScope`, storage key, or independently supplied runtime target. A changed scope, intent, or available policy returns the applicable deterministic error, including `CONNECT_SCOPE_MISMATCH` or `IDEMPOTENCY_CONFLICT`, without silently retargeting the join; an `ACTIVE` retry remains event-free. Exact-final-head PostgreSQL proof and membership-generation snapshot proof remain open. Game Session text JOIN dispatch remains with #2898; recovery/reconciliation after an unknown commit outcome and Logging receipt receiver/readback remain #2848. Direct text-client proof remains open; the canonical JOIN contract remains with [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). | | `DELETE` | `/tenants/{tenantId}/memberships/me` | Leave a joined game using caller-bound membership authority; removes future membership-based discovery/admission while retained character, purchase, audit, and legal data follow their owning policies | | `GET` | `/internal/runtime/tenants/{tenantId}/entitlements` | Internal runtime/admission entitlement snapshot for gameplay-affecting services | | `GET` | `/tenants/{tenantId}/entitlements/me` | Caller-bound tenant-admin entitlement view for billing-safe UX | @@ -414,7 +408,7 @@ The legacy `GET /profiles/{accountId}?tenantId=...` and `PUT /profiles/{accountI Current recovery/verification response and delivery behavior: password-reset, username-recovery, and public email-verification initiation retain the same neutral HTTP success for known and unknown normalized email addresses, including when a known-account post-commit SMTP send throws and is caught/logged; unknown addresses create no token or delivery attempt. This equal outcome does not remove the timing oracle: known-account sends still run synchronously after commit. Durable asynchronous delivery is absent, and focused service-level exception tests do not prove HTTP-level timing parity or timing resistance. This is not full account-enumeration resistance. -The target `POST /auth/connect-token` REST response body is metadata-only: it contains no raw connect token or internal `jti`, and no custom response header may provide one. Target success delivery uses only the protected HttpOnly `Firemud-Connect-Token` `Set-Cookie` with the documented cookie security attributes. **Current endpoint behavior:** after validating bootstrap identity and connect-scope binding, Account returns `AUTH_UNAVAILABLE` before cached-success replay or fresh membership, entitlement, and runtime authority reads, token minting, or replay/session mutation. `ConnectTokenResponse` retains a dormant `jti` field, but the current endpoint does not construct a success response, so no live `jti` exposure or successful cookie delivery is claimed. Exact-result replay and response-envelope recovery remain target behavior; no gRPC `IssueConnectToken` transport exists. +The target `POST /auth/connect-token` REST response body is metadata-only: it contains no raw connect token or internal `jti`, and no custom response header may provide one. Target success delivery uses only the protected HttpOnly `Firemud-Connect-Token` `Set-Cookie` with the documented cookie security attributes. See [Current Receiver Composition](#current-receiver-composition) for the held issuance boundary. `ConnectTokenResponse` retains a dormant `jti` field, but the current endpoint does not construct a success response, so no live `jti` exposure or successful cookie delivery is claimed. Exact-result replay and response-envelope recovery remain target behavior; no gRPC `IssueConnectToken` transport exists. For the bootstrap-character and connect-token REST routes, authenticated gameplay-admission denials (`CONNECT_TOKEN_REJECTED`, `NON_PUBLIC_ENROLLMENT_REQUIRED`, `PUBLIC_PRODUCTION_ADMISSION_DENIED`, `JOIN_REQUIRED`, and `TENANT_BILLING_BLOCKED`) map to HTTP 403; invalid bootstrap credentials remain 401 and unavailable authority remains 503. @@ -448,7 +442,7 @@ Every tenant-targeted request identifies its tenant in the route or request cont | --- | --- | --- | --- | | Public auth/bootstrap | `/auth/login`, `/auth/request-password-reset`, `/auth/complete-password-reset`, `/auth/request-email-verification`, `/auth/verify-email`, `/auth/recover-username`, `/.well-known/jwks.json` | No pre-existing user JWT; endpoint-specific validation and abuse controls | Intended for initial auth/bootstrap flows. The public `POST /auth/verify-email` is configured, but the verification email's `GET /auth/verify-email` link has no controller mapping and no browser handoff to POST. See [Runtime and Data](./runtime-and-data.md#email-and-notification-design). | | Player bootstrap issuance | `/auth/player-bootstrap` | First-party player account authentication bootstrap | **Target state:** issues the `player-bootstrap` token profile only after atomically creating its one active `session:auth:token:` registry record; registry failure fails issuance before exposure. It must not return a `control-ui` JWT or perform tenant-scoped admission checks. It may share Account's credential verification, abuse controls, and account-state checks with `/auth/login`, but the endpoint, audience, claims, lifetime, and allowed surfaces remain distinct. **Current implementation:** uses the legacy `session:auth:account::` Account session key rather than the ADR 0035 registry shape. | -| Player bootstrap | `/auth/bootstrap/worlds`, `/auth/bootstrap/worlds/{world}/realms`, `/auth/bootstrap/join`, `/auth/bootstrap/worlds/{world}/realms/{realm}/characters`, `/auth/connect-token` | Target first-party flow: short-lived, memory-only `player-bootstrap` token in `Authorization: Bearer ...` | The implemented bootstrap derives caller identity before tenant selection, then resolves tenant scope through realm discovery. World and realm discovery may show a public production target before membership exists; character discovery now requires the caller's current membership to exist and permit gameplay admission, and `/auth/bootstrap/join` has a local Account controller/operation for the explicit first-party open-enrollment writer. Character discovery consumes the opaque server-issued `connectScopeId`, verifies the route matches it, and revalidates its tenant/runtime target. Current `POST /auth/connect-token` validates bootstrap identity and scope binding, then returns `AUTH_UNAVAILABLE` before membership, entitlement, admission-pointer, or cached-result reads and token minting. The target character-creation route is not currently routable or implemented: it requires that exact `connectScopeId`, derives `playableStateScope` from the realm catalog/pointer snapshot, and delegates the scoped write to Entity Management `CreateCharacter`; it does not persist character state or accept a caller-selected scope. Later character and connect-token surfaces must require live membership plus applicable grant, entitlement, and pointer checks. `POST /auth/connect-token` must obtain the exact current caller-bound runtime membership snapshot at its issuance commit gate, including lifecycle state, independent membership version, and opaque authority generation; cached or bootstrap evidence cannot substitute even when its generation appears current. Target success delivery uses only the protected `Firemud-Connect-Token` `Set-Cookie` field; the HTTP response body and custom response-header fields are metadata-only. First-party browser/mobile-browser and first-party native-mobile or other first-party non-browser cookie-jar clients remain cookie-only. A separately registered route for explicitly classified public/non-first-party native-mobile and other non-browser clients returns the token once for protected secure storage and permits only the dedicated handshake header; it is not a browser endpoint or a cookie fallback. PostgreSQL exact-final-head, recovery/reconciliation, direct text end-to-end, and membership-generation proof remain open. | +| Player bootstrap | `/auth/bootstrap/worlds`, `/auth/bootstrap/worlds/{world}/realms?tenantSlug={tenant}`, `/auth/bootstrap/join`, `/auth/bootstrap/worlds/{world}/realms/{realm}/characters`, `/auth/connect-token` | Target first-party flow: short-lived, memory-only `player-bootstrap` token in `Authorization: Bearer ...` | Current `/auth/player-bootstrap` issuance authenticates the account before tenant selection and records account-scoped bootstrap session state. Default discovery remains unavailable; JOIN and connect-token receiver availability is recorded under [Current Receiver Composition](#current-receiver-composition). The numeric runtime entitlement receiver returns `ENTITLEMENT_UNAVAILABLE` before reading retained numeric subscription rows. In the target flow, world and realm discovery may show a public production target before membership exists; character discovery requires the caller's current membership to exist and permit gameplay admission, while `/auth/bootstrap/join` is the explicit first-party open-enrollment writer. Character discovery consumes the opaque server-issued `connectScopeId`, verifies the route matches it, and revalidates its tenant/runtime target. The target character-creation route is not currently routable or implemented: it requires that exact `connectScopeId`, derives `playableStateScope` from the realm catalog/pointer snapshot, and delegates the scoped write to Entity Management `CreateCharacter`; it does not persist character state or accept a caller-selected scope. Later character and connect-token surfaces must require live membership plus applicable grant, entitlement, and pointer checks. `POST /auth/connect-token` must obtain the exact current caller-bound runtime membership snapshot at its issuance commit gate, including lifecycle state, independent membership version, and opaque authority generation; cached or bootstrap evidence cannot substitute even when its generation appears current. Target success delivery uses only the protected `Firemud-Connect-Token` `Set-Cookie` field; the HTTP response body and custom response-header fields are metadata-only. First-party browser/mobile-browser and first-party native-mobile or other first-party non-browser cookie-jar clients remain cookie-only. A separately registered route for explicitly classified public/non-first-party native-mobile and other non-browser clients returns the token once for protected secure storage and permits only the dedicated handshake header; it is not a browser endpoint or a cookie fallback. PostgreSQL exact-final-head, recovery/reconciliation, direct text end-to-end, and membership-generation proof remain open. | | Authenticated account control-plane APIs | Current legacy `/accounts/{accountId}/export`; target `/auth/logout`, `/auth/logout-all`, `/tenants/{tenantId}/profiles/{accountId}`, active-account `/accounts/{accountId}/exports/**`, `/accounts/{accountId}`, `/tenants/{tenantId}/memberships/me`, `/tenants/{tenantId}/memberships/{accountId}` | Exact ordinary account subject through the declared `control-ui` JWT route class | This is the target authentication class only while the account remains eligible for ordinary authority. The current singular legacy export is classified here as an ordinary authenticated account-subject route; the target export lifecycle uses the authenticated account subject while active. The REST inventory identifies which routes are currently implemented and which remain target-only. | | Tenant-admin billing-safe export | `/tenant-admin/tenants/{tenantId}/export` | Exact `control-ui` caller with live `tenantAdmin` membership bound to the `{tenantId}` route segment | `billing_safe_tenant` classification. The route has a tenant binding but no `accountId` subject selector, requires live membership and membership-generation evidence, and remains target-only/not currently routable. | @@ -474,6 +468,22 @@ The canonical membership, entitlement response shape, freshness, and sequence co - `GetTenantEntitlementsTenant` and `GetTenantEntitlementsCrossTenantSupportSafe` remain separate caller-bound and redacted support-safe API variants. They must not be multiplexed with the internal runtime surface. - Internal callers must treat missing required owner fields as contract failure and fail closed; Account's REST/OpenAPI and gRPC/proto sources remain the executable API authorities. +### Private player-admission entitlement read + +`AccountPlayerAdmissionEntitlementReadService/ReadPlayerAdmissionEntitlement` is a distinct private `PLAYER_ADMISSION` evidence read defined by the [purpose-specific protobuf](../../../../protos/account/v1/player_admission_entitlement_read.proto). Only the exact same-namespace Game Session workload may call it over mTLS; method authorization precedes request decoding, and ambient bearer or caller-supplied workload context cannot replace transport identity. The request carries schema version 1, the complete retained canonical target selector, Account-issued connect scope and explicit initial `game-session-account-delegation` credential. Repeated transport members each require exactly one value, and unknown fields fail closed. The credential is disclosed only to the verified Account peer on this method and must never be logged or persisted as request evidence. + +Account verifies the credential subject and current committed issuance, retained scope, current membership including explicit absence, and Account-selected paid-or-DEMO source. Callers cannot select a source family or convert missing paid authority into DEMO. The response echoes only the closed selectors and carries exact canonical `PLAYER_ADMISSION` evidence, never the credential. The [closed codec](../../../../services/common-security/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodec.java) owns wire bounds, the call deadline and exact response comparisons; the [evidence codec](../../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidence.java) owns the canonical content. `scopeDigest` preserves the retained V2 `sha256:`-prefixed digest, distinct from raw-hex token/registry hashes. Unavailable, changed or expired authority produces no positive or empty-success evidence. Account validates `evaluatedAt` against its own source and scope ordering. The receiving Game Session clock independently requires `now < validUntil`; it does not treat Account's evaluation timestamp as a cross-host not-before bound. No numerical skew allowance or expiry extension is applied. + +This read supports only public-production `SHARED`/`PRESEEDED_ONLY` targets. Broader WORLDS discovery does not widen that restriction. It supplies point-in-time evidence, not membership repair, actor selection, capacity commitment, a World hold through Account commit or later admission, or gameplay admission. The receiver and Game Session client remain manually composed and unregistered; genuine scope/LOGIN custody, runtime integration and proof limits belong to the [player-admission source tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-public-account-facade-receiving). + +### Private tenant-operation entitlement read + +`AccountTenantOperationEntitlementReadService/ReadTenantOperationEntitlement` is a distinct private `TENANT_OPERATION` evidence read defined by the [purpose-specific protobuf](../../../../protos/account/v1/tenant_operation_entitlement_read.proto). Only the exact same-namespace World Management workload may call it over mTLS; method authorization precedes request decoding, and bearer tokens, ambient caller context and caller-supplied workload values cannot replace transport identity. Account derives the evidence's `callerWorkload` from the authenticated peer, never request data. + +The request carries schema version 1, `targetNamespace` matching Account's configured workload namespace, canonical non-nil `tenantId` and `requestId` UUIDs, and an explicit `sourceKind` of exactly `PAID_HOSTING` or `NON_PAID_DEMO`. There is no default, inference or fallback between sources. The paid branch requires a fresh current Account hosting receipt for the exact tenant and matching current tenant-authority evidence; the DEMO branch reads Account's canonical current DEMO entitlement. Account captures complete entitlement facts, tenant-authority/billing-cutoff evidence and outbox checkpoints in the selected owner source transaction. Missing, stale, mismatched or unavailable selected-source authority supplies no success evidence. The response echoes the exact request and carries strict canonical evidence bound to its tenant, request, source kind and authenticated World workload. Repeated transport members each require exactly one value, and unknown fields fail closed. The [closed codec](../../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementGrpcCodec.java) owns the 1 KiB request bound, response wire allowance of 64 KiB + 1 KiB + 32 bytes, five-second deadline and exact response comparisons; the [evidence codec](../../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementEvidence.java) owns the 64 KiB canonical content bound. + +This held source preparation supplies point-in-time eligibility evidence, not capacity commitment, durable evaluation replay, player admission or runtime activation. The receiver and World client remain manually composed and unregistered, and the owner of a later lifecycle action must enforce currentness at use. Source dependencies and proof limits belong to the [billing and retention tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). + ## Subject-Binding Rules (Normative) - `GET /tenants/{tenantId}/profiles/{accountId}` and `PUT /tenants/{tenantId}/profiles/{accountId}` are tenant-qualified, caller-subject-bound profile routes. They require live membership and the path `accountId` must equal the authenticated account; global roles do not broaden these routes. Cross-account moderation/support views require separate minimized contracts. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 29dbc4cdc1..fe28cf005a 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -8,10 +8,6 @@ Account owns platform identity, hosted Creator Party/operator and terms currentn ## Implementation Status -The local source-foundation preparation retains the existing numeric subscription schema, runtime reader, public facade and demo seeder. It does not install the V1028-and-later subscription UUID transition, archive numeric subscription rows, retire their reader, or replace the facade with denial stubs. This retained runtime is implementation drift under the canonical [membership and entitlement authority](#membership-and-entitlement-authority), not a second target authority. Schema retirement and a functioning canonical UUID admission replacement remain one downstream receiving boundary; this preparation adds no numeric bridge or dual-authority path. The [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#local-source-foundation-preparation) owns source and proof status. - -The manually composed hosting provisioning and terminal-resolution sources require the downstream canonical subscription schema and cannot establish paid lifecycle or entitlement operation against the retained numeric schema. Separate `TENANT_OPERATION` and `PLAYER_ADMISSION` sources/transports, the V2 scope reader, and Account-to-Entity bootstrap-roster client remain unregistered and non-admitting. The player-admission owner performs JWT/registry, provider and protected target reads outside SQL, then rereads current Account issuance, membership, exact retained scope and selected billing source in a final writable `SERIALIZABLE` transaction; failed commit releases no evidence. Its DEMO proof sources use the existing schema, while paid execution requires canonical subscription storage and genuine provider receipts. Existing JOIN transactions are also explicitly writable and `SERIALIZABLE`; neither local guarantee supplies distributed target protection or completes the canonical JOIN commit gate. The [private player-admission API](./api-contracts.md#private-player-admission-entitlement-read) owns the protocol, [Subscription Management](./subscription-management.md) owns billing lifecycle, and the [tracker](../../../project-management/implementation-tracking/player-access-and-session.md#player-admission-entitlement-source-preparation) owns source/proof limits. - Both existing `bootstrap-connect-scope` producer paths mint the exact persisted Account UUID. Scope validation compares canonical UUID subject/Account claims before owner readback; malformed identity remains `CONNECT_SCOPE_INVALID`, while unavailable owner evidence is `AUTH_UNAVAILABLE`. Retained scope/JOIN rows and digests continue to use private Account row keys without a schema rewrite. This scope-artifact transition itself adds no Game Session text dispatch; the separately qualified ordinary receiving cohort now carries UUID Account identity through the direct-text caller context and Account-to-Entity references. Proof and retained-scope rediscovery limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#bootstrap-connect-scope-uuid-artifact) and [ordinary UUID receiving](../../../project-management/implementation-tracking/player-access-and-session.md#ordinary-uuid-issuer-and-receiving). JOIN keeps numeric owner keys inside its retained scope, operation, membership and digest records. A private in-process outcome is projected through full Account owner readback only after the JOIN transaction returns, so response identity failure cannot undo a committed receipt or replace its original outcome. Profile repositories embed only partial Account rows; GET/UPDATE response projection rereads the full owner and supplies its verified UUID to the generated mapper. Both existing export paths verify their already-loaded Account once and reuse that UUID while retaining each profile owner, tenant and mapped-output check. The response identity contract is owned by [Account API contracts](./api-contracts.md); implementation and proof limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#account-owned-response-uuid-projection). @@ -20,7 +16,7 @@ The `player-bootstrap` credential/result profile uses the persisted Account UUID Ordinary control-UI, gameplay password/email-OTP, and player-bootstrap issuance checks the authenticated Account's persisted UUID provenance and source-row identity and resolves that UUID back to the same Account row before consuming a successful challenge, signing, or storing a session. Successful ordinary authentication results and Account-issued JWT subject/Account claims carry that UUID. Identity readback failures use `AUTH_UNAVAILABLE`; invalid credentials retain their existing response. The final ordinary receiving qualification and its limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#ordinary-uuid-issuer-and-receiving). -The global Account REST selectors resolve public UUIDs to private numeric rows before Account-local service calls. Private numeric row keys remain local to storage; the [Account API contract](./api-contracts.md#rest-apis) owns caller authorization, selector, and failure behavior. The final receiving composition carries UUID identity through shared context, gRPC and Logging consumers; tenant storage selectors retain their numeric representation. [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#ordinary-uuid-issuer-and-receiving) records current implementation and focused proof. Full token-profile qualification and production authorization custody remain separate. +The global Account REST selectors resolve public UUIDs to private numeric rows before Account-local service calls. Private numeric row keys remain local to storage; the [Account API contract](./api-contracts.md#rest-apis) owns caller authorization, selector, and failure behavior. The final receiving composition carries UUID identity through shared context, gRPC and Logging consumers. Tenant representations follow the [Account tenant identifier boundary](./api-contracts.md#account-tenant-identifier-boundary), which distinguishes canonical public/direct-text scopes and JOIN results from legacy numeric runtime reads. [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#ordinary-uuid-issuer-and-receiving) records current implementation and focused proof. Full token-profile qualification and production authorization custody remain separate. The caller verifier, lease owner and certificate-guarded seven-method receiver remain manually composed and unregistered. Their [lease contract](./api-contracts.md#canonical-public-production-new-admission-lease-source) preserves immutable original attempts and ACKs, with full tenant-source guards for new acquisition and first finalization and the separate current-caller/global-Account/token guards for exact metadata and cleanup recovery. Current-token verification alone grants no admission. Forward V1014 stores separate immutable resolution of a retained unknown-decision abort without rewriting its original terminal evidence. Forward V1015 adds a disjoint never-admitted negative resolution, retaining the original transition, abandonment and candidate/closure digests without a binding decision; the linked lease contract owns its exact selectors and authority. Focused actual Account–Game Session composition covers that exact recovery and restart boundary; upstream source custody and test PKI remain controlled. Broader token-retirement and orphan-cleanup delivery, default registration and admitted binding remain unqualified. [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) owns the implementation and proof details. @@ -58,7 +54,7 @@ The source preparation also includes unregistered, caller-transaction-bound crea Account's actor-staging eligibility owner read is a read-only, same-namespace Entity workload RPC gated off by default. Under one repeatable-read Account transaction it verifies persisted Account UUID/provenance, current Account membership and pair authority, fresh Game Design tenant-source evidence, and the current membership event/checkpoint, then returns digest-sealed evidence scoped to `PUBLIC_PRODUCTION_STAGING_ONLY`. It reports an eligible or ineligible source snapshot but creates no membership, actor assignment, JOIN, PLAY, or gameplay admission. The staged foundation passed 43 focused Account tests and 92 shared-evidence tests with no failures or skips, plus source generation and Account integration-source compilation. PostgreSQL migration/persistence proof sources are included but physical PostgreSQL and live runtime execution remain unrun; the RPC is not runtime-ready or admission authority. -Account V29 persists immutable, unique, non-nil `account_uuid` values with provenance and the unchanged numeric source-row id. Registration REST exposes that UUID through `AccountDto.id`, while registration gRPC exposes it through `CreateAccountResponse.account_id`; the Account component of current Account/profile-local and legacy tenant exports also carries the UUID. The mapper requires a non-nil UUID, provenance, and an exact positive source-row match. Repository insert/readback checks remain the persistence boundary, and registration audit payloads use the same UUID. `AuthenticationResult.accountId`, `PlayerBootstrapResult.accountId`, Account-issued JWT `sub`/`accountId` claims, and `ProfileDto.accountId` carry the persisted UUID. Account resolves UUIDs to private numeric rows only for local storage operations; the row is not an API identity. REST-specific update DTOs preserve the UUID path/body contract, and internal/gRPC updates and caller binding use UUIDs. Tenant IDs and profile tenant identifiers retain their current representation. The final ordinary receiving proof and its limits are recorded in the [player-access implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#ordinary-uuid-issuer-and-receiving). The current export remains partial Account/profile-local data, not the canonical portable export. [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md) remains the identifier authority. +Account V29 persists immutable, unique, non-nil `account_uuid` values with provenance and the unchanged numeric source-row id. Registration REST exposes that UUID through `AccountDto.id`, while registration gRPC exposes it through `CreateAccountResponse.account_id`; the Account component of current Account/profile-local and legacy tenant exports also carries the UUID. The mapper requires a non-nil UUID, provenance, and an exact positive source-row match. Repository insert/readback checks remain the persistence boundary, and registration audit payloads use the same UUID. `AuthenticationResult.accountId`, `PlayerBootstrapResult.accountId`, Account-issued JWT `sub`/`accountId` claims, and `ProfileDto.accountId` carry the persisted UUID. Account resolves UUIDs to private numeric rows only for local storage operations; the row is not an API identity. REST-specific update DTOs preserve the UUID path/body contract, and internal/gRPC updates and caller binding use UUIDs. Profile tenant identifiers remain numeric; other tenant representations follow the [Account tenant identifier boundary](./api-contracts.md#account-tenant-identifier-boundary). The final ordinary receiving proof and its limits are recorded in the [player-access implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#ordinary-uuid-issuer-and-receiving). The current export remains partial Account/profile-local data, not the canonical portable export. [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md) remains the identifier authority. The account lifecycle state machine, global deletion preconditions, account-scoped versus tenant-scoped portable-data export split, separate safety-restriction lifecycles, hosting-billing authority, and future-marketplace `purchase_entitlement` substrate are the canonical target design. The current service has live identity/authentication, profile, external-link persistence, recovery/verification, payment, subscription, notification, and virtual-currency foundations, but lifecycle state transitions, genuine provider authentication, cross-service export, retained-record handling, complete account lock/platform-ban enforcement, purchased-entitlement fulfillment, and complete billing/subscription follow-through remain partial. The current account export returns only Account and profile rows, the tenant export includes excessive global Account fields, and DeleteAccount preserves its JOIN and billing denials before failing closed without deleting child rows; AccountRepository retains its independent hard-delete guard. A complete retained-data lifecycle remains absent. Those behaviors directly conflict with [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) and the bounded erasure workflow below. @@ -70,11 +66,11 @@ Account implements bounded owner-local cleanup of expired password-reset, email- Account also performs a bounded sweep of public connect-scope evidence after its configured scope expiry. It deletes only rows with a valid parsed expiry at or before the captured UTC time and no `account_join_operations` reference of any status; malformed expiry rows remain untouched without blocking valid rows. V27 adds a restrictive foreign key from each JOIN operation to its exact scope row, fencing concurrent intent insertion against deletion. The sweep does not expire JOIN operation receipts or change account-deletion retention. -The current public registration path creates only a global Account row and a platform-scoped audit outbox record; it does not create a tenant membership or profile, and a legacy caller-supplied `tenantId` does not establish tenant authority. Explicit `JoinPublicProductionMembership` is the only public-production membership writer. It first commits a policy-independent `PENDING` intent containing the global request ID, verified caller binding, exact retained connect-scope evidence, and a version-1 intent digest. Only after authoritative entitlement evaluation succeeds does a separate Account transaction bind `allowPublicJoin`, the positive `entitlementVersion`, and the version-1 policy digest; that transaction revalidates the exact policy at the membership commit gate and atomically commits any membership transition, tenant-scoped audit outbox event, and terminal operation outcome. If entitlement authority is unavailable, the row remains `PENDING` with a typed last-attempt failure and availability but null policy values and null policy digest; an exact request retry may reconcile it after authority recovers. For a retained `PENDING` operation, an expired or malformed scope now fails terminally with `CONNECT_SCOPE_INVALID` before entitlement evaluation or membership mutation. Definitive pre-policy failures retain the intent digest and a durable terminal outcome rather than fabricating policy evidence. A definitive mismatch between the freshly evaluated policy digest and an already-bound digest fails terminally as `IDEMPOTENCY_CONFLICT`, retaining the original request digest, policy version, and policy result without membership or transition audit/outbox mutation; this applies both on a retry and at the immediate commit-gate reread. Unavailable or unsafe authority and uncertain commit outcomes remain `PENDING`. A post-transaction readback applies the terminal retry checks when a terminal row is present; otherwise Account returns retryable `AUTH_UNAVAILABLE` and the caller must retry the same request ID. No background PENDING-operation reconciler is claimed; recovery/reconciliation after an unknown database commit outcome remains open. An exact retry of a terminal JOIN replays its stored result only after the retained scope is still unexpired and current target/entitlement authority is available and matches the stored policy digest; expiry, unavailable authority, or changed policy fails closed without rewriting the terminal operation or membership. `ACTIVE` membership is idempotent, while only missing or inactive membership transitions to `ACTIVE`. PostgreSQL repository proof covers independent intent insertion and atomic policy-binding/membership/outbox/outcome persistence, while the service unit proof covers the separate transaction commit/rollback boundary; focused native PostgreSQL and HTTP execution is recorded with its source-specific limits in the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md). No direct text-client end-to-end proof is claimed. Legacy Account migrations still assign tenant defaults/backfills and retain prior memberships as unverified, non-admitting evidence. This remains a retained-data deployment blocker: before any affected deployment, Account must record either a verified no-data boundary or an explicit retained-row disposition/mapping, including exact readback and admission-isolation evidence. No recovery is implied for already-applied irreversible migrations, and this status does not choose a tenant-identity migration design. +The current public registration path creates only a global Account row and a platform-scoped audit outbox record; it does not create a tenant membership or profile, and a legacy caller-supplied `tenantId` does not establish tenant authority. Current JOIN receiver composition and refusal boundaries are defined by [Account API Contracts](./api-contracts.md#rest-apis). The held receiving boundary, preserved positive implementation obligations, and proof history are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving); unknown-outcome recovery remains open under #2848, with no background reconciler claimed. `ACTIVE` membership is idempotent, while only missing or inactive membership transitions to `ACTIVE`. PostgreSQL repository proof covers independent intent insertion and atomic policy-binding/membership/outbox/outcome persistence, while the service unit proof covers the separate transaction commit/rollback boundary; focused native PostgreSQL and HTTP execution is recorded with its source-specific limits in the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md). No direct text-client end-to-end proof is claimed. Legacy Account migrations still assign tenant defaults/backfills and retain prior memberships as unverified, non-admitting evidence. This remains a retained-data deployment blocker: before any affected deployment, Account must record either a verified no-data boundary or an explicit retained-row disposition/mapping, including exact readback and admission-isolation evidence. No recovery is implied for already-applied irreversible migrations, and this status does not choose a tenant-identity migration design. Account has source-only persistence for individual Creator Party identity, hosted-terms acceptance/environment-binding evidence, and (from V98) disclosure handoffs with immutable captured source evidence. The V98 database guards constrain handoff identity, result transitions, and source-evidence insertion. A passive Account source-fence seam now excludes unsettled World participation from applicable source mutation/abort settlement and hosted-terms disclosure preparation/dispatch admission; `HostedTermsDisclosureHandoff` and its repository use the existing V98 journal. The unregistered historical World-participation reader resolves retained participation coordinates from the complete unchanged original tuple, verifies the retained capture and source-child vector, and can read after lease expiry or immutable terminal settlement; it uses existing rows and introduces no migration or table. It does not establish currentness, renew or admit authorization, or classify an Account expiry or failed response as World `ABORTED`; only the World owner can produce that terminal outcome with its original commit/fence evidence. The handoff retains opaque authority evidence as supplied and does not authenticate it. No verifier, dispatcher, transport, registry/runtime binding, creator UI, or Game Design evidence binding is registered. Reserve, claim, and publication paths that require the hosted-terms workflow remain unavailable. The acceptance/currentness authority remains target-only under [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md), with changed-terms continuity under [ADR 0181](../../decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md); local retention/export treatment must follow [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) when the owner workflow is implemented. Organization support, marketplace enrollment, and creator-player entitlement issuance remain disabled. -The live `GetTenantMembershipForRuntime` producer emits `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`; `roles`, the complete `authorityTuple`, and `outboxCheckpoints` remain absent from the proto and producer. Current text `PLAY` consumes the emitted lifecycle and independent authority generation alongside version and admission evidence; this does not establish the complete atomic-freshness contract. Account-first bootstrap and credential-bearing gameplay `Authenticate` authenticate global Account identity before tenant selection and accept configured password or verified-email OTP modes. The gameplay authentication and challenge protos no longer carry `tenantId`, membership is not an authentication prerequisite, and the private delegation token uses the account-scoped legacy session record; Game Session may retain its bootstrap tenant only as local transport context. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Character discovery requires membership after applicable target and entitlement checks; on an eligible public-production target missing or `INACTIVE` membership returns non-actionable `JOIN_REQUIRED` when `allowPublicJoin` permits entry and `PUBLIC_PRODUCTION_ADMISSION_DENIED` otherwise, while other present non-admitting membership is denied as `CONNECT_TOKEN_REJECTED`. Current `POST /auth/connect-token` validates bootstrap identity and the retained connect scope, then returns `AUTH_UNAVAILABLE` before membership, entitlement, admission-pointer, cached-result, or token-issuance work; it does not currently return an issuance `JOIN_REQUIRED` or `CONNECT_TOKEN_REJECTED` result. Current text `PLAY` evaluates fresh entitlement before membership/grant and later actor/binding checks; public `JOIN_REQUIRED` is limited to coherent missing or `INACTIVE` membership when enrollment permits repair. An active but non-admitting response is not a join fallback. Complete caller-target/atomic authority and the remaining AA-2.1 / Unit 1B boundaries remain open. These flows do not create or restore membership. The Account-owned public-production `JOIN` writer is implemented locally with a v1 policy-bound digest and atomic membership, operation-outcome, and audit-outbox evidence. Its HTTP exposure remains blocked by the Gateway route guard; Game Session text `JOIN`/`Join & Play` dispatch remains with #2898, while durable recovery after an unknown database commit and Logging receipt receiver/readback remain with #2848. Focused PostgreSQL/component proof and its limits are recorded in the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#validation-and-proof); those controlled fixtures do not establish genuine deployed receiving custody or complete public admission. See [Account API Contracts](./api-contracts.md) for the public and internal API boundary and [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) for the canonical direct-text scope and JOIN contract. `GetAdmissionPointer` is a live `game_session.v1.GameSessionService` RPC served by the Game Session runtime owner and consumed by Account through `GameSessionClient`; its current response shape and the target routing semantics owned by Multi-Tenancy are described below. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling remain incomplete. The entitlement producer returns retryable `ENTITLEMENT_UNAVAILABLE` (HTTP 503 and the gRPC error field) when a tenant has zero or multiple subscription rows; only one explicit row is projected through current status mapping. Explicit free/trial row creation, an authoritative current-row selector/constraint/history, and canonical snapshot fields/freshness remain unimplemented, including nullable `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and event delivery. Focused zero-row, mixed-row, gRPC classification, and replay-after-recovery proof covers only that cardinality guard and retry boundary. `CommitTenantCapacityAdmission` has one synchronized target request/replay contract, including `mutationDigest`, but its proto RPC, callers, durable Account-owned authority/usage persistence, and reservation lifecycle remain unimplemented. +The live `GetTenantMembershipForRuntime` producer emits `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`; `roles`, the complete `authorityTuple`, and `outboxCheckpoints` remain absent from the proto and producer. Current text `PLAY` consumes the emitted lifecycle and independent authority generation alongside version and admission evidence; this does not establish the complete atomic-freshness contract. Account-first bootstrap and credential-bearing gameplay `Authenticate` authenticate global Account identity before tenant selection and accept configured password or verified-email OTP modes. The gameplay authentication and challenge protos no longer carry `tenantId`, membership is not an authentication prerequisite, and the private delegation token uses the account-scoped legacy session record; Game Session may retain its bootstrap tenant only as local transport context. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current receiver composition and refusal boundaries belong to [Account API Contracts](./api-contracts.md#rest-apis) and its [gRPC inventory](./api-contracts.md#grpc-apis). The held boundary, preserved positive obligations, and proof history are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-public-account-facade-receiving). Current text `PLAY` evaluates fresh entitlement before membership/grant and later actor/binding checks; public `JOIN_REQUIRED` is limited to coherent missing or `INACTIVE` membership when enrollment permits repair. An active but non-admitting response is not a join fallback. Complete caller-target/atomic authority and the remaining AA-2.1 / Unit 1B boundaries remain open. These flows do not create or restore membership. The Account-owned public-production JOIN writer remains a prepared persistence component with atomic membership, operation-outcome, and audit-outbox evidence; the API composition contract linked above governs access to it. Its HTTP exposure remains blocked by the Gateway route guard; Game Session text `JOIN`/`Join & Play` dispatch remains with #2898, while durable recovery after an unknown database commit and Logging receipt receiver/readback remain with #2848. Focused PostgreSQL/component proof and its limits are recorded in the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#validation-and-proof); those controlled fixtures do not establish genuine deployed receiving custody or complete public admission. See [Account API Contracts](./api-contracts.md) for the public and internal API boundary and [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) for the canonical direct-text scope and JOIN contract. `GetAdmissionPointer` is a live `game_session.v1.GameSessionService` RPC served by the Game Session runtime owner and consumed by Account through `GameSessionClient`; its current response shape and the target routing semantics owned by Multi-Tenancy are described below. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling remain incomplete. The numeric runtime entitlement endpoint remains unavailable under the [Account API contract](./api-contracts.md#grpc-apis). Explicit free/trial row creation, an authoritative current-row selector/constraint/history, and canonical snapshot fields/freshness remain unimplemented, including nullable `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and event delivery. Earlier focused zero-row, mixed-row, gRPC classification, and replay-after-recovery proof is limited to the prior cardinality guard and retry boundary; it does not establish current positive entitlement production. `CommitTenantCapacityAdmission` has one synchronized target request/replay contract, including `mutationDigest`, but its proto RPC, callers, durable Account-owned authority/usage persistence, and reservation lifecycle remain unimplemented. The current `application.yml` and `application-prod.yml` retain `GetTenantMembershipForRuntime`, `GetRealmAccessGrantForRuntime`, `GetTenantEntitlementsForRuntime`, and `ListPresenceVisibilityPolicies` in the gRPC bearer-validation bypass list. Their handlers independently require certificate-derived workload identity in the exact configured namespace: Game Session for membership and realm-grant reads, Game Session or World Management for entitlement reads, and Social & Groups for presence-policy reads. Handler and configured-interceptor tests cover permitted peers without bearer credentials and refusal of unauthorized or wrong-namespace peers. This workload-only bypass does not make the methods unauthenticated public APIs. Complete typed caller-context and tenant-binding qualification, membership/currentness consumption, and the remaining canonical admission and registry contracts remain separate gaps under the [Account API contract](./api-contracts.md); these workload checks alone do not establish readiness. @@ -82,7 +78,7 @@ The target realm-grant mutation boundary remains the Account API's tenant-admin Recovery/verification foundations are live. Password-reset completion now uses an owner-locked atomic token claim/consume, Account update, canonical event and operation receipt, and current-source readback; an unresolved prior source intent fences token/password mutation and returns retryable `AUTH_UNAVAILABLE` until an exact retry can establish its outcome. `AccountAuthoritySourceEventReadback` accepts only the supported closed-operation event shapes with their exact immutable operation receipts; generic Account authority events without that receipt remain unreadable as current source evidence and fail closed as `AUTH_UNAVAILABLE`. This does not establish complete LOGIN/currentness closure. Reset-driven revocation and the broader recovery/session/logout family remain incomplete. Exact retry, concurrent reuse, and physical PostgreSQL proof for this cut remain pending under the [Account API recovery boundary](./api-contracts.md#rest-apis) and [authentication security contract](../../system-architecture-authentication.md). -Account locally implements `IssueDirectTextConnectScope` for an authenticated caller and the exact Game Session-resolved public-production target from `REALMS`, validating its retained target snapshot and caller binding. Game Session does not yet wire this RPC into text `REALMS` or retain the returned scope in transport context. Account also implements the `JoinPublicProductionMembership` RPC/operation and local HTTP JOIN route, including retained-target and caller-binding validation; Game Session text `JOIN`/`Join & Play` dispatch remains unimplemented under #2898. These local Account capabilities do not yet form an end-to-end direct-text `REALMS`-to-`JOIN` flow. Account request retries can resume a committed policy-independent intent across entitlement outages; after an uncertain second-transaction outcome, Account reads back and returns a terminal result if committed, otherwise asks the caller to retry that request ID. No background recovery worker or direct text-client end-to-end proof is claimed. The canonical scope and transport contract remains in [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). +Current public bootstrap, direct-scope, JOIN, connect-token and numeric entitlement receiving boundaries are defined by [Account API Contracts](./api-contracts.md#rest-apis) and its [gRPC inventory](./api-contracts.md#grpc-apis). The held boundary, preserved positive component obligations, and proof history are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). Game Session text `REALMS`/`JOIN` dispatch remains unimplemented under #2898; unknown JOIN outcome recovery and Logging receipt receiver/readback remain #2848, and direct text-client end-to-end proof remains open. The target scope and transport contract remains in [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). The target capacity retry contract uses stable outer `(tenantId, requestId, admissionId)`, fresh per-attempt `admissionAttemptId`, current `capacityRearmFence`, exact complete entitlement evidence, bounded `capacityDelta`, and a versioned `mutationDigest` over that attempt identity, fence, and complete payload. Exact retries replay the stored result. A new attempt requires an Account-owned atomic CAS over the same outer tuple, terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` plus durable no-commit evidence, current fence, and prior digest; the CAS advances the fence without creating a second reservation. Changed fields without a matching rearm return `IDEMPOTENCY_CONFLICT`; stale or losing fences return `FENCE_REJECTED` only with durable no-accept/no-runtime-mutation proof. This remains target-only and follows the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). @@ -99,8 +95,8 @@ Local unregistered Account owners now cover tenant-creation intent, admission, c Raw Telnet and other non-WebSocket text streams never see or transmit these JWT profiles. First-party browser/mobile gameplay clients use only the bounded `player-bootstrap` profile for HTTPS bootstrap; the one-use WebSocket connect token is a separate edge credential. Generic `Service JWT` and `aud=internal` profiles are forbidden. Workload-only calls use mTLS and exact method allowlists without a bearer token. Gameplay protocol clients (Telnet and WebSocket) never see or transmit private delegation tokens. - The live service hashes and verifies raw passwords with `argon2-jvm` Argon2 using `iterations=2`, `memory=65536 KiB`, and `parallelism=1`, with unique salts before PostgreSQL storage. - **Target state:** one versioned issued-token registry record per token is stored in Redis as described in [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md); gameplay session bindings are owned by the Game Session Service and are not managed directly here. **Current runtime:** authentication still uses the legacy Account session key rather than the ADR 0035 registry record. -- **Target state:** global Account registration creates only global account/security state and records a durable, owner-local audit outbox entry in that same local transaction. Tenant-scoped profile and membership operations are separate from registration; registration audit uses explicit **platform scope** and never fabricates a `tenantId`, creates membership, or restores membership. Tenant-scoped profile and successful `JoinPublicProductionMembership` events use explicit **tenant scope** with the exact committed `tenantId`; they never use platform scope. The sole membership writer remains explicit `JoinPublicProductionMembership`; a successful JOIN records its separate tenant-scoped audit/outbox consequence in the same membership transaction as described below. Each outbox record preserves one stable `auditEventId` and immutable event envelope/digest across retries, then delivers that unchanged record through the canonical Account audit-ingress, receipt, and readback contract owned by [Logging & Admin API Contracts](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). Any upstream Account domain-event digest is payload evidence; Logging & Admin's receiver computes its separate `payloadDigest` over the exact payload bytes. Account treats delivery as complete only after an exact receiver receipt; unavailable, timeout, mismatched, or ambiguous responses remain retryable with the same identity and never mint a replacement event. A terminal `MINIMIZED/NON_REPLAYABLE` result after the receiver's safe watermark is recorded against that same outbox identity, ends producer retry/reconciliation, and does not create a replacement event. Account's outbox cleanup remains gated by the receiver/readback horizon and safe-watermark rules owned by Logging & Admin; Account does not invent a second retention policy. This does not make Logging & Admin a second authority for Account state. **Current local implementation:** global registration and successful explicit JOIN append immutable Account audit envelopes in their respective local transactions. Account's directly callable offline delivery method submits the unchanged envelope and marks it delivered only after matching terminal receipt evidence; unavailable, `UNIMPLEMENTED`, timeout, mismatched, or ambiguous responses leave the same outbox identity `PENDING` for retry. The offline receipt/projection owner and authenticated readback are now locally prepared at the [Logging-owned boundary](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). Live `CreateLogEvent` refuses before storage and Account delivery is not automatically scheduled; outstanding outbox rows retain their original identity and remain pending. Account exact readback and guarded evidence recording, retention/cleanup and complete authenticated composition remain unimplemented or unqualified. After a matching terminal minimized receipt, Account atomically clears only its producer payload and retains compact event, digest, and receiver identity evidence; `COMMITTED` producer payloads still lack configured safe-watermark, hold, reference, and finite-retention cleanup proof. These are local producer facts, not PostgreSQL runtime or direct text end-to-end proof. The JOIN intent is committed before entitlement work, while policy binding, membership, audit outbox, and terminal outcome share one second transaction. Request-driven retry can resume a pending intent but does not resolve an unknown database commit outcome; durable JOIN recovery/reconciliation remains #2848 work, and no periodic pending-operation reconciler is claimed. -- **Target state:** Safety-restriction, recovery, and suspicious-activity events are delivered to Logging & Admin through Account's owner-local outbox, with delivery complete only after the exact receipt/readback or terminal reconciliation. Because `account_security_lock` and `platform_access_ban` and their recovery evidence are global, those audits use explicit **platform scope** and omit `tenantId`; Account remains the enforcement owner and Logging & Admin does not own or mutate Account restriction state. **Current implementation status:** registration and successful explicit JOIN use the durable outbox/receipt path described above. The remaining safety-restriction, recovery, and suspicious-activity audit producers have not been converged to that owner-local outbox, so their target delivery and receipt guarantees are not claimed as current behavior. +- **Target state:** global Account registration creates only global account/security state and records a durable, owner-local audit outbox entry in that same local transaction. Tenant-scoped profile and membership operations are separate from registration; registration audit uses explicit **platform scope** and never fabricates a `tenantId`, creates membership, or restores membership. Tenant-scoped profile events and membership creation or restoration through `JoinPublicProductionMembership` use explicit **tenant scope** with the exact committed `tenantId`; they never use platform scope. The sole membership writer remains explicit `JoinPublicProductionMembership`; a JOIN that creates or restores membership records its separate tenant-scoped audit/outbox consequence in the same membership transaction as described below. An existing ACTIVE member commits `ALREADY_ACTIVE` without a new audit/outbox row. Each outbox record preserves one stable `auditEventId` and immutable event envelope/digest across retries, then delivers that unchanged record through the canonical Account audit-ingress, receipt, and readback contract owned by [Logging & Admin API Contracts](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). Any upstream Account domain-event digest is payload evidence; Logging & Admin's receiver computes its separate `payloadDigest` over the exact payload bytes. Account treats delivery as complete only after an exact receiver receipt; unavailable, timeout, mismatched, or ambiguous responses remain retryable with the same identity and never mint a replacement event. A terminal `MINIMIZED/NON_REPLAYABLE` result after the receiver's safe watermark is recorded against that same outbox identity, ends producer retry/reconciliation, and does not create a replacement event. Account's outbox cleanup remains gated by the receiver/readback horizon and safe-watermark rules owned by Logging & Admin; Account does not invent a second retention policy. This does not make Logging & Admin a second authority for Account state. **Current local implementation:** global registration and explicit JOIN membership creation or restoration append immutable Account audit envelopes in their respective local transactions. The `ALREADY_ACTIVE` outcome commits without a new audit row. Account's directly callable offline delivery method submits the unchanged envelope and marks it delivered only after matching terminal receipt evidence; unavailable, `UNIMPLEMENTED`, timeout, mismatched, or ambiguous responses leave the same outbox identity `PENDING` for retry. The offline receipt/projection owner and authenticated readback are now locally prepared at the [Logging-owned boundary](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). Live `CreateLogEvent` refuses before storage and Account delivery is not automatically scheduled; outstanding outbox rows retain their original identity and remain pending. Account exact readback and guarded evidence recording, retention/cleanup and complete authenticated composition remain unimplemented or unqualified. After a matching terminal minimized receipt, Account atomically clears only its producer payload and retains compact event, digest, and receiver identity evidence; `COMMITTED` producer payloads still lack configured safe-watermark, hold, reference, and finite-retention cleanup proof. These are local producer facts, not PostgreSQL runtime or direct text end-to-end proof. The JOIN intent is committed before entitlement work; for membership creation or restoration, policy binding, membership, audit outbox, and terminal outcome share one second transaction. Request-driven retry can resume a pending intent but does not resolve an unknown database commit outcome; durable JOIN recovery/reconciliation remains #2848 work, and no periodic pending-operation reconciler is claimed. +- **Target state:** Safety-restriction, recovery, and suspicious-activity events are delivered to Logging & Admin through Account's owner-local outbox, with delivery complete only after the exact receipt/readback or terminal reconciliation. Because `account_security_lock` and `platform_access_ban` and their recovery evidence are global, those audits use explicit **platform scope** and omit `tenantId`; Account remains the enforcement owner and Logging & Admin does not own or mutate Account restriction state. **Current implementation status:** registration and explicit JOIN membership creation or restoration use the durable outbox/receipt path described above. The remaining safety-restriction, recovery, and suspicious-activity audit producers have not been converged to that owner-local outbox, so their target delivery and receipt guarantees are not claimed as current behavior. - Account may consume bounded relationship/projection data for Entity-owned actor discovery across games; Entity Management owns persisted actor rows, actor identity, playable-state namespace, creation/provisioning, and gameplay state. Account is not the actor writer or ownership authority. See [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md). - The core `account` record represents a global platform account identified by `accountId`. Tables that represent per-game state or billing attach to tenants via a `tenantId` column so the same platform account can join multiple games without data leakage. Every tenant-scoped query enforces this filter as described in [Multi-Tenancy](../../system-architecture-multi-tenancy.md). - Provides a JWKS endpoint for other services to validate tokens. Account Service owns signing-key lifecycle authorization, token issuance/rotation, desired key-ring state, and JWKS publication. In target non-exportable-signer mode, Account delegates only explicitly authorized private-key operations to the approved signer boundary; signer custody does not transfer lifecycle or publication authority. In the interim Account-only mounted fallback, the materialization controller is the sole Kubernetes API reader, writer, and generator for the fixed `jwt-signing-keys` Secret and custodian of that interim private material, but it may act only on Account-authorized operations. Account consumes projected key files and has no signing-Secret API authority. Kubernetes Jobs or CronJobs only observe Account-owned rotation, convergence, and retained evidence; they do not request or own rotation, read or write private keys, or publish JWKS, as described in the [Security Architecture](../../system-architecture-security.md). @@ -205,7 +201,7 @@ The `player-bootstrap` token profile is distinct from both `control-ui` and priv - Audience is `player-bootstrap`. - It is issued only by `POST /auth/player-bootstrap` / `IssuePlayerBootstrapToken`. - `POST /auth/player-bootstrap` is the canonical first-party browser/mobile player-login endpoint. It authenticates player credentials directly under the same password, OTP, brute-force defense, and account-lock policy used for gameplay login rather than deriving bootstrap from a pre-existing admin/creator session. -- It establishes account identity for first-party gameplay bootstrap only. Target behavior is that public-game membership is created only by explicit `/auth/bootstrap/join`; character discovery, character creation, and `POST /auth/connect-token` later require that membership and recheck applicable grants, entitlements, and the discovery-selected runtime target. World and realm discovery remain available before membership. On an eligible public-production target, character discovery returns non-actionable `JOIN_REQUIRED` for missing or `INACTIVE` membership when `allowPublicJoin` permits entry and `PUBLIC_PRODUCTION_ADMISSION_DENIED` otherwise; other present non-admitting membership is denied as `CONNECT_TOKEN_REJECTED`. Current text `PLAY` consumes the emitted membership lifecycle and independent authority generation alongside existence, admission, version, and evaluation-time evidence; it checks fresh entitlement before membership/grant and later actor/binding checks. Its implemented checks follow the [canonical PLAY outcome matrix](../../system-architecture-authentication.md#play-current-and-target-failure-boundaries). This implemented field validation is not the complete atomic freshness contract. Current connect-token issuance validates bootstrap identity and scope, then returns `AUTH_UNAVAILABLE` before membership, entitlement, target-authority, or cached-result processing. None of these paths creates or restores membership. The Account-owned public-production `JOIN` writer is implemented locally; first-party text `JOIN`/`Join & Play` dispatch and durable recovery after an unknown database commit outcome remain open. Non-public or non-visible targets remain subject to their realm-access and grant checks rather than using public onboarding semantics. +- It establishes account identity for first-party gameplay bootstrap only. Target behavior is that public-game membership is created only by explicit `/auth/bootstrap/join`; character discovery, character creation, and `POST /auth/connect-token` later require that membership and recheck applicable grants, entitlements, and the discovery-selected runtime target. World and realm discovery remain available before membership. On an eligible public-production target, character discovery returns non-actionable `JOIN_REQUIRED` for missing or `INACTIVE` membership when `allowPublicJoin` permits entry and `PUBLIC_PRODUCTION_ADMISSION_DENIED` otherwise; other present non-admitting membership is denied as `CONNECT_TOKEN_REJECTED`. Current text `PLAY` consumes the emitted membership lifecycle and independent authority generation alongside existence, admission, version, and evaluation-time evidence; it checks fresh entitlement before membership/grant and later actor/binding checks. Its implemented checks follow the [canonical PLAY outcome matrix](../../system-architecture-authentication.md#play-current-and-target-failure-boundaries). This implemented field validation is not the complete atomic freshness contract. Current connect-token and JOIN receiver composition is defined by [Account API Contracts](./api-contracts.md#rest-apis). None of these paths creates or restores membership. Account's owner-local public-production JOIN v2 remains a prepared persistence component under that API boundary. First-party text `JOIN`/`Join & Play` dispatch and durable recovery after an unknown database commit outcome remain open. Non-public or non-visible targets remain subject to their realm-access and grant checks rather than using public onboarding semantics. - It is stored in memory only by first-party gameplay UIs and is accepted only on gameplay-bootstrap surfaces such as bootstrap discovery and `POST /auth/connect-token`. - For first-party `/ws/game/**`, subsequent gameplay `LOGIN` must complete from the bootstrap/connect context already established for that socket; browser clients must not be required to replay account credentials after bootstrap. - If the token is lost because the page/app process is restarted, the client must restart bootstrap from `POST /auth/player-bootstrap`; the current architecture does not define a hidden silent-bootstrap refresh mechanism. @@ -265,12 +261,12 @@ Runtime caller contract: - Target success delivery uses only `Set-Cookie: Firemud-Connect-Token=...` with the gateway-required security attributes; the token is not returned in the response body or a response-header fallback. Current `/auth/connect-token` returns `AUTH_UNAVAILABLE` before creating a token or cookie, so no current first-party WebSocket admission is established. Under the target flow, browser/mobile clients and first-party non-browser clients with a protected cookie jar remain cookie-only. A future explicitly classified public/non-first-party WebSocket integration may use a dedicated one-time secure-storage response and handshake header only through the separately registered `non_first_party_public` route-matrix variant on the canonical `/ws/game/**` path defined by ADR 0029; it does not convert this cookie endpoint into a header fallback. - Bootstrap discovery surfaces must return the target snapshot `connectScopeId`, which cryptographically binds the exact `tenantId`, `worldSlug`, `realmSlug`, `playableStateNamespaceId`, `playableStateScope`, `gameInstanceId`, `catalogRevision`, `pointerVersion`, and `connectScopeExpiresAt`, together with `evaluatedAt`; every non-public target additionally binds exact `playtestLifecycleId` and positive `playtestStateGeneration`, while a non-grant public-production target omits both fields. - `connectScopeId` is short-lived cryptographic proof of the exact evaluated target, not a reservation. `catalogRevision` is the catalog/policy snapshot reference carried by the same authoritative Game Session routing record as `pointerVersion`; `allowPublicJoin` remains the separate Account entitlement field. `JoinPublicProductionMembership` accepts the unchanged `connectScopeId` and `requestId`; `connectScopeId` exclusively binds the target and exact `catalogRevision`/`pointerVersion` pair, so the request has no duplicate catalog or pointer fields. At the membership commit gate, Account verifies the scope's signature, expiry, and exact bound pair against the same fresh selected-target catalog/pointer/public-production routing snapshot. A missing, unavailable, malformed, stale, regressed, or ambiguous routing snapshot fails closed as `ADMISSION_POINTER_UNAVAILABLE`; a changed bound pair returns `CONNECT_SCOPE_MISMATCH`. Account must not silently re-resolve or select a newer target. Missing proto or caller support for carrying and proving this complete bound snapshot through that gate is implementation drift. -- Authenticated direct-text `REALMS` uses the same Account-issued scope class without exposing it to the text client. The Account `IssueDirectTextConnectScope` RPC is implemented locally: it receives trusted caller context and the exact Game Session-resolved target, validates the current catalog/pointer snapshot, and returns the opaque scope to Game Session. Game Session wiring from text `REALMS` and transport-local scope retention remain unimplemented, as does the subsequent text `JOIN` dispatch (#2898); the end-to-end producer flow and proof remain incomplete. +- Authenticated direct-text `REALMS` uses the same Account-issued scope class without exposing it to the text client. A prepared Account `IssueDirectTextConnectScope` component can receive trusted caller context and the exact Game Session-resolved target, validate the current catalog/pointer snapshot, and return an opaque scope. Current receiver composition and failure behavior are defined by [Account API Contracts](./api-contracts.md#grpc-apis). This is not default runtime exposure or end-to-end proof. Game Session wiring from text `REALMS`, transport-local scope retention, and subsequent text `JOIN` dispatch (#2898) remain unimplemented; the end-to-end producer flow and proof remain incomplete. - `connectScopeExpiresAt` bounds how long the discovery-issued selector may be reused as a convenience token. Once it expires, callers must rerun discovery instead of treating the selector as a durable realm handle. - Account Service must expose bootstrap-discovery endpoints that accept only the `player-bootstrap` token profile and return the canonical caller-visible worlds, realms, characters, and a canonical `connectScopeId` selector for each admissible realm target. - Account Service must use the authoritative realm-routing contract when issuing `/auth/connect-token` so connect-token scope is pinned to the tenant's current admissible instance for the selected realm instead of a caller-supplied guess. - `requestId` is the idempotency key for connect-token issuance. Retrying the same `(accountId, connectScopeId, requestId)` replays the same deterministic application failure directly while its retained failure envelope is available. A stored success returns the same token payload only after current authority and all applicable admission, registry, and issuance postconditions revalidate; failed revalidation returns the applicable canonical denial without reminting or mutating the committed issuance result. If the compact receipt still exists after its encrypted response envelope has been removed at the declared response-recovery horizon, an exact digest match returns `RESPONSE_RECOVERY_EXPIRED`, never remints or reconstructs a JWT, and is terminal for that original issuance attempt; callers must start a fresh authorized request under a new `requestId`. A changed digest remains `IDEMPOTENCY_CONFLICT`. The exact membership freshness baseline used for issuance is bound to that `connectScopeId` and `requestId`; it is immutable comparison evidence, not a duplicate request field. If Gateway may already have consumed the token, the caller must rediscover and use a new `requestId` rather than replaying the prior issuance key. - - **Target contract; current Account behavior is fail-closed.** The target requires caller-bound membership for every selected target. For a publicly visible public-production target whose joining policy permits entry, missing membership returns `JOIN_REQUIRED`, commits no membership row, successful gameplay-connect issuance record, token registry record, token, or cookie, and records the same deterministic failure under `(accountId, connectScopeId, requestId)`. An exact retry replays `JOIN_REQUIRED` even if membership is created later while its failure envelope remains retained; after response-envelope removal, a matching compact receipt returns `RESPONSE_RECOVERY_EXPIRED` rather than minting or changing the result. The caller must use a new request ID after the explicit join or recovery-expired terminal outcome. The target replay outcome is durable for the complete issuance-idempotency window. **Current runtime:** `AccountServiceImpl.issueConnectToken` validates the bootstrap identity and connect scope, then returns `AUTH_UNAVAILABLE` before membership checks, replay reads or writes, token minting, or session mutation. A private or playtest target additionally requires the current Account-owned realm-access grant under the target contract; a grant never substitutes for membership or public onboarding. The canonical contracts remain in [Authentication](../../system-architecture-authentication.md) and [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md). + - **Target contract; current Account behavior is fail-closed.** The target requires caller-bound membership for every selected target. For a publicly visible public-production target whose joining policy permits entry, missing membership returns `JOIN_REQUIRED`, commits no membership row, successful gameplay-connect issuance record, token registry record, token, or cookie, and records the same deterministic failure under `(accountId, connectScopeId, requestId)`. An exact retry replays `JOIN_REQUIRED` even if membership is created later while its failure envelope remains retained; after response-envelope removal, a matching compact receipt returns `RESPONSE_RECOVERY_EXPIRED` rather than minting or changing the result. The caller must use a new request ID after the explicit join or recovery-expired terminal outcome. The target replay outcome is durable for the complete issuance-idempotency window. **Current receiving boundary:** `AccountServiceImpl.issueConnectToken` follows the [Account API conditional bootstrap/scope validation boundary](./api-contracts.md#rest-apis), but remains unavailable before cached-result processing, membership/entitlement/target-authority reads, minting, or replay/session mutation. A private or playtest target additionally requires the current Account-owned realm-access grant under the target contract; a grant never substitutes for membership or public onboarding. The canonical contracts remain in [Authentication](../../system-architecture-authentication.md) and [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md). - The target membership-writer contract is `JoinPublicProductionMembership`; its canonical caller, scope, policy, and replay behavior is owned by [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). Connect-token issuance and public-production `PLAY` require existing membership and never invoke the writer implicitly. The local Account RPC, digest, transaction, and recovery status are recorded under [Implementation Status](#implementation-status). - It is valid only for the default public production realm and only when the caller satisfies the public-production admission policy. @@ -320,7 +316,7 @@ Entitlement producer contract: - `provisioningStatus` is `pending`, `provisioning`, or null; while non-null, `subscriptionStatus` is null and all new gameplay/admission/instance-start flags are false. `tenantAuthorityGeneration` is opaque and may be compared only for exact equality, never ordered or used as an event identity. - The focused producer proof must show that every entitlement response is one Account-authenticated bundle from the same authoritative committed evaluation, that `tenantAuthorityGeneration` is the Account-committed fence rather than a value reconstructed from a later projection read, and that no caller reconstructs or separately sources bundle identities, tuple members, cutoff evidence, or checkpoints. -Current implementation remains a narrower local subscription read: unusable row sets and versions fail closed, and classified storage failures are kept distinct from programming faults. JOIN diagnostic persistence uses its existing post-rollback path, while terminal retry refusal preserves the original receipt. This supplies neither the complete bundle above nor positive connect-token issuance. Current proof and remaining boundaries belong to the [entitlement read tracker](../../../project-management/implementation-tracking/player-access-and-session.md#entitlement-read-and-join-failure-classification). +The numeric runtime entitlement endpoint follows the [Account API refusal boundary](./api-contracts.md#endpoint-authentication-classes). The separate manually composed PLAYER_ADMISSION owner/receiver and Game Session client preserve canonical V2 scope/current-owner evidence under the [private purpose contract](./api-contracts.md#private-player-admission-entitlement-read); their presence does not wire or qualify a runtime cutover. Canonical UUID billing and the distinct unregistered `TENANT_OPERATION` source are prepared separately; the complete public `PLAYER_ADMISSION` consumer is not yet qualified. [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-public-account-facade-receiving) owns public receiving proof and gaps. ### Playtest Grant Persistence and Authority Consequences @@ -357,11 +353,11 @@ Existing `AccountRealmAccessGrant` persistence and registered internal grant rea ### Runtime Implementation Status and Drift -- Account's owner-local JOIN v2 model adds a closed canonical scope, stable intent digest, and policy-bound request digest to the existing persistence foundation. It does not change the current JoinPublicProductionMembership RPC or confer target authority by digest alone. Account login/public JOIN wiring, Game Session text JOIN dispatch (#2898), unknown-outcome recovery (#2848), PostgreSQL execution, and direct text-client proof remain outstanding. +- Account's owner-local JOIN v2 model remains a prepared persistence component with a closed canonical scope, stable intent digest, and policy-bound request digest. The [Account API contract](./api-contracts.md#rest-apis) owns its receiving composition and refusal boundaries; canonical status, preserved obligations, and proof history are in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). Game Session text JOIN dispatch (#2898), unknown-outcome recovery (#2848), PostgreSQL execution, and direct text-client proof remain outstanding. -- Account-first bootstrap now authenticates before tenant selection and accepts configured password or verified-email OTP modes. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current Account connect-token issuance validates bootstrap identity and connect-scope binding, then returns `AUTH_UNAVAILABLE` before membership, entitlement, admission-pointer, cached-success, or token-minting work. Character discovery checks local membership existence/admission after fresh entitlement and target checks. On an eligible public-production target, missing or `INACTIVE` membership returns `JOIN_REQUIRED` when `allowPublicJoin` permits entry and `PUBLIC_PRODUCTION_ADMISSION_DENIED` otherwise; other present non-admitting membership is denied as `CONNECT_TOKEN_REJECTED`. Current text `PLAY` implements lifecycle/generation validation and entitlement-first ordering under the [canonical PLAY outcome matrix](../../system-architecture-authentication.md#play-current-and-target-failure-boundaries); complete caller-target and atomic authority proof remains open. The Account-owned explicit public-production JOIN writer and operation controller, including the local `POST /auth/bootstrap/join` REST route, exist locally; its public Gateway exposure remains blocked by the explicit route guard pending production proof. Game Session text `JOIN`/`Join & Play` dispatch remains with #2898; recovery after unknown JOIN commit outcomes and Logging receipt receiver/readback remain #2848. PostgreSQL exact-final-head proof and direct text-client end-to-end proof remain incomplete. The target connect-token membership-authority-generation reread remains unenforced and is a prerequisite for any future connect-token producer. The current non-public character-discovery mapping returns `NON_PUBLIC_ENROLLMENT_REQUIRED` when membership is missing and `CONNECT_TOKEN_REJECTED` when membership exists but does not admit gameplay; connect-token issuance instead returns `AUTH_UNAVAILABLE` before membership processing. Text `PLAY` implements the private membership and grant checks covered by the canonical outcome matrix linked above; complete caller-target, grant-lifecycle/expiry, and atomic freshness proof remains open. Non-public or non-visible targets remain grant-gated and do not use public onboarding semantics. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling are also incomplete. +- Account-first bootstrap now authenticates before tenant selection and accepts configured password or verified-email OTP modes. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current receiver composition and refusal boundaries belong to [Account API Contracts](./api-contracts.md#rest-apis) and its [gRPC inventory](./api-contracts.md#grpc-apis). The held boundary and preserved source obligations/proof are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). Current text `PLAY` implements lifecycle/generation validation and entitlement-first ordering under the [canonical PLAY outcome matrix](../../system-architecture-authentication.md#play-current-and-target-failure-boundaries); complete caller-target and atomic authority proof remains open. The public Gateway route remains blocked by its explicit guard. Game Session text `JOIN`/`Join & Play` dispatch remains with #2898; recovery after unknown JOIN commit outcomes and Logging receipt receiver/readback remain #2848. PostgreSQL exact-final-head proof and direct text-client end-to-end proof remain incomplete. The target connect-token membership-authority-generation reread remains unenforced and is a prerequisite for any future connect-token producer. The current non-public character-discovery mapping returns `NON_PUBLIC_ENROLLMENT_REQUIRED` when membership is missing and `CONNECT_TOKEN_REJECTED` when membership exists but does not admit gameplay. Text `PLAY` implements the private membership and grant checks covered by the canonical outcome matrix linked above; complete caller-target, grant-lifecycle/expiry, and atomic freshness proof remains open. Non-public or non-visible targets remain grant-gated and do not use public onboarding semantics. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling are also incomplete. -The current JOIN implementation re-reads Game Session routing/catalog/pointer evidence but does not ensure that the exact target remains valid through the Account commit. The strict ADR 0025 commit gate is incomplete; detailed implementation and proof status is tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#capability-status). +The prepared JOIN component re-reads Game Session routing/catalog/pointer evidence but does not ensure that the exact target remains valid through the Account commit. The [Account API contract](./api-contracts.md#rest-apis) owns its receiving composition and refusal boundaries. This does not establish default runtime exposure or qualified live JOIN. The strict ADR 0025 commit gate is incomplete; detailed implementation and proof status is tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#capability-status). Account deletion currently fails closed when `hasRetainedOperation` finds any retained JOIN operation row, including terminal receipts; any such row blocks deletion. Bounded JOIN receipt cleanup/minimization and deletion reconciliation are not implemented. Account's retention/deletion workflow owns that follow-through under [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md) and [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md); it depends on the JOIN receipt and unknown-outcome reconciliation work in #2848. No universal retention duration is implied. diff --git a/design/architecture/system-architecture-authentication.md b/design/architecture/system-architecture-authentication.md index d89d377b00..9d61684ca2 100644 --- a/design/architecture/system-architecture-authentication.md +++ b/design/architecture/system-architecture-authentication.md @@ -418,9 +418,9 @@ POST /auth/player-bootstrap GET /auth/bootstrap/worlds Authorization: Bearer --> [{ worldSlug: "demo", displayName: "Demo World" }] # abbreviated world list; full realm snapshot follows +-> [{ tenantSlug: "demo", worldSlug: "demo", displayName: "Demo World" }] # abbreviated world list; full realm snapshot follows -GET /auth/bootstrap/worlds/demo/realms +GET /auth/bootstrap/worlds/demo/realms?tenantSlug=demo Authorization: Bearer -> [{ worldSlug: "demo", @@ -465,9 +465,9 @@ POST /auth/player-bootstrap GET /auth/bootstrap/worlds Authorization: Bearer --> [{ worldSlug: "emberfall", displayName: "Emberfall" }] # abbreviated world list; full realm snapshot follows +-> [{ tenantSlug: "emberfall-studio", worldSlug: "emberfall", displayName: "Emberfall" }] # abbreviated world list; full realm snapshot follows -GET /auth/bootstrap/worlds/emberfall/realms +GET /auth/bootstrap/worlds/emberfall/realms?tenantSlug=emberfall-studio Authorization: Bearer -> [{ worldSlug: "emberfall", @@ -488,7 +488,7 @@ Authorization: Bearer { connectScopeId: "cs_emberfall_production_v1", requestId: "req-join-1" } -> { tenantId: "e14f2d0c-8b7a-4f26-9c51-6a3d7e8b2c40", membershipExists: true, membershipLifecycleState: "ACTIVE", roles: ["player"], gameplayAdmissionAllowed: true, membershipAuthorityGeneration: 8, membershipVersion: 1, authorityTuple: { issuerAuthGeneration: 7, accountAuthorityGeneration: 12, tenantAuthorityGeneration: { "e14f2d0c-8b7a-4f26-9c51-6a3d7e8b2c40": 4 }, membershipAuthorityGeneration: { "e14f2d0c-8b7a-4f26-9c51-6a3d7e8b2c40": 8 }, privateRealmGrantVersions: [] }, evaluatedAt: "2026-08-02T00:00:00Z", outboxCheckpoints: [{ outboxStreamKey: "account:auth-authority:v1:membership//", outboxSequence: 1 }], joined: true } -GET /auth/bootstrap/worlds/emberfall/realms +GET /auth/bootstrap/worlds/emberfall/realms?tenantSlug=emberfall-studio Authorization: Bearer -> [{ worldSlug: "emberfall", @@ -548,9 +548,9 @@ POST /auth/player-bootstrap GET /auth/bootstrap/worlds Authorization: Bearer --> [{ worldSlug: "demo", displayName: "Demo World" }] # abbreviated world list; full realm snapshot follows +-> [{ tenantSlug: "demo", worldSlug: "demo", displayName: "Demo World" }] # abbreviated world list; full realm snapshot follows -GET /auth/bootstrap/worlds/demo/realms +GET /auth/bootstrap/worlds/demo/realms?tenantSlug=demo Authorization: Bearer -> [ { diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index ed82c88074..e92de2b824 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -76,7 +76,7 @@ The optional [Static Analysis Summary](../../.github/workflows/static-analysis-s | Workflow | Execution context | Responsibility | What its GitHub run means | | --- | --- | --- | --- | -| [`runtime-images.yml`](../../.github/workflows/runtime-images.yml) (`Build Runtime Images`) | Untrusted PR merge commit with read-only repository permissions | Build the PR merge commit locally, run the explicit held-admission qualification, and upload the successful image artifact under an immutable tag keyed to the tested merge SHA | The recorded base/head/merge input was built without registry-write credentials. The smoke preserves direct backend `LOGIN` -> `PLAY` -> `LOOK` proof and verifies Gateway/Telnet fail closed; it does not establish successful public admission. See [player-flow smoke boundaries](system-architecture-testing.md#player-flow-smoke-and-reset-boundaries). | +| [`runtime-images.yml`](../../.github/workflows/runtime-images.yml) (`Build Runtime Images`) | Untrusted PR merge commit with read-only repository permissions | Build the PR merge commit locally, run the explicit held-admission qualification, and upload the successful image artifact under an immutable tag keyed to the tested merge SHA | The recorded base/head/merge input was built without registry-write credentials. Successful smoke preserves direct backend `LOGIN` -> `PLAY` -> `LOOK` proof and verifies Gateway/Telnet fail closed; it does not establish successful public admission. The diagnostic exception below provides no passing `PLAY` or `LOOK` proof. See [player-flow smoke boundaries](system-architecture-testing.md#player-flow-smoke-and-reset-boundaries). | | [`smoke.yml`](../../.github/workflows/smoke.yml) (`PR Smoke Gate`) | PR metadata and Actions API | Decide whether runtime smoke is required and expose the protected `Smoke Gate` by tracking the matching `Build Runtime Images` result | This is a controller and required gate; it does not run a second copy of the runtime qualification. Metadata-only edits keep the required `Smoke Gate` context but do not dispatch or cancel runtime construction; preservation follows [Required Gate Preservation](#required-gate-preservation), including an acknowledged supplementary pending barrier until matching substantive proof succeeds. | | [`publish-pr-runtime-images.yml`](../../.github/workflows/publish-pr-runtime-images.yml) (`Publish PR Runtime Images`) | Trusted default-branch `workflow_run` or typed `repository_dispatch` definition | Verify the current PR and exact source artifact identity, then publish immutable `pr-merge-` tags in GHCR | GitHub displays the default branch because the trusted publisher runs there; its summary identifies the source PR run and base/head/merge SHAs. | | [`preview.yml`](../../.github/workflows/preview.yml) (`PR Preview Environment`) | PR-scoped untrusted source run | Render and upload a sanitized full-stack chart artifact without deployment credentials | The artifact is bound to the PR head and recorded base/merge SHAs; PR-controlled code never receives cluster or registry credentials. | @@ -84,13 +84,13 @@ The optional [Static Analysis Summary](../../.github/workflows/static-analysis-s The trust split is deliberate: PR-controlled source can build and execute without package-write authority, while the trusted publisher never checks out or executes PR source. The current base branch ref and the test merge's ordered base/head parents establish the exact tuple for image publication and preview selection; a pull request event or API `base.sha` can lag the branch ref and is not current-base authority for those actions. The required Smoke Gate accepts a successful credential-free smoke run for its verified PR-event base/head/merge tuple. If GitHub supplies no usable event merge SHA or the event base SHA already lags the event merge's parents, the gate instead requires a successful trusted, typed refresh for the verified current base/head/merge tuple. An unrelated base advance after valid event-tuple smoke does not invalidate that tested merge or require the PR head to absorb new dependencies; a changed PR head or base branch requires new proof. The source run records the verified base, head, and merge SHAs, and the merge SHA keys the immutable PR image tag. Ordinary previews remain limited to same-repository, non-dependency-bot pull requests targeting `main` or `develop`. The credential-free runtime producer and required Smoke Gate cover every PR base, including same-repository feature branches, while retaining runtime path classification and an explicit no-op for irrelevant changes. Hosted preview and registry publication retain their separate eligibility policy: a stacked pull request requires the maintainer-controlled `preview:priority` label, an open mergeable state, and a current same-repository base. Completed Validation callbacks qualify long-lived branch pushes or substantive same-repository PR heads against the current branch ref before dispatching child-specific exact base/head/merge runtime refreshes. PR callbacks verify the current native CI attempt and executed substantive enforcement with skipped metadata preservation before reconciling their source PR's current tuple, recovering retarget edits whose event merge cannot qualify. Metadata-only, superseded, or unclassifiable attempts do not reconstruct runtime. PR-completion reconciliation is isolated by source run ID and attempt, so a metadata completion cannot cancel a substantive refresh; protected branch publication retains its separate branch serialization. Dependent refresh for `main` and `develop` belongs only to their push callback; PR callbacks whose head is one of those branches still reconcile their own source PR. A stale parent callback cannot dispatch proof for an advanced branch, and the callback itself supplies no child smoke proof. Preview reconciliation is dispatched only for independently eligible targets; scheduled preview reconciliation remains an additional recovery path. A failed branch CI run cannot publish branch images; the separately dispatched PR merge images can be published only after their own held-admission qualification succeeds and the trusted publisher validates their current eligibility and provenance. Preview selection fails closed until a successful image run for the new merge is published. An ordinary `main`/`develop` PR with no runtime-image change may instead reuse the proven base-commit service images. A stacked PR always uses its exact merge image because its feature-branch base SHA is not a trusted branch-image identity. -A typed runtime refresh hands off publication explicitly after its required credential-free image and smoke jobs succeed. Its separate trusted default-ref job checks out no source and receives only job-scoped `contents: write` to send `pr-runtime-image-publication` with the sole `source_run_id` field. PR build jobs retain read-only repository permissions. The publisher accepts this fixed repository-dispatch type and ordinary successful runtime workflow-run callbacks, both using the trusted default-branch definition. It exposes no branch-selectable manual publication entrypoint and requires no additional credential. +A typed runtime refresh hands off publication explicitly after its required credential-free image and smoke jobs succeed and its image artifact upload succeeds; an exception pass with no uploaded artifact cannot dispatch publication. Its separate trusted default-ref job checks out no source and receives only job-scoped `contents: write` to send `pr-runtime-image-publication` with the sole `source_run_id` field. PR build jobs retain read-only repository permissions. The publisher accepts this fixed repository-dispatch type and ordinary successful runtime workflow-run callbacks, both using the trusted default-branch definition. It exposes no branch-selectable manual publication entrypoint and requires no additional credential. The publisher's no-checkout, Actions-read-only resolver reads only the supplied exact source run and owning runtime workflow identity. A dispatch can arrive before its source workflow finishes, so the resolver waits for actual terminal success within a two-minute budget; malformed provenance, an API error, a failed or cancelled source, and an exhausted wait fail closed. The resolver never substitutes a successful status. Both trigger paths retain the same exact source, current PR/base/head/merge, artifact provenance, and immutable-tag validation. Publishing jobs serialize on the verified merge-bound source title across both paths; duplicate publication preserves identical existing images and rejects conflicting image bytes. Explicit dispatch avoids relying on a workflow-run callback from a token-origin refresh without weakening the source or registry boundary. -Smoke Gate retains affirmative successful smoke-step evidence for earlier producers. When GitHub omits or delays step metadata, the canonical producer additionally qualifies through its native `PR Full-Stack Smoke (runtime-required=true)` job identity and successful terminal job outcome. This producer has stable smoke and cleanup step IDs and an unconditional terminal guard that requires both Actions-native outcomes to be `success`; skipped, missing, cancelled, or failed execution or authenticated cleanup cannot qualify. Non-required image builds use a different evaluated job name. The gate verifies the exact successful run attempt, owning repository/workflow/event, native job ID/attempt/head/check URL, canonical PR/base/head/merge title, ordered merge parents, and current PR head/base branch before accepting this path. It also rechecks that no newer attempt superseded that source. Job success, logs, command-written outputs, and image artifacts alone are not smoke proof. The existing native job name does not widen the held-admission proof scope defined above. +Smoke Gate retains affirmative successful smoke-step evidence for earlier producers. When GitHub omits or delays step metadata, the canonical producer additionally qualifies through its native `PR Full-Stack Smoke (runtime-required=true)` job identity and successful terminal job outcome. This producer has stable smoke and cleanup step IDs and an unconditional terminal guard. Ordinary runtime qualification requires both Actions-native outcomes to be `success` and the transition-exception marker to be explicitly skipped. Missing marker metadata cannot use the native-job fallback: a successful job alone may instead represent the bounded exception described below. Skipped, missing, cancelled, or failed execution or authenticated cleanup cannot qualify as real runtime proof. Non-required image builds use a different evaluated job name. The gate verifies the exact successful run attempt, owning repository/workflow/event, native job ID/attempt/head/check URL, canonical PR/base/head/merge title, ordered merge parents, and current PR head/base branch before accepting this path. It also rechecks that no newer attempt superseded that source. Job success, logs, command-written outputs, and image artifacts alone are not smoke proof. The existing native job name does not widen the held-admission proof scope defined above. A separate, temporary diagnostic exception lets the required Smoke Gate succeed for a same-repository `benhook1013/FireMUD` pull request whose current live PR carries the `canonical-play-transition` label. A `pull_request` producer also requires the source event label and exact verified PR-event base/head/merge tuple. A typed `pr-runtime-base-refresh` producer instead derives label authority from its verified live same-repository PR, never dispatch payload labels, and requires the exact current base/head/merge tuple again at consumption. Both paths require the latest successful CI attempt with its explicit exception marker while the PR head and base branch remain current. During the default-branch workflow rollout, the exact previous fail-red producer fingerprint remains accepted only with its original failed smoke and terminal guard plus successful marker and cleanup; it supplies the same diagnostic exception and no runtime qualification. The smoke invocation retains its failed Actions-native outcome through step-level continuation; only the exact label, classifier and successful authenticated cleanup can make the mandatory final guard accept that failed probe. Every other probe failure still fails CI. GitHub reports the continued step conclusion as success, so the consumer verifies the immutable marker rather than treating that conclusion as runtime proof. The fingerprinted producer must attest the classified direct-backend `PLAY` `ERROR ENTITLEMENT_UNAVAILABLE` after successful held-admission qualification and backend `LOGIN`, with successful authenticated cleanup. The executing workflow is fingerprinted at the PR merge revision or typed refresh's native default-branch revision, respectively; classifiers, held-admission qualification, authenticated cleanup, certificate setup, and their checked-in environment and Compose inputs are always fingerprinted at the tested PR merge. Its original smoke failure remains visible in the probe logs, summary and Actions-native outcome; unrelated failures still block, and image export and upload must be skipped. The typed publication handoff also requires a real successful image upload. A trusted workflow-run publisher detects the exception marker before exposing a publication source and skips its privileged job; a successful CI conclusion under exception does not authorize registry access or preview images. This is gate acceptance for the nonproduction canonical cutover, not successful smoke, runtime qualification, branch-image promotion, hosted preview eligibility, or production activation. Trusted `main`/`develop` branch publication still requires real passing `LOGIN` → `PLAY` → `LOOK` smoke and cannot use this exception; after the cutover merges, branch images remain on hold until the Account entitlement path is repaired. Remove the label-based marker and consumer exception when fresh-image backend `LOGIN` → `PLAY` → `LOOK` passes, then remove this transitional contract. The [player access tracker](../project-management/implementation-tracking/player-access-and-session.md#temporary-canonical-play-transition-exception) records the current cutover proof gap. -The step-independent producer guarantee is bound to one SHA-256 fingerprint of the entire immutable source workflow definition, including its surrounding YAML execution context. Pull-request attempts use the verified event test-merge revision; typed refresh attempts use their native default-branch `head_sha`. Missing, unavailable, altered, or unattributable definitions cannot use this guarantee, and older producers with missing step metadata remain closed. Every change to [runtime-images.yml](../../.github/workflows/runtime-images.yml) requires review of the producer guarantee and an update of `canonicalRuntimeWorkflowSha256` in [smoke.yml](../../.github/workflows/smoke.yml). The existing [required-gate contract](../../dev-tools/tests/pr-required-gate-context-contract.sh) computes the expected fingerprint and reports the exact update when it is stale; it also exercises native outcome rejection, immutable revision/attempt attribution, and the retained older step-proof path. This single fingerprint is part of the owning workflows, not a separate proof registry. +The producer guarantee, independent of smoke-step metadata but requiring an explicit skipped exception marker, is bound to a SHA-256 fingerprint of the entire immutable source workflow definition, including its surrounding YAML execution context. Pull-request attempts use the verified event test-merge revision; typed refresh attempts use their native default-branch `head_sha`. Missing, unavailable, altered, or unattributable definitions cannot use this guarantee, and older producers with missing step metadata remain closed. Every change to [runtime-images.yml](../../.github/workflows/runtime-images.yml) requires review of the producer guarantee and an update of `canonicalRuntimeWorkflowSha256` in [smoke.yml](../../.github/workflows/smoke.yml). The existing [required-gate contract](../../dev-tools/tests/pr-required-gate-context-contract.sh) computes the expected fingerprint and reports the exact update when it is stale; it also exercises native outcome rejection, immutable revision/attempt attribution, and the retained older step-proof path. Every change to a fingerprinted classifier, qualification or cleanup script, certificate setup, environment defaults, or Compose input also requires review and an update of `canonicalPlayClassifierSha256` in `smoke.yml`; the required-gate contract reports each stale value. These fingerprints remain part of the owning workflows, not a separate proof registry. Branch-to-environment promotion contract: @@ -152,7 +152,7 @@ Other workflows support additional automation: - [`weekly-security-scan.yml`](../../.github/workflows/weekly-security-scan.yml) runs the weekly Trivy image scan. - [`ort-advisory.yml`](../../.github/workflows/ort-advisory.yml) runs the **Weekly ORT Advisory Scan**. - [`publish-base-image.yml`](../../.github/workflows/publish-base-image.yml) runs the **Weekly FireMUD Base Image Refresh** and is also the branch-guarded publication path for explicit base-image rebuilds on `develop` / `main`. -- [`runtime-images.yml`](../../.github/workflows/runtime-images.yml) builds pull-request images locally and runs the explicit held-admission qualification without a registry-write token. This proves direct backend `LOGIN` -> `PLAY` -> `LOOK` and Gateway/Telnet fail-closed behavior; it does not establish successful public admission. After successful required PR jobs, a typed runtime refresh explicitly hands its exact source run to the publisher; ordinary PR runs use completion callbacks. [`publish-pr-runtime-images.yml`](../../.github/workflows/publish-pr-runtime-images.yml) runs from the trusted default-branch workflow definition, verifies the exact source and artifact, and publishes only the immutable `pr-merge-` tags needed by hosted previews. It never checks out or executes PR source and never writes shared cache or branch tags. Trusted branch images use a candidate tag through full-stack smoke before the tested digests receive the canonical commit-SHA and branch aliases. +- [`runtime-images.yml`](../../.github/workflows/runtime-images.yml) builds pull-request images locally and runs the explicit held-admission qualification without a registry-write token. A successful smoke run proves direct backend `LOGIN` -> `PLAY` -> `LOOK` and Gateway/Telnet fail-closed behavior; it does not establish successful public admission. The [temporary diagnostic exception](#pull-request-runtime-and-preview-chain) provides no passing `PLAY` or `LOOK` proof and permits no image publication. After successful required PR jobs, a typed runtime refresh explicitly hands its exact source run to the publisher; ordinary PR runs use completion callbacks. [`publish-pr-runtime-images.yml`](../../.github/workflows/publish-pr-runtime-images.yml) runs from the trusted default-branch workflow definition, verifies the exact source and artifact, and publishes only the immutable `pr-merge-` tags needed by hosted previews. It never checks out or executes PR source and never writes shared cache or branch tags. Trusted branch images use a candidate tag through full-stack smoke before the tested digests receive the canonical commit-SHA and branch aliases. --- diff --git a/design/architecture/system-architecture-frontend.md b/design/architecture/system-architecture-frontend.md index 1c61352bf7..e8f90660fb 100644 --- a/design/architecture/system-architecture-frontend.md +++ b/design/architecture/system-architecture-frontend.md @@ -170,9 +170,9 @@ POST /auth/player-bootstrap GET /auth/bootstrap/worlds Authorization: Bearer --> [{ worldSlug: "demo", displayName: "Demo World" }] # abbreviated world list; full realm snapshot follows +-> [{ tenantSlug: "demo", worldSlug: "demo", displayName: "Demo World" }] # abbreviated world list; full realm snapshot follows -GET /auth/bootstrap/worlds/demo/realms +GET /auth/bootstrap/worlds/demo/realms?tenantSlug=demo Authorization: Bearer -> [{ worldSlug: "demo", diff --git a/design/architecture/system-architecture-testing.md b/design/architecture/system-architecture-testing.md index 689e7ca94e..132d9687c2 100644 --- a/design/architecture/system-architecture-testing.md +++ b/design/architecture/system-architecture-testing.md @@ -145,7 +145,9 @@ This example is illustrative rather than exhaustive and shows the target-state a The `logPipelineQueryability` object above is the default indexed-profile form under [ADR 0162](./decisions/adr-0162-profile-aware-asynchronous-end-to-end-log-queryability-evidence.md) and the canonical [Log Pipeline Queryability Contract](./system-architecture-logging-monitoring.md#log-pipeline-queryability-contract). Its closed capability vocabulary is `indexed-log-observability`, `console-journal-log-observability`, or `log-queryability-omitted`; non-omitted evidence uses `result="passed"` or `result="failed"`, while `result="not_applicable"` is reserved for explicit omission. `backend` and `storageTarget` identify where a non-omitted record is retained; `queryPath` identifies the final supported operator surface and must not contain only an index or stream convention. A `passed` result is valid only when the fresh unique `recordId` and known `traceId` identify the exact retrieved record, `verifiedFields` records every asserted source field, the timestamps are chronological (`emittedAt <= retrievedAt <= evidenceObservedAt <= verifiedAt`), `observedDelaySeconds` equals `retrievedAt - emittedAt`, the observed delay is no greater than `configuredDelayTargetSeconds`, and the retained evidence has not passed `evidenceExpiresAt`. Every result carries a positive finite, profile-resolved `evidenceFreshnessBudgetSeconds`; `evidenceExpiresAt` must equal `evidenceObservedAt + evidenceFreshnessBudgetSeconds`. `verifiedAt` is the trusted evaluator completion time, so source timestamps cannot be future-dated relative to it. A compatible indexed backend retains the same fields with its mapped storage target and supported query path. A reduced profile that advertises console or journal retrieval proves the same unique-record retrieval and timing through its declared backend, storage target, and final operator query path. A failed result is non-authorizing in readiness validation and is accepted only with the explicit incident/failure-evidence mode. A profile that explicitly omits queryability records the selected profile, `capability="log-queryability-omitted"`, `result="not_applicable"`, its omission reason, observation/expiry timestamps, and an evidence reference without fabricating indexed or retrieval fields such as backend, storage target, query path, emission/retrieval timestamps, delay measurements, record identity, source identity, or verified fields. -Use `python3 dev-tools/observability/run-player-experience-smoke.py --external-authority-evidence --queryability-profile --queryability-freshness-budget-seconds --evidence-out [--metrics-out ] [--synthetic-identity-evidence ]` to generate the journey and mirrored-signal part of hosted-assurance smoke evidence, incorporate actual results from the separately exercised canary alert path, then run `python3 dev-tools/observability/validate-player-experience-smoke-evidence.py ` before attaching the completed result to a traffic-open or recovery record. `authority.json` must be the retained profile-aware result from the authoritative external monitor for the deadman and declared public paths, or an explicit `independent-omitted` record with its degraded-detection reason. An advertised player-flow canary additionally requires an implemented authoritative synthetic identity/isolation verifier; until that verifier exists, the runner downgrades the request to `playerFlowCanary=omitted` even when a local `identity.json` contains plausible assertions, and the validator rejects retained evidence that claims `advertised`. The queryability profile and positive freshness budget must be supplied by the selected deployment profile and must match the target environment's expected-bindings declaration; the runner does not invent defaults. The validator uses current UTC by default, or a trusted `--evaluation-time ` seam for deterministic contract tests. Only `--simulate` may synthesize that authority object. +For a live run that exposes WebSocket with published Prometheus mirrors, set `PLAYER_EXPERIENCE_WORLD=` and `PLAYER_EXPERIENCE_TENANT_SLUG=` to the matching world/tenant pair from the Account bootstrap-world listing; world slugs are not globally unique. An authorized player-flow canary on an exposed WebSocket path requires the same selector. The runner checks this configuration before readiness, account, authentication, or WebSocket requests. Simulation, omitted mirrors with no authorized canary, and profiles that expose no WebSocket path do not require the selector. + +Use `PLAYER_EXPERIENCE_WORLD= PLAYER_EXPERIENCE_TENANT_SLUG= python3 dev-tools/observability/run-player-experience-smoke.py --external-authority-evidence --queryability-profile --queryability-freshness-budget-seconds --evidence-out [--metrics-out ] [--synthetic-identity-evidence ]` to generate the journey and mirrored-signal part of hosted-assurance smoke evidence, incorporate actual results from the separately exercised canary alert path, then run `python3 dev-tools/observability/validate-player-experience-smoke-evidence.py ` before attaching the completed result to a traffic-open or recovery record. `authority.json` must be the retained profile-aware result from the authoritative external monitor for the deadman and declared public paths, or an explicit `independent-omitted` record with its degraded-detection reason. An advertised player-flow canary additionally requires an implemented authoritative synthetic identity/isolation verifier; until that verifier exists, the runner downgrades the request to `playerFlowCanary=omitted` even when a local `identity.json` contains plausible assertions, and the validator rejects retained evidence that claims `advertised`. The queryability profile and positive freshness budget must be supplied by the selected deployment profile and must match the target environment's expected-bindings declaration; the runner does not invent defaults. The validator uses current UTC by default, or a trusted `--evaluation-time ` seam for deterministic contract tests. Only `--simulate` may synthesize that authority object. The default runner intake and validator invocation are readiness-strict: every exposed path and advertised canary flow must be green, and every required alert family must have an actually exercised `passed` result, so promotion and recovery consumers fail closed on a current failure or an unproved alert path. For incident capture and alert-path diagnosis only, pass `--allow-failure-evidence` to the runner when the retained source authority is red and to the validator when checking the resulting artifact. That mode accepts structurally complete current red deadman/public-path authority, zero-valued failed or prerequisite-blocked path/canary records, and `failed` or `not_exercised` alert-path results. It keeps external-authority shape, provenance, chronology, freshness, and record completeness strict and must not be used as traffic-open or recovery authority. diff --git a/design/product/user-journeys/players.md b/design/product/user-journeys/players.md index 50659a67c6..5ce40e9026 100644 --- a/design/product/user-journeys/players.md +++ b/design/product/user-journeys/players.md @@ -130,7 +130,7 @@ Example first-party web flow for a returning member or grant-backed target: ```text POST /auth/player-bootstrap { accountIdentifier=player@example.com, secret= } GET /auth/bootstrap/worlds -GET /auth/bootstrap/worlds/{world}/realms +GET /auth/bootstrap/worlds/{world}/realms?tenantSlug={tenantSlug} GET /auth/bootstrap/worlds/{world}/realms/{realm}/characters?connectScopeId={scope} POST /auth/connect-token { connectScopeId=cs_demo_production_v17 } GET /ws/game/** with the Firemud-Connect-Token cookie set by the previous response @@ -143,7 +143,7 @@ Target-state example first-time public production join (explicit `JOIN`/`Join & ```text POST /auth/player-bootstrap { accountIdentifier=player@example.com, secret= } GET /auth/bootstrap/worlds -GET /auth/bootstrap/worlds/emberfall/realms +GET /auth/bootstrap/worlds/emberfall/realms?tenantSlug=emberfall-studio POST /auth/bootstrap/join { connectScopeId=cs_emberfall_production_v1, requestId=req-join-1 } GET /auth/bootstrap/worlds/emberfall/realms/production/characters?connectScopeId=cs_emberfall_production_v1 POST /auth/bootstrap/worlds/emberfall/realms/production/characters { connectScopeId=cs_emberfall_production_v1, createCharacterRequestId=char-create-1, name=Mara, descriptorId=emberfall-human-fighter, descriptorVersion=17 } 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 d4e6960bbe..67eb8aee7d 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,31 +6,53 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +The canonical Account cutover currently authenticates LOGIN but direct backend PLAY fails exactly `ERROR ENTITLEMENT_UNAVAILABLE`; LOOK and successful public admission remain unproved. The [temporary CI exception](#temporary-canonical-play-transition-exception) accepts only that classified failure after held-admission qualification and authenticated cleanup for labeled nonproduction cutover PR merge gating. It does not establish runtime success or permit image publication. Remove it with successful fresh-image backend LOGIN/PLAY/LOOK proof after repairing the Account entitlement cutover. + Account initial/current/final creation owners, explicit initial billing-owner consent, private Game Design create/close receivers, and original-bound dispatch/recovery are locally composed and unregistered. Focused receiving proof passes, while physical cross-owner qualification, protected Redis/source custody and public/default registration remain incomplete; proof limits are recorded below. -### Local source-foundation preparation +### Temporary canonical PLAY transition exception + +The explicitly approved nonproduction canonical-cutover scope has a [bounded Smoke Gate diagnostic exception](../../architecture/system-architecture-cicd.md#pull-request-runtime-and-preview-chain), gated by the `canonical-play-transition` label and fresh evidence for the exact current PR tuple. The label does not authorize expanding that approved scope. The observed failure is successful backend LOGIN followed by exact direct-backend PLAY `ERROR ENTITLEMENT_UNAVAILABLE`, alone or with `Gameplay entitlement is temporarily unavailable. Retry PLAY shortly.` Held-admission denial qualification and authenticated cleanup pass, while LOOK and successful public admission remain unproved. The probe retains its failed Actions-native outcome and exact classified error. Runtime CI and Smoke Gate may pass under the bounded exception after successful authenticated cleanup; their summaries explicitly report that runtime qualification is absent. Image export, upload, typed publication handoff and trusted publication remain blocked for an exception attempt. Repair the canonical Account PLAYER_ADMISSION receiving chain and its Game Session PLAY consumer, then obtain successful fresh-image LOGIN → PLAY → LOOK before removing the exception and resuming trusted branch-image promotion. The integrated stack still leaves the canonical receiver unregistered and numeric PLAY entitlement reads denied; merely registering that receiver or restoring numeric subscription reads does not complete this obligation. This is nonproduction merge-gate accommodation, not activation authority. + +### Direct-text scope and JOIN identifier cutover + +The canonical Account boundary requires non-nil UUID tenant and game-instance identifiers. The held Game Session scope target now takes those UUIDs from `CanonicalPlayableTarget`, and its Account client validates the same canonical shape. JOIN correlation retains exact tenant equality. The numeric transport session identifier remains an independent, bounded positive-long coordinate: its original bytes, including leading zeros, are preserved through scope issuance and JOIN rather than replaced by the proxy connection UUID. + +Selected client-wire and Account receiver tests exercise these contracts separately, including malformed identifiers and mismatches. They are not an actual paired Game Session-to-Account RPC or deployed composition proof. The lobby remains unregistered; source custody, genuine cross-service scope/JOIN qualification and public admission remain unfinished. The observed backend PLAY `ENTITLEMENT_UNAVAILABLE` is a separate recorded failure. The temporary CI exception supplies neither successful JOIN/PLAY proof nor runtime activation. + +This is an intentionally breaking preproduction format cutover of the manually composed, currently unregistered lobby. No production rollback or migration compatibility is claimed. Numeric-era retained scope/JOIN bytes are not supported by the canonical UUID decoder; the existing SQL retention and exact-original identity guards remain unchanged. Repository inspection establishes no runtime registration and supplies no inventory of deployed rows. Existing-data verification belongs to future runtime wiring or activation, not a new merge gate or slicing requirement for this PR: before reusing any database populated by an earlier manual composition, establish whether numeric-era companion evidence exists. If it does, preserve that evidence and resolve its retention and recovery requirements before invoking the new owner against it; neither this cutover nor the temporary CI exception authorizes deletion, identity rewriting or retention bypass. Fresh component fixtures do not prove historical compatibility. + +### Canonical receiving capability boundaries -The local reconstruction based on `6b86f46f3fd0a76729b27f99b1e573bbac649838` carries selected source from #3389, #3390 and #3403 without their subscription-schema retirement or canonical public-facade cutover. The existing numeric subscription schema, reader, public facade and demo seeder remain unchanged. The only retained [`AccountServiceImpl`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java) change makes its independent JOIN transactions explicitly writable and `SERIALIZABLE`; this is local transaction hardening, not completion of the canonical distributed commit gate. Existing runtime behavior remains implementation drift rather than the target contract. +The Account source/transport foundation contains unregistered TENANT_OPERATION and PLAYER_ADMISSION owners, transports and controlled proof, Entity persisted-actor discovery, and policy-aware Game Session discovery. These do not replace live PLAY authority. The public receiving boundary contains canonical UUID schema retirement, the public facade/JOIN cutover, the schema/retention foundation and focused owner units. Provider-write execution, expanded physical proof and private FRESH/World preparation remain separate receiving obligations. A functioning canonical PLAY replacement remains unqualified; no caller custody, runtime registration, admission or activation is established by these source boundaries. -The #3389 source includes the private [`TENANT_OPERATION` proto](../../../protos/account/v1/tenant_operation_entitlement_read.proto), [strict common evidence codec](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementGrpcCodec.java), [Account source owner](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwner.java), [workload guard](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountTenantOperationEntitlementWorkloadGuard.java), [gRPC receiver](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantOperationEntitlementGrpcService.java), and [World client](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/AccountTenantOperationEntitlementClient.java). They prepare an explicit paid-or-DEMO eligibility read for the exact same-namespace World workload without source fallback, capacity commitment or player admission. They remain manually composed and unregistered; the paid branch still depends on the missing canonical subscription schema. The [controlled mTLS transport test source](../../../services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/client/AccountTenantOperationEntitlementClientMtlsTest.java) uses a controlled Account source owner and does not establish physical paid entitlement authority. +### Controlled player-admission transport composition -Held hosting sources here include the [lifecycle repository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java) and [same-owner terminal-resolution composition](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionService.java), with their focused unit sources. Retained dispatch/readback and fresh Account primary-authentication guards do not enable `CreateSubscription`, a provider worker, cancellation recovery, or a production billing route. Their required canonical intent, provisioning, lifecycle, dispatch and terminal-resolution storage is not installed in this candidate; the dependent physical billing/retention proofs are not carried as candidate qualification. +The prepared `controlledOwnerReceiverAndGameSessionClientComposeWithoutGrantingAdmission` case in [AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java) connects the actual Account PostgreSQL entitlement owner and unregistered mTLS receiver to the actual Game Session client. It checks both absent and joined membership, unchanged membership count, exact canonical response bytes, credential exclusion and refusal after the custody callback becomes false. LOGIN issuance/currentness and protected Game Session/World target inputs remain explicit controlled doubles; this does not establish genuine custody, a complete source chain, admission or production registration. Local compilation, enabled integration static analysis, Java formatting, Markdown and link checks pass, but all four PostgreSQL cases were skipped because Docker is unavailable. Physical execution remains outstanding. Required full-stack smoke on `89ae1be` / `e8fa889` still fails at the intentionally denied numeric entitlement endpoint; this test preparation does not replace that evidence or change the default-off runtime. -Initial provider creation is carried by [#3390](https://github.com/benhook1013/FireMUD/pull/3390), alongside its canonical storage and dispatch physical proof. The [Stripe provisioner](https://github.com/benhook1013/FireMUD/blob/d327e67c51637592637b6a349e59aa74aaf74f55/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisioner.java), [provisioning composition](https://github.com/benhook1013/FireMUD/blob/d327e67c51637592637b6a349e59aa74aaf74f55/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningService.java) and both focused unit suites are absent from this front boundary and preserved in that receiver. The paid first-invoice confirmation finding remains open there: `default_incomplete` creation and subscription polling do not complete payment, and controlled active-subscription inputs are not paid-checkout proof. Account/provider-hosted checkout completion after confirmed provider linkage and its proof remain required under [ADR 0044](../../architecture/decisions/adr-0044-account-owned-payment-instruments-with-explicit-subscription-binding.md) and [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md). This ownership transfer enables no provider worker, runtime registration, automatic charging or activation. +A further prepared [committed-LOGIN composition](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlayerAdmissionCommittedLoginCompositionIntegrationTest.java) replaces the LOGIN caller/currentness doubles with real committed issuance, response recovery, signature/profile verification and current Account owner reads. It uses a current persisted connect scope and physical Redis/PostgreSQL fixtures before calling the same unregistered mTLS receiver and Game Session consumer. Test signing custody, initial response delivery and protected published Game Session/World inputs remain controlled. The additional case also refuses a real Account token-fence revocation despite retained signature bytes and local custody. Compilation, enabled integration Checkstyle/SpotBugs, formatting and documentation checks pass. All five selected PostgreSQL cases, including this additional case, are skipped locally because Docker is unavailable; physical execution remains pending. No default PLAY route or activation is enabled. -The #3390 source adds the unregistered [Entity bootstrap-roster proto](../../../protos/entity-management/v1/account_bootstrap_roster_read.proto), [Entity persisted reader](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadService.java), [Account client](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/AccountBootstrapRosterReadClient.java), and [signed V2 scope reader](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalConnectScopeReader.java). Discovery is bounded to independently current public-production `SHARED`/`PRESEEDED_ONLY` targets and actual persisted eligible actors, including their stored level and valid empty rosters; it creates no selection, actor, retained roster, session or admission authority. Target reads surrounding Entity SQL detect source movement but supply no distributed hold. The scope reader compares the signed selector with retained Account evidence and requires an externally authenticated Account identity. Neither reader is consumed by the existing public facade. [`CanonicalJoinScopeV2`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/CanonicalJoinScopeV2.java) also redacts its bearer scope in `toString()`. +### Canonical billing and retention receiving -Focused unit and controlled physical proof sources are retained, including the [Entity PostgreSQL/mTLS roster tests](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterPostgresMtlsIntegrationTest.java), [Account roster-client mTLS tests](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/AccountBootstrapRosterReadClientMtlsTest.java), and [V2 scope-reader units](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalConnectScopeReaderTest.java). Before the provider-write source transfer, the expanded candidate passed 523 selected cases: 403 Account, eight Entity, 73 Game Session, fourteen Common Platform Core, 21 Common Security and four World client mTLS cases, with no failures, errors or skips. The first expanded run passed 524 cases plus affected integration/cross-service source compilation in 13m16s; removing the previously adjudicated duplicate membership test preserved its richer proof, and the final Account rerun plus affected enabled Checkstyle, SpotBugs, formatting and documentation checks passed in 9m26s. Those historical units and controlled transports do not qualify the reduced boundary or establish physical PostgreSQL or source-built runtime Smoke. After the transfer, affected production/unit/integration compilation, all 51 selected Account owner/handler/lifecycle/workload-guard cases, and enabled Account Checkstyle, SpotBugs and Java formatting pass. Physical integration execution is unrun locally; exact-comparison CI and positive Smoke remain required before this earlier boundary is ready. +This Account cutover retains the original numeric subscription heap as immutable, non-authorizing history (V1028), installs the canonical UUID subscription intent/provider-history, provisioning, first-dispatch, terminal-resolution and wallet-settlement schema (V1029/V1030/V1032/V1036/V1039), and moves retention/deletion reads to the dedicated historical-evidence repository. The old numeric entitlement reader and demo subscription seeder are removed together. Numeric runtime entitlement requests fail closed; no canonical entitlement is inferred from retained rows. -The V1028-and-later subscription UUID transition, immutable retained archive, numeric-authority retirement, production denial stubs, canonical public facade and live `PLAYER_ADMISSION` integration are outside this preparation. Schema retirement and a functioning canonical UUID admission replacement must arrive together at one downstream receiving boundary, preserving retained-data safety without a new numeric bridge or dual authority. No entitlement-receiver registration, production custody, canonical player admission, activation or physical proof success is claimed, and the capability ratings below remain unchanged. +The immediate successor owns the initial Stripe provider-write adapter and provisioning composition, the unclaimed-wallet settlement repository refinements, their focused unit and native PostgreSQL proof, and expanded World/stub receiving compositions. Those source and proof obligations are preserved in the original #3390 history and the complete successor tree. Their earlier source-specific proof is not proof of this reduced parent. Required physical migration, fresh-image runtime and exact-head CI qualification remain separate from local source compilation and focused units. -### Player-admission entitlement source preparation +Account deletion remains held. Its conservative billing-owner precondition inspects retained numeric history, not nonterminal canonical UUID subscriptions. No provider worker, billing mutation route, player admission or production activation is enabled by this split. -The local candidate now retains the [Account player-admission owner](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java), [exact workload guard](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountPlayerAdmissionEntitlementWorkloadGuard.java), [receiver](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcService.java), and [Game Session client](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClient.java), with closed protocol/codec and unit/mTLS proof sources. The [Account API contract](../../architecture/microservices/account-service/api-contracts.md#private-player-admission-entitlement-read) owns the wire and caller restrictions. These are manually composed, unregistered components; the default `PLAY` chain still uses the existing numeric entitlement call. No live LOGIN private-result custody, first-party/direct-text scope receiving chain, final admission or `PLAY` wiring is supplied. Policy-aware WORLDS discovery does not widen this read beyond public-production `SHARED`/`PRESEEDED_ONLY` targets. +### Canonical public Account facade receiving -Three Account physical proof sources are present: the [current-source PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java), [entitlement-owner PostgreSQL/mTLS suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java), and [committed-LOGIN composition](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlayerAdmissionCommittedLoginCompositionIntegrationTest.java). They prepare DEMO, absent/joined membership, exact scope and committed LOGIN checks on the existing schema; shared owner/context fixture and resource integration must preserve the existing constructors and numeric runtime dependencies. The owner suite controls caller/current issuance and protected Game Session/World inputs; the committed-LOGIN case replaces Account caller doubles with actual committed issuance and recovery while retaining controlled signing, initial delivery and protected targets. None establishes paid billing composition. The four-file World/shared positive composition cohort remains downstream because it requires the canonical UUID direct-text scope DTOs and producer; genuine LOGIN/World positive composition remains an explicit receiving obligation, not dropped scope. +The parent source restores the complete canonical V2 public facade, actual Account JOIN intent/member/pair/role/event/audit owners, V1037 diagnostics and V1038 existing-membership terminal guard, plus the distinct PLAYER_ADMISSION codec/Account receiver/Game Session client and persisted Account→Entity CHARS purpose. It retains actual same-row actor UUID/name/level, successful empty discovery only for supported targets, truthful admission flags, default-unavailable composition and all original positive cases. Contracts belong to [Account API](../../architecture/microservices/account-service/api-contracts.md#public-bootstrap-worlds-discovery) and [Entity API](../../architecture/microservices/entity-management-service/api-contracts.md#account-bootstrap-persisted-actor-discovery). -Historical #3390 proof324 (22 owner and five shared cases), proof335 (three Account PostgreSQL cases) and proof352 (34 client mTLS cases) remain donor-source results. Earlier locally skipped physical aggregates remain skipped; none of these results qualifies this expanded reconstruction. The selected unit/mTLS, affected source compilation and enabled static checks recorded in the foundation proof above retain their pre-transfer comparison; physical execution remains outstanding here. Production mTLS/custody and Redis qualification, complete authenticated target provenance, a World hold through later commitment, paid schema/provider composition, runtime registration and functional admission remain open; point-in-time evidence is not a capacity or admission decision. +Preserved source proof 310 passes 575 selected Account units; proof 318 passes 312 facade units and two actual HTTP→Entity compositions; proof 320 passes 42 App PostgreSQL cases; proof 321 passes 13 first-JOIN cases; proof 324 passes 22 PLAYER_ADMISSION owner cases plus five shared cases; and proof 335 passes three actual PLAYER_ADMISSION PostgreSQL cases. These are source-specific executions with controlled upstream/PKI limits. Actual receiving compilation 342 passes all affected production/unit/integration sources after carrying the complete transport closure. Receiving proofs 343/345 establish 793 unique selected unit passes after correcting one obsolete first-only generic proof assertion; proof 351 passes 169 selected physical PostgreSQL/HTTP/mTLS/composition cases across Account, Entity, Game Session and World without failures, errors or skips, including both canonical HTTP-to-Entity positives deferred from the foundation. Enabled affected static checks pass except CommonCore SpotBugsTest in proof 346, whose JVM SIGSEGV leaves that task held and the aggregate failed; existing Game Session main proof 198/200 holds remain. Remaining proof 347 static and documentation checks pass. These focused results do not establish complete service suites or runtime qualification. The explicit Game Session entitlement client also prepares a canonical direct-text lobby-scope input under its owning current-custody callback, preserving original LOGIN/transport/target/expiry bindings without a fabricated first-party context. Focused transport proof 352 passes all 34 mTLS client cases (31 new direct-text invocations), enabled Game Session main/test Checkstyle, test SpotBugs, formatting and documentation; held main SpotBugs is not rerun. Published #3390 carries this public source; the terminal-cancellation finding is independently qualified by the coupled composition 356 in #3389. Private/ISOLATED/PLAYER_CREATED/AUTO positives, distributed currentness protection, actual canonical runtime cutover, genuine installed delivery/private FRESH/CLOSED aggregation and registration/issuer/custody/activation holds remain unfinished. + +Receiving migration-order proof allocates the child-only JOIN diagnostics and existing-membership terminal guard as V1037/V1038 after the actual parent frontier V1036, retaining their SQL bytes and every applied-parent artifact. Proof 430 supplies 28 passing canonical scope, first-JOIN and paid-JOIN PostgreSQL cases; its new upgrade case initially failed an incorrect shared-Saga expectation. Corrected proof 432 passes the actual parent-history upgrade with unchanged canonical scope/PENDING-intent JSON and row `xmin`, complete prior Flyway rows/checksums, ordered installation of both scripts, a real attempt-diagnostics update and exact SQLSTATE `23514` immutable-caller refusal. Version checking 428 and Account generation 429 pass; proof 432 also passes enabled integration analysis, formatting and documentation. The failed proof 430 and no-matching-selector proof 431 results remain retained rather than counted as successful aggregate proof. Account has no Common Saga runtime dependency at this boundary; declaring an optional classpath location does not supply those migration resources. + +The original #3390 validation run `41692144820` exposed an obsolete entitlement-call expectation and an Entity test-fixture SpotBugs warning. Every discovery call joins all independent tenant reads, including failed calls, so the three-call fixture now expects three reads of each tenant. The fixture's generated protobuf request is immutable; narrow accessor/constructor annotations follow the existing fixture convention without changing detector configuration. Receiving Proof 443 passes all 312 Account facade cases, the physical allocate→later-prepare→selection regression on the carried V1059 schema, enabled Account test and Entity fixture analysis, formatting and documentation (1m38). Both original CI failures remain retained; replacement comparison CI is still required. + +Foundation draft #3389 at `fec647a5` fails its fresh source-built runtime at PLAY with `ENTITLEMENT_UNAVAILABLE`; authenticated teardown completes with no remaining project resources. The later exact `58a8a10` runtime-image run `41690067116` likewise fails PLAY because Account canonical tenant entitlement authority is unavailable; authenticated cleanup succeeds. Neither metadata-gate success nor local component proof replaces this failed runtime evidence. The denied legacy numeric endpoint is intentional, but a qualified canonical runtime replacement is still required. Remote Validation also exposed a UUID/text readback assertion and an enabled-ALWAYS trigger expectation. Its obsolete numeric-subscription HTTP-to-Entity CHARS fixture belongs to the complete canonical public successor, where both replacement positive compositions pass; the foundation does not claim that positive boundary. These failures remain recorded, with current-head CI and runtime qualification outstanding. + +The complete public WORLDS collection now accepts both canonical `SHARED` creation policies, `PRESEEDED_ONLY` and `PLAYER_CREATED`, without filtering a represented world or changing the one-public-target-per-tenant authority. Unknown/private policies, duplicate identities, changed collections and expired entitlement still refuse. The separate policy-specific source, roster and admission methods keep their own restrictions. This closes the accepted CLI1 discovery observation routed from #3383 in the existing public facade receiver. Proof379 passes all 341 focused cases with zero failures/errors/skips: the full 296-case Common Security suite, 33 Game Session collection/source cases and 12 Account WORLDS cases, including complete mixed-policy readback and deterministic entitlement filtering. Enabled affected analysis, formatting and docs pass. These are controlled component proofs, not successful public runtime or registration/custody qualification. ### Lifecycle-bound private realm-grant source preparation @@ -40,13 +62,15 @@ Bounded source/storage proof passes: 24 shared codec/mutation unit cases and 10 ### Public bootstrap WORLDS source preparation +The browser selector correction preserves tenant-scoped world-slug reuse end to end: WORLDS carries `tenantSlug`, REALMS requires it with `worldSlug`, and the facade uses the existing qualified selector owner. The player-experience smoke caller requires `PLAYER_EXPERIENCE_TENANT_SLUG` rather than inferring a global world. Focused proof passes all 414 selected Account controller, facade, WORLDS, REALMS and containment cases with zero failures, errors or skips using an explicit cached Mockito startup agent because this local JDK cannot self-attach. Smoke-runner and architecture contracts, local links and Markdown checks pass. Account integration-source compilation and enabled Java formatting also pass; registered-runtime and physical database qualifications below are unchanged. See the [Account selector contract](../../architecture/microservices/account-service/api-contracts.md#public-bootstrap-worlds-discovery). + Paid discovery activation requires a composed durable webhook-driven or periodic lifecycle-reconciliation producer that commits a new Account receipt for each verified provider renewal period. The local `reconcile` entry point is implemented, but no such automatic producer is registered or qualified here. A renewal changes provider period facts and expires the prior positive bound; the current read intentionally refuses rather than extending or reinterpreting that immutable receipt. Until the new receipt is committed, a visible paid tenant can therefore make the complete WORLDS collection return `ENTITLEMENT_UNAVAILABLE`. The provider-reconciliation and registration prerequisite remains open under [Subscription Management](../../architecture/microservices/account-service/subscription-management.md#runtime-entitlement-contract) and [Stripe Integration](../../architecture/microservices/account-service/stripe-integration.md#subscriptions-and-hosting-plans); component read proof does not qualify paid discovery activation. -The current-read source also supports a freshly confirmed terminal negative projection for the existing `CANCELED` marker after its retained observation deadline, under [Subscription Management](../../architecture/microservices/account-service/subscription-management.md#runtime-entitlement-contract). Original receipt/source bytes and fresh exact provider facts remain required; this source change needs delayed provider/effective-cancellation physical qualification at the canonical schema receiver before claiming discovery recovery. +The current-read source also supports a freshly confirmed terminal negative projection for the existing `CANCELED` marker after its retained observation deadline, under [Subscription Management](../../architecture/microservices/account-service/subscription-management.md#runtime-entitlement-contract). Original receipt/source bytes and fresh exact provider facts remain required. Proof396 passes 46 front policy/repository/service and Game Session discovery cases with enabled affected analysis, formatting and documentation checks. Proof397 passes 20 discovery/entitlement units and 27 physical lifecycle/terminal cases, including delayed provider-confirmed and effective-cancellation negative reads, stale/changed provider refusal and unchanged receipt/authority rows including xmin. The bounded shared-cause check covers every implemented hosting status and both paid/DEMO discovery branches: proof399 passes 37 physical lifecycle, terminal-recovery and DEMO cases, including delayed suspended reads and real grace/period cutoffs; proof400 passes four tenant-operation owner cases with a fresh SDK evaluation after the original observation window and stable committed snapshot identity. All have zero failures, errors or skips and enabled affected checks. TENANT_OPERATION remains an as-of, non-admitting source observation; this does not add currentness protection, capacity authority or default registration. -The local hosting lifecycle policy and receipt producer separate the committed provider/policy fact bound from each fresh SDK read's observation deadline under [Subscription Management](../../architecture/microservices/account-service/subscription-management.md#runtime-entitlement-contract). Receipt bytes and SQL readback retain the same committed bound; current read results still expire at their own observation deadline without a new lifecycle event. This correction requires focused delayed-read PostgreSQL qualification in the canonical subscription receiver; this source slice does not contain its V1028–V1032 schema foundation. Existing receipts remain immutable, and current paid discovery/runtime support is not inferred from these source changes. +The local hosting lifecycle policy and receipt producer separate the committed provider/policy fact bound from each fresh SDK read's observation deadline under [Subscription Management](../../architecture/microservices/account-service/subscription-management.md#runtime-entitlement-contract). Receipt bytes and SQL readback retain the same committed bound; current read results still expire at their own observation deadline without a new lifecycle event. Proof392 passes all 26 selected physical cases: 21 lifecycle cases and five genuine terminal-recovery compositions, with no failures, errors or skips, plus enabled integration analysis, formatting and documentation checks. The delayed active/trialing reads use new real SDK observations after the original observation window, retain the original receipt and authority rows including xmin, and append no events; stale reads, changed facts, actual period and recovery boundaries still refuse. Proof390 separately passes 32 front policy/repository/service and Game Session published-read cases with enabled affected analysis and documentation checks. Proof389 failed compilation and proof391 failed a public-versus-private error-message assertion; both are retained and corrected. The front carrier does not contain the V1028–V1032 schema foundation and takes this physical qualification from the canonical receiver. Existing receipts remain immutable, and current paid discovery/runtime support is not inferred from these source changes. -[`AccountPublicBootstrapWorldsOwner`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwner.java) composes [`AccountPlayerBootstrapCallerVerifier`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerBootstrapCallerVerifier.java), [`CanonicalGameplayAdmissionDecisionReadClient`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/CanonicalGameplayAdmissionDecisionReadClient.java), and [`AccountPublicBootstrapEntitlementOwner`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapEntitlementOwner.java). The caller is checked before source work and revalidated before return. Account requests the complete public target collection twice, evaluates current entitlement once per canonical tenant, rejects collection changes and duplicate or ambiguous target identities, and checks each observation deadline before returning. It emits only `gameplayAvailable` targets, ordered by world slug; `allowPublicJoin` does not filter discovery. Any required source failure, changed source, or expired evaluation fails the whole call without a partial list. +[`AccountPublicBootstrapWorldsOwner`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwner.java) composes [`AccountPlayerBootstrapCallerVerifier`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerBootstrapCallerVerifier.java), [`CanonicalGameplayAdmissionDecisionReadClient`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/CanonicalGameplayAdmissionDecisionReadClient.java), and [`AccountPublicBootstrapEntitlementOwner`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapEntitlementOwner.java). The caller is checked before source work and revalidated before return. Account requests the complete public target collection twice, evaluates current entitlement once per canonical tenant, rejects collection changes and duplicate or ambiguous target identities, and checks each observation deadline before returning. It emits only `gameplayAvailable` targets, ordered by world slug then tenant slug; `allowPublicJoin` does not filter discovery. Any required source failure, changed source, or expired evaluation fails the whole call without a partial list. Independent tenant entitlement evaluations now overlap, with shared resource bounds across concurrent requests and owner instances under the [Account API contract](../../architecture/microservices/account-service/api-contracts.md#public-bootstrap-worlds-discovery). The implementation preserves transaction isolation, exact tenant identity and original observation expiry. Production pool sizing, throughput and capacity remain unqualified. @@ -56,9 +80,9 @@ The current SDK transport uses socket timeouts while consuming the complete resp The source owner refuses ambient Account SQL and requires a workload-only `SessionContext` for its Game Session call; it rejects authenticated caller and internal-service contexts. Facade integration must satisfy that guard without clearing or bypassing caller security context, and is not established by this unregistered composition. The Game Session read is the exact same-namespace Account mTLS source and now prepares the complete visible public-production `SHARED` collection for both `PRESEEDED_ONLY` and `PLAYER_CREATED`. It preserves complete canonical identity/namespace checks, committed owner/no-abort evidence, tenant UUID/slug and realm uniqueness, bounded closed frames and two complete reads with whole-set equality. Strict target selection, roster and admission remain `PRESEEDED_ONLY`. The owning contract is [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md#public-production-bootstrap-target-collection-read). Focused mixed-policy proof sources are `AccountPublicBootstrapWorldsOwnerTest.mixedPublicCreationPoliciesBothParticipateInCompleteWorldDiscovery` and `CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.discoveryReturnsCompletePlayerCreatedAndMixedPolicyCollectionsOnBothReads`; `CanonicalGameplayAdmissionDecisionReadGrpcCodecTest.discoveryCarriesBothSupportedPublicCreationPoliciesWithoutChangingTargetEvidence` separately covers each supported policy. The CLI12 focused receiving run passes these named cases among 194 selected cases (102 Account, 74 Game Session and 18 Common Security), with no failures, errors or skips; the historical 523-case foundation run is not attributed as their proof. Neither owner supplies a fresh World lifecycle read or hold, and this source does not issue a scope, perform JOIN, or admit gameplay. -Earlier component proof is bounded by the [Account discovery-owner tests](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwnerTest.java), [entitlement-owner tests](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapEntitlementOwnerTest.java), [Account target-client tests](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/CanonicalGameplayAdmissionDecisionReadClientTest.java), [Game Session collection-read tests](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java), and [workload-guard tests](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/CanonicalGameplayAdmissionDecisionReadWorkloadGuardTest.java). The prior affected regression run passed 76 selected Account and Game Session cases without failures, errors or skips, plus enabled affected static analysis, formatting and documentation checks. It covers concurrent requests across separate owners, unchanged target projection and sanitized dependency failures, not the local mixed-policy addition. Retained physical proof passed all 10 [Account DEMO discovery and scope PostgreSQL cases](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapDemoWorldsOwnerPostgresIntegrationTest.java), including deterministic filtering, source-head drift, expiry refusal and immutable rows. Earlier broader unit, loopback-mTLS and final-admission composition runs overlap this coverage and are not additive or a current whole-system qualification. The PostgreSQL discovery tests use controlled Game Session responses; client mTLS tests use a controlled Game Session server, and final-admission composition uses a controlled World capture. These proofs do not establish the complete authenticated cross-owner source chain, deployment custody, paid discovery activation or production capacity. +Earlier component proof is bounded by the [Account discovery-owner tests](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwnerTest.java), [entitlement-owner tests](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapEntitlementOwnerTest.java), [Account target-client tests](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/CanonicalGameplayAdmissionDecisionReadClientTest.java), [Game Session collection-read tests](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java), and [workload-guard tests](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/CanonicalGameplayAdmissionDecisionReadWorkloadGuardTest.java). The earlier affected regression run passed 76 selected Account and Game Session cases without failures, errors or skips, plus enabled affected static analysis, formatting and documentation checks. It covers concurrent requests across separate owners, unchanged target projection and sanitized dependency failures. Retained physical proof passed all 10 [Account DEMO discovery and scope PostgreSQL cases](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapDemoWorldsOwnerPostgresIntegrationTest.java), including deterministic filtering, source-head drift, expiry refusal and immutable rows. Earlier broader unit, loopback-mTLS and final-admission composition runs overlap this coverage and are not additive or a current whole-system qualification. The PostgreSQL discovery tests use controlled Game Session responses; client mTLS tests use a controlled Game Session server, and final-admission composition uses a controlled World capture. These proofs do not establish the complete authenticated cross-owner source chain, deployment custody, paid discovery activation or production capacity. -The existing [`AccountServiceImpl.listBootstrapWorlds`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java) and its positive tests remain on the legacy path in this source slice. The local [`AccountCanonicalPublicRealmScopeOwner`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwner.java) separately issues and retains signed canonical UUID V2 public selector scopes; its focused and pre-V1028 PostgreSQL proof remains component-only. That scope owner and the newly retained [V2 reader](#local-source-foundation-preparation) are not consumed by the existing facade. Unregistered hosting observer, intent, lifecycle and plan implementations and focused units are present; they do not establish paid discovery against this source slice’s legacy schema. Subscription schema retirement and functioning canonical UUID facade/admission consumers remain one downstream receiving boundary, including the V1028 retained archive, V1029 canonical table and dependent lifecycle/dispatch/terminal-resolution storage. No numeric fallback or second subscription table is introduced. Private `REALMS`, registered browser/direct scope consumption, live [player-admission entitlement integration](#player-admission-entitlement-source-preparation), JOIN consumer migration, default registration and gameplay admission remain gaps. +The [canonical public receiving](#canonical-public-account-facade-receiving) composes these sources through the existing facade. Absent composition remains unavailable; retained numeric billing history supplies no fallback. Detailed current proof and gaps remain at that receiving owner. The local [`AccountCanonicalPublicRealmScopeOwner`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwner.java) adds an actual public selector-scope producer over the same complete target and current Account source owners. It preserves genuine membership absence without enrolling a pair, returns current ACTIVE/INACTIVE facts without treating closed enrollment as loss of public visibility, and persists signed canonical UUID V2 scope preimages through the existing Account scope repository. Focused signing and orchestration cases use real local signing and bootstrap verification with controlled source and transaction inputs. The retained pre-V1028 PostgreSQL scope cases preserve exact signed UUID/V2 hash, digest and provenance bytes without membership, pair, JOIN or event writes, refuse a real DEMO source-head change, and roll back a real PostgreSQL insert refusal. No facade/default registration, private lifecycle completion, JOIN or admission is established. Current-head CI remains required after source changes. @@ -502,7 +526,7 @@ Account's persisted UUID now backs registration REST/gRPC output and the Account Internal Account-carrier typing is prepared in Game Session, while current producers, JWT claims/parsers, and numeric-only collaborators remain unchanged. This does not activate canonical Account UUID authentication or Entity roster/entry behavior and does not backfill historical command UUIDs; canonical identity/namespace targets remain [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md), [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md), and [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md). Focused unit proof covers fail-closed first-party retained-context lookup, unreadable presence lookup without index pruning, and bounded pre-mutation rejection of unreadable or wrong-type presence values for removal, AFK/activity updates, and registration. `RedisSessionContextService` mutation reads still expose raw `SerializationException`; mocked tests show unreadable session-alias reads abort before writes/deletes, but mixed-binary behavior, same-session-ID reauthentication/recovery, live Redis/runtime, and fresh-image proof remain unproved. #2898 is not fixed by this preparation. -Implemented seams currently span Account, Common Security, TCP Proxy, Gateway, Game Session, and the gameplay runtime services, including account-first tenantless bootstrap, global-only registration, the Account-local explicit public-production JOIN writer and durable audit outbox/producer retry path, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. Logging & Admin receipt persistence/readback is separate #2848 work and is not included in this Account core. The Account `POST /auth/bootstrap/join` controller/operation exists locally, while the current Gateway guard still blocks external exposure; Game Session text JOIN dispatch remains with #2898 and direct text-client end-to-end proof is unclaimed. Current `PLAY` and connect-token issuance remain partial; Account-owned membership and realm-grant authorities remain separately modeled and read. JOIN's durable `PENDING`/unknown-database-outcome recovery seam remains unresolved under the Overseer decision and is owned by #2848; PostgreSQL runtime proof is not claimed. The membership-authority-generation reread, namespace-aware binding enforcement, resume-window enforcement, exactly-one-prompt proof, and first-party post-logout replay suppression remain incomplete. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift against the namespace-aware takeover contract. The current TCP Proxy keeps bounded ordered input in connection-local memory while an edge bridge is rebindable; that buffer is delivered only on the same retained connection and is never durable replay of input, bytes, or frames. Account lifecycle, Stripe hosting-billing follow-through, entitlement enforcement, safety restriction/appeal workflows, generic prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal implemented paths; manual end-to-end QA and broader continuity/validation follow-ups remain. Canonical target behavior is linked below rather than restated in this tracker. +Implemented seams currently span Account, Common Security, TCP Proxy, Gateway, Game Session, and the gameplay runtime services, including account-first tenantless bootstrap, global-only registration, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. The Account-local explicit public-production JOIN writer and durable audit outbox/producer retry components remain prepared source without default production composition. Logging & Admin receipt persistence/readback is separate #2848 work and is not included in this Account core. The Account `POST /auth/bootstrap/join` route exists locally. Its default receiving composition returns `AUTH_UNAVAILABLE` before bootstrap/scope, target, entitlement, or membership reads or mutation; manually configured JOIN proceeds into canonical validation and authority reads under the [Account API contract](../../architecture/microservices/account-service/api-contracts.md#rest-apis). The Gateway guard still blocks external exposure. See [canonical billing and retention receiving](#canonical-billing-and-retention-receiving) for current status and retained obligations. Game Session text JOIN dispatch remains with #2898 and direct text-client end-to-end proof is unclaimed. Current `PLAY` and connect-token issuance remain partial; Account-owned membership and realm-grant authorities remain separately modeled and read. JOIN's durable `PENDING`/unknown-database-outcome recovery seam remains unresolved under the Overseer decision and is owned by #2848; PostgreSQL runtime proof is not claimed. The membership-authority-generation reread, namespace-aware binding enforcement, resume-window enforcement, exactly-one-prompt proof, and first-party post-logout replay suppression remain incomplete. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift against the namespace-aware takeover contract. The current TCP Proxy keeps bounded ordered input in connection-local memory while an edge bridge is rebindable; that buffer is delivered only on the same retained connection and is never durable replay of input, bytes, or frames. Account lifecycle, Stripe hosting-billing follow-through, entitlement enforcement, safety restriction/appeal workflows, generic prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal implemented paths; manual end-to-end QA and broader continuity/validation follow-ups remain. Canonical target behavior is linked below rather than restated in this tracker. Official-hosted creator-content acceptance remains an unregistered target workflow. Source-only persistence now includes Creator Party and hosted-terms/environment-binding evidence plus V98 disclosure handoff and source-evidence tables; these relations do not supply external environment observation, authenticated publication, a legal authority verifier, dispatch, a consumer, registry/runtime binding, creator UI, or downstream write-gate proof. The fixed server environment-evidence adapter exists but remains deliberately unregistered and supplies no genuine input delivery. Its target authority remains under [ADR 0180](../../architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and [ADR 0181](../../architecture/decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md), outside player-admission and session authority. Future managed creator commerce remains outside player access and session authority; its canonical boundary is [ADR 0179](../../architecture/decisions/adr-0179-firemud-managed-creator-commerce-boundary.md); no marketplace or purchase-entitlement implementation is present. @@ -536,22 +560,22 @@ The local receiving preparation uses the dedicated Gateway RS256 non-JWT envelop [FirstPartyConnectContextService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java) joins that verified context to the current [canonical route owner read](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java). Logical UUID authority stays separate from owner-supplied private storage handles. Retention keeps the original compact envelope and resolved owner snapshot, re-verifies expiry and current owner evidence on reads, and rejects old partial selector fragments, corruption, or unavailable authority. Main's latest focused evidence reports 12 controlled-key envelope tests, 199 Game Session unit cases after two narrow fixes, 184 Account unit cases after the fixture mock-history correction, 15 Gateway unit cases, and six physical Redis cases. The local socket-ownership correction requests transport close after send failure and performs disconnect cleanup only when the close callback atomically removes the exact registered transport. Forty-seven focused ownership unit cases and affected static/format gates pass. A fresh PostgreSQL-backed WebSocket class run passes 19 of 20 cases after default-off route-reader wiring is repaired; its remaining fixture-room assertion is corrected and that case passes in a separate focused run. The original startup and assertion failures and earlier all-skipped result remain retained; no genuine first-party admission authority is claimed. See [Session Behavior](../../architecture/system-architecture-session-behavior.md#session-types-and-lifetimes). These partial results do not establish a complete consumer gate or packaged runtime. -Account connect-token issuance retains its existing bootstrap and scope authentication checks, then denies before cached-success replay, token minting, or session mutation while the canonical producer is unavailable. Gateway removes the legacy HMAC context mint and replay fallback; first-party cookie admission and public gameplay readiness remain unavailable. The separate trusted TCP Proxy listener path retains its existing boundary. First-party bare `LOGIN` and `PLAY` preserve the complete context and deny before legacy Account, Entity, or binding effects pending the genuine authority, lease, and finalization consumers. This entire source batch is local preparation; the `AA-2.1` capability remains partial and no new publication boundary or playable completion is claimed. +With canonical scope consumers absent from the default composition, Account connect-token issuance returns `AUTH_UNAVAILABLE` before bootstrap/scope validation. Manually configured consumers permit bootstrap/scope validation, but issuance remains held before cached-success replay, token minting, or session mutation; see the [Account API contract](../../architecture/microservices/account-service/api-contracts.md#rest-apis). Gateway removes the legacy HMAC context mint and replay fallback; first-party cookie admission and public gameplay readiness remain unavailable. The separate trusted TCP Proxy listener path retains its existing boundary. First-party bare `LOGIN` and `PLAY` preserve the complete context and deny before legacy Account, Entity, or binding effects pending the genuine authority, lease, and finalization consumers. This entire source batch is local preparation; the `AA-2.1` capability remains partial and no new publication boundary or playable completion is claimed. ## Capability Status | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| `AA-1.1` Account and profile identity | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java); [AccountMapper.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/mapper/AccountMapper.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [ProfileController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java); [AccountGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java); [RuntimeAccountIdentityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java); [AccountRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [openapi.yaml](../../../services/account-service/src/main/resources/openapi.yaml); [AccountIdentityProvenance.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java); [V1__init.sql](../../../services/account-service/src/main/resources/db/migration/V1__init.sql); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V29__account_identity_uuid_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V29__account_identity_uuid_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [RuntimeAccountIdentityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [ProfileControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Account V29 and `AccountRepository` persist/read back the non-nil Account UUID, recognized provenance, and unchanged numeric source-row identity required by ADR 0020. Registration REST/gRPC output and Account fields in the existing local exports now use that UUID; new registration audit records carry the same value, and the reverse DTO mapper is removed. `AccountDto` mapping rejects missing or contradictory UUID/provenance/source-row evidence. The historical initial unit/controller/gRPC suites executed 238 tests (174 AccountServiceImpl, 15 AccountController, 2 production-profile route, and 47 gRPC) with no failures, errors, or skips; the 5 PostgreSQL-backed Account application integration cases compiled but skipped when Docker was unavailable. Retained-row migration proof remains available but local PostgreSQL cases skip when Docker is disabled. Registration still creates global Account state plus its platform audit outbox row only, with no profile or tenant membership; caller-supplied tenant input is not authority. Previously merged bootstrap credential and connect-scope artifacts use the Account UUID. Ordinary password/OTP results, JWT subjects and profile/export identity fields also use that UUID in this receiving source; tenant IDs remain numeric and full portable export is not implemented. The [ordinary UUID receiving record](#ordinary-uuid-issuer-and-receiving) owns the current implementation and proof limits. Current profile GET/PUT routes enforce exact caller-account subject binding and current tenant membership; tenant-qualified routes and membership-authority-generation validation remain gaps. Credential and email-OTP gameplay authentication remain global Account-identity operations that do not select a tenant or require current membership. `RuntimeAccountIdentityGrpcService` implements the authenticated Account-owner UUID/provenance read; its 31 focused unit cases, integration-source compilation, and formatting/documentation checks do not prove PostgreSQL execution or a live mTLS handshake, and alone do not qualify the later UUID receiving source or production gameplay admission. Lifecycle-state retention remains tracked under AA-1.3. | -| `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountJoinOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java); [AccountConnectScopeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java); [ExpiredConnectScopeCleanupJob.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java); [AccountAuditOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java); [AccountCanonicalFirstJoinTerminalCoordinator.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java); [AccountMembershipAuthorityEventProducer.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountTenantAuthorityEventRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java); [AccountDemoTenantEntitlementRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java); [AccountTenantEntitlementOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java); [AccountActorStagingEligibilityService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityService.java); [AccountActorStagingEligibilityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcService.java); [AccountActorStagingEligibilityRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountActorStagingEligibilityRepository.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql); [V30__approved_legacy_tenant_associations.sql](../../../services/account-service/src/main/resources/db/migration/V30__approved_legacy_tenant_associations.sql); [V31__subscription_authority_generation.sql](../../../services/account-service/src/main/resources/db/migration/V31__subscription_authority_generation.sql); [V32__realm_grant_currentness.sql](../../../services/account-service/src/main/resources/db/migration/V32__realm_grant_currentness.sql); [V33__fresh_tenant_identity_associations.sql](../../../services/account-service/src/main/resources/db/migration/V33__fresh_tenant_identity_associations.sql); [V34__account_membership_pair_authority.sql](../../../services/account-service/src/main/resources/db/migration/V34__account_membership_pair_authority.sql); [V35__canonical_uuid_membership_identity.sql](../../../services/account-service/src/main/resources/db/migration/V35__canonical_uuid_membership_identity.sql); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V37__canonical_first_join_scope_and_intent.sql](../../../services/account-service/src/main/resources/db/migration/V37__canonical_first_join_scope_and_intent.sql); [V38__account_first_join_authority_outbox_and_roles.sql](../../../services/account-service/src/main/resources/db/migration/V38__account_first_join_authority_outbox_and_roles.sql); [V39__canonical_first_join_terminal_receipt.sql](../../../services/account-service/src/main/resources/db/migration/V39__canonical_first_join_terminal_receipt.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V53__account_protected_demo_entitlements.sql](../../../services/account-service/src/main/resources/db/migration/V53__account_protected_demo_entitlements.sql); [V73__account_tenant_authority_source_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql); [CanonicalGameplayAccountInitialBarrierInitializerRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierInitializerRepository.java); [CanonicalGameplayAccountInitialBarrierRedisOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwner.java); [V1047__canonical_initial_account_admission_barrier.sql](../../../services/game-session-service/src/main/resources/db/migration/V1047__canonical_initial_account_admission_barrier.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [ExpiredConnectScopeCleanupJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJobTest.java); [AccountAuditOutboxRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java); [AccountJoinDigestTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [AccountDemoTenantEntitlementPersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java); [AccountCanonicalFirstJoinEventIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); [AccountCanonicalFirstJoinTerminalCoordinatorTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java); [AccountMembershipAuthorityEventProducerCanonicalJoinTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountTenantAuthorityEventRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java); [AccountActorStagingEligibilityServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityServiceTest.java); [AccountActorStagingEligibilityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcServiceTest.java); [CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java); [CanonicalGameplayAccountInitialBarrierRedisScriptIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisScriptIntegrationTest.java); R849 partial execution, R855/R856 recovery, R867 and R902 focused execution have separate scopes and limits recorded above | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. `AccountTenantAuthorityEventRepository` appends the canonical tenant authority event during demo entitlement provisioning; `AccountMembershipAuthorityEventProducer` emits the first-JOIN membership event with its billing cutoff taken from that current tenant authority event, covered by [AccountCanonicalFirstJoinEventIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); no entitlement caller wires it, and current PostgreSQL proof remains pending because the integration source compiled but was unrun locally. Current connect-token issuance returns `AUTH_UNAVAILABLE` before replay-cache or fresh pointer/visibility/membership reads while the canonical producer is unavailable; target current-authority and postcondition revalidation remain unproved. Current explicit `JoinPublicProductionMembership` validates a server-issued scope and caller binding, re-reads Game Session routing/catalog/pointer evidence before the Account transaction, and binds a v1 digest to verified caller/scope inputs; it does not guarantee that the exact target/catalog/pointer remains valid through Account commit. The strict ADR 0025 commit gate remains incomplete, and no durable Game Session-owned target fence is implemented or proved; transaction duration or timing thresholds alone would not prove it. The subscription authority query's `FOR UPDATE` locks only the subscription row, not its joined billing-owner Account; JOIN also locks the caller Account and operation record. Terminal-operation replay performs remote scope/target/entitlement checks outside its lock-holding transaction. Pending JOINs continue to receive fresh remote reads, while the Account transaction retains atomic membership, operation-outcome, and audit-outbox persistence. Focused unit proof verifies terminal replay revalidation occurs after commit or rollback without rewriting the stored outcome; the PostgreSQL row-lock regression compiles but skips locally without Docker. PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Global-only registration no longer creates an admitting membership. Expired unreferenced connect-scope rows are swept under their existing expiry; V27's restrictive scope FK preserves every scope referenced by a PENDING or terminal JOIN and fences racing intent inserts. JOIN recovery/reconciliation after an unknown database commit outcome remains a separate #2848 gap under the Overseer decision; do not mark ADR 0025 complete. The Gateway continues to block public JOIN exposure, and Game Session text JOIN/Join & Play dispatch remains #2898. `AccountActorStagingEligibilityGrpcService` is a read-only internal eligibility check disabled by default; it does not establish that a realm is public or preseeded and grants no gameplay admission. Membership authority generation in runtime admission, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Current non-public discovery and supported text `PLAY` require admitting membership before the applicable realm grant; connect-token issuance fails closed before these checks and does not establish target grant validation. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). The unregistered INITIAL Account prerequisite preserves one original target and does not supply abandoned-target or account-wide fenced recovery, fresh Account authority, final admission or runtime activation; see the [readiness scope and proof](#canonical-new-admission-components). | +| `AA-1.1` Account and profile identity | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java); [AccountMapper.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/mapper/AccountMapper.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [ProfileController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java); [AccountGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java); [RuntimeAccountIdentityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java); [AccountRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [openapi.yaml](../../../services/account-service/src/main/resources/openapi.yaml); [AccountIdentityProvenance.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java); [V1__init.sql](../../../services/account-service/src/main/resources/db/migration/V1__init.sql); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V29__account_identity_uuid_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V29__account_identity_uuid_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [RuntimeAccountIdentityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [ProfileControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Account V29 and `AccountRepository` persist/read back the non-nil Account UUID, recognized provenance, and unchanged numeric source-row identity required by ADR 0020. Registration REST/gRPC output and Account fields in the existing local exports now use that UUID; new registration audit records carry the same value, and the reverse DTO mapper is removed. `AccountDto` mapping rejects missing or contradictory UUID/provenance/source-row evidence. The historical initial unit/controller/gRPC suites executed 238 tests (174 AccountServiceImpl, 15 AccountController, 2 production-profile route, and 47 gRPC) with no failures, errors, or skips; the 5 PostgreSQL-backed Account application integration cases compiled but skipped when Docker was unavailable. Retained-row migration proof remains available but local PostgreSQL cases skip when Docker is disabled. Registration still creates global Account state plus its platform audit outbox row only, with no profile or tenant membership; caller-supplied tenant input is not authority. Previously merged bootstrap credential and connect-scope artifacts use the Account UUID. Ordinary password/OTP results, JWT subjects and profile/export identity fields also use that UUID in this receiving source; profile and legacy runtime/export tenant IDs remain numeric, while public bootstrap, direct-text scope and JOIN results follow the [Account tenant identifier boundary](../../architecture/microservices/account-service/api-contracts.md#account-tenant-identifier-boundary); full portable export is not implemented. The [ordinary UUID receiving record](#ordinary-uuid-issuer-and-receiving) owns the current implementation and proof limits. Current profile GET/PUT routes enforce exact caller-account subject binding and current tenant membership; tenant-qualified routes and membership-authority-generation validation remain gaps. Credential and email-OTP gameplay authentication remain global Account-identity operations that do not select a tenant or require current membership. `RuntimeAccountIdentityGrpcService` implements the authenticated Account-owner UUID/provenance read; its 31 focused unit cases, integration-source compilation, and formatting/documentation checks do not prove PostgreSQL execution or a live mTLS handshake, and alone do not qualify the later UUID receiving source or production gameplay admission. Lifecycle-state retention remains tracked under AA-1.3. | +| `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountJoinOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java); [AccountConnectScopeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java); [ExpiredConnectScopeCleanupJob.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java); [AccountAuditOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java); [AccountCanonicalFirstJoinTerminalCoordinator.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java); [AccountMembershipAuthorityEventProducer.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountTenantAuthorityEventRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java); [AccountDemoTenantEntitlementRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java); [AccountTenantEntitlementOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java); [AccountActorStagingEligibilityService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityService.java); [AccountActorStagingEligibilityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcService.java); [AccountActorStagingEligibilityRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountActorStagingEligibilityRepository.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql); [V30__approved_legacy_tenant_associations.sql](../../../services/account-service/src/main/resources/db/migration/V30__approved_legacy_tenant_associations.sql); [V31__subscription_authority_generation.sql](../../../services/account-service/src/main/resources/db/migration/V31__subscription_authority_generation.sql); [V32__realm_grant_currentness.sql](../../../services/account-service/src/main/resources/db/migration/V32__realm_grant_currentness.sql); [V33__fresh_tenant_identity_associations.sql](../../../services/account-service/src/main/resources/db/migration/V33__fresh_tenant_identity_associations.sql); [V34__account_membership_pair_authority.sql](../../../services/account-service/src/main/resources/db/migration/V34__account_membership_pair_authority.sql); [V35__canonical_uuid_membership_identity.sql](../../../services/account-service/src/main/resources/db/migration/V35__canonical_uuid_membership_identity.sql); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V37__canonical_first_join_scope_and_intent.sql](../../../services/account-service/src/main/resources/db/migration/V37__canonical_first_join_scope_and_intent.sql); [V38__account_first_join_authority_outbox_and_roles.sql](../../../services/account-service/src/main/resources/db/migration/V38__account_first_join_authority_outbox_and_roles.sql); [V39__canonical_first_join_terminal_receipt.sql](../../../services/account-service/src/main/resources/db/migration/V39__canonical_first_join_terminal_receipt.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V53__account_protected_demo_entitlements.sql](../../../services/account-service/src/main/resources/db/migration/V53__account_protected_demo_entitlements.sql); [V73__account_tenant_authority_source_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql); [CanonicalGameplayAccountInitialBarrierInitializerRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierInitializerRepository.java); [CanonicalGameplayAccountInitialBarrierRedisOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwner.java); [V1047__canonical_initial_account_admission_barrier.sql](../../../services/game-session-service/src/main/resources/db/migration/V1047__canonical_initial_account_admission_barrier.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [ExpiredConnectScopeCleanupJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJobTest.java); [AccountAuditOutboxRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java); [AccountJoinDigestTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [AccountDemoTenantEntitlementPersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java); [AccountCanonicalFirstJoinEventIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); [AccountCanonicalFirstJoinTerminalCoordinatorTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java); [AccountMembershipAuthorityEventProducerCanonicalJoinTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountTenantAuthorityEventRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java); [AccountActorStagingEligibilityServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityServiceTest.java); [AccountActorStagingEligibilityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcServiceTest.java); [CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java); [CanonicalGameplayAccountInitialBarrierRedisScriptIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisScriptIntegrationTest.java); R849 partial execution, R855/R856 recovery, R867 and R902 focused execution have separate scopes and limits recorded above | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. `AccountTenantAuthorityEventRepository` appends the canonical tenant authority event during demo entitlement provisioning; `AccountMembershipAuthorityEventProducer` emits the first-JOIN membership event with its billing cutoff taken from that current tenant authority event, covered by [AccountCanonicalFirstJoinEventIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); no entitlement caller wires it, and current PostgreSQL proof remains pending because the integration source compiled but was unrun locally. The default public bootstrap discovery, direct-scope, JOIN, and connect-token receiving composition returns `AUTH_UNAVAILABLE` before bootstrap/scope or legacy authority reads. Manually configured receivers follow the [Account API composition boundaries](../../architecture/microservices/account-service/api-contracts.md); connect-token validates bootstrap identity and reads scope but remains held before replay or issuance. The numeric runtime entitlement receiver returns `ENTITLEMENT_UNAVAILABLE` before reading retained numeric subscription rows. The held boundary, preserved positive component obligations, and proof history are in [canonical billing and retention receiving](#canonical-billing-and-retention-receiving). Target current-authority and postcondition revalidation remain unproved. The strict ADR 0025 commit gate remains incomplete, and no durable Game Session-owned target fence is implemented or proved; transaction duration or timing thresholds alone would not prove it. Prepared JOIN component behavior retains the subscription-row lock boundary, remote scope/target/entitlement checks outside the lock-holding transaction, and atomic membership, operation-outcome, and audit-outbox persistence. These components are not reachable through the default receiving facade. Focused unit proof verifies terminal replay revalidation occurs after commit or rollback without rewriting the stored outcome; the PostgreSQL row-lock regression compiles but skips locally without Docker. PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Global-only registration no longer creates an admitting membership. Expired unreferenced connect-scope rows are swept under their existing expiry; V27's restrictive scope FK preserves every scope referenced by a PENDING or terminal JOIN and fences racing intent inserts. JOIN recovery/reconciliation after an unknown database commit outcome remains a separate #2848 gap under the Overseer decision; do not mark ADR 0025 complete. The Gateway continues to block public JOIN exposure, and Game Session text JOIN/Join & Play dispatch remains #2898. `AccountActorStagingEligibilityGrpcService` is a read-only internal eligibility check disabled by default; it does not establish that a realm is public or preseeded and grants no gameplay admission. Membership authority generation in runtime admission, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Current non-public discovery and supported text `PLAY` require admitting membership before the applicable realm grant; connect-token issuance fails closed before these checks and does not establish target grant validation. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). The unregistered INITIAL Account prerequisite preserves one original target and does not supply abandoned-target or account-wide fenced recovery, fresh Account authority, final admission or runtime activation; see the [readiness scope and proof](#canonical-new-admission-components). | | `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md); [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references); [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md); [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountJwtSignerDesiredStateRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java); [AccountJwtReadinessProbeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java); [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java); [AccountStartSessionOperatorAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java); [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql); [V99__account_jwt_signer_desired_state.sql](../../../services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql); [V123__account_jwt_readiness_per_pod_closure.sql](../../../services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql); [V125__account_jwt_signer_promotion_receipt_binding.sql](../../../services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql); [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql); [V126.1](../../../services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql); [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql); [V126.3](../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql); [AccountPlatformRestrictionOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java); [V137__account_platform_restriction_revision_receipts.sql](../../../services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql); [V137.1__account_platform_restriction_lifecycle_consistency.sql](../../../services/account-service/src/main/resources/db/migration/V137.1__account_platform_restriction_lifecycle_consistency.sql); [AccountPlatformRestrictionMutationRequest.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionMutationRequest.java); [AccountSecurityStateAuthorityEventV1Codec.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java); [AccountAuthoritySourceEventReadback.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V140](../../../services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql); [V141](../../../services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql); [V142](../../../services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql); [V143](../../../services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql); [V144](../../../services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql); [V145](../../../services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql); [V146](../../../services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql); [AccountGameplayAdmissionLeaseRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java); [AccountGameplayAdmissionOriginalCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java); [AccountGameplayAdmissionOriginalAckReceiptRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java); [AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java); [V158](../../../services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql); [V159](../../../services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql); [V160](../../../services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql); [AccountStartSessionAuthorityCaptureRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java); [AccountStartSessionWorldParticipationRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java); [AccountStartSessionWorldOriginalAttemptEvidenceRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java); [V160.1](../../../services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql); [AccountStartSessionWorldParticipationAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java); [AccountStartSessionWorldParticipationHistoricalReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java); [AccountStartSessionWorldParticipationSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java); [Logging StartSessionAuthorizationCoordinator.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java); [Logging StartSessionOperatorAuthorizationClient.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java); [Logging StartSessionPreAuthorizationReservationRepository.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java); [Game Session StartSessionOperatorRedemptionClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java); [GameSessionStartSessionOperatorAttemptRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java); [GameSessionCanonicalLaunchPreparationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java); [CanonicalGameInstanceLaunchAssociationRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java); [V1003 original StartSession protections](../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql); [V1004 activation settlement lifecycle integrity](../../../services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql); [V1004.1 monotonic lifecycle counters](../../../services/account-service/src/main/resources/db/migration/V1004.1__activation_settlement_monotonic_lifecycle_counters.sql); [V1004.2 retained lifecycle and canonical UUID integrity](../../../services/account-service/src/main/resources/db/migration/V1004.2__activation_settlement_retained_lifecycle_integrity.sql); [V1004.3 canonical activation acquisition carriers](../../../services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.sql); [AccountStartSessionActivationProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepository.java); [V1006 World activation terminal digest alignment](../../../services/account-service/src/main/resources/db/migration/V1006__world_activation_terminal_digest_alignment.sql); [V1007 selected source reservations](../../../services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_source_reservations.sql); [AccountSelectedOwnerIntakeSourceReservationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java); [V1008 selected-owner intake final authorizations](../../../services/account-service/src/main/resources/db/migration/V1008__selected_owner_intake_final_authorizations.sql); [V1009 selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1009__selected_owner_intake_terminal_settlement.sql); [V1010 Entity selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1010__entity_selected_owner_intake_terminal_settlement.sql); [AccountSelectedOwnerIntakeSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java); [AccountSelectedOwnerIntakeAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationService.java); [AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java); [AccountSelectedOwnerIntakeSettlementReceipt.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceipt.java); [AccountStartSessionAdmissionProtectionAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionService.java); [AccountStartSessionAdmissionProtectionSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionSettlementService.java); [AccountStartSessionAdmissionProtectionGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcService.java); [AccountStartSessionAdmissionProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepository.java); [GrpcAccountInitialAdmissionSettlementReadClient.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClient.java); [EmailVerificationTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/EmailVerificationTokenRepository.java); [AccountGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java); [AccountFreshEnrollmentRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentRepository.java); [AccountFreshEnrollmentPolicyRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentPolicyRepository.java); [AccountRecentReauthenticationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationService.java); [AccountRecentReauthenticationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationRepository.java); [V1018__account_fresh_enrollment_certification.sql](../../../services/account-service/src/main/resources/db/migration/V1018__account_fresh_enrollment_certification.sql); [V1018.1__recent_reauthentication_replay_credentials.sql](../../../services/account-service/src/main/resources/db/migration/V1018.1__recent_reauthentication_replay_credentials.sql); [V1018.2](../../../services/account-service/src/main/resources/db/migration/V1018.2__recent_reauthentication_replay_failure_budget.sql); [AccountControlUiCurrentActorVerifier.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifier.java); [V1016__account_recent_reauthentication_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V1016__account_recent_reauthentication_evidence.sql); [V1017__account_global_control_ui_issuance_scope.sql](../../../services/account-service/src/main/resources/db/migration/V1017__account_global_control_ui_issuance_scope.sql) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java); [AccountJwtSignerStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java); [AccountJwtReadinessStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java); [AccountControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationConfigurationTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java); [AccountJwtJwksTrustedSourceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java); [AccountStartSessionOperatorAuthorizationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java); [StartSessionOperatorAuthorizationGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java); [AccountJwtSignerMaterializationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java); [AccountPlatformRestrictionOperationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java); [AccountPlatformRestrictionOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java); [AccountAuthoritySourceEventReadbackTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java); [AccountSecurityStateAuthorityEventV1CodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java); [AccountGenerationProjectionRestrictionDispatchTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java); [RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java); [AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java); [AccountStartSessionWorldParticipationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java); [AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java); [AccountStartSessionAuthorityCapturePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java); [HostedTermsDisclosureHandoffPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorityBundleTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java); [Logging StartSessionOperatorAuthorizationClientTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java); [Logging StartSessionAuthorizationCoordinatorTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java); [Logging reservation PostgreSQL test](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java); [Game Session StartSessionOperatorRedemptionClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java); [Game Session operator-attempt storage test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java); [Game Session canonical launch preparation test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java); [Admission protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java); [Activation protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java); [SelectedOwnerSourceDisclosurePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java); [AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSettlementServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java); [SelectedOwnerIntakeSettlementGrpcCodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodecTest.java); [AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionServiceTest.java); [AccountStartSessionAdmissionProtectionGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcServiceTest.java); [GrpcAccountInitialAdmissionSettlementReadClientTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClientTest.java); [AccountCredentialPeerGrpcMtlsTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountCredentialPeerGrpcMtlsTest.java); [EmailVerificationHttpAuthWiringTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/EmailVerificationHttpAuthWiringTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [AccountFreshEnrollmentPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentPostgresIntegrationTest.java); [AccountGlobalControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGlobalControlUiIssuancePostgresIntegrationTest.java); [AccountGlobalControlUiScopePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGlobalControlUiScopePostgresIntegrationTest.java); [AccountRecentReauthenticationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPostgresIntegrationTest.java); [AccountRecentReauthenticationReplayTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationReplayTest.java); [AccountControlUiCurrentActorVerifierTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifierTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` still fails closed with `501 NOT_IMPLEMENTED` before mutation: the internal recent-reauthentication owner is purpose-bound to self-service game creation and is not wired to factor changes. General factor-change evidence and mutation composition remain open under ADR 0045. Account-global Control-UI, fresh-enrollment certification and purpose-specific recent-reauthentication preparation are present in the sources and focused proof linked here; their receiving limits are recorded below, and they do not establish production registration or custody. The current Account restriction slice adds a closed restriction event variant, V137 immutable revision/current-result receipts, exact SQL source-head dispatch, and protective-category lifecycle sync; the owner mutation stays default-denied because no authoritative policy/intent and authenticated-caller proof receiver exists. V137.1 adds forward final-state protective-category consistency guards while preserving published V137 and retained V126.x bytes. The staged Java writer rejects protective restrictions on pending-deletion and deleted accounts before side effects; supported deletion/recovery producer sequencing remains a gap. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessor evidence, not current absence; physical forward migration, contradiction rollback, concurrency, and readback proof remain pending, so no authorized admission or end-to-end enforcement is claimed. Separate complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; retained-data lifecycle and deletion reconciliation remain unimplemented. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. Account signer lifecycle, current readiness, and validator-inventory storage remain passive V99–V125 evidence preparation; focused physical PostgreSQL 18 signer/readiness suites confirm bounded storage proof only with synthetic inventory/resource inputs, not live Kubernetes currentness, readiness activation, or signer activation; signer runtime/currentness remains inactive. V126/V126.1 separately add Account-owned StartSession authorization and signer-materialization source preparation: StartSession composition remains off by default, materializer trust remains off by default and denies every RPC when absent, and missing bootstrap-coordinator composition denies enrollment and promotion. These source adapters do not register a runtime issuer or promotion/consumer coordinator, establish operator lifecycle ownership under AA-1.3, or establish activation. The current AA-1.3 owner-source cut also includes V126.2 cleanup-deadline storage and V126.3 response-envelope size-guard migration. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Control-UI issuance PostgreSQL suite passed 5/5, including retained-V126.2 row preservation and denial; direct PostgreSQL proof that a newly recorded cleanup deadline cannot be changed remains a tracked gap. Bounded cleanup and late revocation remain incomplete. StartSession recovery accepts a 128 KiB authority bundle and 144 KiB binding/response within the 160 KiB envelope ceiling; the exact-head authorization repository suite passed 15/15 and covers fresh-install, ambiguous legacy-guard rejection, the 160 KiB storage edge, and retained maximum-size V126.2 ciphertext through V126.3 migration. This is bounded fixture proof and does not establish complete mTLS flow or runtime activation. Current receiving original-ACK PostgreSQL proof remains pending. The Account admission-protection acquisition, settlement, gRPC and repository sources are manually composed, but remain unregistered. Focused proof is recorded by the acquisition PostgreSQL, repository PostgreSQL, service unit and gRPC service unit suites linked above; this does not establish runtime registration, the downstream final-admission path, production authority or PKI, operational custody, or Entity placement and delivery. The World protected-activation consumer is also unregistered. The historical R9 report above records 13 Account PostgreSQL cases and four composed World/Account/Game Session cases, including exact authenticated World terminal settlement, with its missing tested-snapshot and original XML attribution stated explicitly. The separately source-bound receiving proof above qualifies only its named scope. These controlled upstream inputs establish no broader proof; runtime registration, genuine upstream authority, admission, Entity placement and delivery remain unproved. V1003 storage remains passive and V1004 lifecycle integrity checks do not authenticate World. V1004.1 and V1004.2 provide storage checks for nondecreasing lifecycle counters, retained PREPARING evidence, and canonical activation-request UUID spelling. V1004.3 requires canonical Base64 spellings for the tuple, projection, launch-read, and PREPARING lifecycle carriers at acquisition; its focused physical PostgreSQL and retained-row upgrade proof passes in the 25-case Account gate, including all 16 whitespace variants. These are controlled Account integrity checks; authenticated World production and runtime activation remain unproved. Email confirmation atomically claims an exact unexpired token under a fresh locked Account/source transaction; equality at expiry, expired and replayed tokens refuse without Account changes. Credential RPCs require the exact same-namespace Game Session workload; only Authenticate has a separate disabled-by-default local Entity demo fixture. Unbound export/linking/Account-ID email-initiation and deferred currency adapters refuse before owner effects; supported REST and token owners remain. This containment and focused proof do not implement those deferred APIs or remove the existing recovery, audit, production and registration gaps. | -| `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [StripeWebhookIntakeService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/StripeWebhookIntakeService.java); [StripeEventInboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/StripeEventInboxRepository.java); [AccountBillingCustomerProvisioningService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountBillingCustomerProvisioningService.java); [AccountBillingCustomerRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBillingCustomerRepository.java); [AccountBillingPrerequisiteConfirmationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountBillingPrerequisiteConfirmationService.java); [AccountPaymentInstrumentAttachmentService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPaymentInstrumentAttachmentService.java); [AccountPaymentInstrumentRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPaymentInstrumentRepository.java); [V1026__stripe_event_inbox.sql](../../../services/account-service/src/main/resources/db/migration/V1026__stripe_event_inbox.sql); [V1027__account_billing_customer_and_instrument_owners.sql](../../../services/account-service/src/main/resources/db/migration/V1027__account_billing_customer_and_instrument_owners.sql); [V1027.1__billing_customer_first_dispatch_claim.sql](../../../services/account-service/src/main/resources/db/migration/V1027.1__billing_customer_first_dispatch_claim.sql); [PaymentServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java); [PurchaseWorkflowServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImpl.java); [PaymentTransaction.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/PaymentTransaction.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml); [StripeHostingSubscriptionObserver.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionObserver.java); [AccountHostingSubscriptionLifecycleRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java); [AccountHostingSubscriptionLifecycleService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionLifecycleService.java); [AccountSubscriptionIntentRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepository.java); [AccountHostingPlanCatalog.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingPlanCatalog.java) | [StripeWebhookIntakePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/StripeWebhookIntakePostgresIntegrationTest.java); [AccountBillingPrerequisitesPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountBillingPrerequisitesPostgresIntegrationTest.java); [AccountBillingCustomerDispatchPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountBillingCustomerDispatchPostgresIntegrationTest.java); [AccountBillingPrerequisiteConfirmationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountBillingPrerequisiteConfirmationPostgresIntegrationTest.java); [AccountPaymentInstrumentAttachmentPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaymentInstrumentAttachmentPostgresIntegrationTest.java); [PaymentServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java); [PaymentGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java); [PurchaseWorkflowServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImplTest.java); [StripeHostingSubscriptionObserverTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionObserverTest.java); [AccountHostingSubscriptionLifecycleRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepositoryTest.java); [AccountHostingSubscriptionLifecycleServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionLifecycleServiceTest.java); [AccountSubscriptionIntentRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepositoryTest.java); [AccountHostingPlanCatalogTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingPlanCatalogTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | The first cut adds an unregistered verified Stripe event inbox (V1026), durable customer intent/first-dispatch source (V1027 and V1027.1), and exact-customer saved-method confirmation source. Controlled Stripe SDK/readback and PostgreSQL proof sources do not establish live provider calls or a public route. The unregistered hosting observer, intent, lifecycle and plan sources and their focused unit proof are present. Their canonical UUID schema prerequisites V1028/V1029, existing facade convergence and initial provider-write source are carried by [#3390](https://github.com/benhook1013/FireMUD/pull/3390); paid first-invoice checkout completion remains open there. This source carrier still retains the legacy numeric schema; `CreateSubscription` still fails closed before mutation. Subscription lifecycle processing, reconciliation, entitlement/availability enforcement, caller-stable creation identity, active-subscription deletion guards, per-subscription binding, transfer, and replacement-before-detach remain incomplete. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION`; generic provider-mutating substrate is unsupported. Creator/player commerce, donations, fees/shares, payouts, and settlement remain deferred. Webhook intake, billing-customer and saved-method registration additionally require approved finite category schedules, guarded minimization/erasure and account-deletion/backup treatment with physical proof under [the Stripe registration prerequisites](../../architecture/microservices/account-service/stripe-integration.md#billing-owner-source-registration-prerequisites). Append-only provider payloads and card-display history do not authorize indefinite production retention or retention of the Account beyond ADR 0043’s minimum billing-evidence boundary. | -| `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The local reader refuses null, missing, ambiguous or nonpositive-version subscription evidence. Classified storage outages preserve `ENTITLEMENT_UNAVAILABLE`; JOIN diagnostic persistence follows rollback, and terminal-outage reads preserve the complete original receipt. The focused current-source qualification is recorded below. Legacy gRPC still carries unavailable outcomes in its error field, an explicit transport-classification gap. Current connect-token issuance returns `AUTH_UNAVAILABLE` before entitlement reads, cached replay or token issuance; older positive-issuance tests are historical. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its shared subscription-version/billing-sequence projection and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. Current `past_due` handling remains gameplay-available and public-join-eligible only when the sole explicit row is `past_due`. | -| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination); [Gateway Architecture](../../architecture/system-architecture-gateway.md#gameplay-websocket-route) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts); [AccountGameplayCanonicalLoginOwner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java); [AccountGameplayDelegationIssuanceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java); [V147__account_gameplay_delegation_issuance.sql](../../../services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql); [V157.1__account_gameplay_token_fence_truncate_guard.sql](../../../services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql); [CanonicalGameplayRosterSelectionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [GatewayFirstPartyConnectContextEnvelope.java](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelope.java); [FirstPartyConnectContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [FirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextRegistry.java); [FirstPartyConnectContextResolution.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java); [RedisFirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java); [GameSessionWebSocketHandshakeInterceptor.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [GameSessionWebSocketHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [InitialGameplayLoginOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwner.java); [CanonicalGameplayLoginAccountClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java); [CanonicalGameplayLoginResult.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java); [GameplayHandshakeFilter.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java); [GameplayRouteReadinessHealthIndicator.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicator.java); [FirstPartyConnectContextConfig.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextConfig.java); [FirstPartyConnectContextProperties.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextProperties.java); [CanonicalPlayerRouteReadService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [ActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/ActiveTransportSessionRegistry.java); [InMemoryActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistry.java); [CommunicationRecipientDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryService.java); [PlayerOutputDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryService.java); [CanonicalGameplayIssuerAdmissionControlRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlRepository.java); [CanonicalGameplayIssuerAdmissionBarrierRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java); [CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java); [V1045__canonical_issuer_binding_local_acknowledgement.sql](../../../services/game-session-service/src/main/resources/db/migration/V1045__canonical_issuer_binding_local_acknowledgement.sql); [V1046__canonical_issuer_live_admission_control.sql](../../../services/game-session-service/src/main/resources/db/migration/V1046__canonical_issuer_live_admission_control.sql); [DirectTextAuthenticatedLobbyOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyOwner.java); [DirectTextAuthenticatedLobbyRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/DirectTextAuthenticatedLobbyRepository.java); [V1052__direct_text_authenticated_lobby.sql](../../../services/game-session-service/src/main/resources/db/migration/V1052__direct_text_authenticated_lobby.sql) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [AccountGameplayCanonicalLoginOwnerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java); [AccountGameplayDelegationIssuancePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java); [CanonicalGameplayRosterSelectionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java); [GatewayFirstPartyConnectContextEnvelopeTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelopeTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [FirstPartyConnectContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java); [FirstPartyConnectContextResolutionTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolutionTest.java); [RedisFirstPartyConnectContextRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java); [GameSessionWebSocketHandshakeInterceptorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java); [GameSessionWebSocketHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java); [InitialGameplayLoginOwnerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java); [InitialGameplayLoginContextRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java); [CanonicalGameplayLoginAccountClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClientTest.java); [CanonicalGameplayLoginResultTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java); [GameplayHandshakeFilterTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java); [GameplayRouteReadinessHealthIndicatorTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicatorTest.java); [CanonicalPlayerRouteReadServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadServiceTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [SessionContextTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java); [InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java); [InMemoryActiveTransportSessionRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistryTest.java); [CommunicationRecipientDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java); [PlayerOutputDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryServiceTest.java); [CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java); [CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java); R849 partial execution, R855/R856 recovery, R867 and R902 focused execution have separate scopes and limits recorded above; [DirectTextAuthenticatedLobbyTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java); [DirectTextAuthenticatedLobbyIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current `/auth/connect-token` validates existing bootstrap and scope, then returns `AUTH_UNAVAILABLE` before cached-success replay, token minting, or replay/session mutation. The canonical Account producer, shared replay fence, dedicated Gateway signing keys, and deployment qualification remain unavailable. Game Session retains complete signed-context, canonical-route/private-handle, and retention sources, but public first-party bare `LOGIN`/`PLAY` deny before legacy Account, Entity, or binding effects; partial selectors never provide fallback. Generic credential LOGIN/PLAY and retained-edge rebind remain separate behavior, and earlier first-party happy-handshake/reconnect proofs are historical. Direct-text `CHARS` returns unavailable without legacy Entity enumeration or an accepted command event; Account HTTP/bootstrap roster discovery remains separate. Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. Live no-key disposal remains fail-closed pending the protected retained binding-history/restore-continuity producer tracked with `PO-3.4` in [Platform Operations](./platform-operations-and-delivery.md#capability-status). The initial private gameplay LOGIN now has local unregistered composition source; runtime caller registration and authentication, deployed ACL/TLS and signer custody, missing-Account decoy timing parity, and singleton source-fence allocator throughput remain open (see [source-intake status](#initial-private-gameplay-login-issuance-source-intake)). The default-off roster selection source has no player-command caller; `PLAY`/`LOOK` activation and live owner-RPC execution remain unproved, so `AA-2.1` stays partial. Issuer LIVE/OPEN/cutoff and INITIAL Account components are manually composed prerequisites, not complete original NEW or playable admission; custody, default registration, final admission and activation remain unqualified as recorded in the [readiness scope and proof](#canonical-new-admission-components). The authenticated lobby SQL companion exists but is unregistered; live REALMS/JOIN registration and admission remain open. | +| `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [StripeWebhookIntakeService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/StripeWebhookIntakeService.java); [StripeEventInboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/StripeEventInboxRepository.java); [AccountBillingCustomerProvisioningService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountBillingCustomerProvisioningService.java); [AccountBillingCustomerRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBillingCustomerRepository.java); [AccountBillingPrerequisiteConfirmationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountBillingPrerequisiteConfirmationService.java); [AccountPaymentInstrumentAttachmentService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPaymentInstrumentAttachmentService.java); [AccountPaymentInstrumentRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPaymentInstrumentRepository.java); [V1026__stripe_event_inbox.sql](../../../services/account-service/src/main/resources/db/migration/V1026__stripe_event_inbox.sql); [V1027__account_billing_customer_and_instrument_owners.sql](../../../services/account-service/src/main/resources/db/migration/V1027__account_billing_customer_and_instrument_owners.sql); [V1027.1__billing_customer_first_dispatch_claim.sql](../../../services/account-service/src/main/resources/db/migration/V1027.1__billing_customer_first_dispatch_claim.sql); [PaymentServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java); [PurchaseWorkflowServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImpl.java); [PaymentTransaction.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/PaymentTransaction.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml); [StripeHostingSubscriptionObserver.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionObserver.java); [AccountHostingSubscriptionLifecycleRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java); [AccountHostingSubscriptionLifecycleService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionLifecycleService.java); [AccountSubscriptionIntentRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepository.java); [AccountHostingPlanCatalog.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingPlanCatalog.java) | [StripeWebhookIntakePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/StripeWebhookIntakePostgresIntegrationTest.java); [AccountBillingPrerequisitesPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountBillingPrerequisitesPostgresIntegrationTest.java); [AccountBillingCustomerDispatchPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountBillingCustomerDispatchPostgresIntegrationTest.java); [AccountBillingPrerequisiteConfirmationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountBillingPrerequisiteConfirmationPostgresIntegrationTest.java); [AccountPaymentInstrumentAttachmentPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaymentInstrumentAttachmentPostgresIntegrationTest.java); [PaymentServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java); [PaymentGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java); [PurchaseWorkflowServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImplTest.java); [StripeHostingSubscriptionObserverTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionObserverTest.java); [AccountHostingSubscriptionLifecycleRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepositoryTest.java); [AccountHostingSubscriptionLifecycleServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionLifecycleServiceTest.java); [AccountSubscriptionIntentRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepositoryTest.java); [AccountHostingPlanCatalogTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingPlanCatalogTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | The first cut adds an unregistered verified Stripe event inbox (V1026), durable customer intent/first-dispatch source (V1027 and V1027.1), and exact-customer saved-method confirmation source. Controlled Stripe SDK/readback and PostgreSQL proof sources do not establish live provider calls or a public route. The unregistered hosting observer, intent, lifecycle and plan sources and their focused unit proof are present. The canonical UUID schema/lifecycle and exact focused proof are present in [canonical billing receiving](#canonical-billing-and-retention-receiving); V1028 retains the original numeric archive, and active canonical ownership uses V1029 and its forward lifecycle migrations. Existing public facade convergence and positive consumers remain in [#3390](https://github.com/benhook1013/FireMUD/pull/3390); `CreateSubscription` still fails closed before mutation. The linked receiving section owns bounded intent/lifecycle/reconciliation and terminal-cancellation proof; production registration, live provider/custody qualification, remaining lifecycle outcomes, complete consumer/runtime enforcement, transfer and replacement-before-detach remain incomplete. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION`; generic provider-mutating substrate is unsupported. Creator/player commerce, donations, fees/shares, payouts, and settlement remain deferred. Webhook intake, billing-customer and saved-method registration additionally require approved finite category schedules, guarded minimization/erasure and account-deletion/backup treatment with physical proof under [the Stripe registration prerequisites](../../architecture/microservices/account-service/stripe-integration.md#billing-owner-source-registration-prerequisites). Append-only provider payloads and card-display history do not authorize indefinite production retention or retention of the Account beyond ADR 0043’s minimum billing-evidence boundary. | +| `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The current numeric runtime entitlement endpoint returns `ENTITLEMENT_UNAVAILABLE` before reading retained numeric subscription rows. Current status, preserved positive receiving obligations, and proof history are recorded in [canonical billing and retention receiving](#canonical-billing-and-retention-receiving); earlier focused storage/retry proof does not establish a live legacy-row producer. Legacy gRPC still carries unavailable outcomes in its error field, an explicit transport-classification gap. Current connect-token issuance follows the [Account API conditional bootstrap/scope validation boundary](../../architecture/microservices/account-service/api-contracts.md#rest-apis), but remains unavailable before entitlement reads, cached replay, or token issuance; older positive-issuance tests are historical. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its shared subscription-version/billing-sequence projection and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. No current gameplay or public-join eligibility is inferred from a retained numeric `past_due` row while the runtime entitlement boundary is held. | +| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination); [Gateway Architecture](../../architecture/system-architecture-gateway.md#gameplay-websocket-route) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts); [AccountGameplayCanonicalLoginOwner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java); [AccountGameplayDelegationIssuanceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java); [V147__account_gameplay_delegation_issuance.sql](../../../services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql); [V157.1__account_gameplay_token_fence_truncate_guard.sql](../../../services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql); [CanonicalGameplayRosterSelectionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [GatewayFirstPartyConnectContextEnvelope.java](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelope.java); [FirstPartyConnectContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [FirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextRegistry.java); [FirstPartyConnectContextResolution.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java); [RedisFirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java); [GameSessionWebSocketHandshakeInterceptor.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [GameSessionWebSocketHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [InitialGameplayLoginOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwner.java); [CanonicalGameplayLoginAccountClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java); [CanonicalGameplayLoginResult.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java); [GameplayHandshakeFilter.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java); [GameplayRouteReadinessHealthIndicator.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicator.java); [FirstPartyConnectContextConfig.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextConfig.java); [FirstPartyConnectContextProperties.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextProperties.java); [CanonicalPlayerRouteReadService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [ActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/ActiveTransportSessionRegistry.java); [InMemoryActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistry.java); [CommunicationRecipientDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryService.java); [PlayerOutputDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryService.java); [CanonicalGameplayIssuerAdmissionControlRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlRepository.java); [CanonicalGameplayIssuerAdmissionBarrierRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java); [CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java); [V1045__canonical_issuer_binding_local_acknowledgement.sql](../../../services/game-session-service/src/main/resources/db/migration/V1045__canonical_issuer_binding_local_acknowledgement.sql); [V1046__canonical_issuer_live_admission_control.sql](../../../services/game-session-service/src/main/resources/db/migration/V1046__canonical_issuer_live_admission_control.sql); [DirectTextAuthenticatedLobbyOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyOwner.java); [DirectTextAuthenticatedLobbyRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/DirectTextAuthenticatedLobbyRepository.java); [V1052__direct_text_authenticated_lobby.sql](../../../services/game-session-service/src/main/resources/db/migration/V1052__direct_text_authenticated_lobby.sql) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [AccountGameplayCanonicalLoginOwnerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java); [AccountGameplayDelegationIssuancePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java); [CanonicalGameplayRosterSelectionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java); [GatewayFirstPartyConnectContextEnvelopeTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelopeTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [FirstPartyConnectContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java); [FirstPartyConnectContextResolutionTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolutionTest.java); [RedisFirstPartyConnectContextRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java); [GameSessionWebSocketHandshakeInterceptorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java); [GameSessionWebSocketHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java); [InitialGameplayLoginOwnerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java); [InitialGameplayLoginContextRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java); [CanonicalGameplayLoginAccountClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClientTest.java); [CanonicalGameplayLoginResultTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java); [GameplayHandshakeFilterTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java); [GameplayRouteReadinessHealthIndicatorTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicatorTest.java); [CanonicalPlayerRouteReadServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadServiceTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [SessionContextTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java); [InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java); [InMemoryActiveTransportSessionRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistryTest.java); [CommunicationRecipientDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java); [PlayerOutputDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryServiceTest.java); [CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java); [CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java); R849 partial execution, R855/R856 recovery, R867 and R902 focused execution have separate scopes and limits recorded above; [DirectTextAuthenticatedLobbyTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java); [DirectTextAuthenticatedLobbyIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current `/auth/connect-token` returns `AUTH_UNAVAILABLE` before bootstrap/scope validation when canonical scope consumers are absent; when manually configured, it validates bootstrap identity and reads the connect scope before refusing cached-success replay, token minting, or replay/session mutation. The canonical Account producer, shared replay fence, dedicated Gateway signing keys, and deployment qualification remain unavailable. Game Session retains complete signed-context, canonical-route/private-handle, and retention sources, but public first-party bare `LOGIN`/`PLAY` deny before legacy Account, Entity, or binding effects; partial selectors never provide fallback. Generic credential LOGIN/PLAY and retained-edge rebind remain separate behavior, and earlier first-party happy-handshake/reconnect proofs are historical. Direct-text `CHARS` returns unavailable without legacy Entity enumeration or an accepted command event; Account HTTP/bootstrap roster discovery remains separate. Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. Live no-key disposal remains fail-closed pending the protected retained binding-history/restore-continuity producer tracked with `PO-3.4` in [Platform Operations](./platform-operations-and-delivery.md#capability-status). The initial private gameplay LOGIN now has local unregistered composition source; runtime caller registration and authentication, deployed ACL/TLS and signer custody, missing-Account decoy timing parity, and singleton source-fence allocator throughput remain open (see [source-intake status](#initial-private-gameplay-login-issuance-source-intake)). The default-off roster selection source has no player-command caller; `PLAY`/`LOOK` activation and live owner-RPC execution remain unproved, so `AA-2.1` stays partial. Issuer LIVE/OPEN/cutoff and INITIAL Account components are manually composed prerequisites, not complete original NEW or playable admission; custody, default registration, final admission and activation remain unqualified as recorded in the [readiness scope and proof](#canonical-new-admission-components). The authenticated lobby SQL companion exists but is unregistered; live REALMS/JOIN registration and admission remain open. | | `AA-2.2` Reconnect, resume eligibility, and cross-device continuity | `partial` | `drift-found` | [Reconnection](../../architecture/system-architecture-reconnection.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [Redis architecture](../../architecture/system-architecture-redis.md); [ADR 0019](../../architecture/decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0133](../../architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md); [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [GameplayWebSocketBridgeHandler.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [EffectiveReconnectionSettingsResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java); [Telnet cross-service test](../../../services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Generic resume, bounded semantic context, and edge rebind exist, but the effective disconnected-resume window is resolved without `PLAY` enforcement; namespace-aware binding/transfer, complete authenticated real-service replacement, lifecycle/presence/stalled-input outcomes, and proof of fresh-edge `LOOK`/prompt behavior are not complete or proved. Current WebSocket reconnect suppresses retained private-context presentation while durable episode/generation eligibility is unqualified; rows remain stored, so this is neither deletion nor proof of logout invalidation. R1424 executed bounded suppression/redraw proof (57 WebSocket-handler units, 20 integration cases and ten LOOK cross-service cases), separately attributed in [Reconnect and Continuity](#reconnect-and-continuity); this is not a fresh current-head image result or proof of eligible-context replay. The earlier first-party post-logout replay defect is historical: current first-party `LOGIN` and `PLAY` deny before legacy effects while the genuine context consumers remain unavailable. Fresh edge reconnect must not replay client input/bytes/frames and must end with fresh `LOOK` plus exactly one reconnect prompt when both effective reconnect-prompt settings are enabled, or zero reconnect prompts when either is disabled. Full token refresh, membership-version and membership-authority-generation persistence, revocation, and non-edge restart continuity remain. See AA-2.1 for the finite namespace controller-index migration-driver prefix, its implementation and proof anchors, and the unproved physical PostgreSQL/Redis, final-image, and trusted-bootstrap/execution gates. | | `AA-2.3` Takeover, logout, idle expiry, and revocation | `partial` | `drift-found` | [Session behavior](../../architecture/system-architecture-session-behavior.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md) | [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [LogoutCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [TelnetServerHandler.java](../../../services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandler.java); [application.yml](../../../services/game-session-service/src/main/resources/application.yml); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisMovementEffectIdempotencyService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyService.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LogoutCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [RedisMovementEffectIdempotencyServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java); [SessionContextSecretAndPresenceRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/SessionContextSecretAndPresenceRedisIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [World Runtime](./world-runtime-and-movement.md); [Gameplay Rules](./gameplay-rules-entities-and-effects.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Gameplay takeover/LOGOUT and transport idle-close handling exist; target takeover requires namespace-scoped atomic monotonic `bindingGeneration`, old-input fencing, and preservation of already-admitted work as defined by [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md), while Account control-plane logout/authority-generation workflows, full idle/session expiry convergence, and first-party post-logout replay cleanup are absent. The [local secret/presence containment](#session-secret-and-presence-containment) prevents new raw delegation-JWT persistence and projects legacy values without rehydration; physical retained-value cleanup remains open; scoped receiving proof is recorded at that owner. | -The Unit 1A Cycle 8 correction strengthens the current `AA-1.2` / `AA-2.1` boundary without claiming explicit JOIN completion. Account bootstrap character discovery requires membership permitting gameplay admission without an Entity read; connect-token issuance returns `AUTH_UNAVAILABLE` before cached replay or membership, entitlement, grant, and routing-authority reads. Pre-membership world and realm discovery remains available. Current text `PLAY` implements the lifecycle/generation and admission checks covered by this receiving boundary. The canonical ordering contract is defined in [Authentication and authorization](../../architecture/system-architecture-authentication.md#play-current-and-target-failure-boundaries). Focused service proof covers Account-before-roster ordering, strict persisted actor selection, and the Game Session-to-Entity peer allowlist across 124 focused tests. Deployment/mTLS and fresh-image proof remain incomplete, so this targeted `PLAY` work does not complete AA-2.1, explicit JOIN, or `playableSmoke`. Account's Game Session discovery/pointer calls use bounded deadlines and translate only unavailable/deadline transport failures to retryable `AUTH_UNAVAILABLE` / HTTP 503. The admission-pointer producer and consumer reject any `stateScope` other than exact `SHARED` or `ISOLATED`, so malformed authority cannot silently become shared-state admission. Account-owned explicit public-production JOIN writing and operation checks are implemented locally; first-party text JOIN dispatch, full caller-target/atomic authority, `allowNewGameplayBindings`, grant lifecycle/expiry, and lease-commit proof remain open as recorded above. +The Unit 1A Cycle 8 correction strengthens the current `AA-1.2` / `AA-2.1` boundary without claiming explicit JOIN completion. Account bootstrap character discovery requires membership permitting gameplay admission without an Entity read; connect-token issuance returns `AUTH_UNAVAILABLE` before cached replay or membership, entitlement, grant, and routing-authority reads. Pre-membership world and realm discovery remains available. Current text `PLAY` implements the lifecycle/generation and admission checks covered by this receiving boundary. The canonical ordering contract is defined in [Authentication and authorization](../../architecture/system-architecture-authentication.md#play-current-and-target-failure-boundaries). Focused service proof covers Account-before-roster ordering, strict persisted actor selection, and the Game Session-to-Entity peer allowlist across 124 focused tests. Deployment/mTLS and fresh-image proof remain incomplete, so this targeted `PLAY` work does not complete AA-2.1, explicit JOIN, or `playableSmoke`. Account's Game Session discovery/pointer calls use bounded deadlines and translate only unavailable/deadline transport failures to retryable `AUTH_UNAVAILABLE` / HTTP 503. The admission-pointer producer and consumer reject any `stateScope` other than exact `SHARED` or `ISOLATED`, so malformed authority cannot silently become shared-state admission. Account-owned explicit public-production JOIN writer and operation-check components remain prepared locally without default production composition; default `POST /auth/bootstrap/join` denies before invoking them, while manually configured JOIN follows the [Account API canonical validation/read path](../../architecture/microservices/account-service/api-contracts.md#rest-apis). First-party text JOIN dispatch, full caller-target/atomic authority, `allowNewGameplayBindings`, grant lifecycle/expiry, and lease-commit proof remain open as recorded above. At receiving source `6c14229c32`, consolidated focused proof passes 572 cases across 15 unit, PostgreSQL-backed WebSocket, physical Redis and cross-service WebSocket/communication/Telnet suites, with zero failures, errors or skips, plus affected Checkstyle, formatting and canonical documentation checks. The gate includes current-parent menu/dispatch corrections; unchanged tasks may reuse qualified Gradle results. Account authority is controlled or mocked in transport fixtures, so these results do not prove full caller-target atomic authority, grant lifecycle/expiry, exact lease commit, genuine custody or public admission. Earlier focused counts overlap and are not additive. @@ -574,9 +598,9 @@ Reconnect prompt-setting precedence remains owned by [Input, Output, and Present Platform accounts are global identities. Tenant membership, tenant-scoped authorization, purchased/runtime entitlements, and non-public realm grants are distinct Account-owned authorities. The canonical tenant roles are `player`, `designer`, `tenantAdmin`, and `moderator`; global elevated roles such as `god`/platform admin are handled separately. Runtime consumers reuse Account and Common Security authority rather than deriving local equivalents. -`POST /auth/player-bootstrap` authenticates the account before tenant selection, accepts the account's configured password or verified-email OTP mode, and records only account-scoped bootstrap session state. Current non-public discovery requires both an admitting Account membership and the separately stored Account-owned realm grant; ordinary credential `PLAY` evaluates the same authorities independently. The current `/auth/connect-token` validates bootstrap and connect scope, then returns `AUTH_UNAVAILABLE` before cached-success replay, membership/entitlement/runtime reads, token minting, or replay/session mutation. The earlier cache-hit and fresh-issuance behavior is historical and does not establish current gameplay authority. A canonical producer must still validate the applicable non-public grant and current Account/runtime authority before it can issue context. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md). +`POST /auth/player-bootstrap` authenticates the account before tenant selection, accepts the account's configured password or verified-email OTP mode, and records only account-scoped bootstrap session state. The target non-public discovery flow requires both an admitting Account membership and the separately stored Account-owned realm grant; ordinary credential `PLAY` evaluates the same authorities independently. With default composition absent, Account bootstrap discovery and connect-token receiving methods return `AUTH_UNAVAILABLE` before bootstrap/scope or legacy authority reads. Manually configured discovery follows the [Account API canonical receiver paths](../../architecture/microservices/account-service/api-contracts.md), while connect-token validates bootstrap identity and reads scope but remains held before cached-success replay or issuance. See [canonical billing and retention receiving](#canonical-billing-and-retention-receiving) for the held boundary and preserved obligations. The earlier cache-hit and fresh-issuance behavior is historical and does not establish current gameplay authority. A canonical producer must still validate the applicable non-public grant and current Account/runtime authority before it can issue context. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md). -The obsolete implicit public-production membership-writer RPC/client/service seam has been removed. Current `/auth/connect-token` fails closed before replay or issuance and does not create membership. The canonical `JoinPublicProductionMembership` Account writer and `POST /auth/bootstrap/join` controller/operation are implemented locally, including a policy-bound v1 digest and membership/audit outbox transaction; the current Gateway guard still blocks external exposure. Game Session text `JOIN` dispatch remains with #2898, so first-party text `Join & Play` is unavailable in this stage. The writer's `PENDING`/unknown-database-outcome recovery seam remains open under #2848, as does direct text-client proof, so ADR 0025 is not complete. The membership-authority-generation reread remains a requirement for any future connect-token producer under [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md) and [Authentication and authorization](../../architecture/system-architecture-authentication.md). +The obsolete implicit public-production membership-writer RPC/client/service seam has been removed. Current `/auth/connect-token` fails closed before replay or issuance and does not create membership. Prepared Account JOIN persistence components and the local `POST /auth/bootstrap/join` route remain, but their default receiving composition returns `AUTH_UNAVAILABLE` before bootstrap/scope, target, entitlement, or membership reads or mutation. Manually configured JOIN proceeds into canonical validation and authority reads under the [Account API contract](../../architecture/microservices/account-service/api-contracts.md#rest-apis). The current Gateway guard still blocks external exposure; the held boundary and preserved positive obligations are recorded in [canonical billing and retention receiving](#canonical-billing-and-retention-receiving). Game Session text `JOIN` dispatch remains with #2898, so first-party text `Join & Play` is unavailable in this stage. The writer's `PENDING`/unknown-database-outcome recovery seam remains open under #2848, as does direct text-client proof, so ADR 0025 is not complete. The membership-authority-generation reread remains a requirement for any future connect-token producer under [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md) and [Authentication and authorization](../../architecture/system-architecture-authentication.md). Account export, deletion, recovery, password reset, username reminder, email verification, and profile operations are account-scoped. Public reset, reminder, and verification initiation resolve normalized email and return neutral success for unknown accounts without creating tokens or deliveries; public verification no longer accepts a numeric account selector. The broader trusted-source and distributed abuse controls remain absent. The target `ExportTenantData` contract is the separate tenant-admin route for a tenant-wide export of tenant-owned records and minimum stable subject references; it has no account subject selector and does not redefine full account export or deletion. The current Account Service route remains account-targeted implementation drift until that contract is implemented. Account deletion observes active subscription/billing preconditions without collapsing global account ownership into tenant ownership. @@ -608,7 +632,7 @@ Previously signed numeric scopes are rejected when presented to the strict reade #### Account-owned response UUID projection -The response-only Account source projects canonical persisted Account UUIDs in every explicit JOIN outcome and in profile GET/UPDATE, gRPC JSON and Account-local export responses. Private scope/operation/member identities, immutable digests, receipts and side effects retain their existing representation. JOIN owner projection follows transaction completion; unavailable owner evidence returns `AUTH_UNAVAILABLE` without rewriting a retained result. Profile projection validates tenant/owner coherence and rereads the full Account because its repository embeds only a partial owner. The [Account API contract](../../architecture/microservices/account-service/api-contracts.md) owns the response semantics. +Current profile GET/UPDATE, gRPC JSON and Account-local export responses project canonical persisted Account UUIDs. Prepared explicit JOIN outcomes retain that UUID response shape, but the current JOIN receiving facade denies before producing them. Private scope/operation/member identities, immutable digests, receipts and side effects retain their existing representation. JOIN owner projection follows transaction completion; unavailable owner evidence returns `AUTH_UNAVAILABLE` without rewriting a retained result. Profile projection validates tenant/owner coherence and rereads the full Account because its repository embeds only a partial owner. The [Account API contract](../../architecture/microservices/account-service/api-contracts.md) owns the response semantics. Focused service/controller/gRPC cases and native PostgreSQL composition cover UUID responses, generated profile mapping, retained private rows, replay and owner readback refusal. R1189 qualifies the response projection; REST selector proof has its separate attribution. At that source, incoming direct-text context, ordinary JWT identity/shared forwarding and Account-to-Entity discovery remained separate gaps; the final ordinary receiving cohort subsequently qualifies those UUID boundaries. Canonical tenant-qualified profile routes/authorization, token registry qualification and gameplay activation remain separate gaps. No production Game Session text-JOIN caller is introduced, and the unavailable JOIN route remains absent from public OpenAPI. @@ -624,7 +648,7 @@ Local receipt of the REST selector source preserves the future UUID ordinary iss #### Ordinary Account UUID receiving preparation -The final ordinary receiving source converges password and verified-email OTP issuance, JWT subject/account binding, shared session intake/forwarding, typed Account internal/gRPC inputs, supported Social consumers/storage and Game Session LOGIN/PLAY/session carriers on persisted canonical Account UUIDs. Profile `SessionContext` self-binding and global REST caller proof also use UUID identity; Account alone resolves UUIDs to private rows through persisted provenance checks. Logging moderation and Entity roster selectors converge with PLAY; tenant identifiers retain their current numeric representation. The [Account identity contract](../../architecture/microservices/account-service/api-contracts.md#account-uuid-response-and-rest-selector-identity) owns representation and owner resolution. R1251 qualifies the actual Account-issued UUID credential through real intake composition. Final receiving proof and its boundaries are recorded below. +The final ordinary receiving source converges password and verified-email OTP issuance, JWT subject/account binding, shared session intake/forwarding, typed Account internal/gRPC inputs, supported Social consumers/storage and Game Session LOGIN/PLAY/session carriers on persisted canonical Account UUIDs. Profile `SessionContext` self-binding and global REST caller proof also use UUID identity; Account alone resolves UUIDs to private rows through persisted provenance checks. Logging moderation and Entity roster selectors converge with PLAY; tenant representations follow the [Account tenant identifier boundary](../../architecture/microservices/account-service/api-contracts.md#account-tenant-identifier-boundary). The [Account identity contract](../../architecture/microservices/account-service/api-contracts.md#account-uuid-response-and-rest-selector-identity) owns representation and owner resolution. R1251 qualifies the actual Account-issued UUID credential through real intake composition. Final receiving proof and its boundaries are recorded below. Earlier composition runs remain separately attributed: R1228 passes 2,840 Game Session units, 22 WebSocket cases, 145 Social units, 16 Social native cases and eight Account native cases, but its aggregate fails Account test compilation; R1230 recovers the corrected Account suite with 1,797 passes and four existing conditional skips, plus affected test analysis/formatting. They are predecessor-source history, not the final qualification. Current Social V1003 and Logging V1003 follow their effective shared-saga V1002 parents; R1235 passes seven Social physical PostgreSQL cases, and R1239 passes two Logging physical cases plus generation, parent-aware ordering and affected analysis/formatting. Both migrations lock affected tables, refuse populated legacy references and preserve rows/history without guessed mappings, deletion or backfill. @@ -708,9 +732,9 @@ The canonical gRPC `GameSessionGrpcService.startSession` path preflights IP admi ### Entitlement read and JOIN failure classification -The shared local Account subscription reader rejects null, missing, ambiguous or nonpositive-version evidence and preserves bounded entitlement-unavailable classification for storage outages; mapping/configuration faults remain unexpected failures. JOIN leaves a potentially aborted SQL transaction before writing diagnostic evidence through its existing post-rollback path. A failed fresh authority read during terminal replay returns unavailable without changing the complete retained result. This does not implement a complete entitlement bundle, current-row history, positive connect-token issuance, unknown-outcome observation after lost authority, or production admission. The [Account runtime owner](../../architecture/microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority) and [API error catalog](../../architecture/microservices/account-service/api-contracts.md#login-error-codes) own those contracts. +R1424 historically proved that the shared local Account subscription reader rejected null, missing, ambiguous or nonpositive-version evidence and preserved bounded entitlement-unavailable classification for storage outages; mapping/configuration faults remained unexpected failures. It also proved that the prepared JOIN owner leaves a potentially aborted SQL transaction before writing diagnostic evidence through its existing post-rollback path, and that a failed fresh authority read during terminal replay returns unavailable without changing the complete retained result. The current JOIN receiving method denies before invoking that owner, and the current numeric runtime entitlement endpoint returns `ENTITLEMENT_UNAVAILABLE` before any subscription read. This historical proof does not implement a complete entitlement bundle, current-row history, positive connect-token issuance, unknown-outcome observation after lost authority, or production admission. The [Account runtime owner](../../architecture/microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority) and [API error catalog](../../architecture/microservices/account-service/api-contracts.md#login-error-codes) own those contracts. -R1424’s current Account correction passes 305 unit cases and nine actual PostgreSQL cases, including a real SQL abort followed by rollback and a successful fresh-transaction diagnostic write, with correct unavailable classification and unchanged terminal evidence. The CHARS-focused Game Session source separately passes 184 selected unit cases and two actual WebSocket cases. All selected executions have zero failures, errors or skips, and affected enabled main/unit/integration analysis and formatting pass. These separate gates cover 500 selected cases; this is not one full service-suite run. The prior 488-case aggregate remains attributed to its earlier classification source. The PostgreSQL cases retain original intent, scope and Account provenance, prove no membership/audit on refusal, and exercise same-original recovery and immutable terminal evidence. The Game Session cases qualify unavailable direct-text `CHARS`, no accepted command event, and consistent HELP/PLAY/localized guidance while preserving supported WORLDS/REALMS and the separate Account roster. These are controlled owner/transport fixtures, not genuine issuer/custody, full service-suite or successful public-admission proof. Fresh packaged-runtime proof remains pending for the combined receiving source. +R1424’s historical Account correction passed 305 unit cases and nine actual PostgreSQL cases, including a real SQL abort followed by rollback and a successful fresh-transaction diagnostic write, with correct unavailable classification and unchanged terminal evidence. The CHARS-focused Game Session source separately passes 184 selected unit cases and two actual WebSocket cases. All selected executions have zero failures, errors or skips, and affected enabled main/unit/integration analysis and formatting pass. These separate gates cover 500 selected cases; this is not one full service-suite run. The prior 488-case aggregate remains attributed to its earlier classification source. The PostgreSQL cases retain original intent, scope and Account provenance, prove no membership/audit on refusal, and exercise same-original recovery and immutable terminal evidence. The Game Session cases qualify unavailable direct-text `CHARS`, no accepted command event, and consistent HELP/PLAY/localized guidance while preserving supported WORLDS/REALMS and the separate Account roster. These are controlled owner/transport fixtures, not genuine issuer/custody, full service-suite or successful public-admission proof. Fresh packaged-runtime proof remains pending for the combined receiving source. ### Session Lifecycle and Logout @@ -756,7 +780,7 @@ R1418 subsequently carries published #3365 parent `1d2b862ea5a176f9c7e08dd3a0d76 The initial review corrections qualify script-local certificate defaults beneath a symlinked checkout ancestor while continuing to refuse explicit caller paths through links and preserving retained certificate bytes, modes and foreign entries. The certificate contract now requires each intended repository refusal marker on stderr as well as unchanged state, so unrelated command failures cannot satisfy it. Four freshly executed currency adapter cases require one response and completion per call, exact fail-closed metrics when a registry exists, no-registry constructor behavior and no owner interaction. Affected test static analysis, full Java formatting, ShellCheck, capability tracking and documentation checks pass. These direct corrections add no currency capability, public browser handoff, production identity or JOIN recovery authority. -Current writer inspection also narrows the retained JOIN recovery gap: the public owner commits membership, transition audit and its terminal together after a separate durable intent. Unknown acknowledgement can leave either that intent without membership effects or a complete terminal; it does not establish the donor's manufactured positive-PENDING state. A lost committed result may remain unobservable after scope expiry, changed replay policy or lost caller binding. Same-original retry and this later outcome-observation limitation require distinct proof; the existing unknown-recovery and lawful-release holds remain. The proposed audit projection-version marker likewise has no implemented Logging receipt/projection producer here and must not be inferred from receiver IDs, payload replay or stamped test rows. No historical producer provenance, new receiver, recovery RPC or release authority is supplied. +Inspection of the prepared JOIN owner path narrows the retained recovery gap: when invoked, the public owner commits membership, transition audit and its terminal together after a separate durable intent. The current receiving method denies before reaching that owner. Unknown acknowledgement can leave either that intent without membership effects or a complete terminal; it does not establish the donor's manufactured positive-PENDING state. A lost committed result may remain unobservable after scope expiry, changed replay policy or lost caller binding. Same-original retry and this later outcome-observation limitation require distinct proof; the existing unknown-recovery and lawful-release holds remain. The proposed audit projection-version marker likewise has no implemented Logging receipt/projection producer here and must not be inferred from receiver IDs, payload replay or stamped test rows. No historical producer provenance, new receiver, recovery RPC or release authority is supplied. ### Fail-Closed Boundary Convergence @@ -772,7 +796,7 @@ The current numeric-reader guardrail is: numeric identifiers still used by an im This includes positive readers for account, tenant, session, game-instance, character, version, item/container, payment, report, formation, and control-plane identities across the participating services; current-account claims that are present but malformed count as authenticated caller context and therefore fail tenant access rather than silently becoming anonymous; and current presence projects only `PLAYER` until an independent gameplay-grant carrier exists. JWT global/scoped role claims and cached elevation supply no gameplay authority; broader admission, grant-issuance, and capability qualification remains tracked in [EA-2.3](./player-experience-commands-and-communication.md#communication-social-and-presence). Automation schedule due-point identities reject fractional JSON numbers as `invalid_built_in_payload` before handler, pin, quota, or durable-queue work. Runtime-version, work-item, tenant, and gameplay routing readers reject malformed/non-positive values before lookups or mutation. Entity replay-backed mutations validate expiry, required text, optional container identity, and positive quantity before replay execution so a replay hit cannot hide malformed request shape. -Replay boundaries validate both read and write sides. The legacy Account connect-token cached-success path is no longer called: `/auth/connect-token` denies after bootstrap/scope validation before any replay read, token mint, or replay/session mutation. Public-production membership replays require valid success/created flags, nonblank required text, and payload identity matching cache-key inputs; otherwise the replay is treated as unavailable rather than as authoritative success. Prepared upgrade and remote-control-plane replays likewise compare request/execution payloads before reuse. Shared control-plane response readers reject malformed or non-positive returned ids instead of projecting them into apparently valid DTOs. +Replay boundaries validate both read and write sides. The legacy Account connect-token cached-success path is no longer called: `/auth/connect-token` returns `AUTH_UNAVAILABLE` before bootstrap/scope validation when canonical scope consumers are absent; when manually configured, it validates bootstrap identity and reads the connect scope before refusing any replay read, token mint, or replay/session mutation. See [canonical billing and retention receiving](#canonical-billing-and-retention-receiving) for current status and preserved obligations. Public-production membership replays require valid success/created flags, nonblank required text, and payload identity matching cache-key inputs; otherwise the replay is treated as unavailable rather than as authoritative success. Prepared upgrade and remote-control-plane replays likewise compare request/execution payloads before reuse. Shared control-plane response readers reject malformed or non-positive returned ids instead of projecting them into apparently valid DTOs. Equivalent HTTP, WebSocket, and gRPC failures use stable boundary semantics. The [gRPC owner contract](../../architecture/system-architecture-grpc.md#outcome-and-transport-classification) uses typed result unions for successfully produced expected domain outcomes and canonical non-OK status with bounded details when a domain result cannot be produced. Current Game Session/peer handlers still return many response-level `ErrorDetail` payloads, while transport failures cover infrastructure and some pre-domain cases; exact per-RPC migration and proof remain gaps. Shared REST exception handling continues to produce `ApiResponse` envelopes and field-specific `INVALID_ARGUMENT` responses instead of framework-default JSON. These seams log application warnings, meter `grpc.app_error` where applicable, and preserve span/error-code classification. @@ -784,8 +808,6 @@ R1419 passes 70 fresh selected cases (49 Logging units, fifteen application/Post ## Validation and Proof -The [local source-foundation preparation](#local-source-foundation-preparation) records selected unit/mTLS, affected source compilation and enabled static/format proof for the reconstructed source before the provider-write transfer. Those results and historical #3389, #3390 and #3403 results retain their original comparisons; the reduced boundary now has the affected compilation and 51-case focused Account proof recorded above, not a repeated whole-foundation qualification. Physical PostgreSQL qualification and fresh positive runtime Smoke remain receiving obligations; the independently supported parent runtime is preserved, not requalified by source-only checks. - The prepared region owner has a scope-local liveness limit when `beginInitialTimeline` commits `INITIALIZING` but the Redis initialization call never executes. The retained phase, initialization operation and source do not grant a second creation permission; absent keys cannot distinguish that cut from metadata loss, so repeated owner retries refuse without a lease or runtime owner installation. No shipped in-place automatic recovery, dedicated alert or operator repair is claimed. The operator recovery boundary is recorded by [Game Session operations](../../architecture/microservices/game-session-service/operations.md#initial-region-timeline-recovery-boundary). Source-added focused regression `CanonicalGameplayRegionLeaseOwnerIntegrationTest.initializingBeforeRedisExecutionRetainsEvidenceAndRefusesRepeatedOwnerRetry` uses actual PostgreSQL preparation/begin APIs, an actual Redis absence probe and repeated actual owner retries at that precise pre-Redis cut. It asserts the retained SQL row image and absent lease/metadata before and after refusals, and no reacquired creation permit or installed runtime owner. World, provisional binding and stable-incarnation inputs are controlled fixtures; the cut is modeled by discarding the original permit before calling Redis, not by killing a process or fabricating SQL. R890 freshly passed all five native region-owner cases, including this cut, and the inherited protected-admission concurrency case; its aggregate still failed Entity test SpotBugs. The extracted Entity producer's R890/R891/R893 history is recorded separately below. This is bounded refusal proof and does not establish recovery or production activation. @@ -798,7 +820,7 @@ The evidence records focused unit, controller, gRPC, WebSocket, cross-service, a The focused admission proofs cover fresh acceptance, same-IP replacement reservation transfer, rejection without destroying the old session, and the non-destructive operator path. Telnet proofs cover envelope parsing, event metadata, reconnect backoff, bounded connection-local ordered input buffering during edge rebind, buffer exhaustion, sensitive logging, and Telnet/WebSocket `LOOK` parity; they do not prove durable replay of client input or transport bytes. Game Session gRPC proofs cover `Ping`, `NotifyDisconnect`, session lifecycle/control-plane parsing, application-error payloads, and `grpc.app_error` classification. Earlier first-party fresh-token, bare-login, `PLAY` scope, replay/expiry/context, screen-buffer restore, and fresh-redraw proofs describe the superseded path; current first-party coverage is fail-closed and does not establish playable admission. -Account authority proof covers account-first tenantless bootstrap authentication and account-scoped session state, the local `JoinPublicProductionMembership` writer and its Account-owned audit/outbox boundary, Account-owned non-public realm grant denial, cross-tenant membership enforcement, and account-owned export/delete/recovery boundaries including active-subscription deletion guards. The strict ADR 0025 commit fence and connect-token membership-authority-generation reread remain incomplete; Game Session text `JOIN`/`Join & Play` dispatch remains #2898, while unknown-outcome recovery and Logging receipt receiver/readback remain #2848 work. Exact-final-head PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Canonical tenant-role, lifecycle-state, and authority-generation follow-through also remain partial or unproved. +Account authority proof covers account-first tenantless bootstrap authentication and account-scoped session state, the prepared local `JoinPublicProductionMembership` writer and its Account-owned audit/outbox components, Account-owned non-public realm grant denial, cross-tenant membership enforcement, and account-owned export/delete/recovery boundaries including active-subscription deletion guards. The current JOIN receiving method denies before invoking that prepared writer. The strict ADR 0025 commit fence and connect-token membership-authority-generation reread remain incomplete; Game Session text `JOIN`/`Join & Play` dispatch remains #2898, while unknown-outcome recovery and Logging receipt receiver/readback remain #2848 work. Exact-final-head PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Canonical tenant-role, lifecycle-state, and authority-generation follow-through also remain partial or unproved. The #3224 candidate adds an explicit held-admission image-smoke mode: it preserves the existing isolated backend `LOGIN` -> `PLAY` -> `LOOK` proof and checks that real Gateway and Telnet public paths fail closed while admission readiness is out of service. This is separate from successful public admission. The focused transport and image-environment contracts pass. Fresh source-built held-admission qualification on `3c71c8c24379af623ca66550a4f4acaadd0ffd81` passes from 2026-10-16 05:20:30 to 05:27:42 UTC: the run-owned Gateway public listener receives the first-party loopback request outside configured TCP-proxy trust and returns exact `CONNECT_REPLAY_PROTECTION_UNAVAILABLE`; Telnet returns `startup_unavailable` and closes; the direct backend completes `WORLDS`, `LOGIN`, `PLAY`, `LOOK` and `LOGOUT`. Canonical teardown completes and independent exact-project inspection finds no containers, networks or volumes. This proves the held mode and isolated backend flow; it does not prove Kubernetes Service endpoint withdrawal or independent TCP Proxy Service readiness. Host-published Gateway ingress and successful public admission also remain unproved. @@ -875,7 +897,7 @@ No competing target state is currently recorded. Future design discussion is req | Owner | Current responsibility | Primary contract boundary | | --- | --- | --- | -| Account Service | Global accounts, credentials/challenges, memberships, canonical tenant roles, entitlements, non-public realm grants, account lifecycle, and explicit public-production JOIN; canonical gameplay connect-token production currently fails closed after bootstrap/scope validation | Account REST/gRPC APIs, including `/auth/bootstrap/join` and the local JOIN RPC; `/auth/connect-token` currently returns `AUTH_UNAVAILABLE` before cached-success replay, minting, or replay/session mutation; public Gateway exposure remains blocked, leave remains target-only, and Game Session text JOIN dispatch remains #2898 | +| Account Service | Global accounts, credentials/challenges, memberships, canonical tenant roles, entitlements, non-public realm grants, account lifecycle, and prepared explicit public-production JOIN (default receiving composition returns `AUTH_UNAVAILABLE`); canonical gameplay connect-token receiving fails closed before bootstrap/scope validation when consumers are absent, or after those checks when manually configured; current status and proof history are recorded in [canonical billing and retention receiving](#canonical-billing-and-retention-receiving) | Account REST/gRPC APIs, including prepared `/auth/bootstrap/join` and local JOIN RPC contracts (default receiving composition returns `AUTH_UNAVAILABLE`); `/auth/connect-token` currently returns `AUTH_UNAVAILABLE` before cached-success replay, minting, or replay/session mutation; public Gateway exposure remains blocked, leave remains target-only, and Game Session text JOIN dispatch remains #2898 | | Common Security | **Current:** JWT/signed-token claims, current-account and tenant access, control-plane privilege claims, legacy session attestation, current service-identity handling, and downstream caller authorization. **Target:** certificate-derived mTLS workload identity and method allowlists authorize services, while typed `PlayerExecutionContext` carries player scope | `JwtClaims`, `SessionClaims`, session-context helpers, target `PlayerExecutionContext`, certificate-derived mTLS caller identity, caller allowlists, and shared authorization checks; legacy attestation/service-identity code is implementation debt, not target player authority | | TCP Proxy | Telnet transport, hidden bootstrap envelope, bounded connection-local ordered input buffering during edge rebind, disconnect notification, and Telnet close taxonomy | Telnet bridge; `TelnetRoutingBundle`; Game Session `NotifyDisconnect` | | Spring Cloud Gateway | Trusted TCP Proxy handshake validation, stable edge socket/session id, upstream gameplay bridge and rebind; public first-party cookie admission and shared pod readiness currently fail closed pending canonical producer/replay/key qualification. The combined readiness hold withdraws both Gateway Service endpoint families; independent route-level Service readiness remains a pre-rollout gap. | `/ws/game/**`; `TrustedTcpProxyIdentity`; current first-party cookie denial and deployment qualification in [Gateway readiness](../../architecture/microservices/spring-cloud-gateway/README.md#readiness-and-liveness) | diff --git a/dev-tools/observability/run-player-experience-smoke.py b/dev-tools/observability/run-player-experience-smoke.py index 01ee59f1a0..e42cf6ec74 100644 --- a/dev-tools/observability/run-player-experience-smoke.py +++ b/dev-tools/observability/run-player-experience-smoke.py @@ -302,6 +302,14 @@ def main() -> int: allow_unadvertised_canary_budget=requested_canary_advertised, ) establish_player_flow_canary_capability(config, initial_external_authority) + try: + validate_live_websocket_tenant_selector( + config, + declared_exposed_paths(initial_external_authority), + simulate=args.simulate, + ) + except ProbeOperationalFailure as exc: + parser.error(str(exc)) try: validate_telnet_transport_config( config, @@ -403,6 +411,7 @@ def __init__( username: str, password: str, world: str, + tenant_slug: str | None, timeout_seconds: int, startup_wait_seconds: int, external_authority_evidence: Path | None, @@ -439,6 +448,7 @@ def __init__( self.username = username self.password = password self.world = world + self.tenant_slug = tenant_slug self.timeout_seconds = timeout_seconds self.startup_wait_seconds = startup_wait_seconds self.external_authority_evidence = external_authority_evidence @@ -503,6 +513,9 @@ def from_env( ) if telnet_ca_file is None and os.environ.get("PLAYER_EXPERIENCE_TELNET_CA_FILE"): telnet_ca_file = Path(os.environ["PLAYER_EXPERIENCE_TELNET_CA_FILE"]) + tenant_slug = os.environ.get("PLAYER_EXPERIENCE_TENANT_SLUG") + if tenant_slug is not None: + tenant_slug = tenant_slug.strip() or None return cls( source=source, canary_path=canary_path, @@ -534,6 +547,7 @@ def from_env( username=os.environ.get("SMOKE_USERNAME", DEFAULT_SMOKE_USERNAME), password=os.environ.get("SMOKE_PASSWORD", DEFAULT_SMOKE_PASSWORD), world=os.environ.get("PLAYER_EXPERIENCE_WORLD", "demo"), + tenant_slug=tenant_slug, timeout_seconds=int(os.environ.get("SMOKE_TIMEOUT_SECONDS", "10")), startup_wait_seconds=int(os.environ.get("SMOKE_STARTUP_WAIT_SECONDS", "90")), external_authority_evidence=external_authority_evidence, @@ -2051,9 +2065,12 @@ def issue_player_bootstrap(config: SmokeConfig) -> dict[str, Any]: def resolve_connect_scope_id(config: SmokeConfig, bootstrap_token: str) -> str: + require_tenant_selector(config) response = http_request_json( public_auth_url( - config, f"/auth/bootstrap/worlds/{quote_path(config.world)}/realms" + config, + f"/auth/bootstrap/worlds/{quote_path(config.world)}/realms" + + "?" + urlencode({"tenantSlug": config.tenant_slug}) ), config.timeout_seconds, headers={"Authorization": f"Bearer {bootstrap_token}"}, @@ -2066,17 +2083,39 @@ def resolve_connect_scope_id(config: SmokeConfig, bootstrap_token: str) -> str: ) +def require_tenant_selector(config: SmokeConfig) -> None: + if not config.tenant_slug or not config.tenant_slug.strip(): + raise ProbeOperationalFailure( + "PLAYER_EXPERIENCE_TENANT_SLUG must select the world's tenant; world slugs are not global" + ) + + +def validate_live_websocket_tenant_selector( + config: SmokeConfig, exposed_paths: set[str], *, simulate: bool +) -> None: + """Preflight tenant selection when a live WebSocket smoke will execute.""" + if simulate or "websocket" not in exposed_paths: + return + if config.prometheus_mirrors == "published" or canary_producer_is_authorized(config): + require_tenant_selector(config) + + def require_visible_world(config: SmokeConfig, bootstrap_token: str) -> None: + require_tenant_selector(config) response = http_request_json( public_auth_url(config, "/auth/bootstrap/worlds"), config.timeout_seconds, headers={"Authorization": f"Bearer {bootstrap_token}"}, ) for world in response["data"]: - if world.get("worldSlug") == config.world: + if ( + world.get("worldSlug") == config.world + and world.get("tenantSlug") == config.tenant_slug + ): return raise ProbeOperationalFailure( - f"World {config.world!r} was not visible during bootstrap discovery" + f"World {config.world!r} for tenant {config.tenant_slug!r} " + "was not visible during bootstrap discovery" ) diff --git a/dev-tools/smoke/smoke_common.py b/dev-tools/smoke/smoke_common.py index 87cb14f20e..31384254e6 100644 --- a/dev-tools/smoke/smoke_common.py +++ b/dev-tools/smoke/smoke_common.py @@ -16,6 +16,18 @@ class ProbeOperationalFailure(RuntimeError): """An expected transport, upstream, or protocol failure from a live probe.""" +class ExplicitProtocolFailure(ProbeOperationalFailure): + """A protocol rejection, preserving exact response evidence without parsing logs.""" + + def __init__(self, response): + super().__init__(f"Command failed explicitly: {response}") + self.response = response + + +class PlayEntitlementUnavailable(ProbeOperationalFailure): + """Direct backend PLAY rejected after a successful LOGIN; never runtime success.""" + + class ProbeCommandTimeout(ProbeOperationalFailure): """The bounded command-response deadline expired without its expected output.""" @@ -301,6 +313,15 @@ def run_transport_session( if time.time() >= deadline: raise continue + except PlayEntitlementUnavailable: + # The temporary CI classification also requires a clean transport close. + try: + session.close() + except Exception as close_exc: + raise ProbeOperationalFailure( + f"Failed to close {session_label} after known PLAY refusal: {close_exc}" + ) from close_exc + raise except retriable_exceptions as exc: try: session.close() @@ -448,7 +469,7 @@ def raise_for_explicit_failure( diagnostic_response = (sanitize_response(response) if sanitize_response else response).strip() if retry_upstream_failure and failure_line.startswith(retryable_upstream_prefixes): raise TransientUpstreamSmokeFailure(f"Command failed explicitly: {diagnostic_response}") - raise ProbeOperationalFailure(f"Command failed explicitly: {diagnostic_response}") + raise ExplicitProtocolFailure(diagnostic_response) def wait_for_incremental_response( @@ -860,19 +881,30 @@ def send_websocket_command_and_expect( ws.settimeout(remaining_timeout) ws.send(line) remaining_timeout = max(0, command_deadline - time.time()) - response = wait_for_incremental_response( - lambda: recv_optional_websocket_chunk(ws, f"{label} response chunk", deadline=command_deadline), - responses, - start_index, - expected_substrings, - remaining_timeout, - lambda parts: "\n".join(chunk for chunk in parts if chunk), - lambda: drain_available_websocket(ws, responses, deadline=command_deadline), - retry_upstream_failure=(retry_upstream_failure and label in RETRYABLE_STARTUP_COMMAND_LABELS), - sanitize_response=lambda value: redact_login_credential(value, line), - deadline=command_deadline, - retryable_upstream_prefixes=retryable_upstream_prefixes, - ) + try: + response = wait_for_incremental_response( + lambda: recv_optional_websocket_chunk(ws, f"{label} response chunk", deadline=command_deadline), + responses, + start_index, + expected_substrings, + remaining_timeout, + lambda parts: "\n".join(chunk for chunk in parts if chunk), + lambda: drain_available_websocket(ws, responses, deadline=command_deadline), + retry_upstream_failure=(retry_upstream_failure and label in RETRYABLE_STARTUP_COMMAND_LABELS), + sanitize_response=lambda value: redact_login_credential(value, line), + deadline=command_deadline, + retryable_upstream_prefixes=retryable_upstream_prefixes, + ) + except ExplicitProtocolFailure as exc: + if (label == "PLAY" and line.startswith("PLAY ") + and exc.response in { + "ERROR ENTITLEMENT_UNAVAILABLE", + "ERROR ENTITLEMENT_UNAVAILABLE Gameplay entitlement is temporarily unavailable. Retry PLAY shortly.", + } + and step_results and step_results[-1]["label"] == "LOGIN" + and step_results[-1]["response"].startswith("OK LOGIN")): + raise PlayEntitlementUnavailable(exc.response) from exc + raise diagnostic_response = redact_login_credential(response, line) print(f"=== {label} response ===") print(diagnostic_response.strip() or "") diff --git a/dev-tools/tests/architecture-doc-contracts.sh b/dev-tools/tests/architecture-doc-contracts.sh index 0c6f7b45b3..37a750bcab 100644 --- a/dev-tools/tests/architecture-doc-contracts.sh +++ b/dev-tools/tests/architecture-doc-contracts.sh @@ -1015,8 +1015,10 @@ require_contains( "design/architecture/system-architecture-cicd.md", [ "builds pull-request images locally and runs the explicit held-admission qualification without a registry-write token", - "This proves direct backend `LOGIN` -> `PLAY` -> `LOOK` and Gateway/Telnet fail-closed behavior", - "it does not establish successful public admission", + "Successful smoke preserves direct backend `LOGIN` -> `PLAY` -> `LOOK` proof and verifies Gateway/Telnet fail closed; it does not establish successful public admission.", + "The diagnostic exception below provides no passing `PLAY` or `LOOK` proof.", + "image export and upload must be skipped", + "Trusted `main`/`develop` branch publication still requires real passing `LOGIN` → `PLAY` → `LOOK` smoke and cannot use this exception;", "publish-pr-runtime-images.yml", "pr-merge-", "never checks out or executes PR source", diff --git a/dev-tools/tests/hosted-identity-controller-workflow-contract.sh b/dev-tools/tests/hosted-identity-controller-workflow-contract.sh index 1643550e98..535f7d75c6 100644 --- a/dev-tools/tests/hosted-identity-controller-workflow-contract.sh +++ b/dev-tools/tests/hosted-identity-controller-workflow-contract.sh @@ -335,15 +335,30 @@ stop_smoke_step = runtime_steps_by_name["Stop smoke stack"] assert "Build controller image for credential-free local validation" not in runtime_steps_by_name assert "Smoke controller image entrypoint and paused health" not in runtime_steps_by_name assert "if" not in build_runtime_step -assert "if" not in export_step -assert "if" not in upload_step +# A passed job under the bounded PLAY exception must not export images. +# Gate publication on the native smoke outcome, never its continued conclusion. +artifact_gate = ( + "${{ success() && (needs.image-meta.outputs.runtime_smoke_required == 'false' " + "|| steps.runtime-smoke.outcome == 'success') }}" +) +assert export_step["if"] == artifact_gate +assert upload_step["if"] == artifact_gate +assert runtime_steps_by_name["Summarize secure PR runtime artifact"]["if"] == artifact_gate +assert upload_step["id"] == "runtime-artifact" +assert runtime_job["outputs"]["publishable"] == ( + "${{ steps.runtime-artifact.outcome == 'success' }}" +) +assert run_smoke_step["id"] == "runtime-smoke" +assert run_smoke_step["continue-on-error"] is True +assert run_smoke_step["env"]["FIREMUD_SMOKE_ADMISSION_QUALIFICATION"] == "held" smoke_gate = "${{ needs.image-meta.outputs.runtime_smoke_required == 'true' }}" assert setup_smoke_python_step["if"] == smoke_gate assert setup_smoke_python_step["uses"] == "./.github/actions/setup-python" assert setup_smoke_python_step["with"] == {"requirements": "smoke"} assert run_smoke_step["if"] == smoke_gate assert dump_logs_step["if"] == ( - "${{ failure() && needs.image-meta.outputs.runtime_smoke_required == 'true' " + "${{ always() && steps.runtime-smoke.outcome == 'failure' && " + "needs.image-meta.outputs.runtime_smoke_required == 'true' " "&& steps.minio-source.outputs.server_image_id != '' " "&& steps.minio-source.outputs.client_image_id != '' }}" ) @@ -353,6 +368,35 @@ assert stop_smoke_step["if"] == ( "&& steps.minio-source.outputs.client_image_id != '' }}" ) +assert stop_smoke_step["id"] == "runtime-cleanup" +exception_step = runtime_steps_by_name[ + "Known canonical transition PLAY failure with successful authenticated cleanup" +] +assert exception_step["id"] == "canonical-play-transition" +for condition in ( + "always()", + "github.repository == 'benhook1013/FireMUD'", + "contains(github.event.pull_request.labels.*.name, 'canonical-play-transition')", + "needs.image-meta.outputs.runtime_smoke_required == 'true'", + "steps.runtime-smoke.outcome == 'failure'", + "steps.runtime-smoke.outputs.known_play_failure == 'direct-backend-play-entitlement-unavailable-after-login'", + "steps.runtime-cleanup.outcome == 'success'", +): + assert condition in exception_step["if"], condition +guard = runtime_steps_by_name["Require successful runtime smoke and authenticated cleanup"] +assert guard["if"] == "${{ always() }}" +assert guard["env"] == { + "RUNTIME_SMOKE_REQUIRED": "${{ needs.image-meta.outputs.runtime_smoke_required }}", + "RUNTIME_SMOKE_OUTCOME": "${{ steps.runtime-smoke.outcome }}", + "RUNTIME_CLEANUP_OUTCOME": "${{ steps.runtime-cleanup.outcome }}", + "KNOWN_PLAY_EXCEPTION_OUTCOME": "${{ steps.canonical-play-transition.outcome }}", +} +# Executed success/failure, skipped, cancelled and malformed-outcome guard cases +# are exercised by pr-required-gate-context-contract.sh. +assert "needs.pr-local-smoke.outputs.publishable == 'true'" in ( + workflow["jobs"]["dispatch-pr-runtime-publication"]["if"] +) + controller_job = workflow["jobs"]["pr-controller-smoke"] assert controller_job["needs"] == ["image-meta"] assert "needs.image-meta.outputs.controller_smoke_required == 'true'" in ( diff --git a/dev-tools/tests/player-experience-smoke-runner-contract.sh b/dev-tools/tests/player-experience-smoke-runner-contract.sh index d79df6903f..6d27e40a62 100644 --- a/dev-tools/tests/player-experience-smoke-runner-contract.sh +++ b/dev-tools/tests/player-experience-smoke-runner-contract.sh @@ -35,6 +35,7 @@ SMOKE_CONFIG_ENV_UNSETS=( -u SMOKE_USERNAME -u SMOKE_PASSWORD -u PLAYER_EXPERIENCE_WORLD + -u PLAYER_EXPERIENCE_TENANT_SLUG -u SMOKE_TIMEOUT_SECONDS -u SMOKE_STARTUP_WAIT_SECONDS -u PLAYER_EXPERIENCE_AUTH_API_BASE @@ -49,6 +50,7 @@ env "${SMOKE_CONFIG_ENV_UNSETS[@]}" \ PLAYER_EXPERIENCE_QUERYABILITY_FRESHNESS_BUDGET_SECONDS=7200 \ python3 - "$ROOT_DIR" <<'PY' import importlib.util +import io import sys from pathlib import Path from unittest.mock import patch @@ -82,6 +84,141 @@ assert env_config.telnet_transport is None assert env_config.telnet_server_hostname is None assert env_config.telnet_ca_file is None +# A live WebSocket mirror or authorized canary must have tenant scope before +# readiness, account, bootstrap, or transport requests begin. +try: + runner_module.validate_live_websocket_tenant_selector( + env_config, {"websocket"}, simulate=False + ) +except runner_module.ProbeOperationalFailure as exc: + assert "PLAYER_EXPERIENCE_TENANT_SLUG" in str(exc) +else: + raise AssertionError("live WebSocket evidence accepted a missing tenant selector") +runner_module.validate_live_websocket_tenant_selector( + env_config, {"websocket"}, simulate=True +) +runner_module.validate_live_websocket_tenant_selector( + env_config, {"telnet"}, simulate=False +) +omitted_websocket = runner_module.SmokeConfig.from_env( + "contract-test", "websocket", None, prometheus_mirrors="omitted", + player_flow_canary="omitted", +) +runner_module.validate_live_websocket_tenant_selector( + omitted_websocket, {"websocket"}, simulate=False +) +authorized_canary = runner_module.SmokeConfig.from_env( + "contract-test", "websocket", None, prometheus_mirrors="omitted", + player_flow_canary="advertised", +) +authorized_canary.username = "non-default@example.com" +authorized_canary.password = "non-default-password" +authorized_canary.player_flow_canary_identity = { + "authority": "account-service", + "classification": "synthetic", + "analyticsSloExclusion": True, + "credentials": {"nonDefault": True, "productionSafe": True}, + "transportCharacters": { + "websocket": {"restricted": True, "isolated": True} + }, + "evidenceRef": "account://contract-test/synthetic-canary", +} +authorized_canary._validated_player_flow_canary_paths = frozenset({"websocket"}) +with patch.object(runner_module, "AUTHORITATIVE_CANARY_IDENTITY_VERIFIER_AVAILABLE", True): + try: + runner_module.validate_live_websocket_tenant_selector( + authorized_canary, {"websocket"}, simulate=False + ) + except runner_module.ProbeOperationalFailure as exc: + assert "PLAYER_EXPERIENCE_TENANT_SLUG" in str(exc) + else: + raise AssertionError("authorized live WebSocket canary accepted missing tenant selector") + +# The CLI fails during configuration preflight, before any live readiness or +# account/auth request can be attempted. +with patch.object(runner_module.sys, "argv", [ + str(root / "run-player-experience-smoke.py"), + "--external-authority-evidence", "/tmp/contract-authority.json", + "--player-flow-canary", "omitted", + "--queryability-profile", "staging", + "--queryability-freshness-budget-seconds", "7200", + "--evidence-out", "/tmp/contract-evidence.json", +]): + with patch.object( + runner_module, "resolve_external_authority", + return_value={"profile": "independent-omitted", "exposedPublicPlayerPaths": ["websocket"]}, + ), patch.object(runner_module, "wait_for_account_schema") as wait_schema, patch.object( + runner_module, "wait_for_http_readiness" + ) as wait_http, patch.object(runner_module, "verify_smoke_account") as verify_account, patch.object( + runner_module, "http_request_json" + ) as auth_request, patch.object( + runner_module, "http_request_json_with_headers" + ) as auth_request_with_headers, patch.object( + runner_module, "execute_smoke" + ) as execute: + stderr = io.StringIO() + try: + with patch("sys.stderr", stderr): + runner_module.main() + except SystemExit as exc: + assert exc.code == 2 + else: + raise AssertionError("live CLI did not reject a missing WebSocket tenant selector") + assert "PLAYER_EXPERIENCE_TENANT_SLUG" in stderr.getvalue() + wait_schema.assert_not_called() + wait_http.assert_not_called() + verify_account.assert_not_called() + auth_request.assert_not_called() + auth_request_with_headers.assert_not_called() + execute.assert_not_called() + +# Browser world selection remains qualified even when another tenant reuses its slug. +assert env_config.tenant_slug is None +with patch.object(runner_module, "http_request_json") as request: + try: + runner_module.resolve_connect_scope_id(env_config, "bootstrap") + except runner_module.ProbeOperationalFailure as exc: + assert "PLAYER_EXPERIENCE_TENANT_SLUG" in str(exc) + else: + raise AssertionError("Bare browser world selector was accepted") + request.assert_not_called() +with patch.dict("os.environ", {"PLAYER_EXPERIENCE_TENANT_SLUG": " tenant-b \t"}): + qualified = runner_module.SmokeConfig.from_env("contract-test", "websocket", None) +assert qualified.tenant_slug == "tenant-b" +with patch.object(runner_module, "http_request_json", return_value={"data": [ + {"worldSlug": qualified.world, "tenantSlug": qualified.tenant_slug} +]}) as request: + runner_module.require_visible_world(qualified, "bootstrap") + request.assert_called_once() +with patch.object(runner_module, "http_request_json", return_value={"data": [ + {"worldSlug": qualified.world, "tenantSlug": "tenant-a"} +]}) as request: + try: + runner_module.require_visible_world(qualified, "bootstrap") + except runner_module.ProbeOperationalFailure as exc: + assert qualified.world in str(exc) + assert qualified.tenant_slug in str(exc) + else: + raise AssertionError("Another tenant's world satisfied discovery") +with patch.object(runner_module, "http_request_json", return_value={"data": [ + {"realmSlug": qualified.realm_slug, "connectScopeId": "qualified-scope"} +]}) as request: + assert runner_module.resolve_connect_scope_id(qualified, "bootstrap") == "qualified-scope" + assert request.call_args.args[0].endswith("/realms?tenantSlug=tenant-b") +with patch.dict("os.environ", {"PLAYER_EXPERIENCE_TENANT_SLUG": " \t "}): + whitespace_only = runner_module.SmokeConfig.from_env( + "contract-test", "websocket", None + ) +assert whitespace_only.tenant_slug is None +with patch.object(runner_module, "http_request_json") as request: + try: + runner_module.resolve_connect_scope_id(whitespace_only, "bootstrap") + except runner_module.ProbeOperationalFailure as exc: + assert "PLAYER_EXPERIENCE_TENANT_SLUG" in str(exc) + else: + raise AssertionError("Whitespace-only tenant selector was accepted") + request.assert_not_called() + runner_module.validate_telnet_transport_config( env_config, {"websocket"}, simulate=False ) diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 5434f2e111..4a6bad2355 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -495,7 +495,9 @@ trap 'rm -rf "$tmp_dir"' EXIT smoke_clock_fixture="$tmp_dir/smoke-clock.js" python3 - "$ROOT_DIR" "$smoke_clock_fixture" <<'PY' from pathlib import Path +import base64 import hashlib +import json import re import sys import yaml @@ -520,13 +522,50 @@ if fingerprint is None or fingerprint[1] != expected: "Smoke Gate producer fingerprint is stale: after reviewing runtime-images.yml, update " f"canonicalRuntimeWorkflowSha256 in smoke.yml to {expected} and rerun this contract." ) +classifier_paths = ( + "dev-tools/verify-smoke-images.sh", + "dev-tools/smoke/smoke_common.py", + "services/game-session-service/websocket-login-look-smoke.sh", + "dev-tools/smoke/demo-smoke-defaults.sh", + "dev-tools/smoke/held-admission-qualification.sh", + "dev-tools/smoke/held_admission_qualification.py", + "dev-tools/smoke/run-owned-compose.sh", + "dev-tools/certs/ensure-dev-certs.sh", + ".env.sample", + "docker/docker-compose.yml", + "docker/docker-compose.override.yml", + "docker/docker-compose.smoke-images.override.yml", + "docker/docker-compose.pr-local-minio.override.yml", + "docker/docker-compose.grpc-mtls.override.yml", +) +classifier_fingerprints = re.search(r"const canonicalPlayClassifierSha256 = (\{[\s\S]*?\});", script) +if classifier_fingerprints is None: + raise SystemExit("Smoke Gate must fingerprint the canonical PLAY classifier files") +classifiers = json.loads(classifier_fingerprints[1]) +if set(classifiers) != set(classifier_paths): + raise SystemExit("Smoke Gate PLAY classifier fingerprint paths must match the canonical classifier, qualification, cleanup, and configuration inputs") +classifier_definitions = {} +for path in classifier_paths: + classifier_bytes = (root / path).read_bytes() + expected = hashlib.sha256(classifier_bytes).hexdigest() + if classifiers[path] != expected: + raise SystemExit( + f"Smoke Gate PLAY classifier fingerprint is stale: after reviewing {path}, update " + f"canonicalPlayClassifierSha256 in smoke.yml to {expected} for that path and rerun this contract." + ) + classifier_definitions[path] = { + "type": "file", "path": path, "encoding": "base64", + "content": base64.b64encode(classifier_bytes).decode("ascii"), "size": len(classifier_bytes), + } +Path(sys.argv[2] + ".classifiers.json").write_text(json.dumps(classifier_definitions)) producer_job = producer["jobs"]["pr-local-smoke"] +if producer["jobs"]["image-meta"]["outputs"].get("canonical_play_transition") != "${{ steps.meta.outputs.canonical_play_transition }}": + raise SystemExit("Typed-refresh PLAY marker authority must come from verified image metadata") cancelled_inventory = re.search( r"const preExecutionCancelledJobNames = new Set\(\[([\s\S]*?)\]\);", script ) if cancelled_inventory is None: raise SystemExit("Smoke Gate must declare its bounded pre-execution cancellation inventory") -import json producer_job_names = [job["name"] for job in producer["jobs"].values()] Path(sys.argv[2] + ".cancelled-job-names.json").write_text(json.dumps(producer_job_names)) if producer_job["name"] != "PR Full-Stack Smoke (runtime-required=${{ needs.image-meta.outputs.runtime_smoke_required }})": @@ -535,8 +574,14 @@ steps = producer_job["steps"] smoke_step = next(step for step in steps if step.get("id") == "runtime-smoke") cleanup_step = next(step for step in steps if step.get("id") == "runtime-cleanup") guard = steps[-1] -if any(step.get("continue-on-error") not in (None, "false") for step in (smoke_step, cleanup_step, guard)): - raise SystemExit("Runtime smoke, cleanup, and terminal guard cannot ignore failures") +if smoke_step.get("continue-on-error") != "true": + raise SystemExit("Probe failure must reach the exact transition terminal guard") +if any(step.get("continue-on-error") not in (None, "false") for step in (cleanup_step, guard)): + raise SystemExit("Cleanup and terminal enforcement cannot ignore failures") +for name in ("Export fixed-tag preview image artifact", "Upload preview image artifact", "Summarize secure PR runtime artifact"): + artifact = next(step for step in steps if step.get("name") == name) + if artifact.get("if") != "${{ success() && (needs.image-meta.outputs.runtime_smoke_required == 'false' || steps.runtime-smoke.outcome == 'success') }}": + raise SystemExit("Failed probe must never export, upload or summarize publishable images") if smoke_step["run"] != "bash ./dev-tools/verify-smoke-images.sh --keep-running": raise SystemExit("Native smoke outcome must belong to the canonical smoke invocation") if guard["if"] != "${{ always() }}" or guard["name"] != "Require successful runtime smoke and authenticated cleanup": @@ -545,9 +590,23 @@ if guard["env"] != { "RUNTIME_SMOKE_REQUIRED": "${{ needs.image-meta.outputs.runtime_smoke_required }}", "RUNTIME_SMOKE_OUTCOME": "${{ steps.runtime-smoke.outcome }}", "RUNTIME_CLEANUP_OUTCOME": "${{ steps.runtime-cleanup.outcome }}", + "KNOWN_PLAY_EXCEPTION_OUTCOME": "${{ steps.canonical-play-transition.outcome }}", }: raise SystemExit("Terminal guard must consume native Actions outcomes, never command-written outputs") Path(sys.argv[2] + ".guard").write_text(guard["with"]["script"]) +marker = next(step for step in steps if step.get("name") == "Known canonical transition PLAY failure with successful authenticated cleanup") +for clause in ( + "always()", "github.event_name == 'pull_request'", "github.repository == 'benhook1013/FireMUD'", + "contains(github.event.pull_request.labels.*.name, 'canonical-play-transition')", "needs.image-meta.outputs.runtime_smoke_required == 'true'", + "github.event_name == 'repository_dispatch'", "github.event.action == 'pr-runtime-base-refresh'", + "needs.image-meta.outputs.canonical_play_transition == 'true'", + "steps.runtime-smoke.outcome == 'failure'", "steps.runtime-cleanup.outcome == 'success'", + "steps.runtime-smoke.outputs.known_play_failure == 'direct-backend-play-entitlement-unavailable-after-login'", +): + if clause not in marker["if"]: + raise SystemExit(f"Temporary PLAY marker lacks fail-closed clause: {clause}") +Path(sys.argv[2] + ".marker").write_text(marker["if"]) +Path(sys.argv[2] + ".producer").write_bytes((root / ".github/workflows/runtime-images.yml").read_bytes()) Path(sys.argv[2]).write_text(script) PY @@ -721,6 +780,19 @@ for (const required of ["false", "", "unknown"]) { guard({env: {RUNTIME_SMOKE_REQUIRED: required}}, {setFailed: message => failures.push(message)}); assert.equal(failures.length === 0, required === "false"); } +for (const smoke of ["success", "failure", "skipped", "cancelled", ""]) { + for (const cleanup of ["success", "failure", "skipped", "cancelled", ""]) { + for (const marker of ["success", "failure", "skipped", ""]) { + const failures = [], warnings = []; + guard({env: {RUNTIME_SMOKE_REQUIRED: "true", RUNTIME_SMOKE_OUTCOME: smoke, + RUNTIME_CLEANUP_OUTCOME: cleanup, KNOWN_PLAY_EXCEPTION_OUTCOME: marker}}, + {setFailed: message => failures.push(message), warning: message => warnings.push(message)}); + const exception = smoke === "failure" && marker === "success" && cleanup === "success"; + assert.equal(failures.length === 0, cleanup === "success" && (smoke === "success" || exception)); + assert.equal(warnings.length, Number(exception)); + } + } +} const execute = new Function("github", "context", "core", "Date", "setTimeout", "require", `return (async () => {\n${script}\n})()`); const head = "a".repeat(40), base = "b".repeat(40), merge = "c".repeat(40), defaultSha = "d".repeat(40); const repository = "example/firemud"; @@ -740,7 +812,10 @@ async function scenario(kind, event = "pull_request") { status: "completed", conclusion: "success", pull_requests: []}; const job = {id: 100, run_id: 42, run_attempt: 1, head_sha: source.head_sha, check_run_url: `https://api.github.com/repos/${repository}/check-runs/100`, - name: "PR Full-Stack Smoke (runtime-required=true)", status: "completed", conclusion: "success", steps: []}; + name: "PR Full-Stack Smoke (runtime-required=true)", status: "completed", conclusion: "success", + steps: [{name: "Known canonical transition PLAY failure with successful authenticated cleanup", status: "completed", conclusion: "skipped"}]}; + if (kind === "marker-missing") job.steps = []; + if (kind === "marker-success") job.steps[0].conclusion = "success"; if (kind.startsWith("legacy")) job.name = "PR Full-Stack Smoke"; if (kind === "not-required") job.name = "PR Full-Stack Smoke (runtime-required=false)"; if (kind === "step-skipped") job.steps = [{name: "Run credential-free full-stack smoke", status: "completed", conclusion: "skipped"}]; @@ -808,7 +883,7 @@ async function scenario(kind, event = "pull_request") { assert.deepEqual(success.refs, [event === "pull_request" ? merge : defaultSha], "immutable definition must come from actual source event revision"); } assert.deepEqual((await scenario("legacy-positive")).failures, []); - for (const kind of ["legacy-missing", "not-required", "step-skipped", "wrong-repository", "wrong-workflow", + for (const kind of ["marker-missing", "marker-success", "legacy-missing", "not-required", "step-skipped", "wrong-repository", "wrong-workflow", "wrong-path", "wrong-event", "wrong-head", "wrong-head-repository", "wrong-title", "wrong-source-attempt", "changed-definition", "unavailable-definition", "wrong-job", "wrong-job-run", "wrong-job-attempt", "wrong-job-head", "wrong-check-url", "failed-job", "pending-job", "duplicate-jobs", "duplicate-attempt-jobs", "newer-attempt", "bad-parents"]) { @@ -3356,3 +3431,260 @@ PY_PUBLISH done echo "Required-gate status producer contract checks passed" + +# Exercise the temporary failed-producer verifier separately: passing producer +# proof above is unchanged and remains the only runtime qualification path. +node - "$smoke_clock_fixture" "$ROOT_DIR/.github/workflows/smoke.yml" <<'NODE' +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const script = fs.readFileSync(process.argv[2], "utf8"); +const icons = [...fs.readFileSync(process.argv[3], "utf8").matchAll(/const statusIcon = \(value\) => \{[\s\S]*?\n\s*\};/g)]; +assert.equal(icons.length, 2); +for (const [declaration] of icons) { + const statusIcon = new Function(`${declaration}; return statusIcon;`)(); + assert.equal(statusIcon("failure (known temporary PLAY exception)"), "❌"); + assert.equal(statusIcon("failure"), "❌"); + assert.equal(statusIcon("success"), "✅"); + assert.equal(statusIcon("cancelled"), "⚪"); + assert.equal(statusIcon("skipped"), "⏭️"); +} +const bytes = fs.readFileSync(process.argv[2] + ".producer"); +const start = script.indexOf("async function verifyKnownPlayFailure("); +const end = script.indexOf("// Commit objects", start); +const fn = script.slice(start, end); +const workflowPath = ".github/workflows/runtime-images.yml"; +const repositoryName = "benhook1013/FireMUD"; +const canonicalSmokeJobName = "PR Full-Stack Smoke (runtime-required=true)"; +const canonicalRuntimeWorkflowSha256 = require("node:crypto").createHash("sha256").update(bytes).digest("hex"); +// Separate test authority lets the same verifier exercise both immutable modes. +const canonicalLegacyRuntimeWorkflowSha256 = "0".repeat(64); +const canonicalPlayClassifierSha256 = JSON.parse(script.match(/const canonicalPlayClassifierSha256 = (\{[\s\S]*?\});/)[1]); +const classifierDefinitions = JSON.parse(fs.readFileSync(process.argv[2] + ".classifiers.json", "utf8")); +const headSha = "a".repeat(40), baseSha = "b".repeat(40), mergeSha = "c".repeat(40); +const workflowSha = "d".repeat(40); +const identity = {headSha, baseSha, mergeSha, baseRef: "develop"}; +const run = {id: 99, run_attempt: 2, event: "pull_request"}; +const failures = ["Run credential-free full-stack smoke", "Require successful runtime smoke and authenticated cleanup"]; +const step = (name, conclusion) => ({name, conclusion, status: "completed"}); +const source = {...run, status: "completed", conclusion: "success", path: workflowPath, + repository: {full_name: repositoryName}, workflow_id: 7, head_repository: {full_name: repositoryName}, head_sha: headSha, + display_title: `Build Runtime Images secure-pr-artifact pr-3390 base-${baseSha} head-${headSha} merge-${mergeSha} mode-required`}; +const candidate = {id: 123, run_id: 99, run_attempt: 2, head_sha: headSha, name: canonicalSmokeJobName, + status: "completed", conclusion: "success", check_run_url: `https://api.github.com/repos/${repositoryName}/check-runs/123`, + steps: [...failures.map(name => step(name, "success")), step("Stop smoke stack", "success"), + step("Known canonical transition PLAY failure with successful authenticated cleanup", "success"), + step("Export fixed-tag preview image artifact", "skipped"), step("Upload preview image artifact", "skipped")]}; +async function verify(mutate = () => {}, event = "pull_request") { + const data = structuredClone({pr: "3390", consumerRepository: repositoryName, run, identity, source, candidate, jobs: [candidate], latest: {...source}, + eventHeadRepository: repositoryName, + currentPullRequest: {state: "open", head: {sha: headSha, repo: {full_name: repositoryName}}, + base: {ref: "develop", repo: {full_name: repositoryName}}, merge_commit_sha: mergeSha, + labels: [{name: "canonical-play-transition"}]}, + currentBase: {ref: "refs/heads/develop", object: {sha: baseSha}}, + definitions: {...classifierDefinitions, + [workflowPath]: {type: "file", path: workflowPath, encoding: "base64", content: bytes.toString("base64"), size: bytes.length}}}); + if (event === "repository_dispatch") { + data.run.event = data.source.event = data.latest.event = event; + data.source.head_branch = data.latest.head_branch = "develop"; + data.source.head_sha = data.latest.head_sha = workflowSha; + data.candidate.head_sha = data.jobs[0].head_sha = workflowSha; + } + mutate(data); + const contentRequests = []; + const github = {request: async () => ({data: data.source}), paginate: async () => data.jobs, + rest: {actions: {getWorkflow: async () => ({data: {id: 7, path: workflowPath, name: "Build Runtime Images"}}), + getWorkflowRun: async () => ({data: data.latest})}, pulls: {get: async () => ({data: data.currentPullRequest})}, + git: {getRef: async ({ref}) => {assert.equal(ref, `heads/${data.identity.baseRef}`); return {data: data.currentBase};}}, + repos: {getContent: async ({owner, repo, path, ref}) => { + assert.equal(`${owner}/${repo}`, repositoryName); + assert.equal(ref, path === workflowPath && event === "repository_dispatch" ? workflowSha : mergeSha, + "workflow attestation must use its executed revision; classifier attestation must use the verified merge"); + contentRequests.push(path); + if (!data.definitions[path]) throw Object.assign(new Error("definition unavailable"), {status: 404}); + return {data: data.definitions[path]}; + }}}}; + const accepted = await new Function("github", "prNumber", "repositoryName", "canonicalSmokeJobName", "workflowPath", + "canonicalRuntimeWorkflowSha256", "canonicalLegacyRuntimeWorkflowSha256", "canonicalPlayClassifierSha256", "positiveInteger", "withTransientGitHubRetry", "context", "owner", "repo", "require", "data", + `${fn}; return verifyKnownPlayFailure(data.run, data.candidate, data.identity);`)( + github, data.pr, data.consumerRepository, canonicalSmokeJobName, workflowPath, canonicalRuntimeWorkflowSha256, data.legacyDefinition ? canonicalRuntimeWorkflowSha256 : canonicalLegacyRuntimeWorkflowSha256, canonicalPlayClassifierSha256, + value => Number.isSafeInteger(value) && value > 0, (_label, call) => call(), + {payload: {repository: {default_branch: "develop"}, pull_request: {head: {repo: {full_name: data.eventHeadRepository}}}}}, + "benhook1013", "FireMUD", require, data); + if (accepted) assert.deepEqual(contentRequests, [workflowPath, ...Object.keys(classifierDefinitions)]); + return accepted; +} +// Proof errors in a successful exception attempt must fail closed. +const failedStart = script.indexOf('// A continued probe'); +const failedEnd = script.indexOf('if (fullSmokeJob?.conclusion !== "success")', failedStart); +const failedBranch = script.slice(failedStart, failedEnd); +class TerminalGitHubRequestError extends Error {} +async function failedProof(error, event = "pull_request") { + const warnings = [], failures = [], outputs = []; + const core = {warning: value => warnings.push(value), setFailed: value => failures.push(value), + setOutput: (...value) => outputs.push(value)}; + const execute = new Function("fullSmokeJob", "matching", "canonicalSmokeJobName", "currentIdentity", + "verifyKnownPlayFailure", "TerminalGitHubRequestError", "core", + `return (async () => { smokeGatePolling: while (true) { ${failedBranch} break; } })();`); + await execute(candidate, {...source, event}, canonicalSmokeJobName, identity, + async () => {throw error;}, TerminalGitHubRequestError, core); + assert.deepEqual(failures, ["Canonical PLAY transition exception could not be verified; runtime qualification remains blocked."]); + assert.equal(warnings.length, 1); + assert.match(warnings[0], /^Canonical PLAY transition exception proof is unavailable:/); + assert.deepEqual(outputs, []); +} +// Execute the failed-run branch so proof errors retain the deterministic failure diagnostic. +const legacyFailedStart = script.indexOf('if (matching.conclusion !== "success")'); +const legacyFailedEnd = script.indexOf("const latestIdentity", legacyFailedStart); +const legacyFailedBranch = script.slice(legacyFailedStart, legacyFailedEnd); +async function failedLegacyProof(stage, error, event = "pull_request") { + const warnings = [], failures = [], outputs = []; + const github = {paginate: async () => { + if (stage === "jobs") throw error; + return stage === "malformed-jobs" ? {} : [candidate]; + }}; + const core = {warning: value => warnings.push(value), setFailed: value => failures.push(value), + setOutput: (...value) => outputs.push(value)}; + const execute = new Function("matching", "repositoryName", "github", "owner", "repo", + "canonicalSmokeJobName", "currentIdentity", "withTransientGitHubRetry", "verifyKnownPlayFailure", + "isCurrentPullRequestObsolete", "TerminalGitHubRequestError", "core", + `return (async () => { smokeGatePolling: while (true) { ${legacyFailedBranch} break; } })();`); + await execute({...source, conclusion: "failure", event}, repositoryName, github, "benhook1013", "FireMUD", canonicalSmokeJobName, + identity, (_label, call) => call(), async () => {throw error;}, async () => false, + TerminalGitHubRequestError, core); + assert.deepEqual(failures, ["Runtime images run 99 did not complete successfully: run=failure"]); + assert.equal(warnings.length, 1); + assert.match(warnings[0], /^Canonical PLAY transition exception proof is unavailable:/); + assert.deepEqual(outputs, []); +} +const markerExpression = fs.readFileSync(process.argv[2] + ".marker", "utf8").trim().slice(3, -2); +const markerValues = { + "github.event_name": "pull_request", "github.repository": repositoryName, + "github.event.action": "pr-runtime-base-refresh", + "github.event.pull_request.labels.*.name": ["canonical-play-transition"], + "needs.image-meta.outputs.canonical_play_transition": "false", + "needs.image-meta.outputs.runtime_smoke_required": "true", + "steps.runtime-smoke.outcome": "failure", "steps.runtime-smoke.outputs.known_play_failure": "direct-backend-play-entitlement-unavailable-after-login", + "steps.runtime-cleanup.outcome": "success", +}; +function markerAccepted(overrides = {}) { + let expression = markerExpression.replace("always()", "true") + .replace("contains(", "includes("); + for (const [key, value] of Object.entries({...markerValues, ...overrides})) { + expression = expression.replaceAll(key, JSON.stringify(value)); + } + return new Function("includes", `return (${expression});`)((values, value) => values.includes(value)); +} +(async () => { + for (const event of ["pull_request", "repository_dispatch"]) { + for (const stage of ["jobs", "proof", "malformed-jobs"]) { + await failedLegacyProof(stage, Object.assign(new Error("unavailable"), {status: 404}), event); + } + } + await failedLegacyProof("proof", null); + for (const event of ["pull_request", "repository_dispatch"]) { + await failedProof(Object.assign(new Error("unavailable"), {status: 404}), event); + await failedProof(null, event); + } + for (const stage of ["jobs", "proof"]) { + const terminal = new TerminalGitHubRequestError("permission denied"); + await assert.rejects(failedLegacyProof(stage, terminal), error => error === terminal); + await assert.rejects(failedProof(terminal), error => error === terminal); + } + assert.equal(markerAccepted(), true); + const refreshMarker = {"github.event_name": "repository_dispatch", + "github.event.pull_request.labels.*.name": [], "needs.image-meta.outputs.canonical_play_transition": "true"}; + assert.equal(markerAccepted(refreshMarker), true); + for (const overrides of [ + {"github.event.action": "other"}, {"needs.image-meta.outputs.canonical_play_transition": "false"}, + {"needs.image-meta.outputs.canonical_play_transition": ""}, {"steps.runtime-cleanup.outcome": "failure"}, + {"steps.runtime-smoke.outputs.known_play_failure": ""}, {"steps.runtime-smoke.outcome": "success"}, + {"needs.image-meta.outputs.runtime_smoke_required": "false"}, {"github.repository": "attacker/FireMUD"}, + ]) assert.equal(markerAccepted({...refreshMarker, ...overrides}), false); + for (const overrides of [ + {"steps.runtime-smoke.outputs.known_play_failure": ""}, + {"steps.runtime-smoke.outputs.known_play_failure": "malformed"}, + {"steps.runtime-smoke.outcome": "success"}, + {"steps.runtime-cleanup.outcome": "failure"}, + {"steps.runtime-cleanup.outcome": "skipped"}, + {"needs.image-meta.outputs.runtime_smoke_required": "false"}, + {"github.event.pull_request.labels.*.name": []}, + {"github.repository": "attacker/FireMUD"}, + {"github.event_name": "repository_dispatch"}, + {"github.event_name": "workflow_run"}, + ]) assert.equal(markerAccepted(overrides), false); + assert.equal(await verify(), true); + for (const event of ["pull_request", "repository_dispatch"]) { + assert.equal(await verify(d => { + d.legacyDefinition = true; + d.source.conclusion = d.latest.conclusion = d.candidate.conclusion = "failure"; + for (const step of d.candidate.steps) if (failures.includes(step.name)) step.conclusion = "failure"; + }, event), true, "exact old fail-red default-branch producer remains a diagnostic exception only"); + } + assert.equal(await verify(() => {}, "repository_dispatch"), true); + for (const path of Object.keys(classifierDefinitions)) { + assert.equal(await verify(d => { + const altered = Buffer.concat([Buffer.from(d.definitions[path].content, "base64"), Buffer.from("\n# altered classifier\n")]); + d.definitions[path].content = altered.toString("base64"); + d.definitions[path].size = altered.length; + }), false, `altered classifier bytes must fail closed: ${path}`); + for (const change of [ + {type: "dir"}, {path: "other-classifier"}, {encoding: "none"}, {content: null}, {size: 0}, + ]) assert.equal(await verify(d => {Object.assign(d.definitions[path], change);}), false, `${path}: ${JSON.stringify(change)}`); + await assert.rejects(verify(d => {delete d.definitions[path];}), /definition unavailable/); + } + for (const stackPr of [3405, 3409, 3407, 3408, 3410]) { + assert.equal(await verify(d => {d.pr = String(stackPr); d.source.display_title = d.source.display_title.replace("pr-3390", `pr-${stackPr}`);}), true); + } + for (const mutate of [ + d => {d.pr = "3391";}, + d => {d.consumerRepository = "attacker/FireMUD";}, + d => {d.currentPullRequest.labels = [];}, + d => {d.currentPullRequest.labels = [{name: "other"}];}, + d => {d.currentPullRequest.state = "closed";}, + d => {d.currentPullRequest.head.sha = "e".repeat(40);}, + d => {d.currentPullRequest.head.repo.full_name = "attacker/FireMUD";}, + d => {d.currentPullRequest.base.repo.full_name = "attacker/FireMUD";}, + d => {d.eventHeadRepository = "fork-owner/FireMUD"; d.source.head_repository.full_name = d.eventHeadRepository;}, + d => {d.currentPullRequest.base.ref = "main";}, + d => {d.identity.baseSha = "d".repeat(40);}, + d => {d.identity.headSha = "d".repeat(40);}, + d => {d.identity.mergeSha = "d".repeat(40);}, + d => {d.run.event = "workflow_dispatch";}, + d => {d.source.event = "workflow_run";}, + d => {d.source.run_attempt = 1;}, + d => {d.latest.run_attempt = 3; assert.equal(d.source.run_attempt, 2);}, + d => {d.latest.conclusion = "failure"; assert.equal(d.source.conclusion, "success");}, + d => {d.source.path = ".github/workflows/spoof.yml";}, + d => {d.source.repository.full_name = "attacker/FireMUD";}, + d => {d.definitions[workflowPath].content = Buffer.from("spoof").toString("base64"); d.definitions[workflowPath].size = 5;}, + d => {d.jobs.push({...d.candidate, id: 124});}, + d => {d.jobs.push({id: 2, status: "completed", conclusion: "failure"});}, + d => {d.jobs[0].steps.push(step("Unrelated failure", "failure"));}, + d => {d.jobs[0].steps.find(s => s.name === "Stop smoke stack").conclusion = "failure";}, + d => {d.jobs[0].steps.find(s => s.name.startsWith("Known canonical transition")).conclusion = "skipped";}, + d => {d.jobs[0].steps = d.jobs[0].steps.filter(s => !s.name.startsWith("Known canonical transition"));}, + d => {d.jobs[0].steps.find(s => s.name.startsWith("Export fixed")).conclusion = "success";}, + d => {d.jobs[0].steps = d.jobs[0].steps.filter(s => !s.name.startsWith("Export fixed"));}, + d => {d.source.conclusion = "failure";}, + d => {d.jobs[0].steps.find(s => s.name === "Run credential-free full-stack smoke").conclusion = "failure";}, + d => {d.jobs[0].steps.find(s => s.name === "Require successful runtime smoke and authenticated cleanup").conclusion = "failure";}, + d => {d.jobs = [];}, + d => {d.jobs[0].steps = [];}, + d => {delete d.jobs[0].steps;}, + ]) { + for (const event of ["pull_request", "repository_dispatch"]) { + assert.equal(await verify(mutate, event), false, `${event}: ${mutate.toString()}`); + } + } + for (const mutate of [ + d => {d.source.head_branch = "feature/untrusted";}, + d => {d.source.head_sha = "invalid";}, + d => {d.source.event = "pull_request";}, + d => {d.currentPullRequest.merge_commit_sha = "e".repeat(40);}, + d => {d.currentBase.object.sha = "e".repeat(40);}, + d => {d.currentBase.ref = "refs/heads/main";}, + d => {delete d.currentBase.object;}, + ]) assert.equal(await verify(mutate, "repository_dispatch"), false, mutate.toString()); + console.log("Canonical PLAY transition exception positive and negative contracts passed."); +})().catch(error => {console.error(error); process.exitCode = 1;}); +NODE diff --git a/dev-tools/tests/pr-runtime-image-publication-contract.sh b/dev-tools/tests/pr-runtime-image-publication-contract.sh index 2110584c9d..803550a80f 100644 --- a/dev-tools/tests/pr-runtime-image-publication-contract.sh +++ b/dev-tools/tests/pr-runtime-image-publication-contract.sh @@ -181,14 +181,18 @@ const title = `Build Runtime Images secure-pr-artifact pr-42 base-${sha("b")} he const repository = { full_name: "benhook1013/FireMUD", default_branch: "develop" }; const source = { id: 4242, workflow_id: 777, path: ".github/workflows/runtime-images.yml", name: title, display_title: title, event: "repository_dispatch", repository, head_repository: repository, head_branch: "develop", head_sha: sha("b"), status: "completed", conclusion: "success" }; const baseContext = { eventName: "repository_dispatch", ref: "refs/heads/develop", repo: {owner: "benhook1013", repo: "FireMUD"}, runId: 4242, payload: { repository, action: "pr-runtime-image-publication", client_payload: { source_run_id: "4242" } } }; -async function resolve({ context = baseContext, runs = [source], workflow = { id: 777, name: "Build Runtime Images", path: source.path }, error = false } = {}) { +async function resolve({ context = baseContext, runs = [source], workflow = { id: 777, name: "Build Runtime Images", path: source.path }, error = false, jobs = [] } = {}) { let reads = 0, clock = 0; const output = {}; - const github = { rest: { actions: { + const github = { paginate: async () => jobs, rest: { actions: { getWorkflow: async () => ({data: workflow}), getWorkflowRun: async request => { assert.equal(request.run_id, 4242); reads++; if (error) throw Error("API unavailable"); return {data: runs[Math.min(reads - 1, runs.length - 1)]}; }, } } }; - await resolver(github, context, {setOutput: (key, value) => {output[key] = value;}}, {now: () => {clock += 60000; return clock;}}, fn => fn()); + await resolver(github, context, {notice: () => {}, setOutput: (key, value) => {output[key] = value;}}, {now: () => {clock += 60000; return clock;}}, fn => fn()); + if (jobs.some(job => (job.steps ?? []).some(step => step.conclusion === "success"))) { + assert.deepEqual(output, {}, "exception attempts must expose no publication source"); + return {reads, output}; + } assert.equal(output.title, title); assert.equal(output.artifact_name, `pr-runtime-images-pr-merge-${sha("c")}`); assert.equal(JSON.parse(output.source).status, "completed"); @@ -224,7 +228,7 @@ const handoffCondition = runtimeWorkflow.split(" dispatch-pr-runtime-publicatio .replace(/needs\.([a-z-]+)/g, (_, key) => `needs[${JSON.stringify(key)}]`); const admitted = new Function("github", "needs", "always", "cancelled", "format", `return ${handoffCondition};`); const trigger = {event_name: "repository_dispatch", event: {action: "pr-runtime-base-refresh", repository}, ref: "refs/heads/develop"}; -const success = {"image-meta": {result: "success", outputs: {controller_smoke_required: "false"}}, "pr-local-smoke": {result: "success"}, "pr-controller-smoke": {result: "skipped"}}; +const success = {"image-meta": {result: "success", outputs: {controller_smoke_required: "false"}}, "pr-local-smoke": {result: "success", outputs: {publishable: "true"}}, "pr-controller-smoke": {result: "skipped"}}; function admits(event = trigger, results = success, cancelled = false) { return admitted(event, results, () => true, () => cancelled, (pattern, value) => pattern.replace("{0}", value)); } @@ -237,6 +241,9 @@ for (const job of ["image-meta", "pr-local-smoke", "pr-controller-smoke"]) { assert.equal(admits(trigger, {...success, "image-meta": {result: "success", outputs: {controller_smoke_required: "true"}}}), false); assert.equal(admits(trigger, {...success, "image-meta": {result: "success", outputs: {}}}), false); assert.equal(admits(trigger, success, true), false); +for (const publishable of ["false", "", undefined]) { + assert.equal(admits(trigger, {...success, "pr-local-smoke": {result: "success", outputs: {publishable}}}), false); +} (async () => { for (const path of diagnosticPaths) { assert.equal(await smokeDecision([path]), "false", `${path} must not require runtime smoke`); @@ -252,6 +259,11 @@ assert.equal(admits(trigger, success, true), false); await dispatch({rest: {repos: {createDispatchEvent: async payload => {dispatched = payload;}}}}, baseContext); assert.deepEqual(dispatched, {...baseContext.repo, event_type: "pr-runtime-image-publication", client_payload: {source_run_id: "4242"}}); const direct = await resolve(); + const exceptionJob = {name: "PR Full-Stack Smoke (runtime-required=true)", steps: [{ + name: "Known canonical transition PLAY failure with successful authenticated cleanup", + status: "completed", conclusion: "success"}]}; + assert.deepEqual((await resolve({jobs: [exceptionJob]})).output, {}); + assert.equal((await resolve({jobs: [{...exceptionJob, steps: [{...exceptionJob.steps[0], conclusion: "skipped"}]}]})).output.title, title); const pending = {...source, status: "in_progress", conclusion: null}; assert.equal((await resolve({runs: [pending, source]})).reads, 2); const callbackContext = {...baseContext, eventName: "workflow_run", payload: {repository, workflow_run: source}}; @@ -263,6 +275,7 @@ assert.equal(admits(trigger, success, true), false); assert.equal((await resolve({runs: [prSource]})).output.artifact_name, direct.output.artifact_name); assert.equal((await resolve({runs: [prSource], context: prCallback})).output.artifact_name, direct.output.artifact_name); const publisherWorkflow = fs.readFileSync(process.argv[5], "utf8"); + assert.ok(publisherWorkflow.includes("if: ${{ needs.source.outputs.source != '' }}"), "no source must skip privileged publication"); const download = publisherWorkflow.split(" - name: Download successful PR image artifacts\n")[1] .split(" - name: Validate exact PR source and artifact before registry login\n")[0]; const inputs = Object.fromEntries([...download.matchAll(/^ (name|path|run-id): (.+)$/gm)] @@ -471,6 +484,20 @@ try: assert f"base_ref={request['base']['ref']}\n" in output assert f"image_tag=pr-merge-{merge['sha']}\n" in output assert f"base_image=ghcr.io/benhook1013/firemud-base:{merge['sha']}\n" in output + assert "canonical_play_transition=false\n" in output + labeled_request = json.loads(json.dumps(request)) + labeled_request["labels"] = [{"name": "canonical-play-transition"}] + assert admit(labeled_request, merge, branch).returncode == 0 + assert "canonical_play_transition=true\n" in Path(env["GITHUB_OUTPUT"]).read_text() + # Event labels are a separate marker path; only typed-refresh admission may + # export verified live-label authority through this metadata output. + assert admit(labeled_request, merge, branch, event_name="pull_request").returncode == 0 + assert "canonical_play_transition=false\n" in Path(env["GITHUB_OUTPUT"]).read_text() + for labels in (None, [], [{"name": "other"}], "canonical-play-transition"): + unlabeled_request = {**request, "labels": labels} + assert admit(unlabeled_request, merge, branch).returncode == 0 + assert "canonical_play_transition=false\n" in Path(env["GITHUB_OUTPUT"]).read_text() + assert admit(labeled_request, merge, branch, {"EVENT_ACTION": "other"}).returncode != 0 assert branch["object"]["sha"] not in dict(line.split("=", 1) for line in output.splitlines())["base_image"] literal_marker = fixture / "must-not-execute" valid_refs = ("feature/topic+fix", "feature/@/parent", "feature/世界", "feature/#fragment", "feature/%encoded", @@ -496,7 +523,7 @@ try: assert not (fixture / "runtime-meta-ref-calls").read_text(), "invalid ref reached GitHub lookup" assert admit(request, merge, {**branch, "ref": "refs/heads/feature/other"}).returncode != 0 for mutation in ("stale-base", "stale-head", "wrong-parents", "fork", "closed", "retarget", "missing-merge", "wrong-default-ref"): - mutated_request, mutated_merge, mutated_branch = [json.loads(json.dumps(payload)) for payload in (request, merge, branch)] + mutated_request, mutated_merge, mutated_branch = [json.loads(json.dumps(payload)) for payload in (labeled_request, merge, branch)] overrides = {} if mutation == "stale-base": mutated_branch["object"]["sha"] = "d" * 40 @@ -516,6 +543,7 @@ try: overrides["GITHUB_REF"] = "refs/heads/feature/untrusted" rejected = admit(mutated_request, mutated_merge, mutated_branch, overrides) assert rejected.returncode != 0, f"runtime metadata admitted {mutation}" + assert "canonical_play_transition=true\n" not in Path(env["GITHUB_OUTPUT"]).read_text() finally: for path, original in zip(paths, originals): path.write_text(original) diff --git a/dev-tools/tests/smoke-transport-contract.sh b/dev-tools/tests/smoke-transport-contract.sh index f315ec186b..14dea193c2 100644 --- a/dev-tools/tests/smoke-transport-contract.sh +++ b/dev-tools/tests/smoke-transport-contract.sh @@ -56,6 +56,62 @@ from smoke_common import ( run_websocket_smoke_session, ) +# Typed evidence is command-local and requires successful LOGIN, not log matching. +class ClassificationSocket: + def settimeout(self, timeout): + pass + + def send(self, command): + pass + + +for label, command, response, prior, expected_type in [ + ("PLAY", "PLAY demo", "ERROR ENTITLEMENT_UNAVAILABLE", [{"label": "LOGIN", "response": "OK LOGIN"}], smoke_common.PlayEntitlementUnavailable), + ("PLAY", "PLAY demo", "ERROR ENTITLEMENT_UNAVAILABLE Gameplay entitlement is temporarily unavailable. Retry PLAY shortly.", [{"label": "LOGIN", "response": "OK LOGIN"}], smoke_common.PlayEntitlementUnavailable), + ("PLAY", "PLAY demo", "ERROR ENTITLEMENT_UNAVAILABLE extra", [{"label": "LOGIN", "response": "OK LOGIN"}], smoke_common.ExplicitProtocolFailure), + ("PLAY", "PLAY demo", "ERROR ENTITLEMENT_UNAVAILABLE Gameplay entitlement is temporarily unavailable. Retry PLAY shortly. more", [{"label": "LOGIN", "response": "OK LOGIN"}], smoke_common.ExplicitProtocolFailure), + ("PLAY", "PLAY demo", "ERROR ENTITLEMENT_UNAVAILABLE Another message.", [{"label": "LOGIN", "response": "OK LOGIN"}], smoke_common.ExplicitProtocolFailure), + ("PLAY", "PLAY demo", "ERROR UNAVAILABLE", [{"label": "LOGIN", "response": "OK LOGIN"}], smoke_common.ExplicitProtocolFailure), + ("PLAY", "LOOK demo", "ERROR ENTITLEMENT_UNAVAILABLE", [{"label": "LOGIN", "response": "OK LOGIN"}], smoke_common.ExplicitProtocolFailure), + ("LOGIN", "LOGIN user secret", "ERROR ENTITLEMENT_UNAVAILABLE", [], smoke_common.ExplicitProtocolFailure), + ("PLAY", "PLAY demo", "ERROR ENTITLEMENT_UNAVAILABLE", [], smoke_common.ExplicitProtocolFailure), + ("PLAY", "PLAY demo", "ERROR ENTITLEMENT_UNAVAILABLE", [{"label": "LOGIN", "response": "ERROR LOGIN"}], smoke_common.ExplicitProtocolFailure), +]: + with patch.object(smoke_common, "wait_for_incremental_response", side_effect=smoke_common.ExplicitProtocolFailure(response)): + try: + smoke_common.send_websocket_command_and_expect( + ClassificationSocket(), [], command, ["OK " + label], label, 1, step_results=prior + ) + except Exception as exc: + assert type(exc) is expected_type, (label, response, type(exc), expected_type) + else: + raise AssertionError("Protocol failure was concealed") + + +# Execute the actual held branch with disposable probe commands: prerequisite +# failure must prevent classification, and no failed probe becomes success. +held_branch_source = (root / "dev-tools/verify-smoke-images.sh").read_text().split( + ' run_held_admission_qualification "${COMPOSE_FILES[@]}"', 1 +)[1] +held_branch, closing_marker, trailing = held_branch_source.rpartition("\nfi\n") +assert closing_marker and not trailing.strip(), "Held smoke branch closing marker changed" +assert held_branch.strip() and "WS_SMOKE_SCRIPT" in held_branch +with tempfile.TemporaryDirectory() as directory: + probe = Path(directory) / "probe.sh" + output = Path(directory) / "output" + for qualification_status, probe_status in [(0, 86), (1, 86), (0, 1), (0, 0)]: + probe.write_text(f"exit {probe_status}\n") + output.write_text("") + code = ( + f"WS_SMOKE_SCRIPT={probe}; GITHUB_OUTPUT={output}; " + f"run_held_admission_qualification() {{ return {qualification_status}; }}; " + 'run_held_admission_qualification;\n' + held_branch + ) + result = subprocess.run(["bash", "-e", "-c", code], capture_output=True, text=True, check=False) + assert result.returncode == (qualification_status or probe_status), result + assert bool(output.read_text()) == (qualification_status == 0 and probe_status == 86) + + assert held_admission.format_success_message() == ( "Held-admission edge qualification passed. It proves Gateway/Telnet denial only; " "the direct backend positive proof is separate. Successful public Gateway/Telnet " @@ -414,6 +470,30 @@ class CommandResponseSession(FakeSession): self.chunks = list(response) if isinstance(response, list) else [response] +# Exercise the newline-bearing server response through the real WebSocket +# reader. The reader strips the line ending before command-local classification. +newline_entitlement_session = CommandResponseSession([ + "ERROR ENTITLEMENT_UNAVAILABLE Gameplay entitlement is temporarily unavailable. Retry PLAY shortly.\n" +]) +try: + smoke_common.send_websocket_command_and_expect( + newline_entitlement_session, + [], + "PLAY demo", + ["OK PLAY"], + "PLAY", + 1, + step_results=[{"label": "LOGIN", "response": "OK LOGIN account=demo"}], + ) +except smoke_common.PlayEntitlementUnavailable as exc: + assert str(exc) == ( + "ERROR ENTITLEMENT_UNAVAILABLE Gameplay entitlement is temporarily unavailable. Retry PLAY shortly." + ) +else: + raise AssertionError("newline entitlement failure did not retain its typed classification") +assert newline_entitlement_session.sent == ["PLAY demo"] + + class FakeTlsContext: def __init__(self, wrapped=None, failure=None): self.wrapped = wrapped or FakeSession() @@ -1824,6 +1904,76 @@ assert len(close_failure_attempts) == 1 assert close_failure_attempts[0].closed is True +def test_known_play_exception_precedes_retriable_exceptions(): + for retriable in (OSError, smoke_common.ProbeOperationalFailure, RuntimeError): + for close_fails in (False, True): + opened = [] + failure = smoke_common.PlayEntitlementUnavailable("ERROR ENTITLEMENT_UNAVAILABLE") + + class KnownPlaySession: + closed = False + + def close(self): + self.closed = True + if close_fails: + raise OSError("close failed") + + def open_session(): + session = KnownPlaySession() + opened.append(session) + return session + + def execute_session(_session): + raise failure + + try: + run_transport_session( + open_session, + execute_session, + "known PLAY session", + retry_window_seconds=1, + retry_interval_seconds=0, + retriable_exceptions=(retriable,), + ) + except smoke_common.ProbeOperationalFailure as exc: + if close_fails: + assert type(exc) is smoke_common.ProbeOperationalFailure + assert "Failed to close known PLAY session after known PLAY refusal" in str(exc) + assert isinstance(exc.__cause__, OSError) + assert str(exc.__cause__) == "close failed" + else: + assert exc is failure + else: + raise AssertionError("Known PLAY refusal was concealed") + assert len(opened) == 1 + assert opened[0].closed is True + + +test_known_play_exception_precedes_retriable_exceptions() + + +known_play_failure = smoke_common.PlayEntitlementUnavailable("ERROR ENTITLEMENT_UNAVAILABLE") + + +def raise_known_play_failure(_session): + raise known_play_failure + + +try: + run_transport_session( + open_close_failure_session, + raise_known_play_failure, + "known PLAY close failure session", + ) +except smoke_common.ProbeOperationalFailure as exc: + assert type(exc) is smoke_common.ProbeOperationalFailure + assert "Failed to close known PLAY close failure session" in str(exc) + assert isinstance(exc.__cause__, OSError) + assert str(exc.__cause__) == "close failed" +else: + raise AssertionError("A failed transport close must not qualify the PLAY exception") + + class FakeHttpResponse: def __init__(self, body): self.body = body diff --git a/dev-tools/tests/test_gradle_compile_failure.py b/dev-tools/tests/test_gradle_compile_failure.py index 2c37ce5d85..5c500b07bf 100644 --- a/dev-tools/tests/test_gradle_compile_failure.py +++ b/dev-tools/tests/test_gradle_compile_failure.py @@ -5,13 +5,14 @@ import json import os import shutil +import signal import subprocess import sys import tempfile import time import unittest from pathlib import Path -from unittest.mock import patch +from unittest.mock import Mock, patch ROOT = Path(__file__).resolve().parents[2] SPEC = importlib.util.spec_from_file_location( @@ -41,6 +42,464 @@ def write(self, relative, content='source'): path.write_text(content) return path + def stall_identity(self, pid=123, parent=100, role='daemon'): + return {'pid': pid, 'ppid': parent, 'start': 42, 'role': role, + 'state': 'S', 'cpu_ticks': 1, 'rss_pages': 10, 'jcmd': '/unused/jcmd'} + + def test_stall_timer_activity_attribution_and_one_batch(self): + identity = self.stall_identity() + with patch.object(CAPTURE.time, 'monotonic', return_value=0) as clock, patch.object( + CAPTURE, 'java_identity', return_value=identity), patch.object( + CAPTURE.subprocess, 'Popen') as launch, patch.object(CAPTURE.os, 'killpg') as kill, patch.object( + CAPTURE, 'owns_session', return_value=True), patch.object(CAPTURE.os, 'waitid', return_value=None): + observer = CAPTURE.StallObserver(self.root, self.output) + observer.observe(b'The client will now receive all logging from the daemon (pi') + observer.observe(b'd: 123). The daemon log file: secret') + self.assertEqual(identity, observer.daemon) + clock.return_value = 299 + observer.tick() + launch.assert_not_called() + observer.observe(b'progress') + clock.return_value = 598 + observer.tick() + launch.assert_not_called() + clock.return_value = 599 + observer.tick() + launch.assert_called_once() + self.assertTrue(launch.call_args.kwargs['start_new_session']) + self.assertEqual(subprocess.DEVNULL, launch.call_args.kwargs['stdin']) + clock.return_value = 690 + observer.tick() + kill.assert_called_once() + observer.observe(b'new progress') + clock.return_value = 1000 + observer.tick() + launch.assert_called_once() + + def test_stall_without_daemon_and_launch_failure_are_nonfatal(self): + with patch.object(CAPTURE.time, 'monotonic', side_effect=[0, 301]), patch.object( + CAPTURE.subprocess, 'Popen') as launch: + observer = CAPTURE.StallObserver(self.root, self.output) + observer.tick() + launch.assert_called_once() + self.assertIn('null', launch.call_args.args[0]) + with patch.object(CAPTURE.time, 'monotonic', side_effect=[0, 301]), patch.object( + CAPTURE.subprocess, 'Popen', side_effect=OSError('unavailable')): + observer = CAPTURE.StallObserver(self.root, self.output) + observer.daemon = self.stall_identity() + observer.tick() + self.assertTrue(observer.attempted) + self.assertIsNone(observer.child) + + def test_stall_processes_include_both_workers_exclude_unrelated_and_reused(self): + proc = self.root / 'proc' + java = self.write('jdk/bin/java') + def process(pid, parent, main, display=b'', executable=None): + base = proc / str(pid) + base.mkdir(parents=True) + fields = ['0'] * 22 + fields[0], fields[1], fields[19] = 'S', str(parent), '42' + (base / 'stat').write_text(f'{pid} (java) ' + ' '.join(fields)) + (base / 'cmdline').write_bytes(b'java\0-Dfixture=SECRET\0' + main + b'\0' + display + b'\0') + (base / 'exe').symlink_to(executable or java) + process(100, 1, b'org.gradle.launcher.daemon.bootstrap.GradleDaemon') + for pid in (101, 102): + process(pid, 100, b'worker.org.gradle.process.internal.worker.GradleWorkerMain', + b"'Gradle Test Executor 4'") + process(103, 999, b'worker.org.gradle.process.internal.worker.GradleWorkerMain', + b"'Gradle Test Executor 5'") + process(104, 100, b'other.JavaMain') + process(105, 100, b'SECRET' * 2000) + process(106, 101, b'worker.org.gradle.process.internal.worker.GradleWorkerMain', + b"'Gradle Test Executor 6'") + process(107, 100, b'worker.org.gradle.process.internal.worker.GradleWorkerMain', + b"'Gradle Test Executor 7'", self.write('jdk/bin/not-java')) + with patch.object(CAPTURE, 'PROC_ROOT', proc): + daemon = CAPTURE.java_identity(100) + coverage = {} + selected = CAPTURE.stall_processes(daemon, coverage) + self.assertEqual(2, coverage['workers_selected']) + self.assertEqual({'selected-test-worker': 2, 'unrecognized-java-role': 1, + 'command-line-limit': 1, 'not-java-executable': 1}, coverage['selection_counts']) + self.assertEqual({101, 102, 104, 105, 107}, {c['pid'] for c in coverage['candidates']}) + self.assertNotIn('SECRET', json.dumps(coverage)) + self.assertEqual({100, 101, 102}, {p['pid'] for p in selected}) + self.assertNotIn('SECRET', json.dumps(selected)) + self.assertEqual([], CAPTURE.stall_processes({**daemon, 'start': 43})) + with patch.object(CAPTURE, 'STALL_MAX_PROCESSES', 2), patch.object( + CAPTURE, 'STALL_MAX_CANDIDATES', 1): + limited = {} + self.assertEqual(2, len(CAPTURE.stall_processes(daemon, limited))) + self.assertEqual(1, limited['selection_counts']['attachment-limit']) + self.assertEqual(1, len(limited['candidates'])) + self.assertEqual(4, limited['candidates_omitted']) + with patch.object(CAPTURE, 'MAX_VISITED_ENTRIES', 1): + limited = {} + CAPTURE.stall_processes(daemon, limited) + self.assertTrue(limited['scan_limit_reached']) + reason = {} + with patch.object(Path, 'open', side_effect=PermissionError('SECRET')): + self.assertIsNone(CAPTURE.java_identity(101, reason)) + self.assertEqual({'reason': 'access-denied'}, reason) + + def test_stall_worker_launch_shape_is_exact_and_bounded(self): + proc = self.root / 'proc' + base = proc / '123' + base.mkdir(parents=True) + java = self.write('jdk/bin/java') + (base / 'exe').symlink_to(java) + fields = ['0'] * 22 + fields[0], fields[1], fields[19] = 'S', '100', '42' + (base / 'stat').write_text('123 (java) ' + ' '.join(fields)) + main = b'worker.org.gradle.process.internal.worker.GradleWorkerMain' + label = b"'Gradle Test Executor 3'" + # The classpath @file precedes the explicit main and is never opened. + valid = [b'java', b'-Xmx512m', b'@/unreadable/classpath', main, label] + cases = [ + (valid, True), + ([b'java', main, b"'Gradle Worker Daemon 3'"], False), + ([b'java', main, b'Gradle Test Executor 3'], False), + ([b'java', main, b'"Gradle Test Executor 3"'], False), + ([b'java', main, b"'Gradle Test Executor 3' suffix"], False), + ([b'java', main, b"'Gradle Test Executor 0'"], False), + ([b'java', main, b"'Gradle Test Executor -3'"], False), + ([b'java', main, b"'Gradle Test Executor 3\n'"], False), + ([b'java', main + b'Extra', label], False), + ([b'java', b'-Dmain=' + main, label], False), + ([b'java', main, b'unrelated', label], False), + ([*valid, b'extra'], False), + ([b'java', b'@/unreadable/launch'], False), + ([b'java', b'-Dsecret=' + b'x' * 8192, main, label], False), + ] + with patch.object(CAPTURE, 'PROC_ROOT', proc): + for index, (argv, accepted) in enumerate(cases): + with self.subTest(case=index): + (base / 'cmdline').write_bytes(b'\0'.join(argv) + b'\0') + result = CAPTURE.java_identity(123) + self.assertEqual(accepted, result is not None) + if result: + self.assertEqual('test-worker', result['role']) + self.assertNotIn('argv', result) + self.assertNotIn('classpath', json.dumps(result)) + + def test_stall_coverage_distinguishes_no_children_from_no_attribution(self): + daemon = self.stall_identity() + coverage = {} + with patch.object(CAPTURE, 'java_identity', return_value=daemon), patch.object( + CAPTURE.os, 'scandir') as entries: + entries.return_value.__enter__.return_value = iter([]) + self.assertEqual([daemon], CAPTURE.stall_processes(daemon, coverage)) + self.assertEqual('verified', coverage['daemon_identity']) + self.assertEqual(0, coverage['workers_selected']) + self.assertEqual([], coverage['candidates']) + self.assertFalse(coverage['scan_limit_reached']) + with patch.object(CAPTURE, 'java_identity', return_value=None): + self.assertEqual([], CAPTURE.stall_processes(daemon, coverage)) + self.assertEqual('exited-or-changed', coverage['daemon_identity']) + + def test_stall_daemon_retains_late_frames_with_fixed_larger_ceiling(self): + fake = self.write('jcmd', '#!/usr/bin/env python3\n' + 'print("ignored" * 24000)\n' + 'print("at org.example.Late.run(Late.java:42)")\n') + fake.chmod(0o755) + for role in ('daemon', 'test-worker'): + identity = {**self.stall_identity(role=role), 'jcmd': str(fake)} + with patch.object(CAPTURE, 'java_identity', return_value=identity): + result = CAPTURE.thread_snapshot(identity) + if role == 'daemon': + self.assertEqual('complete', result['status']) + self.assertIn('Late.run', result['threads']) + self.assertEqual(512 * 1024, result['dump_byte_limit']) + else: + self.assertEqual('limited', result['status']) + self.assertNotIn('Late.run', result['threads']) + self.assertEqual(128 * 1024, result['dump_byte_limit']) + + def test_stall_sanitizer_rejects_names_secrets_and_diagnostic_prose(self): + raw = (b'"SECRET-password" #17 tid=0xabc nid=0xdef waiting\n' + b' java.lang.Thread.State: WAITING (parking)\n' + b' at java.lang.Object.wait0(java.base@25/Native Method)\n' + b' at jdk.internal.misc.Unsafe.park(java.base@25.0.5+8/Native Method)\n' + b'\"SECRET-decimal-thread\" #18 tid=0x123 nid=345 waiting\n' + b' at org.example.Work.run(Work.java:42)\n' + b' - locked <0xabc> (a java.lang.Object)\n' + b'JAVA_TOOL_OPTIONS=SECRET\njdbc:postgresql://SECRET\n' + b'SELECT SECRET FROM private\nVM.command_line SECRET\n') + output = CAPTURE.sanitized_threads(raw) + self.assertNotIn('SECRET', output) + self.assertIn('#17 tid=0xabc nid=0xdef', output) + self.assertIn('#18 tid=0x123 nid=345', output) + self.assertIn('Object.wait0(java.base@25/Native Method)', output) + self.assertIn('Unsafe.park(java.base@25.0.5+8/Native Method)', output) + self.assertIn('WAITING', output) + self.assertIn('Work.run(Work.java:42)', output) + self.assertIn('locked <0xabc>', output) + + def test_stall_identity_change_never_attaches(self): + original = self.stall_identity() + with patch.object(CAPTURE, 'java_identity', return_value={**original, 'start': 43}), patch.object( + CAPTURE.subprocess, 'Popen') as launch: + result = CAPTURE.thread_snapshot(original) + self.assertEqual('exited-or-changed', result['status']) + launch.assert_not_called() + + def test_stall_fake_jcmd_output_limit_and_timeout(self): + fake = self.write('jcmd', '#!/usr/bin/env python3\n' + 'print("at org.example.Work.run(Work.java:42)", flush=True)\n' + 'print("SECRET" * 1000, flush=True)\n' + 'import time; time.sleep(10)\n') + fake.chmod(0o755) + identity = {**self.stall_identity(), 'jcmd': str(fake)} + with patch.object(CAPTURE, 'java_identity', return_value=identity), patch.object( + CAPTURE, 'STALL_DUMP_BYTES', 100): + result = CAPTURE.thread_snapshot(identity) + self.assertEqual('limited', result['status']) + self.assertNotIn('SECRET', json.dumps(result)) + self.assertNotIn('jcmd', result) + fake.write_text('#!/usr/bin/env python3\nimport time; time.sleep(10)\n') + with patch.object(CAPTURE, 'java_identity', return_value=identity), patch.object( + CAPTURE, 'STALL_COMMAND_SECONDS', 0.1): + result = CAPTURE.thread_snapshot(identity) + self.assertEqual('timeout', result['status']) + + def test_stall_missing_jcmd_is_nonfatal(self): + identity = self.stall_identity() + with patch.object(CAPTURE, 'java_identity', return_value=identity): + self.assertEqual('unavailable', CAPTURE.thread_snapshot(identity)['status']) + + def test_stall_snapshots_are_fresh_bounded_and_reject_symlinks(self): + identity = self.stall_identity() + with patch.object(CAPTURE, 'stall_processes', return_value=[identity]), patch.object( + CAPTURE, 'thread_snapshot', return_value={'status': 'complete'}), patch.object( + CAPTURE.time, 'sleep'), patch('sys.stdout', io.StringIO()): + CAPTURE.collect_stall(self.root, self.output, identity) + CAPTURE.collect_stall(self.root, self.output, identity) + self.assertEqual(4, len(list(self.output.glob('observation-*/snapshot-*.json')))) + link = self.root / 'escape' + link.symlink_to(self.output, target_is_directory=True) + with self.assertRaises(ValueError): + CAPTURE.collect_stall(self.root, link, identity) + + def test_stall_session_guard_never_signals_parent_or_unowned_group(self): + with patch.object(CAPTURE.os, 'getpgid', return_value=50), patch.object( + CAPTURE.os, 'getsid', return_value=50): + self.assertFalse(CAPTURE.owns_session(123)) + with patch.object(CAPTURE, 'owns_session', return_value=False), patch.object( + CAPTURE.os, 'killpg') as kill: + with self.assertRaises(SystemExit): + CAPTURE.stop_stall_session(signal.SIGALRM, None) + observer = CAPTURE.StallObserver(self.root, self.output) + child = observer.child = Mock() + observer.close() + kill.assert_not_called() + child.wait.assert_not_called() + with patch.object(CAPTURE, 'owns_session', return_value=True), patch.object( + CAPTURE.os, 'killpg') as kill, self.assertRaises(SystemExit): + CAPTURE.stop_stall_session(signal.SIGALRM, None) + kill.assert_called_once_with(os.getpid(), signal.SIGKILL) + + def test_stall_capture_cancellation_closes_observer(self): + observer = Mock() + observer.tick.side_effect = SystemExit(143) + read_fd, write_fd = os.pipe() + os.close(write_fd) + with os.fdopen(read_fd, 'rb') as source, self.assertRaises(SystemExit): + list(CAPTURE.capture_chunks(source, observer)) + observer.close.assert_called_once() + + def test_stall_missing_attribution_is_explicit_and_never_enumerates_jvms(self): + with patch.object(CAPTURE, 'stall_processes') as enumerate_jvms, patch.object( + CAPTURE.time, 'sleep'), patch('sys.stdout', io.StringIO()) as output: + CAPTURE.collect_stall(self.root, self.output, None) + enumerate_jvms.assert_not_called() + self.assertIn('"daemon_attribution": "unavailable"', output.getvalue()) + + def test_stall_blocked_diagnostic_sink_is_reaped_without_touching_other_processes(self): + child = subprocess.Popen([sys.executable, '-c', + 'import os;\nwhile True: os.write(1, b"x" * 65536)'], + stdout=subprocess.PIPE, start_new_session=True) + unrelated = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(30)']) + self.addCleanup(unrelated.wait) + self.addCleanup(unrelated.kill) + self.addCleanup(child.stdout.close) + self.addCleanup(child.wait) + self.addCleanup(lambda: child.kill() if child.poll() is None else None) + observer = CAPTURE.StallObserver(self.root, self.output) + observer.child, observer.started, observer.attempted = child, time.monotonic(), True + read_fd, write_fd = os.pipe() + os.write(write_fd, b'build output') + os.close(write_fd) + with os.fdopen(read_fd, 'rb') as source: + self.assertEqual([b'build output'], list(CAPTURE.capture_chunks(source, observer))) + self.assertIsNotNone(child.poll()) + self.assertIsNone(unrelated.poll()) + + def test_stall_exited_or_reused_daemon_is_not_labelled_verified(self): + with patch.object(CAPTURE, 'stall_processes', return_value=[]), patch.object( + CAPTURE.time, 'sleep'), patch('sys.stdout', io.StringIO()) as output: + CAPTURE.collect_stall(self.root, self.output, self.stall_identity()) + self.assertIn('"daemon_attribution": "unavailable"', output.getvalue()) + for path in self.output.glob('observation-*/snapshot-*.json'): + self.assertEqual('unavailable', json.loads(path.read_text())['daemon_attribution']) + + def test_stall_symlinked_checkout_preserves_output_containment(self): + alias = self.root / 'checkout' + actual = self.root / 'actual' + actual.mkdir() + alias.symlink_to(actual, target_is_directory=True) + with patch.object(CAPTURE.time, 'sleep'), patch('sys.stdout', io.StringIO()): + CAPTURE.collect_stall(alias, alias / 'build/evidence', None) + self.assertEqual(2, len(list(actual.glob('build/evidence/observation-*/snapshot-*.json')))) + (actual / 'escape').symlink_to(self.root, target_is_directory=True) + with self.assertRaises(ValueError): + CAPTURE.collect_stall(alias, alias / 'escape/evidence', None) + with self.assertRaises(ValueError): + CAPTURE.collect_stall(alias, alias / '../outside', None) + + def test_stall_marker_is_fixed_nonblocking_and_does_not_expose_failure_text(self): + with patch.object(CAPTURE.os, 'open', return_value=99) as opening, patch.object( + CAPTURE.os, 'write', side_effect=BlockingIOError('SECRET')) as writing, patch.object( + CAPTURE.os, 'close') as closing: + CAPTURE.stall_marker('launch-failed') + self.assertTrue(opening.call_args.args[1] & os.O_NONBLOCK) + self.assertTrue(opening.call_args.args[1] & os.O_APPEND) + self.assertEqual(b'FIREMUD_STALL_OBSERVER status=launch-failed\n', writing.call_args.args[1]) + closing.assert_called_once_with(99) + with patch.object(CAPTURE.os, 'open') as opening: + CAPTURE.stall_marker('SECRET exception path') + opening.assert_not_called() + + def test_stall_private_mode_reports_safe_setup_failure_in_subprocess(self): + output = self.root / 'escape' + output.symlink_to(self.root, target_is_directory=True) + result = subprocess.run( + [sys.executable, str(ROOT / 'dev-tools/validation/collect-gradle-compile-failure.py'), + '--stall-daemon', 'null', '--root', str(self.root), '--output', str(output)], + start_new_session=True, capture_output=True, text=True, timeout=5, check=False) + self.assertEqual(1, result.returncode) + self.assertIn('status=started', result.stdout) + self.assertIn('status=setup-failed', result.stdout) + self.assertNotIn(str(self.root), result.stdout + result.stderr) + self.assertNotIn('Traceback', result.stdout + result.stderr) + + def test_stall_enabled_capture_subprocess_preserves_bytes_through_idle_observation(self): + # Copy only the executable under test; shorten constants without attaching to a JVM. + script = self.root / 'collector.py' + script.write_text((ROOT / 'dev-tools/validation/collect-gradle-compile-failure.py').read_text() + .replace('STALL_IDLE_SECONDS = 300', 'STALL_IDLE_SECONDS = 0.01') + .replace('STALL_BATCH_SECONDS = 90', 'STALL_BATCH_SECONDS = 2')) + process = subprocess.Popen( + [sys.executable, str(script), '--capture-log', str(self.log), '--root', str(self.root), + '--stall-output', str(self.output)], stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=subprocess.PIPE) + self.addCleanup(lambda: process.kill() if process.poll() is None else None) + deadline = time.monotonic() + 4 + while not list(self.output.glob('observation-*/snapshot-1.json')): + if time.monotonic() > deadline: + self.fail('bounded fake observer did not create its first snapshot') + time.sleep(0.01) + output, error = process.communicate(b'original bytes\n', timeout=5) + self.assertEqual(0, process.returncode) + self.assertEqual(b'original bytes\n', output) + self.assertIn(b'status=enabled', error) + self.assertIn(b'status=started', error) + self.assertNotIn(b'Traceback', error) + + def test_stall_capture_keeps_exact_stdout_and_closes_on_eof(self): + read_fd, write_fd = os.pipe() + os.write(write_fd, b'original output\n') + os.close(write_fd) + observer = Mock() + destination = io.BytesIO() + with os.fdopen(read_fd, 'rb') as source: + status = CAPTURE.capture_log(source, destination, self.log, observer) + self.assertEqual(0, status) + self.assertEqual(b'original output\n', destination.getvalue()) + self.assertEqual(destination.getvalue(), self.log.read_bytes()) + observer.observe.assert_called_once_with(b'original output\n') + observer.close.assert_called_once() + + def test_stall_capture_falls_back_for_regular_file_input(self): + input_path = self.root / 'build-output.log' + input_path.write_bytes(b'original build output\n') + observer = Mock() + destination = io.BytesIO() + with patch.object(CAPTURE, 'MAX_LOG_BYTES', 8), patch.object( + CAPTURE, 'stall_marker') as marker, input_path.open('rb') as source: + status = CAPTURE.capture_log(source, destination, self.log, observer) + self.assertEqual(0, status) + self.assertEqual(b'original build output\n', destination.getvalue()) + self.assertEqual(b' output\n', self.log.read_bytes()) + marker.assert_called_once_with('observer-failed') + observer.observe.assert_not_called() + observer.close.assert_called_once() + + def test_stall_capture_registration_failure_closes_observer_without_hiding_read_error(self): + selector = Mock() + selector.register.side_effect = PermissionError('regular files cannot be epoll-registered') + observer = Mock() + + class BrokenSource: + def read(self, size): + raise OSError('direct read failed') + + with patch.object(CAPTURE.selectors, 'DefaultSelector', return_value=selector), patch.object( + CAPTURE, 'stall_marker') as marker, self.assertRaisesRegex(OSError, 'direct read failed'): + list(CAPTURE.capture_chunks(BrokenSource(), observer)) + selector.close.assert_called_once() + observer.close.assert_called_once() + marker.assert_called_once_with('observer-failed') + + def test_module_wrapper_uses_two_workers_including_fallback(self): + for module, partition, expected in [('account-service', '4', [2, 2]), + ('account-service', 'full', [2]), + ('game-session-service', '4', [2, 2]), + ('world-management-service', 'full', [2])]: + for fallback in (False, True): + with self.subTest(module=module, partition=partition, fallback=fallback): + root = self.root / f'{module}-{partition}-{fallback}' + script = root / '.github/scripts/run-gradle-module-checks.sh' + script.parent.mkdir(parents=True) + shutil.copyfile(ROOT / '.github/scripts/run-gradle-module-checks.sh', script) + validation = root / 'dev-tools/validation' + validation.mkdir(parents=True) + shutil.copyfile(ROOT / 'dev-tools/validation/collect-gradle-compile-failure.py', + validation / 'collect-gradle-compile-failure.py') + (validation / 'run-gradle-with-dependency-recovery.sh').write_text( + '#!/bin/bash\nrunner="$2"; shift 3; exec "$runner" "$@"\n') + (validation / 'slow_service_ci_test_partition.py').write_text('# Inert planner fixture.\n') + runner = root / 'gradlew' + runner.write_text('#!/bin/bash\nprintf "%s\\n" "$*" >> calls\n' + 'printf "original-check-output\\n"\n') + runner.chmod(0o755) + env = {**os.environ, 'GITHUB_ACTIONS': 'true', 'RUNNER_ENVIRONMENT': 'github-hosted', + 'RUNNER_OS': 'Linux'} + if fallback: + binary = root / 'bin' + binary.mkdir() + mktemp = binary / 'mktemp' + mktemp.write_text('#!/bin/bash\nexit 1\n') + mktemp.chmod(0o755) + env['PATH'] = str(binary) + os.pathsep + env['PATH'] + result = subprocess.run(['bash', str(script), module, partition], cwd=root, env=env, + capture_output=True, text=True, timeout=5, check=False) + self.assertEqual(0, result.returncode, result.stderr) + calls = (root / 'calls').read_text().splitlines() + self.assertEqual(len(expected), len(calls)) + for call, workers in zip(calls, expected, strict=True): + self.assertIn(f'--max-workers={workers}', call) + self.assertIn('-PfullCheck', call) + self.assertNotIn('--tests', call) + self.assertEqual(len(expected), result.stdout.count('original-check-output')) + if partition != 'full': + self.assertIn(f'-PslowServiceCiPartition={partition}', calls[-1]) + self.assertIn(f':{module}:testClasses', calls[0]) + self.assertIn(f':{module}:check', calls[-1]) + marker = ('disabled-capture-unavailable' if fallback else + 'enabled' if module == 'account-service' and partition != 'full' else + 'disabled-scope') + self.assertIn(f'FIREMUD_STALL_ACTIVATION status={marker}', result.stderr) + def test_compile_failure_bounds_and_symlink_rejection(self): self.write('services/common-saga/build/generated/source/Bad.java', 'bad') self.write('services/common-saga/build/generated/source/Huge.java', 'x' * 100) diff --git a/dev-tools/validation/collect-gradle-compile-failure.py b/dev-tools/validation/collect-gradle-compile-failure.py index 0466db2ea5..1354b452b6 100644 --- a/dev-tools/validation/collect-gradle-compile-failure.py +++ b/dev-tools/validation/collect-gradle-compile-failure.py @@ -10,6 +10,7 @@ import signal import subprocess import sys +import tempfile import time from collections import deque from pathlib import Path @@ -38,14 +39,350 @@ def safe_file(root, path): return False -def capture_log(source, destination, path): +# Account CI-only observation. No build process is signalled or restarted. +PROC_ROOT = Path('/proc') +STALL_IDLE_SECONDS = 300 +STALL_BATCH_SECONDS = 90 +STALL_COMMAND_SECONDS = 5 +STALL_MAX_PROCESSES = 8 +STALL_MAX_CANDIDATES = 32 +STALL_DUMP_BYTES = 128 * 1024 +DAEMON_PID = re.compile(rb'The client will now receive all logging from the daemon \(pid: ([0-9]+)\)') + + +def stall_marker(status, fd=2): + """Fixed, best-effort status only; never block capture or change shared descriptor flags.""" + if status not in {'enabled', 'started', 'completed', 'launch-failed', 'setup-failed', + 'observer-failed', 'session-unowned', 'deadline', 'cancelled'}: + return + descriptor = None + try: + # Reopening proc fd creates a separate description; dup()+F_SETFL would also + # make the caller's pipe nonblocking. O_APPEND protects regular-file sinks. + descriptor = os.open(f'/proc/self/fd/{fd}', os.O_WRONLY | os.O_NONBLOCK | os.O_APPEND) + os.write(descriptor, f'FIREMUD_STALL_OBSERVER status={status}\n'.encode('ascii')) + except OSError: + pass + finally: + if descriptor is not None: + os.close(descriptor) + + +def owns_session(pid): + try: + return os.getpgid(pid) == pid and os.getsid(pid) == pid + except ProcessLookupError: + return False + + +def stop_stall_session(signum, frame): + stall_marker('deadline', fd=1) + if owns_session(os.getpid()): + os.killpg(os.getpid(), signal.SIGKILL) + raise SystemExit(128 + signum) + + +def java_identity(pid, rejection=None): + """Classify without retaining argv, environment, or arbitrary process names.""" + def reject(reason): + if rejection is not None: + rejection['reason'] = reason + + try: + path = PROC_ROOT / str(pid) + if path.stat().st_uid != os.getuid(): + return reject('different-uid') + fields = (path / 'stat').read_bytes().rsplit(b')', 1)[1].split() + with (path / 'cmdline').open('rb') as stream: + arguments = stream.read(8193) + if len(arguments) > 8192: + return reject('command-line-limit') + arguments = arguments.removesuffix(b'\0').split(b'\0') + if b'org.gradle.launcher.daemon.bootstrap.GradleDaemon' in arguments: + role = 'daemon' + # Gradle 9.8.2 DefaultWorkerProcessBuilder.build adds literal single + # quotes around the display-name argument (these are not shell quoting). + # Require the complete trailing main/display pair, not an arbitrary argv + # substring. Unknown launch shapes remain unselected; never read argfiles. + elif (len(arguments) >= 3 + and arguments[-2] == b'worker.org.gradle.process.internal.worker.GradleWorkerMain' + and re.fullmatch(rb"'Gradle Test Executor [1-9][0-9]*'", arguments[-1])): + role = 'test-worker' + else: + return reject('unrecognized-java-role') + executable = (path / 'exe').resolve(strict=True) + if executable.name != 'java': + return reject('not-java-executable') + return {'pid': pid, 'ppid': int(fields[1]), 'start': int(fields[19]), + 'state': fields[0].decode('ascii'), 'role': role, + 'cpu_ticks': int(fields[11]) + int(fields[12]), 'rss_pages': int(fields[21]), + 'jcmd': str(executable.with_name('jcmd'))} + except (FileNotFoundError, ProcessLookupError): + return reject('exited') + except PermissionError: + return reject('access-denied') + except (OSError, ValueError, IndexError, UnicodeError): + return reject('process-unavailable') + + +def stall_processes(daemon, coverage=None): + if coverage is None: + coverage = {} + coverage.update({'scope': 'same-uid-direct-daemon-children', 'scan_limit': MAX_VISITED_ENTRIES, + 'scan_limit_reached': False, 'entries_examined': 0, 'inspection_errors': 0, + 'candidate_limit': STALL_MAX_CANDIDATES, 'candidates': [], + 'candidates_omitted': 0, 'selection_counts': {}, 'workers_selected': 0}) + current = java_identity(daemon['pid']) + if not current or (current['start'], current['role']) != (daemon['start'], 'daemon'): + coverage['daemon_identity'] = 'exited-or-changed' + return [] + coverage['daemon_identity'] = 'verified' + result = [current] + # Scope intentionally remains direct children. Rejected candidates are metadata, + # not permission to attach to an unknown JVM or scan its descendants/arguments. + with os.scandir(PROC_ROOT) as entries: + for _, entry in zip(range(MAX_VISITED_ENTRIES), entries): + coverage['entries_examined'] += 1 + if not entry.name.isdigit(): + continue + path = Path(entry.path) + try: + fields = (path / 'stat').read_bytes().rsplit(b')', 1)[1].split() + if int(fields[1]) != daemon['pid'] or path.stat().st_uid != os.getuid(): + continue + candidate = {'pid': int(entry.name), 'ppid': int(fields[1]), + 'start': int(fields[19]), 'state': fields[0].decode('ascii')} + except (OSError, ValueError, IndexError, UnicodeError): + coverage['inspection_errors'] += 1 + continue + rejection = {} + worker = java_identity(candidate['pid'], rejection) + reason = rejection.get('reason', 'unrecognized-java-role') + if worker and worker['role'] == 'test-worker': + if any(worker[key] != candidate[key] for key in ('pid', 'ppid', 'start')): + reason = 'identity-changed' + elif len(result) >= STALL_MAX_PROCESSES: + reason = 'attachment-limit' + else: + result.append(worker) + coverage['workers_selected'] += 1 + reason = 'selected-test-worker' + candidate['selection'] = reason + counts = coverage['selection_counts'] + counts[reason] = counts.get(reason, 0) + 1 + if len(coverage['candidates']) < STALL_MAX_CANDIDATES: + coverage['candidates'].append(candidate) + else: + coverage['candidates_omitted'] += 1 + coverage['scan_limit_reached'] = coverage['entries_examined'] >= MAX_VISITED_ENTRIES + return result + + +def sanitized_threads(raw): + """Allow only stack/state/monitor syntax; thread names and diagnostic prose are private.""" + lines = [] + for line in raw.decode('utf-8', errors='replace').splitlines(): + if line.startswith('"'): + identifiers = re.findall(r'(?:#\d+|tid=0x[0-9a-f]+|nid=(?:0x[0-9a-f]+|[0-9]+))(?=\s|$)', line[line.rfind(chr(34)) + 1:]) + lines.append('thread (name omitted) ' + ' '.join(identifiers)) + elif (re.fullmatch(r'\s*java.lang.Thread.State: [A-Z_]+(?: \([a-z ]+\))?', line) + or re.fullmatch(r'\s*at [A-Za-z0-9_.$/@+\-]+\([A-Za-z0-9_.$:@+ /\-]+\)', line) + or re.fullmatch(r'\s*- (?:locked|waiting on|waiting to lock|parking to wait for)\s+<0x[0-9a-f]+> \(a [A-Za-z0-9_.$]+\)', line)): + lines.append(line.strip()) + return '\n'.join(lines) + + +def thread_snapshot(identity): + facts = {key: value for key, value in identity.items() if key != 'jcmd'} + # The observed daemon exceeded128KiB; retain later actor frames with a fixed ceiling. + dump_limit = STALL_DUMP_BYTES * (4 if identity['role'] == 'daemon' else 1) + facts['dump_byte_limit'] = dump_limit + current = java_identity(identity['pid']) + # Counters may change; only identity and lineage must remain fixed. + keys = ('pid', 'ppid', 'start', 'role', 'jcmd') + if not current or any(current[key] != identity[key] for key in keys): + return {**facts, 'status': 'exited-or-changed'} + process = None + selector = selectors.DefaultSelector() + raw = bytearray() + status = 'complete' + try: + process = subprocess.Popen([identity['jcmd'], str(identity['pid']), 'Thread.print', '-l'], + stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL) + selector.register(process.stdout, selectors.EVENT_READ) + deadline = time.monotonic() + STALL_COMMAND_SECONDS + while True: + remaining = deadline - time.monotonic() + if remaining <= 0 or not selector.select(remaining): + status = 'timeout' + break + chunk = os.read(process.stdout.fileno(), min(8192, dump_limit - len(raw))) + if not chunk: + break + raw.extend(chunk) + if len(raw) >= dump_limit: + status = 'limited' + break + if status == 'complete': + process.wait(timeout=max(0.01, deadline - time.monotonic())) + if process.returncode: + status = 'failed' + except subprocess.TimeoutExpired: + status = 'timeout' + except OSError: + status = 'unavailable' + finally: + selector.close() + if process is not None: + if process.poll() is None: + process.kill() # Only our jcmd helper, never the target JVM. + process.wait() + process.stdout.close() + current = java_identity(identity['pid']) + if not current or any(current[key] != identity[key] for key in keys): + return {**facts, 'status': 'exited-or-changed'} + return {**facts, 'status': status, 'threads': sanitized_threads(raw)} + + +def collect_stall(root, output, daemon): + lexical_root = Path(os.path.abspath(root)) + relative = Path(os.path.abspath(output)).relative_to(lexical_root) + root = lexical_root.resolve() + output = root / relative + cursor = root + for part in relative.parts: + cursor /= part + if cursor.is_symlink(): + raise ValueError('Stall evidence must not traverse symlinks') + output.mkdir(parents=True, exist_ok=True) + # Each invocation owns a fresh directory; never overwrite prior evidence. + target = Path(tempfile.mkdtemp(prefix='observation-', dir=output)) + started = time.monotonic() + for number in range(2): + if number: + time.sleep(max(0, 30 - (time.monotonic() - started))) + coverage = {'daemon_identity': 'unavailable'} + processes = stall_processes(daemon, coverage) if daemon else [] + report = {'snapshot': number + 1, 'reason': '300 seconds without Gradle output', + 'daemon_attribution': 'verified' if processes else 'unavailable', + 'worker_coverage': coverage, + 'process_limit': STALL_MAX_PROCESSES, 'process_limit_reached': len(processes) >= STALL_MAX_PROCESSES, + 'processes': [thread_snapshot(process) for process in processes]} + payload = json.dumps(report, indent=2) + '\n' + (target / f'snapshot-{number + 1}.json').write_text(payload) + # Independent child output: a blocked log sink cannot stall Gradle capture. + print('FIREMUD_STALL_SNAPSHOT ' + json.dumps( + {key: value for key, value in report.items() if key != 'processes'}), flush=True) + for process in report['processes']: + print(json.dumps({key: value for key, value in process.items() if key != 'threads'}), flush=True) + print(process.get('threads', ''), flush=True) + + +class StallObserver: + """One independent, bounded diagnostic batch; capture remains the sole build-output reader.""" + def __init__(self, root, output): + self.root, self.output = root, output + self.last_activity = time.monotonic() + self.prefix = b'' + self.daemon = None + self.child = None + self.started = None + self.attempted = False + + def observe(self, chunk): + self.last_activity = time.monotonic() + data = self.prefix + chunk + for match in DAEMON_PID.finditer(data): + candidate = java_identity(int(match[1])) + if candidate and candidate['role'] == 'daemon': + self.daemon = candidate + self.prefix = data[-256:] + + def tick(self): + now = time.monotonic() + if self.child: + # Observe without reaping: the reserved PID still owns the cleanup group. + try: + exited = os.waitid(os.P_PID, self.child.pid, os.WEXITED | os.WNOHANG | os.WNOWAIT) + except OSError: + stall_marker('observer-failed') + self.close() + return + if exited is not None: + if exited.si_status: + stall_marker('observer-failed') + self.close() + elif now - self.started >= STALL_BATCH_SECONDS: + stall_marker('deadline') + self.close() + if self.attempted or now - self.last_activity < STALL_IDLE_SECONDS: + return + self.attempted = True + try: + self.child = subprocess.Popen( + [sys.executable, str(Path(__file__).resolve()), '--stall-daemon', + json.dumps(self.daemon), '--root', str(self.root), '--output', str(self.output)], + stdin=subprocess.DEVNULL, stdout=sys.stderr, stderr=subprocess.DEVNULL, + start_new_session=True) + self.started = now + except OSError: + stall_marker('launch-failed') # Never include exception text or paths. + + def close(self): + if self.child: + # The session contains only this observer and its jcmd helpers. + # Always reap its group, including a helper surviving an observer error. + try: + if owns_session(self.child.pid): + os.killpg(self.child.pid, signal.SIGKILL) + self.child.wait() + else: + self.child.poll() # Reap if exited; never wait on an unowned process. + except ProcessLookupError: + self.child.wait() + self.child = None + + +def capture_chunks(source, observer): + if observer is None: + reader = getattr(source, 'read1', source.read) + while chunk := reader(64 * 1024): + yield chunk + return + selector = selectors.DefaultSelector() + try: + selector.register(source, selectors.EVENT_READ) + except OSError: + selector.close() + stall_marker('observer-failed') + observer.close() + reader = getattr(source, 'read1', source.read) + while chunk := reader(64 * 1024): + yield chunk + return + try: + while True: + observer.tick() + if not selector.select(1): + continue + chunk = os.read(source.fileno(), 64 * 1024) + if not chunk: + break + observer.observe(chunk) + yield chunk + finally: + selector.close() + observer.close() + + +def capture_log(source, destination, path, observer=None): """Forward immediately; retain only a bounded tail, even if capture fails.""" tail = deque() length = 0 forwarding = True failed = False - reader = getattr(source, 'read1', source.read) - while chunk := reader(64 * 1024): + for chunk in capture_chunks(source, observer): if forwarding: try: destination.write(chunk) @@ -317,9 +654,35 @@ def main(): parser.add_argument('--log', type=Path) parser.add_argument('--output', type=Path) parser.add_argument('--check-exit', type=int) + parser.add_argument('--stall-output', type=Path) + parser.add_argument('--stall-daemon') args = parser.parse_args() + if args.stall_daemon is not None: + # Independent ceiling also applies if the capture parent is abruptly killed. + if not owns_session(os.getpid()): + stall_marker('session-unowned', fd=1) + return 2 # Private mode must be started by our observer, in its own session. + signal.signal(signal.SIGALRM, stop_stall_session) + signal.alarm(STALL_BATCH_SECONDS) + stall_marker('started', fd=1) + try: + collect_stall(args.root, args.output, json.loads(args.stall_daemon)) + except (OSError, ValueError): + stall_marker('setup-failed', fd=1) + return 1 + stall_marker('completed', fd=1) + return 0 if args.capture_log is not None: - return capture_log(sys.stdin.buffer, sys.stdout.buffer, args.capture_log) + observer = StallObserver(args.root, args.stall_output) if args.stall_output else None + if observer: + stall_marker('enabled') + def stop(signum, frame): + stall_marker('cancelled') + observer.close() + raise SystemExit(128 + signum) + for signum in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP): + signal.signal(signum, stop) + return capture_log(sys.stdin.buffer, sys.stdout.buffer, args.capture_log, observer) if any(value is None for value in (args.root, args.log, args.output, args.check_exit)): parser.error('collection requires --root, --log, --output and --check-exit') if 0 < args.check_exit < 128: diff --git a/dev-tools/verify-smoke-images.sh b/dev-tools/verify-smoke-images.sh index 4f03e02b15..7f1fcbf7f2 100644 --- a/dev-tools/verify-smoke-images.sh +++ b/dev-tools/verify-smoke-images.sh @@ -300,6 +300,16 @@ else run_held_admission_qualification "${COMPOSE_FILES[@]}" # This is the existing isolated backend positive proof. Public successful # admission remains a separate runtime obligation. - bash "$WS_SMOKE_SCRIPT" + # Keep the real failure. Only classify after the held-admission proof above. + ws_status=0 + bash "$WS_SMOKE_SCRIPT" || ws_status=$? + if [[ "$ws_status" -eq 86 ]]; then + if [[ -n "${GITHUB_OUTPUT:-}" ]]; then + echo "known_play_failure=direct-backend-play-entitlement-unavailable-after-login" >> "$GITHUB_OUTPUT" + fi + exit "$ws_status" + elif [[ "$ws_status" -ne 0 ]]; then + exit "$ws_status" + fi echo "Held-admission smoke qualification passed; public successful admission remains unproved." fi diff --git a/protos/account/v1/account_service.proto b/protos/account/v1/account_service.proto index 922f3b881c..56e6a9183f 100644 --- a/protos/account/v1/account_service.proto +++ b/protos/account/v1/account_service.proto @@ -78,6 +78,9 @@ message JoinPublicProductionMembershipResponse { uint64 membership_authority_generation = 7; bool replayed = 8; shared.v1.ErrorDetail error = 9; + // Exact current membership flag. A successful membership receipt may be non-admitting; + // this field and success never replace the separate current gameplay admission checks. + bool gameplay_admission_allowed = 10; } // Empty request used to verify that the service is reachable. diff --git a/services/account-service/build.gradle.kts b/services/account-service/build.gradle.kts index 51865174cf..a561467fa3 100644 --- a/services/account-service/build.gradle.kts +++ b/services/account-service/build.gradle.kts @@ -92,6 +92,11 @@ dependencies { add("integrationTestCompileOnly", libs.spotbugs.annotations) integrationTestImplementation(project(path = ":game-session-service", configuration = "gameSessionClassesProof")) integrationTestImplementation(project(path = ":entity-management-service", configuration = "entityClassesProof")) + // Share canonical bootstrap proof values without importing Entity application resources. + val entityBootstrapProof = testFixtures(project(":entity-management-service")) + as org.gradle.api.artifacts.ModuleDependency + entityBootstrapProof.isTransitive = false + integrationTestImplementation(entityBootstrapProof) integrationTestImplementation(testFixtures(project(":common-test-support"))) integrationTestImplementation(project(":social-groups-service")) integrationTestImplementation(testFixtures(project(":account-service"))) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java index e51178229b..7b25dc31cc 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java @@ -73,10 +73,12 @@ public ResponseEntity>> listBootstrapWorlds( @GetMapping("/bootstrap/worlds/{worldSlug}/realms") public ResponseEntity>> listBootstrapRealms( @RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authorization, - @PathVariable String worldSlug) { + @PathVariable String worldSlug, + @RequestParam String tenantSlug) { String bootstrapToken = extractBearerToken(authorization); return ResponseEntity.ok( - ApiResponse.success(accountService.listBootstrapRealms(bootstrapToken, worldSlug))); + ApiResponse.success( + accountService.listBootstrapRealms(bootstrapToken, tenantSlug, worldSlug))); } @GetMapping("/bootstrap/worlds/{worldSlug}/realms/{realmSlug}/characters") diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/TestDataSeeder.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/TestDataSeeder.java index ac571813e3..de5bde5a35 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/TestDataSeeder.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/TestDataSeeder.java @@ -2,19 +2,15 @@ import de.mkammerer.argon2.Argon2; import de.mkammerer.argon2.Argon2Factory; -import java.time.LocalDateTime; -import java.util.List; import java.util.Objects; import java.util.Optional; import lombok.RequiredArgsConstructor; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; import net.firedevops.firemud.accountservice.entity.ProfilePresenceVisibilityPolicy; -import net.firedevops.firemud.accountservice.entity.Subscription; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; import net.firedevops.firemud.accountservice.repository.ProfileRepository; -import net.firedevops.firemud.accountservice.repository.SubscriptionRepository; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @@ -34,12 +30,10 @@ public class TestDataSeeder implements ApplicationRunner { private static final String DEMO_USERNAME = "demo"; private static final String DEMO_EMAIL = "demo@example.com"; private static final String DEMO_PASSWORD = "swordfish"; - private static final String DEMO_SUBSCRIPTION_PLAN_ID = "local-smoke"; private final AccountRepository accountRepository; private final AccountTenantMembershipRepository accountTenantMembershipRepository; private final ProfileRepository profileRepository; - private final SubscriptionRepository subscriptionRepository; @Override @Transactional @@ -98,24 +92,6 @@ public void run(ApplicationArguments args) { profile.setPresenceVisibilityPolicy(ProfilePresenceVisibilityPolicy.FRIENDS_ONLY); profileRepository.save(profile); } - - List subscriptions = subscriptionRepository.findByTenantId(DEMO_TENANT_ID); - if (subscriptions.isEmpty()) { - Subscription subscription = new Subscription(); - subscription.setAccount(account); - subscription.setPlanId(DEMO_SUBSCRIPTION_PLAN_ID); - subscription.setStatus("active"); - subscription.setStartedAt(LocalDateTime.now()); - subscription.setTenantId(DEMO_TENANT_ID); - subscriptionRepository.save(subscription); - } else if (subscriptions.size() > 1) { - throw new IllegalStateException( - "Cannot seed demo tenant entitlement: tenant " - + DEMO_TENANT_ID - + " has ambiguous subscription authority (" - + subscriptions.size() - + " rows)"); - } } private static boolean isQuarantinedDemoMembership( diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/BootstrapRealmDto.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/BootstrapRealmDto.java index 239ad9298d..66d8c25812 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/BootstrapRealmDto.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/BootstrapRealmDto.java @@ -1,20 +1,26 @@ package net.firedevops.firemud.accountservice.dto; -/** Realm visible to a bootstrap-authenticated first-party client. */ +import java.util.UUID; + +/** Public realm selector evidence; its retained scope grants neither entry nor character access. */ public record BootstrapRealmDto( String worldSlug, String realmSlug, - String realmId, + UUID realmId, String displayName, - long tenantId, - long gameInstanceId, + UUID tenantId, + UUID gameInstanceId, long pointerVersion, long catalogRevision, - String playableStateNamespaceId, + UUID playableStateNamespaceId, String playableStateScope, - boolean requiresCharacterSelection, String stateScope, String characterCreationPolicy, String evaluatedAt, String connectScopeExpiresAt, - String connectScopeId) {} + String connectScopeId) { + @Override + public String toString() { + return "BootstrapRealmDto[nonadmitting, connectScopeId=]"; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/BootstrapWorldDto.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/BootstrapWorldDto.java index 9806a2487e..8e3bf534ee 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/BootstrapWorldDto.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/BootstrapWorldDto.java @@ -1,4 +1,4 @@ package net.firedevops.firemud.accountservice.dto; -/** World visible to a bootstrap-authenticated first-party client. */ -public record BootstrapWorldDto(String worldSlug, String displayName) {} +/** Tenant-qualified world selector visible to a bootstrap-authenticated first-party client. */ +public record BootstrapWorldDto(String tenantSlug, String worldSlug, String displayName) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextCallerContext.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextCallerContext.java index 2638dc9cfb..c0c0e8fa2d 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextCallerContext.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextCallerContext.java @@ -4,11 +4,11 @@ /** Parsed scope data from a verified Game Session mTLS call, never an independent capability. */ public record DirectTextCallerContext( - long accountId, - long tenantId, + UUID accountId, + UUID tenantId, UUID realmId, - String playableStateNamespaceId, + UUID playableStateNamespaceId, String playableStateScope, - long gameInstanceId, + UUID gameInstanceId, String sessionId, String requestId) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextJoinTarget.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextJoinTarget.java index b4273bf5b5..e593ee852f 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextJoinTarget.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextJoinTarget.java @@ -6,12 +6,12 @@ * Game Session's complete selected-target evidence, re-resolved by Account before scope issuance. */ public record DirectTextJoinTarget( - long tenantId, + UUID tenantId, UUID realmId, String worldSlug, String realmSlug, - String playableStateNamespaceId, + UUID playableStateNamespaceId, String playableStateScope, - long gameInstanceId, + UUID gameInstanceId, long catalogRevision, long pointerVersion) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/JoinPublicProductionResult.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/JoinPublicProductionResult.java index 803188b178..8140d09562 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/JoinPublicProductionResult.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/JoinPublicProductionResult.java @@ -1,12 +1,18 @@ package net.firedevops.firemud.accountservice.dto; -/** Durable explicit-JOIN outcome; a failure is returned so its receipt can commit first. */ +import java.util.UUID; + +/** + * Durable membership-operation outcome. Success preserves the exact membership admission flag; it + * is not a gameplay admission grant. A failure is returned so its receipt can commit first. + */ public record JoinPublicProductionResult( boolean success, String outcomeCode, String accountId, - long tenantId, + UUID tenantId, long membershipId, long membershipVersion, long membershipAuthorityGeneration, + boolean gameplayAdmissionAllowed, boolean replayed) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java index 4ce8feca92..edd338b5fa 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java @@ -434,15 +434,16 @@ public Preparation prepare( : dsl.fetchOne( "SELECT claimed_at FROM subscription_provisioning_attempts WHERE attempt_id = ?", provisioningAttemptId); + Instant provisioningNow = databaseNow(); if (provisioningAttemptId == null || !"provisioning".equals(current.status()) || claimedAttempt == null - || now.isBefore(instant(claimedAttempt, "claimed_at")) + || provisioningNow.isBefore(instant(claimedAttempt, "claimed_at")) || !"CLAIMED".equals(work.get("phase", String.class)) || !provisioningAttemptId.equals(work.get("last_attempt_id", UUID.class)) || current.rowVersion() != work.get("subscription_row_version", Long.class) - || !now.isBefore(instant(work, "lease_expires_at")) - || !now.isBefore(instant(work, "deadline_at"))) { + || !provisioningNow.isBefore(instant(work, "lease_expires_at")) + || !provisioningNow.isBefore(instant(work, "deadline_at"))) { throw new FenceRejectedException( "Initial confirmation lacks its exact durable provisioning claim"); } @@ -933,6 +934,11 @@ private AccountHostingSubscriptionLifecyclePolicy retainedPolicy(Record operatio Duration.ofMillis(operation.get("grace_millis", Long.class)))); } + /** Provisioning leases and dispatch fences share PostgreSQL time, not the observation clock. */ + private Instant databaseNow() { + return instant(Objects.requireNonNull(dsl.fetchOne("SELECT clock_timestamp() AS now")), "now"); + } + private Instant now() { return clock.instant().truncatedTo(ChronoUnit.MICROS); } @@ -1217,10 +1223,6 @@ public ClaimResult claim(UUID requestId, long expectedRowVersion, UUID attemptId prior == null ? expectedRowVersion : prior.get("claimed_row_version", Long.class); var current = intents.lockForProvisioningRecovery(requestId, versionToLock); var original = intents.findCreation(requestId).orElseThrow(); - Instant now = clock.instant().truncatedTo(ChronoUnit.MICROS); - if (now.isBefore(original.createdAt())) { - throw new FenceRejectedException("Provisioning clock predates the durable intent"); - } dsl.execute( "INSERT INTO subscription_provisioning_work (request_id, subscription_id, phase, row_version, " + "attempt_count, max_attempts, max_stalled_attempts, lease_millis, backoff_millis, deadline_at, retry_at) " @@ -1234,6 +1236,10 @@ public ClaimResult claim(UUID requestId, long expectedRowVersion, UUID attemptId utc(original.createdAt().plus(limits.absoluteTimeout())), utc(original.createdAt())); Record work = workForUpdate(requestId); + Instant now = databaseNow(); + if (now.isBefore(original.createdAt())) { + throw new FenceRejectedException("Provisioning clock predates the durable intent"); + } if ("BILLING_RECONCILIATION_TERMINAL_FAILURE".equals(work.get("phase", String.class))) { return new ClaimResult(Disposition.TERMINAL_FAILURE, null); } @@ -1333,15 +1339,14 @@ public ProviderDispatch prepareProviderDispatch(ProvisioningClaim supplied, UUID "INSERT INTO subscription_provider_dispatch_claim " + "(creation_request_id, subscription_id, provider_operation_id, dispatch_id, classification, " + "first_attempt_id, first_claimed_row_version, recorded_at) " - + "VALUES (?, ?, ?, ?, 'FIRST_DISPATCH', ?, ?, ?::timestamptz) " + + "VALUES (?, ?, ?, ?, 'FIRST_DISPATCH', ?, ?, clock_timestamp()) " + "ON CONFLICT (creation_request_id) DO NOTHING", original.requestId(), original.subscriptionId(), original.subscriptionProvisioningRequestId(), dispatchId, retained.attemptId(), - retained.subscriptionRowVersion(), - utc(now())); + retained.subscriptionRowVersion()); DispatchReceipt receipt = dispatchReceipt(original.requestId()); requireDispatchBinding(retained, receipt); boolean initial = @@ -1557,7 +1562,7 @@ public Disposition deferUnresolved(ProvisioningClaim claim) { intents.lockForProvisioningRecovery( claim.creation().requestId(), claim.subscriptionRowVersion()); Record work = workForUpdate(claim.creation().requestId()); - Instant now = clock.instant().truncatedTo(ChronoUnit.MICROS); + Instant now = databaseNow(); if (now.isBefore(claim.claimedAt())) { throw new FenceRejectedException("Provisioning clock predates its retained claim"); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java index dc5ae14240..60d9ce907c 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java @@ -9,6 +9,7 @@ import java.time.Instant; import java.util.Objects; import java.util.Optional; +import java.util.Set; import java.util.UUID; import java.util.regex.Pattern; import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; @@ -30,6 +31,17 @@ value = "EI_EXPOSE_REP2", justification = "Injected DSLContext is an internal Spring collaborator.") public class AccountJoinOperationRepository { + private static final Set DEFINITIVE_FAILURES = + Set.of( + "CONNECT_SCOPE_INVALID", + "CONNECT_SCOPE_MISMATCH", + "PUBLIC_PRODUCTION_ADMISSION_DENIED", + "TENANT_BILLING_BLOCKED", + "IDEMPOTENCY_CONFLICT", + "MEMBERSHIP_RECONCILIATION_REQUIRED", + "REALM_UNAVAILABLE"); + private static final Set RETRYABLE_FAILURES = + Set.of("AUTH_UNAVAILABLE", "ENTITLEMENT_UNAVAILABLE", "ADMISSION_POINTER_UNAVAILABLE"); private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); private static final String CANONICAL_SELECT_COLUMNS = "SELECT request_id, account_id, tenant_id, verified_caller_binding, scope_token_hash, " @@ -252,8 +264,30 @@ public CanonicalJoinOperationEvidence bindCanonicalPolicyEvidence( if (operation.requestDigest() != null) { requireCanonicalPolicyMatch(operation, requestDigest, allowPublicJoin, entitlementVersion); - return operation; + if (!"PENDING".equals(operation.status()) + || ("AVAILABLE".equals(operation.lastAttemptAuthorityAvailability()) + && operation.lastAttemptFailureCode() == null)) return operation; + int recovered = + dsl.execute( + "UPDATE account_join_operations SET last_attempt_authority_availability = 'AVAILABLE', " + + "last_attempt_failure_code = NULL, updated_at = CURRENT_TIMESTAMP " + + "WHERE request_id = ? AND operation_representation_version = 2 AND status = 'PENDING'", + requestId); + if (recovered != 1) + throw new CanonicalJoinOperationConflictException( + "Canonical JOIN attempt recovery changed"); + CanonicalJoinOperationEvidence readback = + readCanonicalEvidenceByRequestId(requestId, false).orElseThrow(); + requireCanonicalIntentMatch(readback, requestId, callerBinding, intentDigest, scopeEvidence); + requireCanonicalPolicyMatch(readback, requestDigest, allowPublicJoin, entitlementVersion); + if (!"AVAILABLE".equals(readback.lastAttemptAuthorityAvailability()) + || readback.lastAttemptFailureCode() != null) + throw new IllegalStateException("Canonical JOIN recovered attempt readback differs"); + return readback; } + if (!"PENDING".equals(operation.status())) + throw new CanonicalJoinOperationConflictException( + "Terminal canonical JOIN cannot acquire policy evidence"); int updated = dsl.execute( @@ -282,17 +316,34 @@ public CanonicalJoinOperationEvidence bindCanonicalPolicyEvidence( return committed; } - /** Records unavailable policy without creating a policy result, entitlement version or digest. */ + /** Records policy unavailability without downgrading an already-bound available policy. */ @Transactional(propagation = Propagation.MANDATORY) public CanonicalJoinOperationEvidence recordCanonicalPolicyUnavailable( String requestId, CanonicalJoinScopeV2 scope, String callerBinding, String failureCode) { + return recordCanonicalAttemptFailure( + requestId, scope, callerBinding, "UNAVAILABLE", failureCode); + } + + /** + * Records only a retryable PENDING attempt. Bound policy bytes are immutable; an unbound intent + * retains no policy/version/digest. This journal method supplies no source authentication. + */ + @Transactional(propagation = Propagation.MANDATORY) + public CanonicalJoinOperationEvidence recordCanonicalAttemptFailure( + String requestId, + CanonicalJoinScopeV2 scope, + String callerBinding, + String authorityAvailability, + String failureCode) { requireWritableOwnerTransaction(); requireCanonicalOperationInput(requestId, callerBinding); Objects.requireNonNull(scope, "Canonical JOIN scope is required"); - if (failureCode == null || failureCode.isBlank() || failureCode.length() > 64) { + if (!("UNAVAILABLE".equals(authorityAvailability) + || "NOT_EVALUATED".equals(authorityAvailability)) + || failureCode == null + || !RETRYABLE_FAILURES.contains(failureCode)) throw new IllegalArgumentException( - "JOIN attempt failure code must contain 1 to 64 characters"); - } + "Canonical JOIN retryable attempt classification is invalid"); CanonicalConnectScopeEvidence scopeEvidence = requireIncomingScope(scope); String intentDigest = AccountJoinDigest.intentV2(requestId, scope, callerBinding); CanonicalJoinOperationEvidence operation = @@ -301,42 +352,91 @@ public CanonicalJoinOperationEvidence recordCanonicalPolicyUnavailable( () -> new CanonicalJoinOperationConflictException("Canonical JOIN intent is absent")); requireCanonicalIntentMatch(operation, requestId, callerBinding, intentDigest, scopeEvidence); - if (operation.requestDigest() != null) { + if (!"PENDING".equals(operation.status())) throw new CanonicalJoinOperationConflictException( - "Available canonical JOIN policy evidence cannot be downgraded"); - } - + "Terminal canonical JOIN cannot record another attempt"); int updated = dsl.execute( - "UPDATE account_join_operations SET entitlement_authority_availability = 'UNAVAILABLE', " - + "last_attempt_authority_availability = 'UNAVAILABLE', " - + "last_attempt_failure_code = ?, updated_at = CURRENT_TIMESTAMP " - + "WHERE request_id = ? AND operation_representation_version = 2 " - + "AND status = 'PENDING' AND request_digest IS NULL", + "UPDATE account_join_operations SET entitlement_authority_availability = " + + "CASE WHEN request_digest IS NULL THEN ? ELSE entitlement_authority_availability END, " + + "last_attempt_authority_availability = ?, last_attempt_failure_code = ?, " + + "updated_at = CURRENT_TIMESTAMP WHERE request_id = ? " + + "AND operation_representation_version = 2 AND status = 'PENDING'", + authorityAvailability, + authorityAvailability, failureCode, requestId); - if (updated != 1) { - throw new CanonicalJoinOperationConflictException( - "Canonical JOIN operation changed while recording policy unavailability"); - } + if (updated != 1) + throw new CanonicalJoinOperationConflictException("Canonical JOIN attempt changed"); + CanonicalJoinOperationEvidence readback = + readCanonicalEvidenceByRequestId(requestId, false).orElseThrow(); + requireCanonicalIntentMatch(readback, requestId, callerBinding, intentDigest, scopeEvidence); + if (!Objects.equals(operation.requestDigest(), readback.requestDigest()) + || !Objects.equals(operation.requestDigestVersion(), readback.requestDigestVersion()) + || !Objects.equals(operation.entitlementVersion(), readback.entitlementVersion()) + || !Objects.equals(operation.allowPublicJoin(), readback.allowPublicJoin()) + || !authorityAvailability.equals(readback.lastAttemptAuthorityAvailability()) + || !failureCode.equals(readback.lastAttemptFailureCode()) + || (operation.requestDigest() != null + && !operation + .entitlementAuthorityAvailability() + .equals(readback.entitlementAuthorityAvailability()))) + throw new IllegalStateException( + "Canonical JOIN attempt readback changed policy or diagnostics"); + return readback; + } - CanonicalJoinOperationEvidence committed = - readCanonicalEvidenceByRequestId(requestId, false) + /** + * Persists or exactly replays a definitive, noncommitting failure with the original scope/intent + * and optional original policy. Replay performs no UPDATE. Caller/target/current-authority checks + * belong to the public adapter, not this persistence receipt. + */ + @Transactional(propagation = Propagation.MANDATORY) + public CanonicalJoinOperationEvidence finishCanonicalFailure( + String requestId, CanonicalJoinScopeV2 scope, String callerBinding, String outcome) { + requireWritableOwnerTransaction(); + requireCanonicalOperationInput(requestId, callerBinding); + Objects.requireNonNull(scope, "Canonical JOIN scope is required"); + if (outcome == null || !DEFINITIVE_FAILURES.contains(outcome)) + throw new IllegalArgumentException( + "Canonical JOIN definitive failure classification is invalid"); + CanonicalConnectScopeEvidence scopeEvidence = requireIncomingScope(scope); + String intentDigest = AccountJoinDigest.intentV2(requestId, scope, callerBinding); + CanonicalJoinOperationEvidence operation = + lockCanonicalEvidenceByRequestId(requestId) .orElseThrow( () -> - new IllegalStateException( - "Canonical JOIN unavailable-attempt readback is absent")); - requireCanonicalIntentMatch(committed, requestId, callerBinding, intentDigest, scopeEvidence); - if (!"UNAVAILABLE".equals(committed.entitlementAuthorityAvailability()) - || committed.entitlementVersion() != null - || committed.allowPublicJoin() != null - || committed.requestDigestVersion() != null - || committed.requestDigest() != null - || !failureCode.equals(committed.lastAttemptFailureCode())) { - throw new IllegalStateException( - "Canonical JOIN unavailable attempt readback contains policy evidence"); - } - return committed; + new CanonicalJoinOperationConflictException("Canonical JOIN intent is absent")); + requireCanonicalIntentMatch(operation, requestId, callerBinding, intentDigest, scopeEvidence); + if ("FAILED".equals(operation.status()) && outcome.equals(operation.outcome())) + return operation; + if (!"PENDING".equals(operation.status())) + throw new CanonicalJoinOperationConflictException( + "Canonical JOIN terminal outcome conflicts"); + int updated = + dsl.execute( + "UPDATE account_join_operations SET status = 'FAILED', outcome = ?, " + + "entitlement_authority_availability = CASE WHEN request_digest IS NULL " + + "THEN 'NOT_EVALUATED' ELSE entitlement_authority_availability END, " + + "last_attempt_authority_availability = CASE WHEN request_digest IS NULL " + + "THEN 'NOT_EVALUATED' ELSE 'AVAILABLE' END, last_attempt_failure_code = NULL, " + + "updated_at = CURRENT_TIMESTAMP WHERE request_id = ? " + + "AND operation_representation_version = 2 AND status = 'PENDING'", + outcome, + requestId); + if (updated != 1) + throw new CanonicalJoinOperationConflictException("Canonical JOIN failure changed"); + CanonicalJoinOperationEvidence readback = + readCanonicalEvidenceByRequestId(requestId, false).orElseThrow(); + requireCanonicalIntentMatch(readback, requestId, callerBinding, intentDigest, scopeEvidence); + if (!"FAILED".equals(readback.status()) + || !outcome.equals(readback.outcome()) + || !Objects.equals(operation.requestDigest(), readback.requestDigest()) + || !Objects.equals(operation.requestDigestVersion(), readback.requestDigestVersion()) + || !Objects.equals(operation.entitlementVersion(), readback.entitlementVersion()) + || !Objects.equals(operation.allowPublicJoin(), readback.allowPublicJoin())) + throw new IllegalStateException("Canonical JOIN failed receipt readback differs"); + return readback; } /** @@ -350,29 +450,57 @@ public CanonicalJoinOperationEvidence commitCanonicalFirstJoin( CanonicalJoinScopeV2 scope, String callerBinding, CanonicalJoinTerminalProof proof) { + if (proof.eventSequence() != 1L + || proof.membershipVersion() != 2L + || proof.membershipAuthorityGeneration() != 1L + || proof.auditEventId() == null) { + throw new IllegalArgumentException("Exact first-JOIN terminal proof required"); + } + return commitCanonicalJoin(requestId, scope, callerBinding, "JOINED", proof); + } + + /** Persists the exact current ACTIVE snapshot or the same-transaction restore terminal. */ + @Transactional(propagation = Propagation.MANDATORY) + public CanonicalJoinOperationEvidence commitCanonicalJoin( + String requestId, + CanonicalJoinScopeV2 scope, + String callerBinding, + String outcome, + CanonicalJoinTerminalProof proof) { requireWritableOwnerTransaction(); + if (outcome == null || !Set.of("JOINED", "ALREADY_ACTIVE").contains(outcome)) { + throw new CanonicalJoinOperationConflictException("Canonical JOIN outcome/proof conflict"); + } requireCanonicalOperationInput(requestId, callerBinding); Objects.requireNonNull(scope, "Canonical JOIN scope is required"); Objects.requireNonNull(proof, "Canonical first-JOIN terminal proof is required"); CanonicalConnectScopeEvidence scopeEvidence = requireIncomingScope(scope); String intentDigest = AccountJoinDigest.intentV2(requestId, scope, callerBinding); + CanonicalJoinOperationEvidence operation = + lockCanonicalEvidenceByRequestId(requestId) + .orElseThrow( + () -> + new CanonicalJoinOperationConflictException("Canonical JOIN intent is absent")); + boolean publicJoin = Boolean.TRUE.equals(operation.allowPublicJoin()); + if ("JOINED".equals(outcome) && !publicJoin) { + throw new CanonicalJoinOperationConflictException( + "Transition JOIN requires positive public policy"); + } String requestDigest = AccountJoinDigest.requestV2( scope, callerBinding, EntitlementAvailabilityV2.AVAILABLE, - true, + publicJoin, proof.entitlementVersion()); - CanonicalJoinOperationEvidence operation = - lockCanonicalEvidenceByRequestId(requestId) - .orElseThrow( - () -> - new CanonicalJoinOperationConflictException("Canonical JOIN intent is absent")); requireCanonicalIntentMatch(operation, requestId, callerBinding, intentDigest, scopeEvidence); - requireCanonicalPolicyMatch(operation, requestDigest, true, proof.entitlementVersion()); + requireCanonicalPolicyMatch(operation, requestDigest, publicJoin, proof.entitlementVersion()); requireTerminalProofScope(proof, requestId, scope, operation); + if ("JOINED".equals(outcome) != (proof.auditEventId() != null)) { + throw new CanonicalJoinOperationConflictException("Canonical JOIN outcome/proof conflict"); + } if ("COMMITTED".equals(operation.status())) { - if (!"JOINED".equals(operation.outcome()) + if (!outcome.equals(operation.outcome()) || !Objects.equals(operation.terminalProof(), proof)) { throw new CanonicalJoinOperationConflictException( "Canonical JOIN request ID conflicts with its committed receipt"); @@ -386,27 +514,31 @@ public CanonicalJoinOperationEvidence commitCanonicalFirstJoin( int updated = dsl.execute( - "UPDATE account_join_operations SET status = 'COMMITTED', outcome = 'JOINED', " - + "membership_id = ?, outcome_membership_version = 2, " - + "outcome_membership_authority_generation = 1, " + "UPDATE account_join_operations SET status = 'COMMITTED', outcome = ?, " + + "membership_id = ?, outcome_membership_version = ?, " + + "outcome_membership_authority_generation = ?, " + "membership_authority_outbox_stream_key = ?, " + "membership_authority_outbox_sequence = ?, " + "membership_authority_event_id = ?, membership_authority_event_digest = ?, " + "join_audit_event_id = ?, join_audit_payload_digest = ?, " + "join_audit_occurred_at = ?, last_attempt_failure_code = NULL, " + + "last_attempt_authority_availability = 'AVAILABLE', " + "updated_at = CURRENT_TIMESTAMP " + "WHERE request_id = ? AND operation_representation_version = 2 " + "AND account_uuid = ? AND tenant_uuid = ? " + "AND verified_caller_binding = ? AND intent_digest = ? " + "AND request_digest = ? AND status = 'PENDING'", + outcome, proof.membershipId(), + proof.membershipVersion(), + proof.membershipAuthorityGeneration(), proof.eventStreamKey(), proof.eventSequence(), proof.eventId(), proof.eventDigest(), proof.auditEventId(), proof.auditPayloadDigest(), - toLocalDateTime(proof.auditOccurredAt()), + proof.auditOccurredAt() == null ? null : toLocalDateTime(proof.auditOccurredAt()), requestId, scope.accountId(), scope.tenantId(), @@ -423,9 +555,9 @@ public CanonicalJoinOperationEvidence commitCanonicalFirstJoin( .orElseThrow( () -> new IllegalStateException("Canonical JOIN receipt readback is absent")); requireCanonicalIntentMatch(committed, requestId, callerBinding, intentDigest, scopeEvidence); - requireCanonicalPolicyMatch(committed, requestDigest, true, proof.entitlementVersion()); + requireCanonicalPolicyMatch(committed, requestDigest, publicJoin, proof.entitlementVersion()); if (!"COMMITTED".equals(committed.status()) - || !"JOINED".equals(committed.outcome()) + || !outcome.equals(committed.outcome()) || !Objects.equals(committed.terminalProof(), proof)) { throw new IllegalStateException("Canonical JOIN receipt readback differs from its proof"); } @@ -649,6 +781,20 @@ private static CanonicalJoinOperationEvidence toCanonicalOperationEvidence( Long membershipAuthorityGeneration = row.get("outcome_membership_authority_generation", Long.class); CanonicalJoinTerminalProof terminalProof = null; + if (!"COMMITTED".equals(status)) { + for (String column : + Set.of( + "membership_authority_outbox_stream_key", + "membership_authority_outbox_sequence", + "membership_authority_event_id", + "membership_authority_event_digest", + "join_audit_event_id", + "join_audit_payload_digest", + "join_audit_occurred_at")) { + if (row.get(column) != null) + throw new IllegalStateException("Noncommitting canonical JOIN carries success proof"); + } + } if ("COMMITTED".equals(status)) { terminalProof = new CanonicalJoinTerminalProof( @@ -656,9 +802,12 @@ private static CanonicalJoinOperationEvidence toCanonicalOperationEvidence( required(row, "membership_authority_outbox_sequence", Long.class), required(row, "membership_authority_event_id", String.class), required(row, "membership_authority_event_digest", String.class), - required(row, "join_audit_event_id", UUID.class), - required(row, "join_audit_payload_digest", String.class), - toInstant(required(row, "join_audit_occurred_at", java.time.LocalDateTime.class)), + row.get("join_audit_event_id", UUID.class), + row.get("join_audit_payload_digest", String.class), + row.get("join_audit_occurred_at") == null + ? null + : toInstant( + required(row, "join_audit_occurred_at", java.time.LocalDateTime.class)), required(row, "entitlement_version", Long.class), required(row, "membership_id", Long.class), required(row, "outcome_membership_version", Long.class), @@ -703,8 +852,7 @@ private static void requireTerminalProofScope( ("account-join-audit/v1:" + requestId) .getBytes(java.nio.charset.StandardCharsets.UTF_8)); if (!expectedStreamKey.equals(proof.eventStreamKey()) - || proof.eventSequence() != 1L - || !expectedAuditEventId.equals(proof.auditEventId()) + || (proof.auditEventId() != null && !expectedAuditEventId.equals(proof.auditEventId())) || !Objects.equals(operation.entitlementVersion(), proof.entitlementVersion())) { throw new CanonicalJoinOperationConflictException( "Canonical JOIN terminal proof differs from its exact request and owner scope"); @@ -879,7 +1027,7 @@ public CanonicalJoinOperationEvidence( || intentDigest == null || entitlementAuthorityAvailability == null || lastAttemptAuthorityAvailability == null - || (!"PENDING".equals(status) && !"COMMITTED".equals(status)) + || (!"PENDING".equals(status) && !"COMMITTED".equals(status) && !"FAILED".equals(status)) || callerBoundAuthorityInvalidated || scopeEvidence == null || scopeEvidence.privateAccountId() != privateAccountId @@ -887,22 +1035,28 @@ public CanonicalJoinOperationEvidence( || !connectScopeDigest.equals(scopeEvidence.scopeDigest())) { throw new IllegalArgumentException("Canonical JOIN operation evidence is incomplete"); } - if ("PENDING".equals(status) - ? outcome != null + if (!"COMMITTED".equals(status) + ? ("PENDING".equals(status) + ? outcome != null + : outcome == null || !DEFINITIVE_FAILURES.contains(outcome)) || membershipId != null || membershipVersion != null || membershipAuthorityGeneration != null || terminalProof != null - : !"JOINED".equals(outcome) + : outcome == null + || !Set.of("JOINED", "ALREADY_ACTIVE").contains(outcome) || membershipId == null || membershipId <= 0L - || !Long.valueOf(2L).equals(membershipVersion) - || !Long.valueOf(1L).equals(membershipAuthorityGeneration) + || membershipVersion == null + || membershipVersion <= 0L + || membershipAuthorityGeneration == null + || membershipAuthorityGeneration <= 0L || terminalProof == null || membershipId.longValue() != terminalProof.membershipId() || membershipVersion.longValue() != terminalProof.membershipVersion() || membershipAuthorityGeneration.longValue() - != terminalProof.membershipAuthorityGeneration()) { + != terminalProof.membershipAuthorityGeneration() + || ("JOINED".equals(outcome) != (terminalProof.auditEventId() != null))) { throw new IllegalArgumentException("Canonical JOIN terminal evidence is inconsistent"); } requireSha256(scopeTokenHash, "Canonical JOIN scope token hash"); @@ -913,9 +1067,7 @@ public CanonicalJoinOperationEvidence( || entitlementVersion == null || entitlementVersion <= 0L || !Integer.valueOf(2).equals(requestDigestVersion) - || requestDigest == null - || lastAttemptFailureCode != null - || !"AVAILABLE".equals(lastAttemptAuthorityAvailability)) { + || requestDigest == null) { throw new IllegalArgumentException( "Canonical JOIN available policy evidence is incomplete"); } @@ -925,19 +1077,26 @@ public CanonicalJoinOperationEvidence( && allowPublicJoin == null && entitlementVersion == null && requestDigestVersion == null - && requestDigest == null - && (("UNAVAILABLE".equals(entitlementAuthorityAvailability) - && "UNAVAILABLE".equals(lastAttemptAuthorityAvailability) - && lastAttemptFailureCode != null - && !lastAttemptFailureCode.isBlank()) - || ("NOT_EVALUATED".equals(entitlementAuthorityAvailability) - && "NOT_EVALUATED".equals(lastAttemptAuthorityAvailability) - && lastAttemptFailureCode == null))) { - // No policy outcome has been fabricated for this PENDING intent. + && requestDigest == null) { + if (!entitlementAuthorityAvailability.equals(lastAttemptAuthorityAvailability)) + throw new IllegalArgumentException("Unbound canonical JOIN attempt availability differs"); } else { throw new IllegalArgumentException( "Canonical JOIN policy-attempt evidence is inconsistent"); } + boolean retryableAttempt = + "PENDING".equals(status) + && ("UNAVAILABLE".equals(lastAttemptAuthorityAvailability) + || "NOT_EVALUATED".equals(lastAttemptAuthorityAvailability)) + && lastAttemptFailureCode != null + && RETRYABLE_FAILURES.contains(lastAttemptFailureCode); + boolean cleanAttempt = + lastAttemptFailureCode == null + && (requestDigest == null + ? "NOT_EVALUATED".equals(lastAttemptAuthorityAvailability) + : "AVAILABLE".equals(lastAttemptAuthorityAvailability)); + if (!retryableAttempt && !cleanAttempt) + throw new IllegalArgumentException("Canonical JOIN attempt diagnostics are inconsistent"); } } @@ -957,17 +1116,18 @@ public record CanonicalJoinTerminalProof( if (eventStreamKey == null || eventId == null || eventId.isBlank() - || eventSequence != 1L - || auditEventId == null - || auditOccurredAt == null + || eventSequence <= 0L + || ((auditEventId == null) != (auditOccurredAt == null)) + || ((auditEventId == null) != (auditPayloadDigest == null)) || entitlementVersion <= 0L || membershipId <= 0L - || membershipVersion != 2L - || membershipAuthorityGeneration != 1L) { + || membershipVersion <= 0L + || membershipAuthorityGeneration <= 0L) { throw new IllegalArgumentException("Canonical first-JOIN terminal proof is incomplete"); } requireSha256(eventDigest, "Canonical membership event digest"); - requireSha256(auditPayloadDigest, "Canonical JOIN audit payload digest"); + if (auditPayloadDigest != null) + requireSha256(auditPayloadDigest, "Canonical JOIN audit payload digest"); } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepository.java index b1e96d9f72..3a5e3016e4 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepository.java @@ -218,6 +218,95 @@ public PairAuthority commitTransition(PairAuthority expected, PairTransition tra return advanced; } + /** Advances an existing positive pair after its exact restored membership event was appended. */ + @Transactional(propagation = Propagation.MANDATORY) + public PairAuthority commitRestore(PairAuthority expected, PairTransition transition) { + requireOwnerWriteTransaction(); + Objects.requireNonNull(expected); + Objects.requireNonNull(transition); + requireFreshProvenance(expected.provenance()); + long nextSequence = increment(expected.eventSequence(), "membership event sequence"); + long nextVersion = increment(expected.membershipVersion(), "membership version"); + if (!expected.membershipExists() + || expected.eventSequence() <= 0L + || !transition.membershipExists() + || transition.eventSequence() != nextSequence + || transition.callerBoundAuthorityInvalidated() + || !expected.equals( + readForUpdate(expected.accountUuid(), expected.tenantUuid()).orElseThrow())) { + throw new IllegalStateException("Restore requires the exact current positive pair"); + } + Record ownerEvidence = + dsl.fetchOne( + "SELECT EXISTS (SELECT 1 FROM account_authority_outbox_events next_event " + + "JOIN account_authority_outbox_streams stream USING (outbox_stream_key) " + + "JOIN account_authority_outbox_events prior_event USING (outbox_stream_key) " + + "JOIN accounts account ON account.account_uuid = ? " + + "JOIN account_tenant_membership member ON member.account_id = account.id AND member.tenant_uuid = ? " + + "WHERE next_event.outbox_stream_key = ? AND next_event.outbox_sequence = ? " + + "AND next_event.event_id = ? AND next_event.event_digest = ? AND stream.last_sequence = ? " + + "AND prior_event.outbox_sequence = ? AND prior_event.event_id = ? AND prior_event.event_digest = ? " + + "AND convert_from(prior_event.payload, 'UTF8')::JSONB ->> 'membershipLifecycleState' = 'INACTIVE' " + + "AND member.lifecycle_state = 'ACTIVE' AND member.gameplay_admission_allowed IS TRUE " + + "AND member.membership_version = ? AND member.membership_authority_generation = ?)", + expected.accountUuid(), + expected.tenantUuid(), + "account:auth-authority:v1:membership/" + + expected.accountUuid() + + "/" + + expected.tenantUuid(), + nextSequence, + transition.eventId(), + transition.eventDigest(), + nextSequence, + expected.eventSequence(), + expected.eventId(), + expected.eventDigest(), + nextVersion, + expected.membershipAuthorityGeneration()); + if (ownerEvidence == null || !Boolean.TRUE.equals(ownerEvidence.get(0, Boolean.class))) { + throw new IllegalStateException( + "Restore pair requires actual current membership and event evidence"); + } + int changed = + dsl.execute( + "UPDATE " + + TABLE + + " SET membership_version = ?, last_event_sequence = ?, " + + "last_event_id = ?, last_event_digest = ?, last_transition_invalidated = FALSE " + + "WHERE account_uuid = ? AND tenant_uuid = ? AND membership_exists IS TRUE " + + "AND membership_version = ? AND membership_authority_generation = ? " + + "AND last_event_sequence = ? AND last_event_id = ? AND last_event_digest = ?", + nextVersion, + nextSequence, + transition.eventId(), + transition.eventDigest(), + expected.accountUuid(), + expected.tenantUuid(), + expected.membershipVersion(), + expected.membershipAuthorityGeneration(), + expected.eventSequence(), + expected.eventId(), + expected.eventDigest()); + if (changed != 1) throw new IllegalStateException("Restore pair compare-and-advance failed"); + PairAuthority actual = + readForUpdate(expected.accountUuid(), expected.tenantUuid()).orElseThrow(); + PairAuthority required = + new PairAuthority( + expected.accountUuid(), + expected.tenantUuid(), + expected.provenance(), + true, + nextVersion, + expected.membershipAuthorityGeneration(), + nextSequence, + transition.eventId(), + transition.eventDigest(), + false); + if (!required.equals(actual)) throw new IllegalStateException("Restore pair readback differs"); + return actual; + } + private static void requireScope(UUID accountUuid, UUID tenantUuid) { if (accountUuid == null || tenantUuid == null || isNil(accountUuid) || isNil(tenantUuid)) { throw new IllegalArgumentException("Canonical non-nil Account and tenant UUIDs are required"); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java index 6618c17601..f5fac1625f 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java @@ -294,6 +294,51 @@ public AccountTenantMembership createFreshMembershipForJoin(UUID accountUuid, UU return readback; } + /** Stages an INACTIVE restore; its event, pair and terminal receipt must commit atomically. */ + @Transactional(propagation = Propagation.MANDATORY) + public AccountTenantMembership restoreFreshMembershipForJoin( + UUID accountUuid, UUID tenantUuid, AccountTenantMembership expected) { + requireOwnerWriteTransaction(); + AccountTenantMembership current = + findFreshMembershipForUpdate(accountUuid, tenantUuid) + .orElseThrow(() -> new IllegalStateException("Restore membership is absent")); + if (expected == null + || !Objects.equals(current.getId(), expected.getId()) + || !"INACTIVE".equals(current.getLifecycleState()) + || current.getMembershipVersion() != expected.getMembershipVersion() + || current.getMembershipAuthorityGeneration() + != expected.getMembershipAuthorityGeneration()) { + throw new IllegalStateException("Restore membership changed from its locked snapshot"); + } + long next = increment(current.getMembershipVersion(), "membership version"); + int changed = + dsl.execute( + "UPDATE account_tenant_membership SET lifecycle_state = 'ACTIVE', " + + "gameplay_admission_allowed = TRUE, membership_version = ?, " + + "authority_provenance = 'EXPLICIT_JOIN' WHERE id = ? AND account_id = ? " + + "AND tenant_id IS NULL AND tenant_uuid = ? AND lifecycle_state = 'INACTIVE' " + + "AND membership_version = ? AND membership_authority_generation = ?", + next, + current.getId(), + current.getAccount().getId(), + tenantUuid, + current.getMembershipVersion(), + current.getMembershipAuthorityGeneration()); + if (changed != 1) + throw new IllegalStateException("Restore membership compare-and-advance failed"); + AccountTenantMembership restored = + findCanonicalMembershipForUpdate(accountUuid, tenantUuid).orElseThrow(); + if (!"ACTIVE".equals(restored.getLifecycleState()) + || !restored.isGameplayAdmissionAllowed() + || restored.getMembershipVersion() != next + || restored.getMembershipAuthorityGeneration() != current.getMembershipAuthorityGeneration() + || !Objects.equals(restored.getId(), current.getId()) + || !"EXPLICIT_JOIN".equals(restored.getAuthorityProvenance())) { + throw new IllegalStateException("Restore membership readback differs"); + } + return restored; + } + /** Account-fenced absence enrollment for the fresh creator owner; creates no membership. */ @Transactional(propagation = Propagation.MANDATORY) public PairAuthority prepareFreshCreatorAbsence(UUID accountUuid, UUID tenantUuid) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/RetainedSubscriptionEvidenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/RetainedSubscriptionEvidenceRepository.java new file mode 100644 index 0000000000..5aa35ca5b9 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/RetainedSubscriptionEvidenceRepository.java @@ -0,0 +1,41 @@ +package net.firedevops.firemud.accountservice.repository; + +import static net.firedevops.firemud.accountservice.jooq.Tables.ACCOUNT_RETAINED_SUBSCRIPTION_EVIDENCE; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.List; +import net.firedevops.firemud.accountservice.entity.RetainedSubscriptionEvidence; +import org.jooq.DSLContext; +import org.springframework.stereotype.Repository; + +/** Historical evidence for Account retention/deletion checks only; no current-tenant selector. */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring collaborator.") +public class RetainedSubscriptionEvidenceRepository { + private final DSLContext dsl; + + public RetainedSubscriptionEvidenceRepository(DSLContext dsl) { + this.dsl = dsl; + } + + public List findHistoryByAccountId(Long accountId) { + var evidence = ACCOUNT_RETAINED_SUBSCRIPTION_EVIDENCE; + return dsl.selectFrom(evidence) + .where(evidence.ACCOUNT_ID.eq(accountId)) + .orderBy(evidence.ID.asc()) + .fetch( + row -> + new RetainedSubscriptionEvidence( + row.get(evidence.ID), + row.get(evidence.ACCOUNT_ID), + row.get(evidence.PLAN_ID), + row.get(evidence.STATUS), + row.get(evidence.STARTED_AT), + row.get(evidence.ENDED_AT), + row.get(evidence.TENANT_ID), + row.get(evidence.ENTITLEMENT_VERSION), + row.get(evidence.TENANT_AUTHORITY_GENERATION))); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/SubscriptionRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/SubscriptionRepository.java deleted file mode 100644 index 483e041c33..0000000000 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/SubscriptionRepository.java +++ /dev/null @@ -1,158 +0,0 @@ -package net.firedevops.firemud.accountservice.repository; - -import static net.firedevops.firemud.accountservice.jooq.Tables.ACCOUNTS; -import static net.firedevops.firemud.accountservice.jooq.Tables.SUBSCRIPTION; - -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import java.util.List; -import java.util.UUID; -import net.firedevops.firemud.accountservice.entity.Subscription; -import org.jooq.DSLContext; -import org.jooq.Record; -import org.springframework.stereotype.Repository; - -@Repository -@SuppressFBWarnings( - value = "EI_EXPOSE_REP2", - justification = "Injected DSLContext is an internal Spring collaborator.") -public class SubscriptionRepository { - private final DSLContext dsl; - - public SubscriptionRepository(DSLContext dsl) { - this.dsl = dsl; - } - - public List findByTenantId(Long tenantId) { - return baseSelect() - .where(SUBSCRIPTION.TENANT_ID.eq(tenantId)) - .orderBy(SUBSCRIPTION.ID.asc()) - .fetch(this::toEntity); - } - - /** Shares the row lock with subscription writers through the JOIN commit boundary. */ - public List findByTenantIdForUpdate(Long tenantId) { - return baseSelect() - .where(SUBSCRIPTION.TENANT_ID.eq(tenantId)) - .orderBy(SUBSCRIPTION.ID.asc()) - .forUpdate() - .of(SUBSCRIPTION) - .fetch(this::toEntity); - } - - public List findByAccountId(Long accountId) { - return baseSelect() - .where(SUBSCRIPTION.ACCOUNT_ID.eq(accountId)) - .orderBy(SUBSCRIPTION.ID.asc()) - .fetch(this::toEntity); - } - - public Subscription save(Subscription entity) { - Long accountId = entity.getAccount() == null ? null : entity.getAccount().getId(); - if (entity.getId() == null) { - var inserted = - dsl.insertInto(SUBSCRIPTION) - .set(SUBSCRIPTION.ACCOUNT_ID, accountId) - .set(SUBSCRIPTION.PLAN_ID, entity.getPlanId()) - .set(SUBSCRIPTION.STATUS, entity.getStatus()) - .set(SUBSCRIPTION.STARTED_AT, entity.getStartedAt()) - .set(SUBSCRIPTION.ENDED_AT, entity.getEndedAt()) - .set(SUBSCRIPTION.TENANT_ID, entity.getTenantId()) - .set(SUBSCRIPTION.ENTITLEMENT_VERSION, 1L) - .set(SUBSCRIPTION.TENANT_AUTHORITY_GENERATION, UUID.randomUUID()) - .returningResult( - SUBSCRIPTION.ID, - SUBSCRIPTION.ENTITLEMENT_VERSION, - SUBSCRIPTION.TENANT_AUTHORITY_GENERATION) - .fetchOne(); - if (inserted == null) { - throw new IllegalStateException("Subscription insert did not return its authority state"); - } - entity.setId(inserted.get(SUBSCRIPTION.ID)); - entity.setEntitlementVersion(1L); - entity.setTenantAuthorityGeneration(inserted.get(SUBSCRIPTION.TENANT_AUTHORITY_GENERATION)); - return entity; - } - var updated = - dsl.update(SUBSCRIPTION) - .set(SUBSCRIPTION.ACCOUNT_ID, accountId) - .set(SUBSCRIPTION.PLAN_ID, entity.getPlanId()) - .set(SUBSCRIPTION.STATUS, entity.getStatus()) - .set(SUBSCRIPTION.STARTED_AT, entity.getStartedAt()) - .set(SUBSCRIPTION.ENDED_AT, entity.getEndedAt()) - .set(SUBSCRIPTION.TENANT_ID, entity.getTenantId()) - .where( - SUBSCRIPTION - .ID - .eq(entity.getId()) - .and(SUBSCRIPTION.ENTITLEMENT_VERSION.eq(entity.getEntitlementVersion())) - .and( - entity.getTenantAuthorityGeneration() == null - ? SUBSCRIPTION.TENANT_AUTHORITY_GENERATION.isNull() - : SUBSCRIPTION.TENANT_AUTHORITY_GENERATION.eq( - entity.getTenantAuthorityGeneration()))) - .returningResult( - SUBSCRIPTION.ENTITLEMENT_VERSION, SUBSCRIPTION.TENANT_AUTHORITY_GENERATION) - .fetchOne(); - if (updated == null) { - throw JooqAccountRepositorySupport.staleWrite("subscription", entity.getId()); - } - entity.setEntitlementVersion(updated.get(SUBSCRIPTION.ENTITLEMENT_VERSION)); - entity.setTenantAuthorityGeneration(updated.get(SUBSCRIPTION.TENANT_AUTHORITY_GENERATION)); - return entity; - } - - public void deleteByAccountId(Long accountId, Long tenantId) { - dsl.deleteFrom(SUBSCRIPTION) - .where(SUBSCRIPTION.ACCOUNT_ID.eq(accountId).and(SUBSCRIPTION.TENANT_ID.eq(tenantId))) - .execute(); - } - - public void deleteByAccountId(Long accountId) { - dsl.deleteFrom(SUBSCRIPTION).where(SUBSCRIPTION.ACCOUNT_ID.eq(accountId)).execute(); - } - - private org.jooq.SelectOnConditionStep baseSelect() { - return dsl.select( - SUBSCRIPTION.ID, - SUBSCRIPTION.ACCOUNT_ID, - SUBSCRIPTION.PLAN_ID, - SUBSCRIPTION.STATUS, - SUBSCRIPTION.STARTED_AT, - SUBSCRIPTION.ENDED_AT, - SUBSCRIPTION.TENANT_ID, - SUBSCRIPTION.ENTITLEMENT_VERSION, - SUBSCRIPTION.TENANT_AUTHORITY_GENERATION, - ACCOUNTS.ID, - ACCOUNTS.USERNAME, - ACCOUNTS.EMAIL, - ACCOUNTS.PASSWORD_HASH, - ACCOUNTS.ROLE, - ACCOUNTS.EMAIL_VERIFIED, - ACCOUNTS.LOGIN_AUTH_MODES) - .from(SUBSCRIPTION) - .join(ACCOUNTS) - .on(SUBSCRIPTION.ACCOUNT_ID.eq(ACCOUNTS.ID)); - } - - private Subscription toEntity(Record record) { - Subscription entity = new Subscription(); - entity.setId(record.get(SUBSCRIPTION.ID)); - entity.setAccount( - JooqAccountRepositorySupport.partialAccount( - record.get(ACCOUNTS.ID), - record.get(ACCOUNTS.USERNAME), - record.get(ACCOUNTS.EMAIL), - record.get(ACCOUNTS.PASSWORD_HASH), - record.get(ACCOUNTS.ROLE), - record.get(ACCOUNTS.EMAIL_VERIFIED), - record.get(ACCOUNTS.LOGIN_AUTH_MODES))); - entity.setPlanId(record.get(SUBSCRIPTION.PLAN_ID)); - entity.setStatus(record.get(SUBSCRIPTION.STATUS)); - entity.setStartedAt(record.get(SUBSCRIPTION.STARTED_AT)); - entity.setEndedAt(record.get(SUBSCRIPTION.ENDED_AT)); - entity.setTenantId(record.get(SUBSCRIPTION.TENANT_ID)); - entity.setEntitlementVersion(record.get(SUBSCRIPTION.ENTITLEMENT_VERSION)); - entity.setTenantAuthorityGeneration(record.get(SUBSCRIPTION.TENANT_AUTHORITY_GENERATION)); - return entity; - } -} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java index c8c9bb63df..283d449115 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java @@ -9,6 +9,7 @@ import java.util.Map; import java.util.Objects; import java.util.UUID; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; import net.firedevops.firemud.accountservice.dto.AccountAuditTenantIdentity; @@ -21,6 +22,8 @@ import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Checkpoint; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ReadFence; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinOperationConflictException; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinOperationEvidence; @@ -43,8 +46,9 @@ import tools.jackson.databind.json.JsonMapper; /** - * Composes the existing canonical JOIN operation, first membership, authority event/pair, and - * Account-local tenant audit receipt in one caller-owned transaction. + * Composes canonical JOIN membership, authority event/pair, and Account-local terminal receipts in + * one caller-owned transaction. The exact first-JOIN primitive remains separately guarded; the + * existing-membership entry point retains ACTIVE snapshots or restores INACTIVE membership. * *

This is an owner-local persistence primitive, not a caller authenticator, target-currentness * check, public JOIN entry point, cross-service commit gate, or Logging receiver receipt. @@ -97,6 +101,257 @@ public AccountCanonicalFirstJoinTerminalCoordinator( @Transactional(propagation = Propagation.MANDATORY) public CanonicalJoinTerminalProof commitCanonicalFirstJoin( CanonicalJoinScopeV2 scope, String requestId, String verifiedCallerBinding) { + return commitCanonicalFirstJoin(scope, requestId, verifiedCallerBinding, null, null, null); + } + + /** + * Owner-local paid first JOIN, using the actual fence prepared in an earlier source transaction + * and sealed SDK observation obtained outside SQL. The final paid reread, membership/roles, + * authority event/pair, audit and terminal receipt share this caller-owned transaction. + * Exceptions must escape that transaction so every staged write rolls back. This supplies neither + * caller authentication nor a World hold; default Spring composition and the explicit demo path + * are unchanged. + */ + @Transactional(propagation = Propagation.MANDATORY) + public CanonicalJoinTerminalProof commitPaidCanonicalFirstJoin( + CanonicalJoinScopeV2 scope, + String requestId, + String verifiedCallerBinding, + AccountHostingSubscriptionLifecycleRepository hosting, + ReadFence fence, + StripeHostingSubscriptionObserver.Result observed) { + Objects.requireNonNull(hosting, "Actual paid hosting source required"); + Objects.requireNonNull(fence, "Original paid read fence required"); + Objects.requireNonNull(observed, "Original sealed SDK result required"); + return commitCanonicalFirstJoin( + scope, requestId, verifiedCallerBinding, hosting, fence, observed); + } + + /** + * Applies the accepted existing-membership JOIN lifecycle without reusing the first-row writer. + */ + @Transactional(propagation = Propagation.MANDATORY) + public CanonicalJoinOperationEvidence commitCanonicalJoin( + CanonicalJoinScopeV2 scope, + String requestId, + String callerBinding, + AccountHostingSubscriptionLifecycleRepository hosting, + ReadFence fence, + StripeHostingSubscriptionObserver.Result observed) { + requireWritableOwnerTransaction(); + Objects.requireNonNull(scope, "canonical JOIN scope is required"); + requireBoundedText(requestId, "canonical JOIN request ID"); + requireBoundedText(callerBinding, "verified caller binding"); + Account account = accountRepository.findByAccountUuid(scope.accountId()).orElseThrow(); + requireAccountIdentity(account, scope.accountId()); + joinOperationRepository.lockAccount(account.getId()); + CanonicalJoinOperationEvidence operation = + joinOperationRepository.findCanonicalEvidenceForUpdateByRequestId(requestId).orElseThrow(); + requireExactOperation(operation, account.getId(), scope, requestId, callerBinding); + // Definitive FAILED receipts are replayed by the adapter before policy evaluation. + if ("COMMITTED".equals(operation.status())) { + return operation; + } + if (!"PENDING".equals(operation.status())) { + throw new CanonicalJoinOperationConflictException("Canonical JOIN intent conflicts"); + } + AccountTenantMembership membership = + membershipRepository + .findFreshMembershipForUpdate(scope.accountId(), scope.tenantId()) + .orElse(null); + if (membership == null) { + if (hosting == null) commitCanonicalFirstJoin(scope, requestId, callerBinding); + else commitPaidCanonicalFirstJoin(scope, requestId, callerBinding, hosting, fence, observed); + return joinOperationRepository + .findCanonicalEvidenceForUpdateByRequestId(requestId) + .orElseThrow(); + } + eventProducer.requireCurrentCanonicalJoinPolicy( + scope, + operation, + !"ACTIVE".equals(membership.getLifecycleState()), + hosting, + fence, + observed); + VerifiedTenantProvenance provenance = operation.scopeEvidence().tenantProvenance(); + RoleSnapshot roles = + roleSnapshotRepository + .findForCanonicalUpdate( + scope.accountId(), + scope.tenantId(), + provenance, + membership.getId(), + membership.getMembershipVersion()) + .orElseThrow(); + PairAuthority previous = + pairAuthorityRepository.readForUpdate(scope.accountId(), scope.tenantId()).orElseThrow(); + String outcome; + Checkpoint checkpoint; + if ("ACTIVE".equals(membership.getLifecycleState())) { + outcome = "ALREADY_ACTIVE"; + checkpoint = + authorityOutboxRepository + .readCheckpoint( + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + scope.accountId() + + "/" + + scope.tenantId()) + .orElseThrow(); + } else if ("INACTIVE".equals(membership.getLifecycleState())) { + if (!Boolean.TRUE.equals(operation.allowPublicJoin())) { + throw new IllegalStateException("Restore requires current positive public JOIN policy"); + } + membership = + membershipRepository.restoreFreshMembershipForJoin( + scope.accountId(), scope.tenantId(), membership); + // Public enrollment grants only player authority, never retained elevated tenant roles. + List restoredRoles = List.of("player"); + roles = + roleSnapshotRepository.replaceCanonical( + membership, + scope.accountId(), + scope.tenantId(), + provenance, + membership.getMembershipVersion(), + restoredRoles); + checkpoint = + eventProducer.publishCanonicalRestoredMembershipChange( + scope, requestId, callerBinding, previous, hosting, fence, observed); + outcome = "JOINED"; + } else { + throw new IllegalStateException("Membership lifecycle does not allow JOIN"); + } + FirstJoinEvidence current = readCurrentJoinEvidence(scope, membership, roles, checkpoint); + if ("ALREADY_ACTIVE".equals(outcome) && requestId.equals(current.event().requestId())) { + throw new IllegalStateException("Pending JOIN cannot adopt its precommitted transition"); + } + if ("JOINED".equals(outcome) && !requestId.equals(current.event().requestId())) { + throw new IllegalStateException("Transition JOIN event does not belong to this request"); + } + final CanonicalJoinTerminalProof proof; + if ("ALREADY_ACTIVE".equals(outcome)) { + proof = + new CanonicalJoinTerminalProof( + checkpoint.outboxStreamKey(), + checkpoint.outboxSequence(), + checkpoint.sourceEventId(), + checkpoint.sourceEventDigest(), + null, + null, + null, + operation.entitlementVersion(), + membership.getId(), + membership.getMembershipVersion(), + membership.getMembershipAuthorityGeneration()); + } else { + String payload = + canonicalCurrentAuditPayload(scope, requestId, operation, current, checkpoint); + UUID auditId = auditEventIdFor(requestId); + AccountAuditEnvelope appended = + auditOutboxRepository.appendCanonicalTenant( + auditId, scope.tenantId().toString(), JOINED_EVENT_TYPE, payload); + AccountAuditEnvelope audit = + auditOutboxRepository.findExactCanonicalTenantEnvelopeForUpdate(appended).orElseThrow(); + requireExactAudit(audit, scope, auditId, payload, operation.terminalProof()); + proof = proof(operation, current, audit); + } + return joinOperationRepository.commitCanonicalJoin( + requestId, scope, callerBinding, outcome, proof); + } + + private FirstJoinEvidence readCurrentJoinEvidence( + CanonicalJoinScopeV2 scope, + AccountTenantMembership membership, + RoleSnapshot roles, + Checkpoint checkpoint) { + PairAuthority pair = + pairAuthorityRepository.readForUpdate(scope.accountId(), scope.tenantId()).orElseThrow(); + String stream = + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + scope.accountId() + + "/" + + scope.tenantId(); + if (!stream.equals(checkpoint.outboxStreamKey()) + || !pair.membershipExists() + || !scope.accountId().equals(pair.accountUuid()) + || !scope.tenantId().equals(pair.tenantUuid()) + || pair.membershipVersion() != membership.getMembershipVersion() + || pair.membershipAuthorityGeneration() != membership.getMembershipAuthorityGeneration() + || pair.eventSequence() != checkpoint.outboxSequence() + || !pair.eventId().equals(checkpoint.sourceEventId()) + || !pair.eventDigest().equals(checkpoint.sourceEventDigest()) + || roles.snapshotVersion() != membership.getMembershipVersion() + || roles.membershipId() != membership.getId() + || !scope.accountId().equals(roles.accountUuid()) + || !scope.tenantId().equals(roles.tenantUuid()) + || !pair.provenance().equals(roles.tenantProvenance()) + || !"ACTIVE".equals(membership.getLifecycleState())) { + throw new IllegalStateException("Canonical JOIN current membership/pair/roles differ"); + } + Event event = + authorityOutboxRepository.findEvent(stream, checkpoint.outboxSequence()).orElseThrow(); + MembershipEvent decoded = + MembershipAuthorityEventV1Codec.verify(new String(event.payload(), StandardCharsets.UTF_8)); + if (!Arrays.equals(event.payload(), decoded.canonicalJsonUtf8()) + || !checkpoint.sourceEventId().equals(event.eventId()) + || !checkpoint.sourceEventDigest().equals(event.eventDigest()) + || !event.eventId().equals(decoded.eventId()) + || !event.eventDigest().equals(decoded.eventDigest()) + || !scope.accountId().toString().equals(decoded.accountId()) + || !scope.tenantId().toString().equals(decoded.tenantId()) + || !Map.of(scope.tenantId().toString(), Long.toString(membership.getMembershipVersion())) + .equals(decoded.membershipVersion()) + || !Long.toString(membership.getMembershipAuthorityGeneration()) + .equals(decoded.membershipAuthorityGeneration()) + || !roles.roles().equals(decoded.roles()) + || !"ACTIVE".equals(decoded.membershipLifecycleState()) + || decoded.gameplayAdmissionAllowed() != membership.isGameplayAdmissionAllowed()) { + throw new IllegalStateException("Canonical JOIN current event contradicts owner snapshot"); + } + return new FirstJoinEvidence(membership, event); + } + + private static String canonicalCurrentAuditPayload( + CanonicalJoinScopeV2 scope, + String requestId, + CanonicalJoinOperationEvidence operation, + FirstJoinEvidence current, + Checkpoint checkpoint) { + Map payload = new LinkedHashMap<>(); + payload.put("accountId", scope.accountId().toString()); + payload.put("tenantId", scope.tenantId().toString()); + payload.put("requestId", requestId); + payload.put("worldSlug", scope.worldSlug()); + payload.put("realmSlug", scope.realmSlug()); + payload.put("membershipVersion", current.membership().getMembershipVersion()); + payload.put( + "membershipAuthorityGeneration", current.membership().getMembershipAuthorityGeneration()); + payload.put("membershipEventStreamKey", checkpoint.outboxStreamKey()); + payload.put("membershipEventSequence", checkpoint.outboxSequence()); + payload.put("membershipEventId", checkpoint.sourceEventId()); + payload.put("membershipEventDigest", checkpoint.sourceEventDigest()); + payload.put("joinIntentDigest", operation.intentDigest()); + payload.put("joinRequestDigest", operation.requestDigest()); + payload.put("allowPublicJoin", true); + payload.put("entitlementVersion", operation.entitlementVersion()); + try { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(payload)), + StandardCharsets.UTF_8); + } catch (IOException failure) { + throw new IllegalStateException("Canonical JOIN audit cannot be encoded", failure); + } + } + + private CanonicalJoinTerminalProof commitCanonicalFirstJoin( + CanonicalJoinScopeV2 scope, + String requestId, + String verifiedCallerBinding, + AccountHostingSubscriptionLifecycleRepository hosting, + ReadFence fence, + StripeHostingSubscriptionObserver.Result observed) { requireWritableOwnerTransaction(); Objects.requireNonNull(scope, "canonical JOIN scope is required"); requireBoundedText(requestId, "canonical JOIN request ID"); @@ -117,6 +372,10 @@ public CanonicalJoinTerminalProof commitCanonicalFirstJoin( () -> new CanonicalJoinOperationConflictException("Canonical JOIN intent conflicts")); requireExactOperation(operation, account.getId(), scope, requestId, verifiedCallerBinding); + if (!Boolean.TRUE.equals(operation.allowPublicJoin())) { + throw new CanonicalJoinOperationConflictException( + "First JOIN requires available public policy"); + } final Checkpoint checkpoint; if ("PENDING".equals(operation.status())) { @@ -139,8 +398,11 @@ public CanonicalJoinTerminalProof commitCanonicalFirstJoin( requireExactRoleSnapshot(staged, provenance, scope, stagedRoles); checkpoint = - eventProducer.publishCanonicalFirstJoinMembershipChange( - scope, requestId, verifiedCallerBinding); + hosting == null + ? eventProducer.publishCanonicalFirstJoinMembershipChange( + scope, requestId, verifiedCallerBinding) + : eventProducer.publishPaidCanonicalFirstJoinMembershipChange( + scope, requestId, verifiedCallerBinding, hosting, fence, observed); } else if ("COMMITTED".equals(operation.status()) && "JOINED".equals(operation.outcome()) && operation.terminalProof() != null) { @@ -332,7 +594,7 @@ private static void requireExactOperation( throw new CanonicalJoinOperationConflictException("Canonical JOIN intent conflicts"); } if (!"AVAILABLE".equals(operation.entitlementAuthorityAvailability()) - || !Boolean.TRUE.equals(operation.allowPublicJoin()) + || operation.allowPublicJoin() == null || operation.entitlementVersion() == null || operation.entitlementVersion() <= 0L || !Integer.valueOf(2).equals(operation.requestDigestVersion()) @@ -346,7 +608,7 @@ private static void requireExactOperation( scope, callerBinding, AccountJoinDigest.EntitlementAvailabilityV2.AVAILABLE, - true, + operation.allowPublicJoin(), operation.entitlementVersion()); if (!requestDigest.equals(operation.requestDigest())) { throw new CanonicalJoinOperationConflictException("Canonical JOIN policy conflicts"); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwner.java index 87b37f7260..8125edd084 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwner.java @@ -16,6 +16,8 @@ import net.firedevops.firemud.accountservice.config.AccountTokenProperties; import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; +import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; +import net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; @@ -51,7 +53,10 @@ * current identity, provenance, membership and billing heads; the final transaction retains and * exactly reads back the V2 scope. Every repository must use the supplied transaction manager. * - *

Membership-independent public visibility is preserved when enrollment is closed. Returned + *

Browser credentials use their persisted Account/session-registry verifier. Direct text uses + * the exact same-namespace Game Session peer and canonical caller correlation, with its own + * invocation deadline; it never fabricates a bootstrap credential or registry success. + * Membership-independent public visibility is preserved when enrollment is closed. Returned * membership/entitlement facts are observations for later selection, never permission to JOIN, * create a character or admit gameplay. This owner neither enrolls membership nor claims a World * hold, private/ISOLATED support, a registered facade, or qualified credential custody. @@ -112,35 +117,153 @@ public AccountCanonicalPublicRealmScopeOwner( transaction.setReadOnly(false); } - /** Selects only the canonical tenant/world pair; a bare global world slug is not authority. */ + /** Selects the canonical tenant/world pair through the same complete-source pipeline. */ public List listRealmScopes( String bootstrapToken, String tenantSlug, String worldSlug) { + return listRealmScopes(bootstrapToken, tenantSlug, worldSlug, true); + } + + private List listRealmScopes( + String bootstrapToken, String tenantSlug, String worldSlug, boolean tenantQualified) { requireSourceContext(); Caller original = verifyCaller(bootstrapToken); - if (!RealmEntryPolicy.isCanonicalSlug(tenantSlug) + return listRealmScopes( + original, tenantSlug, worldSlug, tenantQualified, () -> verifyCaller(bootstrapToken), null); + } + + /** Existing direct-text selection, authenticated independently of the browser registry. */ + public RealmScope issueDirectTextScope( + DirectTextCallerContext caller, DirectTextJoinTarget target) { + requireSourceContext(); + requireDirectPeer(); + if (caller == null + || target == null + || !Objects.equals(caller.tenantId(), target.tenantId()) + || !Objects.equals(caller.realmId(), target.realmId()) + || !Objects.equals(caller.playableStateNamespaceId(), target.playableStateNamespaceId()) + || !Objects.equals(caller.gameInstanceId(), target.gameInstanceId()) + || !Objects.equals(caller.playableStateScope(), target.playableStateScope()) + || caller.sessionId() == null + || caller.requestId() == null + || caller.sessionId().isBlank() + || caller.requestId().isBlank() + || caller.sessionId().length() > 32 + || caller.requestId().length() > 128) { + throw new AuthenticationException( + "CONNECT_CONTEXT_INVALID", "Direct caller correlation is invalid"); + } + try { + if (!caller.sessionId().matches("[0-9]+")) { + throw new NumberFormatException("Invalid transport session"); + } + if (Long.parseLong(caller.sessionId()) <= 0) { + throw new NumberFormatException("Invalid transport session"); + } + } catch (NumberFormatException failure) { + throw new AuthenticationException( + "CONNECT_CONTEXT_INVALID", "Direct caller session is invalid", failure); + } + // These times describe this Account producer invocation, not a fabricated bootstrap lifetime. + Instant issuedAt = now(); + Instant deadline = issuedAt.plusMillis(scopeLifetimeMillis); + java.util.function.Supplier authenticate = + () -> verifyDirectCaller(caller, issuedAt, deadline); + Caller original = authenticate.get(); + List selected = + listRealmScopes(original, null, target.worldSlug(), false, authenticate, target); + if (selected.size() != 1) throw pointerUnavailable(null); + return selected.getFirst(); + } + + private Caller verifyDirectCaller( + DirectTextCallerContext context, Instant issuedAt, Instant deadline) { + requireDirectPeer(); + if (context.accountId() == null + || new UUID(0L, 0L).equals(context.accountId()) + || now().isBefore(issuedAt) + || !now().isBefore(deadline)) { + throw new AuthenticationException( + "CONNECT_CONTEXT_INVALID", "Direct caller expired or malformed"); + } + return inTransaction( + () -> { + requireDirectPeer(); + Account account = + accounts + .findByAccountUuidForUpdate(context.accountId()) + .orElseThrow( + () -> + new AuthenticationException( + "CONNECT_CONTEXT_INVALID", "Direct caller Account is unknown")); + if (account.getId() == null + || account.getId() <= 0L + || !context.accountId().equals(account.getAccountUuid()) + || !Objects.equals(account.getId(), account.getAccountUuidSourceNumericId()) + || !AccountIdentityProvenance.isAccepted(account.getAccountUuidProvenance()) + || account.getLifecycleState() != AccountLifecycleState.ACTIVE) { + throw authUnavailable("Direct Account owner is unavailable or ineligible", null); + } + return new Caller(account.getId(), account.getAccountUuid(), issuedAt, deadline); + }); + } + + private void requireDirectPeer() { + var peer = net.firedevops.firemud.common.grpc.GrpcPeerIdentity.current(); + if (peer == null || !peer.isService("game-session-service") || !peer.isInNamespace(namespace)) { + throw new AuthenticationException( + "AUTH_UNAVAILABLE", "Exact Game Session workload is required"); + } + } + + private List listRealmScopes( + Caller original, + String tenantSlug, + String worldSlug, + boolean tenantQualified, + java.util.function.Supplier authenticate, + DirectTextJoinTarget directTarget) { + if ((tenantQualified && !RealmEntryPolicy.isCanonicalSlug(tenantSlug)) || !RealmEntryPolicy.isCanonicalSlug(worldSlug)) { throw pointerUnavailable(null); } - Optional selected = select(readTargets(), tenantSlug, worldSlug); + Optional selected = + selectForCaller(readTargets(), tenantSlug, worldSlug, tenantQualified, directTarget); if (selected.isEmpty()) { - if (select(readTargets(), tenantSlug, worldSlug).isPresent()) { + if (selectForCaller(readTargets(), tenantSlug, worldSlug, tenantQualified, directTarget) + .isPresent()) { throw pointerUnavailable(null); } - requireSameCaller(original, verifyCaller(bootstrapToken)); + requireSameCaller(original, authenticate.get()); return List.of(); } Target target = selected.orElseThrow(); + if (directTarget != null + && (!directTarget.tenantId().equals(target.canonicalTenantId()) + || !directTarget.realmId().equals(target.realmId()) + || !directTarget.realmSlug().equals(target.realmSlug()) + || !directTarget.playableStateNamespaceId().equals(target.playableStateNamespaceId()) + || !directTarget.playableStateScope().equals(target.playableStateScope()) + || !directTarget.gameInstanceId().equals(target.canonicalGameInstanceId()) + || directTarget.catalogRevision() != target.catalogRevision() + || directTarget.pointerVersion() != target.pointerVersion())) { + throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", "Direct target changed"); + } Evaluation entitlement = evaluate(target); if (!entitlement.gameplayAvailable()) { - requireSameTarget(target, select(readTargets(), tenantSlug, worldSlug)); - requireSameCaller(original, verifyCaller(bootstrapToken)); + requireSameTarget( + target, + selectForCaller(readTargets(), tenantSlug, worldSlug, tenantQualified, directTarget)); + requireSameCaller(original, authenticate.get()); requireFresh(entitlement); + if (directTarget != null) throw entitlementUnavailable(null); return List.of(); } Prepared prepared = inTransaction(() -> readSources(original, target, entitlement)); - requireSameTarget(target, select(readTargets(), tenantSlug, worldSlug)); - requireSameCaller(original, verifyCaller(bootstrapToken)); + requireSameTarget( + target, + selectForCaller(readTargets(), tenantSlug, worldSlug, tenantQualified, directTarget)); + requireSameCaller(original, authenticate.get()); requireFresh(entitlement); RealmScope retained = inTransaction( @@ -172,7 +295,7 @@ public List listRealmScopes( TenantProvenanceKind.FRESH_GAME_DESIGN, current.tenant().operationId(), current.tenant().evidenceDigest()); - scopes.insertCanonical(original.caller().accountId(), scope, provenance); + scopes.insertCanonical(original.accountId(), scope, provenance); if (!scope.equals(scopes.findCanonical(scope.connectScopeId()).orElse(null))) { throw authUnavailable("Canonical scope readback differs", null); } @@ -186,7 +309,7 @@ public List listRealmScopes( return new RealmScope(target, scope, current.membership(), entitlement); }); // No value escapes a failed commit or a caller/source observation that expired during commit. - requireSameCaller(original, verifyCaller(bootstrapToken)); + requireSameCaller(original, authenticate.get()); requireFresh(entitlement); if (!now().isBefore(Instant.parse(retained.scope().connectScopeExpiresAt()))) { throw authUnavailable("Canonical scope expired before publication", null); @@ -217,7 +340,7 @@ private Caller verifyCaller(String token) { throw new AuthenticationException( "CONNECT_CONTEXT_INVALID", "Invalid bootstrap credential"); } - return new Caller(caller, issuedAt, expiresAt); + return new Caller(caller.accountId(), caller.accountUuid(), issuedAt, expiresAt); } catch (AuthenticationException failure) { throw failure; } catch (JwtException | IllegalArgumentException failure) { @@ -247,12 +370,14 @@ private List readTargets() { } } - private Optional select(List complete, String tenantSlug, String worldSlug) { + private Optional select( + List complete, String tenantSlug, String worldSlug, boolean tenantQualified) { List matches = complete.stream() .filter( target -> - tenantSlug.equals(target.tenantSlug()) && worldSlug.equals(target.worldSlug())) + worldSlug.equals(target.worldSlug()) + && (!tenantQualified || tenantSlug.equals(target.tenantSlug()))) .toList(); if (matches.size() > 1) throw pointerUnavailable(null); for (Target target : matches) { @@ -265,6 +390,21 @@ private Optional select(List complete, String tenantSlug, String return matches.stream().findFirst(); } + private Optional selectForCaller( + List complete, + String tenantSlug, + String worldSlug, + boolean tenantQualified, + DirectTextJoinTarget directTarget) { + List selectedTenant = + directTarget == null + ? complete + : complete.stream() + .filter(target -> directTarget.tenantId().equals(target.canonicalTenantId())) + .toList(); + return select(selectedTenant, tenantSlug, worldSlug, tenantQualified); + } + private Evaluation evaluate(Target target) { requireSourceContext(); try { @@ -286,10 +426,10 @@ private Evaluation evaluate(Target target) { private Prepared readSources(Caller caller, Target target, Evaluation entitlement) { Account account = accounts - .findByAccountUuidForUpdate(caller.caller().accountUuid()) + .findByAccountUuidForUpdate(caller.accountUuid()) .orElseThrow(() -> authUnavailable("Account owner is unavailable", null)); - if (!Objects.equals(account.getId(), caller.caller().accountId()) - || !caller.caller().accountUuid().equals(account.getAccountUuid()) + if (!Objects.equals(account.getId(), caller.accountId()) + || !caller.accountUuid().equals(account.getAccountUuid()) || !Objects.equals(account.getId(), account.getAccountUuidSourceNumericId()) || !AccountIdentityProvenance.isAccepted(account.getAccountUuidProvenance()) || account.getLifecycleState() != AccountLifecycleState.ACTIVE) { @@ -317,8 +457,7 @@ private Prepared readSources(Caller caller, Target target, Evaluation entitlemen throw entitlementUnavailable(failure); } Optional member = - memberships.findFreshMembershipForUpdate( - caller.caller().accountUuid(), target.canonicalTenantId()); + memberships.findFreshMembershipForUpdate(caller.accountUuid(), target.canonicalTenantId()); Optional current = member.map( value -> { @@ -356,7 +495,7 @@ private CanonicalJoinScopeV2 mintScope( Caller caller, Target target, Instant evaluatedAt, Instant expiresAt) { Map claims = new LinkedHashMap<>(); claims.put("aud", "bootstrap-connect-scope"); - claims.put("accountId", caller.caller().accountUuid().toString()); + claims.put("accountId", caller.accountUuid().toString()); claims.put("targetClass", "PUBLIC_PRODUCTION"); claims.put("scopeDigestVersion", 2L); claims.put("tenantId", target.canonicalTenantId().toString()); @@ -375,12 +514,12 @@ private CanonicalJoinScopeV2 mintScope( // Preserve the owner-selected absolute expiry even if signing starts after a scheduling pause. final String token; try { - token = jwt.generateToken(caller.caller().accountUuid().toString(), expiresAt, claims); + token = jwt.generateToken(caller.accountUuid().toString(), expiresAt, claims); } catch (IllegalArgumentException expired) { throw authUnavailable("Scope signing clock is outside its validity", expired); } Claims signed = jwt.parseToken(token).getPayload(); - if (!caller.caller().accountUuid().toString().equals(signed.getSubject()) + if (!caller.accountUuid().toString().equals(signed.getSubject()) || signed.getExpiration() == null || !expiresAt.equals(signed.getExpiration().toInstant()) || signed.getIssuedAt() == null @@ -401,7 +540,7 @@ private CanonicalJoinScopeV2 mintScope( } return new CanonicalJoinScopeV2( token, - caller.caller().accountUuid(), + caller.accountUuid(), target.canonicalTenantId(), target.realmId(), target.tenantSlug(), @@ -420,7 +559,7 @@ private static CanonicalConnectScopeEvidence evidence( Caller caller, CanonicalJoinScopeV2 scope, VerifiedTenantProvenance provenance) { return new CanonicalConnectScopeEvidence( AccountJoinDigest.tokenHash(scope.connectScopeId()), - caller.caller().accountId(), + caller.accountId(), "PUBLIC_PRODUCTION", scope.accountId(), scope.tenantId(), @@ -470,8 +609,8 @@ private void requireFresh(Evaluation evaluation) { } private static void requireSameCaller(Caller original, Caller current) { - if (original.caller().accountId() != current.caller().accountId() - || !original.caller().accountUuid().equals(current.caller().accountUuid()) + if (original.accountId() != current.accountId() + || !original.accountUuid().equals(current.accountUuid()) || !original.issuedAt().equals(current.issuedAt()) || !original.expiresAt().equals(current.expiresAt())) { throw new AuthenticationException("CONNECT_CONTEXT_INVALID", "Bootstrap caller changed"); @@ -519,7 +658,7 @@ private static AuthenticationException entitlementUnavailable(Throwable cause) { cause); } - private record Caller(VerifiedCaller caller, Instant issuedAt, Instant expiresAt) {} + private record Caller(long accountId, UUID accountUuid, Instant issuedAt, Instant expiresAt) {} private record Prepared( FreshTenantCreationEvidence tenant, MembershipFacts membership, SourceSelection head) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java index ab72901bfb..0df534e287 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java @@ -11,10 +11,12 @@ import java.util.Map; import java.util.Objects; import java.util.UUID; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; import net.firedevops.firemud.accountservice.dto.AccountJoinDigest.EntitlementAvailabilityV2; import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; +import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; @@ -28,6 +30,9 @@ import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot; import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionCurrentReceipt; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ReadFence; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinOperationEvidence; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinTerminalProof; @@ -117,6 +122,233 @@ public AccountMembershipAuthorityEventProducer( @Transactional(propagation = Propagation.MANDATORY) public Checkpoint publishCanonicalFirstJoinMembershipChange( CanonicalJoinScopeV2 scope, String requestId, String callerBinding) { + return publishCanonicalFirstJoinMembershipChange(scope, requestId, callerBinding, null); + } + + /** + * Separate manually composed paid source. The fence and sealed SDK Result must have been prepared + * outside this final transaction; this method performs only the actual locked receipt reread. No + * parsed runtime bundle or billing-owner identity supplies player authority. A COMMITTED exact + * replay follows the unchanged historical event/pair path without provider work. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Checkpoint publishPaidCanonicalFirstJoinMembershipChange( + CanonicalJoinScopeV2 scope, + String requestId, + String callerBinding, + AccountHostingSubscriptionLifecycleRepository hosting, + ReadFence fence, + StripeHostingSubscriptionObserver.Result observed) { + return publishCanonicalFirstJoinMembershipChange( + scope, requestId, callerBinding, new PaidJoinSource(hosting, fence, observed)); + } + + /** Publishes exactly the next event for a staged INACTIVE restore under its prior pair fence. */ + @Transactional(propagation = Propagation.MANDATORY) + public Checkpoint publishCanonicalRestoredMembershipChange( + CanonicalJoinScopeV2 scope, + String requestId, + String callerBinding, + PairAuthority previous, + AccountHostingSubscriptionLifecycleRepository hosting, + ReadFence fence, + StripeHostingSubscriptionObserver.Result observed) { + requireWritableOwnerTransaction(); + Objects.requireNonNull(scope, "canonical JOIN scope is required"); + requireBoundedText(requestId, "canonical JOIN request ID", MAX_REQUEST_ID_LENGTH); + requireBoundedText(callerBinding, "verified JOIN caller binding", MAX_CALLER_BINDING_LENGTH); + Objects.requireNonNull(previous); + PaidJoinSource paid = hosting == null ? null : new PaidJoinSource(hosting, fence, observed); + var account = lockCanonicalAccountOwner(scope.accountId()); + CanonicalJoinOperationEvidence operation = + joinOperationRepository.findCanonicalEvidenceForUpdateByRequestId(requestId).orElseThrow(); + requireOperationMatchesRequest(scope, requestId, callerBinding, account.getId(), operation); + if (!"PENDING".equals(operation.status()) + || !previous.membershipExists() + || previous.eventSequence() <= 0L + || !previous.equals( + pairAuthorityRepository + .readForUpdate(scope.accountId(), scope.tenantId()) + .orElseThrow())) { + throw new IllegalStateException("Restore event requires its exact positive predecessor"); + } + AccountTenantMembership membership = + membershipRepository + .findCanonicalMembershipForUpdate(scope.accountId(), scope.tenantId()) + .orElseThrow(); + VerifiedTenantProvenance provenance = operation.scopeEvidence().tenantProvenance(); + requireExactPairScope(previous, scope.accountId(), scope.tenantId(), provenance); + if (!Objects.equals(account.getId(), membership.getAccount().getId()) + || !scope.accountId().equals(membership.getAccount().getAccountUuid()) + || !scope.tenantId().equals(membership.getTenantUuid()) + || !"ACTIVE".equals(membership.getLifecycleState()) + || !membership.isGameplayAdmissionAllowed() + || !"EXPLICIT_JOIN".equals(membership.getAuthorityProvenance()) + || membership.getMembershipVersion() != Math.incrementExact(previous.membershipVersion()) + || membership.getMembershipAuthorityGeneration() + != previous.membershipAuthorityGeneration()) { + throw new IllegalStateException("Restore event contradicts its staged membership"); + } + RoleSnapshot roles = + roleSnapshotRepository + .findForCanonicalUpdate( + scope.accountId(), + scope.tenantId(), + provenance, + membership.getId(), + membership.getMembershipVersion()) + .orElseThrow(); + List exactRoles = + requireCanonicalJoinRoleSnapshot(scope, membership, provenance, roles); + CompositeSnapshot authority = + authorityGenerationRepository.readCompositeSnapshot( + ACCOUNT_JWT_ISSUER, + scope.accountId(), + List.of(scope.tenantId()), + List.of(scope.tenantId())); + IssuerAccountSourceSnapshot sources = + sourceEvidenceRepository.readCurrentIssuerAccountSources( + ACCOUNT_JWT_ISSUER, scope.accountId()); + var tenant = + readCurrentTenantSourceEvent( + scope.tenantId(), provenance, only(authority.tenants(), "tenant")); + requireCurrentAuthority( + authority, + sources, + account.getId(), + scope.accountId(), + scope.tenantId(), + membership, + provenance, + tenant); + if (paid == null) { + requireCurrentJoinEntitlement( + operation, + demoTenantEntitlementRepository.readCurrent(scope.tenantId()), + tenant, + scope.tenantId()); + } else { + requireCurrentPaidJoinEntitlement( + operation, + paid.hosting().readCurrent(paid.fence(), paid.observed()), + tenant, + scope.tenantId()); + } + String stream = membershipStreamKey(scope.accountId(), scope.tenantId()); + Checkpoint prior = authorityOutboxRepository.readCheckpoint(stream).orElseThrow(); + if (prior.outboxSequence() != previous.eventSequence() + || !prior.sourceEventId().equals(previous.eventId()) + || !prior.sourceEventDigest().equals(previous.eventDigest())) { + throw new IllegalStateException("Restore event predecessor differs from current event head"); + } + Event priorEvent = + authorityOutboxRepository.findEvent(stream, previous.eventSequence()).orElseThrow(); + MembershipEvent priorMembership = + MembershipAuthorityEventV1Codec.verify( + new String(priorEvent.payload(), StandardCharsets.UTF_8)); + if (!Arrays.equals(priorMembership.canonicalJsonUtf8(), priorEvent.payload()) + || !previous.eventId().equals(priorEvent.eventId()) + || !previous.eventDigest().equals(priorEvent.eventDigest()) + || !previous.eventId().equals(priorMembership.eventId()) + || !previous.eventDigest().equals(priorMembership.eventDigest()) + || !scope.accountId().toString().equals(priorMembership.accountId()) + || !scope.tenantId().toString().equals(priorMembership.tenantId()) + || !"INACTIVE".equals(priorMembership.membershipLifecycleState()) + || priorMembership.gameplayAdmissionAllowed() + || !Map.of(scope.tenantId().toString(), Long.toString(previous.membershipVersion())) + .equals(priorMembership.membershipVersion()) + || !Long.toString(previous.membershipAuthorityGeneration()) + .equals(priorMembership.membershipAuthorityGeneration())) { + throw new IllegalStateException("Restore requires the exact published INACTIVE predecessor"); + } + long next = Math.incrementExact(previous.eventSequence()); + Event appended = + authorityOutboxRepository.append( + stream, + requestId, + sequence -> { + if (sequence != next) + throw new IllegalStateException("Restore event sequence changed"); + MembershipEvent event = + MembershipAuthorityEventV1Codec.seal( + membershipEventPreimage( + scope, + membership, + exactRoles, + authority, + sources, + tenant, + eventIdForRequest(requestId), + requestId, + sequence)); + return new EventEvidence( + event.eventId(), event.eventDigest(), event.canonicalJsonUtf8()); + }); + Event readback = authorityOutboxRepository.findEvent(stream, next).orElseThrow(); + if (!appended.equals(readback) || !requestId.equals(readback.requestId())) { + throw new IllegalStateException("Restore event readback differs"); + } + MembershipEvent decoded = + MembershipAuthorityEventV1Codec.verify( + new String(readback.payload(), StandardCharsets.UTF_8)); + if (!Arrays.equals(decoded.canonicalJsonUtf8(), readback.payload()) + || !decoded.eventDigest().equals(readback.eventDigest())) { + throw new IllegalStateException("Restore event bytes differ from canonical digest"); + } + Checkpoint checkpoint = authorityOutboxRepository.readCheckpoint(stream).orElseThrow(); + requireCheckpointMatchesEvent(checkpoint, readback); + pairAuthorityRepository.commitRestore( + previous, + new PairTransition(true, next, readback.eventId(), readback.eventDigest(), false)); + return checkpoint; + } + + /** Rechecks actual Account policy sources under the caller's final membership transaction. */ + @Transactional(propagation = Propagation.MANDATORY) + public void requireCurrentCanonicalJoinPolicy( + CanonicalJoinScopeV2 scope, + CanonicalJoinOperationEvidence expected, + boolean transition, + AccountHostingSubscriptionLifecycleRepository hosting, + ReadFence fence, + StripeHostingSubscriptionObserver.Result observed) { + requireWritableOwnerTransaction(); + var current = + joinOperationRepository + .findCanonicalEvidenceForUpdateByRequestId(expected.requestId()) + .orElseThrow(); + if (!current.equals(expected) + || !AccountJoinDigest.scopeV2(scope).equals(current.connectScopeDigest()) + || !scope.accountId().equals(current.scopeEvidence().accountUuid()) + || !scope.tenantId().equals(current.scopeEvidence().tenantUuid())) { + throw new IllegalStateException("Canonical JOIN policy selector changed"); + } + CompositeSnapshot authority = + authorityGenerationRepository.readCompositeSnapshot( + ACCOUNT_JWT_ISSUER, + scope.accountId(), + List.of(scope.tenantId()), + List.of(scope.tenantId())); + var tenant = + readCurrentTenantSourceEvent( + scope.tenantId(), + current.scopeEvidence().tenantProvenance(), + only(authority.tenants(), "tenant")); + if (hosting == null) { + requireCurrentJoinEntitlement( + current, + demoTenantEntitlementRepository.readCurrent(scope.tenantId()), + tenant, + scope.tenantId(), + transition); + } else { + requireCurrentPaidJoinEntitlement( + current, hosting.readCurrent(fence, observed), tenant, scope.tenantId(), transition); + } + } + + private Checkpoint publishCanonicalFirstJoinMembershipChange( + CanonicalJoinScopeV2 scope, String requestId, String callerBinding, PaidJoinSource paid) { requireWritableOwnerTransaction(); Objects.requireNonNull(scope, "canonical JOIN scope is required"); requireBoundedText(requestId, "canonical JOIN request ID", MAX_REQUEST_ID_LENGTH); @@ -124,20 +356,7 @@ public Checkpoint publishCanonicalFirstJoinMembershipChange( UUID accountUuid = scope.accountId(); UUID tenantUuid = scope.tenantId(); - var account = - accountRepository - .findByAccountUuid(accountUuid) - .orElseThrow(() -> new IllegalStateException("Canonical Account identity is absent")); - if (account.getId() == null - || account.getId() <= 0L - || !accountUuid.equals(account.getAccountUuid()) - || !AccountIdentityProvenance.isAccepted(account.getAccountUuidProvenance()) - || !Objects.equals(account.getAccountUuidSourceNumericId(), account.getId())) { - throw new IllegalStateException("Canonical Account owner identity is contradictory"); - } - // The operation repository exposes only a retained private row key. Lock its actual Account - // owner first, then lock/read the operation before resolving any membership source evidence. - joinOperationRepository.lockAccount(account.getId()); + var account = lockCanonicalAccountOwner(accountUuid); CanonicalJoinOperationEvidence operation = joinOperationRepository .findCanonicalEvidenceForUpdateByRequestId(requestId) @@ -170,7 +389,8 @@ public Checkpoint publishCanonicalFirstJoinMembershipChange( membership.getMembershipVersion()) .orElseThrow( () -> new IllegalStateException("Canonical first-JOIN role snapshot is absent")); - List exactRoles = requireFirstJoinRoleSnapshot(scope, membership, provenance, roles); + List exactRoles = + requireCanonicalJoinRoleSnapshot(scope, membership, provenance, roles); PairAuthority pair = pairAuthorityRepository @@ -204,9 +424,16 @@ public Checkpoint publishCanonicalFirstJoinMembershipChange( membership, provenance, tenantSourceEvent); - DemoTenantEntitlementSnapshot entitlementSnapshot = - demoTenantEntitlementRepository.readCurrent(tenantUuid); - requireCurrentJoinEntitlement(operation, entitlementSnapshot, tenantSourceEvent, tenantUuid); + if (paid == null) { + DemoTenantEntitlementSnapshot entitlementSnapshot = + demoTenantEntitlementRepository.readCurrent(tenantUuid); + requireCurrentJoinEntitlement( + operation, entitlementSnapshot, tenantSourceEvent, tenantUuid); + } else { + AccountHostingSubscriptionCurrentReceipt receipt = + paid.hosting().readCurrent(paid.fence(), paid.observed()); + requireCurrentPaidJoinEntitlement(operation, receipt, tenantSourceEvent, tenantUuid); + } if (authorityOutboxRepository.readCheckpoint(streamKey).isPresent()) { throw new IllegalStateException( "Canonical first JOIN cannot publish over retained membership-event history"); @@ -543,10 +770,20 @@ private static void requireCurrentJoinEntitlement( DemoTenantEntitlementSnapshot entitlement, TenantAuthorityEventV1Codec.Event tenantSourceEvent, UUID tenantUuid) { + requireCurrentJoinEntitlement(operation, entitlement, tenantSourceEvent, tenantUuid, true); + } + + private static void requireCurrentJoinEntitlement( + CanonicalJoinOperationEvidence operation, + DemoTenantEntitlementSnapshot entitlement, + TenantAuthorityEventV1Codec.Event tenantSourceEvent, + UUID tenantUuid, + boolean transition) { if (entitlement == null || !tenantUuid.equals(entitlement.canonicalTenantId()) || entitlement.entitlementVersion() != operation.entitlementVersion() - || !entitlement.allowPublicJoin() + || (transition && !entitlement.allowPublicJoin()) + || !Objects.equals(entitlement.allowPublicJoin(), operation.allowPublicJoin()) || !entitlement.gameplayAvailable() || tenantSourceEvent == null || !tenantUuid.equals(tenantSourceEvent.tenantId()) @@ -567,7 +804,81 @@ private static void requireCurrentJoinEntitlement( } } - private static List requireFirstJoinRoleSnapshot( + private static void requireCurrentPaidJoinEntitlement( + CanonicalJoinOperationEvidence operation, + AccountHostingSubscriptionCurrentReceipt receipt, + TenantAuthorityEventV1Codec.Event currentTenant, + UUID tenantUuid) { + requireCurrentPaidJoinEntitlement(operation, receipt, currentTenant, tenantUuid, true); + } + + private static void requireCurrentPaidJoinEntitlement( + CanonicalJoinOperationEvidence operation, + AccountHostingSubscriptionCurrentReceipt receipt, + TenantAuthorityEventV1Codec.Event currentTenant, + UUID tenantUuid, + boolean transition) { + if (receipt == null + || receipt.current() == null + || currentTenant == null + || !tenantUuid.equals(receipt.current().tenantId()) + || receipt.entitlementVersion() != operation.entitlementVersion() + || (transition && !receipt.allowPublicJoin()) + || !Objects.equals(receipt.allowPublicJoin(), operation.allowPublicJoin()) + || !receipt.gameplayAvailable() + || receipt.evaluatedAt() == null + || receipt.validUntil() == null + || !receipt.evaluatedAt().isBefore(receipt.validUntil()) + || receipt.tenantAuthorityEvent() == null + || !Arrays.equals(receipt.tenantAuthorityEvent().payload(), currentTenant.payload()) + || !Objects.equals(receipt.tenantAuthorityEvent().eventId(), currentTenant.eventId()) + || !Objects.equals( + receipt.tenantAuthorityEvent().eventDigest(), currentTenant.eventDigest()) + || receipt.tenantAuthorityEvent().tenantAuthorityGeneration() + != currentTenant.tenantAuthorityGeneration() + || receipt.tenantAuthorityEvent().tenantAuthoritySourceVersion() + != currentTenant.tenantAuthoritySourceVersion() + || receipt.tenantAuthorityEvent().outboxSequence() != currentTenant.outboxSequence() + || !tenantUuid.equals(currentTenant.tenantId()) + || receipt.tenantBillingSequence() != currentTenant.tenantBillingSequence() + || !Objects.equals(receipt.billingEventId(), currentTenant.tenantBillingEventId()) + || !Objects.equals( + receipt.billingEventDigest(), currentTenant.tenantBillingEventDigest())) { + throw new IllegalStateException( + "Canonical paid first JOIN requires exact current public-join entitlement evidence"); + } + } + + private Account lockCanonicalAccountOwner(UUID accountUuid) { + var account = + accountRepository + .findByAccountUuid(accountUuid) + .orElseThrow(() -> new IllegalStateException("Canonical Account identity is absent")); + if (account.getId() == null + || account.getId() <= 0L + || !accountUuid.equals(account.getAccountUuid()) + || !AccountIdentityProvenance.isAccepted(account.getAccountUuidProvenance()) + || !Objects.equals(account.getAccountUuidSourceNumericId(), account.getId())) { + throw new IllegalStateException("Canonical Account owner identity is contradictory"); + } + // The operation repository exposes only a retained private row key. Lock its actual Account + // owner first, then lock/read the operation before resolving any membership source evidence. + joinOperationRepository.lockAccount(account.getId()); + return account; + } + + private record PaidJoinSource( + AccountHostingSubscriptionLifecycleRepository hosting, + ReadFence fence, + StripeHostingSubscriptionObserver.Result observed) { + private PaidJoinSource { + Objects.requireNonNull(hosting, "Actual paid hosting source required"); + Objects.requireNonNull(fence, "Original paid read fence required"); + Objects.requireNonNull(observed, "Original sealed SDK result required"); + } + } + + private static List requireCanonicalJoinRoleSnapshot( CanonicalJoinScopeV2 scope, AccountTenantMembership membership, VerifiedTenantProvenance provenance, @@ -582,7 +893,7 @@ private static List requireFirstJoinRoleSnapshot( if (roles.accountId() != membership.getAccount().getId() || roles.tenantId() != null || roles.membershipId() != membership.getId() - || roles.snapshotVersion() != 2L + || roles.snapshotVersion() != membership.getMembershipVersion() || !scope.accountId().equals(roles.accountUuid()) || !scope.tenantId().equals(roles.tenantUuid()) || !provenance.equals(roles.tenantProvenance()) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwner.java index 5c8cfbe185..ecf214efd4 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwner.java @@ -67,7 +67,6 @@ public List listWorlds(String bootstrapToken) { new IllegalStateException("Canonical public target collection changed during discovery")); } - rejectAmbiguousWorldSlugs(initialTargets); requireSameCaller(originalCaller, verifyCaller(bootstrapToken)); requireFreshEvaluations(initialByTenant, evaluated); @@ -76,10 +75,14 @@ public List listWorlds(String bootstrapToken) { AccountPublicBootstrapEntitlementOwner.Evaluation evaluation = evaluated.get(target.canonicalTenantId()); if (evaluation.gameplayAvailable()) { - visible.add(new BootstrapWorldDto(target.worldSlug(), target.worldDisplayName())); + visible.add( + new BootstrapWorldDto( + target.tenantSlug(), target.worldSlug(), target.worldDisplayName())); } } - visible.sort(Comparator.comparing(BootstrapWorldDto::worldSlug)); + visible.sort( + Comparator.comparing(BootstrapWorldDto::worldSlug) + .thenComparing(BootstrapWorldDto::tenantSlug)); return List.copyOf(visible); } @@ -174,18 +177,6 @@ private Map targetsByCanonicalTenant(List completeTargets) return Map.copyOf(byTenant); } - private void rejectAmbiguousWorldSlugs(List completeTargets) { - Map tenantsByWorldSlug = new HashMap<>(); - for (Target target : completeTargets) { - UUID previousTenant = - tenantsByWorldSlug.putIfAbsent(target.worldSlug(), target.canonicalTenantId()); - if (previousTenant != null && !previousTenant.equals(target.canonicalTenantId())) { - throw admissionPointerUnavailable( - new IllegalStateException("Public world slug is ambiguous across canonical tenants")); - } - } - } - private void requireSameCaller(VerifiedCaller original, VerifiedCaller current) { if (original.accountId() != current.accountId() || !original.accountUuid().equals(current.accountUuid())) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountService.java index 13795c7d9e..93c117a14c 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountService.java @@ -46,7 +46,8 @@ net.firedevops.firemud.accountservice.dto.AuthenticationResult verifyEmailLoginO java.util.List listBootstrapWorlds(String bootstrapToken); - java.util.List listBootstrapRealms(String bootstrapToken, String worldSlug); + java.util.List listBootstrapRealms( + String bootstrapToken, String tenantSlug, String worldSlug); java.util.List listBootstrapCharacters( String bootstrapToken, String worldSlug, String realmSlug, String connectScopeId); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java index cd964043bb..e3ac2ec028 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java @@ -139,13 +139,13 @@ public void issueDirectTextConnectScope( try { requireGameSessionPeer(); var context = request.getPlayerContext(); - long tenantId = requirePositiveRequestId(request.getTenantId(), "tenantId"); + UUID tenantId = requireCanonicalUuid(request.getTenantId(), "tenantId"); UUID realmId = requireCanonicalRealmId(request.getRealmId()); - long gameInstanceId = requirePositiveRequestId(request.getGameInstanceId(), "gameInstanceId"); - if (requirePositiveRequestId(context.getTenantId(), "tenantId") != tenantId + UUID gameInstanceId = requireCanonicalUuid(request.getGameInstanceId(), "gameInstanceId"); + if (!requireCanonicalUuid(context.getTenantId(), "tenantId").equals(tenantId) || !requireCanonicalRealmId(context.getRealmId()).equals(realmId) - || requirePositiveRequestId(context.getGameInstanceId(), "gameInstanceId") - != gameInstanceId + || !requireCanonicalUuid(context.getGameInstanceId(), "gameInstanceId") + .equals(gameInstanceId) || !context.getPlayableStateNamespaceId().equals(request.getPlayableStateNamespaceId()) || !context.getPlayableStateScope().equals(request.getPlayableStateScope())) { throw new InvalidRequestException("Player context and selected realm disagree", null); @@ -159,7 +159,8 @@ public void issueDirectTextConnectScope( realmId, requireText(request.getWorldSlug(), "worldSlug"), requireText(request.getRealmSlug(), "realmSlug"), - requireText(request.getPlayableStateNamespaceId(), "playableStateNamespaceId"), + requireCanonicalUuid( + request.getPlayableStateNamespaceId(), "playableStateNamespaceId"), requireText(request.getPlayableStateScope(), "playableStateScope"), gameInstanceId, request.getCatalogRevision(), @@ -208,17 +209,18 @@ public void joinPublicProductionMembership( new JoinPublicProductionRequest( requireText(request.getConnectScopeId(), "connectScopeId"), requestId)); if (!request.getPlayerContext().getAccountId().equals(result.accountId()) - || result.tenantId() != caller.tenantId()) { + || !result.tenantId().equals(caller.tenantId())) { throw new IllegalStateException("Account JOIN result does not match the validated caller"); } response .setSuccess(result.success()) .setOutcomeCode(result.outcomeCode()) .setAccountId(result.accountId()) - .setTenantId(Long.toString(result.tenantId())) + .setTenantId(result.tenantId().toString()) .setMembershipId(Long.toString(result.membershipId())) .setMembershipVersion(result.membershipVersion()) .setMembershipAuthorityGeneration(result.membershipAuthorityGeneration()) + .setGameplayAdmissionAllowed(result.gameplayAdmissionAllowed()) .setReplayed(result.replayed()); } catch (AdminAuthorizationException ex) { response.setError( @@ -302,9 +304,13 @@ private void requireCallerAccountSubject(UUID accountUuid) { } private static UUID requireCanonicalAccountUuid(String value) { + return requireCanonicalUuid(value, "accountId"); + } + + private static UUID requireCanonicalUuid(String value, String field) { UUID accountUuid = AccountUuidText.parseOrNull(value); if (accountUuid == null) { - throw new InvalidRequestException("accountId must be a canonical non-nil UUID", null); + throw new InvalidRequestException(field + " must be a canonical non-nil UUID", null); } return accountUuid; } @@ -312,57 +318,39 @@ private static UUID requireCanonicalAccountUuid(String value) { private DirectTextCallerContext directTextCaller( net.firedevops.firemud.shared.v1.PlayerExecutionContext context) { UUID accountUuid = requireCanonicalAccountUuid(context.getAccountId()); - long tenantId = requirePositiveRequestId(context.getTenantId(), "tenantId"); + UUID tenantId = requireCanonicalUuid(context.getTenantId(), "tenantId"); UUID realmId = requireCanonicalRealmId(context.getRealmId()); - String namespaceId = - requireCanonicalPlayableStateNamespaceId(context.getPlayableStateNamespaceId()); + UUID namespaceId = + requireCanonicalUuid(context.getPlayableStateNamespaceId(), "playableStateNamespaceId"); String scope = requireText(context.getPlayableStateScope(), "playableStateScope"); - long gameInstanceId = requirePositiveRequestId(context.getGameInstanceId(), "gameInstanceId"); - String sessionId = requireText(context.getSessionId(), "sessionId"); - String requestId = requireText(context.getRequestId(), "requestId"); - long accountStorageId = accountService.resolveAccountStorageId(accountUuid); - if (accountStorageId <= 0L) { - throw new IllegalStateException("Account UUID did not resolve to a persisted owner"); + if (!java.util.Set.of("SHARED", "ISOLATED").contains(scope)) { + throw new InvalidRequestException("playableStateScope must be SHARED or ISOLATED", null); } + UUID gameInstanceId = requireCanonicalUuid(context.getGameInstanceId(), "gameInstanceId"); + String sessionId = requireDirectTextTransportSession(context.getSessionId()); + String requestId = requireText(context.getRequestId(), "requestId"); return new DirectTextCallerContext( - accountStorageId, - tenantId, - realmId, - namespaceId, - scope, - gameInstanceId, - sessionId, - requestId); + accountUuid, tenantId, realmId, namespaceId, scope, gameInstanceId, sessionId, requestId); } - private UUID requireCanonicalRealmId(String value) { - if (value == null || value.isBlank()) { - throw new IllegalArgumentException("realmId is required"); + private static String requireDirectTextTransportSession(String value) { + if (value == null || value.length() > 32) { + throw new InvalidRequestException("sessionId must be a bounded numeric transport ID", null); } try { - UUID realmId = UUID.fromString(value); - if (!realmId.toString().equals(value)) { - throw new IllegalArgumentException("realmId must be a canonical UUID"); + long session = Long.parseLong(value); + if (session <= 0 || !value.matches("[0-9]+")) { + throw new NumberFormatException("Invalid transport session"); } - return realmId; - } catch (IllegalArgumentException ex) { - throw new IllegalArgumentException("realmId must be a canonical UUID", ex); + } catch (NumberFormatException malformed) { + throw new InvalidRequestException( + "sessionId must be a positive numeric transport ID", malformed); } + return value; } - private String requireCanonicalPlayableStateNamespaceId(String value) { - if (value == null || value.isBlank()) { - throw new IllegalArgumentException("playableStateNamespaceId is required"); - } - try { - UUID namespaceId = UUID.fromString(value); - if (!namespaceId.toString().equals(value)) { - throw new IllegalArgumentException("playableStateNamespaceId must be a canonical UUID"); - } - return value; - } catch (IllegalArgumentException ex) { - throw new IllegalArgumentException("playableStateNamespaceId must be a canonical UUID", ex); - } + private UUID requireCanonicalRealmId(String value) { + return requireCanonicalUuid(value, "realmId"); } private String requireText(String value, String fieldName) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java index a8fba53811..5527b0423b 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java @@ -11,6 +11,7 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; +import java.time.Clock; import java.time.Instant; import java.time.LocalDateTime; import java.util.Comparator; @@ -24,21 +25,23 @@ import java.util.UUID; import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.accountservice.AccountUuidText; -import net.firedevops.firemud.accountservice.client.EntityManagementClient; -import net.firedevops.firemud.accountservice.client.GameSessionClient; +import net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient; +import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; import net.firedevops.firemud.accountservice.config.AccountTokenProperties; import net.firedevops.firemud.accountservice.config.MailProperties; import net.firedevops.firemud.accountservice.dto.AccountDataExportDto; import net.firedevops.firemud.accountservice.dto.AccountDto; -import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; import net.firedevops.firemud.accountservice.dto.AccountLoginAuthModesDto; import net.firedevops.firemud.accountservice.dto.BootstrapCharacterDto; import net.firedevops.firemud.accountservice.dto.BootstrapRealmDto; import net.firedevops.firemud.accountservice.dto.BootstrapWorldDto; +import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; import net.firedevops.firemud.accountservice.dto.CompletePasswordResetRequest; import net.firedevops.firemud.accountservice.dto.ConnectTokenRequest; import net.firedevops.firemud.accountservice.dto.ConnectTokenResult; import net.firedevops.firemud.accountservice.dto.CreateAccountRequest; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; import net.firedevops.firemud.accountservice.dto.DirectTextJoinScope; import net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget; @@ -55,7 +58,6 @@ import net.firedevops.firemud.accountservice.dto.UpdateAccountLoginAuthModesRequest; import net.firedevops.firemud.accountservice.dto.UpdateProfileRequest; import net.firedevops.firemud.accountservice.dto.UsernameRecoveryRequest; -import net.firedevops.firemud.accountservice.dto.VerifiedJoinScope; import net.firedevops.firemud.accountservice.dto.VerifyEmailRequest; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge; @@ -68,6 +70,7 @@ import net.firedevops.firemud.accountservice.entity.EmailVerificationToken; import net.firedevops.firemud.accountservice.entity.Profile; import net.firedevops.firemud.accountservice.entity.ProfilePresenceVisibilityPolicy; +import net.firedevops.firemud.accountservice.entity.RetainedSubscriptionEvidence; import net.firedevops.firemud.accountservice.mapper.AccountMapper; import net.firedevops.firemud.accountservice.mapper.ProfileMapper; import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; @@ -79,26 +82,36 @@ import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.EventEvidence; import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; -import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionCurrentReceipt; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ReadFence; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; -import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.JoinOperation; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinOperationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinTerminalProof; import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository.PasswordResetReceipt; import net.firedevops.firemud.accountservice.repository.AccountRealmAccessGrantRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository.SourceSelection; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; import net.firedevops.firemud.accountservice.repository.EmailVerificationTokenRepository; import net.firedevops.firemud.accountservice.repository.ExternalAccountRepository; import net.firedevops.firemud.accountservice.repository.PasswordResetTokenRepository; import net.firedevops.firemud.accountservice.repository.PaymentTransactionRepository; import net.firedevops.firemud.accountservice.repository.ProfileRepository; -import net.firedevops.firemud.accountservice.repository.SubscriptionRepository; +import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback; +import net.firedevops.firemud.accountservice.service.AccountCanonicalConnectScopeReader; +import net.firedevops.firemud.accountservice.service.AccountCanonicalFirstJoinTerminalCoordinator; +import net.firedevops.firemud.accountservice.service.AccountCanonicalPublicRealmScopeOwner; import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository; import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository.Intent; +import net.firedevops.firemud.accountservice.service.AccountPublicBootstrapWorldsOwner; import net.firedevops.firemud.accountservice.service.AccountService; import net.firedevops.firemud.accountservice.service.EmailService; import net.firedevops.firemud.accountservice.service.NotificationService; @@ -110,26 +123,28 @@ import net.firedevops.firemud.common.LoggingUtil; import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec; import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec.PasswordResetAuthorityEvent; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target; import net.firedevops.firemud.common.security.JwtAuthProperties; import net.firedevops.firemud.common.security.JwtClaims; import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import org.jooq.exception.IntegrityConstraintViolationException; import org.slf4j.Logger; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; -import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.TransactionSynchronization; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; import org.springframework.util.StringUtils; import org.springframework.web.server.ResponseStatusException; -import tools.jackson.databind.json.JsonMapper; @Service public class AccountServiceImpl implements AccountService { @@ -149,9 +164,12 @@ public class AccountServiceImpl implements AccountService { private static final int EMAIL_LOGIN_OTP_MAX_ATTEMPTS = 5; private static final UUID NIL_ACCOUNT_UUID = new UUID(0L, 0L); private static final SecureRandom EMAIL_LOGIN_OTP_RANDOM = new SecureRandom(); - private static final JsonMapper AUDIT_JSON = JsonMapper.builder().build(); private String gameplayDecoyPasswordVerifier; + private volatile AccountPublicBootstrapWorldsOwner publicBootstrapWorldsOwner; + private volatile AccountCanonicalPublicRealmScopeOwner canonicalPublicRealmScopeOwner; + private volatile CanonicalScopeConsumers canonicalScopeConsumers; + private volatile AccountBootstrapRosterReadClient accountBootstrapRosterReadClient; private final AccountRepository accountRepository; private final AccountAuthorityGenerationRepository accountAuthorityGenerationRepository; @@ -161,7 +179,6 @@ public class AccountServiceImpl implements AccountService { private final AccountAuthoritySourceEventReadback accountAuthoritySourceEventReadback; private final AccountPasswordResetDraftSourceChangeRepository passwordResetDraftSourceChanges; private final AccountAuditOutboxRepository accountAuditOutboxRepository; - private final AccountConnectScopeRepository accountConnectScopeRepository; private final AccountJoinOperationRepository accountJoinOperationRepository; private final AccountEmailLoginChallengeRepository accountEmailLoginChallengeRepository; private final AccountRealmAccessGrantRepository accountRealmAccessGrantRepository; @@ -170,7 +187,7 @@ public class AccountServiceImpl implements AccountService { private final ProfileRepository profileRepository; private final ProfileMapper profileMapper; private final PaymentTransactionRepository paymentTransactionRepository; - private final SubscriptionRepository subscriptionRepository; + private final RetainedSubscriptionEvidenceRepository retainedSubscriptionEvidenceRepository; private final ExternalAccountRepository externalAccountRepository; private final PasswordResetTokenRepository passwordResetTokenRepository; private final EmailVerificationTokenRepository emailVerificationTokenRepository; @@ -179,8 +196,6 @@ public class AccountServiceImpl implements AccountService { private final MailProperties mailProperties; private final AccountTokenProperties tokenProperties; private final JwtAuthProperties jwtAuthProperties; - private final GameSessionClient gameSessionClient; - private final EntityManagementClient entityManagementClient; private final JwtUtil jwtUtil; private final net.firedevops.firemud.accountservice.service.session.SessionService sessionService; private final TransactionTemplate joinTransactionTemplate; @@ -199,7 +214,6 @@ public AccountServiceImpl( AccountSecurityStateOperationRepository securityStateOperationRepository, AccountPasswordResetDraftSourceChangeRepository passwordResetDraftSourceChanges, AccountAuditOutboxRepository accountAuditOutboxRepository, - AccountConnectScopeRepository accountConnectScopeRepository, AccountJoinOperationRepository accountJoinOperationRepository, AccountEmailLoginChallengeRepository accountEmailLoginChallengeRepository, AccountRealmAccessGrantRepository accountRealmAccessGrantRepository, @@ -208,7 +222,7 @@ public AccountServiceImpl( ProfileRepository profileRepository, ProfileMapper profileMapper, PaymentTransactionRepository paymentTransactionRepository, - SubscriptionRepository subscriptionRepository, + RetainedSubscriptionEvidenceRepository retainedSubscriptionEvidenceRepository, ExternalAccountRepository externalAccountRepository, PasswordResetTokenRepository passwordResetTokenRepository, EmailVerificationTokenRepository emailVerificationTokenRepository, @@ -217,8 +231,6 @@ public AccountServiceImpl( MailProperties mailProperties, AccountTokenProperties tokenProperties, JwtAuthProperties jwtAuthProperties, - GameSessionClient gameSessionClient, - EntityManagementClient entityManagementClient, JwtUtil jwtUtil, net.firedevops.firemud.accountservice.service.session.SessionService sessionService, PlatformTransactionManager transactionManager) { @@ -235,7 +247,6 @@ public AccountServiceImpl( securityStateOperationRepository); this.passwordResetDraftSourceChanges = passwordResetDraftSourceChanges; this.accountAuditOutboxRepository = accountAuditOutboxRepository; - this.accountConnectScopeRepository = accountConnectScopeRepository; this.accountJoinOperationRepository = accountJoinOperationRepository; this.accountEmailLoginChallengeRepository = accountEmailLoginChallengeRepository; this.accountRealmAccessGrantRepository = accountRealmAccessGrantRepository; @@ -244,7 +255,7 @@ public AccountServiceImpl( this.profileRepository = profileRepository; this.profileMapper = profileMapper; this.paymentTransactionRepository = paymentTransactionRepository; - this.subscriptionRepository = subscriptionRepository; + this.retainedSubscriptionEvidenceRepository = retainedSubscriptionEvidenceRepository; this.externalAccountRepository = externalAccountRepository; this.passwordResetTokenRepository = passwordResetTokenRepository; this.emailVerificationTokenRepository = emailVerificationTokenRepository; @@ -253,8 +264,6 @@ public AccountServiceImpl( this.mailProperties = mailProperties; this.tokenProperties = tokenProperties; this.jwtAuthProperties = jwtAuthProperties; - this.gameSessionClient = gameSessionClient; - this.entityManagementClient = entityManagementClient; this.jwtUtil = jwtUtil; this.sessionService = sessionService; this.joinTransactionTemplate = new TransactionTemplate(transactionManager); @@ -439,101 +448,571 @@ public PlayerBootstrapResult issuePlayerBootstrap(String accountIdentifier, Stri Instant.ofEpochMilli(expiresAt).toString()); } + /** + * Explicit held composition only. The canonical source remains unregistered until its owning + * runtime boundary is qualified; absence never selects the retained numeric discovery path. + */ + @Autowired(required = false) + public void setPublicBootstrapWorldsOwner(AccountPublicBootstrapWorldsOwner owner) { + this.publicBootstrapWorldsOwner = Objects.requireNonNull(owner); + } + + // Bootstrap/JOIN orchestration deliberately has no transaction advice: NOT_SUPPORTED would + // still create empty synchronization. These entry points reject ambient SQL, while each + // canonical owner opens its own short transaction around owner-local state only. @Override - @Transactional(readOnly = true) @Timed(value = "account.bootstrap_worlds") public List listBootstrapWorlds(String bootstrapToken) { - BootstrapContext bootstrapContext = requireBootstrapContext(bootstrapToken); - Map discoveryEntitlementMemo = new HashMap<>(); - return gameSessionClient.listGameplayWorlds().stream() - .filter( - world -> - hasAdmissibleRealm( - bootstrapContext, world.getWorldSlug(), discoveryEntitlementMemo)) - .map(world -> new BootstrapWorldDto(world.getWorldSlug(), world.getDisplayName())) - .toList(); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException("Public bootstrap world discovery refuses ambient SQL"); + } + AccountPublicBootstrapWorldsOwner owner = publicBootstrapWorldsOwner; + if (owner == null) { + throw new AuthenticationException( + "AUTH_UNAVAILABLE", "Canonical public-world discovery source is unavailable"); + } + return owner.listWorlds(bootstrapToken); + } + + /** + * Explicit held composition; the owner retains the signed V2 selector before publication. Its + * direct-text entry point authenticates the existing Game Session caller separately. + */ + @Autowired(required = false) + public void setCanonicalPublicRealmScopeOwner(AccountCanonicalPublicRealmScopeOwner owner) { + this.canonicalPublicRealmScopeOwner = Objects.requireNonNull(owner); + } + + /** Explicit composition of the existing canonical consumers; this does not register an issuer. */ + public void setCanonicalScopeConsumers( + AccountCanonicalConnectScopeReader reader, + CanonicalGameplayAdmissionDecisionReadClient targets, + AccountTenantAuthorityEventRepository tenantSources, + AccountDemoTenantEntitlementRepository demos, + AccountHostingSubscriptionLifecycleRepository hosting, + StripeHostingSubscriptionObserver observer, + AccountCanonicalFirstJoinTerminalCoordinator firstJoin, + String namespace, + Clock clock) { + if (!net.firedevops.firemud.common.grpc.GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + canonicalScopeConsumers = + new CanonicalScopeConsumers( + Objects.requireNonNull(reader), + Objects.requireNonNull(targets), + Objects.requireNonNull(tenantSources), + Objects.requireNonNull(demos), + Objects.requireNonNull(hosting), + Objects.requireNonNull(observer), + Objects.requireNonNull(firstJoin), + namespace, + Objects.requireNonNull(clock)); + } + + private CanonicalScopeConsumers requireCanonicalScopeConsumers() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException("Canonical scope consumers refuse ambient Account SQL"); + } + if (canonicalScopeConsumers == null) { + throw new AuthenticationException( + "AUTH_UNAVAILABLE", "Canonical scope consumers are unavailable"); + } + return canonicalScopeConsumers; + } + + private Target readCanonicalScopeTarget( + CanonicalScopeConsumers consumers, CanonicalJoinScopeV2 scope) { + return readCanonicalScopePublishedTarget(consumers, scope).currentTarget(); + } + + private PublishedRealmEvidence readCanonicalScopePublishedTarget( + CanonicalScopeConsumers consumers, CanonicalJoinScopeV2 scope) { + try { + RetainedTargetSelector selector = + new RetainedTargetSelector( + UUID.randomUUID(), + scope.accountId(), + consumers.namespace(), + scope.tenantId(), + scope.tenantSlug(), + scope.worldSlug(), + scope.realmId(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion()); + var resolved = + Objects.requireNonNull( + consumers.targets().resolvePublishedRealmAdmissionTarget(selector)); + // Only a locally verified target mismatch is definitive. Exceptions from either remote + // owner (including malformed evidence) remain unavailable rather than condemning the intent. + try { + net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec + .requireRetainedTargetMatches(selector, resolved.currentTarget()); + } catch (IllegalArgumentException mismatch) { + throw new AuthenticationException( + "CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE, mismatch); + } + if (!selector.equals(resolved.selector())) + throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); + var published = + Objects.requireNonNull( + consumers.targets().readPublishedRealmAdmissionOwner(resolved.strictSelector())); + if (!resolved.strictSelector().equals(published.selector()) + || !resolved.currentTarget().equals(published.currentTarget())) { + throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); + } + return published; + } catch (AuthenticationException failure) { + throw failure; + } catch (RuntimeException failure) { + throw new AuthenticationException( + "ADMISSION_POINTER_UNAVAILABLE", + "Gameplay target authority is unavailable; retry the same request", + failure); + } + } + + private Account lockCanonicalScopeAccount(CanonicalJoinScopeV2 scope) { + Account account = + accountRepository + .findByAccountUuidForUpdate(scope.accountId()) + .orElseThrow( + () -> new AuthenticationException("AUTH_UNAVAILABLE", "Account is unavailable")); + requireAccountStorageId(account, scope.accountId()); + requireAuthenticationEligible(account); + return account; + } + + private CanonicalJoinPreparation prepareCanonicalJoin( + CanonicalScopeConsumers consumers, + CanonicalJoinScopeV2 scope, + String requestId, + String callerBinding) { + // Retain the exact policy-independent intent before any fallible source/provider work. + joinTransactionTemplate.executeWithoutResult( + status -> { + lockCanonicalScopeAccount(scope); + accountJoinOperationRepository.insertCanonicalIntent(requestId, scope, callerBinding); + }); + return Objects.requireNonNull( + joinTransactionTemplate.execute( + status -> { + lockCanonicalScopeAccount(scope); + CanonicalJoinOperationEvidence operation = + accountJoinOperationRepository + .findCanonicalEvidenceForUpdateByRequestId(requestId) + .orElseThrow(); + if ("FAILED".equals(operation.status())) { + return new CanonicalJoinPreparation(operation, null, null, null); + } + SourceSelection source = + consumers.tenantSources().readCurrentSourceSelection(scope.tenantId()); + return switch (source.kind()) { + case PAID_HOSTING -> + new CanonicalJoinPreparation( + operation, + source, + null, + consumers.hosting().prepareCurrentRead(scope.tenantId())); + case NON_PAID_DEMO -> + new CanonicalJoinPreparation( + operation, source, consumers.demos().readCurrent(scope.tenantId()), null); + }; + })); + } + + private CanonicalJoinResult commitCanonicalJoin( + CanonicalScopeConsumers consumers, + CanonicalJoinScopeV2 scope, + String requestId, + String callerBinding, + CanonicalJoinPreparation prepared, + StripeHostingSubscriptionObserver.Result observation) { + return Objects.requireNonNull( + joinTransactionTemplate.execute( + status -> { + lockCanonicalScopeAccount(scope); + requireCanonicalScopeFresh(consumers, scope); + CanonicalJoinOperationEvidence lockedOperation = + accountJoinOperationRepository + .findCanonicalEvidenceForUpdateByRequestId(requestId) + .orElseThrow(); + if ("FAILED".equals(lockedOperation.status())) { + // Preparation precedes provider/target reads. Another exact attempt may have + // finished meanwhile, including before any policy evidence could be bound. + var retained = + accountJoinOperationRepository.finishCanonicalFailure( + requestId, scope, callerBinding, lockedOperation.outcome()); + return new CanonicalJoinResult(retained.outcome(), null, false, true); + } + SourceSelection current = + consumers.tenantSources().readCurrentSourceSelection(scope.tenantId()); + if (current.kind() != prepared.source().kind() + || !prepared.source().matches(current.checkpoint())) { + throw new AuthenticationException( + "ENTITLEMENT_UNAVAILABLE", "Tenant source changed"); + } + final boolean gameplayAvailable; + final boolean allowPublicJoin; + final long entitlementVersion; + if (prepared.fence() != null) { + AccountHostingSubscriptionCurrentReceipt receipt = + consumers.hosting().readCurrent(prepared.fence(), observation); + gameplayAvailable = receipt.gameplayAvailable(); + allowPublicJoin = receipt.allowPublicJoin(); + entitlementVersion = receipt.entitlementVersion(); + } else { + DemoTenantEntitlementSnapshot demo = consumers.demos().revalidate(prepared.demo()); + gameplayAvailable = demo.gameplayAvailable(); + allowPublicJoin = demo.allowPublicJoin(); + entitlementVersion = demo.entitlementVersion(); + } + CanonicalJoinOperationEvidence policyBoundOperation = + accountJoinOperationRepository.bindCanonicalPolicyEvidence( + requestId, scope, callerBinding, allowPublicJoin, entitlementVersion); + Optional member = + accountTenantMembershipRepository.findFreshMembershipForUpdate( + scope.accountId(), scope.tenantId()); + boolean active = + member.filter(value -> "ACTIVE".equals(value.getLifecycleState())).isPresent(); + if ("PENDING".equals(policyBoundOperation.status()) + && (!gameplayAvailable || (!active && !allowPublicJoin))) { + String outcome = + gameplayAvailable + ? "PUBLIC_PRODUCTION_ADMISSION_DENIED" + : "TENANT_BILLING_BLOCKED"; + accountJoinOperationRepository.finishCanonicalFailure( + requestId, scope, callerBinding, outcome); + return new CanonicalJoinResult(outcome, null, false, false); + } + var committed = + consumers + .firstJoin() + .commitCanonicalJoin( + scope, + requestId, + callerBinding, + prepared.fence() == null ? null : consumers.hosting(), + prepared.fence(), + observation); + requireCanonicalScopeFresh(consumers, scope); + Optional currentMembership = + accountTenantMembershipRepository.findFreshMembershipForUpdate( + scope.accountId(), scope.tenantId()); + if ("COMMITTED".equals(policyBoundOperation.status())) { + // A committed exact retry returns its original operation proof after the current + // policy binding above. Membership may have changed since that proof was retained; + // expose only the current admission flag, never use the old proof as admission. + return new CanonicalJoinResult( + committed.outcome(), + committed.terminalProof(), + gameplayAvailable + && currentMembership + .map(AccountTenantMembership::isGameplayAdmissionAllowed) + .orElse(false), + true); + } + AccountTenantMembership committedMembership = currentMembership.orElseThrow(); + if (committedMembership.getMembershipVersion() + != committed.terminalProof().membershipVersion() + || committedMembership.getMembershipAuthorityGeneration() + != committed.terminalProof().membershipAuthorityGeneration()) { + throw new IllegalStateException( + "Canonical JOIN result differs from current membership"); + } + return new CanonicalJoinResult( + committed.outcome(), + committed.terminalProof(), + committedMembership.isGameplayAdmissionAllowed(), + false); + })); + } + + private void requireCanonicalScopeFresh( + CanonicalScopeConsumers consumers, CanonicalJoinScopeV2 scope) { + Instant now = consumers.clock().instant(); + if (now.isBefore(Instant.parse(scope.evaluatedAt())) + || !now.isBefore(Instant.parse(scope.connectScopeExpiresAt()))) { + throw new AuthenticationException("CONNECT_SCOPE_INVALID", INVALID_CONNECT_SCOPE_MESSAGE); + } + } + + private record CanonicalScopeConsumers( + AccountCanonicalConnectScopeReader reader, + CanonicalGameplayAdmissionDecisionReadClient targets, + AccountTenantAuthorityEventRepository tenantSources, + AccountDemoTenantEntitlementRepository demos, + AccountHostingSubscriptionLifecycleRepository hosting, + StripeHostingSubscriptionObserver observer, + AccountCanonicalFirstJoinTerminalCoordinator firstJoin, + String namespace, + Clock clock) {} + + private record CanonicalJoinPreparation( + CanonicalJoinOperationEvidence operation, + SourceSelection source, + DemoTenantEntitlementSnapshot demo, + ReadFence fence) {} + + private record CanonicalJoinResult( + String outcome, + CanonicalJoinTerminalProof proof, + boolean gameplayAdmissionAllowed, + boolean replayed) {} + + /** Explicit non-admitting Entity projection; no default runtime client is registered here. */ + public void setAccountBootstrapRosterReadClient(AccountBootstrapRosterReadClient client) { + accountBootstrapRosterReadClient = Objects.requireNonNull(client); + } + + private BootstrapCharacterAuthority prepareBootstrapCharacterAuthority( + CanonicalScopeConsumers consumers, CanonicalJoinScopeV2 scope) { + return Objects.requireNonNull( + joinTransactionTemplate.execute( + status -> { + lockCanonicalScopeAccount(scope); + requireCanonicalScopeFresh(consumers, scope); + var membership = readBootstrapCharacterMembership(scope); + try { + SourceSelection source = + consumers.tenantSources().readCurrentSourceSelection(scope.tenantId()); + return new BootstrapCharacterAuthority( + source, + membership, + source.kind() == AccountTenantAuthorityEventRepository.SourceKind.NON_PAID_DEMO + ? consumers.demos().readCurrent(scope.tenantId()) + : null, + source.kind() == AccountTenantAuthorityEventRepository.SourceKind.PAID_HOSTING + ? consumers.hosting().prepareCurrentRead(scope.tenantId()) + : null, + consumers.clock().instant()); + } catch (RuntimeException failure) { + throw new AuthenticationException( + "ENTITLEMENT_UNAVAILABLE", + "Bootstrap entitlement source is unavailable", + failure); + } + })); + } + + private Optional + readBootstrapCharacterMembership(CanonicalJoinScopeV2 scope) { + try { + return accountTenantMembershipRepository + .findFreshMembershipForUpdate(scope.accountId(), scope.tenantId()) + .map( + member -> + new AccountCanonicalPublicRealmScopeOwner.ExistingMembership( + member.getId(), + member.getLifecycleState(), + member.isGameplayAdmissionAllowed(), + member.getMembershipVersion(), + member.getMembershipAuthorityGeneration())); + } catch (RuntimeException failure) { + throw new AuthenticationException( + "AUTH_UNAVAILABLE", "Bootstrap membership source is unavailable", failure); + } + } + + private void requireBootstrapCharacterAuthority( + CanonicalScopeConsumers consumers, + CanonicalJoinScopeV2 scope, + BootstrapCharacterAuthority prepared, + StripeHostingSubscriptionObserver.Result observation) { + joinTransactionTemplate.executeWithoutResult( + status -> { + lockCanonicalScopeAccount(scope); + requireCanonicalScopeFresh(consumers, scope); + var membership = readBootstrapCharacterMembership(scope); + if (!prepared.membership().equals(membership)) { + throw new AuthenticationException( + "AUTH_UNAVAILABLE", "Bootstrap membership changed during discovery"); + } + final boolean gameplayAvailable; + final boolean allowPublicJoin; + try { + SourceSelection current = + consumers.tenantSources().readCurrentSourceSelection(scope.tenantId()); + if (current.kind() != prepared.source().kind() + || !prepared.source().matches(current.checkpoint())) { + throw new IllegalStateException("Bootstrap entitlement source changed"); + } + if (prepared.fence() != null) { + var receipt = consumers.hosting().readCurrent(prepared.fence(), observation); + gameplayAvailable = receipt.gameplayAvailable(); + allowPublicJoin = receipt.allowPublicJoin(); + } else { + Instant currentTime = consumers.clock().instant(); + if (currentTime.isBefore(prepared.observedAt()) + || !currentTime.isBefore(prepared.observedAt().plusSeconds(15))) { + throw new IllegalStateException( + "Original bootstrap entitlement observation expired"); + } + var demo = consumers.demos().revalidate(prepared.demo()); + gameplayAvailable = demo.gameplayAvailable(); + allowPublicJoin = demo.allowPublicJoin(); + } + } catch (RuntimeException failure) { + throw new AuthenticationException( + "ENTITLEMENT_UNAVAILABLE", + "Bootstrap entitlement source is unavailable or changed", + failure); + } + if (!gameplayAvailable) { + throw new AuthenticationException( + "TENANT_BILLING_BLOCKED", "Gameplay is not available for this tenant"); + } + if (membership.isEmpty() + || "INACTIVE".equals(membership.orElseThrow().lifecycleState())) { + throw new AuthenticationException( + allowPublicJoin ? "JOIN_REQUIRED" : "PUBLIC_PRODUCTION_ADMISSION_DENIED", + allowPublicJoin ? JOIN_REQUIRED_CHARACTERS_MESSAGE : "Public enrollment is closed"); + } + if (!"ACTIVE".equals(membership.orElseThrow().lifecycleState()) + || !membership.orElseThrow().gameplayAdmissionAllowed()) { + throw new AuthenticationException( + "PUBLIC_PRODUCTION_ADMISSION_DENIED", "Membership does not allow actor discovery"); + } + }); + } + + private record BootstrapCharacterAuthority( + SourceSelection source, + Optional membership, + DemoTenantEntitlementSnapshot demo, + ReadFence fence, + Instant observedAt) {} + + private StripeHostingSubscriptionObserver.Result observeBootstrapCharacterSource( + CanonicalScopeConsumers consumers, BootstrapCharacterAuthority prepared) { + if (prepared.fence() == null) return null; + try { + return consumers.observer().observe(prepared.fence().binding()); + } catch (RuntimeException failure) { + throw new AuthenticationException( + "ENTITLEMENT_UNAVAILABLE", "Bootstrap provider source is unavailable", failure); + } + } + + private void requireSameBootstrapCaller(BootstrapContext original, String token) { + if (!original.equals(requireBootstrapContext(token))) { + throw new AuthenticationException( + "AUTH_UNAVAILABLE", "Bootstrap caller changed during actor discovery"); + } } @Override - @Transactional(propagation = Propagation.NOT_SUPPORTED) @Timed(value = "account.bootstrap_realms") - public List listBootstrapRealms(String bootstrapToken, String worldSlug) { - BootstrapContext bootstrapContext = requireBootstrapContext(bootstrapToken); - Map discoveryEntitlementMemo = new HashMap<>(); - Instant evaluatedAt = Instant.now(); - Instant expiresAt = evaluatedAt.plusMillis(tokenProperties.getConnectScopeExpirationMs()); - final List admissibleRealms; - try { - admissibleRealms = - listAdmissibleRuntimeRealmTargets(bootstrapContext, worldSlug, discoveryEntitlementMemo); - } catch (AuthenticationException ex) { - throw ex; - } catch (RuntimeException ex) { - throw admissionPointerUnavailable(ex); + public List listBootstrapRealms( + String bootstrapToken, String tenantSlug, String worldSlug) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException("Public bootstrap realm discovery refuses ambient SQL"); + } + AccountCanonicalPublicRealmScopeOwner owner = canonicalPublicRealmScopeOwner; + if (owner == null) { + throw new AuthenticationException( + "AUTH_UNAVAILABLE", "Canonical public-realm scope source is unavailable"); } - return admissibleRealms.stream() + return owner.listRealmScopes(bootstrapToken, tenantSlug, worldSlug).stream() .map( - discovered -> { - RuntimeRealmTarget current = - requireRealmTarget( - discovered.tenantId(), discovered.worldSlug(), discovered.realmSlug()); - if (!sameRuntimeRealmAuthority(discovered, current)) { - throw admissionPointerUnavailable( - new IllegalStateException( - "Public realm authority changed during bootstrap discovery")); - } - return current; + retained -> { + var target = retained.target(); + var scope = retained.scope(); + return new BootstrapRealmDto( + scope.worldSlug(), + scope.realmSlug(), + scope.realmId(), + target.realmDisplayName(), + scope.tenantId(), + scope.gameInstanceId(), + scope.pointerVersion(), + scope.catalogRevision(), + scope.playableStateNamespaceId(), + PlayableStateScope.valueOf("PLAYABLE_STATE_SCOPE_" + scope.playableStateScope()) + .name(), + scope.playableStateScope(), + target.characterCreationPolicy(), + scope.evaluatedAt(), + scope.connectScopeExpiresAt(), + scope.connectScopeId()); }) - .map( - realm -> - new BootstrapRealmDto( - realm.worldSlug(), - realm.realmSlug(), - realm.realmId().toString(), - realm.displayName(), - realm.tenantId(), - realm.gameInstanceId(), - realm.pointerVersion(), - realm.catalogRevision(), - realm.playableStateNamespaceId(), - toPlayableStateScope(realm).name(), - realm.requiresCharacterSelection(), - realm.stateScope(), - realm.characterCreationPolicy(), - evaluatedAt.toString(), - expiresAt.toString(), - mintAndRetainConnectScope(bootstrapContext, realm, evaluatedAt, expiresAt))) .toList(); } @Override - @Transactional(readOnly = true) @Timed(value = "account.bootstrap_characters") public List listBootstrapCharacters( String bootstrapToken, String worldSlug, String realmSlug, String connectScopeId) { + CanonicalScopeConsumers consumers = requireCanonicalScopeConsumers(); + AccountBootstrapRosterReadClient roster = accountBootstrapRosterReadClient; + if (roster == null) + throw new AuthenticationException( + "AUTH_UNAVAILABLE", "Canonical Entity bootstrap discovery is unavailable"); BootstrapContext bootstrapContext = requireBootstrapContext(bootstrapToken); - ConnectScopeContext scopeContext = requireConnectScopeContext(connectScopeId); - validateConnectScopeAgainstBootstrap(bootstrapContext, scopeContext); - validateConnectScopeRoute(scopeContext, worldSlug, realmSlug); - RuntimeRealmTarget realm = - requireCurrentAdmissibleConnectScopeTarget(bootstrapContext, scopeContext); - UUID accountUuid = bootstrapContext.accountUuid(); - if (accountUuid == null || NIL_ACCOUNT_UUID.equals(accountUuid)) { - throw new IllegalStateException("Bootstrap Account UUID is unavailable"); + CanonicalJoinScopeV2 scope = + consumers.reader().read(bootstrapContext.accountUuid(), connectScopeId); + if (!scope.worldSlug().equals(worldSlug) || !scope.realmSlug().equals(realmSlug)) { + throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); + } + if (!"SHARED".equals(scope.playableStateScope())) { + throw new AuthenticationException( + "REALM_UNAVAILABLE", "Bootstrap actor discovery does not yet support this realm policy"); } - return entityManagementClient - .listCharactersByAccount( - realm.tenantId(), accountUuid, realm.gameInstanceId(), toPlayableStateScope(realm)) - .stream() - .sorted(Comparator.comparing(net.firedevops.firemud.entitymanagement.v1.Character::getName)) + PublishedRealmEvidence published = readCanonicalScopePublishedTarget(consumers, scope); + if (!"SHARED".equals(published.currentTarget().playableStateScope()) + || !"PRESEEDED_ONLY".equals(published.currentTarget().characterCreationPolicy())) { + throw new AuthenticationException( + "REALM_UNAVAILABLE", "Bootstrap actor discovery does not yet support this realm policy"); + } + BootstrapCharacterAuthority prepared = prepareBootstrapCharacterAuthority(consumers, scope); + var observation = observeBootstrapCharacterSource(consumers, prepared); + requireBootstrapCharacterAuthority(consumers, scope, prepared, observation); + requireSameBootstrapCaller(bootstrapContext, bootstrapToken); + final List actors; + try { + actors = List.copyOf(roster.read(UUID.randomUUID(), scope.accountId(), published)); + } catch (io.grpc.StatusRuntimeException failure) { + String code = + failure.getStatus().getCode() == io.grpc.Status.Code.FAILED_PRECONDITION + ? "CONNECT_SCOPE_MISMATCH" + : "AUTH_UNAVAILABLE"; + throw new AuthenticationException( + code, "Entity bootstrap discovery is unavailable or changed", failure); + } catch (RuntimeException failure) { + throw new AuthenticationException( + "AUTH_UNAVAILABLE", "Entity bootstrap discovery is malformed or unavailable", failure); + } + PublishedRealmEvidence current = readCanonicalScopePublishedTarget(consumers, scope); + if (!published.currentTarget().equals(current.currentTarget()) + || !java.util.Arrays.equals( + published.sourceEvidence().publishedPolicySetEvidence().canonicalBytes(), + current.sourceEvidence().publishedPolicySetEvidence().canonicalBytes())) { + throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); + } + requireSameBootstrapCaller(bootstrapContext, bootstrapToken); + var finalObservation = observeBootstrapCharacterSource(consumers, prepared); + requireBootstrapCharacterAuthority(consumers, scope, prepared, finalObservation); + requireCanonicalScopeFresh(consumers, scope); + requireSameBootstrapCaller(bootstrapContext, bootstrapToken); + return actors.stream() + .sorted( + Comparator.comparing(AccountBootstrapRosterReadClient.Actor::displayName) + .thenComparing(actor -> actor.characterId().toString())) .map( - character -> + actor -> new BootstrapCharacterDto( - character.getId(), - character.getName(), - character.getLevel(), - realm.stateScope(), - realm.characterCreationPolicy())) + actor.characterId().toString(), + actor.displayName(), + actor.level(), + scope.playableStateScope(), + published.currentTarget().characterCreationPolicy())) .toList(); } @@ -541,6 +1020,7 @@ public List listBootstrapCharacters( @Timed(value = "account.public_production_join") public JoinPublicProductionResult joinPublicProduction( String bootstrapToken, JoinPublicProductionRequest request) { + CanonicalScopeConsumers consumers = requireCanonicalScopeConsumers(); BootstrapContext caller = requireBootstrapContext(bootstrapToken); Claims callerClaims = requireSignedTokenClaims( @@ -556,426 +1036,189 @@ public JoinPublicProductionResult joinPublicProduction( throw new AuthenticationException( "CONNECT_CONTEXT_INVALID", "Bootstrap caller binding is missing", ex); } - requireAuthenticationEligible(requireAccount(caller.accountId())); - return projectJoinOutcome( - joinPublicProductionForTrustedCaller(caller.accountId(), callerBinding, null, request)); + return joinCanonicalPublicProduction( + consumers, + caller.accountUuid(), + callerBinding, + request, + () -> { + BootstrapContext current = requireBootstrapContext(bootstrapToken); + if (!caller.equals(current)) { + throw new AuthenticationException("AUTH_UNAVAILABLE", "Bootstrap caller changed"); + } + }); } - @Override - @Transactional(propagation = Propagation.NOT_SUPPORTED) - @Timed(value = "account.direct_text_connect_scope") - public DirectTextJoinScope issueDirectTextConnectScope( - DirectTextCallerContext caller, DirectTextJoinTarget target) { - if (caller == null - || target == null - || caller.accountId() <= 0L - || !StringUtils.hasText(caller.requestId()) - || caller.tenantId() != target.tenantId() - || !caller.realmId().equals(target.realmId()) - || caller.gameInstanceId() != target.gameInstanceId() - || !caller.playableStateNamespaceId().equals(target.playableStateNamespaceId()) - || !caller.playableStateScope().equals(target.playableStateScope())) { + private JoinPublicProductionResult joinCanonicalPublicProduction( + CanonicalScopeConsumers consumers, + UUID accountUuid, + String callerBinding, + JoinPublicProductionRequest request, + Runnable recheckCaller) { + if (request == null + || !StringUtils.hasText(request.connectScopeId()) + || !StringUtils.hasText(request.requestId())) { throw new AuthenticationException("CONNECT_SCOPE_INVALID", INVALID_CONNECT_SCOPE_MESSAGE); } - Account account = requireAccount(caller.accountId()); - requireAuthenticationEligible(account); - RuntimeRealmTarget current = - requireRealmTarget(target.tenantId(), target.worldSlug(), target.realmSlug()); - if (!isPublicProductionRealm(current)) { + if (request.requestId().length() > JoinPublicProductionRequest.MAX_REQUEST_ID_LENGTH) { throw new AuthenticationException( - "REALM_UNAVAILABLE", "Selected public realm is unavailable"); - } - if (!current.realmId().equals(target.realmId()) - || !current.playableStateNamespaceId().equals(target.playableStateNamespaceId()) - || !current.stateScope().equals(target.playableStateScope()) - || current.gameInstanceId() != target.gameInstanceId() - || current.catalogRevision() != target.catalogRevision() - || current.pointerVersion() != target.pointerVersion()) { - throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); + "INVALID_ARGUMENT", "JOIN requestId exceeds the maximum length"); } - RuntimeEntitlementsDto entitlements = - getTenantEntitlementsForRuntime(current.tenantId(), caller.requestId()); - if (!entitlements.gameplayAvailable()) { + CanonicalJoinScopeV2 scope = consumers.reader().read(accountUuid, request.connectScopeId()); + try { + CanonicalJoinPreparation prepared = + prepareCanonicalJoin(consumers, scope, request.requestId(), callerBinding); + StripeHostingSubscriptionObserver.Result observation = null; + if (!"FAILED".equals(prepared.operation().status())) { + Target target = readCanonicalScopeTarget(consumers, scope); + // The SDK's sealed result crosses source transactions; provider I/O never runs under SQL. + observation = + prepared.fence() == null + ? null + : consumers.observer().observe(prepared.fence().binding()); + if (!target.equals(readCanonicalScopeTarget(consumers, scope))) { + throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); + } + } + // Terminal failures need no remote authority, but retain caller and locked identity checks. + recheckCaller.run(); + CanonicalJoinResult committed = + commitCanonicalJoin( + consumers, scope, request.requestId(), callerBinding, prepared, observation); + CanonicalJoinTerminalProof proof = committed.proof(); + // Publish only after the owner transaction has committed; response loss is exact-retryable. + return new JoinPublicProductionResult( + proof != null, + committed.outcome(), + scope.accountId().toString(), + scope.tenantId(), + proof == null ? 0L : proof.membershipId(), + proof == null ? 0L : proof.membershipVersion(), + proof == null ? 0L : proof.membershipAuthorityGeneration(), + committed.gameplayAdmissionAllowed(), + committed.replayed()); + } catch (AccountJoinOperationRepository.CanonicalJoinOperationConflictException failure) { + throw new AuthenticationException( + "IDEMPOTENCY_CONFLICT", "JOIN request ID conflicts", failure); + } catch (RuntimeException failure) { + String code = + failure instanceof AuthenticationException authentication + ? authentication.getCode() + : "ENTITLEMENT_UNAVAILABLE"; + try { + recordCanonicalJoinFailure(scope, request.requestId(), callerBinding, code); + } catch (RuntimeException recordFailure) { + if (recordFailure != failure) failure.addSuppressed(recordFailure); + logger.warn( + "Canonical JOIN failure state could not be recorded; cause={}", + recordFailure.getClass().getSimpleName()); + } + if (failure instanceof AuthenticationException authentication) throw authentication; throw new AuthenticationException( - "TENANT_BILLING_BLOCKED", "Gameplay is not available for this tenant"); + code, "Canonical JOIN authority is unavailable; retry the same request", failure); + } + } + + private void recordCanonicalJoinFailure( + CanonicalJoinScopeV2 scope, String requestId, String callerBinding, String failureCode) { + // Expiry is terminal for this caller attempt, not a new durable operation outcome. The + // reader rejects the same expired scope without rewriting its retained intent; preserve + // that behavior when time crosses the boundary during provider I/O or the commit gate. + if ("CONNECT_SCOPE_INVALID".equals(failureCode)) return; + joinTransactionTemplate.executeWithoutResult( + status -> { + lockCanonicalScopeAccount(scope); + Optional found = + accountJoinOperationRepository.findCanonicalEvidenceForUpdateByRequestId(requestId); + if (found.isEmpty() || !"PENDING".equals(found.orElseThrow().status())) return; + if ("CONNECT_SCOPE_MISMATCH".equals(failureCode)) { + accountJoinOperationRepository.finishCanonicalFailure( + requestId, scope, callerBinding, failureCode); + } else { + String retryCode = + List.of( + "ADMISSION_POINTER_UNAVAILABLE", + "ENTITLEMENT_UNAVAILABLE", + "AUTH_UNAVAILABLE") + .contains(failureCode) + ? failureCode + : "AUTH_UNAVAILABLE"; + String authorityAvailability = + "ENTITLEMENT_UNAVAILABLE".equals(retryCode) ? "UNAVAILABLE" : "NOT_EVALUATED"; + accountJoinOperationRepository.recordCanonicalAttemptFailure( + requestId, scope, callerBinding, authorityAvailability, retryCode); + } + }); + } + + @Override + @Timed(value = "account.direct_text_connect_scope") + public DirectTextJoinScope issueDirectTextConnectScope( + DirectTextCallerContext caller, DirectTextJoinTarget target) { + if (canonicalPublicRealmScopeOwner == null) { + throw new AuthenticationException( + "AUTH_UNAVAILABLE", "Canonical scope producer is unavailable"); } - Instant evaluatedAt = Instant.now(); - Instant expiresAt = evaluatedAt.plusMillis(tokenProperties.getConnectScopeExpirationMs()); - requireAuthenticationAccountUuid(account); - String scopeId = - mintAndRetainConnectScope( - new BootstrapContext(caller.accountId(), account.getAccountUuid()), - current, - evaluatedAt, - expiresAt); - return new DirectTextJoinScope(scopeId, expiresAt.toString(), evaluatedAt.toString()); + CanonicalJoinScopeV2 scope = + canonicalPublicRealmScopeOwner.issueDirectTextScope(caller, target).scope(); + return new DirectTextJoinScope( + scope.connectScopeId(), scope.connectScopeExpiresAt(), scope.evaluatedAt()); } @Override @Timed(value = "account.public_production_join_internal") public JoinPublicProductionResult joinPublicProductionFromGameSession( DirectTextCallerContext caller, JoinPublicProductionRequest request) { + CanonicalScopeConsumers consumers = requireCanonicalScopeConsumers(); + requireCanonicalDirectPeer(consumers); if (caller == null - || caller.accountId() <= 0L + || caller.accountId() == null + || NIL_ACCOUNT_UUID.equals(caller.accountId()) || !StringUtils.hasText(caller.sessionId()) + || caller.sessionId().length() > 32 + || !caller.sessionId().matches("[0-9]+") + || !isPositiveTransportSession(caller.sessionId()) + || !StringUtils.hasText(caller.requestId()) || request == null || !caller.requestId().equals(request.requestId())) { throw new AuthenticationException( "CONNECT_CONTEXT_INVALID", "JOIN caller context is missing"); } - requireAuthenticationEligible(requireAccount(caller.accountId())); - return projectJoinOutcome( - joinPublicProductionForTrustedCaller( - caller.accountId(), caller.sessionId(), caller, request)); - } - - private JoinOutcome joinPublicProductionForTrustedCaller( - long accountId, - String callerBinding, - DirectTextCallerContext directTextCaller, - JoinPublicProductionRequest request) { - if (request == null - || !StringUtils.hasText(request.connectScopeId()) - || !StringUtils.hasText(request.requestId())) { - throw new AuthenticationException("CONNECT_SCOPE_INVALID", INVALID_CONNECT_SCOPE_MESSAGE); - } - if (request.requestId().length() > JoinPublicProductionRequest.MAX_REQUEST_ID_LENGTH) { - throw new AuthenticationException( - "INVALID_ARGUMENT", "JOIN requestId exceeds the maximum length"); - } - String requestId = request.requestId(); - String scopeTokenHash = AccountJoinDigest.tokenHash(request.connectScopeId()); - Optional existing = accountJoinOperationRepository.find(requestId); - VerifiedJoinScope retained; - if (existing.isPresent()) { - JoinOperation operation = existing.orElseThrow(); - if (operation.accountId() != accountId - || !operation.callerBinding().equals(callerBinding) - || !operation.scopeTokenHash().equals(scopeTokenHash)) { - throw new AuthenticationException( - "IDEMPOTENCY_CONFLICT", "JOIN request ID was reused with different input"); - } - retained = retainedJoinScope(request.connectScopeId()); - validateDirectTextJoinScope(directTextCaller, retained); - requireMatchingJoinIntent(operation, requestId, callerBinding, retained); - } else { - ConnectScopeContext signedScope = requireConnectScopeContext(request.connectScopeId()); - retained = retainedJoinScope(request.connectScopeId()); - validateDirectTextJoinScope(directTextCaller, retained); - validateSignedJoinScope(signedScope, retained, accountId); - String intentDigest = AccountJoinDigest.intent(requestId, retained, callerBinding); - try { - joinTransactionTemplate.execute( - transactionStatus -> - accountJoinOperationRepository.insertIntent( - requestId, retained, callerBinding, intentDigest)); - } catch (RuntimeException ex) { - Optional claimReadback = safeFindJoinOperation(requestId); - if (claimReadback.isEmpty()) { - if (connectScopeEvidenceIsMissing(request.connectScopeId())) { - throw new AuthenticationException( - "CONNECT_SCOPE_INVALID", "JOIN scope evidence is unavailable", ex); - } - throw new AuthenticationException( - "AUTH_UNAVAILABLE", "JOIN request claim is uncertain; retry the same request", ex); - } - requireMatchingJoinIntent(claimReadback.orElseThrow(), requestId, callerBinding, retained); - } - JoinOperation claimed = - accountJoinOperationRepository - .find(requestId) - .orElseThrow( - () -> - new AuthenticationException( - "AUTH_UNAVAILABLE", "JOIN request claim is not yet readable")); - requireMatchingJoinIntent(claimed, requestId, callerBinding, retained); - } - - try { - JoinAttemptOutcome outcome = - joinTransactionTemplate.execute( - transactionStatus -> - executeJoinAttempt(accountId, callerBinding, requestId, retained)); - if (outcome.terminalOperation() != null) { - return replayTerminalJoinSafely(outcome.terminalOperation(), callerBinding, retained); - } - return outcome.result(); - } catch (AuthenticationException ex) { - if ("IDEMPOTENCY_CONFLICT".equals(ex.getCode())) { - throw ex; - } - recordJoinAttemptFailureAfterRollback(requestId, ex.getCode()); - return pendingJoinFailure(retained, ex.getCode()); - } catch (RuntimeException ex) { - Optional outcomeReadback = safeFindJoinOperation(requestId); - if (outcomeReadback.isPresent()) { - JoinOperation operation = outcomeReadback.orElseThrow(); - requireMatchingJoinIntent(operation, requestId, callerBinding, retained); - if (!"PENDING".equals(operation.status())) { - return replayTerminalJoinSafely(operation, callerBinding, retained); - } - recordJoinAttemptFailureAfterRollback(requestId, "AUTH_UNAVAILABLE"); - } - throw new AuthenticationException( - "AUTH_UNAVAILABLE", "JOIN outcome is uncertain; retry the same request", ex); - } - } - - private JoinAttemptOutcome executeJoinAttempt( - long accountId, String callerBinding, String requestId, VerifiedJoinScope scope) { - accountJoinOperationRepository.lockAccount(accountId); - JoinOperation operation = - accountJoinOperationRepository - .findForUpdate(requestId) - .orElseThrow(() -> new IllegalStateException("JOIN request claim disappeared")); - requireMatchingJoinIntent(operation, requestId, callerBinding, scope); - - if (!"PENDING".equals(operation.status())) { - return JoinAttemptOutcome.terminal(operation); + CanonicalJoinScopeV2 scope = + consumers.reader().read(caller.accountId(), request.connectScopeId()); + if (!scope.tenantId().equals(caller.tenantId()) + || !scope.realmId().equals(caller.realmId()) + || !scope.playableStateNamespaceId().equals(caller.playableStateNamespaceId()) + || !scope.playableStateScope().equals(caller.playableStateScope()) + || !scope.gameInstanceId().equals(caller.gameInstanceId())) { + throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); } - return JoinAttemptOutcome.result( - executePendingJoinAttempt(accountId, callerBinding, requestId, scope, operation)); - } - - private JoinOutcome executePendingJoinAttempt( - long accountId, - String callerBinding, - String requestId, - VerifiedJoinScope scope, - JoinOperation operation) { - if (isConnectScopeExpired(scope)) { - return failedJoin(requestId, scope, "CONNECT_SCOPE_INVALID"); - } - - JoinEvaluation evaluation = evaluateJoin(scope, false); - if (evaluation.failureCode() != null) { - if (isRetryableJoinAuthorityFailure(evaluation)) { - accountJoinOperationRepository.recordAttemptFailure( - requestId, evaluation.authorityAvailability(), evaluation.failureCode()); - return pendingJoinFailure(scope, evaluation.failureCode()); - } - return failedJoin(requestId, scope, evaluation.failureCode()); - } - if (!"AVAILABLE".equals(evaluation.authorityAvailability()) - || evaluation.allowPublicJoin() == null - || evaluation.entitlementVersion() == null) { - accountJoinOperationRepository.recordAttemptFailure( - requestId, evaluation.authorityAvailability(), "ENTITLEMENT_UNAVAILABLE"); - return pendingJoinFailure(scope, "ENTITLEMENT_UNAVAILABLE"); - } - String requestDigest = - AccountJoinDigest.request( - scope, callerBinding, evaluation.allowPublicJoin(), evaluation.entitlementVersion()); - if (operation.requestDigest() != null - && (!Integer.valueOf(1).equals(operation.requestDigestVersion()) - || !operation.requestDigest().equals(requestDigest))) { - return failedJoin(requestId, scope, "IDEMPOTENCY_CONFLICT"); - } - if (operation.requestDigest() == null) { - accountJoinOperationRepository.bindPolicyEvidence( - requestId, requestDigest, evaluation.entitlementVersion(), evaluation.allowPublicJoin()); - } - if (!evaluation.gameplayAvailable()) { - return failedJoin(requestId, scope, "TENANT_BILLING_BLOCKED"); - } - if (!evaluation.allowPublicJoin()) { - return failedJoin(requestId, scope, "PUBLIC_PRODUCTION_ADMISSION_DENIED"); - } - - JoinEvaluation commitEvaluation = evaluateJoin(scope, true); - if (commitEvaluation.failureCode() != null) { - if (isRetryableJoinAuthorityFailure(commitEvaluation)) { - accountJoinOperationRepository.recordAttemptFailure( - requestId, commitEvaluation.authorityAvailability(), commitEvaluation.failureCode()); - return pendingJoinFailure(scope, commitEvaluation.failureCode()); - } - return failedJoin(requestId, scope, commitEvaluation.failureCode()); - } - if (!"AVAILABLE".equals(commitEvaluation.authorityAvailability())) { - accountJoinOperationRepository.recordAttemptFailure( - requestId, commitEvaluation.authorityAvailability(), "ENTITLEMENT_UNAVAILABLE"); - return pendingJoinFailure(scope, "ENTITLEMENT_UNAVAILABLE"); - } - String commitDigest = - AccountJoinDigest.request( - scope, - callerBinding, - commitEvaluation.allowPublicJoin(), - commitEvaluation.entitlementVersion()); - if (!requestDigest.equals(commitDigest)) { - return failedJoin(requestId, scope, "IDEMPOTENCY_CONFLICT"); - } - if (!commitEvaluation.gameplayAvailable()) { - return failedJoin(requestId, scope, "TENANT_BILLING_BLOCKED"); - } - if (!commitEvaluation.allowPublicJoin()) { - return failedJoin(requestId, scope, "PUBLIC_PRODUCTION_ADMISSION_DENIED"); - } - AccountTenantMembership membership = - accountTenantMembershipRepository - .findByAccountIdAndTenantId(accountId, scope.tenantId()) - .orElse(null); - boolean transitioned = false; - if (membership == null) { - membership = new AccountTenantMembership(); - membership.setAccount(requireAccount(accountId)); - membership.setTenantId(scope.tenantId()); - membership.setMembershipVersion(1L); - membership.setMembershipAuthorityGeneration(1L); - membership.setLifecycleState("ACTIVE"); - membership.setGameplayAdmissionAllowed(true); - membership.setAuthorityProvenance("EXPLICIT_JOIN"); - accountTenantMembershipRepository.save(membership); - transitioned = true; - } else if ("INACTIVE".equals(membership.getLifecycleState())) { - accountJoinOperationRepository.recordCallerBoundAuthorityInvalidation(requestId); - membership.setLifecycleState("ACTIVE"); - membership.setGameplayAdmissionAllowed(true); - membership.setMembershipVersion(membership.getMembershipVersion() + 1L); - membership.setMembershipAuthorityGeneration( - membership.getMembershipAuthorityGeneration() + 1L); - membership.setAuthorityProvenance("EXPLICIT_JOIN"); - accountTenantMembershipRepository.save(membership); - transitioned = true; - } else if (!"ACTIVE".equals(membership.getLifecycleState()) - || !membership.isGameplayAdmissionAllowed()) { - return failedJoin(requestId, scope, "MEMBERSHIP_RECONCILIATION_REQUIRED"); - } - if (transitioned) { - String payload = - AUDIT_JSON.writeValueAsString( - new JoinAuditPayload( - accountId, - scope.tenantId(), - scope.worldSlug(), - scope.realmSlug(), - membership.getMembershipVersion(), - requestId)); - UUID auditEventId = - UUID.nameUUIDFromBytes( - ("account-join-audit/v1:" + requestId).getBytes(StandardCharsets.UTF_8)); - accountAuditOutboxRepository.append( - auditEventId, "tenant", scope.tenantId(), "ACCOUNT_JOINED_PUBLIC_PRODUCTION", payload); - } - accountJoinOperationRepository.finish( - requestId, - "COMMITTED", - transitioned ? "JOINED" : "ALREADY_ACTIVE", - membership.getId(), - membership.getMembershipVersion(), - membership.getMembershipAuthorityGeneration()); - return new JoinOutcome( - true, - transitioned ? "JOINED" : "ALREADY_ACTIVE", - accountId, - scope.tenantId(), - membership.getId(), - membership.getMembershipVersion(), - membership.getMembershipAuthorityGeneration(), - false); - } - - private JoinOutcome failedJoin(String requestId, VerifiedJoinScope scope, String outcomeCode) { - accountJoinOperationRepository.finish(requestId, "FAILED", outcomeCode, null, null, null); - return new JoinOutcome( - false, outcomeCode, scope.accountId(), scope.tenantId(), 0L, 0L, 0L, false); - } - - private JoinOutcome pendingJoinFailure(VerifiedJoinScope scope, String outcomeCode) { - return joinRetryFailure(scope, outcomeCode); + return joinCanonicalPublicProduction( + consumers, + caller.accountId(), + caller.sessionId(), + request, + () -> requireCanonicalDirectPeer(consumers)); } - private JoinOutcome replayTerminalJoin( - JoinOperation operation, String callerBinding, VerifiedJoinScope scope) { - if (isConnectScopeExpired(scope)) { - return joinRetryFailure(scope, "CONNECT_SCOPE_INVALID"); - } - - boolean replayUnboundFailure = - "FAILED".equals(operation.status()) && operation.requestDigest() == null; - - JoinEvaluation evaluation; + private static boolean isPositiveTransportSession(String value) { try { - evaluation = evaluateJoin(scope); - } catch (AuthenticationException ex) { - return joinRetryFailure( - scope, isStorageBackedEntitlementFailure(ex) ? ex.getCode() : "AUTH_UNAVAILABLE"); - } catch (RuntimeException ex) { - return joinRetryFailure(scope, "AUTH_UNAVAILABLE"); - } - if (evaluation.failureCode() != null) { - if ("ENTITLEMENT_UNAVAILABLE".equals(evaluation.failureCode())) { - return joinRetryFailure(scope, evaluation.failureCode()); - } - if (isRetryableJoinAuthorityFailure(evaluation)) { - return joinRetryFailure(scope, "AUTH_UNAVAILABLE"); - } - return joinRetryFailure(scope, evaluation.failureCode()); - } - if (!"AVAILABLE".equals(evaluation.authorityAvailability()) - || evaluation.allowPublicJoin() == null - || evaluation.entitlementVersion() == null) { - return joinRetryFailure(scope, "AUTH_UNAVAILABLE"); - } - if (replayUnboundFailure) { - return resultFromJoinOperation(operation, true); + return Long.parseLong(value) > 0; + } catch (NumberFormatException malformed) { + return false; } + } - String currentRequestDigest = - AccountJoinDigest.request( - scope, callerBinding, evaluation.allowPublicJoin(), evaluation.entitlementVersion()); - if (!Integer.valueOf(1).equals(operation.requestDigestVersion()) - || operation.requestDigest() == null - || operation.allowPublicJoin() == null - || !operation.allowPublicJoin().equals(evaluation.allowPublicJoin()) - || operation.entitlementVersion() == null - || !operation.entitlementVersion().equals(evaluation.entitlementVersion()) - || !operation.requestDigest().equals(currentRequestDigest) - || ("COMMITTED".equals(operation.status()) - && (!evaluation.gameplayAvailable() || !evaluation.allowPublicJoin()))) { - return joinRetryFailure(scope, "IDEMPOTENCY_CONFLICT"); + private void requireCanonicalDirectPeer(CanonicalScopeConsumers consumers) { + var peer = net.firedevops.firemud.common.grpc.GrpcPeerIdentity.current(); + if (peer == null + || !peer.isService("game-session-service") + || !peer.isInNamespace(consumers.namespace())) { + throw new AuthenticationException( + "AUTH_UNAVAILABLE", "Exact Game Session workload is required"); } - return resultFromJoinOperation(operation, true); } - private JoinOutcome replayTerminalJoinSafely( - JoinOperation operation, String callerBinding, VerifiedJoinScope scope) { - try { - return replayTerminalJoin(operation, callerBinding, scope); - } catch (RuntimeException policyCheckFailure) { - return joinRetryFailure(scope, "AUTH_UNAVAILABLE"); - } - } - - private JoinOutcome joinRetryFailure(VerifiedJoinScope scope, String outcomeCode) { - return new JoinOutcome( - false, outcomeCode, scope.accountId(), scope.tenantId(), 0L, 0L, 0L, false); - } - - /** Project only after the JOIN transaction has returned, preserving any committed receipt. */ - private JoinPublicProductionResult projectJoinOutcome(JoinOutcome outcome) { - return new JoinPublicProductionResult( - outcome.success(), - outcome.outcomeCode(), - responseAccountUuid(outcome.accountId()), - outcome.tenantId(), - outcome.membershipId(), - outcome.membershipVersion(), - outcome.membershipAuthorityGeneration(), - outcome.replayed()); - } - - /** Private Account row identities never escape through response projection. */ - private record JoinOutcome( - boolean success, - String outcomeCode, - long accountId, - long tenantId, - long membershipId, - long membershipVersion, - long membershipAuthorityGeneration, - boolean replayed) {} - private String responseAccountUuid(Long accountId) { try { return responseAccountUuid(requireAccount(accountId), accountId); @@ -997,256 +1240,20 @@ private String responseAccountUuid(Account account, Long accountId) { } } - private boolean isConnectScopeExpired(VerifiedJoinScope scope) { - try { - return !Instant.parse(scope.connectScopeExpiresAt()).isAfter(Instant.now()); - } catch (RuntimeException ex) { - return true; - } - } - - private boolean isRetryableJoinAuthorityFailure(JoinEvaluation evaluation) { - return "UNAVAILABLE".equals(evaluation.authorityAvailability()) - || "ADMISSION_POINTER_UNAVAILABLE".equals(evaluation.failureCode()) - || "AUTH_UNAVAILABLE".equals(evaluation.failureCode()) - || "ENTITLEMENT_UNAVAILABLE".equals(evaluation.failureCode()); - } - - private VerifiedJoinScope retainedJoinScope(String connectScopeId) { - return accountConnectScopeRepository - .find(connectScopeId) - .orElseThrow( - () -> - new AuthenticationException( - "CONNECT_SCOPE_INVALID", "JOIN scope evidence is unavailable")); - } - - private boolean connectScopeEvidenceIsMissing(String connectScopeId) { - try { - return accountConnectScopeRepository.find(connectScopeId).isEmpty(); - } catch (RuntimeException ex) { - return false; - } - } - - private void validateSignedJoinScope( - ConnectScopeContext signedScope, VerifiedJoinScope retained, long accountId) { - if (retained.accountId() != accountId - || signedScope.accountId() != accountId - || signedScope.tenantId() != retained.tenantId() - || !signedScope.realmId().equals(retained.realmId()) - || !signedScope.playableStateNamespaceId().equals(retained.playableStateNamespaceId()) - || !signedScope.playableStateScope().equals(retained.playableStateScope()) - || signedScope.gameInstanceId() != retained.gameInstanceId() - || signedScope.catalogRevision() != retained.catalogRevision() - || signedScope.pointerVersion() != retained.pointerVersion() - || !signedScope.worldSlug().equals(retained.worldSlug()) - || !signedScope.realmSlug().equals(retained.realmSlug()) - || !signedScope.evaluatedAt().toString().equals(retained.evaluatedAt()) - || !signedScope - .connectScopeExpiresAt() - .toString() - .equals(retained.connectScopeExpiresAt())) { - throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); - } - } - - private void requireMatchingJoinIntent( - JoinOperation operation, String requestId, String callerBinding, VerifiedJoinScope scope) { - String expectedIntentDigest = AccountJoinDigest.intent(requestId, scope, callerBinding); - if (operation.accountId() != scope.accountId() - || !operation.realmId().equals(scope.realmId()) - || !operation.callerBinding().equals(callerBinding) - || !operation.scopeTokenHash().equals(AccountJoinDigest.tokenHash(scope.connectScopeId())) - || !operation.connectScopeDigest().equals(scope.snapshotDigest()) - || operation.intentDigestVersion() != 1 - || !operation.intentDigest().equals(expectedIntentDigest)) { - throw new AuthenticationException( - "IDEMPOTENCY_CONFLICT", "JOIN request ID was reused with different input"); - } - } - - private JoinOutcome resultFromJoinOperation(JoinOperation operation, boolean replayed) { - return new JoinOutcome( - "COMMITTED".equals(operation.status()), - operation.outcome(), - operation.accountId(), - operation.tenantId(), - operation.membershipId() == null ? 0L : operation.membershipId(), - operation.membershipVersion() == null ? 0L : operation.membershipVersion(), - operation.membershipAuthorityGeneration() == null - ? 0L - : operation.membershipAuthorityGeneration(), - replayed); - } - - private Optional safeFindJoinOperation(String requestId) { - try { - return accountJoinOperationRepository.find(requestId); - } catch (RuntimeException ignored) { - return Optional.empty(); - } - } - - private void recordJoinAttemptFailureAfterRollback(String requestId, String failureCode) { - String availability = - "ENTITLEMENT_UNAVAILABLE".equals(failureCode) ? "UNAVAILABLE" : "NOT_EVALUATED"; - try { - joinTransactionTemplate.execute( - transactionStatus -> { - accountJoinOperationRepository - .findForUpdate(requestId) - .ifPresent( - operation -> { - if ("PENDING".equals(operation.status())) { - accountJoinOperationRepository.recordAttemptFailure( - requestId, availability, failureCode); - } - }); - return null; - }); - } catch (RuntimeException ignored) { - // The durable intent stays pending, and the caller retries the same request ID. - } - } - - private void validateDirectTextJoinScope( - DirectTextCallerContext caller, VerifiedJoinScope scope) { - if (caller != null - && (caller.accountId() != scope.accountId() - || caller.tenantId() != scope.tenantId() - || !caller.realmId().equals(scope.realmId()) - || caller.gameInstanceId() != scope.gameInstanceId() - || !caller.playableStateNamespaceId().equals(scope.playableStateNamespaceId()) - || !caller.playableStateScope().equals(scope.playableStateScope()))) { - throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); - } - } - - private JoinEvaluation evaluateJoin(VerifiedJoinScope scope) { - return evaluateJoin(scope, true); - } - - private JoinEvaluation evaluateJoin(VerifiedJoinScope scope, boolean lockEntitlement) { - return evaluateJoin( - new ConnectScopeContext( - scope.accountId(), - scope.tenantId(), - scope.realmId(), - scope.worldSlug(), - scope.realmSlug(), - scope.playableStateNamespaceId(), - scope.playableStateScope(), - scope.gameInstanceId(), - scope.catalogRevision(), - scope.pointerVersion(), - Instant.parse(scope.evaluatedAt()), - Instant.parse(scope.connectScopeExpiresAt())), - lockEntitlement); - } - - private JoinEvaluation evaluateJoin(ConnectScopeContext scope, boolean lockEntitlement) { - RuntimeRealmTarget target; - try { - target = requireCurrentConnectScopeTarget(scope); - } catch (AuthenticationException ex) { - if ("CONNECT_SCOPE_MISMATCH".equals(ex.getCode()) - || "ADMISSION_POINTER_UNAVAILABLE".equals(ex.getCode())) { - return new JoinEvaluation("NOT_EVALUATED", null, null, false, ex.getCode()); - } - throw ex; - } - if (!isPublicProductionRealm(target)) { - return new JoinEvaluation( - "NOT_EVALUATED", null, null, false, "PUBLIC_PRODUCTION_ADMISSION_DENIED"); - } - try { - RuntimeEntitlementsDto entitlement = joinEntitlement(scope.tenantId(), lockEntitlement); - return new JoinEvaluation( - "AVAILABLE", - entitlement.allowPublicJoin(), - entitlement.entitlementVersion(), - entitlement.gameplayAvailable(), - null); - } catch (AuthenticationException ex) { - if ("ENTITLEMENT_UNAVAILABLE".equals(ex.getCode())) { - if (isStorageBackedEntitlementFailure(ex)) { - // Leave a potentially aborted SQL transaction before recording the failed attempt. - throw ex; - } - return new JoinEvaluation("UNAVAILABLE", null, null, false, ex.getCode()); - } - throw ex; - } - } - - private boolean isStorageBackedEntitlementFailure(AuthenticationException failure) { - return "ENTITLEMENT_UNAVAILABLE".equals(failure.getCode()) - && (failure.getCause() instanceof org.jooq.exception.DataAccessException - || failure.getCause() instanceof DataAccessException); - } - - private record JoinEvaluation( - String authorityAvailability, - Boolean allowPublicJoin, - Long entitlementVersion, - boolean gameplayAvailable, - String failureCode) {} - - private record JoinAttemptOutcome(JoinOutcome result, JoinOperation terminalOperation) { - private static JoinAttemptOutcome result(JoinOutcome result) { - return new JoinAttemptOutcome(result, null); - } - - private static JoinAttemptOutcome terminal(JoinOperation operation) { - return new JoinAttemptOutcome(null, operation); - } - } - - private RuntimeEntitlementsDto joinEntitlement(long tenantId, boolean lockSubscription) { - return readTenantEntitlements(tenantId, lockSubscription); - } - private RuntimeEntitlementsDto readTenantEntitlements(long tenantId, boolean lockSubscription) { - List rows; - try { - rows = - lockSubscription - ? subscriptionRepository.findByTenantIdForUpdate(tenantId) - : subscriptionRepository.findByTenantId(tenantId); - } catch (org.jooq.exception.MappingException | org.jooq.exception.ConfigurationException ex) { - throw ex; - } catch (org.jooq.exception.DataAccessException | DataAccessException ex) { - throw new AuthenticationException( - "ENTITLEMENT_UNAVAILABLE", - "Tenant entitlement authority is unavailable; retry later", - ex); - } - if (rows == null || rows.size() != 1 || rows.getFirst() == null) { - throw new AuthenticationException( - "ENTITLEMENT_UNAVAILABLE", "Tenant entitlement authority is missing or ambiguous"); - } - var subscription = rows.getFirst(); - if (subscription.getEntitlementVersion() <= 0L) { - throw new AuthenticationException( - "ENTITLEMENT_UNAVAILABLE", "Entitlement version is missing"); - } - return new RuntimeEntitlementsDto( - tenantId, - isGameplayAvailableStatus(subscription.getStatus()), - isPublicJoinAllowedStatus(subscription.getStatus()), - subscription.getEntitlementVersion(), - subscription.getEntitlementVersion(), - Instant.now().toString()); + // Retained numeric rows cannot supply canonical identity, provider provenance, current-row + // selection, or a committed billing checkpoint. Deny before any historical evidence read. + throw new AuthenticationException( + "ENTITLEMENT_UNAVAILABLE", + "Canonical tenant entitlement authority is unavailable; retry later"); } @Override - @Transactional(readOnly = true) @Timed(value = "account.connect_token") public ConnectTokenResult issueConnectToken(String bootstrapToken, ConnectTokenRequest request) { + CanonicalScopeConsumers consumers = requireCanonicalScopeConsumers(); BootstrapContext bootstrapContext = requireBootstrapContext(bootstrapToken); - ConnectScopeContext scopeContext = requireConnectScopeContext(request.connectScopeId()); - validateConnectScopeAgainstBootstrap(bootstrapContext, scopeContext); + consumers.reader().read(bootstrapContext.accountUuid(), request.connectScopeId()); throw new AuthenticationException( "AUTH_UNAVAILABLE", "Canonical gameplay connect-token authority is unavailable"); } @@ -1350,385 +1357,11 @@ public RuntimeEntitlementsDto getTenantEntitlementsForRuntime(Long tenantId, Str } private BootstrapContext requireBootstrapContext(String bootstrapToken) { - Claims claims = - requireSignedTokenClaims( - bootstrapToken, - "player-bootstrap", - "CONNECT_CONTEXT_INVALID", - "Missing bootstrap token", - "Invalid bootstrap token"); - UUID subject = - claims.get("sub") instanceof String text ? AccountUuidText.parseOrNull(text) : null; - UUID accountUuid = - claims.get("accountId") instanceof String text ? AccountUuidText.parseOrNull(text) : null; - if (subject == null || accountUuid == null || !subject.equals(accountUuid)) { - throw new AuthenticationException("CONNECT_CONTEXT_INVALID", "Invalid bootstrap token"); - } - final Long accountId; - try { - accountId = resolveAccountStorageId(accountUuid); - } catch (IllegalArgumentException | IllegalStateException | DataAccessException ex) { - throw new AuthenticationException("AUTH_UNAVAILABLE", "Account authority is unavailable", ex); - } - if (!sessionService.isAccountSessionActive(accountId, bootstrapToken)) { - throw new AuthenticationException("CONNECT_CONTEXT_INVALID", "Bootstrap token expired"); - } - return new BootstrapContext(accountId, accountUuid); - } - - private RuntimeRealmTarget requireRealmTarget( - Long expectedTenantId, String worldSlug, String realmSlug) { - try { - List candidates = - listRuntimeRealmTargets(worldSlug, realmSlug).stream() - .filter(realm -> java.util.Objects.equals(worldSlug, realm.worldSlug())) - .filter(realm -> java.util.Objects.equals(realmSlug, realm.realmSlug())) - .filter(realm -> expectedTenantId == null || realm.tenantId() == expectedTenantId) - .toList(); - if (candidates.size() != 1) { - throw new IllegalStateException("Selected gameplay realm is absent or ambiguous"); - } - RuntimeRealmTarget candidate = candidates.getFirst(); - RuntimeRealmTarget realm = - readRuntimeRealmTarget( - gameSessionClient.getAdmissionPointer(candidate.tenantId(), worldSlug, realmSlug)); - if (realm.tenantId() != candidate.tenantId() - || !realm.realmId().equals(candidate.realmId()) - || !realm.playableStateNamespaceId().equals(candidate.playableStateNamespaceId()) - || !realm.stateScope().equals(candidate.stateScope()) - || realm.gameInstanceId() != candidate.gameInstanceId() - || realm.visible() != candidate.visible() - || realm.publicProductionRealm() != candidate.publicProductionRealm() - || realm.catalogRevision() != candidate.catalogRevision() - || realm.pointerVersion() != candidate.pointerVersion() - || !java.util.Objects.equals(worldSlug, realm.worldSlug()) - || !java.util.Objects.equals(realmSlug, realm.realmSlug())) { - throw new AuthenticationException( - "ADMISSION_POINTER_UNAVAILABLE", - "Selected gameplay realm is no longer admissible; rerun realm discovery before retrying gameplay entry"); - } - return realm; - } catch (AuthenticationException ex) { - throw ex; - } catch (RuntimeException ex) { - throw admissionPointerUnavailable(ex); - } - } - - private boolean hasAdmissibleRealm( - BootstrapContext bootstrapContext, - String worldSlug, - Map discoveryEntitlementMemo) { - try { - return !listAdmissibleRuntimeRealmTargets( - bootstrapContext, worldSlug, discoveryEntitlementMemo) - .isEmpty(); - } catch (IllegalStateException ex) { - return false; - } - } - - private List listAdmissibleRuntimeRealmTargets( - BootstrapContext bootstrapContext, - String worldSlug, - Map discoveryEntitlementMemo) { - List realms = - gameSessionClient.listGameplayRealms(worldSlug); - if (realms == null) { - throw new IllegalStateException("Gameplay realm discovery returned no authority"); - } - List targets = - realms.stream() - .map(realm -> readReachableDiscoveryRealm(bootstrapContext, realm)) - .flatMap(Optional::stream) - .toList(); - validatePublicRealmCardinality(targets); - return targets.stream() - .filter( - realm -> isDiscoveryRealmAdmissible(bootstrapContext, realm, discoveryEntitlementMemo)) - .toList(); - } - - private List listRuntimeRealmTargets( - String worldSlug, String selectedRealmSlug) { - try { - List realms = - gameSessionClient.listGameplayRealms(worldSlug); - if (realms == null) { - throw new IllegalStateException("Gameplay realm discovery returned no authority"); - } - var realmStream = realms.stream(); - if (selectedRealmSlug != null) { - realmStream = - realmStream.filter( - realm -> - realm != null - && java.util.Objects.equals(selectedRealmSlug, realm.getRealmSlug())); - } - List targets = realmStream.map(this::readRuntimeRealmTarget).toList(); - validatePublicRealmCardinality(targets); - return targets; - } catch (AuthenticationException ex) { - throw ex; - } catch (RuntimeException ex) { - throw admissionPointerUnavailable(ex); - } - } - - private void validatePublicRealmCardinality(List realms) { - // The RPC is world-local: zero local public realms may be a valid private-only world when the - // tenant's public realm is in another world. Game Session owns the tenant-global zero check; - // Account can defensively reject only duplicate visible public targets returned here. - Map visiblePublicRealmCounts = - realms.stream() - .filter(this::isPublicProductionRealm) - .collect( - java.util.stream.Collectors.groupingBy( - RuntimeRealmTarget::tenantId, java.util.stream.Collectors.counting())); - if (realms.stream() - .map(RuntimeRealmTarget::tenantId) - .distinct() - .anyMatch(tenantId -> visiblePublicRealmCounts.getOrDefault(tenantId, 0L) > 1L)) { - throw admissionPointerUnavailable( - new IllegalStateException("Public production realm authority is ambiguous")); - } - } - - private Optional readReachableDiscoveryRealm( - BootstrapContext bootstrapContext, - net.firedevops.firemud.gamesession.v1.GameplayRealm realm) { - if (realm == null) { - throw admissionPointerUnavailable( - new IllegalArgumentException("Gameplay realm discovery returned a null realm")); - } - final RuntimeRealmTarget target; - try { - target = readRuntimeRealmTarget(realm); - } catch (IllegalArgumentException ex) { - if (isMalformedRealmReachable(bootstrapContext, realm)) { - throw admissionPointerUnavailable(ex); - } - return Optional.empty(); - } - return Optional.of(target); - } - - private boolean isMalformedRealmReachable( - BootstrapContext bootstrapContext, - net.firedevops.firemud.gamesession.v1.GameplayRealm realm) { - if (realm.getVisible() && realm.getPublicProductionRealm()) { - return true; - } - - final long tenantId; - try { - tenantId = requirePositiveLong(realm.getTenantId(), "tenantId"); - } catch (IllegalArgumentException ex) { - return false; - } - if (accountTenantMembershipRepository - .findByAccountIdAndTenantId(bootstrapContext.accountId(), tenantId) - .filter(AccountTenantMembership::isGameplayAdmissionAllowed) - .isEmpty()) { - return false; - } - if (!hasRealmAccessGrant( - bootstrapContext.accountId(), tenantId, realm.getWorldSlug(), realm.getRealmSlug())) { - return false; - } - return true; - } - - private AuthenticationException admissionPointerUnavailable(Throwable cause) { - return new AuthenticationException( - "ADMISSION_POINTER_UNAVAILABLE", - "Selected gameplay realm is no longer admissible; rerun realm discovery before retrying gameplay entry", - cause); - } - - private boolean isDiscoveryRealmAdmissible( - BootstrapContext bootstrapContext, - RuntimeRealmTarget realm, - Map discoveryEntitlementMemo) { - if (!hasRealmAdmissionAccess(bootstrapContext, realm)) { - return false; - } - RuntimeEntitlementsDto entitlements = - discoveryEntitlementMemo.computeIfAbsent( - realm.tenantId(), - tenantId -> getTenantEntitlementsForRuntime(tenantId, "bootstrap-discovery")); - return entitlements.gameplayAvailable(); - } - - private boolean hasRealmAdmissionAccess( - BootstrapContext bootstrapContext, RuntimeRealmTarget realm) { - long tenantId = realm.tenantId(); - if (!isPublicProductionRealm(realm)) { - if (accountTenantMembershipRepository - .findByAccountIdAndTenantId(bootstrapContext.accountId(), tenantId) - .filter(AccountTenantMembership::isGameplayAdmissionAllowed) - .isEmpty()) { - return false; - } - if (!hasRealmAccessGrant( - bootstrapContext.accountId(), tenantId, realm.worldSlug(), realm.realmSlug())) { - return false; - } - } - return true; - } - - private boolean isPublicProductionRealm(RuntimeRealmTarget realm) { - return realm.visible() && realm.publicProductionRealm(); - } - - private boolean sameRuntimeRealmAuthority( - RuntimeRealmTarget expected, RuntimeRealmTarget actual) { - return expected.tenantId() == actual.tenantId() - && expected.realmId().equals(actual.realmId()) - && expected.playableStateNamespaceId().equals(actual.playableStateNamespaceId()) - && expected.gameInstanceId() == actual.gameInstanceId() - && expected.worldSlug().equals(actual.worldSlug()) - && expected.realmSlug().equals(actual.realmSlug()) - && expected.pointerVersion() == actual.pointerVersion() - && expected.catalogRevision() == actual.catalogRevision() - && expected.visible() == actual.visible() - && expected.publicProductionRealm() == actual.publicProductionRealm() - && expected.stateScope().equals(actual.stateScope()) - && expected.characterCreationPolicy().equals(actual.characterCreationPolicy()) - && expected.requiresCharacterSelection() == actual.requiresCharacterSelection(); - } - - private String mintConnectScopeId( - BootstrapContext bootstrapContext, - RuntimeRealmTarget realm, - Instant evaluatedAt, - Instant expiresAt) { - long expirationMs = Math.max(1L, expiresAt.toEpochMilli() - evaluatedAt.toEpochMilli()); - return mintToken( - bootstrapContext.accountUuid().toString(), - expirationMs, - Map.ofEntries( - Map.entry("aud", "bootstrap-connect-scope"), - Map.entry("accountId", bootstrapContext.accountUuid().toString()), - Map.entry("tenantId", realm.tenantId()), - Map.entry("realmId", realm.realmId().toString()), - Map.entry("worldSlug", realm.worldSlug()), - Map.entry("realmSlug", realm.realmSlug()), - Map.entry("playableStateNamespaceId", realm.playableStateNamespaceId()), - Map.entry("playableStateScope", realm.stateScope()), - Map.entry("gameInstanceId", realm.gameInstanceId()), - Map.entry("catalogRevision", realm.catalogRevision()), - Map.entry("pointerVersion", realm.pointerVersion()), - Map.entry("evaluatedAt", evaluatedAt.toString()), - Map.entry("connectScopeExpiresAt", expiresAt.toString()), - Map.entry( - "jti", - stableId( - "connect-scope", - bootstrapContext.accountId(), - Long.toString(realm.tenantId()), - realm.worldSlug(), - realm.realmSlug(), - realm.pointerVersion(), - evaluatedAt.toString())))); - } - - private String mintAndRetainConnectScope( - BootstrapContext caller, RuntimeRealmTarget realm, Instant evaluatedAt, Instant expiresAt) { - try { - if (!Long.valueOf(caller.accountId()).equals(resolveAccountStorageId(caller.accountUuid()))) { - throw new IllegalStateException("Scope Account UUID resolved to a different owner"); - } - } catch (IllegalArgumentException | IllegalStateException | DataAccessException ex) { - throw new AuthenticationException("AUTH_UNAVAILABLE", "Account authority is unavailable", ex); - } - String connectScopeId = mintConnectScopeId(caller, realm, evaluatedAt, expiresAt); - if (isPublicProductionRealm(realm)) { - VerifiedJoinScope pending = - new VerifiedJoinScope( - connectScopeId, - caller.accountId(), - realm.tenantId(), - realm.realmId(), - realm.worldSlug(), - realm.realmSlug(), - realm.playableStateNamespaceId(), - realm.stateScope(), - realm.gameInstanceId(), - realm.catalogRevision(), - realm.pointerVersion(), - evaluatedAt.toString(), - expiresAt.toString(), - ""); - accountConnectScopeRepository.insert( - new VerifiedJoinScope( - pending.connectScopeId(), - pending.accountId(), - pending.tenantId(), - pending.realmId(), - pending.worldSlug(), - pending.realmSlug(), - pending.playableStateNamespaceId(), - pending.playableStateScope(), - pending.gameInstanceId(), - pending.catalogRevision(), - pending.pointerVersion(), - pending.evaluatedAt(), - pending.connectScopeExpiresAt(), - AccountJoinDigest.scope(pending))); - } - return connectScopeId; - } - - private ConnectScopeContext requireConnectScopeContext(String connectScopeId) { - Claims claims = - requireSignedTokenClaims( - connectScopeId, - "bootstrap-connect-scope", - "CONNECT_SCOPE_INVALID", - INVALID_CONNECT_SCOPE_MESSAGE, - INVALID_CONNECT_SCOPE_MESSAGE); - try { - JwtClaims.SignedGameplayRoutingClaims routingClaims = - JwtClaims.requireSignedGameplayRoutingClaims( - claims, "signed token account subject mismatch"); - Instant connectScopeExpiresAt = parseInstant(claims.get("connectScopeExpiresAt")); - Instant evaluatedAt = parseInstant(claims.get("evaluatedAt")); - if (connectScopeExpiresAt == null) { - throw new AuthenticationException("CONNECT_SCOPE_INVALID", INVALID_CONNECT_SCOPE_MESSAGE); - } - if (evaluatedAt == null) { - throw new AuthenticationException("CONNECT_SCOPE_INVALID", INVALID_CONNECT_SCOPE_MESSAGE); - } - UUID realmId = requireCanonicalRealmId(claims.get("realmId")); - String namespace = - JwtClaims.requireText(claims.get("playableStateNamespaceId"), "playableStateNamespaceId"); - String scope = JwtClaims.requireText(claims.get("playableStateScope"), "playableStateScope"); - long catalogRevision = requirePositiveLong(claims.get("catalogRevision"), "catalogRevision"); - final Long accountId; - try { - accountId = resolveAccountStorageId(UUID.fromString(routingClaims.accountId())); - } catch (IllegalArgumentException | IllegalStateException | DataAccessException ex) { - throw new AuthenticationException( - "AUTH_UNAVAILABLE", "Account authority is unavailable", ex); - } - return new ConnectScopeContext( - accountId, - routingClaims.tenantId(), - realmId, - routingClaims.worldSlug(), - routingClaims.realmSlug(), - namespace, - scope, - routingClaims.gameInstanceId(), - catalogRevision, - routingClaims.pointerVersion(), - evaluatedAt, - connectScopeExpiresAt); - } catch (IllegalArgumentException ex) { - throw new AuthenticationException("CONNECT_SCOPE_INVALID", INVALID_CONNECT_SCOPE_MESSAGE, ex); - } + var caller = + new net.firedevops.firemud.accountservice.service.session + .AccountPlayerBootstrapCallerVerifier(jwtUtil, accountRepository, sessionService) + .requireCaller(bootstrapToken); + return new BootstrapContext(caller.accountId(), caller.accountUuid()); } private Claims requireSignedTokenClaims( @@ -1756,93 +1389,6 @@ private Claims requireSignedTokenClaims( } } - private void validateConnectScopeAgainstBootstrap( - BootstrapContext bootstrapContext, ConnectScopeContext scopeContext) { - if (scopeContext.accountId() != bootstrapContext.accountId()) { - throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); - } - } - - private void validateConnectScopeRoute( - ConnectScopeContext scopeContext, String worldSlug, String realmSlug) { - if (!java.util.Objects.equals(scopeContext.worldSlug(), worldSlug) - || !java.util.Objects.equals(scopeContext.realmSlug(), realmSlug)) { - throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); - } - } - - private RuntimeRealmTarget requireCurrentConnectScopeTarget(ConnectScopeContext scopeContext) { - RuntimeRealmTarget currentRealm = - requireRealmTarget( - scopeContext.tenantId(), scopeContext.worldSlug(), scopeContext.realmSlug()); - if (currentRealm.tenantId() != scopeContext.tenantId() - || !currentRealm.realmId().equals(scopeContext.realmId()) - || !currentRealm.playableStateNamespaceId().equals(scopeContext.playableStateNamespaceId()) - || !currentRealm.stateScope().equals(scopeContext.playableStateScope()) - || currentRealm.gameInstanceId() != scopeContext.gameInstanceId() - || currentRealm.catalogRevision() != scopeContext.catalogRevision() - || currentRealm.pointerVersion() != scopeContext.pointerVersion()) { - throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); - } - return currentRealm; - } - - private RuntimeRealmTarget requireCurrentAdmissibleConnectScopeTarget( - BootstrapContext bootstrapContext, ConnectScopeContext scopeContext) { - RuntimeRealmTarget currentRealm = requireCurrentConnectScopeTarget(scopeContext); - RuntimeEntitlementsDto entitlements = - getTenantEntitlementsForRuntime(currentRealm.tenantId(), "bootstrap-characters"); - if (!entitlements.gameplayAvailable()) { - throw new AuthenticationException( - "TENANT_BILLING_BLOCKED", "Gameplay is not available for this tenant"); - } - - boolean publicProductionRealm = isPublicProductionRealm(currentRealm); - Optional maybeMembership = - accountTenantMembershipRepository.findByAccountIdAndTenantId( - bootstrapContext.accountId(), currentRealm.tenantId()); - if (maybeMembership.isPresent() - && "INACTIVE".equals(maybeMembership.orElseThrow().getLifecycleState()) - && publicProductionRealm) { - if (!entitlements.allowPublicJoin()) { - throw new AuthenticationException( - "PUBLIC_PRODUCTION_ADMISSION_DENIED", - "Public joining is not allowed for the selected game"); - } - throw new AuthenticationException("JOIN_REQUIRED", JOIN_REQUIRED_CHARACTERS_MESSAGE); - } - if (maybeMembership.isPresent() - && !maybeMembership.orElseThrow().isGameplayAdmissionAllowed()) { - throw new AuthenticationException( - "CONNECT_TOKEN_REJECTED", "Gameplay admission is not allowed for this account"); - } - if (maybeMembership.isEmpty()) { - if (!publicProductionRealm) { - throw new AuthenticationException( - "NON_PUBLIC_ENROLLMENT_REQUIRED", - "Existing game membership is required for this non-public realm"); - } - if (!entitlements.allowPublicJoin()) { - throw new AuthenticationException( - "PUBLIC_PRODUCTION_ADMISSION_DENIED", - "Public joining is not allowed for the selected game"); - } - throw new AuthenticationException("JOIN_REQUIRED", JOIN_REQUIRED_CHARACTERS_MESSAGE); - } - - if (!publicProductionRealm - && !hasRealmAccessGrant( - bootstrapContext.accountId(), - currentRealm.tenantId(), - currentRealm.worldSlug(), - currentRealm.realmSlug())) { - throw new AuthenticationException( - "ADMISSION_POINTER_UNAVAILABLE", - "Selected gameplay realm is no longer admissible; rerun realm discovery before retrying gameplay entry"); - } - return currentRealm; - } - private Optional findAccountForAuthentication(String usernameOrEmail) { Optional emailMatch = accountRepository.findByEmail(EmailCanonicalization.normalize(usernameOrEmail)); @@ -2250,12 +1796,6 @@ private long requireAccountStorageId(Account account, UUID accountUuid) { return account.getId(); } - private boolean hasRealmAccessGrant( - Long accountId, Long tenantId, String worldSlug, String realmSlug) { - return accountRealmAccessGrantRepository.existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( - accountId, tenantId, worldSlug, realmSlug); - } - private String mintToken(String subject, long expirationMs, Map claims) { return jwtUtil.generateToken(subject, expirationMs, claims); } @@ -2276,56 +1816,6 @@ private Map authenticationTokenClaims(String audience, Account a UUID.randomUUID().toString()); } - private Instant parseInstant(Object value) { - if (value == null) { - return null; - } - try { - return Instant.parse(value.toString()); - } catch (RuntimeException ex) { - return null; - } - } - - private String stableId(Object... components) { - try { - MessageDigest digest = MessageDigest.getInstance("SHA-256"); - for (Object component : components) { - digest.update(String.valueOf(component).getBytes(StandardCharsets.UTF_8)); - digest.update((byte) 0); - } - byte[] encoded = digest.digest(); - StringBuilder builder = new StringBuilder(encoded.length * 2); - for (byte value : encoded) { - builder.append(Character.forDigit((value >> 4) & 0xF, 16)); - builder.append(Character.forDigit(value & 0xF, 16)); - } - return builder.toString(); - } catch (NoSuchAlgorithmException ex) { - throw new IllegalStateException("Missing SHA-256 implementation", ex); - } - } - - private boolean isGameplayAvailableStatus(String status) { - if (status == null) { - return false; - } - return switch (status.trim().toLowerCase(java.util.Locale.ROOT)) { - case "active", "trialing", "past_due", "grace" -> true; - default -> false; - }; - } - - private boolean isPublicJoinAllowedStatus(String status) { - if (status == null) { - return false; - } - return switch (status.trim().toLowerCase(java.util.Locale.ROOT)) { - case "active", "trialing", "past_due" -> true; - default -> false; - }; - } - @Override @Transactional(readOnly = true) @Timed(value = "account.get_profile") @@ -2476,9 +1966,9 @@ public void deleteAccount(Long accountId) { "ACCOUNT_DELETE_JOIN_RECEIPT_RETAINED", "Account JOIN receipts require retention and deletion reconciliation"); } - List subscriptions = - subscriptionRepository.findByAccountId(accountId); - Optional blockingSubscription = + List subscriptions = + retainedSubscriptionEvidenceRepository.findHistoryByAccountId(accountId); + Optional blockingSubscription = subscriptions.stream().filter(this::isNonterminalSubscription).findFirst(); if (blockingSubscription.isPresent()) { throw new AccountLifecycleException( @@ -2491,18 +1981,17 @@ public void deleteAccount(Long accountId) { + "deletion reconciliation are implemented"); } - private boolean isNonterminalSubscription( - net.firedevops.firemud.accountservice.entity.Subscription subscription) { + private boolean isNonterminalSubscription(RetainedSubscriptionEvidence subscription) { String status = - subscription.getStatus() == null + subscription.status() == null ? "" - : subscription.getStatus().trim().toLowerCase(java.util.Locale.ROOT); + : subscription.status().trim().toLowerCase(java.util.Locale.ROOT); boolean terminalStatus = switch (status) { case "canceled", "cancelled", "ended", "expired" -> true; default -> false; }; - return !terminalStatus || subscription.getEndedAt() == null; + return !terminalStatus || subscription.endedAt() == null; } @Override @@ -3398,176 +2887,4 @@ public void afterCommit() { } private record BootstrapContext(long accountId, UUID accountUuid) {} - - private record JoinAuditPayload( - long accountId, - long tenantId, - String worldSlug, - String realmSlug, - long membershipVersion, - String requestId) {} - - private RuntimeRealmTarget readRuntimeRealmTarget( - net.firedevops.firemud.gamesession.v1.GameplayRealm realm) { - return buildRuntimeRealmTarget( - realm.getTenantId(), - realm.getRealmId(), - realm.getPlayableStateNamespaceId(), - realm.getGameInstanceId(), - realm.getCatalogRevision(), - realm.getPointerVersion(), - realm.getWorldSlug(), - realm.getRealmSlug(), - realm.getVisible(), - realm.getPublicProductionRealm(), - realm.getStateScope(), - realm.getCharacterCreationPolicy(), - realm.getRequiresCharacterSelection(), - realm.getDisplayName()); - } - - private RuntimeRealmTarget readRuntimeRealmTarget( - net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer realm) { - return buildRuntimeRealmTarget( - realm.getTenantId(), - realm.getRealmId(), - realm.getPlayableStateNamespaceId(), - realm.getGameInstanceId(), - realm.getCatalogRevision(), - realm.getPointerVersion(), - realm.getWorldSlug(), - realm.getRealmSlug(), - realm.getVisible(), - realm.getPublicProductionRealm(), - realm.getStateScope(), - realm.getCharacterCreationPolicy(), - realm.getRequiresCharacterSelection(), - realm.getRealmDisplayName()); - } - - private RuntimeRealmTarget buildRuntimeRealmTarget( - String tenantIdText, - String realmIdText, - String playableStateNamespaceId, - String gameInstanceIdText, - long catalogRevision, - long pointerVersion, - String worldSlug, - String realmSlug, - boolean visible, - boolean publicProductionRealm, - String stateScope, - String characterCreationPolicy, - boolean requiresCharacterSelection, - String displayName) { - long tenantId = requirePositiveLong(tenantIdText, "tenantId"); - UUID realmId = requireCanonicalRealmId(realmIdText); - long gameInstanceId = requirePositiveLong(gameInstanceIdText, "gameInstanceId"); - String canonicalPlayableStateNamespaceId = - requireCanonicalPlayableStateNamespaceId(playableStateNamespaceId); - if (catalogRevision <= 0) { - throw new IllegalArgumentException("catalogRevision must be positive"); - } - if (pointerVersion <= 0) { - throw new IllegalArgumentException("pointerVersion must be positive"); - } - if (!StringUtils.hasText(worldSlug)) { - throw new IllegalArgumentException("worldSlug is required"); - } - if (!StringUtils.hasText(realmSlug)) { - throw new IllegalArgumentException("realmSlug is required"); - } - if (!"SHARED".equals(stateScope) && !"ISOLATED".equals(stateScope)) { - throw new IllegalArgumentException("stateScope must be SHARED or ISOLATED"); - } - return new RuntimeRealmTarget( - tenantId, - realmId, - canonicalPlayableStateNamespaceId, - gameInstanceId, - worldSlug, - realmSlug, - pointerVersion, - catalogRevision, - visible, - publicProductionRealm, - stateScope, - characterCreationPolicy, - requiresCharacterSelection, - displayName); - } - - private PlayableStateScope toPlayableStateScope(RuntimeRealmTarget realm) { - if ("SHARED".equals(realm.stateScope())) { - return PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED; - } - if ("ISOLATED".equals(realm.stateScope())) { - return PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED; - } - throw new IllegalArgumentException("stateScope must be SHARED or ISOLATED"); - } - - private long requirePositiveLong(Object value, String field) { - return JwtClaims.requireLong(value, field, false); - } - - private UUID requireCanonicalRealmId(Object value) { - if (!(value instanceof String text) || text.isBlank()) { - throw new IllegalArgumentException("realmId must be a canonical UUID"); - } - try { - UUID realmId = UUID.fromString(text); - if (!realmId.toString().equals(text)) { - throw new IllegalArgumentException("realmId must be a canonical UUID"); - } - return realmId; - } catch (IllegalArgumentException ex) { - throw new IllegalArgumentException("realmId must be a canonical UUID", ex); - } - } - - private String requireCanonicalPlayableStateNamespaceId(String value) { - if (!StringUtils.hasText(value)) { - throw new IllegalArgumentException("playableStateNamespaceId is required"); - } - try { - UUID namespaceId = UUID.fromString(value); - if (!namespaceId.toString().equals(value)) { - throw new IllegalArgumentException("playableStateNamespaceId must be a canonical UUID"); - } - return value; - } catch (IllegalArgumentException ex) { - throw new IllegalArgumentException("playableStateNamespaceId must be a canonical UUID", ex); - } - } - - private record ConnectScopeContext( - long accountId, - long tenantId, - UUID realmId, - String worldSlug, - String realmSlug, - String playableStateNamespaceId, - String playableStateScope, - long gameInstanceId, - long catalogRevision, - long pointerVersion, - Instant evaluatedAt, - Instant connectScopeExpiresAt) {} - - private record RuntimeRealmTarget( - long tenantId, - UUID realmId, - String playableStateNamespaceId, - long gameInstanceId, - String worldSlug, - String realmSlug, - long pointerVersion, - long catalogRevision, - boolean visible, - boolean publicProductionRealm, - String stateScope, - String characterCreationPolicy, - boolean requiresCharacterSelection, - String displayName) {} } diff --git a/services/account-service/src/main/resources/db/migration/V1028__retain_non_authorizing_subscription_evidence.sql b/services/account-service/src/main/resources/db/migration/V1028__retain_non_authorizing_subscription_evidence.sql new file mode 100644 index 0000000000..c5d5ff151d --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1028__retain_non_authorizing_subscription_evidence.sql @@ -0,0 +1,44 @@ +-- Preview-only containment: retain the original heap, not a copy/backfill. No UUID +-- subscription, owner, provider mapping, winner or billing sequence is inferred. +/* [jooq ignore start] */ +LOCK TABLE subscription IN ACCESS EXCLUSIVE MODE; +/* [jooq ignore stop] */ + +ALTER TABLE subscription RENAME TO account_retained_subscription_evidence; +-- PostgreSQL-generated object names are absent from the jOOQ/H2 schema simulator. +/* [jooq ignore start] */ +ALTER TABLE account_retained_subscription_evidence + RENAME CONSTRAINT subscription_pkey TO account_retained_subscription_evidence_pkey; +ALTER TABLE account_retained_subscription_evidence + RENAME CONSTRAINT subscription_account_id_fkey TO account_retained_subscription_evidence_account_fk; +ALTER TABLE account_retained_subscription_evidence + RENAME CONSTRAINT subscription_entitlement_version_positive TO account_retained_subscription_evidence_version_positive; +ALTER TABLE account_retained_subscription_evidence + RENAME CONSTRAINT subscription_tenant_authority_generation_non_nil TO account_retained_subscription_evidence_generation_non_nil; +ALTER INDEX idx_subscription_account_id RENAME TO idx_account_retained_subscription_evidence_account; +ALTER INDEX idx_subscription_tenant_id RENAME TO idx_account_retained_subscription_evidence_tenant; +ALTER SEQUENCE subscription_id_seq RENAME TO account_retained_subscription_evidence_id_seq; +/* [jooq ignore stop] */ + +/* [jooq ignore start] */ +DROP TRIGGER subscription_authority_generation_advance ON account_retained_subscription_evidence; +-- RESTRICT is deliberate: an unexpected user of the obsolete function aborts +-- this whole transactional migration, including the rename, without row changes. +DROP FUNCTION advance_subscription_authority_generation() RESTRICT; + +CREATE FUNCTION account_retained_subscription_evidence_refuse_mutation() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'Retained subscription evidence is immutable and non-authorizing' + USING ERRCODE = '23514'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER account_retained_subscription_evidence_immutable + BEFORE INSERT OR UPDATE OR DELETE OR TRUNCATE ON account_retained_subscription_evidence + FOR EACH STATEMENT EXECUTE FUNCTION account_retained_subscription_evidence_refuse_mutation(); +ALTER TABLE account_retained_subscription_evidence + ENABLE ALWAYS TRIGGER account_retained_subscription_evidence_immutable; +/* [jooq ignore stop] */ + +COMMENT ON TABLE account_retained_subscription_evidence IS + 'Immutable numeric historical evidence only. Not subscription, billing-owner, provider or production entitlement authority.'; diff --git a/services/account-service/src/main/resources/db/migration/V1029__canonical_subscription_intent_and_provider_history.sql b/services/account-service/src/main/resources/db/migration/V1029__canonical_subscription_intent_and_provider_history.sql new file mode 100644 index 0000000000..c2418e52a7 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1029__canonical_subscription_intent_and_provider_history.sql @@ -0,0 +1,494 @@ +-- One new, initially empty UUID owner. Numeric evidence remains untouched in the V1028 archive. +-- No provider dispatch, verified lifecycle producer, transfer, entitlement or runtime grant. +CREATE TABLE subscription_create_operations ( + request_id UUID PRIMARY KEY CHECK (request_id <> '00000000-0000-0000-0000-000000000000'::UUID), + subscription_id UUID NOT NULL UNIQUE CHECK (subscription_id <> '00000000-0000-0000-0000-000000000000'::UUID), + tenant_id UUID NOT NULL REFERENCES account_tenant_billing_owners(tenant_uuid) ON DELETE RESTRICT, + account_uuid UUID NOT NULL REFERENCES accounts(account_uuid) ON DELETE RESTRICT, + owner_version BIGINT NOT NULL CHECK (owner_version > 0), + owner_generation UUID NOT NULL CHECK (owner_generation <> '00000000-0000-0000-0000-000000000000'::UUID), + actor_account_uuid UUID NOT NULL REFERENCES accounts(account_uuid) ON DELETE RESTRICT, + authorization_operation_id UUID NOT NULL CHECK (authorization_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID), + authorization_digest VARCHAR(71) NOT NULL CHECK (authorization_digest ~ '^sha256:[0-9a-f]{64}$'), + plan_code VARCHAR(255) NOT NULL CHECK (length(btrim(plan_code)) > 0 AND plan_code = btrim(plan_code)), + plan_quote_payload BYTEA NOT NULL CHECK (octet_length(plan_quote_payload) BETWEEN 1 AND 4096), + plan_quote_digest VARCHAR(71) NOT NULL CHECK (plan_quote_digest ~ '^sha256:[0-9a-f]{64}$') + CHECK (plan_quote_digest = 'sha256:' || encode(sha256(plan_quote_payload), 'hex')), + provider_price_id VARCHAR(255) NOT NULL CHECK (provider_price_id ~ '^price_[A-Za-z0-9]+$'), + provider_quantity BIGINT NOT NULL CHECK (provider_quantity > 0), + max_active_sessions BIGINT NOT NULL CHECK (max_active_sessions >= 0), + max_concurrent_game_instances BIGINT NOT NULL CHECK (max_concurrent_game_instances >= 0), + max_storage_bytes BIGINT NOT NULL CHECK (max_storage_bytes >= 0), + payment_instrument_id UUID NOT NULL REFERENCES payment_instrument(instrument_uuid) ON DELETE RESTRICT, + reserved_instrument_version BIGINT NOT NULL CHECK (reserved_instrument_version > 0), + customer_provisioning_request_id UUID NOT NULL REFERENCES billing_customer(customer_provisioning_request_id) ON DELETE RESTRICT, + provider_customer_id VARCHAR(255) NOT NULL, + subscription_provisioning_request_id UUID NOT NULL UNIQUE + CHECK (subscription_provisioning_request_id <> '00000000-0000-0000-0000-000000000000'::UUID), + cleanup_provider_identity UUID NOT NULL UNIQUE + CHECK (cleanup_provider_identity <> '00000000-0000-0000-0000-000000000000'::UUID), + request_payload BYTEA NOT NULL CHECK (octet_length(request_payload) BETWEEN 1 AND 1048576), + request_digest VARCHAR(71) NOT NULL CHECK (request_digest ~ '^sha256:[0-9a-f]{64}$') + CHECK (request_digest = 'sha256:' || encode(sha256(request_payload), 'hex')), + replaced_subscription_id UUID, + replaced_row_version BIGINT CHECK (replaced_row_version > 0), + -- The immutable creation result is these columns, not a later mutable lifecycle snapshot. + result_status VARCHAR(16) NOT NULL DEFAULT 'pending' CHECK (result_status = 'pending'), + result_row_version BIGINT NOT NULL DEFAULT 1 CHECK (result_row_version = 1), + created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + CHECK ((replaced_subscription_id IS NULL) = (replaced_row_version IS NULL)), + CHECK (request_id <> subscription_provisioning_request_id AND request_id <> cleanup_provider_identity + AND subscription_provisioning_request_id <> cleanup_provider_identity + AND customer_provisioning_request_id NOT IN (request_id, subscription_provisioning_request_id, cleanup_provider_identity)), + UNIQUE (request_id, subscription_id), + UNIQUE (request_id, plan_quote_digest), + UNIQUE (request_id, subscription_provisioning_request_id), + UNIQUE (request_id, cleanup_provider_identity), + UNIQUE (request_id, subscription_id, payment_instrument_id, reserved_instrument_version), + FOREIGN KEY (account_uuid, customer_provisioning_request_id, provider_customer_id) + REFERENCES billing_customer(account_uuid, customer_provisioning_request_id, provider_customer_id) ON DELETE RESTRICT +); + +CREATE TABLE subscription ( + subscription_id UUID PRIMARY KEY, + tenant_id UUID NOT NULL REFERENCES account_tenant_billing_owners(tenant_uuid) ON DELETE RESTRICT, + account_uuid UUID NOT NULL REFERENCES accounts(account_uuid) ON DELETE RESTRICT, + owner_version BIGINT NOT NULL CHECK (owner_version > 0), + owner_generation UUID NOT NULL, + plan_code VARCHAR(255) NOT NULL, + -- The exact current quote is retained by the immutable operation, not reconstructed from a + -- mutable plan catalog. This digest couples the current read to that original snapshot. + plan_quote_digest VARCHAR(71) NOT NULL, + payment_instrument_id UUID NOT NULL REFERENCES payment_instrument(instrument_uuid) ON DELETE RESTRICT, + reserved_instrument_version BIGINT NOT NULL CHECK (reserved_instrument_version > 0), + customer_provisioning_request_id UUID NOT NULL REFERENCES billing_customer(customer_provisioning_request_id) ON DELETE RESTRICT, + provider_customer_id VARCHAR(255) NOT NULL, + creation_request_id UUID NOT NULL UNIQUE, + row_version BIGINT NOT NULL CHECK (row_version > 0), + status VARCHAR(16) NOT NULL CHECK (status IN ('pending','provisioning','trialing','active','past_due','grace','suspended','canceled')), + provider_subscription_id VARCHAR(255) CHECK (provider_subscription_id ~ '^sub_[A-Za-z0-9]+$'), + terminal_resolution_id UUID, + superseded_at TIMESTAMPTZ, + superseded_by_request_id UUID UNIQUE, + created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + CHECK (status NOT IN ('trialing','active','past_due','grace','suspended') OR provider_subscription_id IS NOT NULL), + -- Effective hosting cutoff and provider retirement are separate: a scheduled end may close + -- hosting before a provider-terminal read permits retiring the instrument reservation. + CHECK (terminal_resolution_id IS NULL OR status = 'canceled'), + CHECK ((superseded_at IS NULL) = (superseded_by_request_id IS NULL)), + CHECK (superseded_at IS NULL OR status = 'canceled'), + UNIQUE (creation_request_id, subscription_id), + FOREIGN KEY (creation_request_id, subscription_id) + REFERENCES subscription_create_operations(request_id, subscription_id) DEFERRABLE INITIALLY DEFERRED, + FOREIGN KEY (creation_request_id, plan_quote_digest) + REFERENCES subscription_create_operations(request_id, plan_quote_digest) ON DELETE RESTRICT, + FOREIGN KEY (superseded_by_request_id) REFERENCES subscription_create_operations(request_id) DEFERRABLE INITIALLY DEFERRED +); +ALTER TABLE subscription_create_operations ADD CONSTRAINT subscription_create_current_pair_fk + FOREIGN KEY (request_id, subscription_id) REFERENCES subscription(creation_request_id, subscription_id) + DEFERRABLE INITIALLY DEFERRED; +ALTER TABLE subscription_create_operations ADD CONSTRAINT subscription_create_replaced_fk + FOREIGN KEY (replaced_subscription_id) REFERENCES subscription(subscription_id) ON DELETE RESTRICT; + +-- A shared key registry prevents even cross-role reuse between different subscription creates. +CREATE TABLE subscription_create_provider_identities ( + provider_identity UUID PRIMARY KEY, + request_id UUID NOT NULL REFERENCES subscription_create_operations(request_id) ON DELETE RESTRICT, + purpose VARCHAR(16) NOT NULL CHECK (purpose IN ('CREATE','CLEANUP')), + UNIQUE (request_id, purpose) +); + +CREATE TABLE subscription_instrument_reservations ( + request_id UUID PRIMARY KEY, + subscription_id UUID NOT NULL UNIQUE, + payment_instrument_id UUID NOT NULL, + instrument_version BIGINT NOT NULL CHECK (instrument_version > 0), + terminal_resolution_id UUID UNIQUE, + released_at TIMESTAMPTZ, + CHECK ((terminal_resolution_id IS NULL) = (released_at IS NULL)), + FOREIGN KEY (request_id, subscription_id, payment_instrument_id, instrument_version) + REFERENCES subscription_create_operations(request_id, subscription_id, payment_instrument_id, reserved_instrument_version) + ON DELETE RESTRICT, + UNIQUE (request_id, subscription_id) +); +CREATE INDEX idx_subscription_instrument_hold ON subscription_instrument_reservations(payment_instrument_id) + WHERE released_at IS NULL; + +-- An immutable local work intent, NOT a dispatched item or lifecycle-event authority bridge. +CREATE TABLE subscription_create_outbox ( + request_id UUID PRIMARY KEY, + subscription_id UUID NOT NULL UNIQUE, + work_kind VARCHAR(40) NOT NULL CHECK (work_kind = 'SUBSCRIPTION_PROVISIONING_INTENT'), + created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + FOREIGN KEY (request_id, subscription_id) REFERENCES subscription_create_operations(request_id, subscription_id) ON DELETE RESTRICT, + UNIQUE (request_id, subscription_id) +); +ALTER TABLE subscription_create_operations ADD CONSTRAINT subscription_create_reservation_pair_fk + FOREIGN KEY (request_id, subscription_id) REFERENCES subscription_instrument_reservations(request_id, subscription_id) + DEFERRABLE INITIALLY DEFERRED; +ALTER TABLE subscription_create_operations ADD CONSTRAINT subscription_create_outbox_pair_fk + FOREIGN KEY (request_id, subscription_id) REFERENCES subscription_create_outbox(request_id, subscription_id) + DEFERRABLE INITIALLY DEFERRED; + +CREATE TABLE subscription_provider_history ( + provider_subscription_id VARCHAR(255) PRIMARY KEY CHECK (provider_subscription_id ~ '^sub_[A-Za-z0-9]+$'), + subscription_id UUID NOT NULL REFERENCES subscription(subscription_id) ON DELETE RESTRICT, + operation_kind VARCHAR(32) NOT NULL CHECK (operation_kind = 'SUBSCRIPTION_PROVISIONING'), + request_id UUID NOT NULL, + provider_operation_id UUID NOT NULL, + -- Transfer roles/references require the genuine transfer owner, not an invented operation. + role VARCHAR(16) NOT NULL CHECK (role = 'canonical'), + effective_at TIMESTAMPTZ NOT NULL, + evidence_digest VARCHAR(71) NOT NULL CHECK (evidence_digest ~ '^sha256:[0-9a-f]{64}$'), + recorded_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + UNIQUE (provider_subscription_id, subscription_id), + UNIQUE (request_id), + FOREIGN KEY (request_id, subscription_id) REFERENCES subscription_create_operations(request_id, subscription_id) ON DELETE RESTRICT, + FOREIGN KEY (request_id, provider_operation_id) + REFERENCES subscription_create_operations(request_id, subscription_provisioning_request_id) ON DELETE RESTRICT +); +ALTER TABLE subscription ADD CONSTRAINT subscription_confirmed_provider_history_fk + FOREIGN KEY (provider_subscription_id, subscription_id) + REFERENCES subscription_provider_history(provider_subscription_id, subscription_id) DEFERRABLE INITIALLY DEFERRED; + +-- Separate immutable terminal evidence; inserting a history mapping cannot imply cancellation. +-- No public writer exists until provider reconciliation and local cleanup are genuinely composed. +CREATE TABLE subscription_provider_terminal_resolutions ( + resolution_id UUID PRIMARY KEY CHECK (resolution_id <> '00000000-0000-0000-0000-000000000000'::UUID), + request_id UUID NOT NULL UNIQUE, + subscription_id UUID NOT NULL UNIQUE, + cleanup_provider_identity UUID NOT NULL, + provider_subscription_id VARCHAR(255), + outcome VARCHAR(24) NOT NULL CHECK (outcome IN ('PROVIDER_ABSENT','CANCELED')), + effective_at TIMESTAMPTZ NOT NULL, + evidence_digest VARCHAR(71) NOT NULL CHECK (evidence_digest ~ '^sha256:[0-9a-f]{64}$'), + recorded_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + CHECK ((outcome = 'PROVIDER_ABSENT') = (provider_subscription_id IS NULL)), + UNIQUE (resolution_id, subscription_id), + FOREIGN KEY (request_id, subscription_id) REFERENCES subscription_create_operations(request_id, subscription_id) ON DELETE RESTRICT, + FOREIGN KEY (request_id, cleanup_provider_identity) + REFERENCES subscription_create_operations(request_id, cleanup_provider_identity) ON DELETE RESTRICT, + FOREIGN KEY (provider_subscription_id, subscription_id) + REFERENCES subscription_provider_history(provider_subscription_id, subscription_id) ON DELETE RESTRICT +); +ALTER TABLE subscription ADD CONSTRAINT subscription_terminal_resolution_fk + FOREIGN KEY (terminal_resolution_id, subscription_id) + REFERENCES subscription_provider_terminal_resolutions(resolution_id, subscription_id) DEFERRABLE INITIALLY DEFERRED; +ALTER TABLE subscription_instrument_reservations ADD CONSTRAINT subscription_reservation_resolution_fk + FOREIGN KEY (terminal_resolution_id, subscription_id) + REFERENCES subscription_provider_terminal_resolutions(resolution_id, subscription_id) DEFERRABLE INITIALLY DEFERRED; + +CREATE TABLE subscription_current_observations ( + subscription_id UUID NOT NULL REFERENCES subscription(subscription_id) ON DELETE RESTRICT, + row_version BIGINT NOT NULL CHECK (row_version > 0), + status VARCHAR(16) NOT NULL, + provider_subscription_id VARCHAR(255), + terminal_resolution_id UUID, + superseded_at TIMESTAMPTZ, + superseded_by_request_id UUID, + recorded_at TIMESTAMPTZ NOT NULL, + PRIMARY KEY (subscription_id, row_version) +); + +-- [jooq ignore start] +-- The canonical relation is new and empty. No old numeric row is a duplicate candidate/winner. +-- Fence this new owner while checking the exact index candidates, not another schema catalog. +LOCK TABLE subscription IN ACCESS EXCLUSIVE MODE; +DO $$ +BEGIN + IF EXISTS (SELECT tenant_id FROM subscription WHERE superseded_at IS NULL GROUP BY tenant_id HAVING count(*) > 1) + OR EXISTS (SELECT provider_subscription_id FROM subscription + WHERE superseded_at IS NULL AND provider_subscription_id IS NOT NULL + GROUP BY provider_subscription_id HAVING count(*) <> 1) THEN + RAISE EXCEPTION 'Canonical subscription candidates require explicit reconciliation'; + END IF; +END; +$$; +-- [jooq ignore stop] +CREATE UNIQUE INDEX uq_subscription_active_tenant ON subscription(tenant_id) WHERE superseded_at IS NULL; +CREATE UNIQUE INDEX uq_subscription_active_provider ON subscription(provider_subscription_id) + WHERE superseded_at IS NULL AND provider_subscription_id IS NOT NULL; + +-- [jooq ignore start] +CREATE FUNCTION account_subscription_no_mutation() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Canonical subscription evidence is retained and immutable' USING ERRCODE = '23514'; +END; +$$; + +CREATE FUNCTION account_subscription_create_source_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + wallet payment_instrument%ROWTYPE; + customer billing_customer%ROWTYPE; + owner account_tenant_billing_owners%ROWTYPE; + previous subscription%ROWTYPE; +BEGIN + -- Same lock order as V1027 repositories: Account -> customer -> instrument -> tenant owner. + PERFORM 1 FROM accounts WHERE account_uuid = NEW.account_uuid FOR UPDATE; + SELECT * INTO STRICT customer FROM billing_customer WHERE account_uuid = NEW.account_uuid FOR UPDATE; + SELECT * INTO STRICT wallet FROM payment_instrument WHERE instrument_uuid = NEW.payment_instrument_id FOR UPDATE; + SELECT * INTO STRICT owner FROM account_tenant_billing_owners WHERE tenant_uuid = NEW.tenant_id FOR UPDATE; + IF convert_from(NEW.plan_quote_payload, 'UTF8')::jsonb IS DISTINCT FROM jsonb_build_object( + 'schemaVersion', 'account-hosting-plan-quote/v1', 'planCode', NEW.plan_code, + 'providerPriceId', NEW.provider_price_id, 'providerQuantity', NEW.provider_quantity::text, + 'maxActiveSessions', NEW.max_active_sessions::text, + 'maxConcurrentGameInstances', NEW.max_concurrent_game_instances::text, + 'maxStorageBytes', NEW.max_storage_bytes::text) THEN + RAISE EXCEPTION 'Subscription hosting quote differs from its exact retained fields' USING ERRCODE = '23514'; + END IF; + IF (owner.owner_account_uuid, owner.owner_version, owner.owner_generation) + IS DISTINCT FROM (NEW.account_uuid, NEW.owner_version, NEW.owner_generation) + OR (wallet.account_uuid, wallet.row_version, wallet.customer_provisioning_request_id, wallet.provider_customer_id) + IS DISTINCT FROM (NEW.account_uuid, NEW.reserved_instrument_version, NEW.customer_provisioning_request_id, NEW.provider_customer_id) + OR wallet.state <> 'ATTACHABLE' OR customer.state <> 'CONFIRMED' + OR customer.provider_customer_id IS DISTINCT FROM NEW.provider_customer_id + OR customer.provider_idempotency_id IN (NEW.request_id, NEW.subscription_provisioning_request_id, NEW.cleanup_provider_identity) + OR convert_from(NEW.request_payload, 'UTF8')::jsonb IS DISTINCT FROM jsonb_build_object( + 'schemaVersion', 'account-subscription-create-request/v1', 'tenantId', NEW.tenant_id::text, + 'ownerAccountId', NEW.account_uuid::text, 'planCode', NEW.plan_code, + 'instrumentSelection', jsonb_build_object('kind', 'EXACT_SAVED_INSTRUMENT', 'paymentInstrumentId', NEW.payment_instrument_id::text)) THEN + RAISE EXCEPTION 'Subscription create owner, wallet or normalized request fence rejected' USING ERRCODE = '23514'; + END IF; + IF NEW.replaced_subscription_id IS NOT NULL THEN + SELECT * INTO STRICT previous FROM subscription WHERE subscription_id = NEW.replaced_subscription_id FOR UPDATE; + IF previous.tenant_id <> NEW.tenant_id OR previous.status <> 'canceled' + OR previous.terminal_resolution_id IS NULL + OR previous.row_version <> NEW.replaced_row_version + 1 + OR previous.superseded_by_request_id IS DISTINCT FROM NEW.request_id THEN + RAISE EXCEPTION 'Canceled subscription replacement fence rejected' USING ERRCODE = '23514'; + END IF; + ELSIF EXISTS (SELECT 1 FROM subscription WHERE tenant_id = NEW.tenant_id AND superseded_at IS NULL) THEN + RAISE EXCEPTION 'Tenant already has a current subscription' USING ERRCODE = '23514'; + END IF; + NEW.created_at := clock_timestamp(); + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_subscription_record_provider_identities() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + INSERT INTO subscription_create_provider_identities VALUES (NEW.subscription_provisioning_request_id, NEW.request_id, 'CREATE'); + INSERT INTO subscription_create_provider_identities VALUES (NEW.cleanup_provider_identity, NEW.request_id, 'CLEANUP'); + RETURN NEW; +END; +$$; +CREATE FUNCTION account_subscription_provider_identity_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF NOT EXISTS (SELECT 1 FROM subscription_create_operations WHERE request_id = NEW.request_id + AND ((NEW.purpose = 'CREATE' AND subscription_provisioning_request_id = NEW.provider_identity) + OR (NEW.purpose = 'CLEANUP' AND cleanup_provider_identity = NEW.provider_identity))) THEN + RAISE EXCEPTION 'Subscription provider identity differs from its typed operation' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_subscription_current_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + intent subscription_create_operations%ROWTYPE; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Canonical subscription cannot be deleted' USING ERRCODE = '23514'; + ELSIF TG_OP = 'INSERT' THEN + SELECT * INTO STRICT intent FROM subscription_create_operations WHERE request_id = NEW.creation_request_id; + IF (NEW.subscription_id, NEW.tenant_id, NEW.account_uuid, NEW.owner_version, NEW.owner_generation, + NEW.plan_code, NEW.plan_quote_digest, NEW.payment_instrument_id, NEW.reserved_instrument_version, + NEW.customer_provisioning_request_id, NEW.provider_customer_id) + IS DISTINCT FROM (intent.subscription_id, intent.tenant_id, intent.account_uuid, intent.owner_version, + intent.owner_generation, intent.plan_code, intent.plan_quote_digest, intent.payment_instrument_id, intent.reserved_instrument_version, + intent.customer_provisioning_request_id, intent.provider_customer_id) + OR NEW.row_version <> 1 OR NEW.status <> 'pending' OR NEW.provider_subscription_id IS NOT NULL + OR NEW.terminal_resolution_id IS NOT NULL OR NEW.superseded_at IS NOT NULL THEN + RAISE EXCEPTION 'Subscription must begin as its exact pending intent' USING ERRCODE = '23514'; + END IF; + NEW.created_at := intent.created_at; + NEW.updated_at := NEW.created_at; + ELSE + -- No generic plan/instrument/owner rebind. Future typed update/transfer owners must extend + -- this guard with their real operation and authority evidence, never a compatibility path. + IF (NEW.subscription_id, NEW.tenant_id, NEW.account_uuid, NEW.owner_version, NEW.owner_generation, + NEW.plan_code, NEW.plan_quote_digest, NEW.payment_instrument_id, NEW.reserved_instrument_version, + NEW.customer_provisioning_request_id, NEW.provider_customer_id, NEW.creation_request_id, NEW.created_at) + IS DISTINCT FROM (OLD.subscription_id, OLD.tenant_id, OLD.account_uuid, OLD.owner_version, OLD.owner_generation, + OLD.plan_code, OLD.plan_quote_digest, OLD.payment_instrument_id, OLD.reserved_instrument_version, + OLD.customer_provisioning_request_id, OLD.provider_customer_id, OLD.creation_request_id, OLD.created_at) + OR OLD.superseded_at IS NOT NULL OR NEW.row_version <> OLD.row_version + 1 + OR (OLD.provider_subscription_id IS NOT NULL AND NEW.provider_subscription_id IS DISTINCT FROM OLD.provider_subscription_id) + OR (OLD.terminal_resolution_id IS NOT NULL AND NEW.terminal_resolution_id IS DISTINCT FROM OLD.terminal_resolution_id) + OR (OLD.status = 'canceled' AND NEW.status <> 'canceled') THEN + RAISE EXCEPTION 'Subscription identity, terminal state or row-version fence rejected' USING ERRCODE = '23514'; + END IF; + IF NEW.superseded_at IS NOT NULL THEN + IF OLD.status <> 'canceled' OR OLD.terminal_resolution_id IS NULL OR NEW.status <> OLD.status + OR NEW.provider_subscription_id IS DISTINCT FROM OLD.provider_subscription_id + OR NEW.terminal_resolution_id IS DISTINCT FROM OLD.terminal_resolution_id THEN + RAISE EXCEPTION 'Only terminal canceled current subscriptions may be superseded' USING ERRCODE = '23514'; + END IF; + NEW.superseded_at := clock_timestamp(); + END IF; + NEW.updated_at := clock_timestamp(); + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_subscription_record_observation() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + INSERT INTO subscription_current_observations VALUES (NEW.subscription_id, NEW.row_version, NEW.status, + NEW.provider_subscription_id, NEW.terminal_resolution_id, NEW.superseded_at, NEW.superseded_by_request_id, NEW.updated_at); + RETURN NEW; +END; +$$; +CREATE FUNCTION account_subscription_observation_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE current_row subscription%ROWTYPE; +BEGIN + SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = NEW.subscription_id FOR UPDATE; + IF (NEW.row_version, NEW.status, NEW.provider_subscription_id, NEW.terminal_resolution_id, + NEW.superseded_at, NEW.superseded_by_request_id, NEW.recorded_at) IS DISTINCT FROM + (current_row.row_version, current_row.status, current_row.provider_subscription_id, current_row.terminal_resolution_id, + current_row.superseded_at, current_row.superseded_by_request_id, current_row.updated_at) THEN + RAISE EXCEPTION 'Subscription observation differs from its current owner' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_subscription_reservation_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'INSERT' THEN + IF NEW.terminal_resolution_id IS NOT NULL OR NEW.released_at IS NOT NULL THEN + RAISE EXCEPTION 'Subscription reservation must begin held' USING ERRCODE = '23514'; + END IF; + ELSIF TG_OP = 'DELETE' OR OLD.released_at IS NOT NULL + OR (NEW.request_id, NEW.subscription_id, NEW.payment_instrument_id, NEW.instrument_version) + IS DISTINCT FROM (OLD.request_id, OLD.subscription_id, OLD.payment_instrument_id, OLD.instrument_version) + OR NEW.terminal_resolution_id IS NULL OR NEW.released_at IS NULL THEN + RAISE EXCEPTION 'Subscription reservation identity or terminal release fence rejected' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_subscription_final_pair_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + current_row subscription%ROWTYPE; + hold subscription_instrument_reservations%ROWTYPE; + resolution subscription_provider_terminal_resolutions%ROWTYPE; + successor subscription_create_operations%ROWTYPE; + wallet payment_instrument%ROWTYPE; + owner account_tenant_billing_owners%ROWTYPE; +BEGIN + SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = NEW.subscription_id; + SELECT * INTO STRICT hold FROM subscription_instrument_reservations WHERE subscription_id = NEW.subscription_id; + IF current_row.row_version = 1 AND current_row.status = 'pending' THEN + SELECT * INTO STRICT wallet FROM payment_instrument WHERE instrument_uuid = current_row.payment_instrument_id; + SELECT * INTO STRICT owner FROM account_tenant_billing_owners WHERE tenant_uuid = current_row.tenant_id; + IF (owner.owner_account_uuid, owner.owner_version, owner.owner_generation) + IS DISTINCT FROM (current_row.account_uuid, current_row.owner_version, current_row.owner_generation) + OR (wallet.account_uuid, wallet.row_version, wallet.customer_provisioning_request_id, wallet.provider_customer_id, wallet.state) + IS DISTINCT FROM (current_row.account_uuid, current_row.reserved_instrument_version, + current_row.customer_provisioning_request_id, current_row.provider_customer_id, 'ATTACHABLE'::varchar) THEN + RAISE EXCEPTION 'Subscription commit owner/instrument fence rejected' USING ERRCODE = '23514'; + END IF; + END IF; + IF current_row.status = 'canceled' AND current_row.terminal_resolution_id IS NOT NULL THEN + SELECT * INTO STRICT resolution FROM subscription_provider_terminal_resolutions + WHERE resolution_id = current_row.terminal_resolution_id; + IF hold.terminal_resolution_id IS DISTINCT FROM current_row.terminal_resolution_id OR hold.released_at IS NULL + OR resolution.provider_subscription_id IS DISTINCT FROM current_row.provider_subscription_id THEN + RAISE EXCEPTION 'Subscription terminal result requires exact provider resolution and reservation release' USING ERRCODE = '23514'; + END IF; + ELSIF hold.released_at IS NOT NULL THEN + RAISE EXCEPTION 'Nonterminal subscription must retain its instrument reservation' USING ERRCODE = '23514'; + END IF; + IF current_row.superseded_at IS NOT NULL THEN + SELECT * INTO STRICT successor FROM subscription_create_operations WHERE request_id = current_row.superseded_by_request_id; + IF successor.replaced_subscription_id IS DISTINCT FROM current_row.subscription_id + OR successor.replaced_row_version <> current_row.row_version - 1 OR successor.tenant_id <> current_row.tenant_id THEN + RAISE EXCEPTION 'Subscription supersession requires the exact atomic replacement operation' USING ERRCODE = '23514'; + END IF; + END IF; + RETURN NULL; +END; +$$; +CREATE FUNCTION account_subscription_terminal_source_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE current_row subscription%ROWTYPE; +BEGIN + SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = NEW.subscription_id FOR UPDATE; + IF NEW.request_id IS DISTINCT FROM current_row.creation_request_id + OR (NEW.provider_subscription_id IS DISTINCT FROM current_row.provider_subscription_id + AND NOT (current_row.provider_subscription_id IS NULL AND NEW.provider_subscription_id IS NOT NULL + AND EXISTS (SELECT 1 FROM subscription_provider_history h + WHERE h.subscription_id = NEW.subscription_id AND h.provider_subscription_id = NEW.provider_subscription_id))) + OR (NEW.provider_subscription_id IS NULL AND EXISTS ( + SELECT 1 FROM subscription_provider_history WHERE subscription_id = NEW.subscription_id)) THEN + RAISE EXCEPTION 'Subscription terminal evidence differs from its exact provider mapping' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE FUNCTION account_subscription_provider_history_source_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE current_row subscription%ROWTYPE; +BEGIN + SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = NEW.subscription_id FOR UPDATE; + IF current_row.status = 'canceled' OR current_row.superseded_at IS NOT NULL + OR EXISTS (SELECT 1 FROM subscription_provider_terminal_resolutions WHERE subscription_id = NEW.subscription_id) THEN + RAISE EXCEPTION 'Terminal subscription cannot acquire a new provider mapping' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER subscription_create_source_guard BEFORE INSERT ON subscription_create_operations + FOR EACH ROW EXECUTE FUNCTION account_subscription_create_source_guard(); +CREATE TRIGGER subscription_create_provider_keys AFTER INSERT ON subscription_create_operations + FOR EACH ROW EXECUTE FUNCTION account_subscription_record_provider_identities(); +CREATE TRIGGER subscription_provider_key_guard BEFORE INSERT ON subscription_create_provider_identities + FOR EACH ROW EXECUTE FUNCTION account_subscription_provider_identity_guard(); +CREATE TRIGGER subscription_current_guard BEFORE INSERT OR UPDATE OR DELETE ON subscription + FOR EACH ROW EXECUTE FUNCTION account_subscription_current_guard(); +CREATE TRIGGER subscription_current_history AFTER INSERT OR UPDATE ON subscription + FOR EACH ROW EXECUTE FUNCTION account_subscription_record_observation(); +CREATE TRIGGER subscription_observation_guard BEFORE INSERT ON subscription_current_observations + FOR EACH ROW EXECUTE FUNCTION account_subscription_observation_guard(); +CREATE TRIGGER subscription_terminal_source_guard BEFORE INSERT ON subscription_provider_terminal_resolutions + FOR EACH ROW EXECUTE FUNCTION account_subscription_terminal_source_guard(); +CREATE TRIGGER subscription_provider_history_source_guard BEFORE INSERT ON subscription_provider_history + FOR EACH ROW EXECUTE FUNCTION account_subscription_provider_history_source_guard(); +CREATE TRIGGER subscription_reservation_guard BEFORE INSERT OR UPDATE OR DELETE ON subscription_instrument_reservations + FOR EACH ROW EXECUTE FUNCTION account_subscription_reservation_guard(); +CREATE CONSTRAINT TRIGGER subscription_final_pair_guard AFTER INSERT OR UPDATE ON subscription + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_subscription_final_pair_guard(); +CREATE CONSTRAINT TRIGGER subscription_reservation_final_pair_guard AFTER INSERT OR UPDATE ON subscription_instrument_reservations + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_subscription_final_pair_guard(); + +CREATE TRIGGER subscription_create_immutable BEFORE UPDATE OR DELETE ON subscription_create_operations + FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_create_no_truncate BEFORE TRUNCATE ON subscription_create_operations + FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_provider_keys_immutable BEFORE UPDATE OR DELETE ON subscription_create_provider_identities + FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_provider_keys_no_truncate BEFORE TRUNCATE ON subscription_create_provider_identities + FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_no_truncate BEFORE TRUNCATE ON subscription + FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_reservation_no_truncate BEFORE TRUNCATE ON subscription_instrument_reservations + FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_outbox_immutable BEFORE UPDATE OR DELETE ON subscription_create_outbox + FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_outbox_no_truncate BEFORE TRUNCATE ON subscription_create_outbox + FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_provider_history_immutable BEFORE UPDATE OR DELETE ON subscription_provider_history + FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_provider_history_no_truncate BEFORE TRUNCATE ON subscription_provider_history + FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_terminal_immutable BEFORE UPDATE OR DELETE ON subscription_provider_terminal_resolutions + FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_terminal_no_truncate BEFORE TRUNCATE ON subscription_provider_terminal_resolutions + FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_observation_immutable BEFORE UPDATE OR DELETE ON subscription_current_observations + FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_observation_no_truncate BEFORE TRUNCATE ON subscription_current_observations + FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V1030__hosting_subscription_provisioning_claims.sql b/services/account-service/src/main/resources/db/migration/V1030__hosting_subscription_provisioning_claims.sql new file mode 100644 index 0000000000..20fd82966c --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1030__hosting_subscription_provisioning_claims.sql @@ -0,0 +1,561 @@ +-- Local durable provisioning ownership only. No runtime reader, provider dispatch or entitlement +-- receipt is enabled by these rows. Failure never proves provider absence or releases a hold. +CREATE TABLE subscription_provisioning_work ( + request_id UUID PRIMARY KEY, + subscription_id UUID NOT NULL UNIQUE, + phase VARCHAR(48) NOT NULL CHECK (phase IN ('RECONCILING','CLAIMED','CONFIRMED','BILLING_RECONCILIATION_TERMINAL_FAILURE')), + row_version BIGINT NOT NULL CHECK (row_version > 0), + attempt_count INTEGER NOT NULL CHECK (attempt_count >= 0), + max_attempts INTEGER NOT NULL CHECK (max_attempts > 0), + max_stalled_attempts INTEGER NOT NULL CHECK (max_stalled_attempts > 0), + lease_millis BIGINT NOT NULL CHECK (lease_millis > 0), + backoff_millis BIGINT NOT NULL CHECK (backoff_millis > 0), + deadline_at TIMESTAMPTZ NOT NULL, + retry_at TIMESTAMPTZ NOT NULL, + last_attempt_id UUID, + subscription_row_version BIGINT CHECK (subscription_row_version > 1), + lease_expires_at TIMESTAMPTZ, + failure_reason VARCHAR(64), + terminal_at TIMESTAMPTZ, + CHECK ((attempt_count = 0) = (last_attempt_id IS NULL)), + CHECK ((last_attempt_id IS NULL) = (subscription_row_version IS NULL)), + CHECK ((last_attempt_id IS NULL) = (lease_expires_at IS NULL)), + CHECK (phase <> 'CLAIMED' OR last_attempt_id IS NOT NULL), + CHECK ((phase = 'BILLING_RECONCILIATION_TERMINAL_FAILURE') = (terminal_at IS NOT NULL)), + CHECK (phase <> 'BILLING_RECONCILIATION_TERMINAL_FAILURE' OR failure_reason IS NOT NULL), + FOREIGN KEY (request_id, subscription_id) REFERENCES subscription_create_outbox(request_id, subscription_id) ON DELETE RESTRICT, + UNIQUE (request_id, subscription_id) +); + +CREATE TABLE subscription_provisioning_attempts ( + attempt_id UUID PRIMARY KEY CHECK (attempt_id <> '00000000-0000-0000-0000-000000000000'::UUID), + request_id UUID NOT NULL, + subscription_id UUID NOT NULL, + attempt_number INTEGER NOT NULL CHECK (attempt_number > 0), + expected_row_version BIGINT NOT NULL CHECK (expected_row_version > 0), + claimed_row_version BIGINT NOT NULL CHECK (claimed_row_version = expected_row_version + 1), + claimed_at TIMESTAMPTZ NOT NULL, + expires_at TIMESTAMPTZ NOT NULL CHECK (expires_at > claimed_at), + FOREIGN KEY (request_id, subscription_id) REFERENCES subscription_provisioning_work(request_id, subscription_id) ON DELETE RESTRICT, + UNIQUE (request_id, attempt_number), + UNIQUE (attempt_id, request_id, subscription_id, claimed_row_version) +); +ALTER TABLE subscription_provisioning_work ADD CONSTRAINT subscription_provisioning_last_attempt_fk + FOREIGN KEY (last_attempt_id, request_id, subscription_id, subscription_row_version) + REFERENCES subscription_provisioning_attempts(attempt_id, request_id, subscription_id, claimed_row_version) + DEFERRABLE INITIALLY DEFERRED; + +CREATE TABLE subscription_provisioning_operator_outbox ( + request_id UUID PRIMARY KEY, + subscription_id UUID NOT NULL UNIQUE, + reason VARCHAR(64) NOT NULL CHECK (reason IN ('ABSOLUTE_DEADLINE','ATTEMPT_BUDGET','STALLED_WITHOUT_COMMITTED_PROGRESS')), + recorded_at TIMESTAMPTZ NOT NULL, + FOREIGN KEY (request_id, subscription_id) REFERENCES subscription_provisioning_work(request_id, subscription_id) ON DELETE RESTRICT +); + +-- [jooq ignore start] +CREATE FUNCTION account_subscription_provisioning_work_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Provisioning work is retained' USING ERRCODE = '23514'; + ELSIF TG_OP = 'INSERT' THEN + IF NEW.phase <> 'RECONCILING' OR NEW.attempt_count <> 0 OR NEW.row_version <> 1 + OR NEW.failure_reason IS NOT NULL OR NEW.terminal_at IS NOT NULL THEN + RAISE EXCEPTION 'Provisioning work must start unclaimed' USING ERRCODE = '23514'; + END IF; + ELSE + IF OLD.phase IN ('CONFIRMED','BILLING_RECONCILIATION_TERMINAL_FAILURE') + OR (NEW.request_id, NEW.subscription_id, NEW.max_attempts, NEW.max_stalled_attempts, + NEW.lease_millis, NEW.backoff_millis, NEW.deadline_at) + IS DISTINCT FROM (OLD.request_id, OLD.subscription_id, OLD.max_attempts, OLD.max_stalled_attempts, + OLD.lease_millis, OLD.backoff_millis, OLD.deadline_at) + OR NEW.row_version <> OLD.row_version + 1 THEN + RAISE EXCEPTION 'Provisioning identity, limits or terminal fence rejected' USING ERRCODE = '23514'; + END IF; + IF NEW.phase = 'CLAIMED' THEN + IF NEW.attempt_count <> OLD.attempt_count + 1 OR NEW.last_attempt_id IS NOT DISTINCT FROM OLD.last_attempt_id + OR NEW.attempt_count > NEW.max_attempts OR NEW.attempt_count > NEW.max_stalled_attempts THEN + RAISE EXCEPTION 'Provisioning claim count or attempt fence rejected' USING ERRCODE = '23514'; + END IF; + ELSIF (NEW.attempt_count, NEW.last_attempt_id, NEW.subscription_row_version, NEW.lease_expires_at) + IS DISTINCT FROM (OLD.attempt_count, OLD.last_attempt_id, OLD.subscription_row_version, OLD.lease_expires_at) THEN + RAISE EXCEPTION 'Provisioning settlement cannot replace its attempt' USING ERRCODE = '23514'; + END IF; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_subscription_provisioning_consistency() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + work subscription_provisioning_work%ROWTYPE; + attempt subscription_provisioning_attempts%ROWTYPE; + current_row subscription%ROWTYPE; + notice subscription_provisioning_operator_outbox%ROWTYPE; +BEGIN + SELECT * INTO STRICT work FROM subscription_provisioning_work WHERE request_id = NEW.request_id; + SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = work.subscription_id; + IF work.last_attempt_id IS NOT NULL THEN + SELECT * INTO STRICT attempt FROM subscription_provisioning_attempts WHERE attempt_id = work.last_attempt_id; + IF (attempt.request_id, attempt.subscription_id, attempt.attempt_number, attempt.claimed_row_version, attempt.expires_at) + IS DISTINCT FROM (work.request_id, work.subscription_id, work.attempt_count, work.subscription_row_version, work.lease_expires_at) + OR attempt.expires_at > work.deadline_at + OR (work.phase <> 'CONFIRMED' AND (current_row.status <> 'provisioning' OR current_row.row_version < attempt.claimed_row_version + OR current_row.superseded_at IS NOT NULL)) THEN + RAISE EXCEPTION 'Provisioning attempt lacks its exact current CAS' USING ERRCODE = '23514'; + END IF; + END IF; + IF work.phase = 'BILLING_RECONCILIATION_TERMINAL_FAILURE' THEN + SELECT * INTO STRICT notice FROM subscription_provisioning_operator_outbox WHERE request_id = work.request_id; + IF (notice.subscription_id, notice.reason, notice.recorded_at) + IS DISTINCT FROM (work.subscription_id, work.failure_reason, work.terminal_at) THEN + RAISE EXCEPTION 'Provisioning failure lacks its exact operator work item' USING ERRCODE = '23514'; + END IF; + ELSIF EXISTS (SELECT 1 FROM subscription_provisioning_operator_outbox WHERE request_id = work.request_id) THEN + RAISE EXCEPTION 'Operator resolution work requires terminal reconciliation failure' USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; + +CREATE FUNCTION account_subscription_provisioning_attempt_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + work subscription_provisioning_work%ROWTYPE; + current_row subscription%ROWTYPE; +BEGIN + SELECT * INTO STRICT work FROM subscription_provisioning_work WHERE request_id = NEW.request_id FOR UPDATE; + SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = NEW.subscription_id; + IF work.phase = 'BILLING_RECONCILIATION_TERMINAL_FAILURE' + OR work.subscription_id <> NEW.subscription_id OR current_row.status <> 'provisioning' + OR current_row.provider_subscription_id IS NOT NULL OR current_row.superseded_at IS NOT NULL + OR current_row.row_version <> NEW.claimed_row_version + OR NEW.attempt_number <> work.attempt_count + 1 + OR NEW.attempt_number > work.max_attempts OR NEW.attempt_number > work.max_stalled_attempts + OR NEW.expected_row_version <> coalesce(work.subscription_row_version, 1) + OR NEW.claimed_at < current_row.created_at OR NEW.claimed_at < work.retry_at + OR NEW.claimed_at >= work.deadline_at OR NEW.expires_at > work.deadline_at + OR (work.phase = 'CLAIMED' AND NEW.claimed_at < work.lease_expires_at) + OR extract(epoch FROM (NEW.expires_at - NEW.claimed_at)) * 1000 > work.lease_millis THEN + RAISE EXCEPTION 'Provisioning attempt lacks its exact work and current-row fence' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER subscription_provisioning_work_guard BEFORE INSERT OR UPDATE OR DELETE ON subscription_provisioning_work + FOR EACH ROW EXECUTE FUNCTION account_subscription_provisioning_work_guard(); +CREATE TRIGGER subscription_provisioning_attempt_guard BEFORE INSERT ON subscription_provisioning_attempts + FOR EACH ROW EXECUTE FUNCTION account_subscription_provisioning_attempt_guard(); +CREATE CONSTRAINT TRIGGER subscription_provisioning_work_consistency AFTER INSERT OR UPDATE ON subscription_provisioning_work + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_subscription_provisioning_consistency(); +CREATE CONSTRAINT TRIGGER subscription_provisioning_attempt_consistency AFTER INSERT ON subscription_provisioning_attempts + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_subscription_provisioning_consistency(); +CREATE CONSTRAINT TRIGGER subscription_provisioning_notice_consistency AFTER INSERT ON subscription_provisioning_operator_outbox + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_subscription_provisioning_consistency(); +CREATE TRIGGER subscription_provisioning_work_no_truncate BEFORE TRUNCATE ON subscription_provisioning_work + FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_provisioning_attempt_immutable BEFORE UPDATE OR DELETE ON subscription_provisioning_attempts + FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_provisioning_attempt_no_truncate BEFORE TRUNCATE ON subscription_provisioning_attempts + FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_provisioning_notice_immutable BEFORE UPDATE OR DELETE ON subscription_provisioning_operator_outbox + FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_provisioning_notice_no_truncate BEFORE TRUNCATE ON subscription_provisioning_operator_outbox + FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); +-- [jooq ignore stop] + +-- Provider reads are outside SQL. One durable, row-version-bound reconciliation operation fences +-- currentness before the SDK read starts. It is not a provider mutation or a reused create command. +CREATE TABLE subscription_lifecycle_operations ( + request_id UUID PRIMARY KEY CHECK (request_id <> '00000000-0000-0000-0000-000000000000'::UUID), + creation_request_id UUID NOT NULL, + subscription_id UUID NOT NULL, + tenant_id UUID NOT NULL, + expected_row_version BIGINT NOT NULL CHECK (expected_row_version > 0), + reserved_row_version BIGINT NOT NULL CHECK (reserved_row_version = expected_row_version + 1), + provider_subscription_id VARCHAR(255) NOT NULL CHECK (provider_subscription_id ~ '^sub_[A-Za-z0-9]+$'), + provisioning_attempt_id UUID REFERENCES subscription_provisioning_attempts(attempt_id) ON DELETE RESTRICT, + request_payload BYTEA NOT NULL, + request_digest VARCHAR(71) NOT NULL CHECK (request_digest = 'sha256:' || encode(sha256(request_payload), 'hex')), + state VARCHAR(48) NOT NULL CHECK (state IN ('PENDING','COMMITTED','BILLING_RECONCILIATION_TERMINAL_FAILURE')), + row_version BIGINT NOT NULL CHECK (row_version > 0), + attempt_count INTEGER NOT NULL DEFAULT 0 CHECK (attempt_count >= 0), + stalled_count INTEGER NOT NULL DEFAULT 0 CHECK (stalled_count >= 0), + max_attempts INTEGER NOT NULL CHECK (max_attempts > 0), + max_stalled_attempts INTEGER NOT NULL CHECK (max_stalled_attempts > 0), + lease_millis BIGINT NOT NULL CHECK (lease_millis > 0), + backoff_millis BIGINT NOT NULL CHECK (backoff_millis > 0), + observation_age_millis BIGINT NOT NULL CHECK (observation_age_millis > 0), + warning_millis BIGINT NOT NULL CHECK (warning_millis > 0), + grace_millis BIGINT NOT NULL CHECK (grace_millis > 0), + deadline_at TIMESTAMPTZ NOT NULL, + retry_at TIMESTAMPTZ NOT NULL, + last_attempt_id UUID, + last_facts_digest VARCHAR(71), + failure_reason VARCHAR(96), + created_at TIMESTAMPTZ NOT NULL, + created_transaction_id BIGINT NOT NULL DEFAULT txid_current(), + FOREIGN KEY (creation_request_id, subscription_id) REFERENCES subscription_create_operations(request_id, subscription_id) ON DELETE RESTRICT, + UNIQUE (request_id, subscription_id), + UNIQUE (request_id, tenant_id), + CHECK (octet_length(request_payload) BETWEEN 1 AND 32768) +); +CREATE UNIQUE INDEX subscription_lifecycle_one_inflight ON subscription_lifecycle_operations(subscription_id) + WHERE state IN ('PENDING','BILLING_RECONCILIATION_TERMINAL_FAILURE'); + +CREATE TABLE subscription_lifecycle_attempts ( + attempt_id UUID PRIMARY KEY, + request_id UUID NOT NULL REFERENCES subscription_lifecycle_operations(request_id) ON DELETE RESTRICT, + attempt_number INTEGER NOT NULL CHECK (attempt_number > 0), + started_at TIMESTAMPTZ NOT NULL, + expires_at TIMESTAMPTZ NOT NULL CHECK (expires_at > started_at), + UNIQUE (request_id, attempt_number), + UNIQUE (request_id, attempt_id) +); +ALTER TABLE subscription_lifecycle_operations ADD CONSTRAINT subscription_lifecycle_last_attempt_fk + FOREIGN KEY (request_id, last_attempt_id) REFERENCES subscription_lifecycle_attempts(request_id, attempt_id) + DEFERRABLE INITIALLY DEFERRED; + +CREATE TABLE subscription_lifecycle_observations ( + attempt_id UUID PRIMARY KEY, + request_id UUID NOT NULL, + payload BYTEA NOT NULL CHECK (octet_length(payload) BETWEEN 1 AND 32768), + evidence_digest VARCHAR(71) NOT NULL CHECK (evidence_digest = 'sha256:' || encode(sha256(payload), 'hex')), + facts_digest VARCHAR(71) NOT NULL CHECK (facts_digest ~ '^sha256:[0-9a-f]{64}$'), + raw_status VARCHAR(32), + period_start TIMESTAMPTZ, + period_end TIMESTAMPTZ, + read_started_at TIMESTAMPTZ NOT NULL, + observed_at TIMESTAMPTZ NOT NULL, + mapping_reason VARCHAR(64) NOT NULL, + recorded_transaction_id BIGINT NOT NULL DEFAULT txid_current(), + FOREIGN KEY (request_id, attempt_id) REFERENCES subscription_lifecycle_attempts(request_id, attempt_id) ON DELETE RESTRICT, + UNIQUE (request_id, attempt_id, evidence_digest) +); + +CREATE TABLE subscription_lifecycle_receipts ( + request_id UUID PRIMARY KEY, + subscription_id UUID NOT NULL, + tenant_id UUID NOT NULL, + request_digest VARCHAR(71) NOT NULL, + subscription_row_version BIGINT NOT NULL CHECK (subscription_row_version > 0), + status VARCHAR(16) NOT NULL CHECK (status IN ('trialing','active','past_due','grace','suspended','canceled')), + plan_quote_digest VARCHAR(71) NOT NULL, + provider_subscription_id VARCHAR(255) NOT NULL, + attempt_id UUID NOT NULL, + observation_digest VARCHAR(71) NOT NULL, + receipt_payload BYTEA NOT NULL CHECK (octet_length(receipt_payload) BETWEEN 1 AND 32768), + receipt_digest VARCHAR(71) NOT NULL CHECK (receipt_digest = 'sha256:' || encode(sha256(receipt_payload), 'hex')), + valid_until TIMESTAMPTZ NOT NULL, + cutoff_at TIMESTAMPTZ, + past_due_since TIMESTAMPTZ, + warning_millis BIGINT NOT NULL CHECK (warning_millis > 0), + grace_millis BIGINT NOT NULL CHECK (grace_millis > 0), + entitlement_version BIGINT NOT NULL CHECK (entitlement_version > 0), + billing_sequence BIGINT NOT NULL CHECK (billing_sequence > 0), + billing_event_id UUID NOT NULL, + billing_event_digest VARCHAR(71) NOT NULL, + authority_generation BIGINT NOT NULL CHECK (authority_generation > 1), + authority_source_version BIGINT NOT NULL CHECK (authority_source_version > 1), + authority_sequence BIGINT NOT NULL CHECK (authority_sequence > 0), + authority_event_id VARCHAR(512) NOT NULL, + authority_event_digest VARCHAR(71) NOT NULL, + committed_at TIMESTAMPTZ NOT NULL, + committed_transaction_id BIGINT NOT NULL DEFAULT txid_current(), + FOREIGN KEY (request_id, subscription_id) REFERENCES subscription_lifecycle_operations(request_id, subscription_id) ON DELETE RESTRICT, + FOREIGN KEY (request_id, attempt_id, observation_digest) REFERENCES subscription_lifecycle_observations(request_id, attempt_id, evidence_digest) ON DELETE RESTRICT, + FOREIGN KEY (tenant_id, billing_sequence, billing_event_id, billing_event_digest) + REFERENCES account_tenant_entitlement_outbox_events(tenant_uuid, tenant_billing_sequence, event_id, event_digest) ON DELETE RESTRICT, + UNIQUE (request_id, subscription_id), + UNIQUE (subscription_id, subscription_row_version) +); +CREATE TABLE subscription_lifecycle_operator_outbox ( + request_id UUID PRIMARY KEY REFERENCES subscription_lifecycle_operations(request_id) ON DELETE RESTRICT, + reason VARCHAR(96) NOT NULL, + recorded_at TIMESTAMPTZ NOT NULL +); +ALTER TABLE subscription ADD COLUMN lifecycle_inflight_request_id UUID, + ADD COLUMN current_receipt_request_id UUID; +ALTER TABLE subscription ADD CONSTRAINT subscription_lifecycle_inflight_fk + FOREIGN KEY (lifecycle_inflight_request_id, subscription_id) REFERENCES subscription_lifecycle_operations(request_id, subscription_id) + DEFERRABLE INITIALLY DEFERRED; +ALTER TABLE subscription ADD CONSTRAINT subscription_current_receipt_fk + FOREIGN KEY (current_receipt_request_id, subscription_id) REFERENCES subscription_lifecycle_receipts(request_id, subscription_id) + DEFERRABLE INITIALLY DEFERRED; + +-- [jooq ignore start] +CREATE FUNCTION account_subscription_lifecycle_current_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'INSERT' THEN + IF NEW.lifecycle_inflight_request_id IS NOT NULL OR NEW.current_receipt_request_id IS NOT NULL THEN + RAISE EXCEPTION 'Subscription cannot begin with lifecycle authority' USING ERRCODE = '23514'; + END IF; + ELSIF OLD.lifecycle_inflight_request_id IS NOT NULL THEN + IF NEW.lifecycle_inflight_request_id IS NULL THEN + IF NEW.current_receipt_request_id IS DISTINCT FROM OLD.lifecycle_inflight_request_id THEN + RAISE EXCEPTION 'Lifecycle fence may clear only into its exact receipt' USING ERRCODE = '23514'; + END IF; + ELSIF NEW.lifecycle_inflight_request_id IS DISTINCT FROM OLD.lifecycle_inflight_request_id + OR NEW.current_receipt_request_id IS DISTINCT FROM OLD.current_receipt_request_id THEN + RAISE EXCEPTION 'In-flight lifecycle ownership cannot be replaced' USING ERRCODE = '23514'; + END IF; + ELSE + IF NEW.current_receipt_request_id IS DISTINCT FROM OLD.current_receipt_request_id THEN + RAISE EXCEPTION 'Committed current receipt cannot be detached or replaced without a lifecycle fence' USING ERRCODE = '23514'; + END IF; + IF NEW.lifecycle_inflight_request_id IS NOT NULL + AND (NEW.status, NEW.provider_subscription_id, NEW.terminal_resolution_id) + IS DISTINCT FROM (OLD.status, OLD.provider_subscription_id, OLD.terminal_resolution_id) THEN + RAISE EXCEPTION 'Lifecycle preparation cannot pre-commit provider state' USING ERRCODE = '23514'; + END IF; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER subscription_lifecycle_current_guard BEFORE INSERT OR UPDATE ON subscription + FOR EACH ROW EXECUTE FUNCTION account_subscription_lifecycle_current_guard(); + +CREATE FUNCTION account_subscription_lifecycle_operation_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Lifecycle operation is retained' USING ERRCODE = '23514'; + ELSIF TG_OP = 'INSERT' THEN + IF NEW.state <> 'PENDING' OR NEW.row_version <> 1 OR NEW.attempt_count <> 0 OR NEW.last_attempt_id IS NOT NULL THEN + RAISE EXCEPTION 'Lifecycle operation must start pending' USING ERRCODE = '23514'; + END IF; + NEW.created_transaction_id := txid_current(); + ELSE + IF OLD.state <> 'PENDING' OR NEW.row_version <> OLD.row_version + 1 + OR (NEW.request_id, NEW.creation_request_id, NEW.subscription_id, NEW.tenant_id, NEW.expected_row_version, + NEW.reserved_row_version, NEW.provider_subscription_id, NEW.provisioning_attempt_id, NEW.request_payload, + NEW.request_digest, NEW.max_attempts, NEW.max_stalled_attempts, NEW.lease_millis, NEW.backoff_millis, + NEW.observation_age_millis, NEW.warning_millis, NEW.grace_millis, NEW.deadline_at, NEW.created_at, NEW.created_transaction_id) + IS DISTINCT FROM (OLD.request_id, OLD.creation_request_id, OLD.subscription_id, OLD.tenant_id, OLD.expected_row_version, + OLD.reserved_row_version, OLD.provider_subscription_id, OLD.provisioning_attempt_id, OLD.request_payload, + OLD.request_digest, OLD.max_attempts, OLD.max_stalled_attempts, OLD.lease_millis, OLD.backoff_millis, + OLD.observation_age_millis, OLD.warning_millis, OLD.grace_millis, OLD.deadline_at, OLD.created_at, OLD.created_transaction_id) + OR NEW.attempt_count NOT BETWEEN OLD.attempt_count AND OLD.attempt_count + 1 THEN + RAISE EXCEPTION 'Lifecycle immutable identity or transition CAS rejected' USING ERRCODE = '23514'; + END IF; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_subscription_lifecycle_observation_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE attempt subscription_lifecycle_attempts%ROWTYPE; operation subscription_lifecycle_operations%ROWTYPE; +BEGIN + SELECT * INTO STRICT attempt FROM subscription_lifecycle_attempts WHERE attempt_id = NEW.attempt_id; + SELECT * INTO STRICT operation FROM subscription_lifecycle_operations WHERE request_id = NEW.request_id; + IF operation.state <> 'PENDING' OR operation.last_attempt_id IS DISTINCT FROM NEW.attempt_id + OR NEW.read_started_at < attempt.started_at OR NEW.observed_at < NEW.read_started_at + OR NEW.observed_at >= attempt.expires_at THEN + RAISE EXCEPTION 'SDK observation is not from the exact live read attempt' USING ERRCODE = '23514'; + END IF; + NEW.recorded_transaction_id := txid_current(); + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_subscription_lifecycle_receipt_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE operation subscription_lifecycle_operations%ROWTYPE; observation subscription_lifecycle_observations%ROWTYPE; + current_row subscription%ROWTYPE; creation subscription_create_operations%ROWTYPE; payload JSONB; +BEGIN + SELECT * INTO STRICT operation FROM subscription_lifecycle_operations WHERE request_id = NEW.request_id; + SELECT * INTO STRICT observation FROM subscription_lifecycle_observations WHERE attempt_id = NEW.attempt_id; + SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = NEW.subscription_id; + SELECT * INTO STRICT creation FROM subscription_create_operations WHERE request_id = operation.creation_request_id; + payload := convert_from(NEW.receipt_payload, 'UTF8')::jsonb; + IF operation.state <> 'PENDING' OR current_row.lifecycle_inflight_request_id IS DISTINCT FROM NEW.request_id + OR current_row.row_version <> operation.reserved_row_version + OR NEW.subscription_row_version <> current_row.row_version + 1 + OR NEW.request_digest IS DISTINCT FROM operation.request_digest OR NEW.tenant_id <> operation.tenant_id + OR NEW.provider_subscription_id <> operation.provider_subscription_id + OR NEW.plan_quote_digest <> creation.plan_quote_digest + OR observation.recorded_transaction_id <> txid_current() + OR payload->>'requestId' IS DISTINCT FROM NEW.request_id::text + OR payload->>'subscriptionId' IS DISTINCT FROM NEW.subscription_id::text + OR payload->>'tenantId' IS DISTINCT FROM NEW.tenant_id::text + OR payload->>'subscriptionRowVersion' IS DISTINCT FROM NEW.subscription_row_version::text + OR payload->>'subscriptionStatus' IS DISTINCT FROM NEW.status + OR payload->>'planQuoteDigest' IS DISTINCT FROM NEW.plan_quote_digest + OR payload->>'planQuote' IS DISTINCT FROM convert_from(creation.plan_quote_payload, 'UTF8') + OR payload->>'billingOwnerAccountId' IS DISTINCT FROM creation.account_uuid::text + OR payload->>'billingOwnerVersion' IS DISTINCT FROM creation.owner_version::text + OR payload->>'billingOwnerGeneration' IS DISTINCT FROM creation.owner_generation::text + OR payload->>'paymentInstrumentId' IS DISTINCT FROM creation.payment_instrument_id::text + OR payload->>'reservedInstrumentVersion' IS DISTINCT FROM creation.reserved_instrument_version::text + OR payload->>'customerProvisioningRequestId' IS DISTINCT FROM creation.customer_provisioning_request_id::text + OR payload->>'providerCustomerId' IS DISTINCT FROM creation.provider_customer_id + OR payload->>'entitlementVersion' IS DISTINCT FROM NEW.entitlement_version::text + OR payload->>'observationDigest' IS DISTINCT FROM NEW.observation_digest + OR payload->>'providerSubscriptionId' IS DISTINCT FROM NEW.provider_subscription_id THEN + RAISE EXCEPTION 'Hosting receipt lacks its exact same-transaction provider/current CAS' USING ERRCODE = '23514'; + END IF; + NEW.committed_transaction_id := txid_current(); + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_subscription_lifecycle_consistency() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE current_row subscription%ROWTYPE; operation subscription_lifecycle_operations%ROWTYPE; + receipt subscription_lifecycle_receipts%ROWTYPE; notice subscription_lifecycle_operator_outbox%ROWTYPE; + source_head account_tenant_authority_source_records%ROWTYPE; generation_row RECORD; +BEGIN + IF TG_TABLE_NAME = 'subscription' THEN + SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = NEW.subscription_id; + ELSE + SELECT * INTO STRICT operation FROM subscription_lifecycle_operations WHERE request_id = NEW.request_id; + SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = operation.subscription_id; + IF operation.state = 'COMMITTED' THEN + SELECT * INTO STRICT receipt FROM subscription_lifecycle_receipts WHERE request_id = operation.request_id; + IF EXISTS (SELECT 1 FROM subscription_lifecycle_operator_outbox WHERE request_id = operation.request_id) THEN + RAISE EXCEPTION 'Committed lifecycle cannot carry terminal-failure work' USING ERRCODE = '23514'; + END IF; + ELSIF operation.state = 'BILLING_RECONCILIATION_TERMINAL_FAILURE' THEN + SELECT * INTO STRICT notice FROM subscription_lifecycle_operator_outbox WHERE request_id = operation.request_id; + IF notice.reason IS DISTINCT FROM operation.failure_reason THEN + RAISE EXCEPTION 'Lifecycle failure lacks its exact operator work item' USING ERRCODE = '23514'; + END IF; + END IF; + END IF; + IF current_row.lifecycle_inflight_request_id IS NOT NULL THEN + SELECT * INTO STRICT operation FROM subscription_lifecycle_operations WHERE request_id = current_row.lifecycle_inflight_request_id; + IF operation.state = 'COMMITTED' OR current_row.row_version <> operation.reserved_row_version + OR current_row.tenant_id <> operation.tenant_id THEN + RAISE EXCEPTION 'In-flight lifecycle operation lacks its exact current fence' USING ERRCODE = '23514'; + END IF; + ELSIF current_row.current_receipt_request_id IS NOT NULL THEN + SELECT * INTO STRICT receipt FROM subscription_lifecycle_receipts WHERE request_id = current_row.current_receipt_request_id; + SELECT * INTO STRICT operation FROM subscription_lifecycle_operations WHERE request_id = receipt.request_id; + IF operation.state <> 'COMMITTED' OR current_row.status <> receipt.status + OR current_row.provider_subscription_id IS DISTINCT FROM receipt.provider_subscription_id + OR current_row.plan_quote_digest <> receipt.plan_quote_digest + OR (current_row.superseded_at IS NULL AND current_row.row_version <> receipt.subscription_row_version) THEN + RAISE EXCEPTION 'Hosting current row lacks its exact committed lifecycle receipt' USING ERRCODE = '23514'; + END IF; + IF current_row.superseded_at IS NULL THEN + SELECT * INTO STRICT source_head FROM account_tenant_authority_source_records WHERE tenant_uuid = current_row.tenant_id; + SELECT generation, source_version INTO STRICT generation_row FROM account_authority_generations + WHERE scope_kind = 'TENANT' AND tenant_uuid = current_row.tenant_id; + IF source_head.last_request_id IS DISTINCT FROM receipt.request_id + OR source_head.last_request_digest IS DISTINCT FROM receipt.request_digest + OR source_head.current_generation <> receipt.authority_generation + OR source_head.current_source_version <> receipt.authority_source_version + OR source_head.last_outbox_sequence <> receipt.authority_sequence + OR source_head.last_event_id IS DISTINCT FROM receipt.authority_event_id + OR source_head.last_event_digest IS DISTINCT FROM receipt.authority_event_digest + OR source_head.tenant_billing_sequence <> receipt.billing_sequence + OR source_head.tenant_billing_event_id IS DISTINCT FROM receipt.billing_event_id + OR source_head.tenant_billing_event_digest IS DISTINCT FROM receipt.billing_event_digest + OR generation_row.generation <> receipt.authority_generation OR generation_row.source_version <> receipt.authority_source_version THEN + RAISE EXCEPTION 'Hosting current receipt requires its atomic canonical source checkpoint' USING ERRCODE = '23514'; + END IF; + END IF; + END IF; + RETURN NULL; +END; +$$; + +-- Extend only the canonical source's receipt branch. Original demo receipt semantics remain intact. +CREATE OR REPLACE FUNCTION account_tenant_authority_source_consistency() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE head RECORD; generation_row RECORD; stream_sequence BIGINT; operation_row RECORD; entitlement_row RECORD; + hosting subscription_lifecycle_receipts%ROWTYPE; current_row subscription%ROWTYPE; billing RECORD; +BEGIN + SELECT * INTO head FROM account_tenant_authority_source_records WHERE outbox_stream_key = NEW.outbox_stream_key; + SELECT generation, source_version INTO generation_row FROM account_authority_generations WHERE scope_kind = 'TENANT' AND tenant_uuid = NEW.tenant_uuid; + SELECT last_sequence INTO stream_sequence FROM account_authority_outbox_streams WHERE outbox_stream_key = NEW.outbox_stream_key; + IF head.outbox_stream_key IS NULL OR head.last_outbox_sequence <= 0 + OR head.current_generation IS DISTINCT FROM generation_row.generation + OR head.current_source_version IS DISTINCT FROM generation_row.source_version OR stream_sequence IS DISTINCT FROM head.last_outbox_sequence THEN + RAISE EXCEPTION 'Tenant authority source checkpoint is not the current Account generation' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_authority_source_consistent'; + END IF; + SELECT * INTO hosting FROM subscription_lifecycle_receipts WHERE request_id = head.last_request_id; + IF FOUND THEN + SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = hosting.subscription_id; + SELECT * INTO STRICT operation_row FROM subscription_lifecycle_operations WHERE request_id = hosting.request_id; + SELECT * INTO STRICT billing FROM account_tenant_entitlement_outbox_events + WHERE tenant_uuid = hosting.tenant_id AND tenant_billing_sequence = hosting.billing_sequence; + IF operation_row.state <> 'COMMITTED' OR hosting.tenant_id <> NEW.tenant_uuid + OR current_row.superseded_at IS NOT NULL OR current_row.current_receipt_request_id IS DISTINCT FROM hosting.request_id + OR current_row.lifecycle_inflight_request_id IS NOT NULL OR current_row.row_version <> hosting.subscription_row_version + OR current_row.status <> hosting.status OR current_row.provider_subscription_id IS DISTINCT FROM hosting.provider_subscription_id + OR hosting.request_digest IS DISTINCT FROM head.last_request_digest + OR hosting.authority_generation <> head.current_generation OR hosting.authority_source_version <> head.current_source_version + OR hosting.authority_sequence <> head.last_outbox_sequence OR hosting.authority_event_id IS DISTINCT FROM head.last_event_id + OR hosting.authority_event_digest IS DISTINCT FROM head.last_event_digest + OR hosting.billing_sequence <> head.tenant_billing_sequence OR hosting.billing_event_id IS DISTINCT FROM head.tenant_billing_event_id + OR hosting.billing_event_digest IS DISTINCT FROM head.tenant_billing_event_digest + OR convert_from(billing.payload, 'UTF8')::jsonb->'receipt' IS DISTINCT FROM convert_from(hosting.receipt_payload, 'UTF8')::jsonb THEN + RAISE EXCEPTION 'Hosting tenant source lacks its exact current receipt and billing event' USING ERRCODE = '23514'; + END IF; + RETURN NULL; + END IF; + SELECT request_id, tenant_uuid, request_digest, status, tenant_billing_sequence, event_id, event_digest, + tenant_authority_outbox_stream_key, tenant_authority_outbox_sequence, tenant_authority_event_id, tenant_authority_event_digest + INTO operation_row FROM account_demo_tenant_entitlement_operations WHERE request_id = head.last_request_id; + SELECT * INTO entitlement_row FROM account_demo_tenant_entitlements WHERE tenant_uuid = NEW.tenant_uuid; + IF operation_row.status IS DISTINCT FROM 'COMMITTED' OR operation_row.tenant_uuid IS DISTINCT FROM NEW.tenant_uuid + OR operation_row.request_digest IS DISTINCT FROM head.last_request_digest + OR operation_row.tenant_billing_sequence IS DISTINCT FROM head.tenant_billing_sequence + OR operation_row.event_id IS DISTINCT FROM head.tenant_billing_event_id OR operation_row.event_digest IS DISTINCT FROM head.tenant_billing_event_digest + OR operation_row.tenant_authority_outbox_stream_key IS DISTINCT FROM head.outbox_stream_key + OR operation_row.tenant_authority_outbox_sequence IS DISTINCT FROM head.last_outbox_sequence + OR operation_row.tenant_authority_event_id IS DISTINCT FROM head.last_event_id OR operation_row.tenant_authority_event_digest IS DISTINCT FROM head.last_event_digest + OR entitlement_row.tenant_uuid IS DISTINCT FROM NEW.tenant_uuid + OR entitlement_row.tenant_authority_generation IS DISTINCT FROM head.current_generation OR entitlement_row.tenant_authority_source_version IS DISTINCT FROM head.current_source_version + OR entitlement_row.tenant_billing_sequence IS DISTINCT FROM head.tenant_billing_sequence + OR entitlement_row.event_id IS DISTINCT FROM head.tenant_billing_event_id OR entitlement_row.event_digest IS DISTINCT FROM head.tenant_billing_event_digest + OR entitlement_row.tenant_authority_outbox_stream_key IS DISTINCT FROM head.outbox_stream_key + OR entitlement_row.tenant_authority_outbox_sequence IS DISTINCT FROM head.last_outbox_sequence + OR entitlement_row.tenant_authority_event_id IS DISTINCT FROM head.last_event_id OR entitlement_row.tenant_authority_event_digest IS DISTINCT FROM head.last_event_digest THEN + RAISE EXCEPTION 'Tenant authority source lacks its exact current Account receipt and entitlement' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_authority_source_receipt'; + END IF; + RETURN NULL; +END; +$$; + +CREATE TRIGGER subscription_lifecycle_operation_guard BEFORE INSERT OR UPDATE OR DELETE ON subscription_lifecycle_operations + FOR EACH ROW EXECUTE FUNCTION account_subscription_lifecycle_operation_guard(); +CREATE TRIGGER subscription_lifecycle_observation_guard BEFORE INSERT ON subscription_lifecycle_observations + FOR EACH ROW EXECUTE FUNCTION account_subscription_lifecycle_observation_guard(); +CREATE TRIGGER subscription_lifecycle_receipt_guard BEFORE INSERT ON subscription_lifecycle_receipts + FOR EACH ROW EXECUTE FUNCTION account_subscription_lifecycle_receipt_guard(); +CREATE CONSTRAINT TRIGGER subscription_lifecycle_current_consistency AFTER INSERT OR UPDATE ON subscription + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_subscription_lifecycle_consistency(); +CREATE CONSTRAINT TRIGGER subscription_lifecycle_operation_consistency AFTER INSERT OR UPDATE ON subscription_lifecycle_operations + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_subscription_lifecycle_consistency(); +CREATE CONSTRAINT TRIGGER subscription_lifecycle_receipt_consistency AFTER INSERT ON subscription_lifecycle_receipts + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_subscription_lifecycle_consistency(); +CREATE CONSTRAINT TRIGGER subscription_lifecycle_notice_consistency AFTER INSERT ON subscription_lifecycle_operator_outbox + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_subscription_lifecycle_consistency(); + +CREATE TRIGGER subscription_lifecycle_operation_no_truncate BEFORE TRUNCATE ON subscription_lifecycle_operations FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_lifecycle_attempt_immutable BEFORE UPDATE OR DELETE ON subscription_lifecycle_attempts FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_lifecycle_attempt_no_truncate BEFORE TRUNCATE ON subscription_lifecycle_attempts FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_lifecycle_observation_immutable BEFORE UPDATE OR DELETE ON subscription_lifecycle_observations FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_lifecycle_observation_no_truncate BEFORE TRUNCATE ON subscription_lifecycle_observations FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_lifecycle_receipt_immutable BEFORE UPDATE OR DELETE ON subscription_lifecycle_receipts FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_lifecycle_receipt_no_truncate BEFORE TRUNCATE ON subscription_lifecycle_receipts FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_lifecycle_notice_immutable BEFORE UPDATE OR DELETE ON subscription_lifecycle_operator_outbox FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_lifecycle_notice_no_truncate BEFORE TRUNCATE ON subscription_lifecycle_operator_outbox FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); + +CREATE FUNCTION account_subscription_provisioning_confirmed_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE work subscription_provisioning_work%ROWTYPE; +BEGIN + SELECT * INTO STRICT work FROM subscription_provisioning_work WHERE request_id = NEW.request_id; + IF work.phase = 'CONFIRMED' AND NOT EXISTS ( + SELECT 1 FROM subscription_lifecycle_operations operation + JOIN subscription_lifecycle_receipts receipt USING (request_id, subscription_id) + WHERE operation.creation_request_id = work.request_id AND operation.subscription_id = work.subscription_id + AND operation.provisioning_attempt_id = work.last_attempt_id AND operation.state = 'COMMITTED') THEN + RAISE EXCEPTION 'Provisioning confirmation lacks its exact lifecycle receipt' USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; +CREATE CONSTRAINT TRIGGER subscription_provisioning_confirmed_guard AFTER INSERT OR UPDATE ON subscription_provisioning_work + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_subscription_provisioning_confirmed_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V1032__hosting_subscription_first_provider_dispatch.sql b/services/account-service/src/main/resources/db/migration/V1032__hosting_subscription_first_provider_dispatch.sql new file mode 100644 index 0000000000..f5884ad7cc --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1032__hosting_subscription_first_provider_dispatch.sql @@ -0,0 +1,89 @@ +-- Separate remote dispatch from renewable worker attempts. Presence/replay is never permission. +CREATE TABLE subscription_provider_dispatch_claim ( + creation_request_id UUID PRIMARY KEY, + subscription_id UUID NOT NULL UNIQUE, + provider_operation_id UUID NOT NULL UNIQUE, + dispatch_id UUID NOT NULL UNIQUE CHECK (dispatch_id <> '00000000-0000-0000-0000-000000000000'::UUID), + classification VARCHAR(24) NOT NULL CHECK (classification IN ('FIRST_DISPATCH', 'PREEXISTING_UNKNOWN')), + first_attempt_id UUID, + first_claimed_row_version BIGINT, + recorded_at TIMESTAMPTZ NOT NULL, + CHECK ((first_attempt_id IS NULL) = (first_claimed_row_version IS NULL)), + CHECK (classification <> 'FIRST_DISPATCH' OR first_attempt_id IS NOT NULL), + FOREIGN KEY (creation_request_id, subscription_id) + REFERENCES subscription_create_operations(request_id, subscription_id) ON DELETE RESTRICT, + FOREIGN KEY (creation_request_id, provider_operation_id) + REFERENCES subscription_create_operations(request_id, subscription_provisioning_request_id) ON DELETE RESTRICT, + FOREIGN KEY (first_attempt_id, creation_request_id, subscription_id, first_claimed_row_version) + REFERENCES subscription_provisioning_attempts(attempt_id, request_id, subscription_id, claimed_row_version) ON DELETE RESTRICT +); + +-- Existing attempt-1/work rows may already have unknown remote effects. Preserve their bytes and +-- add only a non-authorizing guard. No dispatched/absent/canceled result is inferred. +-- Work without an attempt has no dispatch history to guard. +INSERT INTO subscription_provider_dispatch_claim + (creation_request_id, subscription_id, provider_operation_id, dispatch_id, classification, + first_attempt_id, first_claimed_row_version, recorded_at) +SELECT w.request_id, w.subscription_id, c.subscription_provisioning_request_id, + gen_random_uuid(), 'PREEXISTING_UNKNOWN', a.attempt_id, a.claimed_row_version, clock_timestamp() +FROM subscription_provisioning_work w +JOIN subscription_create_operations c ON c.request_id = w.request_id +JOIN subscription_provisioning_attempts a ON a.request_id = w.request_id AND a.attempt_number = 1; + +-- [jooq ignore start] +CREATE FUNCTION account_subscription_provider_dispatch_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + creation subscription_create_operations%ROWTYPE; + current_row subscription%ROWTYPE; + work subscription_provisioning_work%ROWTYPE; + attempt subscription_provisioning_attempts%ROWTYPE; + instrument payment_instrument%ROWTYPE; + customer billing_customer%ROWTYPE; + dispatch_at TIMESTAMPTZ; +BEGIN + SELECT * INTO STRICT creation FROM subscription_create_operations WHERE request_id = NEW.creation_request_id; + PERFORM 1 FROM accounts WHERE account_uuid = creation.account_uuid FOR UPDATE; + -- Match the canonical Account -> customer -> instrument acquisition order. + SELECT * INTO STRICT customer FROM billing_customer WHERE account_uuid = creation.account_uuid FOR UPDATE; + SELECT * INTO STRICT instrument FROM payment_instrument WHERE instrument_uuid = creation.payment_instrument_id FOR UPDATE; + SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = creation.subscription_id FOR UPDATE; + SELECT * INTO STRICT work FROM subscription_provisioning_work WHERE request_id = creation.request_id FOR UPDATE; + SELECT * INTO STRICT attempt FROM subscription_provisioning_attempts WHERE attempt_id = NEW.first_attempt_id; + -- Sample after every potentially blocking owner lock. A caller timestamp or transaction-start + -- timestamp cannot prove that the original lease is still live at the dispatch boundary. + dispatch_at := clock_timestamp(); + IF NEW.classification <> 'FIRST_DISPATCH' + OR NEW.subscription_id <> creation.subscription_id + OR NEW.provider_operation_id <> creation.subscription_provisioning_request_id + OR NEW.dispatch_id IN (creation.request_id, creation.subscription_provisioning_request_id, creation.cleanup_provider_identity) + OR NEW.first_claimed_row_version <> attempt.claimed_row_version + OR attempt.request_id <> creation.request_id OR attempt.subscription_id <> creation.subscription_id + OR work.phase <> 'CLAIMED' OR work.last_attempt_id <> attempt.attempt_id + OR work.attempt_count > work.max_attempts OR work.attempt_count > work.max_stalled_attempts + OR current_row.row_version <> attempt.claimed_row_version + OR current_row.status <> 'provisioning' OR current_row.provider_subscription_id IS NOT NULL + OR current_row.superseded_at IS NOT NULL OR current_row.lifecycle_inflight_request_id IS NOT NULL + OR instrument.account_uuid <> creation.account_uuid OR instrument.state <> 'ATTACHABLE' + OR instrument.row_version <> creation.reserved_instrument_version + OR instrument.customer_provisioning_request_id <> creation.customer_provisioning_request_id + OR instrument.provider_customer_id <> creation.provider_customer_id + OR customer.state <> 'CONFIRMED' OR customer.provider_customer_id <> creation.provider_customer_id + OR customer.customer_provisioning_request_id <> creation.customer_provisioning_request_id + OR dispatch_at < attempt.claimed_at OR dispatch_at >= attempt.expires_at + OR dispatch_at >= work.deadline_at THEN + RAISE EXCEPTION 'Provider dispatch lacks exact live original provisioning fence' USING ERRCODE = '23514'; + END IF; + NEW.recorded_at := dispatch_at; + RETURN NEW; +END; +$$; +CREATE TRIGGER subscription_provider_dispatch_insert_guard + BEFORE INSERT ON subscription_provider_dispatch_claim + FOR EACH ROW EXECUTE FUNCTION account_subscription_provider_dispatch_guard(); +CREATE TRIGGER subscription_provider_dispatch_immutable + BEFORE UPDATE OR DELETE ON subscription_provider_dispatch_claim + FOR EACH ROW EXECUTE FUNCTION account_billing_prerequisite_no_erasure(); +CREATE TRIGGER subscription_provider_dispatch_no_truncate + BEFORE TRUNCATE ON subscription_provider_dispatch_claim + FOR EACH STATEMENT EXECUTE FUNCTION account_billing_prerequisite_no_erasure(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V1036__hosting_subscription_terminal_resolution.sql b/services/account-service/src/main/resources/db/migration/V1036__hosting_subscription_terminal_resolution.sql new file mode 100644 index 0000000000..11bb675ceb --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1036__hosting_subscription_terminal_resolution.sql @@ -0,0 +1,202 @@ +-- Internal cancellation-only recovery. No actor authentication, provider absence, transfer, +-- caller registration or operational permission is established by these stored comparison facts. +CREATE TABLE subscription_lifecycle_terminal_resolutions ( + resolution_request_id UUID PRIMARY KEY CHECK (resolution_request_id <> '00000000-0000-0000-0000-000000000000'::uuid), + failed_request_id UUID NOT NULL REFERENCES subscription_lifecycle_operations(request_id) ON DELETE RESTRICT, + creation_request_id UUID NOT NULL REFERENCES subscription_create_operations(request_id) ON DELETE RESTRICT, + subscription_id UUID NOT NULL REFERENCES subscription(subscription_id) ON DELETE RESTRICT, + tenant_id UUID NOT NULL, + expected_failed_version BIGINT NOT NULL CHECK (expected_failed_version > 0), + expected_subscription_version BIGINT NOT NULL CHECK (expected_subscription_version > 0 AND expected_subscription_version < 9223372036854775805), + actor_account_id UUID NOT NULL REFERENCES accounts(account_uuid) ON DELETE RESTRICT, + control_ui_issuance_operation_id UUID NOT NULL CHECK (control_ui_issuance_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid), + control_ui_token_hash VARCHAR(64) NOT NULL CHECK (control_ui_token_hash ~ '^[0-9a-f]{64}$'), + audit_event_id UUID NOT NULL UNIQUE REFERENCES account_audit_outbox(audit_event_id) ON DELETE RESTRICT, + audit_reason TEXT NOT NULL CHECK (octet_length(audit_reason) BETWEEN 1 AND 1000), + request_payload BYTEA NOT NULL CHECK (octet_length(request_payload) BETWEEN 1 AND 32768), + request_digest VARCHAR(71) NOT NULL CHECK (request_digest = 'sha256:' || encode(sha256(request_payload), 'hex')), + attempt_id UUID NOT NULL UNIQUE, + captured_at TIMESTAMPTZ NOT NULL, + expires_at TIMESTAMPTZ NOT NULL CHECK (expires_at > captured_at), + authenticated_at TIMESTAMPTZ NOT NULL, + authorization_outcome VARCHAR(32) NOT NULL DEFAULT 'PRIMARY_AUTHENTICATED' CHECK (authorization_outcome = 'PRIMARY_AUTHENTICATED'), + state VARCHAR(16) NOT NULL CHECK (state IN ('PREPARED', 'COMMITTED')), + result_row_version BIGINT, + receipt_digest VARCHAR(71), + committed_at TIMESTAMPTZ, + created_transaction_id BIGINT NOT NULL DEFAULT txid_current(), + CHECK (resolution_request_id <> failed_request_id), + CHECK (authenticated_at >= captured_at AND authenticated_at < expires_at), + CHECK ((state = 'PREPARED' AND result_row_version IS NULL AND receipt_digest IS NULL AND committed_at IS NULL) + OR (state = 'COMMITTED' AND result_row_version IS NOT NULL AND receipt_digest IS NOT NULL + AND result_row_version = expected_subscription_version + 2 + AND receipt_digest ~ '^sha256:[0-9a-f]{64}$' AND committed_at IS NOT NULL)), + UNIQUE (failed_request_id) +); + +-- Failure history stays immutable. Its retained subscription fence still blocks normal prepare; +-- only the journal-backed atomic cancellation transition may replace that fence. +DROP INDEX subscription_lifecycle_one_inflight; +CREATE UNIQUE INDEX subscription_lifecycle_one_inflight ON subscription_lifecycle_operations(subscription_id) + WHERE state = 'PENDING'; + +-- [jooq ignore start] +ALTER TABLE subscription_lifecycle_terminal_resolutions + ADD CONSTRAINT subscription_terminal_resolution_reason_nfc CHECK (audit_reason IS NFC NORMALIZED); + +CREATE FUNCTION account_subscription_terminal_resolution_guard() RETURNS trigger LANGUAGE plpgsql AS $$ +DECLARE failed subscription_lifecycle_operations%ROWTYPE; current_row subscription%ROWTYPE; + audit account_audit_outbox%ROWTYPE; payload JSONB; field_count INTEGER; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Terminal lifecycle resolution is retained' USING ERRCODE = '23514'; + ELSIF TG_OP = 'UPDATE' THEN + IF OLD.state <> 'PREPARED' OR NEW.state <> 'COMMITTED' + OR (to_jsonb(NEW) - ARRAY['state','result_row_version','receipt_digest','committed_at']) + IS DISTINCT FROM (to_jsonb(OLD) - ARRAY['state','result_row_version','receipt_digest','committed_at']) + OR OLD.created_transaction_id <> txid_current() THEN + RAISE EXCEPTION 'Terminal lifecycle resolution is immutable outside its owner commit' USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + SELECT * INTO STRICT failed FROM subscription_lifecycle_operations WHERE request_id = NEW.failed_request_id FOR UPDATE; + SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = NEW.subscription_id FOR UPDATE; + SELECT * INTO STRICT audit FROM account_audit_outbox WHERE audit_event_id = NEW.audit_event_id; + payload := convert_from(NEW.request_payload, 'UTF8')::jsonb; + SELECT count(*) INTO field_count FROM jsonb_object_keys(payload); + IF NEW.state <> 'PREPARED' OR failed.state <> 'BILLING_RECONCILIATION_TERMINAL_FAILURE' + OR failed.row_version <> NEW.expected_failed_version + OR failed.creation_request_id <> NEW.creation_request_id OR failed.subscription_id <> NEW.subscription_id + OR failed.tenant_id <> NEW.tenant_id OR current_row.tenant_id <> NEW.tenant_id + OR current_row.account_uuid <> NEW.actor_account_id OR current_row.creation_request_id <> NEW.creation_request_id + OR current_row.row_version <> NEW.expected_subscription_version OR current_row.superseded_at IS NOT NULL + OR current_row.lifecycle_inflight_request_id IS DISTINCT FROM NEW.failed_request_id + OR audit.scope <> 'tenant' OR audit.tenant_identity_version <> 2 OR audit.tenant_uuid IS DISTINCT FROM NEW.tenant_id + OR audit.producer_service <> 'account-service' OR audit.event_type <> 'HOSTING_SUBSCRIPTION_TERMINAL_RESOLVED' + OR audit.payload_digest <> NEW.request_digest OR audit.payload IS DISTINCT FROM convert_from(NEW.request_payload, 'UTF8') + OR field_count <> 14 OR payload->>'schemaVersion' IS DISTINCT FROM 'account-hosting-terminal-resolution/v1' + OR payload->>'outcome' IS DISTINCT FROM 'CANCELED' + OR payload->>'resolutionRequestId' IS DISTINCT FROM NEW.resolution_request_id::text + OR payload->>'failedRequestId' IS DISTINCT FROM NEW.failed_request_id::text + OR payload->>'creationRequestId' IS DISTINCT FROM NEW.creation_request_id::text + OR payload->>'subscriptionId' IS DISTINCT FROM NEW.subscription_id::text + OR payload->>'tenantId' IS DISTINCT FROM NEW.tenant_id::text + OR payload->>'expectedFailedOperationVersion' IS DISTINCT FROM NEW.expected_failed_version::text + OR payload->>'expectedSubscriptionVersion' IS DISTINCT FROM NEW.expected_subscription_version::text + OR payload->>'actorAccountId' IS DISTINCT FROM NEW.actor_account_id::text + OR payload->>'controlUiIssuanceOperationId' IS DISTINCT FROM NEW.control_ui_issuance_operation_id::text + OR payload->>'controlUiTokenHash' IS DISTINCT FROM NEW.control_ui_token_hash + OR payload->>'auditEventId' IS DISTINCT FROM NEW.audit_event_id::text + OR payload->>'auditReason' IS DISTINCT FROM NEW.audit_reason + OR btrim(NEW.audit_reason, E'\t\n\f\r ' || chr(11) || chr(133) || chr(160) || chr(5760) + || chr(8192) || chr(8193) || chr(8194) || chr(8195) || chr(8196) || chr(8197) + || chr(8198) || chr(8199) || chr(8200) || chr(8201) || chr(8202) || chr(8232) + || chr(8233) || chr(8239) || chr(8287) || chr(12288)) = '' THEN + RAISE EXCEPTION 'Terminal lifecycle resolution lacks its exact failed target and audit' USING ERRCODE = '23514'; + END IF; + NEW.created_transaction_id := txid_current(); + RETURN NEW; +END; +$$; +CREATE TRIGGER subscription_terminal_resolution_guard BEFORE INSERT OR UPDATE OR DELETE ON subscription_lifecycle_terminal_resolutions + FOR EACH ROW EXECUTE FUNCTION account_subscription_terminal_resolution_guard(); + +CREATE OR REPLACE FUNCTION account_subscription_lifecycle_current_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'INSERT' THEN + IF NEW.lifecycle_inflight_request_id IS NOT NULL OR NEW.current_receipt_request_id IS NOT NULL THEN + RAISE EXCEPTION 'Subscription cannot begin with lifecycle authority' USING ERRCODE = '23514'; + END IF; + ELSIF OLD.lifecycle_inflight_request_id IS NOT NULL THEN + IF NEW.lifecycle_inflight_request_id IS NULL THEN + IF NEW.current_receipt_request_id IS DISTINCT FROM OLD.lifecycle_inflight_request_id THEN + RAISE EXCEPTION 'Lifecycle fence may clear only into its exact receipt' USING ERRCODE = '23514'; + END IF; + ELSIF NEW.lifecycle_inflight_request_id IS DISTINCT FROM OLD.lifecycle_inflight_request_id + OR NEW.current_receipt_request_id IS DISTINCT FROM OLD.current_receipt_request_id THEN + IF NEW.current_receipt_request_id IS DISTINCT FROM OLD.current_receipt_request_id + OR NOT EXISTS (SELECT 1 FROM subscription_lifecycle_terminal_resolutions resolution + JOIN subscription_lifecycle_operations operation ON operation.request_id = resolution.resolution_request_id + WHERE resolution.failed_request_id = OLD.lifecycle_inflight_request_id + AND resolution.resolution_request_id = NEW.lifecycle_inflight_request_id + AND resolution.subscription_id = OLD.subscription_id AND resolution.state = 'PREPARED' + AND resolution.expected_subscription_version = OLD.row_version + AND resolution.created_transaction_id = txid_current() + AND operation.state = 'PENDING' AND operation.request_digest = resolution.request_digest + AND operation.reserved_row_version = NEW.row_version + AND operation.creation_request_id = OLD.creation_request_id + AND operation.tenant_id = OLD.tenant_id) THEN + RAISE EXCEPTION 'In-flight lifecycle ownership cannot be replaced without exact resolution' USING ERRCODE = '23514'; + END IF; + END IF; + ELSE + IF NEW.current_receipt_request_id IS DISTINCT FROM OLD.current_receipt_request_id THEN + RAISE EXCEPTION 'Committed current receipt cannot be detached or replaced without a lifecycle fence' USING ERRCODE = '23514'; + END IF; + IF NEW.lifecycle_inflight_request_id IS NOT NULL + AND (NEW.status, NEW.provider_subscription_id, NEW.terminal_resolution_id) + IS DISTINCT FROM (OLD.status, OLD.provider_subscription_id, OLD.terminal_resolution_id) THEN + RAISE EXCEPTION 'Lifecycle preparation cannot pre-commit provider state' USING ERRCODE = '23514'; + END IF; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_subscription_terminal_resolution_consistency() RETURNS trigger LANGUAGE plpgsql AS $$ +DECLARE resolution subscription_lifecycle_terminal_resolutions%ROWTYPE; operation subscription_lifecycle_operations%ROWTYPE; + receipt subscription_lifecycle_receipts%ROWTYPE; observation subscription_lifecycle_observations%ROWTYPE; + current_row subscription%ROWTYPE; failed subscription_lifecycle_operations%ROWTYPE; +BEGIN + SELECT * INTO STRICT resolution FROM subscription_lifecycle_terminal_resolutions WHERE resolution_request_id = NEW.resolution_request_id; + SELECT * INTO STRICT failed FROM subscription_lifecycle_operations WHERE request_id = resolution.failed_request_id; + SELECT * INTO STRICT operation FROM subscription_lifecycle_operations WHERE request_id = resolution.resolution_request_id; + SELECT * INTO STRICT receipt FROM subscription_lifecycle_receipts WHERE request_id = resolution.resolution_request_id; + SELECT * INTO STRICT observation FROM subscription_lifecycle_observations WHERE attempt_id = resolution.attempt_id; + SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = resolution.subscription_id; + IF resolution.state <> 'COMMITTED' OR resolution.created_transaction_id <> txid_current() + OR failed.state <> 'BILLING_RECONCILIATION_TERMINAL_FAILURE' OR failed.row_version <> resolution.expected_failed_version + OR operation.state <> 'COMMITTED' OR operation.request_digest <> resolution.request_digest + OR operation.request_payload <> resolution.request_payload OR operation.creation_request_id <> resolution.creation_request_id + OR receipt.status <> 'canceled' OR receipt.request_digest <> resolution.request_digest + OR receipt.subscription_id <> resolution.subscription_id OR receipt.tenant_id <> resolution.tenant_id + OR receipt.subscription_row_version <> resolution.result_row_version OR receipt.receipt_digest <> resolution.receipt_digest + OR receipt.attempt_id <> resolution.attempt_id OR receipt.committed_transaction_id <> txid_current() + OR observation.raw_status <> 'canceled' OR observation.recorded_transaction_id <> txid_current() + OR convert_from(observation.payload, 'UTF8')::jsonb->>'kind' IS DISTINCT FROM 'SDK_OBSERVED' + OR convert_from(observation.payload, 'UTF8')::jsonb->>'providerStatus' IS DISTINCT FROM 'canceled' + OR observation.read_started_at < resolution.captured_at OR observation.observed_at > resolution.authenticated_at + OR resolution.authenticated_at >= resolution.expires_at OR resolution.committed_at >= resolution.expires_at + OR current_row.current_receipt_request_id IS DISTINCT FROM resolution.resolution_request_id + OR current_row.lifecycle_inflight_request_id IS NOT NULL OR current_row.row_version <> resolution.result_row_version + OR current_row.status <> 'canceled' OR current_row.terminal_resolution_id IS NULL + OR NOT EXISTS (SELECT 1 FROM subscription_instrument_reservations reservation + WHERE reservation.request_id = resolution.creation_request_id AND reservation.subscription_id = resolution.subscription_id + AND reservation.terminal_resolution_id = current_row.terminal_resolution_id AND reservation.released_at IS NOT NULL) THEN + RAISE EXCEPTION 'Cancellation resolution lacks its atomic receipt, retained failure and terminal reservation' USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; +CREATE CONSTRAINT TRIGGER subscription_terminal_resolution_consistency AFTER INSERT OR UPDATE ON subscription_lifecycle_terminal_resolutions + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_subscription_terminal_resolution_consistency(); +CREATE TRIGGER subscription_terminal_resolution_no_truncate BEFORE TRUNCATE ON subscription_lifecycle_terminal_resolutions + FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); + +-- Replacing the partial index must not make unowned dangling PENDING rows committable. +CREATE FUNCTION account_subscription_pending_owner_consistency() RETURNS trigger LANGUAGE plpgsql AS $$ +DECLARE operation subscription_lifecycle_operations%ROWTYPE; current_row subscription%ROWTYPE; +BEGIN + SELECT * INTO STRICT operation FROM subscription_lifecycle_operations WHERE request_id = NEW.request_id; + IF operation.state = 'PENDING' THEN + SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = operation.subscription_id; + IF current_row.lifecycle_inflight_request_id IS DISTINCT FROM operation.request_id THEN + RAISE EXCEPTION 'Pending lifecycle requires its exact retained current fence' USING ERRCODE = '23514'; + END IF; + END IF; + RETURN NULL; +END; +$$; +CREATE CONSTRAINT TRIGGER subscription_pending_owner_consistency AFTER INSERT OR UPDATE ON subscription_lifecycle_operations + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_subscription_pending_owner_consistency(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V1037__canonical_join_failure_and_attempt_diagnostics.sql b/services/account-service/src/main/resources/db/migration/V1037__canonical_join_failure_and_attempt_diagnostics.sql new file mode 100644 index 0000000000..8f8e183945 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1037__canonical_join_failure_and_attempt_diagnostics.sql @@ -0,0 +1,440 @@ +-- Extend only the canonical V2 journal. V1 rows and applied migrations are unchanged. +-- Bound policy bytes remain immutable while PENDING diagnostics can describe an unavailable +-- retry or exact-policy recovery. FAILED retains intent/scope and optional original policy, +-- never membership/event/audit success evidence. Both terminal states remain immutable. +/* [jooq ignore start] */ +ALTER TABLE account_join_operations + DROP CONSTRAINT account_join_operation_representation_check; + +ALTER TABLE account_join_operations + ADD CONSTRAINT account_join_operation_representation_check CHECK ( + (operation_representation_version = 1 AND scope_digest_version = 1 + AND target_class IS NULL AND account_uuid IS NULL AND tenant_uuid IS NULL + AND tenant_slug IS NULL AND playable_state_namespace_uuid IS NULL + AND game_instance_uuid IS NULL) + OR + (operation_representation_version = 2 AND scope_digest_version = 2 + AND request_id IS NOT NULL AND account_id IS NOT NULL + AND verified_caller_binding IS NOT NULL AND scope_token_hash IS NOT NULL + AND connect_scope_digest IS NOT NULL AND realm_id IS NOT NULL + AND world_slug IS NOT NULL AND realm_slug IS NOT NULL + AND playable_state_scope IS NOT NULL AND catalog_revision IS NOT NULL + AND pointer_version IS NOT NULL AND intent_digest_version = 2 + AND intent_digest ~ '^sha256:[0-9a-f]{64}$' + AND entitlement_authority_availability IS NOT NULL + AND last_attempt_authority_availability IS NOT NULL + AND caller_bound_authority_invalidated IS FALSE + AND btrim(request_id) <> '' AND verified_caller_binding <> '' + AND scope_token_hash ~ '^sha256:[0-9a-f]{64}$' + AND target_class = 'PUBLIC_PRODUCTION' + AND tenant_id IS NULL AND game_instance_id IS NULL + AND playable_state_namespace_id IS NULL + AND account_uuid IS NOT NULL + AND account_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND tenant_uuid IS NOT NULL + AND tenant_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND tenant_slug IS NOT NULL AND tenant_slug <> '' + AND realm_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND world_slug <> '' AND realm_slug <> '' + AND playable_state_namespace_uuid IS NOT NULL + AND playable_state_namespace_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND playable_state_scope IN ('SHARED', 'ISOLATED') + AND game_instance_uuid IS NOT NULL + AND game_instance_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND connect_scope_digest ~ '^sha256:[0-9a-f]{64}$' + AND ((status = 'PENDING' AND outcome IS NULL AND membership_id IS NULL + AND outcome_membership_version IS NULL + AND outcome_membership_authority_generation IS NULL) + OR (status = 'FAILED' AND outcome IS NOT NULL + AND outcome IN ('CONNECT_SCOPE_INVALID', 'CONNECT_SCOPE_MISMATCH', 'PUBLIC_PRODUCTION_ADMISSION_DENIED', 'TENANT_BILLING_BLOCKED', 'IDEMPOTENCY_CONFLICT', 'MEMBERSHIP_RECONCILIATION_REQUIRED', 'REALM_UNAVAILABLE') + AND membership_id IS NULL AND outcome_membership_version IS NULL + AND outcome_membership_authority_generation IS NULL) + OR (status = 'COMMITTED' AND outcome = 'JOINED' + AND membership_id IS NOT NULL AND membership_id > 0 + AND outcome_membership_version = 2 + AND outcome_membership_authority_generation = 1))) + ); + +ALTER TABLE account_join_operations DROP CONSTRAINT account_join_canonical_terminal_proof_check; + +ALTER TABLE account_join_operations + ADD CONSTRAINT account_join_canonical_terminal_proof_check CHECK ( + (operation_representation_version = 1 + AND membership_authority_outbox_stream_key IS NULL + AND membership_authority_outbox_sequence IS NULL + AND membership_authority_event_id IS NULL + AND membership_authority_event_digest IS NULL + AND join_audit_event_id IS NULL + AND join_audit_payload_digest IS NULL + AND join_audit_occurred_at IS NULL) + OR (operation_representation_version = 2 AND status IN ('PENDING', 'FAILED') + AND ((status = 'PENDING' AND outcome IS NULL) + OR (status = 'FAILED' AND outcome IS NOT NULL AND outcome IN ('CONNECT_SCOPE_INVALID', 'CONNECT_SCOPE_MISMATCH', 'PUBLIC_PRODUCTION_ADMISSION_DENIED', 'TENANT_BILLING_BLOCKED', 'IDEMPOTENCY_CONFLICT', 'MEMBERSHIP_RECONCILIATION_REQUIRED', 'REALM_UNAVAILABLE'))) AND membership_id IS NULL + AND outcome_membership_version IS NULL + AND outcome_membership_authority_generation IS NULL + AND membership_authority_outbox_stream_key IS NULL + AND membership_authority_outbox_sequence IS NULL + AND membership_authority_event_id IS NULL + AND membership_authority_event_digest IS NULL + AND join_audit_event_id IS NULL + AND join_audit_payload_digest IS NULL + AND join_audit_occurred_at IS NULL) + OR (operation_representation_version = 2 AND status = 'COMMITTED' + AND outcome = 'JOINED' + AND membership_id IS NOT NULL AND membership_id > 0 + AND outcome_membership_version = 2 + AND outcome_membership_authority_generation = 1 + AND membership_authority_outbox_stream_key IS NOT NULL + AND membership_authority_outbox_stream_key = + 'account:auth-authority:v1:membership/' || account_uuid::TEXT || '/' || tenant_uuid::TEXT + AND membership_authority_outbox_sequence IS NOT NULL + AND membership_authority_outbox_sequence = 1 + AND membership_authority_event_id IS NOT NULL + AND btrim(membership_authority_event_id) <> '' + AND membership_authority_event_digest IS NOT NULL + AND membership_authority_event_digest ~ '^sha256:[0-9a-f]{64}$' + AND join_audit_event_id IS NOT NULL + AND join_audit_event_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND join_audit_payload_digest IS NOT NULL + AND join_audit_payload_digest ~ '^sha256:[0-9a-f]{64}$' + AND join_audit_occurred_at IS NOT NULL) + ); + +ALTER TABLE account_join_operations + ADD CONSTRAINT account_join_v2_attempt_diagnostics_check CHECK ( + operation_representation_version = 1 OR ( + operation_representation_version = 2 AND ( + (last_attempt_failure_code IS NULL AND ( + (request_digest IS NULL + AND entitlement_authority_availability = 'NOT_EVALUATED' + AND last_attempt_authority_availability = 'NOT_EVALUATED') + OR (request_digest IS NOT NULL + AND entitlement_authority_availability = 'AVAILABLE' + AND last_attempt_authority_availability = 'AVAILABLE'))) + OR (status = 'PENDING' AND last_attempt_failure_code IS NOT NULL + AND last_attempt_failure_code IN ('AUTH_UNAVAILABLE', 'ENTITLEMENT_UNAVAILABLE', 'ADMISSION_POINTER_UNAVAILABLE') + AND last_attempt_authority_availability IN ('UNAVAILABLE', 'NOT_EVALUATED') + AND (request_digest IS NOT NULL + OR entitlement_authority_availability = last_attempt_authority_availability)) + ) + ) + ); + +CREATE OR REPLACE FUNCTION guard_account_join_operation_identity() RETURNS trigger AS $$ +DECLARE + scope_source_matches BOOLEAN := FALSE; + membership_matches BOOLEAN := FALSE; + pair_matches BOOLEAN := FALSE; + authority_event_matches BOOLEAN := FALSE; + audit_envelope_matches BOOLEAN := FALSE; +BEGIN + IF TG_OP = 'DELETE' THEN + IF OLD.operation_representation_version = 2 THEN + RAISE EXCEPTION 'Canonical JOIN operation evidence cannot be deleted' + USING ERRCODE = 'check_violation'; + END IF; + RETURN OLD; + END IF; + + IF TG_OP = 'INSERT' THEN + IF NEW.operation_representation_version = 1 THEN + RETURN NEW; + END IF; + IF NEW.operation_representation_version IS DISTINCT FROM 2 + OR NEW.scope_digest_version IS DISTINCT FROM 2 + OR NEW.intent_digest_version IS DISTINCT FROM 2 + OR NEW.status IS DISTINCT FROM 'PENDING' + OR NEW.outcome IS NOT NULL OR NEW.membership_id IS NOT NULL + OR NEW.outcome_membership_version IS NOT NULL + OR NEW.outcome_membership_authority_generation IS NOT NULL + OR NEW.membership_authority_outbox_stream_key IS NOT NULL + OR NEW.membership_authority_outbox_sequence IS NOT NULL + OR NEW.membership_authority_event_id IS NOT NULL + OR NEW.membership_authority_event_digest IS NOT NULL + OR NEW.join_audit_event_id IS NOT NULL + OR NEW.join_audit_payload_digest IS NOT NULL + OR NEW.join_audit_occurred_at IS NOT NULL + OR NEW.caller_bound_authority_invalidated IS DISTINCT FROM FALSE + OR NEW.entitlement_authority_availability IS DISTINCT FROM 'NOT_EVALUATED' + OR NEW.entitlement_version IS NOT NULL OR NEW.allow_public_join IS NOT NULL + OR NEW.request_digest_version IS NOT NULL OR NEW.request_digest IS NOT NULL + OR NEW.last_attempt_authority_availability IS DISTINCT FROM 'NOT_EVALUATED' + OR NEW.last_attempt_failure_code IS NOT NULL THEN + RAISE EXCEPTION 'Canonical JOIN operation must start as an exact pending intent' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT EXISTS ( + SELECT 1 FROM account_connect_scope_records scope_row + WHERE scope_row.scope_token_hash = NEW.scope_token_hash + AND scope_row.scope_digest_version = 2 + AND scope_row.snapshot_digest = NEW.connect_scope_digest + AND scope_row.account_id = NEW.account_id + AND scope_row.account_uuid = NEW.account_uuid + AND scope_row.target_class = NEW.target_class + AND scope_row.tenant_id IS NULL + AND scope_row.tenant_uuid = NEW.tenant_uuid + AND scope_row.tenant_slug = NEW.tenant_slug + AND scope_row.realm_id = NEW.realm_id + AND scope_row.world_slug = NEW.world_slug + AND scope_row.realm_slug = NEW.realm_slug + AND scope_row.playable_state_namespace_id IS NULL + AND scope_row.playable_state_namespace_uuid = NEW.playable_state_namespace_uuid + AND scope_row.playable_state_scope = NEW.playable_state_scope + AND scope_row.game_instance_id IS NULL + AND scope_row.game_instance_uuid = NEW.game_instance_uuid + AND scope_row.catalog_revision = NEW.catalog_revision + AND scope_row.pointer_version = NEW.pointer_version + ) INTO scope_source_matches; + IF NOT scope_source_matches THEN + RAISE EXCEPTION 'Canonical JOIN operation has no exact persisted scope source' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF OLD.operation_representation_version = 1 THEN + IF NEW.operation_representation_version IS DISTINCT FROM 1 THEN + RAISE EXCEPTION 'Retained JOIN operation evidence cannot change representation' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF OLD.operation_representation_version <> 2 + OR NEW.operation_representation_version IS DISTINCT FROM 2 + OR NEW.request_id IS DISTINCT FROM OLD.request_id + OR NEW.account_id IS DISTINCT FROM OLD.account_id + OR NEW.tenant_id IS DISTINCT FROM OLD.tenant_id + OR NEW.verified_caller_binding IS DISTINCT FROM OLD.verified_caller_binding + OR NEW.scope_token_hash IS DISTINCT FROM OLD.scope_token_hash + OR NEW.connect_scope_digest IS DISTINCT FROM OLD.connect_scope_digest + OR NEW.world_slug IS DISTINCT FROM OLD.world_slug + OR NEW.realm_slug IS DISTINCT FROM OLD.realm_slug + OR NEW.realm_id IS DISTINCT FROM OLD.realm_id + OR NEW.playable_state_namespace_id IS DISTINCT FROM OLD.playable_state_namespace_id + OR NEW.playable_state_scope IS DISTINCT FROM OLD.playable_state_scope + OR NEW.game_instance_id IS DISTINCT FROM OLD.game_instance_id + OR NEW.catalog_revision IS DISTINCT FROM OLD.catalog_revision + OR NEW.pointer_version IS DISTINCT FROM OLD.pointer_version + OR NEW.intent_digest_version IS DISTINCT FROM OLD.intent_digest_version + OR NEW.intent_digest IS DISTINCT FROM OLD.intent_digest + OR NEW.scope_digest_version IS DISTINCT FROM OLD.scope_digest_version + OR NEW.target_class IS DISTINCT FROM OLD.target_class + OR NEW.account_uuid IS DISTINCT FROM OLD.account_uuid + OR NEW.tenant_uuid IS DISTINCT FROM OLD.tenant_uuid + OR NEW.tenant_slug IS DISTINCT FROM OLD.tenant_slug + OR NEW.playable_state_namespace_uuid IS DISTINCT FROM OLD.playable_state_namespace_uuid + OR NEW.game_instance_uuid IS DISTINCT FROM OLD.game_instance_uuid + OR NEW.caller_bound_authority_invalidated IS DISTINCT FROM FALSE + OR NEW.created_at IS DISTINCT FROM OLD.created_at THEN + RAISE EXCEPTION 'Canonical JOIN operation intent evidence is immutable' + USING ERRCODE = 'check_violation'; + END IF; + + IF OLD.status IN ('COMMITTED', 'FAILED') THEN + RAISE EXCEPTION 'Terminal canonical JOIN receipt is immutable' + USING ERRCODE = 'check_violation'; + END IF; + IF OLD.status IS DISTINCT FROM 'PENDING' THEN + RAISE EXCEPTION 'Canonical JOIN operation has unsupported prior status' + USING ERRCODE = 'check_violation'; + END IF; + + IF OLD.request_digest IS NULL THEN + IF NEW.request_digest IS NOT NULL THEN + IF NEW.request_digest_version IS DISTINCT FROM 2 + OR NEW.entitlement_authority_availability IS DISTINCT FROM 'AVAILABLE' + OR NEW.entitlement_version IS NULL OR NEW.entitlement_version <= 0 + OR NEW.allow_public_join IS NULL + OR NEW.last_attempt_authority_availability IS DISTINCT FROM 'AVAILABLE' + OR NEW.last_attempt_failure_code IS NOT NULL THEN + RAISE EXCEPTION 'Canonical JOIN policy binding is incomplete' + USING ERRCODE = 'check_violation'; + END IF; + ELSIF NEW.status = 'FAILED' THEN + IF NEW.request_digest_version IS NOT NULL + OR NEW.entitlement_version IS NOT NULL OR NEW.allow_public_join IS NOT NULL + OR NEW.entitlement_authority_availability IS DISTINCT FROM 'NOT_EVALUATED' + OR NEW.last_attempt_authority_availability IS DISTINCT FROM 'NOT_EVALUATED' + OR NEW.last_attempt_failure_code IS NOT NULL THEN + RAISE EXCEPTION 'Unbound failed canonical JOIN cannot invent policy evidence' + USING ERRCODE = 'check_violation'; + END IF; + ELSIF NEW.request_digest_version IS NOT NULL + OR NEW.entitlement_version IS NOT NULL OR NEW.allow_public_join IS NOT NULL + OR NEW.entitlement_authority_availability NOT IN ('UNAVAILABLE', 'NOT_EVALUATED') + OR NEW.last_attempt_authority_availability IS DISTINCT FROM NEW.entitlement_authority_availability + OR NEW.last_attempt_failure_code IS NULL + OR NEW.last_attempt_failure_code NOT IN ('AUTH_UNAVAILABLE', 'ENTITLEMENT_UNAVAILABLE', 'ADMISSION_POINTER_UNAVAILABLE') THEN + RAISE EXCEPTION 'Canonical JOIN unavailable attempt cannot invent policy evidence' + USING ERRCODE = 'check_violation'; + END IF; + ELSE + IF NEW.request_digest IS DISTINCT FROM OLD.request_digest + OR NEW.request_digest_version IS DISTINCT FROM OLD.request_digest_version + OR NEW.entitlement_authority_availability IS DISTINCT FROM OLD.entitlement_authority_availability + OR NEW.entitlement_version IS DISTINCT FROM OLD.entitlement_version + OR NEW.allow_public_join IS DISTINCT FROM OLD.allow_public_join THEN + RAISE EXCEPTION 'Canonical JOIN available policy evidence is immutable' + USING ERRCODE = 'check_violation'; + END IF; + END IF; + + IF NEW.status = 'FAILED' THEN + IF NEW.outcome IS NULL OR NEW.outcome NOT IN ('CONNECT_SCOPE_INVALID', 'CONNECT_SCOPE_MISMATCH', 'PUBLIC_PRODUCTION_ADMISSION_DENIED', 'TENANT_BILLING_BLOCKED', 'IDEMPOTENCY_CONFLICT', 'MEMBERSHIP_RECONCILIATION_REQUIRED', 'REALM_UNAVAILABLE') + OR NEW.request_digest IS DISTINCT FROM OLD.request_digest + OR NEW.request_digest_version IS DISTINCT FROM OLD.request_digest_version + OR NEW.entitlement_version IS DISTINCT FROM OLD.entitlement_version + OR NEW.allow_public_join IS DISTINCT FROM OLD.allow_public_join + OR NEW.membership_id IS NOT NULL + OR NEW.outcome_membership_version IS NOT NULL + OR NEW.outcome_membership_authority_generation IS NOT NULL + OR NEW.membership_authority_outbox_stream_key IS NOT NULL + OR NEW.membership_authority_outbox_sequence IS NOT NULL + OR NEW.membership_authority_event_id IS NOT NULL + OR NEW.membership_authority_event_digest IS NOT NULL + OR NEW.join_audit_event_id IS NOT NULL + OR NEW.join_audit_payload_digest IS NOT NULL + OR NEW.join_audit_occurred_at IS NOT NULL + OR NEW.last_attempt_failure_code IS NOT NULL THEN + RAISE EXCEPTION 'Failed canonical JOIN must retain original policy and no success proof' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF NEW.status = 'PENDING' THEN + IF NEW.outcome IS NOT NULL OR NEW.membership_id IS NOT NULL + OR NEW.outcome_membership_version IS NOT NULL + OR NEW.outcome_membership_authority_generation IS NOT NULL + OR NEW.membership_authority_outbox_stream_key IS NOT NULL + OR NEW.membership_authority_outbox_sequence IS NOT NULL + OR NEW.membership_authority_event_id IS NOT NULL + OR NEW.membership_authority_event_digest IS NOT NULL + OR NEW.join_audit_event_id IS NOT NULL + OR NEW.join_audit_payload_digest IS NOT NULL + OR NEW.join_audit_occurred_at IS NOT NULL THEN + RAISE EXCEPTION 'Pending canonical JOIN cannot carry terminal receipt evidence' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF NEW.status IS DISTINCT FROM 'COMMITTED' + OR NEW.outcome IS DISTINCT FROM 'JOINED' + OR NEW.entitlement_authority_availability IS DISTINCT FROM 'AVAILABLE' + OR NEW.allow_public_join IS DISTINCT FROM TRUE + OR NEW.entitlement_version IS NULL OR NEW.entitlement_version <= 0 + OR NEW.request_digest_version IS DISTINCT FROM 2 + OR NEW.request_digest IS NULL + OR NEW.request_digest !~ '^sha256:[0-9a-f]{64}$' + OR NEW.last_attempt_failure_code IS NOT NULL + OR NEW.last_attempt_authority_availability IS DISTINCT FROM 'AVAILABLE' + OR NEW.membership_id IS NULL + OR NEW.outcome_membership_version IS DISTINCT FROM 2 + OR NEW.outcome_membership_authority_generation IS DISTINCT FROM 1 + OR NEW.membership_authority_outbox_stream_key IS NULL + OR NEW.membership_authority_outbox_sequence IS DISTINCT FROM 1 + OR NEW.membership_authority_event_id IS NULL + OR NEW.membership_authority_event_digest IS NULL + OR NEW.membership_authority_event_digest !~ '^sha256:[0-9a-f]{64}$' + OR NEW.join_audit_event_id IS NULL + OR NEW.join_audit_payload_digest IS NULL + OR NEW.join_audit_payload_digest !~ '^sha256:[0-9a-f]{64}$' + OR NEW.join_audit_occurred_at IS NULL THEN + RAISE EXCEPTION 'Canonical JOIN terminal receipt is incomplete or noncommitting' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT EXISTS ( + SELECT 1 FROM account_tenant_membership membership + WHERE membership.id = NEW.membership_id + AND membership.account_id = NEW.account_id + AND membership.tenant_uuid = NEW.tenant_uuid + AND membership.tenant_id IS NULL + AND membership.tenant_provenance_kind = 'FRESH_GAME_DESIGN' + AND membership.lifecycle_state = 'ACTIVE' + AND membership.gameplay_admission_allowed IS TRUE + AND membership.authority_provenance = 'EXPLICIT_JOIN' + AND membership.membership_version = NEW.outcome_membership_version + AND membership.membership_authority_generation = + NEW.outcome_membership_authority_generation + ) INTO membership_matches; + + SELECT EXISTS ( + SELECT 1 FROM account_membership_pair_authority pair + JOIN account_tenant_membership membership + ON membership.id = NEW.membership_id + WHERE pair.account_uuid = NEW.account_uuid + AND pair.tenant_uuid = NEW.tenant_uuid + AND pair.membership_exists IS TRUE + AND pair.membership_version = NEW.outcome_membership_version + AND pair.membership_authority_generation = + NEW.outcome_membership_authority_generation + AND pair.last_event_sequence = NEW.membership_authority_outbox_sequence + AND pair.last_event_id = NEW.membership_authority_event_id + AND pair.last_event_digest = NEW.membership_authority_event_digest + AND pair.last_transition_invalidated IS FALSE + AND pair.tenant_provenance_kind = membership.tenant_provenance_kind + AND pair.tenant_source_operation_id = membership.tenant_source_operation_id + AND pair.tenant_provenance_digest = membership.tenant_provenance_digest + ) INTO pair_matches; + + SELECT EXISTS ( + SELECT 1 FROM account_authority_outbox_events event + JOIN account_authority_outbox_streams stream + ON stream.outbox_stream_key = event.outbox_stream_key + WHERE event.outbox_stream_key = NEW.membership_authority_outbox_stream_key + AND event.outbox_sequence = NEW.membership_authority_outbox_sequence + AND event.request_id = NEW.request_id + AND event.event_id = NEW.membership_authority_event_id + AND event.event_digest = NEW.membership_authority_event_digest + AND stream.last_sequence = NEW.membership_authority_outbox_sequence + ) INTO authority_event_matches; + + SELECT EXISTS ( + SELECT 1 FROM account_audit_outbox audit + WHERE audit.audit_event_id = NEW.join_audit_event_id + AND audit.scope = 'tenant' + AND audit.tenant_identity_version = 2 + AND audit.tenant_id IS NULL + AND audit.tenant_uuid = NEW.tenant_uuid + AND audit.producer_service = 'account-service' + AND audit.event_type = 'ACCOUNT_JOINED_PUBLIC_PRODUCTION' + AND audit.schema_version = 1 + AND audit.payload_digest_version = 1 + AND audit.payload_digest = NEW.join_audit_payload_digest + AND audit.occurred_at = NEW.join_audit_occurred_at + AND audit.delivery_status = 'PENDING' + AND audit.payload IS NOT NULL + AND audit.payload::JSONB ->> 'accountId' = NEW.account_uuid::TEXT + AND audit.payload::JSONB ->> 'tenantId' = NEW.tenant_uuid::TEXT + AND audit.payload::JSONB ->> 'requestId' = NEW.request_id + AND audit.payload::JSONB ->> 'worldSlug' = NEW.world_slug + AND audit.payload::JSONB ->> 'realmSlug' = NEW.realm_slug + AND audit.payload::JSONB ->> 'membershipVersion' = '2' + AND audit.payload::JSONB ->> 'membershipAuthorityGeneration' = '1' + AND audit.payload::JSONB ->> 'membershipEventStreamKey' = + NEW.membership_authority_outbox_stream_key + AND audit.payload::JSONB ->> 'membershipEventSequence' = + NEW.membership_authority_outbox_sequence::TEXT + AND audit.payload::JSONB ->> 'membershipEventId' = NEW.membership_authority_event_id + AND audit.payload::JSONB ->> 'membershipEventDigest' = + NEW.membership_authority_event_digest + AND audit.payload::JSONB ->> 'joinIntentDigest' = NEW.intent_digest + AND audit.payload::JSONB ->> 'joinRequestDigest' = NEW.request_digest + AND audit.payload::JSONB ->> 'allowPublicJoin' = 'true' + AND audit.payload::JSONB ->> 'entitlementVersion' = NEW.entitlement_version::TEXT + ) INTO audit_envelope_matches; + + IF NOT membership_matches OR NOT pair_matches OR NOT authority_event_matches + OR NOT audit_envelope_matches THEN + RAISE EXCEPTION 'Canonical JOIN terminal receipt does not match committed owner evidence' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +/* [jooq ignore stop] */ diff --git a/services/account-service/src/main/resources/db/migration/V1038__canonical_join_existing_membership_terminal.sql b/services/account-service/src/main/resources/db/migration/V1038__canonical_join_existing_membership_terminal.sql new file mode 100644 index 0000000000..d39f798333 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1038__canonical_join_existing_membership_terminal.sql @@ -0,0 +1,456 @@ +-- Extend canonical V2 terminals to the ADR 0025 existing-membership lifecycle. Applied migrations +-- and retained receipts remain immutable. ACTIVE records its exact current owner/event snapshot +-- without a new transition or audit; INACTIVE restoration records one later event and audit. +/* [jooq ignore start] */ +ALTER TABLE account_join_operations DROP CONSTRAINT account_join_committed_policy_check; +ALTER TABLE account_join_operations ADD CONSTRAINT account_join_committed_policy_check CHECK ( + status <> 'COMMITTED' OR (entitlement_version IS NOT NULL AND entitlement_version > 0 + AND allow_public_join IS NOT NULL + AND (allow_public_join IS TRUE OR (operation_representation_version = 2 AND outcome = 'ALREADY_ACTIVE')) + AND membership_id IS NOT NULL AND outcome_membership_version > 0 + AND outcome_membership_authority_generation > 0) +); + +ALTER TABLE account_join_operations + DROP CONSTRAINT account_join_operation_representation_check; + +ALTER TABLE account_join_operations ADD CONSTRAINT account_join_exact_first_transition_check CHECK ( + operation_representation_version <> 2 OR status <> 'COMMITTED' OR outcome <> 'JOINED' + OR ((membership_authority_outbox_sequence = 1 AND outcome_membership_version = 2 + AND outcome_membership_authority_generation = 1) + OR (membership_authority_outbox_sequence > 1 AND outcome_membership_version > 2)) +); + +ALTER TABLE account_join_operations + ADD CONSTRAINT account_join_operation_representation_check CHECK ( + (operation_representation_version = 1 AND scope_digest_version = 1 + AND target_class IS NULL AND account_uuid IS NULL AND tenant_uuid IS NULL + AND tenant_slug IS NULL AND playable_state_namespace_uuid IS NULL + AND game_instance_uuid IS NULL) + OR + (operation_representation_version = 2 AND scope_digest_version = 2 + AND request_id IS NOT NULL AND account_id IS NOT NULL + AND verified_caller_binding IS NOT NULL AND scope_token_hash IS NOT NULL + AND connect_scope_digest IS NOT NULL AND realm_id IS NOT NULL + AND world_slug IS NOT NULL AND realm_slug IS NOT NULL + AND playable_state_scope IS NOT NULL AND catalog_revision IS NOT NULL + AND pointer_version IS NOT NULL AND intent_digest_version = 2 + AND intent_digest ~ '^sha256:[0-9a-f]{64}$' + AND entitlement_authority_availability IS NOT NULL + AND last_attempt_authority_availability IS NOT NULL + AND caller_bound_authority_invalidated IS FALSE + AND btrim(request_id) <> '' AND verified_caller_binding <> '' + AND scope_token_hash ~ '^sha256:[0-9a-f]{64}$' + AND target_class = 'PUBLIC_PRODUCTION' + AND tenant_id IS NULL AND game_instance_id IS NULL + AND playable_state_namespace_id IS NULL + AND account_uuid IS NOT NULL + AND account_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND tenant_uuid IS NOT NULL + AND tenant_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND tenant_slug IS NOT NULL AND tenant_slug <> '' + AND realm_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND world_slug <> '' AND realm_slug <> '' + AND playable_state_namespace_uuid IS NOT NULL + AND playable_state_namespace_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND playable_state_scope IN ('SHARED', 'ISOLATED') + AND game_instance_uuid IS NOT NULL + AND game_instance_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND connect_scope_digest ~ '^sha256:[0-9a-f]{64}$' + AND ((status = 'PENDING' AND outcome IS NULL AND membership_id IS NULL + AND outcome_membership_version IS NULL + AND outcome_membership_authority_generation IS NULL) + OR (status = 'FAILED' AND outcome IS NOT NULL + AND outcome IN ('CONNECT_SCOPE_INVALID', 'CONNECT_SCOPE_MISMATCH', 'PUBLIC_PRODUCTION_ADMISSION_DENIED', 'TENANT_BILLING_BLOCKED', 'IDEMPOTENCY_CONFLICT', 'MEMBERSHIP_RECONCILIATION_REQUIRED', 'REALM_UNAVAILABLE') + AND membership_id IS NULL AND outcome_membership_version IS NULL + AND outcome_membership_authority_generation IS NULL) + OR (status = 'COMMITTED' AND outcome IN ('JOINED', 'ALREADY_ACTIVE') + AND membership_id IS NOT NULL AND membership_id > 0 + AND outcome_membership_version >= 2 + AND outcome_membership_authority_generation > 0))) + ); + +ALTER TABLE account_join_operations DROP CONSTRAINT account_join_canonical_terminal_proof_check; + +ALTER TABLE account_join_operations + ADD CONSTRAINT account_join_canonical_terminal_proof_check CHECK ( + (operation_representation_version = 1 + AND membership_authority_outbox_stream_key IS NULL + AND membership_authority_outbox_sequence IS NULL + AND membership_authority_event_id IS NULL + AND membership_authority_event_digest IS NULL + AND join_audit_event_id IS NULL + AND join_audit_payload_digest IS NULL + AND join_audit_occurred_at IS NULL) + OR (operation_representation_version = 2 AND status IN ('PENDING', 'FAILED') + AND ((status = 'PENDING' AND outcome IS NULL) + OR (status = 'FAILED' AND outcome IS NOT NULL AND outcome IN ('CONNECT_SCOPE_INVALID', 'CONNECT_SCOPE_MISMATCH', 'PUBLIC_PRODUCTION_ADMISSION_DENIED', 'TENANT_BILLING_BLOCKED', 'IDEMPOTENCY_CONFLICT', 'MEMBERSHIP_RECONCILIATION_REQUIRED', 'REALM_UNAVAILABLE'))) AND membership_id IS NULL + AND outcome_membership_version IS NULL + AND outcome_membership_authority_generation IS NULL + AND membership_authority_outbox_stream_key IS NULL + AND membership_authority_outbox_sequence IS NULL + AND membership_authority_event_id IS NULL + AND membership_authority_event_digest IS NULL + AND join_audit_event_id IS NULL + AND join_audit_payload_digest IS NULL + AND join_audit_occurred_at IS NULL) + OR (operation_representation_version = 2 AND status = 'COMMITTED' + AND outcome IN ('JOINED', 'ALREADY_ACTIVE') + AND membership_id IS NOT NULL AND membership_id > 0 + AND outcome_membership_version >= 2 + AND outcome_membership_authority_generation > 0 + AND membership_authority_outbox_stream_key IS NOT NULL + AND membership_authority_outbox_stream_key = + 'account:auth-authority:v1:membership/' || account_uuid::TEXT || '/' || tenant_uuid::TEXT + AND membership_authority_outbox_sequence IS NOT NULL + AND membership_authority_outbox_sequence > 0 + AND membership_authority_event_id IS NOT NULL + AND btrim(membership_authority_event_id) <> '' + AND membership_authority_event_digest IS NOT NULL + AND membership_authority_event_digest ~ '^sha256:[0-9a-f]{64}$' + AND ((outcome = 'ALREADY_ACTIVE' AND join_audit_event_id IS NULL + AND join_audit_payload_digest IS NULL AND join_audit_occurred_at IS NULL) + OR (outcome = 'JOINED' AND join_audit_event_id IS NOT NULL + AND join_audit_event_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND join_audit_payload_digest IS NOT NULL + AND join_audit_payload_digest ~ '^sha256:[0-9a-f]{64}$' + AND join_audit_occurred_at IS NOT NULL))) + ); + +CREATE OR REPLACE FUNCTION guard_account_join_operation_identity() RETURNS trigger AS $$ +DECLARE + scope_source_matches BOOLEAN := FALSE; + membership_matches BOOLEAN := FALSE; + pair_matches BOOLEAN := FALSE; + authority_event_matches BOOLEAN := FALSE; + audit_envelope_matches BOOLEAN := FALSE; +BEGIN + IF TG_OP = 'DELETE' THEN + IF OLD.operation_representation_version = 2 THEN + RAISE EXCEPTION 'Canonical JOIN operation evidence cannot be deleted' + USING ERRCODE = 'check_violation'; + END IF; + RETURN OLD; + END IF; + + IF TG_OP = 'INSERT' THEN + IF NEW.operation_representation_version = 1 THEN + RETURN NEW; + END IF; + IF NEW.operation_representation_version IS DISTINCT FROM 2 + OR NEW.scope_digest_version IS DISTINCT FROM 2 + OR NEW.intent_digest_version IS DISTINCT FROM 2 + OR NEW.status IS DISTINCT FROM 'PENDING' + OR NEW.outcome IS NOT NULL OR NEW.membership_id IS NOT NULL + OR NEW.outcome_membership_version IS NOT NULL + OR NEW.outcome_membership_authority_generation IS NOT NULL + OR NEW.membership_authority_outbox_stream_key IS NOT NULL + OR NEW.membership_authority_outbox_sequence IS NOT NULL + OR NEW.membership_authority_event_id IS NOT NULL + OR NEW.membership_authority_event_digest IS NOT NULL + OR NEW.join_audit_event_id IS NOT NULL + OR NEW.join_audit_payload_digest IS NOT NULL + OR NEW.join_audit_occurred_at IS NOT NULL + OR NEW.caller_bound_authority_invalidated IS DISTINCT FROM FALSE + OR NEW.entitlement_authority_availability IS DISTINCT FROM 'NOT_EVALUATED' + OR NEW.entitlement_version IS NOT NULL OR NEW.allow_public_join IS NOT NULL + OR NEW.request_digest_version IS NOT NULL OR NEW.request_digest IS NOT NULL + OR NEW.last_attempt_authority_availability IS DISTINCT FROM 'NOT_EVALUATED' + OR NEW.last_attempt_failure_code IS NOT NULL THEN + RAISE EXCEPTION 'Canonical JOIN operation must start as an exact pending intent' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT EXISTS ( + SELECT 1 FROM account_connect_scope_records scope_row + WHERE scope_row.scope_token_hash = NEW.scope_token_hash + AND scope_row.scope_digest_version = 2 + AND scope_row.snapshot_digest = NEW.connect_scope_digest + AND scope_row.account_id = NEW.account_id + AND scope_row.account_uuid = NEW.account_uuid + AND scope_row.target_class = NEW.target_class + AND scope_row.tenant_id IS NULL + AND scope_row.tenant_uuid = NEW.tenant_uuid + AND scope_row.tenant_slug = NEW.tenant_slug + AND scope_row.realm_id = NEW.realm_id + AND scope_row.world_slug = NEW.world_slug + AND scope_row.realm_slug = NEW.realm_slug + AND scope_row.playable_state_namespace_id IS NULL + AND scope_row.playable_state_namespace_uuid = NEW.playable_state_namespace_uuid + AND scope_row.playable_state_scope = NEW.playable_state_scope + AND scope_row.game_instance_id IS NULL + AND scope_row.game_instance_uuid = NEW.game_instance_uuid + AND scope_row.catalog_revision = NEW.catalog_revision + AND scope_row.pointer_version = NEW.pointer_version + ) INTO scope_source_matches; + IF NOT scope_source_matches THEN + RAISE EXCEPTION 'Canonical JOIN operation has no exact persisted scope source' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF OLD.operation_representation_version = 1 THEN + IF NEW.operation_representation_version IS DISTINCT FROM 1 THEN + RAISE EXCEPTION 'Retained JOIN operation evidence cannot change representation' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF OLD.operation_representation_version <> 2 + OR NEW.operation_representation_version IS DISTINCT FROM 2 + OR NEW.request_id IS DISTINCT FROM OLD.request_id + OR NEW.account_id IS DISTINCT FROM OLD.account_id + OR NEW.tenant_id IS DISTINCT FROM OLD.tenant_id + OR NEW.verified_caller_binding IS DISTINCT FROM OLD.verified_caller_binding + OR NEW.scope_token_hash IS DISTINCT FROM OLD.scope_token_hash + OR NEW.connect_scope_digest IS DISTINCT FROM OLD.connect_scope_digest + OR NEW.world_slug IS DISTINCT FROM OLD.world_slug + OR NEW.realm_slug IS DISTINCT FROM OLD.realm_slug + OR NEW.realm_id IS DISTINCT FROM OLD.realm_id + OR NEW.playable_state_namespace_id IS DISTINCT FROM OLD.playable_state_namespace_id + OR NEW.playable_state_scope IS DISTINCT FROM OLD.playable_state_scope + OR NEW.game_instance_id IS DISTINCT FROM OLD.game_instance_id + OR NEW.catalog_revision IS DISTINCT FROM OLD.catalog_revision + OR NEW.pointer_version IS DISTINCT FROM OLD.pointer_version + OR NEW.intent_digest_version IS DISTINCT FROM OLD.intent_digest_version + OR NEW.intent_digest IS DISTINCT FROM OLD.intent_digest + OR NEW.scope_digest_version IS DISTINCT FROM OLD.scope_digest_version + OR NEW.target_class IS DISTINCT FROM OLD.target_class + OR NEW.account_uuid IS DISTINCT FROM OLD.account_uuid + OR NEW.tenant_uuid IS DISTINCT FROM OLD.tenant_uuid + OR NEW.tenant_slug IS DISTINCT FROM OLD.tenant_slug + OR NEW.playable_state_namespace_uuid IS DISTINCT FROM OLD.playable_state_namespace_uuid + OR NEW.game_instance_uuid IS DISTINCT FROM OLD.game_instance_uuid + OR NEW.caller_bound_authority_invalidated IS DISTINCT FROM FALSE + OR NEW.created_at IS DISTINCT FROM OLD.created_at THEN + RAISE EXCEPTION 'Canonical JOIN operation intent evidence is immutable' + USING ERRCODE = 'check_violation'; + END IF; + + IF OLD.status IN ('COMMITTED', 'FAILED') THEN + RAISE EXCEPTION 'Terminal canonical JOIN receipt is immutable' + USING ERRCODE = 'check_violation'; + END IF; + IF OLD.status IS DISTINCT FROM 'PENDING' THEN + RAISE EXCEPTION 'Canonical JOIN operation has unsupported prior status' + USING ERRCODE = 'check_violation'; + END IF; + + IF OLD.request_digest IS NULL THEN + IF NEW.request_digest IS NOT NULL THEN + IF NEW.request_digest_version IS DISTINCT FROM 2 + OR NEW.entitlement_authority_availability IS DISTINCT FROM 'AVAILABLE' + OR NEW.entitlement_version IS NULL OR NEW.entitlement_version <= 0 + OR NEW.allow_public_join IS NULL + OR NEW.last_attempt_authority_availability IS DISTINCT FROM 'AVAILABLE' + OR NEW.last_attempt_failure_code IS NOT NULL THEN + RAISE EXCEPTION 'Canonical JOIN policy binding is incomplete' + USING ERRCODE = 'check_violation'; + END IF; + ELSIF NEW.status = 'FAILED' THEN + IF NEW.request_digest_version IS NOT NULL + OR NEW.entitlement_version IS NOT NULL OR NEW.allow_public_join IS NOT NULL + OR NEW.entitlement_authority_availability IS DISTINCT FROM 'NOT_EVALUATED' + OR NEW.last_attempt_authority_availability IS DISTINCT FROM 'NOT_EVALUATED' + OR NEW.last_attempt_failure_code IS NOT NULL THEN + RAISE EXCEPTION 'Unbound failed canonical JOIN cannot invent policy evidence' + USING ERRCODE = 'check_violation'; + END IF; + ELSIF NEW.request_digest_version IS NOT NULL + OR NEW.entitlement_version IS NOT NULL OR NEW.allow_public_join IS NOT NULL + OR NEW.entitlement_authority_availability NOT IN ('UNAVAILABLE', 'NOT_EVALUATED') + OR NEW.last_attempt_authority_availability IS DISTINCT FROM NEW.entitlement_authority_availability + OR NEW.last_attempt_failure_code IS NULL + OR NEW.last_attempt_failure_code NOT IN ('AUTH_UNAVAILABLE', 'ENTITLEMENT_UNAVAILABLE', 'ADMISSION_POINTER_UNAVAILABLE') THEN + RAISE EXCEPTION 'Canonical JOIN unavailable attempt cannot invent policy evidence' + USING ERRCODE = 'check_violation'; + END IF; + ELSE + IF NEW.request_digest IS DISTINCT FROM OLD.request_digest + OR NEW.request_digest_version IS DISTINCT FROM OLD.request_digest_version + OR NEW.entitlement_authority_availability IS DISTINCT FROM OLD.entitlement_authority_availability + OR NEW.entitlement_version IS DISTINCT FROM OLD.entitlement_version + OR NEW.allow_public_join IS DISTINCT FROM OLD.allow_public_join THEN + RAISE EXCEPTION 'Canonical JOIN available policy evidence is immutable' + USING ERRCODE = 'check_violation'; + END IF; + END IF; + + IF NEW.status = 'FAILED' THEN + IF NEW.outcome IS NULL OR NEW.outcome NOT IN ('CONNECT_SCOPE_INVALID', 'CONNECT_SCOPE_MISMATCH', 'PUBLIC_PRODUCTION_ADMISSION_DENIED', 'TENANT_BILLING_BLOCKED', 'IDEMPOTENCY_CONFLICT', 'MEMBERSHIP_RECONCILIATION_REQUIRED', 'REALM_UNAVAILABLE') + OR NEW.request_digest IS DISTINCT FROM OLD.request_digest + OR NEW.request_digest_version IS DISTINCT FROM OLD.request_digest_version + OR NEW.entitlement_version IS DISTINCT FROM OLD.entitlement_version + OR NEW.allow_public_join IS DISTINCT FROM OLD.allow_public_join + OR NEW.membership_id IS NOT NULL + OR NEW.outcome_membership_version IS NOT NULL + OR NEW.outcome_membership_authority_generation IS NOT NULL + OR NEW.membership_authority_outbox_stream_key IS NOT NULL + OR NEW.membership_authority_outbox_sequence IS NOT NULL + OR NEW.membership_authority_event_id IS NOT NULL + OR NEW.membership_authority_event_digest IS NOT NULL + OR NEW.join_audit_event_id IS NOT NULL + OR NEW.join_audit_payload_digest IS NOT NULL + OR NEW.join_audit_occurred_at IS NOT NULL + OR NEW.last_attempt_failure_code IS NOT NULL THEN + RAISE EXCEPTION 'Failed canonical JOIN must retain original policy and no success proof' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF NEW.status = 'PENDING' THEN + IF NEW.outcome IS NOT NULL OR NEW.membership_id IS NOT NULL + OR NEW.outcome_membership_version IS NOT NULL + OR NEW.outcome_membership_authority_generation IS NOT NULL + OR NEW.membership_authority_outbox_stream_key IS NOT NULL + OR NEW.membership_authority_outbox_sequence IS NOT NULL + OR NEW.membership_authority_event_id IS NOT NULL + OR NEW.membership_authority_event_digest IS NOT NULL + OR NEW.join_audit_event_id IS NOT NULL + OR NEW.join_audit_payload_digest IS NOT NULL + OR NEW.join_audit_occurred_at IS NOT NULL THEN + RAISE EXCEPTION 'Pending canonical JOIN cannot carry terminal receipt evidence' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF NEW.status IS DISTINCT FROM 'COMMITTED' + OR NEW.outcome IS NULL OR NEW.outcome NOT IN ('JOINED', 'ALREADY_ACTIVE') + OR NEW.entitlement_authority_availability IS DISTINCT FROM 'AVAILABLE' + OR (NEW.outcome = 'JOINED' AND NEW.allow_public_join IS DISTINCT FROM TRUE) + OR NEW.allow_public_join IS NULL + OR NEW.entitlement_version IS NULL OR NEW.entitlement_version <= 0 + OR NEW.request_digest_version IS DISTINCT FROM 2 + OR NEW.request_digest IS NULL + OR NEW.request_digest !~ '^sha256:[0-9a-f]{64}$' + OR NEW.last_attempt_failure_code IS NOT NULL + OR NEW.last_attempt_authority_availability IS DISTINCT FROM 'AVAILABLE' + OR NEW.membership_id IS NULL + OR NEW.outcome_membership_version IS NULL OR NEW.outcome_membership_version < 2 + OR NEW.outcome_membership_authority_generation IS NULL OR NEW.outcome_membership_authority_generation <= 0 + OR NEW.membership_authority_outbox_stream_key IS NULL + OR NEW.membership_authority_outbox_sequence IS NULL OR NEW.membership_authority_outbox_sequence <= 0 + OR NEW.membership_authority_event_id IS NULL + OR NEW.membership_authority_event_digest IS NULL + OR NEW.membership_authority_event_digest !~ '^sha256:[0-9a-f]{64}$' + OR (NEW.outcome = 'JOINED' AND (NEW.join_audit_event_id IS NULL + OR NEW.join_audit_payload_digest IS NULL + OR NEW.join_audit_payload_digest !~ '^sha256:[0-9a-f]{64}$' + OR NEW.join_audit_occurred_at IS NULL)) + OR (NEW.outcome = 'ALREADY_ACTIVE' AND (NEW.join_audit_event_id IS NOT NULL + OR NEW.join_audit_payload_digest IS NOT NULL OR NEW.join_audit_occurred_at IS NOT NULL)) THEN + RAISE EXCEPTION 'Canonical JOIN terminal receipt is incomplete or noncommitting' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT EXISTS ( + SELECT 1 FROM account_tenant_membership membership + WHERE membership.id = NEW.membership_id + AND membership.account_id = NEW.account_id + AND membership.tenant_uuid = NEW.tenant_uuid + AND membership.tenant_id IS NULL + AND membership.tenant_provenance_kind = 'FRESH_GAME_DESIGN' + AND membership.lifecycle_state = 'ACTIVE' + AND (NEW.outcome = 'ALREADY_ACTIVE' OR membership.gameplay_admission_allowed IS TRUE) + AND (NEW.outcome = 'ALREADY_ACTIVE' OR membership.authority_provenance = 'EXPLICIT_JOIN') + AND membership.membership_version = NEW.outcome_membership_version + AND membership.membership_authority_generation = + NEW.outcome_membership_authority_generation + ) INTO membership_matches; + + SELECT EXISTS ( + SELECT 1 FROM account_membership_pair_authority pair + JOIN account_tenant_membership membership + ON membership.id = NEW.membership_id + WHERE pair.account_uuid = NEW.account_uuid + AND pair.tenant_uuid = NEW.tenant_uuid + AND pair.membership_exists IS TRUE + AND pair.membership_version = NEW.outcome_membership_version + AND pair.membership_authority_generation = + NEW.outcome_membership_authority_generation + AND pair.last_event_sequence = NEW.membership_authority_outbox_sequence + AND pair.last_event_id = NEW.membership_authority_event_id + AND pair.last_event_digest = NEW.membership_authority_event_digest + AND (NEW.outcome = 'ALREADY_ACTIVE' OR pair.last_transition_invalidated IS FALSE) + AND pair.tenant_provenance_kind = membership.tenant_provenance_kind + AND pair.tenant_source_operation_id = membership.tenant_source_operation_id + AND pair.tenant_provenance_digest = membership.tenant_provenance_digest + ) INTO pair_matches; + + SELECT EXISTS ( + SELECT 1 FROM account_authority_outbox_events event + JOIN account_authority_outbox_streams stream + ON stream.outbox_stream_key = event.outbox_stream_key + JOIN account_tenant_membership membership ON membership.id = NEW.membership_id + JOIN account_tenant_membership_role_snapshots role_header + ON role_header.membership_id = membership.id + AND role_header.snapshot_version = membership.membership_version + WHERE event.outbox_stream_key = NEW.membership_authority_outbox_stream_key + AND event.outbox_sequence = NEW.membership_authority_outbox_sequence + AND ((NEW.outcome = 'ALREADY_ACTIVE' AND event.request_id <> NEW.request_id) + OR (NEW.outcome = 'JOINED' AND event.request_id = NEW.request_id)) + AND event.event_id = NEW.membership_authority_event_id + AND event.event_digest = NEW.membership_authority_event_digest + AND stream.last_sequence = NEW.membership_authority_outbox_sequence + AND convert_from(event.payload, 'UTF8')::JSONB ->> 'accountId' = NEW.account_uuid::TEXT + AND convert_from(event.payload, 'UTF8')::JSONB ->> 'tenantId' = NEW.tenant_uuid::TEXT + AND convert_from(event.payload, 'UTF8')::JSONB ->> 'membershipLifecycleState' = 'ACTIVE' + AND convert_from(event.payload, 'UTF8')::JSONB -> 'membershipVersion' ->> NEW.tenant_uuid::TEXT = NEW.outcome_membership_version::TEXT + AND convert_from(event.payload, 'UTF8')::JSONB ->> 'membershipAuthorityGeneration' = NEW.outcome_membership_authority_generation::TEXT + AND (convert_from(event.payload, 'UTF8')::JSONB ->> 'gameplayAdmissionAllowed')::BOOLEAN = membership.gameplay_admission_allowed + AND convert_from(event.payload, 'UTF8')::JSONB -> 'roles' = COALESCE(( + SELECT jsonb_agg(role_identifier ORDER BY convert_to(role_identifier, 'UTF8')) + FROM account_tenant_membership_role_snapshot_roles roles + WHERE roles.membership_id = membership.id AND roles.snapshot_version = membership.membership_version + ), '[]'::JSONB) + ) INTO authority_event_matches; + + SELECT EXISTS ( + SELECT 1 FROM account_audit_outbox audit + WHERE audit.audit_event_id = NEW.join_audit_event_id + AND audit.scope = 'tenant' + AND audit.tenant_identity_version = 2 + AND audit.tenant_id IS NULL + AND audit.tenant_uuid = NEW.tenant_uuid + AND audit.producer_service = 'account-service' + AND audit.event_type = 'ACCOUNT_JOINED_PUBLIC_PRODUCTION' + AND audit.schema_version = 1 + AND audit.payload_digest_version = 1 + AND audit.payload_digest = NEW.join_audit_payload_digest + AND audit.occurred_at = NEW.join_audit_occurred_at + AND audit.delivery_status = 'PENDING' + AND audit.payload IS NOT NULL + AND audit.payload::JSONB ->> 'accountId' = NEW.account_uuid::TEXT + AND audit.payload::JSONB ->> 'tenantId' = NEW.tenant_uuid::TEXT + AND audit.payload::JSONB ->> 'requestId' = NEW.request_id + AND audit.payload::JSONB ->> 'worldSlug' = NEW.world_slug + AND audit.payload::JSONB ->> 'realmSlug' = NEW.realm_slug + AND audit.payload::JSONB ->> 'membershipVersion' = NEW.outcome_membership_version::TEXT + AND audit.payload::JSONB ->> 'membershipAuthorityGeneration' = NEW.outcome_membership_authority_generation::TEXT + AND audit.payload::JSONB ->> 'membershipEventStreamKey' = + NEW.membership_authority_outbox_stream_key + AND audit.payload::JSONB ->> 'membershipEventSequence' = + NEW.membership_authority_outbox_sequence::TEXT + AND audit.payload::JSONB ->> 'membershipEventId' = NEW.membership_authority_event_id + AND audit.payload::JSONB ->> 'membershipEventDigest' = + NEW.membership_authority_event_digest + AND audit.payload::JSONB ->> 'joinIntentDigest' = NEW.intent_digest + AND audit.payload::JSONB ->> 'joinRequestDigest' = NEW.request_digest + AND audit.payload::JSONB ->> 'allowPublicJoin' = 'true' + AND audit.payload::JSONB ->> 'entitlementVersion' = NEW.entitlement_version::TEXT + ) INTO audit_envelope_matches; + + IF NOT membership_matches OR NOT pair_matches OR NOT authority_event_matches + OR (NEW.outcome = 'JOINED' AND NOT audit_envelope_matches) THEN + RAISE EXCEPTION 'Canonical JOIN terminal receipt does not match committed owner evidence' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +/* [jooq ignore stop] */ diff --git a/services/account-service/src/main/resources/db/migration/V1039__hosting_unclaimed_wallet_settlement.sql b/services/account-service/src/main/resources/db/migration/V1039__hosting_unclaimed_wallet_settlement.sql new file mode 100644 index 0000000000..fcd77e4828 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1039__hosting_unclaimed_wallet_settlement.sql @@ -0,0 +1,10 @@ +-- A wallet observation can invalidate dispatch before the first worker claim. Retain a terminal +-- operator item without asserting provider absence, canceling the intent, or releasing its hold. +-- [jooq ignore start] +ALTER TABLE subscription_provisioning_operator_outbox + DROP CONSTRAINT subscription_provisioning_operator_outbox_reason_check; +ALTER TABLE subscription_provisioning_operator_outbox + ADD CONSTRAINT subscription_provisioning_operator_outbox_reason_check + CHECK (reason IN ('ABSOLUTE_DEADLINE', 'ATTEMPT_BUDGET', + 'STALLED_WITHOUT_COMMITTED_PROGRESS', 'RESERVED_INSTRUMENT_CHANGED')); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/openapi.yaml b/services/account-service/src/main/resources/openapi.yaml index 4745356dd3..09cc4c7e7e 100644 --- a/services/account-service/src/main/resources/openapi.yaml +++ b/services/account-service/src/main/resources/openapi.yaml @@ -182,15 +182,20 @@ components: type: boolean BootstrapWorldDto: type: object + description: Tenant-qualified world selector; worldSlug is not globally unique. + required: [tenantSlug, worldSlug, displayName] properties: + tenantSlug: + type: string worldSlug: type: string displayName: type: string BootstrapRealmDto: type: object + description: Public realm selector evidence; the retained scope does not grant entry or character access. required: - [worldSlug, realmSlug, realmId, catalogRevision, playableStateNamespaceId, playableStateScope] + [worldSlug, realmSlug, realmId, tenantId, gameInstanceId, catalogRevision, playableStateNamespaceId, playableStateScope] properties: worldSlug: type: string @@ -202,9 +207,11 @@ components: displayName: type: string tenantId: - type: integer + type: string + format: uuid gameInstanceId: - type: integer + type: string + format: uuid pointerVersion: type: integer catalogRevision: @@ -217,8 +224,6 @@ components: playableStateScope: type: string enum: [PLAYABLE_STATE_SCOPE_SHARED, PLAYABLE_STATE_SCOPE_ISOLATED] - requiresCharacterSelection: - type: boolean stateScope: type: string enum: [SHARED, ISOLATED] @@ -233,13 +238,27 @@ components: description: Opaque signed scope with canonical UUID Account identity; obtain fresh scope through discovery rather than interpreting its payload. BootstrapCharacterDto: type: object + description: Persisted, non-admitting actor discovery for the current public SHARED PRESEEDED_ONLY target. + required: [characterId, characterName, level, stateScope, characterCreationPolicy] properties: characterId: type: string + format: uuid characterName: type: string + minLength: 1 + maxLength: 100 level: type: integer + format: int32 + minimum: 0 + description: Actual persisted Entity level from the same eligible actor row. + stateScope: + type: string + enum: [SHARED] + characterCreationPolicy: + type: string + enum: [PRESEEDED_ONLY] ResultStatus: type: string enum: [SUCCESS, ERROR] @@ -421,7 +440,7 @@ paths: $ref: '#/components/responses/RetryableAuthenticationUnavailable' /auth/bootstrap/worlds/{worldSlug}/realms: get: - summary: List caller-visible realms for a selected world + summary: List caller-visible realms for a tenant-qualified world operationId: listBootstrapRealms security: - bearerAuth: [] @@ -431,6 +450,12 @@ paths: required: true schema: type: string + - in: query + name: tenantSlug + required: true + description: Tenant selector from the selected BootstrapWorldDto; required because worldSlug is tenant-scoped. + schema: + type: string responses: '200': description: Visible realms 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 cb6e7bc04c..ed7fc5ed23 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 @@ -8,32 +8,86 @@ import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Duration; import java.time.Instant; import java.time.LocalDateTime; import java.util.List; +import java.util.Map; +import java.util.Objects; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; +import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; import net.firedevops.firemud.accountservice.client.EntityManagementClient; import net.firedevops.firemud.accountservice.client.GameSessionClient; import net.firedevops.firemud.accountservice.client.LoggingAdminClient; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; +import net.firedevops.firemud.accountservice.config.AccountTokenProperties; +import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; +import net.firedevops.firemud.accountservice.dto.AccountSecurityStateMutationRequest; import net.firedevops.firemud.accountservice.dto.CreateAccountRequest; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; import net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget; import net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest; import net.firedevops.firemud.accountservice.dto.JoinPublicProductionResult; import net.firedevops.firemud.accountservice.dto.VerifyEmailRequest; +import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.entity.AccountLoginAuthModes; +import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository.Capture; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantIdentityResolver; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.service.AccountCanonicalConnectScopeReader; +import net.firedevops.firemud.accountservice.service.AccountCanonicalFirstJoinTerminalCoordinator; +import net.firedevops.firemud.accountservice.service.AccountCanonicalPublicRealmScopeOwner; +import net.firedevops.firemud.accountservice.service.AccountHostingSubscriptionLifecycleService; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer; +import net.firedevops.firemud.accountservice.service.AccountPublicBootstrapEntitlementOwner; +import net.firedevops.firemud.accountservice.service.AccountPublicBootstrapWorldsOwner; import net.firedevops.firemud.accountservice.service.AccountService; import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import net.firedevops.firemud.accountservice.service.session.AccountPlayerBootstrapCallerVerifier; +import net.firedevops.firemud.accountservice.service.session.SessionService; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec.AccountState; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target; import net.firedevops.firemud.common.security.HttpAuthProperties; import net.firedevops.firemud.common.security.HttpAuthRoleRequirement; import net.firedevops.firemud.common.security.HttpJwtAuthInterceptor; import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import net.firedevops.firemud.test.GatewayTestProperties; import net.firedevops.firemud.test.HttpTestSupport; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; @@ -90,9 +144,12 @@ static void configure(DynamicPropertyRegistry registry) { } @LocalServerPort private int port; + @Autowired private javax.sql.DataSource dataSource; @Autowired private JwtUtil jwtUtil; @Autowired private DSLContext dsl; @Autowired private AccountService accountService; + @Autowired private AccountServiceImpl canonicalFacade; + @Autowired private SessionService realAccountSessions; @Autowired private HttpAuthProperties httpAuthProperties; @Autowired private ObjectProvider httpJwtAuthInterceptorProvider; @@ -103,18 +160,6 @@ static void configure(DynamicPropertyRegistry registry) { private net.firedevops.firemud.accountservice.repository.EmailVerificationTokenRepository emailVerificationTokenRepository; - @org.springframework.test.context.bean.override.mockito.MockitoSpyBean - private net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository - joinOperationRepository; - - @org.springframework.test.context.bean.override.mockito.MockitoSpyBean - private net.firedevops.firemud.accountservice.repository.SubscriptionRepository - subscriptionRepository; - - @Autowired - private net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository - connectScopeRepository; - @Autowired private org.springframework.transaction.PlatformTransactionManager transactionManager; @Autowired @@ -410,653 +455,1847 @@ private List emailVerificationState(EmailVerificationFixture fixture) { private record EmailVerificationFixture(long accountId, String token) {} @Test - void publicJoinLostCommitAcknowledgementAndReadbackReplayTheSameOriginalOnce() { - var fixture = publicJoinFixture(); - var readbackDropped = losePublicJoinTerminalResponse(fixture); - - assertPublicJoinUnavailable(fixture); - - assertThat(readbackDropped).isTrue(); - assertPublicJoinCommittedOnce(fixture); - var committed = publicJoinState(fixture); - var replay = publicJoin(fixture); - + void publicJoinBrowserAndDirectScopesUseActualUuidIntentMembershipEventAndAuditOwners() + throws Exception { + var f = publicJoinFixture(false); + var worlds = f.service.listBootstrapWorlds(f.bootstrap); + assertThat(worlds).extracting(value -> value.worldSlug()).containsExactly(f.target.worldSlug()); + var browser = f.browserScope(); + var direct = f.directScope(); + for (String token : List.of(browser, direct)) { + var claims = f.jwt.parseToken(token).getPayload(); + assertThat(claims.getSubject()).isEqualTo(f.account.getAccountUuid().toString()); + assertThat(claims.get("tenantId")).isEqualTo(f.tenantId.toString()); + assertThat(claims.get("gameInstanceId")) + .isEqualTo(f.target.canonicalGameInstanceId().toString()); + var retained = + f.in( + () -> + f.scopes + .findCanonicalEvidenceByTokenHash(AccountJoinDigest.tokenHash(token)) + .orElseThrow()); + assertThat(retained.privateAccountId()).isEqualTo(f.account.getId()); + assertThat(retained.scopeDigestVersion()).isEqualTo(2); + assertThat(retained.tenantUuid()).isEqualTo(f.tenantId); + assertThat(f.in(() -> f.scopes.find(token))).isEmpty(); + } + for (String token : List.of(browser, direct)) { + assertThatThrownBy( + () -> + f.service.issueConnectToken( + f.bootstrap, + new net.firedevops.firemud.accountservice.dto.ConnectTokenRequest( + token, "held-issuer"))) + .isInstanceOf(AuthenticationException.class) + .extracting(value -> ((AuthenticationException) value).getCode()) + .isEqualTo("AUTH_UNAVAILABLE"); + } + String request = UUID.randomUUID().toString(); + var first = f.join(browser, request); + assertThat(first.success()).isTrue(); + assertThat(first.accountId()).isEqualTo(f.account.getAccountUuid().toString()); + assertThat(first.tenantId()).isEqualTo(f.tenantId); + assertThat(first.membershipVersion()).isEqualTo(2L); + assertThat(first.membershipAuthorityGeneration()).isEqualTo(1L); + org.mockito.Mockito.verify(f.targets, org.mockito.Mockito.times(2)) + .readPublishedRealmAdmissionOwner(org.mockito.ArgumentMatchers.any()); + var committed = f.state(request); + var replay = f.join(browser, request); assertThat(replay.success()).isTrue(); assertThat(replay.replayed()).isTrue(); - assertThat(replay.outcomeCode()).isEqualTo("JOINED"); - assertThat(replay.accountId()).isEqualTo(fixture.accountUuid()); - assertPublicJoinCommittedOnce(fixture); - assertThat(publicJoinState(fixture)).isEqualTo(committed); + assertThat(replay.membershipId()).isEqualTo(first.membershipId()); + assertThat(f.state(request)).isEqualTo(committed); + f.assertTransitionCount(1L); + var active = f.directJoin(direct, UUID.randomUUID().toString()); + assertThat(active.success()).isTrue(); + assertThat(active.outcomeCode()).isEqualTo("ALREADY_ACTIVE"); + assertThat(active.membershipVersion()).isEqualTo(first.membershipVersion()); + assertThat(active.membershipAuthorityGeneration()) + .isEqualTo(first.membershipAuthorityGeneration()); + f.assertTransitionCount(1L); } @Test - void publicJoinFailureBeforeCommitRollsBackEffectsAndContinuesTheOriginalIntent() { - var fixture = publicJoinFixture(); - var failOnce = new AtomicBoolean(true); - org.mockito.Mockito.doAnswer( - invocation -> { - invocation.callRealMethod(); - if (failOnce.compareAndSet(true, false)) { - // The real terminal UPDATE ran, but its owner transaction has not committed. - throw new IllegalStateException("Injected failure before public JOIN commit"); - } - return null; - }) - .when(joinOperationRepository) - .finish( - org.mockito.ArgumentMatchers.eq(fixture.caller().requestId()), - org.mockito.ArgumentMatchers.eq("COMMITTED"), - org.mockito.ArgumentMatchers.eq("JOINED"), - org.mockito.ArgumentMatchers.any(), - org.mockito.ArgumentMatchers.any(), - org.mockito.ArgumentMatchers.any()); - - assertPublicJoinUnavailable(fixture); - - assertThat(failOnce).isFalse(); - var pending = - dsl.fetchOne( - "SELECT status, outcome, intent_digest, request_digest, membership_id " - + "FROM account_join_operations WHERE request_id = ?", - fixture.caller().requestId()); - assertThat(pending).isNotNull(); - assertThat(pending.get("status", String.class)).isEqualTo("PENDING"); - assertThat(pending.get("intent_digest", String.class)).startsWith("sha256:"); - assertThat(pending.get("outcome")).isNull(); - assertThat(pending.get("request_digest")).isNull(); - assertThat(pending.get("membership_id")).isNull(); - assertThat(publicJoinMembershipCount(fixture)).isZero(); - assertThat(publicJoinAuditCount(fixture)).isZero(); - - var continued = publicJoin(fixture); - - assertThat(continued.success()).isTrue(); - assertThat(continued.replayed()).isFalse(); - assertThat(continued.outcomeCode()).isEqualTo("JOINED"); - assertPublicJoinCommittedOnce(fixture); - assertThat(publicJoin(fixture).replayed()).isTrue(); - assertPublicJoinCommittedOnce(fixture); + void publicJoinPaidOwnerUsesRealProvisioningCurrentRowFenceAndSealedStripeObservation() { + var f = publicJoinFixture(true); + String token = f.browserScope(); + int reads = f.paid.transport().reads(); + String request = UUID.randomUUID().toString(); + var first = f.join(token, request); + assertThat(first.success()).isTrue(); + assertThat(f.paid.transport().reads()).isGreaterThan(reads); + f.assertTransitionCount(1L); + assertThat(f.operation(request).operationRepresentationVersion()).isEqualTo(2); + assertThat(f.operation(request).entitlementVersion()).isPositive(); + assertThat(f.operation(request).terminalProof().entitlementVersion()) + .isEqualTo(f.operation(request).entitlementVersion()); } @Test - void publicJoinLostResponseThenExpiredScopePreservesTheCompleteCommittedOriginal() { - var fixture = publicJoinFixture(); - var readbackDropped = losePublicJoinTerminalResponse(fixture); - assertPublicJoinUnavailable(fixture); - assertThat(readbackDropped).isTrue(); - assertPublicJoinCommittedOnce(fixture); - var committed = publicJoinState(fixture); - String retainedExpiry = - dsl.resultQuery( - "SELECT s.connect_scope_expires_at FROM account_connect_scope_records s " - + "JOIN account_join_operations j ON j.scope_token_hash = s.scope_token_hash " - + "WHERE j.request_id = ?", - fixture.caller().requestId()) - .fetchOne(0, String.class); - assertThat(retainedExpiry).isNotBlank(); - Instant expiredNow = Instant.parse(retainedExpiry).plusSeconds(1); - - // Advance only the owner clock; never rewrite the original scope, intent or terminal row. - try (org.mockito.MockedStatic clock = - org.mockito.Mockito.mockStatic(Instant.class, org.mockito.Mockito.CALLS_REAL_METHODS)) { - clock.when(Instant::now).thenReturn(expiredNow); - var refused = publicJoin(fixture); - assertThat(refused.success()).isFalse(); - assertThat(refused.replayed()).isFalse(); - assertThat(refused.outcomeCode()).isEqualTo("CONNECT_SCOPE_INVALID"); - } - - assertThat(publicJoinState(fixture)).isEqualTo(committed); - assertPublicJoinCommittedOnce(fixture); - } - - @org.junit.jupiter.params.ParameterizedTest - @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) - void publicJoinUnavailableSubscriptionRetainsOriginalAndRecoversOnce(boolean ambiguous) { - var fixture = publicJoinFixture(); - var originalEvidence = publicJoinOriginalEvidence(fixture); - if (ambiguous) { - var duplicate = new net.firedevops.firemud.accountservice.entity.Subscription(); - duplicate.setAccount(accountRepository.findById(fixture.accountId()).orElseThrow()); - duplicate.setTenantId(fixture.tenantId()); - duplicate.setPlanId("join-proof-duplicate"); - duplicate.setStatus("active"); - subscriptionRepository.save(duplicate); - } else { - subscriptionRepository.deleteByAccountId(fixture.accountId(), fixture.tenantId()); - } - assertThat(subscriptionRepository.findByTenantId(fixture.tenantId())) - .hasSize(ambiguous ? 2 : 0); - - var unavailable = publicJoin(fixture); - - assertThat(unavailable.success()).isFalse(); - assertThat(unavailable.replayed()).isFalse(); - assertThat(unavailable.accountId()).isEqualTo(fixture.accountUuid()); - assertThat(unavailable.outcomeCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); - assertPublicJoinUnboundPending(fixture, "ENTITLEMENT_UNAVAILABLE", "UNAVAILABLE"); - String originalIntent = - joinOperationRepository.find(fixture.caller().requestId()).orElseThrow().intentDigest(); - assertThat(publicJoinOriginalEvidence(fixture)).isEqualTo(originalEvidence); - - var stillUnavailable = publicJoin(fixture); - assertThat(stillUnavailable.outcomeCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); - assertPublicJoinUnboundPending(fixture, "ENTITLEMENT_UNAVAILABLE", "UNAVAILABLE"); - assertThat( - joinOperationRepository.find(fixture.caller().requestId()).orElseThrow().intentDigest()) - .isEqualTo(originalIntent); - - // Restore explicit unique authority through the real repository, not a synthetic read result. - subscriptionRepository.deleteByAccountId(fixture.accountId(), fixture.tenantId()); - var restored = new net.firedevops.firemud.accountservice.entity.Subscription(); - restored.setAccount(accountRepository.findById(fixture.accountId()).orElseThrow()); - restored.setTenantId(fixture.tenantId()); - restored.setPlanId("join-proof-recovered"); - restored.setStatus("active"); - subscriptionRepository.save(restored); - assertThat(subscriptionRepository.findByTenantId(fixture.tenantId())).hasSize(1); - - var recovered = publicJoin(fixture); - assertThat(recovered.success()).isTrue(); - assertThat(recovered.replayed()).isFalse(); - assertThat(recovered.accountId()).isEqualTo(fixture.accountUuid()); - assertPublicJoinCommittedOnce(fixture); - assertThat( - joinOperationRepository.find(fixture.caller().requestId()).orElseThrow().intentDigest()) - .isEqualTo(originalIntent); - assertThat(publicJoinOriginalEvidence(fixture)).isEqualTo(originalEvidence); - var committed = publicJoinState(fixture); - assertThat(publicJoin(fixture).replayed()).isTrue(); - assertPublicJoinCommittedOnce(fixture); - assertThat(publicJoinState(fixture)).isEqualTo(committed); + void publicJoinStrictPublishedWorldSourceOutageCannotCommitFromResolverOnlyEvidence() { + var f = publicJoinFixture(false); + String token = f.browserScope(); + String request = UUID.randomUUID().toString(); + org.mockito.Mockito.when( + f.targets.readPublishedRealmAdmissionOwner(org.mockito.ArgumentMatchers.any())) + .thenThrow( + new IllegalStateException("controlled strict published/World ACTIVE source outage")); + assertThatThrownBy(() -> f.join(token, request)) + .isInstanceOf(AuthenticationException.class) + .extracting(value -> ((AuthenticationException) value).getCode()) + .isEqualTo("ADMISSION_POINTER_UNAVAILABLE"); + assertThat(f.operation(request).status()).isEqualTo("PENDING"); + assertThat(f.operation(request).lastAttemptFailureCode()) + .isEqualTo("ADMISSION_POINTER_UNAVAILABLE"); + assertThat(f.membershipCount()).isZero(); + f.assertTransitionCount(0L); } @Test - void publicJoinActualSqlAbortAtLockedReadRollsBackPolicyAndContinuesOriginalOnce() { - var fixture = publicJoinFixture(); - var originalEvidence = publicJoinOriginalEvidence(fixture); - var failOnce = new AtomicBoolean(true); - var rolledBack = new AtomicBoolean(); - var diagnosticWritten = new AtomicBoolean(); - var originalSqlFailure = new java.util.concurrent.atomic.AtomicReference(); + void publicJoinFailureBeforeCommitRollsBackMembershipPairEventAuditAndTerminalReceipt() { + var f = publicJoinFixture(false); + String token = f.browserScope(); + String request = UUID.randomUUID().toString(); + var failed = new AtomicBoolean(); org.mockito.Mockito.doAnswer( invocation -> { - assertThat(rolledBack).isTrue(); - assertThat( - org.springframework.transaction.support.TransactionSynchronizationManager - .isActualTransactionActive()) - .isTrue(); - invocation.callRealMethod(); - diagnosticWritten.set(true); - return null; + var result = invocation.callRealMethod(); + if (failed.compareAndSet(false, true)) + throw new IllegalStateException("controlled terminal rollback"); + return result; }) - .when(joinOperationRepository) - .recordAttemptFailure( - fixture.caller().requestId(), "UNAVAILABLE", "ENTITLEMENT_UNAVAILABLE"); + .when(f.operations) + .commitCanonicalJoin( + org.mockito.ArgumentMatchers.eq(request), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any()); + assertThatThrownBy(() -> f.join(token, request)).isInstanceOf(AuthenticationException.class); + assertThat(f.operation(request).status()).isEqualTo("PENDING"); + assertThat(f.operation(request).terminalProof()).isNull(); + assertThat(f.operation(request).requestDigest()).isNull(); + f.assertTransitionCount(0L); + assertThat(f.membershipCount()).isZero(); + String intent = f.operation(request).intentDigest(); + assertThat(f.join(token, request).success()).isTrue(); + assertThat(f.operation(request).intentDigest()).isEqualTo(intent); + f.assertTransitionCount(1L); + } + + @Test + void publicJoinLostCommitAcknowledgementReplaysTheCompleteCommittedOriginal() { + var f = publicJoinFixture(false); + String token = f.browserScope(); + String request = UUID.randomUUID().toString(); + var lost = new AtomicBoolean(); org.mockito.Mockito.doAnswer( invocation -> { - var lockedRows = invocation.callRealMethod(); - if (failOnce.compareAndSet(true, false)) { - assertThat( - org.springframework.transaction.support.TransactionSynchronizationManager - .isActualTransactionActive()) - .isTrue(); - // The initial available read and real policy UPDATE have already run in this tx. - var transientPolicy = - joinOperationRepository.find(fixture.caller().requestId()).orElseThrow(); - assertThat(transientPolicy.entitlementAuthorityAvailability()) - .isEqualTo("AVAILABLE"); - assertThat(transientPolicy.allowPublicJoin()).isTrue(); - assertThat(transientPolicy.entitlementVersion()).isEqualTo(1L); - assertThat(transientPolicy.requestDigest()).startsWith("sha256:"); - var independentRead = new TransactionTemplate(transactionManager); - independentRead.setPropagationBehavior( - org.springframework.transaction.TransactionDefinition.PROPAGATION_REQUIRES_NEW); - independentRead.executeWithoutResult( - status -> { - var committedIntent = - joinOperationRepository.find(fixture.caller().requestId()).orElseThrow(); - assertThat(committedIntent.status()).isEqualTo("PENDING"); - assertThat(committedIntent.requestDigest()).isNull(); - assertThat(committedIntent.intentDigest()) - .isEqualTo(transientPolicy.intentDigest()); - }); + var result = invocation.callRealMethod(); + if (lost.compareAndSet(false, true)) { org.springframework.transaction.support.TransactionSynchronizationManager .registerSynchronization( new org.springframework.transaction.support.TransactionSynchronization() { @Override - public void afterCompletion(int status) { - rolledBack.set(status == STATUS_ROLLED_BACK); + public void afterCommit() { + throw new IllegalStateException( + "controlled lost commit acknowledgement"); } }); - try { - // A real PostgreSQL error poisons this physical owner transaction; no savepoint. - dsl.fetch("SELECT 1 / 0"); - throw new AssertionError("PostgreSQL division by zero must fail"); - } catch (org.jooq.exception.DataAccessException - | org.springframework.dao.DataAccessException ex) { - originalSqlFailure.set(ex); - throw ex; - } } - return lockedRows; + return result; }) - .when(subscriptionRepository) - .findByTenantIdForUpdate(fixture.tenantId()); - - var unavailable = publicJoin(fixture); - - assertThat(unavailable.success()).isFalse(); - assertThat(unavailable.replayed()).isFalse(); - assertThat(unavailable.outcomeCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); - assertThat(originalSqlFailure.get()).isNotNull(); - assertThat(sqlState(originalSqlFailure.get())).isEqualTo("22012"); - assertThat(rolledBack).isTrue(); - assertThat(diagnosticWritten).isTrue(); - org.mockito.Mockito.verify(joinOperationRepository) - .recordAttemptFailure( - fixture.caller().requestId(), "UNAVAILABLE", "ENTITLEMENT_UNAVAILABLE"); - assertPublicJoinUnboundPending(fixture, "ENTITLEMENT_UNAVAILABLE", "UNAVAILABLE"); - String originalIntent = - joinOperationRepository.find(fixture.caller().requestId()).orElseThrow().intentDigest(); - assertThat(publicJoinOriginalEvidence(fixture)).isEqualTo(originalEvidence); - - var recovered = publicJoin(fixture); - assertThat(recovered.success()).isTrue(); - assertThat(recovered.replayed()).isFalse(); - assertThat(recovered.accountId()).isEqualTo(fixture.accountUuid()); - assertPublicJoinCommittedOnce(fixture); - assertThat( - joinOperationRepository.find(fixture.caller().requestId()).orElseThrow().intentDigest()) - .isEqualTo(originalIntent); - assertThat(publicJoinOriginalEvidence(fixture)).isEqualTo(originalEvidence); - var committed = publicJoinState(fixture); - assertThat(publicJoin(fixture).replayed()).isTrue(); - assertPublicJoinCommittedOnce(fixture); - assertThat(publicJoinState(fixture)).isEqualTo(committed); + .when(f.operations) + .commitCanonicalJoin( + org.mockito.ArgumentMatchers.eq(request), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any()); + assertThatThrownBy(() -> f.join(token, request)).isInstanceOf(AuthenticationException.class); + assertThat(f.operation(request).status()).isEqualTo("COMMITTED"); + var committed = f.state(request); + var replay = f.join(token, request); + assertThat(replay.success()).isTrue(); + assertThat(replay.replayed()).isTrue(); + assertThat(f.state(request)).isEqualTo(committed); + f.assertTransitionCount(1L); + } + + @Test + void publicJoinActualSqlAbortAtFinalEntitlementReadRetainsIntentAndRecoversOnce() { + var f = publicJoinFixture(false); + String token = f.browserScope(); + String request = UUID.randomUUID().toString(); + var abort = new AtomicBoolean(true); + org.mockito.Mockito.doAnswer( + invocation -> { + if (abort.compareAndSet(true, false)) { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isTrue(); + dsl.fetch("SELECT 1 / 0"); + } + return invocation.callRealMethod(); + }) + .when(f.demos) + .revalidate(org.mockito.ArgumentMatchers.any()); + var failure = + org.junit.jupiter.api.Assertions.assertThrows( + AuthenticationException.class, () -> f.join(token, request)); + assertThat(failure.getCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); + assertThat(sqlState(failure)).isEqualTo("22012"); + assertThat(f.operation(request).status()).isEqualTo("PENDING"); + assertThat(f.operation(request).lastAttemptFailureCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); + assertThat(f.operation(request).requestDigest()).isNull(); + f.assertTransitionCount(0L); + String intent = f.operation(request).intentDigest(); + assertThat(f.join(token, request).success()).isTrue(); + assertThat(f.operation(request).intentDigest()).isEqualTo(intent); + f.assertTransitionCount(1L); } @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) - void publicJoinTerminalEntitlementOutagePreservesOriginalBytes(boolean storageFailure) { - var fixture = publicJoinFixture(); - var originalResult = publicJoin(fixture); - assertThat(originalResult.success()).isTrue(); - assertPublicJoinCommittedOnce(fixture); - var committed = publicJoinState(fixture); - var originalEvidence = publicJoinOriginalEvidence(fixture); - var subscription = subscriptionRepository.findByTenantId(fixture.tenantId()).getFirst(); + void publicJoinUnavailableCanonicalSourceRetainsOriginalIntentAndRecovers(boolean sourceRead) { + var f = publicJoinFixture(false); + String token = f.browserScope(); + String request = UUID.randomUUID().toString(); var outage = new AtomicBoolean(true); - var sqlFailure = new java.util.concurrent.atomic.AtomicReference(); - if (storageFailure) { + if (sourceRead) { org.mockito.Mockito.doAnswer( invocation -> { - var rows = invocation.callRealMethod(); - if (outage.get()) { - assertThat( - org.springframework.transaction.support.TransactionSynchronizationManager - .isActualTransactionActive()) - .isFalse(); - try { - dsl.fetch("SELECT 1 / 0"); - throw new AssertionError("PostgreSQL division by zero must fail"); - } catch (org.jooq.exception.DataAccessException - | org.springframework.dao.DataAccessException ex) { - sqlFailure.set(ex); - throw ex; - } - } - return rows; + if (outage.get()) + throw new org.springframework.dao.DataAccessResourceFailureException( + "source unavailable"); + return invocation.callRealMethod(); }) - .when(subscriptionRepository) - .findByTenantIdForUpdate(fixture.tenantId()); + .when(f.sources) + .readCurrentSourceSelection(f.tenantId); } else { - subscriptionRepository.deleteByAccountId(fixture.accountId(), fixture.tenantId()); + org.mockito.Mockito.doAnswer( + invocation -> { + if (outage.get()) + throw new org.springframework.dao.DataAccessResourceFailureException( + "demo unavailable"); + return invocation.callRealMethod(); + }) + .when(f.demos) + .readCurrent(f.tenantId); } + assertThatThrownBy(() -> f.join(token, request)).isInstanceOf(AuthenticationException.class); + var pending = f.operation(request); + assertThat(pending.status()).isEqualTo("PENDING"); + assertThat(pending.requestDigest()).isNull(); + assertThat(pending.lastAttemptFailureCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); + assertThat(f.membershipCount()).isZero(); + f.assertTransitionCount(0L); + outage.set(false); + assertThat(f.join(token, request).success()).isTrue(); + assertThat(f.operation(request).intentDigest()).isEqualTo(pending.intentDigest()); + f.assertTransitionCount(1L); + } - var unavailable = publicJoin(fixture); + @Test + void publicJoinLostResponseThenExpiredScopePreservesCompleteCommittedOriginal() { + var f = publicJoinFixture(false); + String token = f.browserScope(); + String request = UUID.randomUUID().toString(); + assertThat(f.join(token, request).success()).isTrue(); + var committed = f.state(request); + f.clock.offset = Duration.ofMinutes(3); + assertThatThrownBy(() -> f.join(token, request)) + .isInstanceOf(AuthenticationException.class) + .extracting(value -> ((AuthenticationException) value).getCode()) + .isEqualTo("CONNECT_SCOPE_INVALID"); + assertThat(f.state(request)).isEqualTo(committed); + f.assertTransitionCount(1L); + } - assertThat(unavailable.success()).isFalse(); - assertThat(unavailable.replayed()).isFalse(); - assertThat(unavailable.accountId()).isEqualTo(fixture.accountUuid()); - assertThat(unavailable.outcomeCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); - if (storageFailure) { - assertThat(sqlFailure.get()).isNotNull(); - assertThat(sqlState(sqlFailure.get())).isEqualTo("22012"); - } - assertThat(publicJoinState(fixture)).isEqualTo(committed); - assertThat(publicJoinOriginalEvidence(fixture)).isEqualTo(originalEvidence); - assertPublicJoinCommittedOnce(fixture); + @Test + void publicJoinExpiredPendingScopePreservesIntentAndCannotCommitMembership() { + var f = publicJoinFixture(false); + String token = f.browserScope(); + String request = UUID.randomUUID().toString(); + org.mockito.Mockito.doThrow( + new org.springframework.dao.DataAccessResourceFailureException( + "controlled source outage")) + .when(f.demos) + .readCurrent(f.tenantId); + assertThatThrownBy(() -> f.join(token, request)).isInstanceOf(AuthenticationException.class); + var pending = f.state(request); + f.clock.offset = Duration.ofMinutes(3); + org.mockito.Mockito.doCallRealMethod().when(f.demos).readCurrent(f.tenantId); + assertThatThrownBy(() -> f.join(token, request)) + .isInstanceOf(AuthenticationException.class) + .extracting(value -> ((AuthenticationException) value).getCode()) + .isEqualTo("CONNECT_SCOPE_INVALID"); + assertThat(f.state(request)).isEqualTo(pending); + assertThat(f.operation(request).status()).isEqualTo("PENDING"); + assertThat(f.membershipCount()).isZero(); + f.assertTransitionCount(0L); + } - outage.set(false); - if (!storageFailure) { - subscription.setId(null); - subscriptionRepository.save(subscription); + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) + void publicJoinExpiryDuringProcessingPreservesPendingIntentAndRollsBack(boolean duringProvider) { + var f = publicJoinFixture(duringProvider); + String token = f.browserScope(); + String request = UUID.randomUUID().toString(); + var intent = new java.util.concurrent.atomic.AtomicReference(); + if (duringProvider) { + f.paid + .transport() + .duringRead( + () -> { + intent.set(f.operation(request).intentDigest()); + f.clock.offset = Duration.ofMinutes(3); + }); + } else { + org.mockito.Mockito.doAnswer( + invocation -> { + var result = + (AccountJoinOperationRepository.CanonicalJoinOperationEvidence) + invocation.callRealMethod(); + // Reuse the owner receipt: a new transaction would wait on the owner's locks. + intent.set(result.intentDigest()); + f.clock.offset = Duration.ofMinutes(3); + return result; + }) + .when(f.operations) + .commitCanonicalJoin( + org.mockito.ArgumentMatchers.eq(request), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any()); } - var replay = publicJoin(fixture); - assertThat(replay.success()).isTrue(); - assertThat(replay.replayed()).isTrue(); - assertThat(replay.accountId()).isEqualTo(originalResult.accountId()); - assertThat(replay.membershipId()).isEqualTo(originalResult.membershipId()); - assertThat(replay.membershipVersion()).isEqualTo(originalResult.membershipVersion()); - assertThat(replay.membershipAuthorityGeneration()) - .isEqualTo(originalResult.membershipAuthorityGeneration()); - assertThat(replay.outcomeCode()).isEqualTo(originalResult.outcomeCode()); - assertThat(publicJoinState(fixture)).isEqualTo(committed); - assertThat(publicJoinOriginalEvidence(fixture)).isEqualTo(originalEvidence); - assertPublicJoinCommittedOnce(fixture); + assertThatThrownBy(() -> f.join(token, request)) + .isInstanceOf(AuthenticationException.class) + .extracting(value -> ((AuthenticationException) value).getCode()) + .isEqualTo("CONNECT_SCOPE_INVALID"); + assertThat(intent.get()).isNotBlank(); + assertThat(f.operation(request).intentDigest()).isEqualTo(intent.get()); + assertThat(f.operation(request).status()).isEqualTo("PENDING"); + assertThat(f.operation(request).requestDigest()).isNull(); + assertThat(f.operation(request).terminalProof()).isNull(); + assertThat(f.operation(request).lastAttemptFailureCode()).isNull(); + assertThat(f.membershipCount()).isZero(); + f.assertTransitionCount(0L); + var pending = f.state(request); + assertThatThrownBy(() -> f.join(token, request)) + .isInstanceOf(AuthenticationException.class) + .extracting(value -> ((AuthenticationException) value).getCode()) + .isEqualTo("CONNECT_SCOPE_INVALID"); + assertThat(f.state(request)).isEqualTo(pending); } @Test - void publicJoinChangedAvailablePolicyPreservesTheOriginalTerminalBytes() { - var fixture = publicJoinFixture(); - assertThat(publicJoin(fixture).success()).isTrue(); - assertPublicJoinCommittedOnce(fixture); - var committed = publicJoinState(fixture); - var originalEvidence = publicJoinOriginalEvidence(fixture); - var original = joinOperationRepository.find(fixture.caller().requestId()).orElseThrow(); - var subscription = subscriptionRepository.findByTenantId(fixture.tenantId()).getFirst(); - UUID originalGeneration = subscription.getTenantAuthorityGeneration(); - subscription.setStatus("trialing"); - subscriptionRepository.save(subscription); - assertThat(subscription.getEntitlementVersion()).isEqualTo(original.entitlementVersion() + 1L); - assertThat(subscription.getTenantAuthorityGeneration()).isNotEqualTo(originalGeneration); - var available = - accountService.getTenantEntitlementsForRuntime( - fixture.tenantId(), "changed-policy-" + fixture.caller().requestId()); - assertThat(available.gameplayAvailable()).isTrue(); - assertThat(available.allowPublicJoin()).isTrue(); - - var conflict = publicJoin(fixture); - - assertThat(conflict.success()).isFalse(); - assertThat(conflict.replayed()).isFalse(); - assertThat(conflict.accountId()).isEqualTo(fixture.accountUuid()); - assertThat(conflict.outcomeCode()).isEqualTo("IDEMPOTENCY_CONFLICT"); - assertThat(publicJoinState(fixture)).isEqualTo(committed); - assertThat(publicJoinOriginalEvidence(fixture)).isEqualTo(originalEvidence); - assertPublicJoinCommittedOnce(fixture); + void publicJoinChangedCallerOrScopeCannotReplaceOriginalTerminalBytes() { + var f = publicJoinFixture(false); + String token = f.browserScope(); + String request = UUID.randomUUID().toString(); + assertThat(f.join(token, request).success()).isTrue(); + var committed = f.state(request); + String different = f.browserScope(); + assertThatThrownBy(() -> f.join(different, request)) + .isInstanceOf(AuthenticationException.class) + .extracting(value -> ((AuthenticationException) value).getCode()) + .isEqualTo("IDEMPOTENCY_CONFLICT"); + assertThat(f.state(request)).isEqualTo(committed); + f.assertTransitionCount(1L); } - private static String sqlState(Throwable failure) { - for (Throwable cause = failure; cause != null; cause = cause.getCause()) { - if (cause instanceof java.sql.SQLException sql) { - return sql.getSQLState(); - } + @Test + void publicJoinFreshClosedPolicyPersistsDenialWithoutMembershipOrTransition() { + var f = publicJoinFixture(false); + String token = f.browserScope(); + f.policy(false, true); + String request = UUID.randomUUID().toString(); + var denied = f.join(token, request); + assertThat(denied.success()).isFalse(); + assertThat(denied.outcomeCode()).isEqualTo("PUBLIC_PRODUCTION_ADMISSION_DENIED"); + assertThat(f.operation(request).status()).isEqualTo("FAILED"); + assertThat(f.operation(request).allowPublicJoin()).isFalse(); + assertThat(f.membershipCount()).isZero(); + f.assertTransitionCount(0L); + var original = f.state(request); + assertThat(f.join(token, request).replayed()).isTrue(); + assertThat(f.state(request)).isEqualTo(original); + } + + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) + void publicJoinTerminalEntitlementOutagePreservesOriginalBytesAndRecovers(boolean paid) { + var f = publicJoinFixture(paid); + String token = f.browserScope(); + String request = UUID.randomUUID().toString(); + var original = f.join(token, request); + assertThat(original.success()).isTrue(); + var committed = f.state(request); + if (paid) { + // A complete but contradictory provider object cannot be used as cached current authority. + f.paid.providerStatus("unpaid"); + } else { + org.mockito.Mockito.doThrow( + new org.springframework.dao.DataAccessResourceFailureException( + "controlled current demo outage")) + .when(f.demos) + .readCurrent(f.tenantId); } - return null; + assertThatThrownBy(() -> f.join(token, request)) + .isInstanceOf(AuthenticationException.class) + .extracting(value -> ((AuthenticationException) value).getCode()) + .isEqualTo("ENTITLEMENT_UNAVAILABLE"); + assertThat(f.state(request)).isEqualTo(committed); + f.assertTransitionCount(1L); + if (paid) f.paid.providerStatus("active"); + else org.mockito.Mockito.doCallRealMethod().when(f.demos).readCurrent(f.tenantId); + var recovered = f.join(token, request); + assertThat(recovered.success()).isTrue(); + assertThat(recovered.replayed()).isTrue(); + assertThat(recovered.membershipId()).isEqualTo(original.membershipId()); + assertThat(recovered.membershipVersion()).isEqualTo(original.membershipVersion()); + assertThat(recovered.membershipAuthorityGeneration()) + .isEqualTo(original.membershipAuthorityGeneration()); + assertThat(f.state(request)).isEqualTo(committed); } - private void assertPublicJoinUnboundPending( - PublicJoinFixture fixture, String failureCode, String availability) { - var operation = joinOperationRepository.find(fixture.caller().requestId()).orElseThrow(); - var scope = connectScopeRepository.find(fixture.connectScopeId()).orElseThrow(); - assertThat(operation.accountId()).isEqualTo(fixture.accountId()); - assertThat(operation.tenantId()).isEqualTo(fixture.tenantId()); - assertThat(operation.callerBinding()).isEqualTo(fixture.caller().sessionId()); - assertThat(operation.scopeTokenHash()) - .isEqualTo( - net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash( - fixture.connectScopeId())); - assertThat(operation.connectScopeDigest()).isEqualTo(scope.snapshotDigest()); - assertThat(operation.intentDigestVersion()).isEqualTo(1); - assertThat(operation.intentDigest()) - .isEqualTo( - net.firedevops.firemud.accountservice.dto.AccountJoinDigest.intent( - fixture.caller().requestId(), scope, fixture.caller().sessionId())); - assertThat(operation.status()).isEqualTo("PENDING"); - assertThat(operation.outcome()).isNull(); - assertThat(operation.requestDigest()).isNull(); - assertThat(operation.requestDigestVersion()).isNull(); - assertThat(operation.allowPublicJoin()).isNull(); - assertThat(operation.entitlementVersion()).isNull(); - assertThat(operation.membershipId()).isNull(); - assertThat(operation.membershipVersion()).isNull(); - assertThat(operation.membershipAuthorityGeneration()).isNull(); - assertThat(operation.entitlementAuthorityAvailability()).isEqualTo(availability); - assertThat(operation.lastAttemptAuthorityAvailability()).isEqualTo(availability); - assertThat(operation.lastAttemptFailureCode()).isEqualTo(failureCode); - assertThat(publicJoinMembershipCount(fixture)).isZero(); - assertThat(publicJoinAuditCount(fixture)).isZero(); + @Test + void publicJoinChangedAvailablePolicyCannotRebindTheOriginalTerminalReceipt() { + var f = publicJoinFixture(false); + String token = f.browserScope(); + String request = UUID.randomUUID().toString(); + assertThat(f.join(token, request).success()).isTrue(); + var committed = f.state(request); + // The new current version is still open; immutable request/policy evidence must still conflict. + f.policy(true, true); + assertThatThrownBy(() -> f.join(token, request)) + .isInstanceOf(AuthenticationException.class) + .extracting(value -> ((AuthenticationException) value).getCode()) + .isEqualTo("IDEMPOTENCY_CONFLICT"); + assertThat(f.state(request)).isEqualTo(committed); + f.assertTransitionCount(1L); } - private List publicJoinOriginalEvidence(PublicJoinFixture fixture) { - assertThat(jwtUtil.parseToken(fixture.connectScopeId()).getPayload().getSubject()) - .isEqualTo(fixture.accountUuid()); - var account = accountRepository.findById(fixture.accountId()).orElseThrow(); - assertThat(account.getAccountUuid().toString()).isEqualTo(fixture.accountUuid()); - assertThat(account.getAccountUuidSourceNumericId()).isEqualTo(fixture.accountId()); - assertThat(account.getAccountUuidProvenance()) - .isEqualTo(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); - return List.of( - dsl.resultQuery( - "SELECT row_to_json(a)::text FROM accounts a WHERE id = ?", fixture.accountId()) - .fetchOne(0, String.class), - dsl.resultQuery( - "SELECT COALESCE(json_agg(s ORDER BY outbox_stream_key)::text, '[]') " - + "FROM account_authority_source_records s WHERE account_uuid = ?", - UUID.fromString(fixture.accountUuid())) - .fetchOne(0, String.class), - dsl.resultQuery( - "SELECT COALESCE(json_agg(e ORDER BY outbox_sequence)::text, '[]') " - + "FROM account_authority_outbox_events e WHERE outbox_stream_key = ?", - "account:auth-authority:v1:account/" + fixture.accountUuid()) - .fetchOne(0, String.class), - dsl.resultQuery( - "SELECT row_to_json(s)::text FROM account_connect_scope_records s WHERE scope_token_hash = ?", - net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash( - fixture.connectScopeId())) - .fetchOne(0, String.class)); + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) + void publicJoinRestoresControlledInactiveSnapshotOnceAndPreservesAuthorityGeneration( + boolean paid) { + var f = publicJoinFixture(paid); + String token = f.browserScope(); + assertThat(f.join(token, UUID.randomUUID().toString()).success()).isTrue(); + f.seedControlledInactiveSnapshot(); + String request = UUID.randomUUID().toString(); + var restored = f.join(token, request); + assertThat(restored.success()).isTrue(); + assertThat(restored.outcomeCode()).isEqualTo("JOINED"); + assertThat(restored.membershipVersion()).isEqualTo(4L); + assertThat(restored.membershipAuthorityGeneration()).isEqualTo(2L); + assertThat(f.membershipCount()).isEqualTo(1L); + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM account_authority_outbox_events WHERE outbox_stream_key = ?", + f.stream())) + .isEqualTo(3L); + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM account_audit_outbox WHERE tenant_uuid = ? AND event_type = 'ACCOUNT_JOINED_PUBLIC_PRODUCTION'", + f.tenantId)) + .isEqualTo(2L); + var restoredEvent = f.in(() -> f.outbox.findEvent(f.stream(), 3L).orElseThrow()); + var decodedRestoredEvent = + MembershipAuthorityEventV1Codec.verify( + new String(restoredEvent.payload(), StandardCharsets.UTF_8)); + assertThat(decodedRestoredEvent.requestId()).isEqualTo(request); + assertThat(decodedRestoredEvent.outboxSequence()).isEqualTo("3"); + assertThat(decodedRestoredEvent.callerBoundAuthorityInvalidated()).isFalse(); + var committed = f.state(request); + assertThat(f.join(token, request).replayed()).isTrue(); + assertThat(f.state(request)).isEqualTo(committed); } - private AtomicBoolean losePublicJoinTerminalResponse(PublicJoinFixture fixture) { - var committed = new AtomicBoolean(); - var readbackDropped = new AtomicBoolean(); - org.mockito.Mockito.doAnswer( - invocation -> { - invocation.callRealMethod(); - org.springframework.transaction.support.TransactionSynchronizationManager - .registerSynchronization( - new org.springframework.transaction.support.TransactionSynchronization() { - @Override - public void afterCommit() { - committed.set(true); - throw new IllegalStateException("Injected lost public JOIN commit ACK"); - } - }); - return null; - }) - .when(joinOperationRepository) - .finish( - org.mockito.ArgumentMatchers.eq(fixture.caller().requestId()), - org.mockito.ArgumentMatchers.eq("COMMITTED"), - org.mockito.ArgumentMatchers.eq("JOINED"), - org.mockito.ArgumentMatchers.any(), - org.mockito.ArgumentMatchers.any(), - org.mockito.ArgumentMatchers.any()); - org.mockito.Mockito.doAnswer( - invocation -> { - if (committed.get() && readbackDropped.compareAndSet(false, true)) { - throw new org.springframework.dao.DataAccessResourceFailureException( - "Injected unavailable first post-commit JOIN readback"); - } - return invocation.callRealMethod(); - }) - .when(joinOperationRepository) - .find(fixture.caller().requestId()); - return readbackDropped; + @Test + void publicJoinActiveControlOnlyMemberReturnsCurrentSnapshotWithoutGrantingGameplay() { + var f = publicJoinFixture(false); + String token = f.browserScope(); + assertThat(f.join(token, UUID.randomUUID().toString()).success()).isTrue(); + f.seedControlledSnapshot("ACTIVE", false, List.of("moderator")); + f.policy(false, true); + String request = UUID.randomUUID().toString(); + var result = f.join(token, request); + assertThat(result.success()).isTrue(); + assertThat(result.outcomeCode()).isEqualTo("ALREADY_ACTIVE"); + assertThat(result.membershipVersion()).isEqualTo(3L); + assertThat(result.membershipAuthorityGeneration()).isEqualTo(2L); + assertThat(result.gameplayAdmissionAllowed()).isFalse(); + assertThat(f.currentRoles()).containsExactly("moderator"); + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM account_authority_outbox_events WHERE outbox_stream_key = ?", + f.stream())) + .isEqualTo(2L); + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM account_audit_outbox WHERE tenant_uuid = ? AND event_type = 'ACCOUNT_JOINED_PUBLIC_PRODUCTION'", + f.tenantId)) + .isEqualTo(1L); + var committed = f.state(request); + var replay = f.join(token, request); + assertThat(replay.success()).isTrue(); + assertThat(replay.gameplayAdmissionAllowed()).isFalse(); + assertThat(replay.replayed()).isTrue(); + assertThat(f.state(request)).isEqualTo(committed); + assertThat(f.currentRoles()).containsExactly("moderator"); } - private void assertPublicJoinUnavailable(PublicJoinFixture fixture) { - var unavailable = - org.junit.jupiter.api.Assertions.assertThrows( - AuthenticationException.class, () -> publicJoin(fixture)); - assertThat(unavailable.getCode()).isEqualTo("AUTH_UNAVAILABLE"); + @Test + void publicJoinAnotherAuthenticatedAccountCannotConsumeTheOriginalScopeOrCreateIntent() { + var f = publicJoinFixture(false); + String token = f.browserScope(); + String suffix = UUID.randomUUID().toString(); + var other = + accountService.createAccount( + new CreateAccountRequest( + "other-facade-" + suffix, + "other-facade-" + suffix + "@example.test", + "password123")); + Account owner = f.accounts.findByAccountUuid(UUID.fromString(other.id())).orElseThrow(); + String bootstrap = + f.jwt.generateToken( + other.id(), + Map.of( + "aud", + "player-bootstrap", + "accountId", + other.id(), + "jti", + UUID.randomUUID().toString())); + org.mockito.Mockito.when(f.sessions.isAccountSessionActive(owner.getId(), bootstrap)) + .thenReturn(true); + String request = UUID.randomUUID().toString(); + assertThatThrownBy( + () -> + f.service.joinPublicProduction( + bootstrap, new JoinPublicProductionRequest(token, request))) + .isInstanceOf(AuthenticationException.class) + .extracting(value -> ((AuthenticationException) value).getCode()) + .isEqualTo("CONNECT_SCOPE_INVALID"); + assertThat(f.in(() -> f.operations.findCanonicalEvidenceByRequestId(request))).isEmpty(); + assertThat(f.membershipCount()).isZero(); + f.assertTransitionCount(0L); } - private JoinPublicProductionResult publicJoin(PublicJoinFixture fixture) { - return accountService.joinPublicProductionFromGameSession( - fixture.caller(), - new JoinPublicProductionRequest(fixture.connectScopeId(), fixture.caller().requestId())); + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) + void bootstrapCharactersUsesActualAccountAuthorityAndPreservesControlledEntityNamesAndLevels( + boolean paid) { + var f = publicJoinFixture(paid); + String token = f.browserScope(); + String join = UUID.randomUUID().toString(); + assertThat(f.join(token, join).success()).isTrue(); + UUID ada = UUID.randomUUID(), zed = UUID.randomUUID(); + org.mockito.Mockito.when( + f.roster.read( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.eq(f.account.getAccountUuid()), + org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isSynchronizationActive()) + .isFalse(); + return List.of( + new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .Actor(zed, "Zed", 37), + new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .Actor(ada, "Ada", 12)); + }); + var before = f.state(join); + int providerReads = paid ? f.paid.transport().reads() : 0; + var actors = f.characters(token); + assertThat(actors).extracting(value -> value.characterName()).containsExactly("Ada", "Zed"); + assertThat(actors) + .extracting(value -> value.characterId()) + .containsExactly(ada.toString(), zed.toString()); + assertThat(actors).extracting(value -> value.level()).containsExactly(12, 37); + assertThat(actors) + .allSatisfy( + actor -> { + assertThat(actor.stateScope()).isEqualTo("SHARED"); + assertThat(actor.characterCreationPolicy()).isEqualTo("PRESEEDED_ONLY"); + }); + var selected = + org.mockito.ArgumentCaptor.forClass( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence.class); + org.mockito.Mockito.verify(f.roster) + .read( + org.mockito.ArgumentMatchers.any(UUID.class), + org.mockito.ArgumentMatchers.eq(f.account.getAccountUuid()), + selected.capture()); + assertThat(selected.getValue().selector().canonicalAccountUuid()) + .isEqualTo(f.account.getAccountUuid()); + assertThat(selected.getValue().selector().canonicalTenantUuid()).isEqualTo(f.tenantId); + assertThat(selected.getValue().selector().realmUuid()).isEqualTo(f.target.realmId()); + assertThat(selected.getValue().selector().playableStateNamespaceUuid()) + .isEqualTo(f.target.playableStateNamespaceId()); + assertThat(selected.getValue().selector().canonicalGameInstanceUuid()) + .isEqualTo(f.target.canonicalGameInstanceId()); + assertThat(selected.getValue().selector().canonicalVersionUuid()) + .isEqualTo(f.target.canonicalVersionId()); + assertThat(selected.getValue().selector().expectedCatalogRevision()) + .isEqualTo(f.target.catalogRevision()); + assertThat(selected.getValue().selector().expectedPointerVersion()) + .isEqualTo(f.target.pointerVersion()); + assertThat(selected.getValue().selector().expectedActiveWorldEpoch()) + .isEqualTo(f.target.activeWorldEpoch()); + if (paid) assertThat(f.paid.transport().reads()).isGreaterThanOrEqualTo(providerReads + 2); + assertThat(f.state(join)).isEqualTo(before); + f.assertTransitionCount(1L); } - private PublicJoinFixture publicJoinFixture() { - String suffix = UUID.randomUUID().toString().substring(0, 8); - String world = "join-" + suffix; - var account = - accountService.createAccount( - new CreateAccountRequest(world, world + "@example.com", "password123")); - long accountId = - java.util.Objects.requireNonNull( - dsl.resultQuery( - "SELECT id FROM accounts WHERE account_uuid = ?", UUID.fromString(account.id())) - .fetchOne(0, Long.class)); - long tenantId = 6000000000L + accountId; - dsl.execute( - "INSERT INTO subscription(account_id,plan_id,status,tenant_id,entitlement_version) " - + "VALUES(?,'join-proof','active',?,1)", - accountId, - tenantId); - UUID realmId = UUID.randomUUID(); - String namespace = UUID.randomUUID().toString(); - var realm = - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setTenantId(Long.toString(tenantId)) - .setRealmId(realmId.toString()) - .setWorldSlug(world) - .setRealmSlug("production") - .setPlayableStateNamespaceId(namespace) - .setStateScope("SHARED") - .setGameInstanceId("44") - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .build(); - var pointer = - net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() - .setTenantId(Long.toString(tenantId)) - .setRealmId(realmId.toString()) - .setWorldSlug(world) - .setRealmSlug("production") - .setPlayableStateNamespaceId(namespace) - .setStateScope("SHARED") - .setGameInstanceId("44") - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .build(); - org.mockito.Mockito.when(gameSessionClient.listGameplayRealms(world)) - .thenReturn(List.of(realm)); - org.mockito.Mockito.when(gameSessionClient.getAdmissionPointer(tenantId, world, "production")) - .thenReturn(pointer); - var caller = - new DirectTextCallerContext( - accountId, - tenantId, - realmId, - namespace, - "SHARED", - 44L, - "controlled-join-session-" + suffix, - "original-join-" + suffix); - var scope = - accountService.issueDirectTextConnectScope( - caller, - new DirectTextJoinTarget( - tenantId, realmId, world, "production", namespace, "SHARED", 44L, 23L, 17L)); - return new PublicJoinFixture(accountId, account.id(), tenantId, caller, scope.connectScopeId()); + @Test + void bootstrapCharactersValidEmptyResultStillRequiresSuccessfulEntityDiscovery() { + var f = publicJoinFixture(false); + String token = f.browserScope(); + assertThat(f.join(token, UUID.randomUUID().toString()).success()).isTrue(); + assertThat(f.characters(token)).isEmpty(); + org.mockito.Mockito.verify(f.roster) + .read( + org.mockito.ArgumentMatchers.any(UUID.class), + org.mockito.ArgumentMatchers.eq(f.account.getAccountUuid()), + org.mockito.ArgumentMatchers.any()); + f.assertTransitionCount(1L); } - private long publicJoinMembershipCount(PublicJoinFixture fixture) { - return java.util.Objects.requireNonNull( - dsl.resultQuery( - "SELECT COUNT(*) FROM account_tenant_membership WHERE account_id = ? AND tenant_id = ?", - fixture.accountId(), - fixture.tenantId()) - .fetchOne(0, Long.class)); + @Test + void + bootstrapCharactersSameAccountAndDuplicateWorldRealmNamesRemainBoundToExactTenantAndTarget() { + var first = publicJoinFixture(false); + var second = new CanonicalPublicJoinFixture(false, first.account); + String firstScope = first.browserScope(), secondScope = second.browserScope(); + assertThat(first.target.worldSlug()).isEqualTo(second.target.worldSlug()); + assertThat(first.target.realmSlug()).isEqualTo(second.target.realmSlug()); + assertThat(first.tenantId).isNotEqualTo(second.tenantId); + assertThat(first.join(firstScope, UUID.randomUUID().toString()).success()).isTrue(); + assertThat(second.join(secondScope, UUID.randomUUID().toString()).success()).isTrue(); + UUID firstActor = UUID.randomUUID(), secondActor = UUID.randomUUID(); + org.mockito.Mockito.when( + first.roster.read( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.eq(first.account.getAccountUuid()), + org.mockito.ArgumentMatchers.any())) + .thenReturn( + List.of( + new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .Actor(firstActor, "First tenant actor", 9))); + org.mockito.Mockito.when( + second.roster.read( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.eq(second.account.getAccountUuid()), + org.mockito.ArgumentMatchers.any())) + .thenReturn( + List.of( + new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .Actor(secondActor, "Second tenant actor", 21))); + assertThat(first.characters(firstScope)) + .extracting(value -> value.characterId()) + .containsExactly(firstActor.toString()); + assertThat(second.characters(secondScope)) + .extracting(value -> value.characterId()) + .containsExactly(secondActor.toString()); + var selected = + org.mockito.ArgumentCaptor.forClass( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence.class); + org.mockito.Mockito.verify(first.roster) + .read( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.eq(first.account.getAccountUuid()), + selected.capture()); + assertThat(selected.getValue().selector().canonicalTenantUuid()).isEqualTo(first.tenantId); + org.mockito.Mockito.verify(second.roster) + .read( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.eq(second.account.getAccountUuid()), + selected.capture()); + assertThat(selected.getValue().selector().canonicalTenantUuid()).isEqualTo(second.tenantId); + assertThat(selected.getValue().selector().realmUuid()).isEqualTo(second.target.realmId()); + assertThat(selected.getValue().selector().playableStateNamespaceUuid()) + .isEqualTo(second.target.playableStateNamespaceId()); + assertThat(selected.getValue().selector().canonicalGameInstanceUuid()) + .isEqualTo(second.target.canonicalGameInstanceId()); } - private UUID publicJoinAuditId(PublicJoinFixture fixture) { - return UUID.nameUUIDFromBytes( - ("account-join-audit/v1:" + fixture.caller().requestId()).getBytes(StandardCharsets.UTF_8)); + @Test + void bootstrapCharactersAnotherAuthenticatedAccountCannotConsumeTheSelectedScope() { + var f = publicJoinFixture(false); + String token = f.browserScope(); + assertThat(f.join(token, UUID.randomUUID().toString()).success()).isTrue(); + String suffix = UUID.randomUUID().toString(); + var other = + accountService.createAccount( + new CreateAccountRequest( + "other-roster-" + suffix, + "other-roster-" + suffix + "@example.test", + "password123")); + Account owner = f.accounts.findByAccountUuid(UUID.fromString(other.id())).orElseThrow(); + String bootstrap = + f.jwt.generateToken( + other.id(), + Map.of( + "aud", + "player-bootstrap", + "accountId", + other.id(), + "jti", + UUID.randomUUID().toString())); + org.mockito.Mockito.when(f.sessions.isAccountSessionActive(owner.getId(), bootstrap)) + .thenReturn(true); + assertThatThrownBy( + () -> + f.service.listBootstrapCharacters( + bootstrap, f.target.worldSlug(), f.target.realmSlug(), token)) + .isInstanceOf(AuthenticationException.class) + .extracting(value -> ((AuthenticationException) value).getCode()) + .isEqualTo("CONNECT_SCOPE_INVALID"); + org.mockito.Mockito.verifyNoInteractions(f.roster); + f.assertTransitionCount(1L); } - private long publicJoinAuditCount(PublicJoinFixture fixture) { - return java.util.Objects.requireNonNull( - dsl.resultQuery( - "SELECT COUNT(*) FROM account_audit_outbox WHERE audit_event_id = ?", - publicJoinAuditId(fixture)) - .fetchOne(0, Long.class)); + @Test + void bootstrapCharactersMissingAndControlledInactiveMembersRequireJoinWithoutEntityDisclosure() { + var f = publicJoinFixture(false); + String token = f.browserScope(); + assertThatThrownBy(() -> f.characters(token)) + .isInstanceOf(AuthenticationException.class) + .extracting(value -> ((AuthenticationException) value).getCode()) + .isEqualTo("JOIN_REQUIRED"); + org.mockito.Mockito.verifyNoInteractions(f.roster); + assertThat(f.join(token, UUID.randomUUID().toString()).success()).isTrue(); + f.seedControlledInactiveSnapshot(); + assertThatThrownBy(() -> f.characters(token)) + .isInstanceOf(AuthenticationException.class) + .extracting(value -> ((AuthenticationException) value).getCode()) + .isEqualTo("JOIN_REQUIRED"); + org.mockito.Mockito.verifyNoInteractions(f.roster); + } + + @Test + void bootstrapCharactersClosedPolicyAndControlOnlyMembershipCannotBecomeAnEmptySuccess() { + var f = publicJoinFixture(false); + String token = f.browserScope(); + f.policy(false, true); + assertThatThrownBy(() -> f.characters(token)) + .isInstanceOf(AuthenticationException.class) + .extracting(value -> ((AuthenticationException) value).getCode()) + .isEqualTo("PUBLIC_PRODUCTION_ADMISSION_DENIED"); + org.mockito.Mockito.verifyNoInteractions(f.roster); + f.policy(true, true); + assertThat(f.join(token, UUID.randomUUID().toString()).success()).isTrue(); + f.seedControlledSnapshot("ACTIVE", false, List.of("moderator")); + assertThatThrownBy(() -> f.characters(token)) + .isInstanceOf(AuthenticationException.class) + .extracting(value -> ((AuthenticationException) value).getCode()) + .isEqualTo("PUBLIC_PRODUCTION_ADMISSION_DENIED"); + assertThat(f.currentRoles()).containsExactly("moderator"); + org.mockito.Mockito.verifyNoInteractions(f.roster); } - private void assertPublicJoinCommittedOnce(PublicJoinFixture fixture) { - assertThat(publicJoinMembershipCount(fixture)).isEqualTo(1L); - assertThat(publicJoinAuditCount(fixture)).isEqualTo(1L); + @Test + void bootstrapCharactersRechecksActualMembershipSnapshotAfterEntityDiscovery() { + var f = publicJoinFixture(false); + String token = f.browserScope(); + String join = UUID.randomUUID().toString(); + assertThat(f.join(token, join).success()).isTrue(); + org.mockito.Mockito.when( + f.roster.read( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.eq(f.account.getAccountUuid()), + org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + f.seedControlledInactiveSnapshot(); + return List.of( + new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .Actor(UUID.randomUUID(), "Withheld", 19)); + }); + assertThatThrownBy(() -> f.characters(token)) + .isInstanceOf(AuthenticationException.class) + .extracting(value -> ((AuthenticationException) value).getCode()) + .isEqualTo("AUTH_UNAVAILABLE"); + assertThat(f.operation(join).status()).isEqualTo("COMMITTED"); + assertThat(f.operation(join).membershipVersion()).isEqualTo(2L); assertThat( dsl.fetchValue( - "SELECT COUNT(*) FROM account_join_operations j " - + "JOIN account_tenant_membership m ON m.id = j.membership_id " - + "WHERE j.request_id = ? AND j.status = 'COMMITTED' AND j.outcome = 'JOINED' " - + "AND j.account_id = ? AND j.tenant_id = ? " - + "AND m.account_id = j.account_id AND m.tenant_id = j.tenant_id " - + "AND m.lifecycle_state = 'ACTIVE' AND m.authority_provenance = 'EXPLICIT_JOIN' " - + "AND m.membership_version = 1 AND m.membership_authority_generation = 1 " - + "AND j.outcome_membership_version = m.membership_version " - + "AND j.outcome_membership_authority_generation = m.membership_authority_generation", - fixture.caller().requestId(), - fixture.accountId(), - fixture.tenantId())) - .isEqualTo(1L); + "SELECT lifecycle_state FROM account_tenant_membership WHERE account_id = ? AND tenant_uuid = ?", + f.account.getId(), + f.tenantId)) + .isEqualTo("INACTIVE"); assertThat( dsl.fetchValue( - "SELECT COUNT(*) FROM account_audit_outbox " - + "WHERE audit_event_id = ? AND scope = 'tenant' AND tenant_id = ? " - + "AND producer_service = 'account-service' " - + "AND event_type = 'ACCOUNT_JOINED_PUBLIC_PRODUCTION' " - + "AND payload::jsonb ->> 'requestId' = ? " - + "AND payload::jsonb ->> 'accountId' = ? " - + "AND payload::jsonb ->> 'membershipVersion' = '1'", - publicJoinAuditId(fixture), - fixture.tenantId(), - fixture.caller().requestId(), - Long.toString(fixture.accountId()))) + "SELECT membership_version FROM account_tenant_membership WHERE account_id = ? AND tenant_uuid = ?", + f.account.getId(), + f.tenantId)) + .isEqualTo(3L); + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM account_authority_outbox_events WHERE outbox_stream_key = ?", + f.stream())) + .isEqualTo(2L); + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM account_audit_outbox WHERE tenant_uuid = ? AND event_type = 'ACCOUNT_JOINED_PUBLIC_PRODUCTION'", + f.tenantId)) .isEqualTo(1L); } - private List publicJoinState(PublicJoinFixture fixture) { - return List.of( - dsl.resultQuery( - "SELECT row_to_json(j)::text FROM account_join_operations j WHERE request_id = ?", - fixture.caller().requestId()) - .fetchOne(0, String.class), - dsl.resultQuery( - "SELECT row_to_json(m)::text FROM account_tenant_membership m " - + "WHERE account_id = ? AND tenant_id = ?", - fixture.accountId(), - fixture.tenantId()) - .fetchOne(0, String.class), - dsl.resultQuery( - // Delivery retry diagnostics may advance independently of original JOIN evidence. - "SELECT (to_jsonb(a) - ARRAY['attempt_count','last_attempt_at','next_attempt_at'])::text " - + "FROM account_audit_outbox a WHERE audit_event_id = ?", - publicJoinAuditId(fixture)) - .fetchOne(0, String.class), - dsl.resultQuery( - "SELECT row_to_json(s)::text FROM account_connect_scope_records s " - + "JOIN account_join_operations j ON j.scope_token_hash = s.scope_token_hash " - + "WHERE j.request_id = ?", - fixture.caller().requestId()) - .fetchOne(0, String.class)); + @Test + void bootstrapCharactersFinalEntitlementOutageDiscardsEntityResultAndPreservesAccountState() { + var f = publicJoinFixture(false); + String token = f.browserScope(); + String join = UUID.randomUUID().toString(); + assertThat(f.join(token, join).success()).isTrue(); + var before = f.state(join); + org.mockito.Mockito.when( + f.roster.read( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.eq(f.account.getAccountUuid()), + org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + org.mockito.Mockito.doThrow( + new org.springframework.dao.DataAccessResourceFailureException( + "controlled late demo currentness outage")) + .when(f.demos) + .revalidate(org.mockito.ArgumentMatchers.any()); + return List.of( + new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .Actor(UUID.randomUUID(), "Withheld", 31)); + }); + assertThatThrownBy(() -> f.characters(token)) + .isInstanceOf(AuthenticationException.class) + .extracting(value -> ((AuthenticationException) value).getCode()) + .isEqualTo("ENTITLEMENT_UNAVAILABLE"); + assertThat(f.state(join)).isEqualTo(before); + f.assertTransitionCount(1L); + } + + @Test + void bootstrapCharactersEntityFailureAndExpiredScopeNeverReturnAnEmptySuccess() { + var f = publicJoinFixture(false); + String token = f.browserScope(); + String join = UUID.randomUUID().toString(); + assertThat(f.join(token, join).success()).isTrue(); + var before = f.state(join); + org.mockito.Mockito.when( + f.roster.read( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.eq(f.account.getAccountUuid()), + org.mockito.ArgumentMatchers.any())) + .thenThrow(new IllegalStateException("controlled Entity discovery failure")); + assertThatThrownBy(() -> f.characters(token)) + .isInstanceOf(AuthenticationException.class) + .extracting(value -> ((AuthenticationException) value).getCode()) + .isEqualTo("AUTH_UNAVAILABLE"); + f.clock.offset = Duration.ofMinutes(3); + assertThatThrownBy(() -> f.characters(token)) + .isInstanceOf(AuthenticationException.class) + .extracting(value -> ((AuthenticationException) value).getCode()) + .isEqualTo("CONNECT_SCOPE_INVALID"); + assertThat(f.state(join)).isEqualTo(before); + f.assertTransitionCount(1L); + } + + private static String sqlState(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof java.sql.SQLException sql) return sql.getSQLState(); + } + return null; + } + + private CanonicalPublicJoinFixture publicJoinFixture(boolean paid) { + return new CanonicalPublicJoinFixture(paid); + } + + /** + * Actual Account SQL/JWT/intent/subscription/member/event/audit composition. GS + * resolver/published-source/World ACTIVE responses and caller registry inputs are controlled (the + * strict source decoder and remote freshness are not qualified); this does not qualify PKI, + * issuer custody or runtime registration. + */ + private final class CanonicalPublicJoinFixture { + private final String namespace; + private final AccountRepository accounts = new AccountRepository(dsl); + private final AccountAuthorityGenerationRepository generations = + new AccountAuthorityGenerationRepository(dsl); + private final AccountAuthorityOutboxRepository outbox = + new AccountAuthorityOutboxRepository(dsl); + private final AccountAuthoritySourceEvidenceRepository evidence = + new AccountAuthoritySourceEvidenceRepository(dsl, generations, outbox); + private final AccountMembershipPairAuthorityRepository pairs = + new AccountMembershipPairAuthorityRepository(dsl); + private final AccountTenantMembershipRoleSnapshotRepository roles = + new AccountTenantMembershipRoleSnapshotRepository(dsl); + private final AccountAuditOutboxRepository audits = new AccountAuditOutboxRepository(dsl); + private final FreshTenantIdentityAssociationRepository tenants; + private final AccountTenantMembershipRepository members; + private final AccountTenantAuthorityEventRepository sources; + private final AccountDemoTenantEntitlementRepository demos; + private final AccountConnectScopeRepository scopes; + private final AccountJoinOperationRepository operations; + private final AccountCanonicalFirstJoinTerminalCoordinator terminal; + private final integration.net.firedevops.firemud.accountservice.repository + .CanonicalHostingSubscriptionTestFixture.Fixture + paid; + private final AccountHostingSubscriptionLifecycleRepository hosting; + private final StripeHostingSubscriptionObserver observer; + private final FreshTenantCreationEvidence source; + private final UUID tenantId; + private final Account account; + private final FixtureClock clock; + private final TransactionTemplate transaction = new TransactionTemplate(transactionManager); + private final CanonicalGameplayAdmissionDecisionReadClient targets = + org.mockito.Mockito.mock(CanonicalGameplayAdmissionDecisionReadClient.class); + private final SessionService sessions = org.mockito.Mockito.mock(SessionService.class); + private final net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + roster = + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .class); + private final JwtUtil jwt = + new JwtUtil("controlled-public-facade-fixture-key-01234567890123456789", 300000L); + private final String bootstrap; + private final AccountServiceImpl service; + private final Target target; + + private CanonicalPublicJoinFixture(boolean usePaid) { + this(usePaid, null); + } + + private CanonicalPublicJoinFixture(boolean usePaid, Account existingAccount) { + namespace = usePaid ? "prod" : "test"; + transaction.setPropagationBehavior( + org.springframework.transaction.TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel( + org.springframework.transaction.TransactionDefinition.ISOLATION_SERIALIZABLE); + tenants = new FreshTenantIdentityAssociationRepository(dsl, namespace); + members = new AccountTenantMembershipRepository(dsl, accounts, tenants, pairs); + var billing = new AccountTenantEntitlementOutboxRepository(dsl); + sources = + org.mockito.Mockito.spy( + new AccountTenantAuthorityEventRepository( + dsl, outbox, billing, tenants, generations)); + demos = + org.mockito.Mockito.spy( + new AccountDemoTenantEntitlementRepository( + dsl, tenants, generations, billing, sources)); + scopes = + new AccountConnectScopeRepository( + dsl, + new AccountTenantIdentityResolver( + org.mockito.Mockito.mock(ApprovedLegacyTenantAssociationRepository.class), + namespace), + tenants); + operations = org.mockito.Mockito.spy(new AccountJoinOperationRepository(dsl, scopes)); + var producer = + new AccountMembershipAuthorityEventProducer( + operations, + accounts, + pairs, + members, + roles, + generations, + outbox, + evidence, + sources, + demos); + terminal = + new AccountCanonicalFirstJoinTerminalCoordinator( + accounts, operations, members, roles, outbox, pairs, audits, producer); + if (usePaid) { + paid = + integration.net.firedevops.firemud.accountservice.repository + .CanonicalHostingSubscriptionTestFixture.create(dataSource); + var claim = + paid.service() + .claimProvisioning(paid.creation().requestId(), 1, UUID.randomUUID()) + .claim(); + assertThat( + paid.service() + .reconcile( + UUID.randomUUID(), + paid.creation().requestId(), + claim.subscriptionRowVersion(), + paid.providerId(), + claim.attemptId()) + .outcome()) + .isEqualTo(AccountHostingSubscriptionLifecycleRepository.Outcome.COMMITTED); + hosting = paid.lifecycleRepository(); + observer = paid.observer(); + tenantId = paid.tenantId(); + source = in(() -> tenants.read(tenantId).orElseThrow()); + clock = new FixtureClock(paid.clock()); + } else { + paid = null; + hosting = org.mockito.Mockito.mock(AccountHostingSubscriptionLifecycleRepository.class); + observer = org.mockito.Mockito.mock(StripeHostingSubscriptionObserver.class); + tenantId = UUID.randomUUID(); + UUID request = UUID.randomUUID(); + UUID operation = UUID.randomUUID(); + String key = "f-" + tenantId.toString().replace("-", ""); + String digest = + GameTenantCreationDigest.requestDigest(namespace, request, key, "Facade fixture", null); + source = + new FreshTenantCreationEvidence( + 1, + namespace, + request, + operation, + digest, + tenantId, + 100000000L + Integer.toUnsignedLong(key.hashCode()), + key, + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + namespace, + request, + operation, + digest, + tenantId, + 100000000L + Integer.toUnsignedLong(key.hashCode()), + key, + "NEW_GAME_ROW")); + clock = new FixtureClock(Clock.systemUTC()); + in( + () -> { + tenants.importVerified(source); + generations.initializeTenantIfAbsent(tenantId); + return null; + }); + policy(true, true); + } + String suffix = UUID.randomUUID().toString(); + if (existingAccount == null) { + var created = + accountService.createAccount( + new CreateAccountRequest( + "facade-" + suffix, "facade-" + suffix + "@example.test", "password123")); + account = accounts.findByAccountUuid(UUID.fromString(created.id())).orElseThrow(); + } else { + account = accounts.findByAccountUuid(existingAccount.getAccountUuid()).orElseThrow(); + } + in( + () -> { + evidence.initializeIssuerIfAbsent("firemud-account-service"); + generations.initialize( + AccountAuthorityGenerationRepository.AuthorityScope.membership( + account.getAccountUuid(), tenantId)); + return null; + }); + if (paid != null) { + // The SQL lifecycle owner evaluates at microsecond precision; its SDK input must use the + // same controlled instant rather than appear nanoseconds later than the evaluation. + Instant browserTime = + Instant.now().plusSeconds(1).truncatedTo(java.time.temporal.ChronoUnit.MICROS); + if (paid.clock().instant().isBefore(browserTime)) { + paid.clock().advance(Duration.between(paid.clock().instant(), browserTime)); + } + } + target = target(); + org.mockito.Mockito.when( + targets.listVisiblePublicProductionAdmissionTargets( + org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + var request = + new CanonicalGameplayAdmissionDecisionReadGrpcCodec.DiscoveryRequest( + invocation.getArgument(0, UUID.class), namespace); + return CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromDiscoveryResponse( + request, + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse( + request, List.of(target))); + }); + org.mockito.Mockito.when( + targets.resolvePublishedRealmAdmissionTarget(org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + var selector = + invocation.getArgument( + 0, + CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector + .class); + return CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromTargetResolutionResponse( + selector, + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toTargetResolutionResponse( + selector, target)); + }); + // The transport boundary is controlled. Actual Account owners must still request this strict + // published-source/World ACTIVE result; the resolver response alone cannot authorize JOIN. + org.mockito.Mockito.when( + targets.readPublishedRealmAdmissionOwner(org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + var strict = + invocation.getArgument( + 0, + net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence + .Request.class); + var published = + org.mockito.Mockito.mock( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence + .class); + org.mockito.Mockito.when(published.selector()).thenReturn(strict); + org.mockito.Mockito.when(published.currentTarget()).thenReturn(target); + var sourceEvidence = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence + .class); + org.mockito.Mockito.when(sourceEvidence.request()).thenReturn(strict); + org.mockito.Mockito.when(sourceEvidence.admissionPointerSnapshotDigest()) + .thenReturn(target.admissionPointerSnapshotDigest()); + // Controlled remote policy capture; the Account integration test does not qualify + // its decoder. + var policies = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.publication + .PublishedRealmEntryPolicySetEvidence.class); + org.mockito.Mockito.when(policies.canonicalBytes()) + .thenReturn( + ("controlled-policy-set-" + tenantId).getBytes(StandardCharsets.UTF_8)); + org.mockito.Mockito.when(sourceEvidence.publishedPolicySetEvidence()) + .thenReturn(policies); + var world = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence + .class); + org.mockito.Mockito.when(world.lifecycleStatus()).thenReturn("ACTIVE"); + org.mockito.Mockito.when(world.lifecycleEpoch()) + .thenReturn(target.activeWorldEpoch()); + org.mockito.Mockito.when(world.rowVersion()).thenReturn(1L); + org.mockito.Mockito.when(published.sourceEvidence()).thenReturn(sourceEvidence); + org.mockito.Mockito.when(published.worldLifecycleEvidence()).thenReturn(world); + return published; + }); + var properties = new AccountTokenProperties(); + properties.setConnectScopeExpirationMs(120000L); + bootstrap = + jwt.generateToken( + account.getAccountUuid().toString(), + Map.of( + "aud", + "player-bootstrap", + "accountId", + account.getAccountUuid().toString(), + "jti", + UUID.randomUUID().toString())); + org.mockito.Mockito.when(sessions.isAccountSessionActive(account.getId(), bootstrap)) + .thenReturn(true); + var caller = new AccountPlayerBootstrapCallerVerifier(jwt, accounts, sessions); + var entitlement = + new AccountPublicBootstrapEntitlementOwner( + sources, + new AccountHostingSubscriptionLifecycleService(hosting, observer, transactionManager), + demos, + transactionManager, + clock); + service = + new AccountServiceImpl( + accounts, + generations, + evidence, + outbox, + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountPasswordResetOperationRepository.class), + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountLogoutAllOperationRepository.class), + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository.class), + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.service + .AccountPasswordResetDraftSourceChangeRepository.class), + audits, + operations, + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountEmailLoginChallengeRepository.class), + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository.AccountRealmAccessGrantRepository + .class), + members, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + new net.firedevops.firemud.accountservice.config.MailProperties(), + properties, + new net.firedevops.firemud.common.security.JwtAuthProperties(), + jwt, + sessions, + transactionManager); + service.setPublicBootstrapWorldsOwner( + new AccountPublicBootstrapWorldsOwner(caller, targets, entitlement, clock)); + service.setCanonicalPublicRealmScopeOwner( + new AccountCanonicalPublicRealmScopeOwner( + caller, + targets, + entitlement, + accounts, + members, + tenants, + sources, + scopes, + jwt, + properties, + clock, + transactionManager, + namespace)); + service.setAccountBootstrapRosterReadClient(roster); + org.mockito.Mockito.when( + roster.read( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.eq(account.getAccountUuid()), + org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isSynchronizationActive()) + .isFalse(); + return List.of(); + }); + service.setCanonicalScopeConsumers( + new AccountCanonicalConnectScopeReader(jwt, scopes, transactionManager, clock), + targets, + sources, + demos, + hosting, + observer, + terminal, + namespace, + clock); + } + + private void policy(boolean join, boolean gameplay) { + in( + () -> { + DemoTenantEntitlementSnapshot previous; + try { + previous = demos.readCurrent(tenantId); + } catch ( + net.firedevops.firemud.accountservice.service.DemoTenantEntitlementException + missing) { + if (missing.code() + != net.firedevops.firemud.accountservice.service.DemoTenantEntitlementException + .Code.ENTITLEMENT_UNAVAILABLE) throw missing; + previous = null; + } + return demos.provision( + new DemoTenantEntitlementRequest( + UUID.randomUUID(), + tenantId, + source.creationRequestId(), + source.requestDigest(), + previous == null ? null : previous.entitlementVersion(), + previous == null ? null : previous.tenantAuthorityGeneration(), + previous == null ? null : previous.tenantAuthoritySourceVersion(), + gameplay, + join, + gameplay, + gameplay, + new DemoTenantEntitlementRequest.Quotas(3L, 2L, 4096L)), + source); + }); + } + + private Target target() { + UUID realm = UUID.randomUUID(), + state = UUID.randomUUID(), + instance = UUID.randomUUID(), + version = UUID.randomUUID(); + String digest = "a".repeat(64), initial = UUID.randomUUID().toString(); + var request = + new net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.Request( + namespace, + tenantId, + "world", + realm, + state, + "SHARED", + instance, + version, + 1L, + initial, + digest, + net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold + .InitialAdmissionOrigin.NO_PRIOR_POINTER, + 23L, + null); + var hold = + new net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity( + request, UUID.randomUUID(), UUID.randomUUID()); + return new Target( + namespace, + "tenant", + tenantId, + "world", + "World", + realm, + "production", + "Production", + 11L, + 44L, + state, + "SHARED", + instance, + version, + 1L, + 23L, + 17L, + digest, + 1L, + initial, + digest, + CanonicalGameplayAdmissionDecisionReadGrpcCodec.OriginKind.NO_PRIOR_POINTER, + null, + hold.holdId(), + hold.holdFence(), + hold.holdBindingDigest(), + 1L, + "sha256:" + digest, + CanonicalGameplayAdmissionDecisionReadGrpcCodec.OwnerProofOutcome.COMMITTED, + false, + clock.instant(), + "PRESEEDED_ONLY"); + } + + private String browserScope() { + return service + .listBootstrapRealms(bootstrap, target.tenantSlug(), target.worldSlug()) + .getFirst() + .connectScopeId(); + } + + private List characters( + String token) { + return service.listBootstrapCharacters( + bootstrap, target.worldSlug(), target.realmSlug(), token); + } + + private DirectTextCallerContext directCaller(String request) { + return new DirectTextCallerContext( + account.getAccountUuid(), + tenantId, + target.realmId(), + target.playableStateNamespaceId(), + target.playableStateScope(), + target.canonicalGameInstanceId(), + "00042", + request); + } + + private String directScope() throws Exception { + String request = UUID.randomUUID().toString(); + return peer() + .call( + () -> + service + .issueDirectTextConnectScope( + directCaller(request), + new DirectTextJoinTarget( + tenantId, + target.realmId(), + target.worldSlug(), + target.realmSlug(), + target.playableStateNamespaceId(), + target.playableStateScope(), + target.canonicalGameInstanceId(), + target.catalogRevision(), + target.pointerVersion())) + .connectScopeId()); + } + + private JoinPublicProductionResult directJoin(String token, String request) throws Exception { + return peer() + .call( + () -> + service.joinPublicProductionFromGameSession( + directCaller(request), new JoinPublicProductionRequest(token, request))); + } + + private io.grpc.Context peer() { + return io.grpc.Context.ROOT.withValue( + net.firedevops.firemud.common.grpc.GrpcPeerIdentity.CONTEXT_KEY, + new net.firedevops.firemud.common.grpc.GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/game-session-service", + namespace, + "game-session-service")); + } + + private JoinPublicProductionResult join(String token, String request) { + return service.joinPublicProduction( + bootstrap, new JoinPublicProductionRequest(token, request)); + } + + private AccountJoinOperationRepository.CanonicalJoinOperationEvidence operation( + String request) { + return in(() -> operations.findCanonicalEvidenceForUpdateByRequestId(request).orElseThrow()); + } + + /** + * Controlled prior lifecycle event; this does not claim a production leave/suspension owner. + */ + private void seedControlledInactiveSnapshot() { + seedControlledSnapshot("INACTIVE", false, List.of("player")); + } + + @SuppressWarnings("unchecked") + private void seedControlledSnapshot(String lifecycle, boolean gameplay, List roleSet) { + TransactionTemplate history = new TransactionTemplate(transactionManager); + history.setPropagationBehavior( + org.springframework.transaction.TransactionDefinition.PROPAGATION_REQUIRES_NEW); + history.setIsolationLevel( + org.springframework.transaction.TransactionDefinition.ISOLATION_READ_COMMITTED); + history.execute( + status -> { + operations.lockAccount(account.getId()); + var member = + members + .findFreshMembershipForUpdate(account.getAccountUuid(), tenantId) + .orElseThrow(); + var generation = + generations.read( + AccountAuthorityGenerationRepository.AuthorityScope.membership( + account.getAccountUuid(), tenantId)); + var beforeSource = + evidence.readCurrentIssuerAccountSources( + "firemud-account-service", account.getAccountUuid()); + + // Closed receipt/source-change mechanics supply the one shared Account fence advance. + // This remains controlled historical input, not a registered security or leave + // producer. + var currentSource = advanceControlledClosedAccountSource(beforeSource); + if (currentSource.account().generation() != beforeSource.account().generation() + 1L + || currentSource.account().sourceVersion() + != beforeSource.account().sourceVersion() + 1L + || currentSource.account().checkpoint().sequence() + != beforeSource.account().checkpoint().sequence() + 1L + || currentSource.issuanceFence().value() != generation.issuanceFence().value() + 1L + || currentSource.issuanceFence().sourceVersion() + != generation.issuanceFence().sourceVersion() + 1L) { + throw new IllegalStateException( + "Controlled Account source/fence did not advance once"); + } + int advanced = + dsl.execute( + "UPDATE account_authority_generations SET generation = generation + 1, " + + "source_version = source_version + 1, updated_at = CURRENT_TIMESTAMP " + + "WHERE scope_kind = 'MEMBERSHIP' AND issuer_id IS NULL " + + "AND account_uuid = ? AND tenant_uuid = ? AND generation = ? AND source_version = ?", + account.getAccountUuid(), + tenantId, + generation.generation(), + generation.sourceVersion()); + if (advanced != 1) { + throw new IllegalStateException( + "Controlled membership authority CAS did not advance once"); + } + var authority = + generations.readCompositeSnapshot( + "firemud-account-service", + account.getAccountUuid(), + List.of(tenantId), + List.of(tenantId)); + var next = authority.memberships().getFirst(); + if (next.generation() != generation.generation() + 1L + || next.sourceVersion() != generation.sourceVersion() + 1L + || !next.issuanceFence().equals(currentSource.issuanceFence()) + || !authority.issuanceFence().equals(currentSource.issuanceFence())) { + throw new IllegalStateException( + "Controlled membership differs from the actual Account fence"); + } + var tenantSource = sources.readCurrentSourceSelection(tenantId).checkpoint(); + var prior = pairs.readForUpdate(account.getAccountUuid(), tenantId).orElseThrow(); + var previous = outbox.findEvent(stream(), prior.eventSequence()).orElseThrow(); + Map event = + JsonMapper.builder() + .build() + .readValue(new String(previous.payload(), StandardCharsets.UTF_8), Map.class); + event.remove("eventDigest"); + String leave = "controlled-inactive-" + UUID.randomUUID(); + event.put("eventId", UUID.randomUUID().toString()); + event.put("requestId", leave); + event.put("outboxSequence", "2"); + event.put("membershipLifecycleState", lifecycle); + event.put("roles", roleSet); + event.put("membershipVersion", Map.of(tenantId.toString(), "3")); + event.put("membershipAuthorityGeneration", Long.toString(next.generation())); + Map tuple = new java.util.LinkedHashMap<>(); + tuple.put("issuerAuthGeneration", Long.toString(authority.issuer().generation())); + tuple.put( + "accountAuthorityGeneration", Long.toString(authority.account().generation())); + tuple.put( + "tenantAuthorityGeneration", + Map.of( + tenantId.toString(), + Long.toString(authority.tenants().getFirst().generation()))); + tuple.put( + "membershipAuthorityGeneration", + Map.of(tenantId.toString(), Long.toString(next.generation()))); + tuple.put("privateRealmGrantVersions", List.of()); + currentSource + .account() + .accountSecurityCutoff() + .ifPresent( + cutoff -> + tuple.put( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", cutoff.accountAuthorityGeneration(), + "outboxStreamKey", cutoff.outboxStreamKey(), + "outboxSequence", cutoff.outboxSequence()))); + tuple.put( + "tenantBillingCutoff", + Map.of( + tenantId.toString(), + Map.of( + "tenantAuthorityGeneration", + Long.toString(tenantSource.tenantAuthorityGeneration()), + "tenantBillingSequence", + Long.toString(tenantSource.tenantBillingSequence()), + "outboxStreamKey", tenantSource.outboxStreamKey(), + "outboxSequence", Long.toString(tenantSource.outboxSequence())))); + event.put("authorityTuple", tuple); + event.put("issuanceFence", Long.toString(authority.issuanceFence().value())); + event.put("gameplayAdmissionAllowed", gameplay); + event.put("callerBoundAuthorityInvalidated", true); + var sealed = MembershipAuthorityEventV1Codec.seal(event); + var appended = + outbox.append( + stream(), + leave, + sequence -> { + if (sequence != 2L) + throw new IllegalStateException("Controlled prior event sequence changed"); + return new AccountAuthorityOutboxRepository.EventEvidence( + sealed.eventId(), sealed.eventDigest(), sealed.canonicalJsonUtf8()); + }); + dsl.execute( + "UPDATE account_tenant_membership SET lifecycle_state = ?, gameplay_admission_allowed = ?, membership_version = 3, membership_authority_generation = 2 WHERE id = ?", + lifecycle, + gameplay, + member.getId()); + var inactive = + members + .findCanonicalMembershipForUpdate(account.getAccountUuid(), tenantId) + .orElseThrow(); + var provenance = + new AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance( + null, + AccountMembershipPairAuthorityRepository.TenantProvenanceKind.FRESH_GAME_DESIGN, + source.operationId(), + source.evidenceDigest()); + roles.replaceCanonical( + inactive, account.getAccountUuid(), tenantId, provenance, 3L, roleSet); + dsl.execute( + "UPDATE account_membership_pair_authority SET membership_version = 3, membership_authority_generation = 2, last_event_sequence = 2, last_event_id = ?, last_event_digest = ?, last_transition_invalidated = TRUE WHERE account_uuid = ? AND tenant_uuid = ?", + appended.eventId(), + appended.eventDigest(), + account.getAccountUuid(), + tenantId); + return null; + }); + } + + /** + * Completes one controlled closed security-state receipt in the caller's history transaction. + */ + private AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot + advanceControlledClosedAccountSource( + AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot beforeSource) { + Account current = accounts.findByAccountUuidForUpdate(account.getAccountUuid()).orElseThrow(); + var sourceState = + generations.read( + AccountAuthorityGenerationRepository.AuthorityScope.account( + account.getAccountUuid())); + var roleSource = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT global_roles, global_role_source_version FROM account_global_role_sources " + + "WHERE account_uuid = ? FOR SHARE", + account.getAccountUuid())); + long roleVersion = roleSource.get("global_role_source_version", Long.class); + var beforeState = + new AccountState( + current.isEmailVerified(), + AccountLoginAuthModes.read(current.getLoginAuthModes()).stream() + .map(Enum::name) + .sorted() + .toList(), + java.util.Arrays.stream(roleSource.get("global_roles", String[].class)) + .sorted() + .toList(), + current.getLifecycleState().name()); + var afterState = + new AccountState( + !beforeState.emailVerified(), + beforeState.loginAuthModes(), + beforeState.globalRoles(), + beforeState.lifecycleState()); + UUID requestId = UUID.randomUUID(); + // These bytes are retained fixture correlation, not authenticated caller authorization. + byte[] correlation = + ("{\"actorAccountUuid\":\"" + + account.getAccountUuid() + + "\",\"ownerEvidenceDigest\":\"sha256:" + + "a".repeat(64) + + "\",\"ownerOperationId\":\"" + + requestId + + "\",\"schemaVersion\":\"account-security-state-caller-correlation/v1\"}") + .getBytes(StandardCharsets.UTF_8); + var request = + new AccountSecurityStateMutationRequest( + requestId, + account.getAccountUuid(), + correlation, + sourceState.generation(), + sourceState.sourceVersion(), + AccountSecurityStateOperationRepository.detectedKinds(beforeState, afterState), + afterState); + var checkpoint = beforeSource.account().checkpoint(); + byte[] checkpointPayload = + checkpoint.sequence() == 0L + ? new byte[0] + : outbox + .findEvent(checkpoint.outboxStreamKey(), checkpoint.sequence()) + .orElseThrow() + .payload(); + var draft = + new Capture( + current.getId(), + current.getAccountUuidProvenance(), + beforeState, + sourceState, + checkpoint.sequence(), + checkpointPayload, + roleVersion, + null); + byte[] captureBytes = AccountSecurityStateOperationRepository.captureBytes(request, draft); + var source = + new SourceEvidence( + SourceKind.ACCOUNT, + account.getAccountUuid().toString(), + Long.toString(sourceState.generation()), + Long.toString(sourceState.sourceVersion()), + checkpoint.outboxStreamKey(), + Long.toString(checkpoint.sequence()), + captureBytes); + var change = new SourceChange(UUID.randomUUID(), List.of(source), captureBytes); + var capture = + new Capture( + draft.accountId(), + draft.provenance(), + beforeState, + sourceState, + checkpoint.sequence(), + checkpointPayload, + roleVersion, + change); + var fences = new DraftAuthorizationFenceRepository(dsl); + var security = new AccountSecurityStateOperationRepository(dsl); + if (!fences.requestSourceChange(change) + || !security.claim(request, capture).claimed() + || !fences.sourceMutationPermitted(change)) { + throw new IllegalStateException( + "Controlled closed source change is not exclusively settled"); + } + var advanced = + evidence.prepareClosedAccountAdvance(account.getAccountUuid(), beforeSource.account()); + int changed = + dsl.execute( + "UPDATE accounts SET email_verified = ? WHERE account_uuid = ? AND email_verified = ?", + afterState.emailVerified(), + account.getAccountUuid(), + beforeState.emailVerified()); + if (changed != 1) { + throw new IllegalStateException("Controlled closed Account state CAS did not change once"); + } + var event = + outbox.append( + checkpoint.outboxStreamKey(), + requestId.toString(), + sequence -> { + var sealed = + AccountSecurityStateAuthorityEventV1Codec.seal( + AccountSecurityStateMutationRequest.eventPreimage( + requestId, + account.getAccountUuid(), + Long.toString(advanced.generation()), + Long.toString(advanced.sourceVersion()), + Long.toString(sequence), + request.mutationKinds(), + afterState)); + return new AccountAuthorityOutboxRepository.EventEvidence( + sealed.eventId(), sealed.eventDigest(), sealed.canonicalJsonUtf8()); + }); + fences.markSourceCommitted(change); + var completed = security.complete(request, event, advanced, roleVersion); + assertThat(completed.receipt().orElseThrow().event()).isEqualTo(event); + assertThat(completed.receipt().orElseThrow().sourceState()).isEqualTo(advanced); + assertThat(completed.capture().sourceChange().canonicalBytes()) + .isEqualTo(change.canonicalBytes()); + assertThat(fences.readSourceChange(change).status()).isEqualTo("SOURCE_COMMITTED"); + return evidence.readCurrentIssuerAccountSources( + "firemud-account-service", account.getAccountUuid()); + } + + private List currentRoles() { + return in( + () -> { + operations.lockAccount(account.getId()); + var member = + members + .findFreshMembershipForUpdate(account.getAccountUuid(), tenantId) + .orElseThrow(); + var provenance = + new AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance( + null, + AccountMembershipPairAuthorityRepository.TenantProvenanceKind.FRESH_GAME_DESIGN, + source.operationId(), + source.evidenceDigest()); + return roles + .findForCanonicalUpdate( + account.getAccountUuid(), + tenantId, + provenance, + member.getId(), + member.getMembershipVersion()) + .orElseThrow() + .roles(); + }); + } + + private long membershipCount() { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT COUNT(*) FROM account_tenant_membership WHERE account_id = ? AND tenant_uuid = ?", + account.getId(), + tenantId)) + .get(0, Long.class); + } + + private String stream() { + return MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + account.getAccountUuid() + + "/" + + tenantId; + } + + private void assertTransitionCount(long expected) { + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM account_authority_outbox_events WHERE outbox_stream_key = ?", + stream())) + .isEqualTo(expected); + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM account_audit_outbox WHERE tenant_uuid = ? AND event_type = 'ACCOUNT_JOINED_PUBLIC_PRODUCTION'", + tenantId)) + .isEqualTo(expected); + } + + private List state(String request) { + return List.of( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT row_to_json(j)::text FROM account_join_operations j WHERE request_id = ?", + request)) + .get(0, String.class), + Objects.requireNonNull( + dsl.fetchOne( + "SELECT COALESCE(json_agg(m)::text, '[]') FROM account_tenant_membership m WHERE account_id = ? AND tenant_uuid = ?", + account.getId(), + tenantId)) + .get(0, String.class), + Objects.requireNonNull( + dsl.fetchOne( + "SELECT COALESCE(json_agg(e ORDER BY outbox_sequence)::text, '[]') FROM account_authority_outbox_events e WHERE outbox_stream_key = ?", + stream())) + .get(0, String.class), + Objects.requireNonNull( + dsl.fetchOne( + "SELECT COALESCE(json_agg(to_jsonb(a) - ARRAY['attempt_count','last_attempt_at','next_attempt_at'])::text, '[]') FROM account_audit_outbox a WHERE tenant_uuid = ?", + tenantId)) + .get(0, String.class)); + } + + private T in(Supplier work) { + return transaction.execute(status -> work.get()); + } } - private record PublicJoinFixture( - long accountId, - String accountUuid, - long tenantId, - DirectTextCallerContext caller, - String connectScopeId) {} + private static final class FixtureClock extends Clock { + private final Clock delegate; + private volatile Duration offset = Duration.ZERO; + + private FixtureClock(Clock delegate) { + this.delegate = delegate; + } + + @Override + public java.time.ZoneId getZone() { + return java.time.ZoneOffset.UTC; + } + + @Override + public Clock withZone(java.time.ZoneId zone) { + return this; + } + + @Override + public Instant instant() { + return delegate.instant().plus(offset); + } + } @Test void publicRegistrationCreatesGlobalIdentityAndDurablePlatformAuditOnly() throws Exception { @@ -1140,6 +2379,7 @@ void publicRegistrationCreatesGlobalIdentityAndDurablePlatformAuditOnly() throws } @Test + @org.springframework.test.annotation.DirtiesContext void ordinaryUuidPasswordOtpBootstrapAndScopeJourneysPreservePersistedIdentity() throws Exception { String suffix = UUID.randomUUID().toString().substring(0, 8); @@ -1231,8 +2471,29 @@ void ordinaryUuidPasswordOtpBootstrapAndScopeJourneysPreservePersistedIdentity() assertThat(bootstrapClaims.getSubject()).isEqualTo(persistedAccountUuid.toString()); assertThat(bootstrapClaims.get("accountId", String.class)) .isEqualTo(persistedAccountUuid.toString()); - org.mockito.Mockito.when(gameSessionClient.listGameplayWorlds()) - .thenReturn(java.util.List.of()); + // Controlled complete empty source; caller identity and Redis session reads remain real. + var emptyTargets = org.mockito.Mockito.mock(CanonicalGameplayAdmissionDecisionReadClient.class); + org.mockito.Mockito.when( + emptyTargets.listVisiblePublicProductionAdmissionTargets( + org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + var request = + new CanonicalGameplayAdmissionDecisionReadGrpcCodec.DiscoveryRequest( + invocation.getArgument(0, UUID.class), "test"); + return CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromDiscoveryResponse( + request, + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse( + request, List.of())); + }); + var unusedEntitlements = org.mockito.Mockito.mock(AccountPublicBootstrapEntitlementOwner.class); + canonicalFacade.setPublicBootstrapWorldsOwner( + new AccountPublicBootstrapWorldsOwner( + new AccountPlayerBootstrapCallerVerifier( + jwtUtil, accountRepository, realAccountSessions), + emptyTargets, + unusedEntitlements, + Clock.systemUTC())); String passwordBootstrap = bootstrapData.path("bootstrapToken").asText(); assertThat(bootstrapWorlds(passwordBootstrap).statusCode()).isEqualTo(200); invalidateBootstrapSession(numericAccountId, passwordBootstrap); @@ -1397,182 +2658,28 @@ void ordinaryUuidPasswordOtpBootstrapAndScopeJourneysPreservePersistedIdentity() } @Test - void browserAndControlledDirectScopesRetainUuidClaimsAndPrivateJoinRows() throws Exception { + void retainedProfileUuidProjectionAndControlAuthorizationPreservePersistedIdentity() + throws Exception { String suffix = UUID.randomUUID().toString().substring(0, 8); - String username = "scope-" + suffix; + String username = "profile-" + suffix; var account = accountService.createAccount( - new net.firedevops.firemud.accountservice.dto.CreateAccountRequest( - username, username + "@example.com", "password123")); - var persistedAccount = - java.util.Objects.requireNonNull( - dsl.fetchOne( - "SELECT id FROM accounts WHERE account_uuid=?", UUID.fromString(account.id())), - "Expected persisted Account"); + new CreateAccountRequest(username, username + "@example.com", "password123")); long row = - java.util.Objects.requireNonNull( - persistedAccount.get(0, Long.class), "Expected persisted Account storage key"); + Objects.requireNonNull( + dsl.fetchOne( + "SELECT id FROM accounts WHERE account_uuid = ?", + UUID.fromString(account.id()))) + .get(0, Long.class); long tenant = 500000000L + Integer.toUnsignedLong(suffix.hashCode()); + // Retained profile access checks relationship existence; this quarantined row grants no + // gameplay. dsl.execute( - "INSERT INTO subscription(account_id,plan_id,status,tenant_id,entitlement_version) VALUES(?,'scope-proof','active',?,1)", + "INSERT INTO account_tenant_membership (account_id, tenant_id, lifecycle_state, " + + "gameplay_admission_allowed, membership_version, membership_authority_generation, authority_provenance) " + + "VALUES (?, ?, 'LEGACY_UNVERIFIED', FALSE, 1, 1, 'LEGACY_UNVERIFIED')", row, tenant); - String realm = UUID.randomUUID().toString(); - String namespace = UUID.randomUUID().toString(); - var target = - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("scope-proof") - .setRealmSlug("production") - .setDisplayName("Scope proof") - .setTenantId(Long.toString(tenant)) - .setGameInstanceId("44") - .setRealmId(realm) - .setPlayableStateNamespaceId(namespace) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build(); - org.mockito.Mockito.when(gameSessionClient.listGameplayRealms("scope-proof")) - .thenReturn(java.util.List.of(target)); - org.mockito.Mockito.when( - gameSessionClient.getAdmissionPointer(tenant, "scope-proof", "production")) - .thenReturn( - net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() - .setWorldSlug("scope-proof") - .setRealmSlug("production") - .setTenantId(Long.toString(tenant)) - .setGameInstanceId("44") - .setRealmId(realm) - .setPlayableStateNamespaceId(namespace) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build()); - var bootstrap = accountService.issuePlayerBootstrap(username, "password123"); - String browser = - accountService - .listBootstrapRealms(bootstrap.bootstrapToken(), "scope-proof") - .getFirst() - .connectScopeId(); - var player = - net.firedevops.firemud.shared.v1.PlayerExecutionContext.newBuilder() - .setAccountId(account.id()) - .setTenantId(Long.toString(tenant)) - .setRealmId(realm) - .setPlayableStateNamespaceId(namespace) - .setPlayableStateScope("SHARED") - .setGameInstanceId("44") - .setSessionId("controlled-session") - .setRequestId("scope-direct-" + suffix) - .build(); - var request = - net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeRequest.newBuilder() - .setPlayerContext(player) - .setTenantId(Long.toString(tenant)) - .setRealmId(realm) - .setWorldSlug("scope-proof") - .setRealmSlug("production") - .setPlayableStateNamespaceId(namespace) - .setPlayableStateScope("SHARED") - .setGameInstanceId("44") - .setCatalogRevision(23L) - .setPointerVersion(17L) - .build(); - var response = - new java.util.concurrent.atomic.AtomicReference< - net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse>(); - var receiver = - new net.firedevops.firemud.accountservice.service.impl.AccountGrpcService( - org.mockito.Mockito.mock( - net.firedevops.firemud.accountservice.service.PingService.class), - accountService, - null, - "test"); - var context = - io.grpc.Context.ROOT.withValue( - net.firedevops.firemud.common.grpc.GrpcPeerIdentity.CONTEXT_KEY, - new net.firedevops.firemud.common.grpc.GrpcPeerIdentity( - "spiffe://firemud/ns/test/sa/game-session-service", - "test", - "game-session-service")); - context.run( - () -> - receiver.issueDirectTextConnectScope( - request, - new io.grpc.stub.StreamObserver<>() { - @Override - public void onNext( - net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse value) { - response.set(value); - } - - @Override - public void onError(Throwable error) { - org.junit.jupiter.api.Assertions.fail(error); - } - - @Override - public void onCompleted() {} - })); - var directResponse = - java.util.Objects.requireNonNull(response.get(), "Expected controlled direct response"); - assertThat(directResponse.hasError()).isFalse(); - String direct = directResponse.getConnectScopeId(); - var scopes = - new net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository(dsl); - for (String token : java.util.List.of(browser, direct)) { - var claims = jwtUtil.parseToken(token).getPayload(); - assertThat(claims.getSubject()).isEqualTo(account.id()); - assertThat(claims.get("accountId", String.class)).isEqualTo(account.id()); - var retained = scopes.find(token).orElseThrow(); - assertThat(retained.accountId()).isEqualTo(row); - assertThat(retained.snapshotDigest()) - .isEqualTo(net.firedevops.firemud.accountservice.dto.AccountJoinDigest.scope(retained)); - var held = - org.junit.jupiter.api.Assertions.assertThrows( - net.firedevops.firemud.accountservice.service.exception.AuthenticationException.class, - () -> - accountService.issueConnectToken( - bootstrap.bootstrapToken(), - new net.firedevops.firemud.accountservice.dto.ConnectTokenRequest( - token, "held-" + suffix))); - assertThat(held.getCode()).isEqualTo("AUTH_UNAVAILABLE"); - assertThat(scopes.find(token)).contains(retained); - } - var browserJoin = - new net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest( - browser, "scope-browser-" + suffix); - var first = accountService.joinPublicProduction(bootstrap.bootstrapToken(), browserJoin); - assertThat(first.success()).isTrue(); - assertThat(first.accountId()).isEqualTo(account.id()); - assertThat( - accountService.joinPublicProduction(bootstrap.bootstrapToken(), browserJoin).replayed()) - .isTrue(); - var caller = - new net.firedevops.firemud.accountservice.dto.DirectTextCallerContext( - row, - tenant, - UUID.fromString(realm), - namespace, - "SHARED", - 44L, - "controlled-session", - "scope-direct-" + suffix); - var directJoin = - new net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest( - direct, caller.requestId()); - assertThat(accountService.joinPublicProductionFromGameSession(caller, directJoin).success()) - .isTrue(); - assertThat(accountService.joinPublicProductionFromGameSession(caller, directJoin).replayed()) - .isTrue(); - assertThat(accountService.joinPublicProductionFromGameSession(caller, directJoin).accountId()) - .isEqualTo(account.id()); dsl.execute( "INSERT INTO profiles(account_id,tenant_id,display_name,bio,presence_visibility_policy) " + "VALUES(?,?,?,?, 'HIDDEN_STAFF')", @@ -1821,8 +2928,6 @@ public void onCompleted() {} "Expected retained private profile owner row") .get(0, Long.class)) .isEqualTo(row); - assertThat(scopes.find(browser)).isPresent(); - assertThat(scopes.find(direct)).isPresent(); } private void assertOrdinaryCredentialPreservesSocialGuildSelf( diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java index 1f5d79c7b6..15b72d484c 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java @@ -5,11 +5,13 @@ import io.grpc.ManagedChannel; import io.grpc.Server; import io.grpc.ServerInterceptors; +import io.grpc.Status; import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.io.IOException; import java.net.URI; @@ -21,27 +23,82 @@ import java.nio.file.Files; import java.nio.file.Path; import java.security.cert.CertificateEncodingException; +import java.time.Clock; +import java.time.Instant; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Deque; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.TimeUnit; -import net.firedevops.firemud.accountservice.client.GameSessionClient; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient; +import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; import net.firedevops.firemud.accountservice.client.LoggingAdminClient; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; +import net.firedevops.firemud.accountservice.config.AccountTokenProperties; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.service.AccountCanonicalConnectScopeReader; +import net.firedevops.firemud.accountservice.service.AccountCanonicalFirstJoinTerminalCoordinator; +import net.firedevops.firemud.accountservice.service.AccountCanonicalPublicRealmScopeOwner; +import net.firedevops.firemud.accountservice.service.AccountHostingSubscriptionLifecycleService; +import net.firedevops.firemud.accountservice.service.AccountPublicBootstrapEntitlementOwner; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import net.firedevops.firemud.accountservice.service.session.AccountPlayerBootstrapCallerVerifier; +import net.firedevops.firemud.accountservice.service.session.SessionService; +import net.firedevops.firemud.common.account.RuntimeAccountIdentityEvidence; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadGrpcCodec; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.entitymanagement.bootstrap.AccountBootstrapRosterFixture; +import net.firedevops.firemud.entitymanagement.bootstrap.AccountBootstrapRosterPeerInterceptor; +import net.firedevops.firemud.entitymanagement.bootstrap.AccountBootstrapRosterReadGrpcService; +import net.firedevops.firemud.entitymanagement.bootstrap.AccountBootstrapRosterReadService; +import net.firedevops.firemud.entitymanagement.client.GameSessionCanonicalGameplayRosterOwnerReadClient; import net.firedevops.firemud.entitymanagement.entity.ActorIdentityStatus; import net.firedevops.firemud.entitymanagement.mapper.CharacterMapper; import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterTarget; import net.firedevops.firemud.entitymanagement.service.PlayableStateKeyResolver; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentExpectedTarget; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentOwnerEvidence; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentRequest; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentResult; +import net.firedevops.firemud.entitymanagement.service.PreseededActorCorePayload; import net.firedevops.firemud.entitymanagement.service.ScopedCharacterResolver; import net.firedevops.firemud.entitymanagement.service.impl.CharacterServiceImpl; import net.firedevops.firemud.entitymanagement.service.impl.EntityManagementGrpcService; +import net.firedevops.firemud.entitymanagement.service.impl.GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter; import net.firedevops.firemud.entitymanagement.v1.EntityManagementServiceGrpc; import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountRequest; import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterOwnerReadServiceGrpc; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterOwnerReadRequest; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterOwnerReadResponse; import net.firedevops.firemud.test.GatewayTestProperties; import net.firedevops.firemud.test.LoopbackMtlsTestPki; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; @@ -62,11 +119,15 @@ import org.springframework.cache.concurrent.ConcurrentMapCacheManager; import org.springframework.http.HttpHeaders; import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; @@ -75,10 +136,12 @@ import tools.jackson.databind.json.JsonMapper; /** - * Composes real Account bootstrap HTTP with its mTLS Entity roster client and real Entity storage. - * Game Session target reads, test-owned membership rows, and test PKI are controlled fixtures; this - * proves neither World-owned active lifecycle nor public admission or first OPEN. Entity RPCs not - * used by ordinary roster reads remain mocked. + * Real Account HTTP registration/bootstrap/REALMS/CHARS, Redis credential lookup, canonical Account + * JOIN owners and Entity/Saga PostgreSQL assignment/discovery, with Account-to-Entity-to-GS mTLS. + * Account-side GS target/World observations and complete upstream publication/COMMITTED owner bytes + * are controlled fixtures. Assignment eligibility and local PKI are also controlled: this does not + * execute publication, GS/World owner stores, production custody, admission or first OPEN. The + * ordinary RPC is retained only for a separate numeric-selector refusal/retention proof. */ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") @@ -97,17 +160,9 @@ class BootstrapCharacterUuidEntityCompositionIntegrationTest { private static final String TEST_ACCOUNT_PEER = "spiffe://firemud/ns/test/sa/account-service"; private static final String TEST_ENTITY_PEER = "spiffe://firemud/ns/test/sa/entity-management-service"; - private static final long TARGET_TENANT_ID = 1L; - private static final long TARGET_GAME_INSTANCE_ID = 44L; - private static final String WORLD_SLUG = "uuid-bootstrap-proof"; - private static final String REALM_SLUG = "production"; - private static final UUID TARGET_REALM_ID = - UUID.fromString("d8f8de2e-89fd-4432-8cb4-93f241f56af6"); - private static final UUID TARGET_NAMESPACE_ID = - UUID.fromString("f711c0c9-c1fc-46fb-8ff2-1af7c4d96a67"); private static final long RETAINED_NUMERIC_ACCOUNT_ID = 98765L; - private static final HttpClient HTTP_CLIENT = HttpClient.newHttpClient(); + private static final AccountBootstrapRosterFixture.Fixture SOURCE = createSource(); private static final Path PKI_DIRECTORY = createTemporaryDirectory(); private static final LoopbackMtlsTestPki.Pki TEST_PKI = createTestPki(); private static final CommonGrpcClientProperties ACCOUNT_CLIENT_TLS = createAccountClientTls(); @@ -138,94 +193,414 @@ static void configure(DynamicPropertyRegistry registry) { @LocalServerPort private int accountHttpPort; @Autowired private DSLContext accountDsl; @Autowired private JwtUtil jwtUtil; - - @MockitoBean private GameSessionClient gameSessionClient; + @Autowired private AccountServiceImpl facade; + @Autowired private AccountRepository accounts; + @Autowired private AccountAuthorityGenerationRepository generations; + @Autowired private AccountAuthoritySourceEvidenceRepository accountSources; + @Autowired private FreshTenantIdentityAssociationRepository tenants; + @Autowired private AccountTenantMembershipRepository members; + @Autowired private AccountConnectScopeRepository scopes; + @Autowired private AccountTenantAuthorityEventRepository tenantEvents; + @Autowired private AccountDemoTenantEntitlementRepository demos; + @Autowired private AccountCanonicalFirstJoinTerminalCoordinator terminal; + @Autowired private AccountTokenProperties tokenProperties; + @Autowired private SessionService sessions; + @Autowired private PlatformTransactionManager transactionManager; @MockitoBean private LoggingAdminClient loggingAdminClient; @MockitoBean private JavaMailSender mailSender; - private final JsonMapper jsonMapper = JsonMapper.builder().build(); @org.junit.jupiter.api.AfterAll - static void stopEntityRuntime() throws InterruptedException { + static void stopEntityRuntime() throws Exception { EntityRuntime runtime = entityRuntime; if (runtime != null) { runtime.server().shutdownNow(); assertThat(runtime.server().awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + runtime.ownerClient().close(); + runtime.sourceServer().shutdownNow(); + assertThat(runtime.sourceServer().awaitTermination(5, TimeUnit.SECONDS)).isTrue(); runtime.meters().close(); } - if (entityPostgres.isRunning()) { - entityPostgres.stop(); - } + if (entityPostgres.isRunning()) entityPostgres.stop(); } @org.junit.jupiter.api.Test - void bootstrapCharactersUsePersistedUuidAcrossHttpAndRealEntityOwnerReads() throws Exception { - stubControlledCurrentTarget(); + void failedEntityStartupClosesEveryRegisteredResourceDespiteCleanupFailures() { + var failure = new IOException("Entity startup failed"); + var clientFailure = new IOException("Owner client cleanup failed"); + var sourceFailure = new IllegalStateException("Source server cleanup failed"); + var closed = new ArrayList(); + Deque resources = new ArrayDeque<>(); + resources.push(() -> closed.add("postgres")); + resources.push( + () -> { + closed.add("source server"); + throw sourceFailure; + }); + resources.push( + () -> { + closed.add("owner client"); + throw clientFailure; + }); + resources.push(() -> closed.add("meters")); + resources.push(() -> closed.add("entity server")); + + closeFailedStartup(failure, resources); + assertThat(closed) + .containsExactly("entity server", "meters", "owner client", "source server", "postgres"); + assertThat(failure.getSuppressed()).containsExactly(clientFailure, sourceFailure); + assertThat(resources).isEmpty(); + } + + @org.junit.jupiter.api.Test + @org.springframework.test.annotation.DirtiesContext + void bootstrapCharactersUseCanonicalOwnersAndPersistedLevelsAcrossHttpAndTwoMtlsReads() + throws Exception { + var entity = requireEntityRuntime(); String suffix = UUID.randomUUID().toString().substring(0, 8); TestAccount ownerA = registerAccount("uuid-owner-a-" + suffix); TestAccount ownerB = registerAccount("uuid-owner-b-" + suffix); assertThat(ownerA.accountUuid()).isNotEqualTo(ownerB.accountUuid()); - seedAdmittingMembership(ownerA.storageId()); - seedAdmittingMembership(ownerB.storageId()); - seedActiveSubscription(ownerA.storageId()); - - EntityRuntime entity = requireEntityRuntime(); - String ownerACharacterName = "owned-by-a-" + suffix; - String ownerBCharacterName = "owned-by-b-" + suffix; - String wrongTenantCharacterName = "wrong-tenant-a-" + suffix; - var ownerACharacter = - saveOrdinaryCharacter( - entity, TARGET_TENANT_ID, ownerA.accountUuid(), ownerACharacterName, "shared-live"); - var ownerBCharacter = - saveOrdinaryCharacter( - entity, TARGET_TENANT_ID, ownerB.accountUuid(), ownerBCharacterName, "shared-live"); - var wrongTenantCharacter = - saveOrdinaryCharacter( - entity, - TARGET_TENANT_ID + 1, - ownerA.accountUuid(), - wrongTenantCharacterName, - "shared-live"); - - assertOrdinaryUuidRowIsQuarantined(entity, ownerACharacter.getId(), ownerA.accountUuid()); - assertOrdinaryUuidRowIsQuarantined(entity, ownerBCharacter.getId(), ownerB.accountUuid()); - assertOrdinaryUuidRowIsQuarantined(entity, wrongTenantCharacter.getId(), ownerA.accountUuid()); + configureCanonicalAccountOwners(); + initializeMemberAuthority(ownerA); + initializeMemberAuthority(ownerB); + String tokenA = issuePlayerBootstrap(ownerA); + String tokenB = issuePlayerBootstrap(ownerB); + String scopeA = discoverConnectScope(ownerA, tokenA); + String scopeB = discoverConnectScope(ownerB, tokenB); + // Existing canonical JOIN is invoked as an owner composition, not a newly exposed HTTP route. + var joinedA = + facade.joinPublicProduction( + tokenA, new JoinPublicProductionRequest(scopeA, UUID.randomUUID().toString())); + var joinedB = + facade.joinPublicProduction( + tokenB, new JoinPublicProductionRequest(scopeB, UUID.randomUUID().toString())); + assertThat(joinedA.success()).isTrue(); + assertThat(joinedB.success()).isTrue(); + assertThat(joinedA.tenantId()).isEqualTo(SOURCE.target().tenantUuid()); + assertThat(joinedA.membershipVersion()).isEqualTo(2L); + assertThat(joinedB.membershipVersion()).isEqualTo(2L); + assertThat( + accountDsl + .fetch( + "SELECT role_identifier FROM account_tenant_membership_role_snapshot_roles roles " + + "JOIN account_tenant_membership member ON member.id = roles.membership_id " + + "WHERE member.tenant_uuid = ? ORDER BY member.id", + SOURCE.target().tenantUuid()) + .getValues(0, String.class)) + .containsExactly("player", "player"); + try (var client = newRosterClient()) { + client.init(); + facade.setAccountBootstrapRosterReadClient(client); + var beforeEmpty = entityRows(entity); + var emptyRoster = listBootstrapCharacters(tokenA, scopeA); + assertThat(emptyRoster.isArray()).isTrue(); + assertThat(emptyRoster.size()).isZero(); + assertThat(entityRows(entity)).isEqualTo(beforeEmpty); + } + UUID actorA = assign(entity, ownerA, SOURCE.target(), "owned-by-a-" + suffix); + UUID actorB = assign(entity, ownerB, SOURCE.target(), "owned-by-b-" + suffix); + entity.dsl().execute("UPDATE characters SET level = 12 WHERE character_uuid = ?", actorA); + assertThat( + entity + .dsl() + .fetchValue("SELECT level FROM characters WHERE character_uuid = ?", actorB)) + .isEqualTo(0); + var anotherNamespace = + CanonicalGameplayRosterTarget.fromWire( + SOURCE.target().toWire().toBuilder() + .setPlayableStateNamespaceUuid(UUID.randomUUID().toString()) + .build()); + var anotherTenant = + CanonicalGameplayRosterTarget.fromWire( + SOURCE.target().toWire().toBuilder() + .setTenantUuid(UUID.randomUUID().toString()) + .build()); + assign(entity, ownerA, anotherNamespace, "wrong-namespace-" + suffix); + assign(entity, ownerA, anotherTenant, "wrong-tenant-" + suffix); + var quarantined = saveOrdinaryCharacter(entity, ownerA.accountUuid(), "quarantined-" + suffix); + assertOrdinaryUuidRowIsQuarantined(entity, quarantined.getId(), ownerA.accountUuid()); + var entityBefore = entityRows(entity); var retainedBefore = retainedNumericOwnerRow(entity); - assertThat(retainedBefore).hasSize(1); + int ownerReadsBefore = entity.ownerReads().get(); - String ownerAToken = issuePlayerBootstrap(ownerA); - String ownerBToken = issuePlayerBootstrap(ownerB); - String ownerAScope = discoverConnectScope(ownerA, ownerAToken); - String ownerBScope = discoverConnectScope(ownerB, ownerBToken); - - JsonNode ownerACharacters = listBootstrapCharacters(ownerAToken, ownerAScope); - JsonNode ownerBCharacters = listBootstrapCharacters(ownerBToken, ownerBScope); - - assertThat(characterNames(ownerACharacters)).containsExactly(ownerACharacterName); - assertThat(characterNames(ownerACharacters)) - .doesNotContain(ownerBCharacterName, wrongTenantCharacterName); - assertThat(characterNames(ownerBCharacters)).containsExactly(ownerBCharacterName); - assertThat(characterNames(ownerBCharacters)).doesNotContain(ownerACharacterName); + try (var client = newRosterClient()) { + client.init(); + facade.setAccountBootstrapRosterReadClient(client); + JsonNode actorsA = listBootstrapCharacters(tokenA, scopeA); + JsonNode actorsB = listBootstrapCharacters(tokenB, scopeB); + assertThat(characterNames(actorsA)).containsExactly("owned-by-a-" + suffix); + assertThat(characterNames(actorsB)).containsExactly("owned-by-b-" + suffix); + assertThat(actorsA.get(0).path("characterId").asText()).isEqualTo(actorA.toString()); + assertThat(actorsB.get(0).path("characterId").asText()).isEqualTo(actorB.toString()); + assertThat(actorsA.get(0).path("level").asInt()).isEqualTo(12); + assertThat(actorsB.get(0).path("level").asInt()).isZero(); + assertThat(actorsA.get(0).has("level")).isTrue(); + assertThat(actorsB.get(0).has("level")).isTrue(); + assertThat(actorsA.get(0).path("stateScope").asText()).isEqualTo("SHARED"); + assertThat(actorsA.get(0).path("characterCreationPolicy").asText()) + .isEqualTo("PRESEEDED_ONLY"); + var crossOwner = charactersResponse(tokenA, scopeB); + assertThat(crossOwner.statusCode()).isBetween(400, 499); + assertThat(jsonMapper.readTree(crossOwner.body()).path("error").path("code").asText()) + .isEqualTo("CONNECT_SCOPE_INVALID"); + } + assertThat(entity.ownerReads().get() - ownerReadsBefore).isEqualTo(4); + assertThat(entityRows(entity)).isEqualTo(entityBefore); + assertThat(retainedNumericOwnerRow(entity)).isEqualTo(retainedBefore); + assertThat( + accountDsl.fetchValue( + "SELECT COUNT(*) FROM account_tenant_membership WHERE tenant_uuid = ?", + SOURCE.target().tenantUuid())) + .isEqualTo(2L); + assertThat( + accountDsl.fetchValue( + "SELECT COUNT(*) FROM account_audit_outbox WHERE tenant_uuid = ? AND event_type = 'ACCOUNT_JOINED_PUBLIC_PRODUCTION'", + SOURCE.target().tenantUuid())) + .isEqualTo(2L); + assertThat( + accountDsl.fetchValue( + "SELECT COUNT(*) FROM account_join_operations WHERE account_uuid IN (?, ?) AND status = 'COMMITTED'", + ownerA.accountUuid(), + ownerB.accountUuid())) + .isEqualTo(2L); + } - var retainedAccountIdRequest = + @org.junit.jupiter.api.Test + void retainedNumericSelectorIsRefusedByOrdinaryRpcWithoutRewritingItsRow() throws Exception { + var entity = requireEntityRuntime(); + var retainedBefore = retainedNumericOwnerRow(entity); + assertThat(retainedBefore).hasSize(1); + var request = ListCharactersByAccountRequest.newBuilder() - .setTenantId(Long.toString(TARGET_TENANT_ID)) + .setTenantId("1") .setAccountId(Long.toString(RETAINED_NUMERIC_ACCOUNT_ID)) - .setGameInstanceId(Long.toString(TARGET_GAME_INSTANCE_ID)) + .setGameInstanceId("44") .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .build(); - var retainedOwnerResponse = listCharactersDirectlyAsAccount(retainedAccountIdRequest); - assertThat(retainedOwnerResponse.hasError()).isTrue(); - assertThat(retainedOwnerResponse.getError().getCode()).isEqualTo("INVALID_ARGUMENT"); - assertThat(retainedOwnerResponse.getCharactersList()).isEmpty(); + var response = listCharactersDirectlyAsAccount(request); + assertThat(response.hasError()).isTrue(); + assertThat(response.getError().getCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(response.getCharactersList()).isEmpty(); assertThat(retainedNumericOwnerRow(entity)).isEqualTo(retainedBefore); } + private void configureCanonicalAccountOwners() { + var transaction = new TransactionTemplate(transactionManager); + var target = accountTarget(); + var creationRequest = UUID.randomUUID(); + var operation = UUID.randomUUID(); + String key = "b-" + operation.toString().replace("-", ""); + String digest = + GameTenantCreationDigest.requestDigest( + TEST_NAMESPACE, creationRequest, key, "Bootstrap composition", null); + long rowId = 101L; + var source = + new FreshTenantCreationEvidence( + 1, + TEST_NAMESPACE, + creationRequest, + operation, + digest, + target.canonicalTenantId(), + rowId, + key, + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + TEST_NAMESPACE, + creationRequest, + operation, + digest, + target.canonicalTenantId(), + rowId, + key, + "NEW_GAME_ROW")); + transaction.executeWithoutResult( + status -> { + tenants.importVerified(source); + generations.initializeTenantIfAbsent(target.canonicalTenantId()); + accountSources.initializeIssuerIfAbsent("firemud-account-service"); + demos.provision( + new DemoTenantEntitlementRequest( + UUID.randomUUID(), + target.canonicalTenantId(), + source.creationRequestId(), + source.requestDigest(), + null, + null, + null, + true, + true, + true, + true, + new DemoTenantEntitlementRequest.Quotas(10L, 3L, 4096L)), + source); + }); + var targets = controlledAccountTargets(target); + var hosting = Mockito.mock(AccountHostingSubscriptionLifecycleRepository.class); + var observer = Mockito.mock(StripeHostingSubscriptionObserver.class); + var clock = Clock.systemUTC(); + var entitlement = + new AccountPublicBootstrapEntitlementOwner( + tenantEvents, + new AccountHostingSubscriptionLifecycleService(hosting, observer, transactionManager), + demos, + transactionManager, + clock); + facade.setCanonicalPublicRealmScopeOwner( + new AccountCanonicalPublicRealmScopeOwner( + new AccountPlayerBootstrapCallerVerifier(jwtUtil, accounts, sessions), + targets, + entitlement, + accounts, + members, + tenants, + tenantEvents, + scopes, + jwtUtil, + tokenProperties, + clock, + transactionManager, + TEST_NAMESPACE)); + facade.setCanonicalScopeConsumers( + new AccountCanonicalConnectScopeReader(jwtUtil, scopes, transactionManager, clock), + targets, + tenantEvents, + demos, + hosting, + observer, + terminal, + TEST_NAMESPACE, + clock); + } + + private CanonicalGameplayAdmissionDecisionReadClient controlledAccountTargets(Target target) { + var client = Mockito.mock(CanonicalGameplayAdmissionDecisionReadClient.class); + Mockito.when(client.listVisiblePublicProductionAdmissionTargets(Mockito.any())) + .thenAnswer( + invocation -> { + var request = + new CanonicalGameplayAdmissionDecisionReadGrpcCodec.DiscoveryRequest( + invocation.getArgument(0, UUID.class), TEST_NAMESPACE); + return CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromDiscoveryResponse( + request, + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse( + request, List.of(target))); + }); + Mockito.when(client.resolvePublishedRealmAdmissionTarget(Mockito.any())) + .thenAnswer( + invocation -> { + var request = + invocation.getArgument( + 0, + CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector.class); + return CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromTargetResolutionResponse( + request, + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toTargetResolutionResponse( + request, target)); + }); + Mockito.when(client.readPublishedRealmAdmissionOwner(Mockito.any())) + .thenAnswer( + invocation -> { + var request = + invocation.getArgument(0, CanonicalGameplayRosterOwnerReadEvidence.Request.class); + var published = + Mockito.mock( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence.class); + Mockito.when(published.selector()).thenReturn(request); + Mockito.when(published.currentTarget()).thenReturn(target); + Mockito.when(published.sourceEvidence()).thenReturn(ownerEvidence(request)); + var world = Mockito.mock(WorldCanonicalInstanceLifecycleEvidence.class); + Mockito.when(world.lifecycleStatus()).thenReturn("ACTIVE"); + Mockito.when(world.lifecycleEpoch()).thenReturn(target.activeWorldEpoch()); + Mockito.when(published.worldLifecycleEvidence()).thenReturn(world); + return published; + }); + return client; + } + + private void initializeMemberAuthority(TestAccount account) { + new TransactionTemplate(transactionManager) + .executeWithoutResult( + status -> + generations.initialize( + AccountAuthorityGenerationRepository.AuthorityScope.membership( + account.accountUuid(), SOURCE.target().tenantUuid()))); + } + + private static Target accountTarget() { + var target = SOURCE.target(); + var proof = SOURCE.evidence().gameSessionOwnerProof(); + var hold = proof.holdIdentity(); + var request = hold.request(); + return new Target( + TEST_NAMESPACE, + "bootstrap-tenant", + target.tenantUuid(), + target.worldSlug(), + "Earth", + target.realmUuid(), + target.realmSlug(), + "Main", + 1L, + 44L, + target.playableStateNamespaceId(), + "SHARED", + target.gameInstanceUuid(), + target.canonicalVersionUuid(), + 1L, + target.catalogRevision(), + target.pointerVersion(), + target.admissionPointerSnapshotDigest(), + target.activeWorldEpoch(), + request.initialAdmissionRequestId(), + request.initialAdmissionRequestDigest(), + CanonicalGameplayAdmissionDecisionReadGrpcCodec.OriginKind.NO_PRIOR_POINTER, + null, + hold.holdId(), + hold.holdFence(), + hold.holdBindingDigest(), + proof.auditEventId(), + proof.proofDigest(), + CanonicalGameplayAdmissionDecisionReadGrpcCodec.OwnerProofOutcome.COMMITTED, + false, + proof.terminalAt(), + "PRESEEDED_ONLY"); + } + + private static CanonicalGameplayRosterOwnerReadEvidence ownerEvidence( + CanonicalGameplayRosterOwnerReadEvidence.Request request) { + var base = SOURCE.evidence().request(); + var expected = + new CanonicalGameplayRosterOwnerReadEvidence.Request( + request.requestUuid(), + request.canonicalAccountUuid(), + base.targetNamespace(), + base.canonicalTenantUuid(), + base.worldSlug(), + base.realmUuid(), + base.realmSlug(), + base.playableStateNamespaceUuid(), + base.playableStateScope(), + base.canonicalGameInstanceUuid(), + base.canonicalVersionUuid(), + base.expectedCatalogRevision(), + base.expectedPointerVersion(), + base.expectedActiveWorldEpoch()); + if (!request.equals(expected)) + throw new IllegalArgumentException("Controlled owner target mismatch"); + return new CanonicalGameplayRosterOwnerReadEvidence( + request, + SOURCE.target().admissionPointerSnapshotDigest(), + SOURCE.evidence().gameSessionOwnerProof(), + SOURCE.evidence().publishedPolicySetEvidence()); + } + private TestAccount registerAccount(String username) throws Exception { String email = username + "@example.com"; - HttpRequest request = + var request = HttpRequest.newBuilder(URI.create(accountBaseUrl() + "/accounts")) .header(HttpHeaders.CONTENT_TYPE, "application/json") .POST( @@ -233,59 +608,18 @@ private TestAccount registerAccount(String username) throws Exception { jsonMapper.writeValueAsString( Map.of("username", username, "email", email, "password", "password123")))) .build(); - HttpResponse response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); + var response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); assertThat(response.statusCode()).as(response.body()).isEqualTo(200); - - String responseUuid = jsonMapper.readTree(response.body()).path("data").path("id").asText(); - UUID accountUuid = UUID.fromString(responseUuid); - Number accountId = - accountDsl - .resultQuery("SELECT id FROM accounts WHERE email = ?", email) - .fetchOne(0, Number.class); - assertThat(accountId).isNotNull(); - long storageId = accountId.longValue(); - assertThat( - accountDsl - .resultQuery("SELECT account_uuid FROM accounts WHERE id = ?", storageId) - .fetchOne(0, UUID.class)) - .isEqualTo(accountUuid); - assertThat( - accountDsl - .resultQuery( - "SELECT account_uuid_source_numeric_id FROM accounts WHERE id = ?", storageId) - .fetchOne(0, Long.class)) - .isEqualTo(storageId); - assertThat( - accountDsl - .resultQuery("SELECT account_uuid_provenance FROM accounts WHERE id = ?", storageId) - .fetchOne(0, String.class)) - .isEqualTo("ACCOUNT_REPOSITORY_INSERT"); - return new TestAccount(username, email, storageId, accountUuid); - } - - private void seedAdmittingMembership(long accountId) { - // This is test-owned Account state for the existing roster guard, not canonical membership - // proof. - accountDsl.execute( - "INSERT INTO account_tenant_membership " - + "(account_id, tenant_id, gameplay_admission_allowed, lifecycle_state, " - + "membership_version, membership_authority_generation, authority_provenance) " - + "VALUES (?, ?, TRUE, 'ACTIVE', 1, 1, 'SEEDED_DEMO')", - accountId, - TARGET_TENANT_ID); - } - - private void seedActiveSubscription(long accountId) { - accountDsl.execute( - "INSERT INTO subscription " - + "(account_id, plan_id, status, tenant_id, entitlement_version) " - + "VALUES (?, 'uuid-bootstrap-composition', 'active', ?, 1)", - accountId, - TARGET_TENANT_ID); + UUID id = + UUID.fromString(jsonMapper.readTree(response.body()).path("data").path("id").asText()); + var row = accounts.findByAccountUuid(id).orElseThrow(); + assertThat(row.getAccountUuidSourceNumericId()).isEqualTo(row.getId()); + assertThat(row.getAccountUuidProvenance().name()).isEqualTo("ACCOUNT_REPOSITORY_INSERT"); + return new TestAccount(username, email, row.getId(), id); } private String issuePlayerBootstrap(TestAccount account) throws Exception { - HttpRequest request = + var request = HttpRequest.newBuilder(URI.create(accountBaseUrl() + "/auth/player-bootstrap")) .header(HttpHeaders.CONTENT_TYPE, "application/json") .POST( @@ -293,142 +627,195 @@ private String issuePlayerBootstrap(TestAccount account) throws Exception { jsonMapper.writeValueAsString( Map.of("accountIdentifier", account.username(), "secret", "password123")))) .build(); - HttpResponse response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); + var response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); assertThat(response.statusCode()).as(response.body()).isEqualTo(200); - JsonNode data = jsonMapper.readTree(response.body()).path("data"); + var data = jsonMapper.readTree(response.body()).path("data"); assertThat(data.path("accountId").asText()).isEqualTo(account.accountUuid().toString()); - String bootstrapToken = data.path("bootstrapToken").asText(); - var claims = jwtUtil.parseToken(bootstrapToken).getPayload(); - assertThat(claims.getSubject()).isEqualTo(account.accountUuid().toString()); - assertThat(claims.get("accountId", String.class)).isEqualTo(account.accountUuid().toString()); - return bootstrapToken; + String token = data.path("bootstrapToken").asText(); + assertThat(jwtUtil.parseToken(token).getPayload().getSubject()) + .isEqualTo(account.accountUuid().toString()); + return token; } - private String discoverConnectScope(TestAccount account, String bootstrapToken) throws Exception { - HttpRequest request = + private String discoverConnectScope(TestAccount account, String token) throws Exception { + var request = HttpRequest.newBuilder( - URI.create(accountBaseUrl() + "/auth/bootstrap/worlds/" + WORLD_SLUG + "/realms")) - .header(HttpHeaders.AUTHORIZATION, "Bearer " + bootstrapToken) + URI.create( + accountBaseUrl() + + "/auth/bootstrap/worlds/" + + SOURCE.target().worldSlug() + + "/realms?tenantSlug=" + + accountTarget().tenantSlug())) + .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) .GET() .build(); - HttpResponse response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); + var response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); + if (response.statusCode() != 200) { + // Preserve the HTTP assertion while exposing an owner/proxy exception otherwise hidden by + // the public INTERNAL_ERROR projection. This uses the same actual caller and owner setup. + org.assertj.core.api.Assertions.assertThatCode( + () -> + facade.listBootstrapRealms( + token, accountTarget().tenantSlug(), SOURCE.target().worldSlug())) + .as("REALMS owner composition after HTTP response: %s", response.body()) + .doesNotThrowAnyException(); + } assertThat(response.statusCode()).as(response.body()).isEqualTo(200); - JsonNode realms = jsonMapper.readTree(response.body()).path("data"); - assertThat(realms.isArray()).isTrue(); + var realms = jsonMapper.readTree(response.body()).path("data"); assertThat(realms.size()).isEqualTo(1); - JsonNode realm = realms.get(0); - assertThat(realm.path("tenantId").asLong()).isEqualTo(TARGET_TENANT_ID); - String scope = realm.path("connectScopeId").asText(); + assertThat(realms.get(0).path("tenantId").asText()) + .isEqualTo(SOURCE.target().tenantUuid().toString()); + String scope = realms.get(0).path("connectScopeId").asText(); var claims = jwtUtil.parseToken(scope).getPayload(); assertThat(claims.getSubject()).isEqualTo(account.accountUuid().toString()); - assertThat(claims.get("accountId", String.class)).isEqualTo(account.accountUuid().toString()); + assertThat(claims.get("scopeDigestVersion", Number.class).longValue()).isEqualTo(2L); + assertThat(claims.get("tenantId", String.class)) + .isEqualTo(SOURCE.target().tenantUuid().toString()); return scope; } - private JsonNode listBootstrapCharacters(String bootstrapToken, String connectScopeId) - throws Exception { - String encodedScope = URLEncoder.encode(connectScopeId, StandardCharsets.UTF_8); - HttpRequest request = + private HttpResponse charactersResponse(String token, String scope) throws Exception { + String encoded = URLEncoder.encode(scope, StandardCharsets.UTF_8); + var request = HttpRequest.newBuilder( URI.create( accountBaseUrl() + "/auth/bootstrap/worlds/" - + WORLD_SLUG + + SOURCE.target().worldSlug() + "/realms/" - + REALM_SLUG + + SOURCE.target().realmSlug() + "/characters?connectScopeId=" - + encodedScope)) - .header(HttpHeaders.AUTHORIZATION, "Bearer " + bootstrapToken) + + encoded)) + .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) .GET() .build(); - HttpResponse response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); - assertThat(response.statusCode()).as(response.body()).isEqualTo(200); - return jsonMapper.readTree(response.body()).path("data"); + return HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); } - private ListCharactersByAccountResponse listCharactersDirectlyAsAccount( - ListCharactersByAccountRequest request) throws Exception { - EntityRuntime runtime = requireEntityRuntime(); - var identity = TEST_PKI.identity("account"); - ManagedChannel channel = - NettyChannelBuilder.forAddress("localhost", runtime.server().getPort()) - .sslContext( - GrpcSslContexts.forClient() - .trustManager(TEST_PKI.caCertificate()) - .keyManager( - identity.privateKey(), identity.certificate(), TEST_PKI.caCertificate()) - .build()) - .intercept(new GrpcServerPeerIdentityClientInterceptor(TEST_ENTITY_PEER)) - .build(); - try { - return EntityManagementServiceGrpc.newBlockingStub(channel) - .withDeadlineAfter(5, TimeUnit.SECONDS) - .listCharactersByAccount(request); - } finally { - channel.shutdownNow(); - assertThat(channel.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); - } + private JsonNode listBootstrapCharacters(String token, String scope) throws Exception { + var response = charactersResponse(token, scope); + assertThat(response.statusCode()).as(response.body()).isEqualTo(200); + return jsonMapper.readTree(response.body()).path("data"); } - private void stubControlledCurrentTarget() { - var realm = - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug(WORLD_SLUG) - .setRealmSlug(REALM_SLUG) - .setDisplayName("Controlled UUID composition target") - .setTenantId(Long.toString(TARGET_TENANT_ID)) - .setGameInstanceId(Long.toString(TARGET_GAME_INSTANCE_ID)) - .setRealmId(TARGET_REALM_ID.toString()) - .setPlayableStateNamespaceId(TARGET_NAMESPACE_ID.toString()) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build(); - var pointer = - net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() - .setWorldSlug(WORLD_SLUG) - .setRealmSlug(REALM_SLUG) - .setTenantId(Long.toString(TARGET_TENANT_ID)) - .setGameInstanceId(Long.toString(TARGET_GAME_INSTANCE_ID)) - .setRealmId(TARGET_REALM_ID.toString()) - .setPlayableStateNamespaceId(TARGET_NAMESPACE_ID.toString()) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build(); - Mockito.when(gameSessionClient.listGameplayRealms(WORLD_SLUG)).thenReturn(List.of(realm)); - Mockito.when(gameSessionClient.getAdmissionPointer(TARGET_TENANT_ID, WORLD_SLUG, REALM_SLUG)) - .thenReturn(pointer); + private static UUID assign( + EntityRuntime runtime, + TestAccount account, + CanonicalGameplayRosterTarget target, + String name) { + UUID operation = UUID.randomUUID(); + var evidence = + new PreseededActorAssignmentOwnerEvidence( + operation, + account.accountUuid(), + PreseededActorAssignmentOwnerEvidence.Eligibility.ELIGIBLE, + Instant.parse("2026-10-04T00:00:00Z"), + 4L, + "1".repeat(64), + target.tenantUuid(), + target.realmUuid(), + target.worldSlug(), + target.realmSlug(), + target.gameInstanceUuid().toString(), + target.catalogRevision(), + target.canonicalVersionUuid(), + target.publishedPolicyDigest(), + target.playableStateNamespaceId(), + target.playableStateScope(), + PreseededActorAssignmentOwnerEvidence.PublishedEntryPolicy.PRESEEDED_ONLY, + PreseededActorAssignmentOwnerEvidence.AccountPurpose.PRESEEDED_ACTOR_STAGING, + PreseededActorAssignmentOwnerEvidence.AccountCurrentness.CURRENT_AT_REVALIDATION, + "2".repeat(64), + target.publishedOwnerProofDigest(), + target.publishedReleaseBundleRef()); + var request = + new PreseededActorAssignmentRequest( + operation, + account.accountUuid(), + new PreseededActorCorePayload(PreseededActorCorePayload.ActorKind.PLAYER, name), + new PreseededActorAssignmentExpectedTarget( + target.tenantUuid(), + target.realmUuid(), + target.worldSlug(), + target.realmSlug(), + target.gameInstanceUuid().toString(), + target.catalogRevision(), + target.canonicalVersionUuid(), + target.publishedPolicyDigest(), + target.playableStateNamespaceId(), + target.publishedReleaseBundleRef(), + target.playableStateScope())); + var result = + new TransactionTemplate(runtime.transactionManager()) + .execute( + status -> + runtime + .characterRepository() + .assignPreseededActor( + request, + evidence, + new RuntimeAccountIdentityEvidence( + 1, + TEST_NAMESPACE, + operation, + account.accountUuid(), + account.storageId(), + "ACCOUNT_REPOSITORY_INSERT"), + request.mutationIntentDigest())); + assertThat(result.outcome()).isEqualTo(PreseededActorAssignmentResult.Outcome.ASSIGNED); + assertThat( + runtime + .dsl() + .fetchValue( + "SELECT actor_identity_status FROM characters WHERE character_uuid = ?", + result.characterUuid())) + .isEqualTo("OWNER_RESOLVED"); + return result.characterUuid(); } private static net.firedevops.firemud.entitymanagement.entity.Character saveOrdinaryCharacter( - EntityRuntime runtime, - long tenantId, - UUID accountUuid, - String name, - String playableStateKey) { + EntityRuntime runtime, UUID account, String name) { var character = new net.firedevops.firemud.entitymanagement.entity.Character(); - character.setTenantId(tenantId); - character.setAccountUuid(accountUuid); - character.setPlayableStateKey(playableStateKey); + character.setTenantId(1L); + character.setAccountUuid(account); + character.setPlayableStateKey("shared-live"); character.setName(name); return runtime.characterRepository().save(character); } private static void assertOrdinaryUuidRowIsQuarantined( - EntityRuntime runtime, long characterId, UUID accountUuid) { - var persisted = runtime.characterRepository().findById(characterId).orElseThrow(); - assertThat(persisted.getAccountUuid()).isEqualTo(accountUuid); - assertThat(persisted.getAccountId()).isNull(); - assertThat(persisted.getActorIdentity().status()).isEqualTo(ActorIdentityStatus.QUARANTINED); - assertThat(persisted.getActorIdentity().tenantUuid()).isNull(); - assertThat(persisted.getActorIdentity().playableStateNamespaceId()).isNull(); + EntityRuntime runtime, long id, UUID account) { + var character = runtime.characterRepository().findById(id).orElseThrow(); + assertThat(character.getAccountUuid()).isEqualTo(account); + assertThat(character.getAccountId()).isNull(); + assertThat(character.getActorIdentity().status()).isEqualTo(ActorIdentityStatus.QUARANTINED); + assertThat(character.getActorIdentity().tenantUuid()).isNull(); + assertThat(character.getActorIdentity().playableStateNamespaceId()).isNull(); + } + + private static Map> entityRows(EntityRuntime runtime) { + var rows = new LinkedHashMap>(); + for (String table : + List.of( + "characters", + "entity_playable_state_namespace_scopes", + "entity_preseeded_actor_assignment_operations", + "entity_canonical_gameplay_roster_snapshots", + "entity_canonical_gameplay_roster_snapshot_actors", + "entity_canonical_roster_original_selections", + "entity_canonical_roster_admissions", + "entity_canonical_roster_retention_references")) { + rows.put( + table, + runtime + .dsl() + .fetch( + "SELECT to_jsonb(t)::text || ':' || xmin::text AS value FROM " + + table + + " t ORDER BY value") + .getValues(0, String.class)); + } + return rows; } private static List> retainedNumericOwnerRow(EntityRuntime runtime) { @@ -453,133 +840,243 @@ private static String entityServiceTarget() { return "localhost:" + requireEntityRuntime().server().getPort(); } + private static AccountBootstrapRosterReadClient newRosterClient() { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setEntityManagementService(entityServiceTarget()); + return new AccountBootstrapRosterReadClient( + endpoints, ACCOUNT_CLIENT_TLS, new GrpcChannelFactory(), TEST_NAMESPACE); + } + private static synchronized EntityRuntime requireEntityRuntime() { - if (entityRuntime != null) { - return entityRuntime; - } + if (entityRuntime != null) return entityRuntime; + Deque startedResources = new ArrayDeque<>(); + startedResources.push( + () -> { + if (entityPostgres.isRunning()) entityPostgres.stop(); + }); try { - if (!entityPostgres.isRunning()) { - entityPostgres.start(); - } - var dataSource = + if (!entityPostgres.isRunning()) entityPostgres.start(); + var ds = new DriverManagerDataSource( entityPostgres.getJdbcUrl(), entityPostgres.getUsername(), entityPostgres.getPassword()); - String migrationProperty = - System.getProperty("firemud.entity-management.migration-directory"); - if (migrationProperty == null || migrationProperty.isBlank()) { - throw new IllegalStateException("Entity migration directory property is missing or blank"); - } - Path migrationDirectory = Path.of(migrationProperty); - if (!Files.isDirectory(migrationDirectory)) { - throw new IllegalStateException( - "Entity migration directory is unavailable: " + migrationDirectory); - } - entityMigrationConfiguration(dataSource, migrationDirectory) + String configured = System.getProperty("firemud.entity-management.migration-directory"); + if (configured == null || !Files.isDirectory(Path.of(configured))) + throw new IllegalStateException("Entity migration directory is unavailable"); + var migrations = Path.of(configured); + entityMigrationConfiguration(ds, migrations) .target(MigrationVersion.fromVersion("1023")) .load() .migrate(); - var jdbc = new JdbcTemplate(dataSource); + var jdbc = new JdbcTemplate(ds); jdbc.update( - "INSERT INTO characters (tenant_id, account_id, name) VALUES (?, ?, ?)", - TARGET_TENANT_ID, - RETAINED_NUMERIC_ACCOUNT_ID, - "retained-numeric-owner"); - entityMigrationConfiguration(dataSource, migrationDirectory).load().migrate(); - - DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + "INSERT INTO characters (tenant_id, account_id, name) VALUES (1, ?, 'retained-numeric-owner')", + RETAINED_NUMERIC_ACCOUNT_ID); + entityMigrationConfiguration(ds, migrations).load().migrate(); + var manager = new DataSourceTransactionManager(ds); + DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(ds), SQLDialect.POSTGRES); var repository = new CharacterRepository(dsl); - var stateKeys = new PlayableStateKeyResolver(); - var meters = new SimpleMeterRegistry(); - var characterService = - new CharacterServiceImpl( - repository, - Mappers.getMapper(CharacterMapper.class), - new ConcurrentMapCacheManager("characterGraph"), - meters, - stateKeys, - new ScopedCharacterResolver(repository, stateKeys)); - var receiver = - new EntityManagementGrpcService( - Mockito.mock(net.firedevops.firemud.entitymanagement.service.PingService.class), - characterService, - Mockito.mock(net.firedevops.firemud.entitymanagement.service.ActorStateService.class), - Mockito.mock( - net.firedevops.firemud.entitymanagement.service.ActorConditionMutationService - .class), - Mockito.mock( - net.firedevops.firemud.entitymanagement.service.EntityDraftDesignDigestService - .class), - Mockito.mock(net.firedevops.firemud.entitymanagement.service.EquipmentService.class), - Mockito.mock(net.firedevops.firemud.entitymanagement.service.InventoryService.class), - Mockito.mock(net.firedevops.firemud.entitymanagement.service.ContainerService.class), - Mockito.mock(net.firedevops.firemud.entitymanagement.service.RoomEntityService.class), - Mockito.mock( - net.firedevops.firemud.entitymanagement.service.RuntimeInstanceCleanupService - .class), - Mockito.mock( - net.firedevops.firemud.entitymanagement.service.impl - .EntityMutationEffectReplayService.class), - Mockito.mock( - net.firedevops.firemud.entitymanagement.service.EntityUpgradeValidationService - .class), - Mockito.mock( - net.firedevops.firemud.entitymanagement.service.EntityTemplateReferenceService - .class), - Mockito.mock( - net.firedevops.firemud.common.security.GameplaySessionAttestationService.class), - meters, - Mockito.mock( - net.firedevops.firemud.entitymanagement.effect.EffectPayloadParser.class), + var reads = new AtomicInteger(); + Server sourceServer = startSourceServer(reads); + startedResources.push(() -> stopFixtureServer(sourceServer)); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameSessionService("localhost:" + sourceServer.getPort()); + var client = + new GameSessionCanonicalGameplayRosterOwnerReadClient( + endpoints, + TEST_PKI.clientProperties(PKI_DIRECTORY, TEST_PKI.identity("entity-client")), + new GrpcChannelFactory(), TEST_NAMESPACE); - var entityIdentity = TEST_PKI.identity("entity"); + startedResources.push(client); + client.init(); + var service = + new AccountBootstrapRosterReadService( + new GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter(client, TEST_NAMESPACE), + repository, + manager); + var meters = new SimpleMeterRegistry(); + startedResources.push(meters::close); + var identity = TEST_PKI.identity("entity"); Server server = NettyServerBuilder.forPort(0) .sslContext( GrpcSslContexts.configure( SslContextBuilder.forServer( - entityIdentity.privateKey(), entityIdentity.certificate())) + identity.privateKey(), identity.certificate())) .trustManager(TEST_PKI.caCertificate()) .clientAuth(ClientAuth.REQUIRE) .build()) - .addService(ServerInterceptors.intercept(receiver, new GrpcPeerIdentityInterceptor())) - .build() - .start(); - entityRuntime = new EntityRuntime(repository, jdbc, server, meters); + .addService( + ServerInterceptors.intercept( + new AccountBootstrapRosterReadGrpcService(service, TEST_NAMESPACE), + new AccountBootstrapRosterPeerInterceptor(TEST_NAMESPACE))) + .addService( + ServerInterceptors.intercept( + ordinaryReceiver(repository, meters), new GrpcPeerIdentityInterceptor())) + .build(); + startedResources.push(() -> stopFixtureServer(server)); + server.start(); + entityRuntime = + new EntityRuntime( + repository, jdbc, dsl, manager, server, sourceServer, client, reads, meters); return entityRuntime; - } catch (IOException | RuntimeException failure) { - if (entityPostgres.isRunning()) { - entityPostgres.stop(); - } + } catch (IOException | CertificateEncodingException | RuntimeException failure) { + closeFailedStartup(failure, startedResources); throw new IllegalStateException( "Could not start the real Entity mTLS owner fixture", failure); } } + private static void closeFailedStartup(Throwable failure, Deque resources) { + boolean interrupted = false; + while (!resources.isEmpty()) { + try { + resources.pop().close(); + } catch (Exception cleanup) { + failure.addSuppressed(cleanup); + if (cleanup instanceof InterruptedException) interrupted = true; + } + } + if (interrupted) Thread.currentThread().interrupt(); + } + + private static void stopFixtureServer(Server server) throws InterruptedException { + server.shutdownNow(); + if (!server.awaitTermination(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("Entity fixture gRPC server did not terminate"); + } + } + + private static Server startSourceServer(AtomicInteger reads) throws IOException { + var identity = TEST_PKI.identity("gs"); + return NettyServerBuilder.forPort(0) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(TEST_PKI.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + new CanonicalGameplayRosterOwnerReadServiceGrpc + .CanonicalGameplayRosterOwnerReadServiceImplBase() { + @Override + public void getCanonicalGameplayRosterOwnerRead( + GetCanonicalGameplayRosterOwnerReadRequest wire, + StreamObserver observer) { + var peer = GrpcPeerIdentity.current(); + if (peer == null + || !peer.isService("entity-management-service") + || !peer.isInNamespace(TEST_NAMESPACE)) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + try { + var request = CanonicalGameplayRosterOwnerReadGrpcCodec.fromRequest(wire); + var evidence = ownerEvidence(request); + reads.incrementAndGet(); + observer.onNext( + CanonicalGameplayRosterOwnerReadGrpcCodec.toResponse(request, evidence)); + observer.onCompleted(); + } catch (IllegalArgumentException invalid) { + observer.onError(Status.FAILED_PRECONDITION.asRuntimeException()); + } + } + }, + new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private static EntityManagementGrpcService ordinaryReceiver( + CharacterRepository repository, SimpleMeterRegistry meters) { + var stateKeys = new PlayableStateKeyResolver(); + var characters = + new CharacterServiceImpl( + repository, + Mappers.getMapper(CharacterMapper.class), + new ConcurrentMapCacheManager("characterGraph"), + meters, + stateKeys, + new ScopedCharacterResolver(repository, stateKeys)); + return new EntityManagementGrpcService( + Mockito.mock(net.firedevops.firemud.entitymanagement.service.PingService.class), + characters, + Mockito.mock(net.firedevops.firemud.entitymanagement.service.ActorStateService.class), + Mockito.mock( + net.firedevops.firemud.entitymanagement.service.ActorConditionMutationService.class), + Mockito.mock( + net.firedevops.firemud.entitymanagement.service.EntityDraftDesignDigestService.class), + Mockito.mock(net.firedevops.firemud.entitymanagement.service.EquipmentService.class), + Mockito.mock(net.firedevops.firemud.entitymanagement.service.InventoryService.class), + Mockito.mock(net.firedevops.firemud.entitymanagement.service.ContainerService.class), + Mockito.mock(net.firedevops.firemud.entitymanagement.service.RoomEntityService.class), + Mockito.mock( + net.firedevops.firemud.entitymanagement.service.RuntimeInstanceCleanupService.class), + Mockito.mock( + net.firedevops.firemud.entitymanagement.service.impl.EntityMutationEffectReplayService + .class), + Mockito.mock( + net.firedevops.firemud.entitymanagement.service.EntityUpgradeValidationService.class), + Mockito.mock( + net.firedevops.firemud.entitymanagement.service.EntityTemplateReferenceService.class), + Mockito.mock( + net.firedevops.firemud.common.security.GameplaySessionAttestationService.class), + meters, + Mockito.mock(net.firedevops.firemud.entitymanagement.effect.EffectPayloadParser.class), + TEST_NAMESPACE); + } + + private ListCharactersByAccountResponse listCharactersDirectlyAsAccount( + ListCharactersByAccountRequest request) throws Exception { + var identity = TEST_PKI.identity("account"); + ManagedChannel channel = + NettyChannelBuilder.forAddress("localhost", requireEntityRuntime().server().getPort()) + .sslContext( + GrpcSslContexts.forClient() + .trustManager(TEST_PKI.caCertificate()) + .keyManager( + identity.privateKey(), identity.certificate(), TEST_PKI.caCertificate()) + .build()) + .intercept(new GrpcServerPeerIdentityClientInterceptor(TEST_ENTITY_PEER)) + .build(); + try { + return EntityManagementServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .listCharactersByAccount(request); + } finally { + channel.shutdownNow(); + assertThat(channel.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + private static FluentConfiguration entityMigrationConfiguration( - DriverManagerDataSource dataSource, Path migrationDirectory) { - FluentConfiguration configuration = + DriverManagerDataSource ds, Path directory) { + var config = Flyway.configure() - .dataSource(dataSource) - .locations( - "filesystem:" + migrationDirectory, - "filesystem:" - + migrationDirectory - .resolve( - "../../../../../../common-saga/src/main/resources/db/migration/saga") - .normalize()) + .dataSource(ds) + .table("flyway_schema_history_entity_management_service") + .locations("filesystem:" + directory, "classpath:db/migration/saga") .placeholders(Map.of("serviceSchema", "public")); - configuration + config .getConfigurationExtension(PostgreSQLConfigurationExtension.class) .setTransactionalLock(false); - return configuration; + return config; + } + + private static AccountBootstrapRosterFixture.Fixture createSource() { + try { + return AccountBootstrapRosterFixture.create(); + } catch (Exception failure) { + throw new ExceptionInInitializerError(failure); + } } private static Path createTemporaryDirectory() { try { return Files.createTempDirectory("firemud-account-entity-composition-"); - } catch (Exception failure) { + } catch (IOException failure) { throw new ExceptionInInitializerError(failure); } } @@ -590,7 +1087,10 @@ private static LoopbackMtlsTestPki.Pki createTestPki() { PKI_DIRECTORY, "Account-to-Entity composition proof CA", new LoopbackMtlsTestPki.IdentitySpec("entity", TEST_ENTITY_PEER, true), - new LoopbackMtlsTestPki.IdentitySpec("account", TEST_ACCOUNT_PEER, false)); + new LoopbackMtlsTestPki.IdentitySpec("account", TEST_ACCOUNT_PEER, false), + new LoopbackMtlsTestPki.IdentitySpec("entity-client", TEST_ENTITY_PEER, false), + new LoopbackMtlsTestPki.IdentitySpec( + "gs", "spiffe://firemud/ns/test/sa/game-session-service", true)); } catch (Exception failure) { throw new ExceptionInInitializerError(failure); } @@ -599,7 +1099,7 @@ private static LoopbackMtlsTestPki.Pki createTestPki() { private static CommonGrpcClientProperties createAccountClientTls() { try { return TEST_PKI.clientProperties(PKI_DIRECTORY, TEST_PKI.identity("account")); - } catch (CertificateEncodingException | java.io.IOException failure) { + } catch (CertificateEncodingException | IOException failure) { throw new ExceptionInInitializerError(failure); } } @@ -609,6 +1109,11 @@ private record TestAccount(String username, String email, long storageId, UUID a private record EntityRuntime( CharacterRepository characterRepository, JdbcTemplate jdbc, + DSLContext dsl, + DataSourceTransactionManager transactionManager, Server server, + Server sourceServer, + GameSessionCanonicalGameplayRosterOwnerReadClient ownerClient, + AtomicInteger ownerReads, SimpleMeterRegistry meters) {} } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java index 706cd84e0c..f5952eeb40 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java @@ -38,6 +38,7 @@ import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; import net.firedevops.firemud.accountservice.repository.PasswordResetTokenRepository; +import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback.LatestSourceSnapshot; import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; @@ -785,8 +786,7 @@ private AccountServiceImpl newService( fixture.logoutAllOperations(), fixture.securityStateOperations(), fixture.sourceChanges(), - null, // audit outbox - null, // connect scopes + null, // audit outbox is not on the password-reset path null, // join operations null, // email login challenges null, // realm grants @@ -795,7 +795,8 @@ private AccountServiceImpl newService( null, // profiles null, // profile mapper null, // payment transactions - null, // subscriptions + // retained subscription evidence + org.mockito.Mockito.mock(RetainedSubscriptionEvidenceRepository.class), null, // external account identities fixture.tokens(), null, // email verification tokens @@ -806,8 +807,6 @@ private AccountServiceImpl newService( null, null, null, - null, - null, fixture.transactionManager()); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthorityCurrentnessIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthorityCurrentnessIntegrationTest.java index efbabc1e55..c6b3054318 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthorityCurrentnessIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthorityCurrentnessIntegrationTest.java @@ -1,7 +1,9 @@ package integration.net.firedevops.firemud.accountservice.repository; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.time.Duration; import java.time.Instant; import java.util.List; import java.util.Map; @@ -14,9 +16,12 @@ import java.util.concurrent.TimeUnit; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountRealmAccessGrant; -import net.firedevops.firemud.accountservice.entity.Subscription; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionCurrentReceipt; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.Outcome; import net.firedevops.firemud.accountservice.repository.AccountRealmAccessGrantRepository; -import net.firedevops.firemud.accountservice.repository.SubscriptionRepository; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; @@ -29,7 +34,7 @@ import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; import org.springframework.transaction.support.TransactionTemplate; -/** Physical V31/V32 currentness proof, isolated from Account lifecycle/source writers. */ +/** Canonical hosting lifecycle/source currentness and separate realm-grant tombstone/CAS proof. */ class AccountAuthorityCurrentnessIntegrationTest { private static final AccountPostgresIntegrationFixture postgres = new AccountPostgresIntegrationFixture(); @@ -59,39 +64,115 @@ void subscriptionAndRealmGrantMutationsAdvanceCurrentnessAndKeepRevocationTombst JdbcTemplate jdbc = new JdbcTemplate(dataSource); DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); - Long accountId = - Objects.requireNonNull( + var fixture = CanonicalHostingSubscriptionTestFixture.create(dataSource); + var claim = + fixture + .service() + .claimProvisioning(fixture.creation().requestId(), 1, UUID.randomUUID()) + .claim(); + UUID initialRequest = UUID.randomUUID(); + var initialCommit = + fixture + .service() + .reconcile( + initialRequest, + fixture.creation().requestId(), + claim.subscriptionRowVersion(), + fixture.providerId(), + claim.attemptId()); + assertThat(initialCommit.outcome()).isEqualTo(Outcome.COMMITTED); + var initial = fixture.service().readCurrent(fixture.tenantId()); + assertThat(initial.entitlementVersion()).isOne(); + assertCanonicalCheckpoint(fixture, initial); + int initialReads = fixture.transport().reads(); + assertThat( + fixture + .service() + .reconcile( + initialRequest, + fixture.creation().requestId(), + claim.subscriptionRowVersion(), + fixture.providerId(), + claim.attemptId())) + .isEqualTo(initialCommit); + assertThat(fixture.transport().reads()).isEqualTo(initialReads); + var initialRetry = fixture.service().readCurrent(fixture.tenantId()); + assertThat(initialRetry.receiptRequestId()).isEqualTo(initial.receiptRequestId()); + assertThat(initialRetry.tenantAuthorityEvent().payload()) + .isEqualTo(initial.tenantAuthorityEvent().payload()); + + fixture.clock().advance(Duration.ofSeconds(1)); + fixture.providerStatus("canceled"); + UUID changedRequest = UUID.randomUUID(); + var changedCommit = + fixture + .service() + .reconcile( + changedRequest, + fixture.creation().requestId(), + initial.current().rowVersion(), + fixture.providerId(), + null); + assertThat(changedCommit.outcome()).isEqualTo(Outcome.COMMITTED); + var changed = fixture.service().readCurrent(fixture.tenantId()); + assertThat(changed.rawProviderStatus()).isEqualTo("canceled"); + assertThat(changed.entitlementVersion()).isGreaterThan(initial.entitlementVersion()); + assertThat(changed.tenantBillingSequence()).isGreaterThan(initial.tenantBillingSequence()); + assertThat(changed.tenantAuthorityEvent().tenantAuthorityGeneration()) + .isGreaterThan(initial.tenantAuthorityEvent().tenantAuthorityGeneration()); + assertThat(changed.tenantAuthorityEvent().outboxSequence()) + .isGreaterThan(initial.tenantAuthorityEvent().outboxSequence()); + assertThat(changed.tenantAuthorityEvent().eventId()) + .isNotEqualTo(initial.tenantAuthorityEvent().eventId()); + assertCanonicalCheckpoint(fixture, changed); + + assertThatThrownBy( + () -> + jdbc.update( + "UPDATE subscription SET status = 'active', row_version = row_version + 1 WHERE subscription_id = ?", + fixture.creation().subscriptionId())) + .isInstanceOf(org.springframework.dao.DataIntegrityViolationException.class); + int changedReads = fixture.transport().reads(); + assertThat( + fixture + .service() + .reconcile( + changedRequest, + fixture.creation().requestId(), + initial.current().rowVersion(), + fixture.providerId(), + null)) + .isEqualTo(changedCommit); + assertThat(fixture.transport().reads()).isEqualTo(changedReads); + var changedRetry = fixture.service().readCurrent(fixture.tenantId()); + assertThat(changedRetry.current()).isEqualTo(changed.current()); + assertThat(changedRetry.receiptRequestId()).isEqualTo(changed.receiptRequestId()); + assertThat(changedRetry.tenantAuthorityEvent().payload()) + .isEqualTo(changed.tenantAuthorityEvent().payload()); + assertCanonicalCheckpoint(fixture, changedRetry); + assertThat( jdbc.queryForObject( - "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) RETURNING id", + "SELECT payload FROM account_authority_outbox_events WHERE outbox_stream_key = ? AND outbox_sequence = ?", + byte[].class, + initial.tenantAuthorityEvent().outboxStreamKey(), + initial.tenantAuthorityEvent().outboxSequence())) + .isEqualTo(initial.tenantAuthorityEvent().payload()); + assertThat( + jdbc.queryForObject( + "SELECT count(*) FROM account_authority_outbox_events WHERE outbox_stream_key = ?", Long.class, - "currentness-" + UUID.randomUUID(), - "currentness-" + UUID.randomUUID() + "@example.test", - "test-hash")); + changed.tenantAuthorityEvent().outboxStreamKey())) + .isEqualTo(2L); + assertThat( + jdbc.queryForObject( + "SELECT count(*) FROM account_tenant_entitlement_outbox_events WHERE tenant_uuid = ?", + Long.class, + fixture.tenantId())) + .isEqualTo(2L); + // Realm grants retain their separate authority and numeric legacy scope in this existing proof. + long accountId = fixture.accountId(); long tenantId = 7_654_322L; - jdbc.update( - "INSERT INTO subscription (account_id, plan_id, status, tenant_id, entitlement_version) " - + "VALUES (?, 'test-plan', 'active', ?, 1)", - accountId, - tenantId); - SubscriptionRepository subscriptions = new SubscriptionRepository(dsl); - Subscription subscription = subscriptions.findByTenantId(tenantId).getFirst(); - UUID initialTenantGeneration = subscription.getTenantAuthorityGeneration(); - assertThat(initialTenantGeneration).isNotNull(); - assertThat(subscription.getEntitlementVersion()).isEqualTo(1L); - - subscription.setStatus("past_due"); - subscriptions.save(subscription); - Subscription repositoryUpdated = subscriptions.findByTenantId(tenantId).getFirst(); - assertThat(repositoryUpdated.getTenantAuthorityGeneration()) - .isNotEqualTo(initialTenantGeneration); - assertThat(repositoryUpdated.getEntitlementVersion()).isEqualTo(2L); - - jdbc.update("UPDATE subscription SET status = 'active' WHERE tenant_id = ?", tenantId); - Subscription directlyUpdated = subscriptions.findByTenantId(tenantId).getFirst(); - assertThat(directlyUpdated.getTenantAuthorityGeneration()) - .isNotEqualTo(repositoryUpdated.getTenantAuthorityGeneration()); - assertThat(directlyUpdated.getEntitlementVersion()).isEqualTo(3L); Account account = new Account(); account.setId(accountId); @@ -141,6 +222,57 @@ void subscriptionAndRealmGrantMutationsAdvanceCurrentnessAndKeepRevocationTombst .isFalse(); } + private static void assertCanonicalCheckpoint( + CanonicalHostingSubscriptionTestFixture.Fixture fixture, + AccountHostingSubscriptionCurrentReceipt receipt) { + var event = receipt.tenantAuthorityEvent(); + assertThat(event.tenantId()).isEqualTo(fixture.tenantId()); + assertThat(event.tenantBillingSequence()).isEqualTo(receipt.tenantBillingSequence()); + assertThat(event.tenantBillingEventId()).isEqualTo(receipt.billingEventId()); + assertThat(event.tenantBillingEventDigest()).isEqualTo(receipt.billingEventDigest()); + fixture + .transaction() + .executeWithoutResult( + status -> { + var currentGeneration = + new AccountAuthorityGenerationRepository(fixture.dsl()) + .read(AuthorityScope.tenant(fixture.tenantId())); + assertThat(currentGeneration.generation()) + .isEqualTo(event.tenantAuthorityGeneration()); + assertThat(currentGeneration.sourceVersion()) + .isEqualTo(event.tenantAuthoritySourceVersion()); + var checkpoint = + new AccountAuthorityOutboxRepository(fixture.dsl()) + .readCheckpoint(event.outboxStreamKey()) + .orElseThrow(); + assertThat(checkpoint.outboxSequence()).isEqualTo(event.outboxSequence()); + assertThat(checkpoint.sourceEventId()).isEqualTo(event.eventId().toString()); + assertThat(checkpoint.sourceEventDigest()).isEqualTo(event.eventDigest()); + assertThat( + fixture + .jdbc() + .queryForObject( + "SELECT event_digest FROM account_tenant_entitlement_outbox_events WHERE tenant_uuid = ? AND tenant_billing_sequence = ? AND event_id = ?", + String.class, + fixture.tenantId(), + receipt.tenantBillingSequence(), + receipt.billingEventId())) + .isEqualTo(receipt.billingEventDigest()); + assertThat( + fixture + .jdbc() + .queryForMap( + "SELECT current_generation, tenant_billing_sequence, last_outbox_sequence, " + + "last_event_id, last_event_digest FROM account_tenant_authority_source_records WHERE tenant_uuid = ?", + fixture.tenantId())) + .containsEntry("current_generation", event.tenantAuthorityGeneration()) + .containsEntry("tenant_billing_sequence", receipt.tenantBillingSequence()) + .containsEntry("last_outbox_sequence", checkpoint.outboxSequence()) + .containsEntry("last_event_id", event.eventId().toString()) + .containsEntry("last_event_digest", event.eventDigest()); + }); + } + @Test void concurrentRealmGrantWritersCannotOverwriteAnObservedGeneration() throws Exception { String schema = "account_grant_cas_" + UUID.randomUUID().toString().replace("-", ""); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java index caba218cf3..a052837a81 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java @@ -123,7 +123,6 @@ void preV40RetainedPasswordResetFailsTypedAndRollsBackWithoutInventingSource() { .AccountSecurityStateOperationRepository(dsl), new net.firedevops.firemud.accountservice.service .AccountPasswordResetDraftSourceChangeRepository(dsl), - null, // audit outbox null, null, null, @@ -144,8 +143,6 @@ void preV40RetainedPasswordResetFailsTypedAndRollsBackWithoutInventingSource() { null, null, null, - null, - null, manager); // remote clients/JWT/session are not used by reset UUID accountUuid = accounts.findById(accountId).orElseThrow().getAccountUuid(); var beforeToken = diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchClockPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchClockPostgresIntegrationTest.java new file mode 100644 index 0000000000..5c7a518e5c --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchClockPostgresIntegrationTest.java @@ -0,0 +1,173 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import integration.net.firedevops.firemud.accountservice.repository.CanonicalHostingSubscriptionTestFixture; +import integration.net.firedevops.firemud.accountservice.repository.CanonicalHostingSubscriptionTestFixture.Fixture; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.Disposition; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ReconciliationLimits; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.exception.DataAccessException; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Real PostgreSQL clock/locks; controlled enrollment only, with no provider calls or registration. + */ +@Testcontainers(disabledWithoutDocker = true) +class AccountHostingSubscriptionDispatchClockPostgresIntegrationTest { + @Container + private static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @ParameterizedTest + @ValueSource(ints = {-365, 365}) + void claimAndFirstDispatchUseDatabaseTimeDespiteObservationClockSkew(int skewDays) { + Fixture f = fixture(); + var owner = owner(f, Duration.ofSeconds(10), Duration.ofHours(1), skewDays); + Instant before = databaseNow(f); + var claim = + Objects.requireNonNull( + f.transaction() + .execute(s -> owner.claim(f.creation().requestId(), 1, UUID.randomUUID()))) + .claim(); + assertThat(claim.claimedAt()).isBetween(before, databaseNow(f)); + assertThat(claim.expiresAt()).isEqualTo(claim.claimedAt().plusSeconds(10)); + + var prepared = + f.transaction().execute(s -> owner.prepareProviderDispatch(claim, UUID.randomUUID())); + var read = + Objects.requireNonNull(f.transaction().execute(s -> owner.readProviderDispatch(prepared))); + assertThat(read.readyForProviderIo()).isTrue(); + assertThat(read.initialCallAllowed()).isTrue(); + Instant recorded = + Objects.requireNonNull( + f.dsl().fetchOne("SELECT recorded_at FROM subscription_provider_dispatch_claim")) + .get("recorded_at", OffsetDateTime.class) + .toInstant(); + assertThat(recorded).isBetween(claim.claimedAt(), databaseNow(f)); + assertThat(recorded).isBefore(claim.expiresAt()); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void backdatedDispatchCannotConsumeFirstPermissionAfterActualDatabaseExpiry( + boolean absoluteDeadline) { + Fixture f = fixture(); + var owner = + owner( + f, + absoluteDeadline ? Duration.ofSeconds(5) : Duration.ofSeconds(3), + absoluteDeadline ? Duration.ofSeconds(5) : Duration.ofHours(1), + 0); + var claim = + Objects.requireNonNull( + f.transaction() + .execute(s -> owner.claim(f.creation().requestId(), 1, UUID.randomUUID()))) + .claim(); + assertThat(claim).isNotNull(); + if (absoluteDeadline) { + assertThat(claim.expiresAt()).isEqualTo(f.creation().createdAt().plusSeconds(5)); + } + // Retain the same timestamp the old application-clock INSERT could sample while still live. + // Start this transaction before expiry, then wait on PostgreSQL time. Neither transaction time + // nor the caller's earlier recorded_at is a valid substitute for the trigger's late clock read. + Instant sampled = databaseNow(f); + assertThat(sampled).isBefore(claim.expiresAt()); + assertThatThrownBy( + () -> + f.transaction() + .executeWithoutResult( + s -> { + assertThat(databaseNow(f)).isBefore(claim.expiresAt()); + f.dsl() + .execute( + "SELECT pg_sleep_until(?::timestamptz)", + claim.expiresAt().plusMillis(5).atOffset(ZoneOffset.UTC)); + assertThat(databaseNow(f)).isAfterOrEqualTo(claim.expiresAt()); + f.dsl() + .execute( + "INSERT INTO subscription_provider_dispatch_claim " + + "(creation_request_id, subscription_id, provider_operation_id, dispatch_id, " + + "classification, first_attempt_id, first_claimed_row_version, recorded_at) " + + "VALUES (?, ?, ?, ?, 'FIRST_DISPATCH', ?, ?, ?::timestamptz)", + f.creation().requestId(), + f.creation().subscriptionId(), + f.creation().subscriptionProvisioningRequestId(), + UUID.randomUUID(), + claim.attemptId(), + claim.subscriptionRowVersion(), + sampled.atOffset(ZoneOffset.UTC)); + })) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("Provider dispatch lacks exact live original provisioning fence") + .satisfies( + failure -> assertThat(((DataAccessException) failure).sqlState()).isEqualTo("23514")); + assertThat(f.dsl().fetchCount(org.jooq.impl.DSL.table("subscription_provider_dispatch_claim"))) + .isZero(); + var replay = + Objects.requireNonNull( + f.transaction() + .execute(s -> owner.claim(f.creation().requestId(), 1, claim.attemptId()))); + assertThat(replay.disposition()).isEqualTo(Disposition.ATTEMPT_EXPIRED); + assertThat(replay.claim()).isNull(); + assertThat(f.transaction().execute(s -> owner.deferUnresolved(claim))) + .isEqualTo(absoluteDeadline ? Disposition.TERMINAL_FAILURE : Disposition.ATTEMPT_EXPIRED); + } + + private static AccountHostingSubscriptionLifecycleRepository owner( + Fixture f, Duration lease, Duration timeout, int skewDays) { + return new AccountHostingSubscriptionLifecycleRepository( + f.dsl(), + f.intents(), + skewDays == 0 + ? Clock.systemUTC() + : Clock.fixed(f.creation().createdAt().plus(Duration.ofDays(skewDays)), ZoneOffset.UTC), + new ReconciliationLimits(4, 3, lease, Duration.ofMillis(1), timeout), + new AccountHostingSubscriptionLifecyclePolicy( + Duration.ofSeconds(15), + new AccountHostingSubscriptionLifecyclePolicy.RecoveryTiming( + Duration.ofSeconds(60), Duration.ofSeconds(120))), + "prod", + false); + } + + private static Instant databaseNow(Fixture f) { + return Objects.requireNonNull(f.dsl().fetchOne("SELECT clock_timestamp() AS now")) + .get("now", OffsetDateTime.class) + .toInstant(); + } + + private static Fixture fixture() { + String schema = "dispatch_clock_" + UUID.randomUUID().toString().replace("-", ""); + var source = + new DriverManagerDataSource( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); + source.setSchema(schema); + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration", "classpath:db/migration/saga") + .load() + .migrate(); + Fixture f = CanonicalHostingSubscriptionTestFixture.create(source); + f.transaction().setTimeout(10); + return f; + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java index eb3bc68da2..8e9c5d1650 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; +import integration.net.firedevops.firemud.accountservice.repository.CanonicalHostingSubscriptionTestFixture; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.sql.SQLException; import java.time.Duration; @@ -521,28 +522,36 @@ void auditAttemptTimesUseUtcLocalDateTimeUnderNonUtcDatabaseSession() { } @Test - void subscriptionForUpdateLocksOnlySubscriptionAndKeepsThatLockThroughTransaction() - throws Exception { + void canonicalSubscriptionOriginalBindingLocksRequiredOwnerChainThroughCommit() throws Exception { + var fixture = CanonicalHostingSubscriptionTestFixture.create(dataSource); + var claim = + fixture + .service() + .claimProvisioning(fixture.creation().requestId(), 1, UUID.randomUUID()) + .claim(); + assertThat( + fixture + .service() + .reconcile( + UUID.randomUUID(), + fixture.creation().requestId(), + claim.subscriptionRowVersion(), + fixture.providerId(), + claim.attemptId()) + .outcome()) + .isEqualTo(AccountHostingSubscriptionLifecycleRepository.Outcome.COMMITTED); + var receipt = fixture.service().readCurrent(fixture.tenantId()); JdbcTemplate jdbc = new JdbcTemplate(dataSource); - long accountId = + long unrelatedAccountId = Objects.requireNonNull( jdbc.queryForObject( "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) RETURNING id", Long.class, - "subscription-lock", - "subscription-lock@example.com", + "unrelated-subscription-lock", + "unrelated-subscription-lock@example.com", "hash")); - long tenantId = 7654321L; - jdbc.update( - "INSERT INTO subscription (account_id, plan_id, status, tenant_id, entitlement_version) " - + "VALUES (?, 'test-plan', 'active', ?, 1)", - accountId, - tenantId); - TransactionAwareDataSourceProxy transactionAwareDataSource = new TransactionAwareDataSourceProxy(dataSource); - DSLContext transactionDsl = DSL.using(transactionAwareDataSource, SQLDialect.POSTGRES); - SubscriptionRepository subscriptions = new SubscriptionRepository(transactionDsl); TransactionTemplate lockTransaction = new TransactionTemplate(new DataSourceTransactionManager(dataSource)); CountDownLatch subscriptionLocked = new CountDownLatch(1); @@ -553,7 +562,15 @@ void subscriptionForUpdateLocksOnlySubscriptionAndKeepsThatLockThroughTransactio () -> lockTransaction.executeWithoutResult( status -> { - assertThat(subscriptions.findByTenantIdForUpdate(tenantId)).hasSize(1); + assertThat( + fixture + .intents() + .lockForLifecycle( + fixture.creation().requestId(), + receipt.current().rowVersion())) + .isEqualTo(receipt.current()); + assertThat(fixture.intents().findCreation(fixture.creation().requestId())) + .contains(fixture.creation()); subscriptionLocked.countDown(); try { if (!releaseSubscriptionLock.await(10, TimeUnit.SECONDS)) { @@ -572,16 +589,33 @@ void subscriptionForUpdateLocksOnlySubscriptionAndKeepsThatLockThroughTransactio TransactionTemplate conflictingTransaction = new TransactionTemplate(new DataSourceTransactionManager(dataSource)); JdbcTemplate conflictingJdbc = new JdbcTemplate(transactionAwareDataSource); - assertThatThrownBy( - () -> - conflictingTransaction.executeWithoutResult( - status -> { - conflictingJdbc.execute("SET LOCAL lock_timeout = '250ms'"); - conflictingJdbc.update( - "UPDATE subscription SET status = status WHERE tenant_id = ?", - tenantId); - })) - .hasMessageContaining("lock timeout"); + // These are the mutable rows actually locked by the canonical original-binding reader. + // Creation intent is immutable and validated above; it is not a competing mutable row. + Map lockedRows = + Map.of( + "SELECT 1 FROM accounts WHERE account_uuid = ? FOR UPDATE", fixture.accountUuid(), + "SELECT 1 FROM billing_customer WHERE account_uuid = ? FOR UPDATE", + fixture.accountUuid(), + "SELECT 1 FROM payment_instrument WHERE instrument_uuid = ? FOR UPDATE", + fixture.instrument().instrumentUuid(), + "SELECT 1 FROM account_tenant_billing_owners WHERE tenant_uuid = ? FOR UPDATE", + fixture.tenantId(), + "SELECT 1 FROM subscription WHERE subscription_id = ? FOR UPDATE", + fixture.creation().subscriptionId(), + "SELECT 1 FROM subscription_instrument_reservations WHERE request_id = ? FOR UPDATE", + fixture.creation().requestId()); + for (var row : lockedRows.entrySet()) { + assertThatThrownBy( + () -> + conflictingTransaction.executeWithoutResult( + status -> { + conflictingJdbc.execute("SET LOCAL lock_timeout = '250ms'"); + conflictingJdbc.queryForObject( + row.getKey(), Integer.class, row.getValue()); + })) + .as("owner-chain lock retained: %s", row.getKey()) + .hasMessageContaining("lock timeout"); + } Integer updatedAccounts = conflictingTransaction.execute( @@ -589,8 +623,8 @@ void subscriptionForUpdateLocksOnlySubscriptionAndKeepsThatLockThroughTransactio conflictingJdbc.execute("SET LOCAL lock_timeout = '2s'"); return conflictingJdbc.update( "UPDATE accounts SET email = ? WHERE id = ?", - "subscription-lock-updated@example.com", - accountId); + "unrelated-subscription-lock-updated@example.com", + unrelatedAccountId); }); assertThat(updatedAccounts).isEqualTo(1); } finally { @@ -601,6 +635,19 @@ void subscriptionForUpdateLocksOnlySubscriptionAndKeepsThatLockThroughTransactio executor.shutdownNow(); } } + // The same real owner operation succeeds from an independent transaction after holder commit. + lockTransaction.executeWithoutResult( + status -> { + jdbc.execute("SET LOCAL lock_timeout = '2s'"); + assertThat( + fixture + .intents() + .lockForLifecycle( + fixture.creation().requestId(), receipt.current().rowVersion())) + .isEqualTo(receipt.current()); + }); + assertThat(fixture.intents().findCreation(fixture.creation().requestId())) + .contains(fixture.creation()); } @Test @@ -643,16 +690,13 @@ void privateRealmGrantRevocationRetainsMonotonicCurrentnessForRevalidation() { null, null, null, - null, grants, null, null, null, null, null, - null, - null, - null, + org.mockito.Mockito.mock(RetainedSubscriptionEvidenceRepository.class), null, null, null, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSecuritySourceOwnerGuardPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSecuritySourceOwnerGuardPostgresIntegrationTest.java index 37e1cfda6f..529cca5037 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSecuritySourceOwnerGuardPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSecuritySourceOwnerGuardPostgresIntegrationTest.java @@ -26,6 +26,7 @@ import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; import net.firedevops.firemud.accountservice.repository.PasswordResetTokenRepository; +import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback; import net.firedevops.firemud.accountservice.service.AccountLogoutAllAuthorityEventProducer; import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository; @@ -302,8 +303,7 @@ private AccountServiceImpl newPasswordResetService( logoutOperations, securityOperations, resetSourceChanges, - null, // audit outbox - null, // connect scopes + null, // account audit outbox null, // join operations null, // email login challenges null, // realm grants @@ -312,7 +312,8 @@ private AccountServiceImpl newPasswordResetService( null, // profiles null, // profile mapper null, // payment transactions - null, // subscriptions + // retained subscription evidence + org.mockito.Mockito.mock(RetainedSubscriptionEvidenceRepository.class), null, // external account identities tokens, null, // email verification tokens @@ -323,8 +324,6 @@ private AccountServiceImpl newPasswordResetService( null, null, null, - null, - null, context.transactionManager()); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java index 83e548e6dc..dbb5872a20 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java @@ -196,10 +196,16 @@ void actualDefaultLocationsFreshBootstrapAppliesFullCombinedHistoryAndEnabledGua var dsl = DSL.using(source, SQLDialect.POSTGRES); assertThat( dsl.fetchSingle( - "SELECT count(*) FROM pg_trigger t JOIN pg_class c ON c.oid = t.tgrelid JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = ? AND NOT t.tgisinternal AND t.tgenabled <> 'O'", + "SELECT count(*) FROM pg_trigger t JOIN pg_class c ON c.oid = t.tgrelid JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = ? AND NOT t.tgisinternal AND t.tgenabled NOT IN ('O', 'A')", schema) .get(0, Long.class)) .isZero(); + assertThat( + dsl.fetchSingle( + "SELECT count(*) FROM pg_trigger t JOIN pg_class c ON c.oid = t.tgrelid JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = ? AND c.relname = 'account_retained_subscription_evidence' AND t.tgname = 'account_retained_subscription_evidence_immutable' AND t.tgenabled = 'A'", + schema) + .get(0, Long.class)) + .isEqualTo(1L); for (String signature : List.of( "account_ss_admission_assert_current(account_start_session_admission_protections,boolean)", diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CanonicalHostingSubscriptionTestFixture.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CanonicalHostingSubscriptionTestFixture.java new file mode 100644 index 0000000000..fb911fdfbb --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CanonicalHostingSubscriptionTestFixture.java @@ -0,0 +1,502 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.stripe.exception.StripeException; +import com.stripe.model.StripeObject; +import com.stripe.net.ApiMode; +import com.stripe.net.ApiResource.RequestMethod; +import com.stripe.net.BaseAddress; +import com.stripe.net.RequestOptions; +import com.stripe.net.StripeResponseGetter; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.InputStream; +import java.lang.reflect.Type; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicLong; +import java.util.function.Supplier; +import javax.sql.DataSource; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountBillingCustomerRecord; +import net.firedevops.firemud.accountservice.repository.AccountBillingCustomerRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingPlanCatalog; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecyclePolicy; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecyclePolicy.RecoveryTiming; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ReconciliationLimits; +import net.firedevops.firemud.accountservice.repository.AccountInitialTenantBillingOwnerRepository; +import net.firedevops.firemud.accountservice.repository.AccountPaymentInstrumentRecord; +import net.firedevops.firemud.accountservice.repository.AccountPaymentInstrumentRecord.DisplayMetadata; +import net.firedevops.firemud.accountservice.repository.AccountPaymentInstrumentRecord.State; +import net.firedevops.firemud.accountservice.repository.AccountPaymentInstrumentRepository; +import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCreateRequest; +import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCreateRequest.OwnerFence; +import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCreateRequest.ProducerEvidence; +import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCreationRecord; +import net.firedevops.firemud.accountservice.repository.AccountSubscriptionIntentRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.service.AccountHostingSubscriptionLifecycleService; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorDigest; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Controlled local source setup plus the real hosting lifecycle owner and Stripe SDK read path. The + * caller must migrate its isolated Account schema before using this fixture. The fresh-tenant, + * creator/consent, customer, wallet, and transport inputs are controlled; they do not qualify their + * authenticated producers, PKI, Stripe, runtime registration, or production entitlement use. + */ +public final class CanonicalHostingSubscriptionTestFixture { + private static final String DIGEST = "sha256:" + "a".repeat(64); + private static final AtomicLong GAME_ROWS = new AtomicLong(20_000); + + private CanonicalHostingSubscriptionTestFixture() {} + + public static Fixture create(DataSource source) { + return createInternal(source, null); + } + + /** Reuses the exact persisted Account of a genuine actor/authentication composition. */ + public static Fixture create(DataSource source, Account account) { + return createInternal(source, Objects.requireNonNull(account, "persisted Account required")); + } + + private static Fixture createInternal(DataSource source, Account existingAccount) { + Objects.requireNonNull(source, "migrated Account datasource is required"); + JdbcTemplate jdbc = new JdbcTemplate(source); + DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + TransactionTemplate transaction = + new TransactionTemplate(new DataSourceTransactionManager(source)); + AccountHostingPlanCatalog catalog = + new AccountHostingPlanCatalog( + List.of( + new AccountHostingPlanCatalog.ConfiguredPlan( + "hosting", "price_controlled", "1", "100", "2", "1048576"))); + AccountSubscriptionIntentRepository intents = + new AccountSubscriptionIntentRepository(dsl, catalog); + + long row = GAME_ROWS.incrementAndGet(); + var accountRow = + existingAccount == null + ? dsl.fetchOne( + "INSERT INTO accounts (username, email, password_hash) " + + "VALUES (?, ?, 'controlled-hash') RETURNING id, account_uuid", + "hosting-fixture-" + row, + "hosting-fixture-" + row + "@example.test") + : dsl.fetchOne( + "SELECT id, account_uuid FROM accounts WHERE id = ? AND account_uuid = ?", + Objects.requireNonNull(existingAccount.getId(), "persisted Account ID required"), + Objects.requireNonNull( + existingAccount.getAccountUuid(), "persisted Account UUID required")); + Objects.requireNonNull(accountRow, "Exact persisted Account row required"); + long accountId = accountRow.get("id", Long.class); + UUID accountUuid = accountRow.get("account_uuid", UUID.class); + + UUID tenantId = UUID.randomUUID(); + UUID tenantCreateRequest = UUID.randomUUID(); + UUID tenantCreateOperation = UUID.randomUUID(); + String tenantKey = "hosting-fixture-game-" + row; + String tenantRequestDigest = + GameTenantCreationDigest.requestDigest( + "prod", tenantCreateRequest, tenantKey, "Controlled hosting", "Storage only"); + var tenantSource = + new FreshTenantCreationEvidence( + 1, + "prod", + tenantCreateRequest, + tenantCreateOperation, + tenantRequestDigest, + tenantId, + row, + tenantKey, + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + "prod", + tenantCreateRequest, + tenantCreateOperation, + tenantRequestDigest, + tenantId, + row, + tenantKey, + "NEW_GAME_ROW")); + in( + transaction, + () -> { + new FreshTenantIdentityAssociationRepository(dsl, "prod").importVerified(tenantSource); + return new AccountAuthorityGenerationRepository(dsl).initializeTenantIfAbsent(tenantId); + }); + + UUID authorizationOperation = UUID.randomUUID(); + var creator = + new FreshTenantCreatorEvidence( + 1, + tenantSource, + accountUuid, + authorizationOperation, + DIGEST, + FreshTenantCreatorDigest.evidenceDigest( + 1, tenantSource, accountUuid, authorizationOperation, DIGEST)); + var owner = + in( + transaction, + () -> + new AccountInitialTenantBillingOwnerRepository(dsl) + .establishInitial( + new AccountInitialTenantBillingOwnerRepository.InitialRequest( + UUID.randomUUID(), creator, UUID.randomUUID(), 1, true))); + + var customers = new AccountBillingCustomerRepository(dsl); + var pendingCustomer = + in( + transaction, + () -> + customers + .retainIntent(accountUuid, UUID.randomUUID(), UUID.randomUUID()) + .customer()); + var customer = + pendingCustomer.state() == AccountBillingCustomerRecord.State.CONFIRMED + ? pendingCustomer + : in( + transaction, + () -> + customers.recordObservation( + accountUuid, + pendingCustomer.customerProvisioningRequestId(), + pendingCustomer.rowVersion(), + UUID.randomUUID(), + AccountBillingCustomerRecord.Observation.CONFIRMED, + "cus_" + row, + DIGEST)); + var instrument = + in( + transaction, + () -> + new AccountPaymentInstrumentRepository(dsl) + .retainAttachment( + new AccountPaymentInstrumentRepository.Attachment( + UUID.randomUUID(), + UUID.randomUUID(), + accountUuid, + customer.customerProvisioningRequestId(), + customer.providerCustomerId(), + "pm_" + row, + State.ATTACHABLE, + new DisplayMetadata("visa", "4242", 12, 2030), + DIGEST))); + var creation = + in( + transaction, + () -> + intents.retainPending( + new AccountSubscriptionCreateRequest( + UUID.randomUUID(), + tenantId, + new OwnerFence(accountUuid, owner.ownerVersion(), owner.ownerGeneration()), + "hosting", + instrument.instrumentUuid(), + 1, + new ProducerEvidence(accountUuid, UUID.randomUUID(), DIGEST), + null))); + + MutableClock clock = new MutableClock(creation.createdAt().plusSeconds(1)); + ControlledStripeTransport transport = new ControlledStripeTransport(); + var lifecycleRepository = + new AccountHostingSubscriptionLifecycleRepository( + dsl, + intents, + clock, + new ReconciliationLimits( + 4, 3, Duration.ofSeconds(10), Duration.ofSeconds(1), Duration.ofHours(1)), + new AccountHostingSubscriptionLifecyclePolicy( + Duration.ofSeconds(15), + new RecoveryTiming(Duration.ofSeconds(60), Duration.ofSeconds(120))), + "prod", + false); + var observer = + new StripeHostingSubscriptionObserver( + new com.stripe.StripeClient(transport), + clock, + Duration.ofMillis(250), + Duration.ofSeconds(1)); + var service = + new AccountHostingSubscriptionLifecycleService( + lifecycleRepository, observer, new DataSourceTransactionManager(source)); + Fixture fixture = + new Fixture( + jdbc, + dsl, + transaction, + accountId, + accountUuid, + tenantId, + creation, + intents, + instrument, + "sub_" + row, + clock, + transport, + service, + lifecycleRepository, + observer); + fixture.providerStatus("active"); + return fixture; + } + + private static T in(TransactionTemplate transaction, Supplier body) { + return Objects.requireNonNull(transaction.execute(status -> body.get())); + } + + public static final class Fixture { + private final JdbcTemplate jdbc; + private final DSLContext dsl; + private final TransactionTemplate transaction; + private final long accountId; + private final UUID accountUuid; + private final UUID tenantId; + private final AccountSubscriptionCreationRecord creation; + private final AccountSubscriptionIntentRepository intents; + private final AccountPaymentInstrumentRecord instrument; + private final String providerId; + private final MutableClock clock; + private final ControlledStripeTransport transport; + private final AccountHostingSubscriptionLifecycleService service; + private final AccountHostingSubscriptionLifecycleRepository lifecycleRepository; + private final StripeHostingSubscriptionObserver observer; + + private Fixture( + JdbcTemplate jdbc, + DSLContext dsl, + TransactionTemplate transaction, + long accountId, + UUID accountUuid, + UUID tenantId, + AccountSubscriptionCreationRecord creation, + AccountSubscriptionIntentRepository intents, + AccountPaymentInstrumentRecord instrument, + String providerId, + MutableClock clock, + ControlledStripeTransport transport, + AccountHostingSubscriptionLifecycleService service, + AccountHostingSubscriptionLifecycleRepository lifecycleRepository, + StripeHostingSubscriptionObserver observer) { + this.jdbc = jdbc; + this.dsl = dsl; + this.transaction = transaction; + this.accountId = accountId; + this.accountUuid = accountUuid; + this.tenantId = tenantId; + this.creation = creation; + this.intents = intents; + this.instrument = instrument; + this.providerId = providerId; + this.clock = clock; + this.transport = transport; + this.service = service; + this.lifecycleRepository = lifecycleRepository; + this.observer = observer; + } + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = + "Integration tests intentionally inspect the fixture's actual JdbcTemplate and datasource; copying it would change the physical SQL boundary.") + public JdbcTemplate jdbc() { + return jdbc; + } + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = + "Integration tests intentionally use this exact datasource-backed DSLContext for physical SQL assertions; a copy would change the fixture boundary.") + public DSLContext dsl() { + return dsl; + } + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = + "Integration tests intentionally use this exact TransactionTemplate to exercise the fixture's real transaction boundary; a copy would change it.") + public TransactionTemplate transaction() { + return transaction; + } + + public long accountId() { + return accountId; + } + + public UUID accountUuid() { + return accountUuid; + } + + public UUID tenantId() { + return tenantId; + } + + public AccountSubscriptionCreationRecord creation() { + return creation; + } + + public AccountSubscriptionIntentRepository intents() { + return intents; + } + + public AccountPaymentInstrumentRecord instrument() { + return instrument; + } + + public String providerId() { + return providerId; + } + + public MutableClock clock() { + return clock; + } + + public ControlledStripeTransport transport() { + return transport; + } + + public AccountHostingSubscriptionLifecycleService service() { + return service; + } + + /** Actual source collaborators for explicit prepare/observe/final-transaction tests. */ + public AccountHostingSubscriptionLifecycleRepository lifecycleRepository() { + return lifecycleRepository; + } + + public StripeHostingSubscriptionObserver observer() { + return observer; + } + + public void providerStatus(String status) { + transport.json = response(this, status); + } + } + + public static final class MutableClock extends Clock { + private volatile Instant current; + + private MutableClock(Instant current) { + this.current = current; + } + + public void advance(Duration duration) { + current = current.plus(duration); + } + + @Override + public ZoneId getZone() { + return ZoneOffset.UTC; + } + + @Override + public Clock withZone(ZoneId zone) { + return this; + } + + @Override + public Instant instant() { + return current; + } + } + + public static final class ControlledStripeTransport implements StripeResponseGetter { + private String json; + private int reads; + private Runnable duringRead; + + public int reads() { + return reads; + } + + /** One-shot owner mutation while the real SDK request is outside Account SQL. */ + public void duringRead(Runnable action) { + if (duringRead != null) throw new IllegalStateException("A provider-read action is pending"); + duringRead = Objects.requireNonNull(action); + } + + @Override + @SuppressWarnings("unchecked") + public T request( + BaseAddress address, + RequestMethod method, + String path, + Map params, + Type type, + RequestOptions options, + ApiMode mode) + throws StripeException { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(method).isEqualTo(RequestMethod.GET); + assertThat(path).startsWith("/v1/subscriptions/"); + reads++; + Runnable action = duringRead; + duringRead = null; + if (action != null) action.run(); + return (T) com.stripe.net.ApiResource.GSON.fromJson(json, type); + } + + @Override + public InputStream requestStream( + BaseAddress address, + RequestMethod method, + String path, + Map params, + RequestOptions options, + ApiMode mode) + throws StripeException { + throw new AssertionError("No Stripe streaming or provider mutations are allowed"); + } + } + + @SuppressFBWarnings( + value = "VA_FORMAT_STRING_USES_NEWLINE", + justification = + "This is a JSON test fixture whose text block intentionally retains LF characters independent of the host console line separator.") + private static String response(Fixture fixture, String status) { + String endedAt = + "canceled".equals(status) + ? Long.toString(fixture.clock().instant().getEpochSecond()) + : "null"; + return """ + {"id":"%s","object":"subscription","customer":"%s","default_payment_method":"%s", + "livemode":false,"status":"%s","cancel_at_period_end":false,"cancel_at":null,"canceled_at":null,"ended_at":%s, + "metadata":{"firemud_metadata_schema_version":"1","firemud_operation_type":"subscription_provisioning", + "firemud_operation_id":"%s","firemud_subscription_id":"%s"}, + "items":{"object":"list","data":[{"id":"si_controlled","object":"subscription_item","subscription":"%s", + "quantity":1,"current_period_start":%d,"current_period_end":%d,"price":{"id":"%s","object":"price"}}],"has_more":false}} + """ + .formatted( + fixture.providerId(), + fixture.creation().providerCustomerId(), + fixture.instrument().providerPaymentMethodId(), + status, + endedAt, + fixture.creation().subscriptionProvisioningRequestId(), + fixture.creation().subscriptionId(), + fixture.providerId(), + fixture.creation().createdAt().getEpochSecond(), + fixture.creation().createdAt().getEpochSecond() + 3600, + fixture.creation().planQuote().providerPriceId()); + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/RetainedSubscriptionEvidencePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/RetainedSubscriptionEvidencePostgresIntegrationTest.java new file mode 100644 index 0000000000..fa81372c91 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/RetainedSubscriptionEvidencePostgresIntegrationTest.java @@ -0,0 +1,233 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.configuration.FluentConfiguration; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Populated, combined-history forward upgrade; no generated or synthetic canonical subscription. + */ +@Testcontainers(disabledWithoutDocker = true) +class RetainedSubscriptionEvidencePostgresIntegrationTest { + private static final String EVIDENCE = "account_retained_subscription_evidence"; + + @Container + private static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void forwardUpgradePreservesEveryValueHeapIdentityXminAndPublishedFlywayHistory() { + Context context = predecessor(); + DSLContext dsl = context.dsl(); + List> before = rows(dsl, "subscription"); + List> history = history(dsl); + Long originalOid = relationOid(dsl, "subscription"); + List> accounts = + dsl.fetch( + "SELECT row_to_json(a)::text AS value, xmin::text AS xmin FROM accounts a ORDER BY id") + .intoMaps(); + + configuration(context).load().migrate(); + + assertThat(rows(dsl, EVIDENCE)).isEqualTo(before); + assertThat(relationOid(dsl, EVIDENCE)).isEqualTo(originalOid); + var afterHistory = history(dsl); + assertThat(afterHistory).hasSize(history.size() + 4); + assertThat(afterHistory.subList(history.size(), afterHistory.size())) + .extracting(row -> row.get("version")) + .containsExactly("1027", "1027.1", "1027.2", "1028"); + assertThat(afterHistory.subList(0, history.size())).containsExactlyElementsOf(history); + assertThat(history(dsl).getLast().get("version")).isEqualTo("1028"); + assertThat( + dsl.fetch( + "SELECT version FROM flyway_schema_history WHERE version IN ('1000', '1001', '1002')")) + .hasSize(3); + assertThat( + dsl.fetch( + "SELECT row_to_json(a)::text AS value, xmin::text AS xmin FROM accounts a ORDER BY id") + .intoMaps()) + .isEqualTo(accounts); + assertThat(scalar(dsl, "SELECT to_regclass('subscription')", String.class)).isNull(); + assertThat( + scalar( + dsl, + "SELECT to_regprocedure('advance_subscription_authority_generation()')", + String.class)) + .isNull(); + assertThat( + dsl.fetch( + "SELECT conname FROM pg_constraint WHERE conrelid = ?::regclass ORDER BY conname", + EVIDENCE) + .getValues(0, String.class)) + .containsExactly( + "account_retained_subscription_evidence_account_fk", + "account_retained_subscription_evidence_generation_non_nil", + "account_retained_subscription_evidence_pkey", + "account_retained_subscription_evidence_version_positive", + "subscription_account_id_not_null", + "subscription_entitlement_version_not_null", + "subscription_id_not_null", + "subscription_plan_id_not_null", + "subscription_status_not_null", + "subscription_tenant_authority_generation_not_null", + "subscription_tenant_id_not_null"); + assertThat( + dsl.fetch( + "SELECT indexname FROM pg_indexes WHERE schemaname = current_schema() AND tablename = ?", + EVIDENCE) + .getValues(0, String.class)) + .containsExactlyInAnyOrder( + "account_retained_subscription_evidence_pkey", + "idx_account_retained_subscription_evidence_account", + "idx_account_retained_subscription_evidence_tenant"); + assertThat( + scalar( + dsl, + "SELECT to_regclass('account_retained_subscription_evidence_id_seq')", + String.class)) + .isNotNull(); + configuration(context).load().validate(); + } + + @Test + void archiveRefusesAllMutationIncludingNoOpEmptyStatementsAndTruncateCascade() { + Context context = predecessor(); + configuration(context).load().migrate(); + DSLContext dsl = context.dsl(); + var before = rows(dsl, EVIDENCE); + for (String sql : + List.of( + "INSERT INTO " + EVIDENCE + " SELECT * FROM " + EVIDENCE + " WHERE false", + "INSERT INTO " + + EVIDENCE + + " (id, account_id, plan_id, status, tenant_id) VALUES (9999, " + + context.accountId() + + ", 'forbidden', 'active', 7)", + "UPDATE " + EVIDENCE + " SET status = status", + "UPDATE " + EVIDENCE + " SET tenant_id = 99 WHERE false", + "DELETE FROM " + EVIDENCE + " WHERE false", + "DELETE FROM " + EVIDENCE, + "TRUNCATE " + EVIDENCE, + "TRUNCATE " + EVIDENCE + " RESTART IDENTITY CASCADE")) { + assertThatThrownBy(() -> dsl.execute(sql)) + .hasMessageContaining("Retained subscription evidence is immutable and non-authorizing"); + assertThat(rows(dsl, EVIDENCE)).isEqualTo(before); + } + // Account FK remains restrictive even for terminal-looking historical rows. + assertThatThrownBy(() -> dsl.execute("DELETE FROM accounts WHERE id = ?", context.accountId())) + .hasMessageContaining("account_retained_subscription_evidence_account_fk"); + // Other retained Account families can refuse first; no cascade may erase this evidence. + assertThatThrownBy(() -> dsl.execute("TRUNCATE accounts CASCADE")) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThat(rows(dsl, EVIDENCE)).isEqualTo(before); + } + + @Test + void historicalRepositoryReadsOnlyTheRequestedAccountWithoutChoosingATenantWinner() { + Context context = predecessor(); + configuration(context).load().migrate(); + var repository = new RetainedSubscriptionEvidenceRepository(context.dsl()); + var history = repository.findHistoryByAccountId(context.accountId()); + assertThat(history).hasSize(4); + assertThat(history) + .extracting(row -> row.status()) + .containsExactly("active", "canceled", "grace", "provider_unknown"); + assertThat(history).extracting(row -> row.accountId()).containsOnly(context.accountId()); + assertThat(history).extracting(row -> row.tenantId()).containsExactly(7L, 7L, 8L, 8L); + assertThat(repository.findHistoryByAccountId(-1L)).isEmpty(); + assertThat(rows(context.dsl(), EVIDENCE)).hasSize(6); + } + + private static List> rows(DSLContext dsl, String relation) { + return dsl.fetch( + "SELECT row_to_json(s)::text AS value, xmin::text AS xmin, ctid::text AS ctid FROM " + + relation + + " s ORDER BY id") + .intoMaps(); + } + + private static List> history(DSLContext dsl) { + return dsl.fetch("SELECT * FROM flyway_schema_history ORDER BY installed_rank").intoMaps(); + } + + private static T scalar(DSLContext dsl, String sql, Class type, Object... bindings) { + return Objects.requireNonNull(dsl.fetchOne(sql, bindings)).get(0, type); + } + + private static Long relationOid(DSLContext dsl, String relation) { + return scalar(dsl, "SELECT ?::regclass::oid::bigint", Long.class, relation); + } + + private static FluentConfiguration configuration(Context context) { + return Flyway.configure() + .dataSource(context.source()) + .target("1028") + .schemas(context.schema()) + .defaultSchema(context.schema()) + .placeholders(Map.of("serviceSchema", context.schema())) + .locations("classpath:db/migration", "classpath:db/migration/saga"); + } + + private static Context predecessor() { + String schema = "subscription_retention_" + UUID.randomUUID().toString().replace("-", ""); + var source = + new DriverManagerDataSource( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); + source.setSchema(schema); + DSLContext dsl = DSL.using(source, SQLDialect.POSTGRES); + var empty = new Context(source, schema, dsl, 0L); + configuration(empty).target("1026").load().migrate(); + Long accountId = + Objects.requireNonNull( + scalar( + dsl, + "INSERT INTO accounts(username,email,password_hash) VALUES ('retained','retained@example.test','hash') RETURNING id", + Long.class)); + Long otherAccount = + Objects.requireNonNull( + scalar( + dsl, + "INSERT INTO accounts(username,email,password_hash) VALUES ('other','other@example.test','hash') RETURNING id", + Long.class)); + dsl.execute( + "INSERT INTO subscription(id,account_id,plan_id,status,started_at,ended_at,tenant_id,entitlement_version,tenant_authority_generation) VALUES " + + "(91,?,'unqualified-active','active','2025-01-02 03:04:05.123456',NULL,7,19,?::uuid)," + + "(92,?,'retained-canceled','canceled',NULL,'2025-02-03 04:05:06.654321',7,21,?::uuid)," + + "(93,?,'grace','grace',NULL,NULL,8,1,?::uuid)," + + "(94,?,'unknown','provider_unknown',NULL,NULL,8,2,?::uuid)," + + "(95,?,'other-account','active',NULL,NULL,7,5,?::uuid)", + accountId, + UUID.randomUUID(), + accountId, + UUID.randomUUID(), + accountId, + UUID.randomUUID(), + accountId, + UUID.randomUUID(), + otherAccount, + UUID.randomUUID()); + // Preserve V5's numeric default as historical evidence, not canonical tenant provenance. + dsl.execute( + "INSERT INTO subscription(id,account_id,plan_id,status) VALUES (96,?,'default-tenant','active')", + otherAccount); + return new Context(source, schema, dsl, accountId); + } + + private record Context( + DriverManagerDataSource source, String schema, DSLContext dsl, Long accountId) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapDemoWorldsOwnerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapDemoWorldsOwnerPostgresIntegrationTest.java index c17b6a2360..9654b5bc97 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapDemoWorldsOwnerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapDemoWorldsOwnerPostgresIntegrationTest.java @@ -18,6 +18,7 @@ import java.time.Instant; import java.time.ZoneId; import java.time.ZoneOffset; +import java.util.Comparator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; @@ -150,12 +151,12 @@ void actualDemoHeadsProduceSortedPublicWorldsWithoutMembershipJoinOrAnyReadMutat assertThat(f.worlds.listWorlds(f.token)) .containsExactly( - new BootstrapWorldDto("alpha", "World alpha"), - new BootstrapWorldDto("zulu", "World zulu")); + new BootstrapWorldDto(alpha.target().tenantSlug(), "alpha", "World alpha"), + new BootstrapWorldDto(zulu.target().tenantSlug(), "zulu", "World zulu")); assertThat(f.worlds.listWorlds(f.token)) .containsExactly( - new BootstrapWorldDto("alpha", "World alpha"), - new BootstrapWorldDto("zulu", "World zulu")); + new BootstrapWorldDto(alpha.target().tenantSlug(), "alpha", "World alpha"), + new BootstrapWorldDto(zulu.target().tenantSlug(), "zulu", "World zulu")); assertThat(f.snapshot()).isEqualTo(before); assertThat(f.inTransaction(() -> f.sources.readCurrentSourceSelection(alpha.tenantId()).kind())) @@ -223,7 +224,7 @@ void originalDemoObservationExpiresDuringFinalCollectionReadWithoutRestamping() } @Test - void ambiguousWorldSlugAcrossTwoRealDemoTenantsRefusesInsteadOfChoosingOne() { + void repeatedWorldSlugAcrossTwoRealDemoTenantsReturnsBothQualifiedSelectorsInOrder() { Fixture f = fixture(); DemoTenant first = f.demo("same-world", true); DemoTenant second = f.demo("same-world", true); @@ -231,7 +232,20 @@ void ambiguousWorldSlugAcrossTwoRealDemoTenantsRefusesInsteadOfChoosingOne() { List.of(first.target(), second.target()), List.of(second.target(), first.target())); Map before = f.snapshot(); - assertCode("ADMISSION_POINTER_UNAVAILABLE", () -> f.worlds.listWorlds(f.token)); + List expected = + List.of(first, second).stream() + .sorted( + Comparator.comparing((DemoTenant tenant) -> tenant.target().worldSlug()) + .thenComparing(tenant -> tenant.target().tenantSlug())) + .map( + tenant -> + new BootstrapWorldDto( + tenant.target().tenantSlug(), + tenant.target().worldSlug(), + tenant.target().worldDisplayName())) + .toList(); + + assertThat(f.worlds.listWorlds(f.token)).containsExactlyElementsOf(expected); assertThat(f.snapshot()).isEqualTo(before); f.assertNoAdmissionRowsOrPaidReads(); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPrimaryAuthenticationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPrimaryAuthenticationPostgresIntegrationTest.java index 43a3e85b93..238822168b 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPrimaryAuthenticationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPrimaryAuthenticationPostgresIntegrationTest.java @@ -31,6 +31,7 @@ import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; import net.firedevops.firemud.accountservice.repository.PasswordResetTokenRepository; +import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository; import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; @@ -440,8 +441,7 @@ public Account updatePasswordHashForLockedAccount(Account expected, String passw logoutAllOperations, securityStateOperations, resetSourceChanges, - null, // Audit outbox is not used by credential/reset owner tests. - null, // Connect scopes are not used by credential/reset owner tests. + null, // Account audit outbox is not used by credential/reset owner tests. null, // JOIN operations are not used by credential/reset owner tests. challenges, null, // Realm grants are not used by primary authentication. @@ -450,7 +450,8 @@ public Account updatePasswordHashForLockedAccount(Account expected, String passw null, // Profiles are not used by primary authentication. null, // Profile mapper is not used by primary authentication. null, // Payment transactions are not used by primary authentication. - null, // Subscriptions are not used by primary authentication. + // Retained evidence is not read by primary authentication. + org.mockito.Mockito.mock(RetainedSubscriptionEvidenceRepository.class), null, // External identities are not used by primary authentication. resetTokens, null, // Email verification tokens are not used by primary authentication. @@ -459,8 +460,6 @@ public Account updatePasswordHashForLockedAccount(Account expected, String passw null, // Mail properties are not used by primary authentication. null, // Token properties are not used by primary authentication. null, // JWT auth properties are not used by primary authentication. - null, // Game Session client is not used by primary authentication. - null, // Entity Management client is not used by primary authentication. null, // JWT utility is not used by primary authentication. null, // Session service is not used by primary authentication. manager); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java index 62ee56af53..88edc2d1c8 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java @@ -70,6 +70,7 @@ import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; import net.firedevops.firemud.accountservice.repository.PasswordResetTokenRepository; +import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; import net.firedevops.firemud.accountservice.service.AccountGenerationProjection; import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; @@ -2507,7 +2508,6 @@ private static AccountServiceImpl primaryCredentialAuthority( null, null, null, - null, challenges, null, null, @@ -2515,9 +2515,7 @@ private static AccountServiceImpl primaryCredentialAuthority( null, null, null, - null, - null, - null, + org.mockito.Mockito.mock(RetainedSubscriptionEvidenceRepository.class), null, null, null, @@ -3116,8 +3114,7 @@ private static void commitPasswordResetAuthorityChange( logoutAllOperations, securityStateOperations, sourceChanges, - null, // audit outbox - null, // connect scopes + null, // account audit outbox null, // join operations null, // email login challenges null, // realm grants @@ -3126,7 +3123,8 @@ private static void commitPasswordResetAuthorityChange( null, // profiles null, // profile mapper null, // payment transactions - null, // subscriptions + // retained subscription evidence + org.mockito.Mockito.mock(RetainedSubscriptionEvidenceRepository.class), null, // external account identities resetTokens, null, // email verification tokens @@ -3137,8 +3135,6 @@ private static void commitPasswordResetAuthorityChange( null, null, null, - null, - null, context.manager()); inTransaction( context, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifierPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifierPostgresIntegrationTest.java index 696ffe803a..124b9a3fac 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifierPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifierPostgresIntegrationTest.java @@ -31,6 +31,7 @@ import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; +import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; import net.firedevops.firemud.accountservice.service.session.AccountGameplayCanonicalLoginOwner; @@ -294,7 +295,6 @@ private static Harness harness(String authModes, boolean expired) { null, null, null, - null, challenges, null, null, @@ -302,9 +302,7 @@ private static Harness harness(String authModes, boolean expired) { null, null, null, - null, - null, - null, + org.mockito.Mockito.mock(RetainedSubscriptionEvidenceRepository.class), null, null, null, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPostgresIntegrationTest.java index d11ddd6fad..8731b20cf2 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPostgresIntegrationTest.java @@ -37,13 +37,13 @@ import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; -import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; +import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository; import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; @@ -1892,7 +1892,6 @@ private static Context contextAtVersion( mock(AccountSecurityStateOperationRepository.class), mock(AccountPasswordResetDraftSourceChangeRepository.class), mock(AccountAuditOutboxRepository.class), - mock(AccountConnectScopeRepository.class), mock(AccountJoinOperationRepository.class), challenges, null, @@ -1901,9 +1900,7 @@ private static Context contextAtVersion( null, null, null, - null, - null, - null, + org.mockito.Mockito.mock(RetainedSubscriptionEvidenceRepository.class), null, null, null, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationAdmissionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationAdmissionPostgresIntegrationTest.java index be5a5fdb41..0b6d5c792c 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationAdmissionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationAdmissionPostgresIntegrationTest.java @@ -22,13 +22,13 @@ import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; -import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; +import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; import net.firedevops.firemud.test.TestContainerImages; @@ -513,7 +513,6 @@ private static Context context() { mock(AccountSecurityStateOperationRepository.class), mock(AccountPasswordResetDraftSourceChangeRepository.class), mock(AccountAuditOutboxRepository.class), - mock(AccountConnectScopeRepository.class), mock(AccountJoinOperationRepository.class), challenges, null, @@ -522,9 +521,7 @@ private static Context context() { null, null, null, - null, - null, - null, + org.mockito.Mockito.mock(RetainedSubscriptionEvidenceRepository.class), null, null, null, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java index 95aabd3c51..0d552450fc 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java @@ -42,7 +42,6 @@ import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; -import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository; import net.firedevops.firemud.accountservice.repository.AccountInitialTenantBillingOwnerRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; @@ -55,6 +54,7 @@ import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; import net.firedevops.firemud.accountservice.service.AccountCreatorMembershipSourceReader; import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository; import net.firedevops.firemud.accountservice.service.AccountTenantCreationBootstrapAuthorizationSource; @@ -1267,7 +1267,6 @@ private static StorageContext storageContext(int recentAgeSeconds, int maxClockS mock(AccountSecurityStateOperationRepository.class), mock(AccountPasswordResetDraftSourceChangeRepository.class), mock(AccountAuditOutboxRepository.class), - mock(AccountConnectScopeRepository.class), mock(AccountJoinOperationRepository.class), challenges, null, @@ -1276,9 +1275,7 @@ private static StorageContext storageContext(int recentAgeSeconds, int maxClockS null, null, null, - null, - null, - null, + org.mockito.Mockito.mock(RetainedSubscriptionEvidenceRepository.class), null, null, null, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationSourceOrderPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationSourceOrderPostgresIntegrationTest.java index 78248339c5..d8c9ba3a53 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationSourceOrderPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationSourceOrderPostgresIntegrationTest.java @@ -49,13 +49,13 @@ import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; -import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; +import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; @@ -916,7 +916,6 @@ private static Context context() { mock(AccountSecurityStateOperationRepository.class), mock(AccountPasswordResetDraftSourceChangeRepository.class), mock(AccountAuditOutboxRepository.class), - mock(AccountConnectScopeRepository.class), mock(AccountJoinOperationRepository.class), challenges, null, @@ -925,9 +924,7 @@ private static Context context() { null, null, null, - null, - null, - null, + org.mockito.Mockito.mock(RetainedSubscriptionEvidenceRepository.class), null, null, null, diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java index 609772d54f..d5cd84e263 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java @@ -17,6 +17,7 @@ import java.util.List; import java.util.Map; +import java.util.UUID; import net.firedevops.firemud.accountservice.dto.AuthenticationResult; import net.firedevops.firemud.accountservice.dto.BootstrapCharacterDto; import net.firedevops.firemud.accountservice.dto.BootstrapRealmDto; @@ -62,7 +63,44 @@ void localJoinResponseCarriesAccountUuidWithoutPublishingTheRoute() throws Excep when(accountService.joinPublicProduction("bootstrap", request)) .thenReturn( new net.firedevops.firemud.accountservice.dto.JoinPublicProductionResult( - true, "JOINED", accountUuid, 7L, 8L, 1L, 1L, false)); + true, + "JOINED", + accountUuid, + UUID.fromString("22222222-2222-4222-8222-222222222222"), + 8L, + 2L, + 1L, + true, + false)); + mockMvc + .perform( + post("/auth/bootstrap/join") + .header(HttpHeaders.AUTHORIZATION, "Bearer bootstrap") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(request))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.data.accountId").value(accountUuid)) + .andExpect(jsonPath("$.data.gameplayAdmissionAllowed").value(true)); + } + + @Test + void successfulActiveMembershipResponsePreservesNonAdmittingSnapshot() throws Exception { + String account = "d09f80cb-a46a-415e-8d35-c9e8068e49de"; + var request = + new net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest( + "scope", "active-request"); + when(accountService.joinPublicProduction("bootstrap", request)) + .thenReturn( + new net.firedevops.firemud.accountservice.dto.JoinPublicProductionResult( + true, + "ALREADY_ACTIVE", + account, + UUID.fromString("22222222-2222-4222-8222-222222222222"), + 8L, + 3L, + 2L, + false, + false)); mockMvc .perform( post("/auth/bootstrap/join") @@ -70,7 +108,9 @@ void localJoinResponseCarriesAccountUuidWithoutPublishingTheRoute() throws Excep .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(request))) .andExpect(status().isOk()) - .andExpect(jsonPath("$.data.accountId").value(accountUuid)); + .andExpect(jsonPath("$.data.success").value(true)) + .andExpect(jsonPath("$.data.outcomeCode").value("ALREADY_ACTIVE")) + .andExpect(jsonPath("$.data.gameplayAdmissionAllowed").value(false)); } @Test @@ -222,34 +262,34 @@ void connectTokenSetsCookieAndReturnsMetadataOnly() throws Exception { @Test void listBootstrapWorldsReturnsVisibleWorlds() throws Exception { when(accountService.listBootstrapWorlds("boot123")) - .thenReturn(List.of(new BootstrapWorldDto("demo", "Demo World"))); + .thenReturn(List.of(new BootstrapWorldDto("tenant-demo", "demo", "Demo World"))); mockMvc .perform(get("/auth/bootstrap/worlds").header(HttpHeaders.AUTHORIZATION, "Bearer boot123")) .andExpect(status().isOk()) .andExpect(jsonPath("$.status").value("SUCCESS")) + .andExpect(jsonPath("$.data[0].tenantSlug").value("tenant-demo")) .andExpect(jsonPath("$.data[0].worldSlug").value("demo")); } @Test void listBootstrapRealmsReturnsVisibleRealms() throws Exception { - when(accountService.listBootstrapRealms("boot123", "demo")) + when(accountService.listBootstrapRealms("boot123", "tenant-demo", "demo")) .thenReturn( List.of( new BootstrapRealmDto( "demo", "production", - "4c4b57d8-e3a2-48fe-9977-e7df0fdce901", + UUID.fromString("4c4b57d8-e3a2-48fe-9977-e7df0fdce901"), "Live Realm", - 1L, - 42L, + UUID.fromString("07aee9f3-a635-4b7f-aa66-86489320d7c3"), + UUID.fromString("3ddc3564-435b-479d-b14d-c91995e673cc"), 17L, 23L, - "8b1a9953-c461-4f4c-9f6d-1f5c5c0d2d88", + UUID.fromString("8b1a9953-c461-4f4c-9f6d-1f5c5c0d2d88"), "PLAYABLE_STATE_SCOPE_SHARED", - false, "SHARED", - "ALLOW_NEW", + "PRESEEDED_ONLY", "2026-03-30T00:00:00Z", "2026-03-30T00:02:00Z", "scope-1"))); @@ -257,11 +297,16 @@ void listBootstrapRealmsReturnsVisibleRealms() throws Exception { mockMvc .perform( get("/auth/bootstrap/worlds/demo/realms") + .param("tenantSlug", "tenant-demo") .header(HttpHeaders.AUTHORIZATION, "Bearer boot123")) .andExpect(status().isOk()) .andExpect(jsonPath("$.status").value("SUCCESS")) .andExpect(jsonPath("$.data[0].realmSlug").value("production")) .andExpect(jsonPath("$.data[0].realmId").value("4c4b57d8-e3a2-48fe-9977-e7df0fdce901")) + .andExpect(jsonPath("$.data[0].tenantId").value("07aee9f3-a635-4b7f-aa66-86489320d7c3")) + .andExpect( + jsonPath("$.data[0].gameInstanceId").value("3ddc3564-435b-479d-b14d-c91995e673cc")) + .andExpect(jsonPath("$.data[0].requiresCharacterSelection").doesNotExist()) .andExpect(jsonPath("$.data[0].catalogRevision").value(23)) .andExpect( jsonPath("$.data[0].playableStateNamespaceId") @@ -271,11 +316,27 @@ void listBootstrapRealmsReturnsVisibleRealms() throws Exception { .andExpect(jsonPath("$.data[0].connectScopeId").value("scope-1")); } + @Test + void listBootstrapRealmsRequiresTenantSelector() throws Exception { + mockMvc + .perform( + get("/auth/bootstrap/worlds/demo/realms") + .header(HttpHeaders.AUTHORIZATION, "Bearer boot123")) + .andExpect(status().isBadRequest()); + org.mockito.Mockito.verifyNoInteractions(accountService); + } + @Test void listBootstrapCharactersReturnsCharacters() throws Exception { when(accountService.listBootstrapCharacters("boot123", "demo", "production", "scope-1")) .thenReturn( - List.of(new BootstrapCharacterDto("char-1", "Mara", 12, "SHARED", "ALLOW_NEW"))); + List.of( + new BootstrapCharacterDto( + "11111111-1111-4111-8111-111111111111", + "Mara", + 12, + "SHARED", + "PRESEEDED_ONLY"))); mockMvc .perform( @@ -284,8 +345,11 @@ void listBootstrapCharactersReturnsCharacters() throws Exception { .header(HttpHeaders.AUTHORIZATION, "Bearer boot123")) .andExpect(status().isOk()) .andExpect(jsonPath("$.status").value("SUCCESS")) - .andExpect(jsonPath("$.data[0].characterId").value("char-1")) - .andExpect(jsonPath("$.data[0].characterName").value("Mara")); + .andExpect(jsonPath("$.data[0].characterId").value("11111111-1111-4111-8111-111111111111")) + .andExpect(jsonPath("$.data[0].characterName").value("Mara")) + .andExpect(jsonPath("$.data[0].level").value(12)) + .andExpect(jsonPath("$.data[0].stateScope").value("SHARED")) + .andExpect(jsonPath("$.data[0].characterCreationPolicy").value("PRESEEDED_ONLY")); } @Test diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/data/TestDataSeederTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/data/TestDataSeederTest.java index b76fe71ace..9f17499d2c 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/data/TestDataSeederTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/data/TestDataSeederTest.java @@ -4,9 +4,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.never; @@ -14,17 +11,13 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import java.time.LocalDateTime; -import java.util.List; import java.util.Optional; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; import net.firedevops.firemud.accountservice.entity.Profile; -import net.firedevops.firemud.accountservice.entity.Subscription; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; import net.firedevops.firemud.accountservice.repository.ProfileRepository; -import net.firedevops.firemud.accountservice.repository.SubscriptionRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; @@ -36,7 +29,6 @@ class TestDataSeederTest { @Mock AccountRepository accountRepository; @Mock AccountTenantMembershipRepository accountTenantMembershipRepository; @Mock ProfileRepository profileRepository; - @Mock SubscriptionRepository subscriptionRepository; private TestDataSeeder seeder; @@ -44,15 +36,11 @@ class TestDataSeederTest { void setup() { MockitoAnnotations.openMocks(this); seeder = - new TestDataSeeder( - accountRepository, - accountTenantMembershipRepository, - profileRepository, - subscriptionRepository); + new TestDataSeeder(accountRepository, accountTenantMembershipRepository, profileRepository); } @Test - void runSeedsDemoAccountMembershipProfileAndSubscriptionWhenMissing() { + void runSeedsDemoAccountMembershipAndProfileWhenMissing() { Account account = new Account(); account.setId(1L); account.setEmail("demo@example.com"); @@ -62,23 +50,12 @@ void runSeedsDemoAccountMembershipProfileAndSubscriptionWhenMissing() { when(accountTenantMembershipRepository.findByAccountIdAndTenantId(1L, 1L)) .thenReturn(Optional.empty()); when(profileRepository.findByAccountIdAndTenantId(1L, 1L)).thenReturn(Optional.empty()); - when(subscriptionRepository.findByTenantId(1L)).thenReturn(List.of()); seeder.run(new DefaultApplicationArguments(new String[] {})); verify(accountRepository).save(any(Account.class)); verify(accountTenantMembershipRepository).save(any(AccountTenantMembership.class)); verify(profileRepository).save(any(Profile.class)); - ArgumentCaptor subscriptionCaptor = ArgumentCaptor.forClass(Subscription.class); - verify(subscriptionRepository).save(subscriptionCaptor.capture()); - Subscription seededSubscription = subscriptionCaptor.getValue(); - assertAll( - () -> assertSame(account, seededSubscription.getAccount()), - () -> assertEquals("local-smoke", seededSubscription.getPlanId()), - () -> assertEquals("active", seededSubscription.getStatus()), - () -> assertNotNull(seededSubscription.getStartedAt()), - () -> assertNull(seededSubscription.getEndedAt()), - () -> assertEquals(1L, seededSubscription.getTenantId())); } @Test @@ -96,7 +73,6 @@ void runReassertsExistingDemoAccountWithoutOverwritingExplicitJoin() throws Exce .thenReturn(Optional.of(explicitJoin)); when(profileRepository.findByAccountIdAndTenantId(1L, 1L)) .thenReturn(Optional.of(new Profile())); - when(subscriptionRepository.findByTenantId(1L)).thenReturn(List.of()); seeder.run(new DefaultApplicationArguments(new String[] {})); @@ -126,7 +102,6 @@ void runReassertsExistingDemoAccountWithoutOverwritingExplicitJoin() throws Exce org.junit.jupiter.api.Assertions.assertEquals( "EXPLICIT_JOIN", explicitJoin.getAuthorityProvenance())); verify(profileRepository, never()).save(any(Profile.class)); - verify(subscriptionRepository).save(any(Subscription.class)); } @Test @@ -136,11 +111,6 @@ void runIsIdempotentWhenInvokedTwice() { account.setEmail("demo@example.com"); AccountTenantMembership seededMembership = membership(account, 1L, "ACTIVE", "SEEDED_DEMO", true); - Subscription seededSubscription = new Subscription(); - seededSubscription.setAccount(account); - seededSubscription.setPlanId("local-smoke"); - seededSubscription.setStatus("active"); - seededSubscription.setTenantId(1L); when(accountRepository.findByEmail("demo@example.com")) .thenReturn(Optional.empty(), Optional.of(account)); @@ -149,82 +119,12 @@ void runIsIdempotentWhenInvokedTwice() { .thenReturn(Optional.empty(), Optional.of(seededMembership)); when(profileRepository.findByAccountIdAndTenantId(1L, 1L)) .thenReturn(Optional.empty(), Optional.of(new Profile())); - when(subscriptionRepository.findByTenantId(1L)) - .thenReturn(List.of(), List.of(seededSubscription)); seeder.run(new DefaultApplicationArguments(new String[] {})); seeder.run(new DefaultApplicationArguments(new String[] {})); verify(accountTenantMembershipRepository, times(1)).save(any(AccountTenantMembership.class)); verify(profileRepository, times(1)).save(any(Profile.class)); - verify(subscriptionRepository, times(1)).save(any(Subscription.class)); - } - - @Test - void runRetainsExistingSubscriptionWithoutOverwritingItsStatus() { - Account account = new Account(); - account.setId(1L); - account.setEmail("demo@example.com"); - Account billingOwner = new Account(); - billingOwner.setId(2L); - AccountTenantMembership explicitJoin = membership(account, 1L, "ACTIVE", "EXPLICIT_JOIN", true); - explicitJoin.setMembershipVersion(4L); - explicitJoin.setMembershipAuthorityGeneration(8L); - Subscription existingSubscription = new Subscription(); - existingSubscription.setAccount(billingOwner); - existingSubscription.setPlanId("billing-owned-plan"); - existingSubscription.setStatus("canceled"); - existingSubscription.setEndedAt(LocalDateTime.of(2025, 1, 2, 3, 4)); - existingSubscription.setTenantId(1L); - - when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); - when(accountRepository.save(any(Account.class))).thenReturn(account); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(1L, 1L)) - .thenReturn(Optional.of(explicitJoin)); - when(profileRepository.findByAccountIdAndTenantId(1L, 1L)) - .thenReturn(Optional.of(new Profile())); - when(subscriptionRepository.findByTenantId(1L)).thenReturn(List.of(existingSubscription)); - - seeder.run(new DefaultApplicationArguments(new String[] {})); - - assertAll( - () -> assertSame(billingOwner, existingSubscription.getAccount()), - () -> assertEquals("canceled", existingSubscription.getStatus()), - () -> assertEquals("billing-owned-plan", existingSubscription.getPlanId()), - () -> assertEquals(LocalDateTime.of(2025, 1, 2, 3, 4), existingSubscription.getEndedAt())); - verify(accountTenantMembershipRepository, never()).save(any(AccountTenantMembership.class)); - verify(subscriptionRepository, never()).save(any(Subscription.class)); - } - - @Test - void runFailsClosedWhenExistingTenantSubscriptionsAreAmbiguous() { - Account account = new Account(); - account.setId(1L); - account.setEmail("demo@example.com"); - AccountTenantMembership explicitJoin = membership(account, 1L, "ACTIVE", "EXPLICIT_JOIN", true); - Subscription active = new Subscription(); - active.setStatus("active"); - active.setTenantId(1L); - Subscription canceled = new Subscription(); - canceled.setStatus("canceled"); - canceled.setTenantId(1L); - - when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); - when(accountRepository.save(any(Account.class))).thenReturn(account); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(1L, 1L)) - .thenReturn(Optional.of(explicitJoin)); - when(profileRepository.findByAccountIdAndTenantId(1L, 1L)) - .thenReturn(Optional.of(new Profile())); - when(subscriptionRepository.findByTenantId(1L)).thenReturn(List.of(active, canceled)); - - IllegalStateException exception = - assertThrows( - IllegalStateException.class, - () -> seeder.run(new DefaultApplicationArguments(new String[] {}))); - - assertTrue(exception.getMessage().contains("ambiguous subscription authority")); - verify(accountTenantMembershipRepository, never()).save(any(AccountTenantMembership.class)); - verify(subscriptionRepository, never()).save(any(Subscription.class)); } @Test diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepositoryTest.java index 3d6f9cb464..19b9f00349 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepositoryTest.java @@ -78,7 +78,7 @@ void expiredExactAttemptBeforeAbsoluteDeadlineLeavesWorkAndReservationUntouched( new AccountHostingSubscriptionLifecycleRepository( dsl, controlledIntents, - Clock.fixed(expiresAt.plusSeconds(secondsAfterExpiry), ZoneOffset.UTC), + Clock.fixed(expiresAt.minusSeconds(5), ZoneOffset.UTC), limits(3, 2, Duration.ofSeconds(10), Duration.ofSeconds(1), Duration.ofHours(1)), new AccountHostingSubscriptionLifecyclePolicy( Duration.ofSeconds(15), @@ -102,14 +102,19 @@ void expiredExactAttemptBeforeAbsoluteDeadlineLeavesWorkAndReservationUntouched( String lockedWorkSql = "SELECT * FROM subscription_provisioning_work WHERE request_id = ? FOR UPDATE"; when(dsl.fetchOne(lockedWorkSql, requestId)).thenReturn(retainedWork); + var databaseClock = mock(Record.class); + when(databaseClock.get("now", OffsetDateTime.class)) + .thenReturn(expiresAt.plusSeconds(secondsAfterExpiry).atOffset(ZoneOffset.UTC)); + when(dsl.fetchOne("SELECT clock_timestamp() AS now")).thenReturn(databaseClock); TransactionSynchronizationManager.setActualTransactionActive(true); assertThat(controlledRepository.deferUnresolved(claim)).isEqualTo(Disposition.ATTEMPT_EXPIRED); - // Exactly the owner/retained-work locks are allowed: no SQL writes, intent settlement, + // Only owner/retained-work locks and the database clock are read: no SQL writes, settlement, // reservation release, or replacement attempt can occur on this return. verify(controlledIntents).lockForProvisioningRecovery(requestId, 7L); verify(dsl).fetchOne(lockedWorkSql, requestId); + verify(dsl).fetchOne("SELECT clock_timestamp() AS now"); verifyNoMoreInteractions(controlledIntents, dsl); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepositoryCanonicalTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepositoryCanonicalTest.java index 13ca149b90..9b297e414a 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepositoryCanonicalTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepositoryCanonicalTest.java @@ -2,11 +2,24 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; import java.time.Instant; import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; +import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository.CanonicalConnectScopeEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinOperationConflictException; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinOperationEvidence; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinTerminalProof; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; +import org.jooq.DSLContext; import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; class AccountJoinOperationRepositoryCanonicalTest { private static final String STREAM = @@ -26,39 +39,241 @@ void terminalProofBindsFirstSequenceAndExactMembershipRevision() { } @Test - void terminalProofRejectsNonFirstSequenceAndUnsupportedMembershipRevision() { + void terminalProofRetainsLaterMembershipEventAndRevisionWithoutClaimingFirstJoin() { + var later = proof(3L, 4L); + assertThat(later.eventSequence()).isEqualTo(3L); + assertThat(later.membershipVersion()).isEqualTo(4L); + // Actual first-JOIN writes retain their distinct exact 1/2/1 repository and SQL checks. + } + + @Test + void firstJoinRejectsNonFirstEventSequenceBeforeOwnerStorageReads() { + DSLContext dsl = mock(DSLContext.class); + AccountConnectScopeRepository scopes = mock(AccountConnectScopeRepository.class); + var repository = new AccountJoinOperationRepository(dsl, scopes); + + assertThatThrownBy( + () -> + repository.commitCanonicalFirstJoin( + "request-v2", mock(CanonicalJoinScopeV2.class), "caller", proof(2L, 2L))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Exact first-JOIN terminal proof required"); + verifyNoInteractions(dsl, scopes); + } + + @Test + void firstJoinRejectsNonFirstMembershipRevisionBeforeOwnerStorageReads() { + DSLContext dsl = mock(DSLContext.class); + AccountConnectScopeRepository scopes = mock(AccountConnectScopeRepository.class); + var repository = new AccountJoinOperationRepository(dsl, scopes); + + assertThatThrownBy( + () -> + repository.commitCanonicalFirstJoin( + "request-v2", mock(CanonicalJoinScopeV2.class), "caller", proof(1L, 3L))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Exact first-JOIN terminal proof required"); + verifyNoInteractions(dsl, scopes); + } + + @Test + void terminalProofRejectsNonpositiveEventOrMembershipRevision() { + assertThatThrownBy(() -> proof(0L, 2L)).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> proof(1L, 0L)).isInstanceOf(IllegalArgumentException.class); + } + + private static CanonicalJoinTerminalProof proof(long sequence, long version) { + return new CanonicalJoinTerminalProof( + STREAM, + sequence, + "event-1", + SHA256, + UUID.fromString("75c70a9e-beb4-3ee2-9d9d-50e28f1123d6"), + SHA256, + Instant.parse("2026-10-04T00:00:00Z"), + 5L, + 73L, + version, + 1L); + } + + @Test + void boundPendingDiagnosticsRemainSeparateFromTheAvailablePolicy() { + var unavailable = + evidence(true, "PENDING", null, "UNAVAILABLE", "ENTITLEMENT_UNAVAILABLE", null, null); + assertThat(unavailable.entitlementAuthorityAvailability()).isEqualTo("AVAILABLE"); + assertThat(unavailable.entitlementVersion()).isEqualTo(5); + assertThat(unavailable.lastAttemptAuthorityAvailability()).isEqualTo("UNAVAILABLE"); + assertThat(unavailable.lastAttemptFailureCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); + assertThatThrownBy(() -> evidence(true, "PENDING", null, "UNAVAILABLE", null, null, null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + evidence(true, "PENDING", null, "AVAILABLE", "ENTITLEMENT_UNAVAILABLE", null, null)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void failedEvidenceMayRetainPolicyButCannotCarrySuccessProofOrRetryableOutcome() { + var prePolicy = + evidence(false, "FAILED", "CONNECT_SCOPE_INVALID", "NOT_EVALUATED", null, null, null); + var afterPolicy = + evidence(true, "FAILED", "IDEMPOTENCY_CONFLICT", "AVAILABLE", null, null, null); + assertThat(prePolicy.requestDigest()).isNull(); + assertThat(afterPolicy.entitlementVersion()).isEqualTo(5); + assertThat(afterPolicy.membershipId()).isNull(); + assertThat(afterPolicy.terminalProof()).isNull(); + assertThatThrownBy( + () -> evidence(true, "FAILED", "AUTH_UNAVAILABLE", "AVAILABLE", null, null, null)) + .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy( () -> - new CanonicalJoinTerminalProof( - STREAM, - 2L, - "event-1", - SHA256, - UUID.fromString("75c70a9e-beb4-3ee2-9d9d-50e28f1123d6"), - SHA256, - Instant.parse("2026-10-04T00:00:00Z"), - 5L, - 73L, - 2L, - 1L)) + evidence( + true, "FAILED", "CONNECT_SCOPE_INVALID", "AVAILABLE", null, validProof(), 73L)) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy( () -> - new CanonicalJoinTerminalProof( - STREAM, - 1L, - "event-1", - SHA256, - UUID.fromString("75c70a9e-beb4-3ee2-9d9d-50e28f1123d6"), - SHA256, - Instant.parse("2026-10-04T00:00:00Z"), - 5L, - 73L, - 3L, - 1L)) + evidence( + true, + "FAILED", + "CONNECT_SCOPE_INVALID", + "UNAVAILABLE", + "ENTITLEMENT_UNAVAILABLE", + null, + null)) .isInstanceOf(IllegalArgumentException.class); } + /** Controlled journal content, not caller authentication or entitlement source evidence. */ + @Test + void committedNullOutcomeIsClassifiedAsInconsistentTerminalEvidence() { + var proof = validProof(); + var proofWithoutAudit = + new CanonicalJoinTerminalProof( + proof.eventStreamKey(), + proof.eventSequence(), + proof.eventId(), + proof.eventDigest(), + null, + null, + null, + proof.entitlementVersion(), + proof.membershipId(), + proof.membershipVersion(), + proof.membershipAuthorityGeneration()); + assertThat(evidence(true, "COMMITTED", "JOINED", "AVAILABLE", null, proof, 73L)).isNotNull(); + assertThat( + evidence( + true, "COMMITTED", "ALREADY_ACTIVE", "AVAILABLE", null, proofWithoutAudit, 73L)) + .isNotNull(); + assertThatThrownBy( + () -> evidence(true, "COMMITTED", null, "AVAILABLE", null, proofWithoutAudit, 73L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Canonical JOIN terminal evidence is inconsistent"); + } + + @Test + void nullCommitOutcomeIsClassifiedBeforeOwnerStorageReads() { + DSLContext dsl = mock(DSLContext.class); + AccountConnectScopeRepository scopes = mock(AccountConnectScopeRepository.class); + var repository = new AccountJoinOperationRepository(dsl, scopes); + boolean active = TransactionSynchronizationManager.isActualTransactionActive(); + boolean readOnly = TransactionSynchronizationManager.isCurrentTransactionReadOnly(); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + try { + assertThatThrownBy( + () -> + repository.commitCanonicalJoin( + "request-v2", mock(CanonicalJoinScopeV2.class), "caller", null, validProof())) + .isInstanceOf(CanonicalJoinOperationConflictException.class) + .hasMessage("Canonical JOIN outcome/proof conflict"); + verifyNoInteractions(dsl, scopes); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(active); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(readOnly); + } + } + + private static CanonicalJoinOperationEvidence evidence( + boolean bound, + String status, + String outcome, + String attemptAvailability, + String attemptFailure, + CanonicalJoinTerminalProof proof, + Long membershipId) { + UUID account = UUID.fromString("f4df3b0a-5fc6-4f86-9efc-0f053103b200"); + UUID tenant = UUID.fromString("4347218b-6914-4d50-a5ce-1b4836034f45"); + UUID realm = UUID.fromString("33333333-3333-4333-8333-333333333333"); + var scope = + new CanonicalJoinScopeV2( + "controlled-canonical-scope", + account, + tenant, + realm, + "tenant", + "world", + "production", + realm, + "SHARED", + realm, + 7, + 3, + "2026-11-02T00:00:00Z", + "2026-11-02T00:02:00Z"); + var retained = + new CanonicalConnectScopeEvidence( + AccountJoinDigest.tokenHash(scope.connectScopeId()), + 17, + "PUBLIC_PRODUCTION", + account, + tenant, + realm, + "tenant", + "world", + "production", + realm, + "SHARED", + realm, + 7, + 3, + scope.evaluatedAt(), + scope.connectScopeExpiresAt(), + 2, + AccountJoinDigest.scopeV2(scope), + new VerifiedTenantProvenance( + null, TenantProvenanceKind.FRESH_GAME_DESIGN, realm, SHA256)); + return new CanonicalJoinOperationEvidence( + "request-1", + 17, + "caller-1", + retained.scopeTokenHash(), + retained.scopeDigest(), + 2, + 2, + 2, + AccountJoinDigest.intentV2("request-1", scope, "caller-1"), + bound ? "AVAILABLE" : "NOT_EVALUATED", + bound ? true : null, + bound ? 5L : null, + bound ? 2 : null, + bound + ? AccountJoinDigest.requestV2( + scope, "caller-1", AccountJoinDigest.EntitlementAvailabilityV2.AVAILABLE, true, 5L) + : null, + attemptAvailability, + attemptFailure, + false, + status, + outcome, + membershipId, + proof == null ? null : proof.membershipVersion(), + proof == null ? null : proof.membershipAuthorityGeneration(), + proof, + retained); + } + private static CanonicalJoinTerminalProof validProof() { return new CanonicalJoinTerminalProof( STREAM, diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepositoryTest.java index 73ebf73ad8..33c03fd2ca 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepositoryTest.java @@ -270,6 +270,48 @@ baseline, new PairTransition(true, 2L, EVENT_ID_TEXT, EVENT_DIGEST, false))) verifyNoInteractions(dsl); } + @Test + void restoreCannotReuseAbsenceOrInventAnAuthorityInvalidation() { + DSLContext dsl = mock(DSLContext.class); + AccountMembershipPairAuthorityRepository repository = + new AccountMembershipPairAuthorityRepository(dsl); + TransactionSynchronizationManager.setActualTransactionActive(true); + PairAuthority absence = + new PairAuthority( + ACCOUNT_UUID, TENANT_UUID, freshProvenance(), false, 1L, 1L, 0L, null, null, false); + assertThatThrownBy( + () -> + repository.commitRestore( + absence, new PairTransition(true, 1L, EVENT_ID_TEXT, EVENT_DIGEST, false))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("exact current positive pair"); + PairAuthority positive = + new PairAuthority( + ACCOUNT_UUID, + TENANT_UUID, + freshProvenance(), + true, + 3L, + 2L, + 2L, + "inactive-event", + EVENT_DIGEST, + true); + assertThatThrownBy( + () -> + repository.commitRestore( + positive, new PairTransition(true, 3L, EVENT_ID_TEXT, EVENT_DIGEST, true))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("exact current positive pair"); + assertThatThrownBy( + () -> + repository.commitRestore( + positive, new PairTransition(true, 4L, EVENT_ID_TEXT, EVENT_DIGEST, false))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("exact current positive pair"); + verifyNoInteractions(dsl); + } + private static VerifiedTenantProvenance freshProvenance() { return new VerifiedTenantProvenance( null, TenantProvenanceKind.FRESH_GAME_DESIGN, OPERATION_ID, DIGEST); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java index 636c33e740..edef33bdaf 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java @@ -19,6 +19,7 @@ import java.util.Map; import java.util.Optional; import java.util.UUID; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; import net.firedevops.firemud.accountservice.dto.AccountAuditTenantIdentity; @@ -32,6 +33,8 @@ import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Checkpoint; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ReadFence; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinOperationEvidence; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinTerminalProof; @@ -75,14 +78,25 @@ void clearTransactionState() { TransactionSynchronizationManager.clear(); } - @Test - void pendingFirstJoinStagesSourcesAppendsAuditAndCommitsExactTerminalProof() { + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) + void pendingFirstJoinStagesSourcesAppendsAuditAndCommitsExactTerminalProof(boolean paid) { Fixture fixture = new Fixture(); fixture.arrangePending(); fixture.startWritableTransaction(); + var hosting = mock(AccountHostingSubscriptionLifecycleRepository.class); + var fence = mock(ReadFence.class); + var observed = mock(StripeHostingSubscriptionObserver.ObservedSubscription.class); + when(fixture.eventProducer.publishPaidCanonicalFirstJoinMembershipChange( + fixture.scope, REQUEST_ID, CALLER_BINDING, hosting, fence, observed)) + .thenReturn(fixture.checkpoint); CanonicalJoinTerminalProof result = - fixture.coordinator.commitCanonicalFirstJoin(fixture.scope, REQUEST_ID, CALLER_BINDING); + paid + ? fixture.coordinator.commitPaidCanonicalFirstJoin( + fixture.scope, REQUEST_ID, CALLER_BINDING, hosting, fence, observed) + : fixture.coordinator.commitCanonicalFirstJoin( + fixture.scope, REQUEST_ID, CALLER_BINDING); assertThat(result).isEqualTo(fixture.expectedProof); InOrder ordered = inOrder(fixture.memberships, fixture.roles, fixture.eventProducer); @@ -91,9 +105,15 @@ void pendingFirstJoinStagesSourcesAppendsAuditAndCommitsExactTerminalProof() { .verify(fixture.roles) .replaceCanonical( fixture.membership, ACCOUNT_ID, TENANT_ID, fixture.provenance, 2L, List.of("player")); - ordered - .verify(fixture.eventProducer) - .publishCanonicalFirstJoinMembershipChange(fixture.scope, REQUEST_ID, CALLER_BINDING); + if (paid) + ordered + .verify(fixture.eventProducer) + .publishPaidCanonicalFirstJoinMembershipChange( + fixture.scope, REQUEST_ID, CALLER_BINDING, hosting, fence, observed); + else + ordered + .verify(fixture.eventProducer) + .publishCanonicalFirstJoinMembershipChange(fixture.scope, REQUEST_ID, CALLER_BINDING); verify(fixture.audit) .appendCanonicalTenant( fixture.expectedProof.auditEventId(), @@ -104,14 +124,25 @@ void pendingFirstJoinStagesSourcesAppendsAuditAndCommitsExactTerminalProof() { .commitCanonicalFirstJoin(REQUEST_ID, fixture.scope, CALLER_BINDING, fixture.expectedProof); } - @Test - void committedExactRetryReadsReceiptWithoutCreatingMembershipOrAppendingAudit() { + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) + void committedExactRetryReadsReceiptWithoutCreatingMembershipOrAppendingAudit(boolean paid) { Fixture fixture = new Fixture(); fixture.arrangeCommittedReplay(); fixture.startWritableTransaction(); + var hosting = mock(AccountHostingSubscriptionLifecycleRepository.class); + var fence = mock(ReadFence.class); + var observed = mock(StripeHostingSubscriptionObserver.ObservedSubscription.class); CanonicalJoinTerminalProof result = - fixture.coordinator.commitCanonicalFirstJoin(fixture.scope, REQUEST_ID, CALLER_BINDING); + paid + ? fixture.coordinator.commitPaidCanonicalFirstJoin( + fixture.scope, REQUEST_ID, CALLER_BINDING, hosting, fence, observed) + : fixture.coordinator.commitCanonicalFirstJoin( + fixture.scope, REQUEST_ID, CALLER_BINDING); + verifyNoInteractions(hosting); + verify(fixture.eventProducer, never()) + .publishPaidCanonicalFirstJoinMembershipChange(any(), any(), any(), any(), any(), any()); assertThat(result).isEqualTo(fixture.expectedProof); assertThat(fixture.minimalAuditEnvelope.payload()).isNull(); @@ -129,6 +160,194 @@ void committedExactRetryReadsReceiptWithoutCreatingMembershipOrAppendingAudit() .commitCanonicalFirstJoin(REQUEST_ID, fixture.scope, CALLER_BINDING, fixture.expectedProof); } + @Test + void committedJoinReturnsStoredEvidenceWithoutReadingOrMutatingCurrentAuthority() { + Fixture fixture = new Fixture(); + var committed = Fixture.terminal(fixture.operation, fixture.expectedProof, "COMMITTED"); + when(fixture.accounts.findByAccountUuid(ACCOUNT_ID)).thenReturn(Optional.of(fixture.account)); + when(fixture.operations.findCanonicalEvidenceForUpdateByRequestId(REQUEST_ID)) + .thenReturn(Optional.of(committed)); + fixture.startWritableTransaction(); + + var result = + fixture.coordinator.commitCanonicalJoin( + fixture.scope, REQUEST_ID, CALLER_BINDING, null, null, null); + + assertThat(result).isSameAs(committed); + InOrder ordered = inOrder(fixture.accounts, fixture.operations); + ordered.verify(fixture.accounts).findByAccountUuid(ACCOUNT_ID); + ordered.verify(fixture.operations).lockAccount(fixture.account.getId()); + ordered.verify(fixture.operations).findCanonicalEvidenceForUpdateByRequestId(REQUEST_ID); + ordered.verifyNoMoreInteractions(); + verifyNoInteractions( + fixture.memberships, + fixture.roles, + fixture.outbox, + fixture.pairs, + fixture.audit, + fixture.eventProducer); + } + + @Test + void existingJoinRejectsNullScopeBeforeAnyOwnerRead() { + Fixture fixture = new Fixture(); + fixture.startWritableTransaction(); + + assertThatThrownBy( + () -> + fixture.coordinator.commitCanonicalJoin( + null, REQUEST_ID, CALLER_BINDING, null, null, null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("canonical JOIN scope is required"); + verifyNoInteractions( + fixture.accounts, + fixture.operations, + fixture.memberships, + fixture.roles, + fixture.outbox, + fixture.pairs, + fixture.audit, + fixture.eventProducer); + } + + @Test + void existingJoinRejectsUnboundedSelectorsBeforeAnyOwnerRead() { + Fixture fixture = new Fixture(); + fixture.startWritableTransaction(); + + for (String requestId : new String[] {null, "", " ", "x".repeat(129)}) { + assertThatThrownBy( + () -> + fixture.coordinator.commitCanonicalJoin( + fixture.scope, requestId, CALLER_BINDING, null, null, null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical JOIN request ID"); + } + for (String callerBinding : new String[] {null, "", " ", "x".repeat(129)}) { + assertThatThrownBy( + () -> + fixture.coordinator.commitCanonicalJoin( + fixture.scope, REQUEST_ID, callerBinding, null, null, null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("verified caller binding"); + } + verifyNoInteractions( + fixture.accounts, + fixture.operations, + fixture.memberships, + fixture.roles, + fixture.outbox, + fixture.pairs, + fixture.audit, + fixture.eventProducer); + } + + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) + void inactiveJoinRestoresOnlyPlayerWithoutRegrantingRetainedElevatedRoles( + boolean retainedPlayerRole) { + Fixture fixture = new Fixture(); + fixture.arrangePending(); + AccountTenantMembership inactive = fixture.membership(fixture.account); + inactive.setLifecycleState("INACTIVE"); + inactive.setGameplayAdmissionAllowed(false); + inactive.setMembershipVersion(1L); + List retainedRoles = + retainedPlayerRole + ? List.of("designer", "moderator", "player", "tenantAdmin") + : List.of("designer", "moderator", "tenantAdmin"); + RoleSnapshot inactiveRoles = + new RoleSnapshot( + 17L, null, 73L, 1L, retainedRoles, ACCOUNT_ID, TENANT_ID, fixture.provenance); + when(fixture.memberships.findFreshMembershipForUpdate(ACCOUNT_ID, TENANT_ID)) + .thenReturn(Optional.of(inactive)); + when(fixture.roles.findForCanonicalUpdate(ACCOUNT_ID, TENANT_ID, fixture.provenance, 73L, 1L)) + .thenReturn(Optional.of(inactiveRoles)); + when(fixture.memberships.restoreFreshMembershipForJoin(ACCOUNT_ID, TENANT_ID, inactive)) + .thenReturn(fixture.membership); + when(fixture.eventProducer.publishCanonicalRestoredMembershipChange( + fixture.scope, + REQUEST_ID, + CALLER_BINDING, + fixture.positivePair(fixture.event.eventId(), fixture.event.eventDigest()), + null, + null, + null)) + .thenReturn(fixture.checkpoint); + var committed = Fixture.committed(fixture.operation, fixture.expectedProof); + when(fixture.operations.commitCanonicalJoin( + REQUEST_ID, fixture.scope, CALLER_BINDING, "JOINED", fixture.expectedProof)) + .thenReturn(committed); + fixture.startWritableTransaction(); + + var result = + fixture.coordinator.commitCanonicalJoin( + fixture.scope, REQUEST_ID, CALLER_BINDING, null, null, null); + + assertThat(result).isSameAs(committed); + verify(fixture.eventProducer) + .requireCurrentCanonicalJoinPolicy( + fixture.scope, fixture.operation, true, null, null, null); + verify(fixture.audit) + .appendCanonicalTenant( + fixture.expectedProof.auditEventId(), + TENANT_ID.toString(), + "ACCOUNT_JOINED_PUBLIC_PRODUCTION", + fixture.auditPayload); + verify(fixture.audit).findExactCanonicalTenantEnvelopeForUpdate(fixture.auditEnvelope); + verify(fixture.audit, never()).findCanonicalTenantEnvelopeForUpdate(any()); + InOrder ordered = inOrder(fixture.roles, fixture.eventProducer); + ordered + .verify(fixture.roles) + .findForCanonicalUpdate(ACCOUNT_ID, TENANT_ID, fixture.provenance, 73L, 1L); + ordered + .verify(fixture.roles) + .replaceCanonical( + fixture.membership, ACCOUNT_ID, TENANT_ID, fixture.provenance, 2L, List.of("player")); + ordered + .verify(fixture.eventProducer) + .publishCanonicalRestoredMembershipChange( + fixture.scope, + REQUEST_ID, + CALLER_BINDING, + fixture.positivePair(fixture.event.eventId(), fixture.event.eventDigest()), + null, + null, + null); + // Capture every role write, not the immutable fixture event returned by the mocked producer. + org.mockito.ArgumentCaptor> writtenRoles = + org.mockito.ArgumentCaptor.forClass(List.class); + verify(fixture.roles) + .replaceCanonical(any(), any(), any(), any(), anyLong(), writtenRoles.capture()); + assertThat(writtenRoles.getValue()).containsExactly("player"); + } + + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) + void committedJoinStillRejectsChangedRequestOrCallerBinding(boolean changedRequest) { + Fixture fixture = new Fixture(); + String requestId = changedRequest ? "different-request" : REQUEST_ID; + String callerBinding = changedRequest ? CALLER_BINDING : "different-caller"; + when(fixture.accounts.findByAccountUuid(ACCOUNT_ID)).thenReturn(Optional.of(fixture.account)); + when(fixture.operations.findCanonicalEvidenceForUpdateByRequestId(requestId)) + .thenReturn(Optional.of(Fixture.committed(fixture.operation, fixture.expectedProof))); + fixture.startWritableTransaction(); + + assertThatThrownBy( + () -> + fixture.coordinator.commitCanonicalJoin( + fixture.scope, requestId, callerBinding, null, null, null)) + .isInstanceOf(AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class) + .hasMessage("Canonical JOIN intent conflicts"); + verifyNoInteractions( + fixture.memberships, + fixture.roles, + fixture.outbox, + fixture.pairs, + fixture.audit, + fixture.eventProducer); + } + @Test void changedCallerUnderGlobalRequestIdConflictsBeforeReturningAnyReceipt() { Fixture fixture = new Fixture(); @@ -569,6 +788,12 @@ private static CanonicalJoinOperationEvidence operation( private static CanonicalJoinOperationEvidence committed( CanonicalJoinOperationEvidence pending, CanonicalJoinTerminalProof proof) { + return terminal(pending, proof, "COMMITTED"); + } + + private static CanonicalJoinOperationEvidence terminal( + CanonicalJoinOperationEvidence pending, CanonicalJoinTerminalProof proof, String status) { + boolean success = "COMMITTED".equals(status); return new CanonicalJoinOperationEvidence( pending.requestId(), pending.privateAccountId(), @@ -587,12 +812,12 @@ private static CanonicalJoinOperationEvidence committed( pending.lastAttemptAuthorityAvailability(), pending.lastAttemptFailureCode(), pending.callerBoundAuthorityInvalidated(), - "COMMITTED", - "JOINED", - proof.membershipId(), - proof.membershipVersion(), - proof.membershipAuthorityGeneration(), - proof, + status, + success ? "JOINED" : "PUBLIC_PRODUCTION_ADMISSION_DENIED", + success ? proof.membershipId() : null, + success ? proof.membershipVersion() : null, + success ? proof.membershipAuthorityGeneration() : null, + success ? proof : null, pending.scopeEvidence()); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwnerTest.java index 7964545d21..7765522719 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwnerTest.java @@ -34,6 +34,8 @@ import net.firedevops.firemud.accountservice.config.AccountTokenProperties; import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; +import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; +import net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; @@ -86,6 +88,246 @@ class AccountCanonicalPublicRealmScopeOwnerTest { private static final UUID TENANT = UUID.fromString("22222222-2222-4222-8222-222222222222"); private static final long PRIVATE_ACCOUNT = 41L; private static final String NAMESPACE = "prod"; + + @Test + void directProducerUsesExactGameSessionPeerAndCurrentOwnersWithoutBootstrapRegistry() { + Fixture f = new Fixture(300000L); + f.active.set(false); + var target = directTarget(f.target); + var caller = directCaller(f.target); + java.util.concurrent.atomic.AtomicReference result = + new java.util.concurrent.atomic.AtomicReference<>(); + directPeer(NAMESPACE, "game-session-service") + .run(() -> result.set(f.owner.issueDirectTextScope(caller, target).scope())); + + CanonicalJoinScopeV2 scope = result.get(); + assertThat(scope.accountId()).isEqualTo(ACCOUNT); + assertThat(scope.tenantId()).isEqualTo(TENANT); + assertThat(scope.gameInstanceId()).isEqualTo(f.target.canonicalGameInstanceId()); + assertThat(f.retained.get()).isEqualTo(scope); + assertThat(f.registryChecks.get()).isZero(); + assertThat(Instant.parse(scope.connectScopeExpiresAt())).isAfter(f.clock.instant()); + verifyNoInteractions(f.sessions); + verify(f.scopes).insertCanonical(PRIVATE_ACCOUNT, scope, f.provenance()); + } + + @ParameterizedTest + @ValueSource(strings = {"00042", "00000000000000000000000000000042", "9223372036854775807"}) + void directProducerAcceptsPositiveSessionBytesWithinTheJoinBoundary(String sessionId) { + Fixture f = new Fixture(300000L); + directPeer(NAMESPACE, "game-session-service") + .run( + () -> { + var scope = + f.owner + .issueDirectTextScope( + directCaller(f.target, sessionId), directTarget(f.target)) + .scope(); + assertThat(scope.accountId()).isEqualTo(ACCOUNT); + assertThat(f.retained.get()).isEqualTo(scope); + verify(f.scopes).insertCanonical(PRIVATE_ACCOUNT, scope, f.provenance()); + }); + } + + @ParameterizedTest + @ValueSource(ints = {33, 128, 129}) + void directProducerRefusesSessionBytesBeyondTheJoinBoundaryBeforeOwnerReads(int length) { + Fixture f = new Fixture(300000L); + String sessionId = "0".repeat(length - 1) + "1"; + directPeer(NAMESPACE, "game-session-service") + .run( + () -> + assertCode( + "CONNECT_CONTEXT_INVALID", + () -> + f.owner.issueDirectTextScope( + directCaller(f.target, sessionId), directTarget(f.target)))); + verifyNoInteractions( + f.accounts, + f.memberships, + f.tenants, + f.heads, + f.scopes, + f.sessions, + f.targets, + f.entitlements); + } + + @ParameterizedTest + @ValueSource( + strings = { + "0", + "-1", + "+1", + " 42", + "42 ", + "1.0", + "1e2", + "abc", + "9223372036854775808", + "\u0664\u0662", + "\uff14\uff12" + }) + void directProducerRefusesNonPositiveAsciiLongsAndRetainsParseCauseBeforeOwnerReads( + String sessionId) { + Fixture f = new Fixture(300000L); + directPeer(NAMESPACE, "game-session-service") + .run( + () -> + assertThatThrownBy( + () -> + f.owner.issueDirectTextScope( + directCaller(f.target, sessionId), directTarget(f.target))) + .isInstanceOf(AuthenticationException.class) + .hasCauseInstanceOf(NumberFormatException.class) + .extracting(failure -> ((AuthenticationException) failure).getCode()) + .isEqualTo("CONNECT_CONTEXT_INVALID")); + verifyNoInteractions( + f.accounts, + f.memberships, + f.tenants, + f.heads, + f.scopes, + f.sessions, + f.targets, + f.entitlements); + } + + @ParameterizedTest + @ValueSource(strings = {"other-namespace", "wrong-service"}) + void directProducerRefusesWrongPeerBeforeReadingAccountOrSources(String mismatch) { + Fixture f = new Fixture(300000L); + var peer = + directPeer( + mismatch.equals("other-namespace") ? "other" : NAMESPACE, + mismatch.equals("wrong-service") ? "world-management-service" : "game-session-service"); + peer.run( + () -> + assertCode( + "AUTH_UNAVAILABLE", + () -> + f.owner.issueDirectTextScope(directCaller(f.target), directTarget(f.target)))); + verifyNoInteractions( + f.accounts, + f.memberships, + f.tenants, + f.heads, + f.scopes, + f.sessions, + f.targets, + f.entitlements); + } + + @Test + void directProducerRejectsUnknownAccountWithoutReadingTargetsOrPersistingScope() { + Fixture f = new Fixture(300000L); + doReturn(Optional.empty()).when(f.accounts).findByAccountUuidForUpdate(ACCOUNT); + + directPeer(NAMESPACE, "game-session-service") + .run( + () -> + assertCode( + "CONNECT_CONTEXT_INVALID", + () -> + f.owner.issueDirectTextScope( + directCaller(f.target), directTarget(f.target)))); + + verify(f.accounts).findByAccountUuidForUpdate(ACCOUNT); + verifyNoInteractions( + f.memberships, f.tenants, f.heads, f.scopes, f.sessions, f.targets, f.entitlements); + } + + @Test + void directProducerKeepsAccountRepositoryFailureRetryableWithoutReadingTargets() { + Fixture f = new Fixture(300000L); + doThrow(new IllegalStateException("Account repository unavailable")) + .when(f.accounts) + .findByAccountUuidForUpdate(ACCOUNT); + + directPeer(NAMESPACE, "game-session-service") + .run( + () -> + assertCode( + "AUTH_UNAVAILABLE", + () -> + f.owner.issueDirectTextScope( + directCaller(f.target), directTarget(f.target)))); + + verify(f.accounts).findByAccountUuidForUpdate(ACCOUNT); + verifyNoInteractions( + f.memberships, f.tenants, f.heads, f.scopes, f.sessions, f.targets, f.entitlements); + } + + @Test + void directProducerReportsUnavailableEntitlementWithoutMisclassifyingThePointer() { + Fixture f = new Fixture(300000L); + when(f.entitlements.evaluate(TENANT)).thenReturn(f.evaluation(false)); + + directPeer(NAMESPACE, "game-session-service") + .run( + () -> + assertCode( + "ENTITLEMENT_UNAVAILABLE", + () -> + f.owner.issueDirectTextScope( + directCaller(f.target), directTarget(f.target)))); + + assertThat(f.targetReads.get()).isEqualTo(2); + verifyNoInteractions(f.scopes, f.sessions, f.memberships); + } + + @Test + void directProducerRechecksCurrentAccountAndTargetBeforePersistingScope() { + Fixture f = new Fixture(300000L); + f.onSecondTargetRead = + () -> f.account.setLifecycleState(AccountLifecycleState.DEACTIVATED_PENDING_DELETE); + directPeer(NAMESPACE, "game-session-service") + .run( + () -> + assertCode( + "AUTH_UNAVAILABLE", + () -> + f.owner.issueDirectTextScope( + directCaller(f.target), directTarget(f.target)))); + verifyNoInteractions(f.scopes, f.sessions); + } + + private static io.grpc.Context directPeer(String namespace, String service) { + return io.grpc.Context.ROOT.withValue( + net.firedevops.firemud.common.grpc.GrpcPeerIdentity.CONTEXT_KEY, + new net.firedevops.firemud.common.grpc.GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service)); + } + + private static DirectTextCallerContext directCaller(Target target) { + return directCaller(target, "00042"); + } + + private static DirectTextCallerContext directCaller(Target target, String sessionId) { + return new DirectTextCallerContext( + ACCOUNT, + target.canonicalTenantId(), + target.realmId(), + target.playableStateNamespaceId(), + target.playableStateScope(), + target.canonicalGameInstanceId(), + sessionId, + "direct-request"); + } + + private static DirectTextJoinTarget directTarget(Target target) { + return new DirectTextJoinTarget( + target.canonicalTenantId(), + target.realmId(), + target.worldSlug(), + target.realmSlug(), + target.playableStateNamespaceId(), + target.playableStateScope(), + target.canonicalGameInstanceId(), + target.catalogRevision(), + target.pointerVersion()); + } + private static final String HASH = "a".repeat(64); @AfterEach @@ -250,6 +492,73 @@ void exactTenantWorldSelectionNeverUsesABareGlobalWorldOrAnotherTenant() { verifyNoInteractions(f.entitlements, f.memberships, f.scopes); } + @Test + void qualifiedWorldUsesTheExactSourceTenantAndRetainedV2Scope() { + Fixture f = new Fixture(300000L); + + var result = f.owner.listRealmScopes(f.token, "tenant", "world").getFirst(); + + assertThat(result.target()).isEqualTo(f.target); + assertThat(result.scope().tenantId()).isEqualTo(f.target.canonicalTenantId()); + assertThat(result.scope().tenantSlug()).isEqualTo(f.target.tenantSlug()); + assertThat(result.scope()).isEqualTo(f.retained.get()); + verify(f.entitlements).evaluate(TENANT); + } + + @Test + void qualifiedWorldAmbiguityWithinOneTenantRefusesBeforeEntitlementOrAccountScopeSources() { + Fixture f = new Fixture(300000L); + Target duplicate = target(TENANT, "tenant", 1L); + f.firstCollection = List.of(f.target, duplicate); + + assertCode( + "ADMISSION_POINTER_UNAVAILABLE", () -> f.owner.listRealmScopes(f.token, "tenant", "world")); + + verifyNoInteractions(f.entitlements, f.tenants, f.heads, f.memberships, f.scopes); + assertThat(f.transactions.started).isZero(); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void qualifiedWorldReplacementOrAmbiguityOnRereadCannotPublishScope(boolean ambiguous) { + Fixture f = new Fixture(300000L); + Target changed = target(TENANT, "tenant", 2L); + f.secondCollection = ambiguous ? List.of(f.target, changed) : List.of(changed); + + assertCode( + "ADMISSION_POINTER_UNAVAILABLE", () -> f.owner.listRealmScopes(f.token, "tenant", "world")); + + verifyNoInteractions(f.scopes); + verify(f.entitlements).evaluate(TENANT); + } + + @Test + void qualifiedWorldSelectionUsesTheSamePipelineWithinTheCompleteCollection() { + Fixture f = new Fixture(300000L); + Target other = target(UUID.randomUUID(), "another-tenant", 1L); + f.firstCollection = List.of(f.target, other); + f.secondCollection = f.firstCollection; + + var result = f.owner.listRealmScopes(f.token, "tenant", "world").getFirst(); + + assertThat(result.scope().tenantId()).isEqualTo(TENANT); + assertThat(result.target()).isEqualTo(f.target); + } + + @Test + void qualifiedWorldAbsenceIsRereadWithoutMintingAndMalformedCallerPrecedesSelection() { + Fixture f = new Fixture(300000L); + f.firstCollection = List.of(); + f.secondCollection = List.of(); + + assertCode( + "CONNECT_CONTEXT_INVALID", () -> f.owner.listRealmScopes("malformed", "tenant", "world")); + verifyNoInteractions(f.targets, f.entitlements, f.scopes); + assertThat(f.owner.listRealmScopes(f.token, "tenant", "world")).isEmpty(); + assertThat(f.targetReads.get()).isEqualTo(2); + verifyNoInteractions(f.entitlements, f.scopes, f.memberships); + } + @Test void changedIndependentTargetReadRefusesBeforeAnyScopeWrite() { Fixture f = new Fixture(300000L); @@ -481,6 +790,8 @@ private static final class Fixture { private final String token; private final AccountCanonicalPublicRealmScopeOwner owner; private Target secondTarget = target; + private List firstCollection; + private List secondCollection; private Runnable onSecondTargetRead = () -> {}; private boolean corruptReadback; private boolean corruptDigest; @@ -548,7 +859,10 @@ private Fixture(long bootstrapLifetime) { if (count == 2) onSecondTargetRead.run(); var request = new DiscoveryRequest(invocation.getArgument(0, UUID.class), NAMESPACE); - List values = List.of(count == 1 ? target : secondTarget); + List values = + count == 1 + ? (firstCollection == null ? List.of(target) : firstCollection) + : (secondCollection == null ? List.of(secondTarget) : secondCollection); return CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromDiscoveryResponse( request, CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse( @@ -757,6 +1071,10 @@ private static FreshTenantCreationEvidence source() { } private static Target target(long pointer) { + return target(TENANT, "tenant", pointer); + } + + private static Target target(UUID tenantId, String tenantSlug, long pointer) { UUID realm = UUID.randomUUID(); UUID playableNamespace = UUID.randomUUID(); UUID instance = UUID.randomUUID(); @@ -767,7 +1085,7 @@ private static Target target(long pointer) { var request = new WorldCanonicalInitialAdmissionHold.Request( NAMESPACE, - TENANT, + tenantId, "world", realm, playableNamespace, @@ -783,8 +1101,8 @@ private static Target target(long pointer) { var hold = new WorldCanonicalInitialAdmissionHold.HoldIdentity(request, holdId, holdFence); return new Target( NAMESPACE, - "tenant", - TENANT, + tenantSlug, + tenantId, "world", "World", realm, diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java index 48e957464f..895c108fda 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java @@ -21,6 +21,7 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.LongFunction; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; import net.firedevops.firemud.accountservice.dto.AccountJoinDigest.EntitlementAvailabilityV2; import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; @@ -45,6 +46,10 @@ import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.SourceCheckpoint; import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionCurrentReceipt; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecyclePolicy.Status; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ReadFence; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinOperationEvidence; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinTerminalProof; @@ -54,6 +59,7 @@ import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCurrentRecord; import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; @@ -93,8 +99,279 @@ void clearTransactionState() { TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); } + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.CsvSource({ + "false,current", "true,current", + "false,baseline", "true,baseline", + "false,generation", "true,generation", + "false,source-version", "true,source-version", + "false,provenance", "true,provenance" + }) + void alreadyActivePolicyRequiresTenantEventBoundToCurrentAuthorityAndOperation( + boolean paid, String evidence) { + Fixture fixture = new Fixture(); + fixture.arrangePendingFirstJoin(); + fixture.startWritableTransaction(); + var event = + tenantAuthorityEvent( + TENANT_UUID, + "provenance".equals(evidence) ? UUID.randomUUID() : TENANT_OPERATION_ID, + "generation".equals(evidence) ? 3L : 2L, + "source-version".equals(evidence) ? 3L : 2L, + 1L, + 1L); + when(fixture.tenantAuthorityEvents.readCurrentByTenant(TENANT_UUID)).thenReturn(event); + // Both entitlement sources agree with the event, even when its authority or provenance is + // stale. + when(fixture.entitlements.readCurrent(TENANT_UUID)) + .thenReturn(fixture.entitlementSnapshot(event)); + if ("baseline".equals(evidence)) { + when(fixture.authority.readCompositeSnapshot( + "firemud-account-service", ACCOUNT_UUID, List.of(TENANT_UUID), List.of(TENANT_UUID))) + .thenReturn(fixture.authoritySnapshot(1L, 1L, 1L, 1L)); + } + var hosting = mock(AccountHostingSubscriptionLifecycleRepository.class); + var fence = mock(ReadFence.class); + var observed = mock(StripeHostingSubscriptionObserver.ObservedSubscription.class); + var receipt = paidReceipt(event, 5L, true); + when(hosting.readCurrent(fence, observed)).thenReturn(receipt); + Runnable validate = + () -> + fixture.producer.requireCurrentCanonicalJoinPolicy( + fixture.scope, + fixture.operation(CALLER_BINDING), + false, + paid ? hosting : null, + paid ? fence : null, + paid ? observed : null); + + if ("current".equals(evidence)) { + validate.run(); + } else { + assertThatThrownBy(validate::run) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("tenant authority evidence"); + } + verifyNoInteractions(fixture.outbox); + verify(fixture.pairs, never()).commitTransition(any(), any()); + } + @Test - void appendsCanonicalEventReadbackAndFirstPairCasFromLockedOwnerEvidence() { + void restoreRequiresCanonicalScopeBeforeReadingOwnerState() { + Fixture fixture = new Fixture(); + fixture.startWritableTransaction(); + + assertThatThrownBy( + () -> + fixture.producer.publishCanonicalRestoredMembershipChange( + null, REQUEST_ID, CALLER_BINDING, fixture.absenceBaseline, null, null, null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("canonical JOIN scope is required"); + + fixture.verifyNoOwnerInteractions(); + } + + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource( + strings = {"absent", "null-id", "zero-id", "wrong-uuid", "null-provenance", "source-id"}) + void restoreRejectsContradictoryAccountIdentityBeforeLocking(String malformed) { + Fixture fixture = new Fixture(); + fixture.startWritableTransaction(); + switch (malformed) { + case "null-id" -> fixture.account.setId(null); + case "zero-id" -> fixture.account.setId(0L); + case "wrong-uuid" -> fixture.account.setAccountUuid(UUID.randomUUID()); + case "null-provenance" -> fixture.account.setAccountUuidProvenance(null); + case "source-id" -> fixture.account.setAccountUuidSourceNumericId(99L); + default -> {} + } + when(fixture.accounts.findByAccountUuid(ACCOUNT_UUID)) + .thenReturn("absent".equals(malformed) ? Optional.empty() : Optional.of(fixture.account)); + + assertThatThrownBy( + () -> + fixture.producer.publishCanonicalRestoredMembershipChange( + fixture.scope, + REQUEST_ID, + CALLER_BINDING, + fixture.absenceBaseline, + null, + null, + null)) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + "absent".equals(malformed) + ? "Canonical Account identity is absent" + : "Canonical Account owner identity is contradictory"); + + verifyNoInteractions( + fixture.joinOperations, + fixture.memberships, + fixture.roles, + fixture.pairs, + fixture.authority, + fixture.outbox, + fixture.sourceEvidence, + fixture.tenantAuthorityEvents, + fixture.entitlements); + } + + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource( + strings = { + "account-id", "membership-id", "legacy-tenant", "account-uuid", "tenant-uuid", + "provenance", "version", "unsorted", "duplicate", "missing-player" + }) + void restoreRejectsUnboundOrNoncanonicalRoleSnapshotBeforeAuthorityReads(String malformed) { + Fixture fixture = new Fixture(); + fixture.startWritableTransaction(); + fixture.membership.setMembershipVersion(4L); + fixture.membership.setMembershipAuthorityGeneration(2L); + var previous = + new PairAuthority( + ACCOUNT_UUID, + TENANT_UUID, + fixture.provenance, + true, + 3L, + 2L, + 2L, + UUID.randomUUID().toString(), + DIGEST, + true); + when(fixture.accounts.findByAccountUuid(ACCOUNT_UUID)).thenReturn(Optional.of(fixture.account)); + when(fixture.joinOperations.findCanonicalEvidenceForUpdateByRequestId(REQUEST_ID)) + .thenReturn(Optional.of(fixture.operation(CALLER_BINDING))); + when(fixture.pairs.readForUpdate(ACCOUNT_UUID, TENANT_UUID)).thenReturn(Optional.of(previous)); + when(fixture.memberships.findCanonicalMembershipForUpdate(ACCOUNT_UUID, TENANT_UUID)) + .thenReturn(Optional.of(fixture.membership)); + // Deliberately bypass the record's own construction checks to exercise the producer boundary. + var roles = + mock( + RoleSnapshot.class, + org.mockito.AdditionalAnswers.delegatesTo( + new RoleSnapshot( + 17L, + null, + 73L, + 4L, + List.of("player"), + ACCOUNT_UUID, + TENANT_UUID, + fixture.provenance))); + switch (malformed) { + case "account-id" -> when(roles.accountId()).thenReturn(18L); + case "membership-id" -> when(roles.membershipId()).thenReturn(74L); + case "legacy-tenant" -> when(roles.tenantId()).thenReturn(9L); + case "account-uuid" -> when(roles.accountUuid()).thenReturn(UUID.randomUUID()); + case "tenant-uuid" -> when(roles.tenantUuid()).thenReturn(UUID.randomUUID()); + case "provenance" -> when(roles.tenantProvenance()).thenReturn(null); + case "version" -> when(roles.snapshotVersion()).thenReturn(3L); + case "unsorted" -> when(roles.roles()).thenReturn(List.of("player", "admin")); + case "duplicate" -> when(roles.roles()).thenReturn(List.of("player", "player")); + case "missing-player" -> when(roles.roles()).thenReturn(List.of("admin")); + default -> throw new AssertionError(malformed); + } + when(fixture.roles.findForCanonicalUpdate( + ACCOUNT_UUID, TENANT_UUID, fixture.provenance, 73L, 4L)) + .thenReturn(Optional.of(roles)); + + assertThatThrownBy( + () -> + fixture.producer.publishCanonicalRestoredMembershipChange( + fixture.scope, REQUEST_ID, CALLER_BINDING, previous, null, null, null)) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + List.of("unsorted", "duplicate").contains(malformed) + ? "Canonical JOIN role snapshot is not canonical" + : "Canonical JOIN role snapshot differs from its exact membership source or lacks player role"); + verifyNoInteractions( + fixture.authority, + fixture.sourceEvidence, + fixture.tenantAuthorityEvents, + fixture.entitlements, + fixture.outbox); + verify(fixture.pairs, never()).commitTransition(any(), any()); + } + + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.CsvSource({ + "request,null", + "request,empty", + "request,blank", + "request,oversized", + "caller,null", + "caller,empty", + "caller,blank", + "caller,oversized" + }) + void restoreRequiresBoundedRequestSelectorsBeforeReadingOwnerState( + String selector, String malformed) { + Fixture fixture = new Fixture(); + fixture.startWritableTransaction(); + String invalid = + switch (malformed) { + case "null" -> null; + case "empty" -> ""; + case "blank" -> " "; + case "oversized" -> "x".repeat(129); + default -> throw new AssertionError(malformed); + }; + + assertThatThrownBy( + () -> + fixture.producer.publishCanonicalRestoredMembershipChange( + fixture.scope, + "request".equals(selector) ? invalid : REQUEST_ID, + "caller".equals(selector) ? invalid : CALLER_BINDING, + fixture.absenceBaseline, + null, + null, + null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage( + ("request".equals(selector) + ? "canonical JOIN request ID" + : "verified JOIN caller binding") + + " must contain 1 to 128 characters"); + + fixture.verifyNoOwnerInteractions(); + } + + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) + void paidRestoreRequiresOriginalFenceAndSealedResultBeforeReadingOwnerState( + boolean missingFence) { + Fixture fixture = new Fixture(); + fixture.startWritableTransaction(); + var hosting = mock(AccountHostingSubscriptionLifecycleRepository.class); + var fence = missingFence ? null : mock(ReadFence.class); + var observed = + missingFence ? mock(StripeHostingSubscriptionObserver.ObservedSubscription.class) : null; + + assertThatThrownBy( + () -> + fixture.producer.publishCanonicalRestoredMembershipChange( + fixture.scope, + REQUEST_ID, + CALLER_BINDING, + fixture.absenceBaseline, + hosting, + fence, + observed)) + .isInstanceOf(NullPointerException.class) + .hasMessage( + missingFence + ? "Original paid read fence required" + : "Original sealed SDK result required"); + + fixture.verifyNoOwnerInteractions(); + verifyNoInteractions(hosting); + } + + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) + void appendsCanonicalEventReadbackAndFirstPairCasFromLockedOwnerEvidence(boolean paid) { Fixture fixture = new Fixture(); fixture.arrangePendingFirstJoin(); DemoTenantEntitlementSnapshot currentEntitlement = @@ -145,9 +422,17 @@ void appendsCanonicalEventReadbackAndFirstPairCasFromLockedOwnerEvidence() { }); fixture.startWritableTransaction(); + var hosting = mock(AccountHostingSubscriptionLifecycleRepository.class); + var fence = mock(ReadFence.class); + var observed = mock(StripeHostingSubscriptionObserver.ObservedSubscription.class); + var currentPaidReceipt = paidReceipt(fixture.currentTenantEvent(), 5, true); + when(hosting.readCurrent(fence, observed)).thenReturn(currentPaidReceipt); Checkpoint checkpoint = - fixture.producer.publishCanonicalFirstJoinMembershipChange( - fixture.scope, REQUEST_ID, CALLER_BINDING); + paid + ? fixture.producer.publishPaidCanonicalFirstJoinMembershipChange( + fixture.scope, REQUEST_ID, CALLER_BINDING, hosting, fence, observed) + : fixture.producer.publishCanonicalFirstJoinMembershipChange( + fixture.scope, REQUEST_ID, CALLER_BINDING); MembershipEvent event = MembershipAuthorityEventV1Codec.verify( @@ -168,7 +453,13 @@ void appendsCanonicalEventReadbackAndFirstPairCasFromLockedOwnerEvidence() { new MembershipAuthorityEventV1Codec.TenantBillingCutoff( "2", "1", "account:auth-authority:v1:tenant/" + TENANT_UUID, "1"))); verify(fixture.tenantAuthorityEvents).readCurrentByTenant(TENANT_UUID); - verify(fixture.entitlements).readCurrent(TENANT_UUID); + if (paid) { + verify(hosting).readCurrent(fence, observed); + verifyNoInteractions(fixture.entitlements); + } else { + verify(fixture.entitlements).readCurrent(TENANT_UUID); + verifyNoInteractions(hosting); + } var order = inOrder(fixture.accounts, fixture.joinOperations, fixture.memberships); order.verify(fixture.accounts).findByAccountUuid(ACCOUNT_UUID); @@ -180,8 +471,9 @@ void appendsCanonicalEventReadbackAndFirstPairCasFromLockedOwnerEvidence() { verify(fixture.pairs).commitTransition(eq(fixture.absenceBaseline), any(PairTransition.class)); } - @Test - void exactPositiveReplayReturnsTheExistingCheckpointWithoutAnotherAppendOrCas() { + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) + void exactPositiveReplayReturnsTheExistingCheckpointWithoutAnotherAppendOrCas(boolean paid) { Fixture fixture = new Fixture(); fixture.arrangePendingFirstJoin(); Event event = fixture.existingEvent(); @@ -210,9 +502,19 @@ void exactPositiveReplayReturnsTheExistingCheckpointWithoutAnotherAppendOrCas() .thenThrow(new IllegalStateException("current entitlement is no longer available")); fixture.startWritableTransaction(); + var hosting = mock(AccountHostingSubscriptionLifecycleRepository.class); Checkpoint replay = - fixture.producer.publishCanonicalFirstJoinMembershipChange( - fixture.scope, REQUEST_ID, CALLER_BINDING); + paid + ? fixture.producer.publishPaidCanonicalFirstJoinMembershipChange( + fixture.scope, + REQUEST_ID, + CALLER_BINDING, + hosting, + mock(ReadFence.class), + mock(StripeHostingSubscriptionObserver.ObservedSubscription.class)) + : fixture.producer.publishCanonicalFirstJoinMembershipChange( + fixture.scope, REQUEST_ID, CALLER_BINDING); + verifyNoInteractions(hosting); assertThat(replay).isEqualTo(checkpoint); verify(fixture.outbox, never()) @@ -667,6 +969,93 @@ void eventPublicationRequiresWritableAccountTransactionBeforeAnyLookup() { fixture.tenantAuthorityEvents); } + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource( + strings = {"version", "denied", "billing", "unavailable"}) + void paidMismatchOrUnavailableSourceNeverPublishesOrFallsBack(String failure) { + Fixture fixture = new Fixture(); + fixture.arrangePendingFirstJoin(); + var hosting = mock(AccountHostingSubscriptionLifecycleRepository.class); + var fence = mock(ReadFence.class); + var observed = mock(StripeHostingSubscriptionObserver.ObservedSubscription.class); + var receipt = + paidReceipt( + fixture.currentTenantEvent(), + "version".equals(failure) ? 6 : 5, + !"denied".equals(failure)); + if ("billing".equals(failure)) { + receipt = + new AccountHostingSubscriptionCurrentReceipt( + receipt.current(), + receipt.receiptRequestId(), + receipt.subscriptionStatus(), + true, + true, + true, + true, + 5, + 9, + receipt.billingEventId(), + receipt.billingEventDigest(), + receipt.tenantAuthorityEvent(), + "active", + receipt.currentPeriodStart(), + receipt.currentPeriodEnd(), + false, + null, + null, + receipt.evaluatedAt(), + receipt.validUntil()); + } + if ("unavailable".equals(failure)) + when(hosting.readCurrent(fence, observed)) + .thenThrow(new IllegalStateException("controlled paid source unavailable")); + else when(hosting.readCurrent(fence, observed)).thenReturn(receipt); + fixture.startWritableTransaction(); + assertThatThrownBy( + () -> + fixture.producer.publishPaidCanonicalFirstJoinMembershipChange( + fixture.scope, REQUEST_ID, CALLER_BINDING, hosting, fence, observed)) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + "unavailable".equals(failure) + ? "controlled paid source unavailable" + : "Canonical paid first JOIN requires exact current public-join entitlement evidence"); + verify(hosting).readCurrent(fence, observed); + verifyNoInteractions(fixture.entitlements); + verify(fixture.outbox, never()) + .append(eq(MEMBERSHIP_STREAM), eq(REQUEST_ID), any(LongFunction.class)); + verify(fixture.pairs, never()).commitTransition(any(), any()); + } + + private static AccountHostingSubscriptionCurrentReceipt paidReceipt( + TenantAuthorityEventV1Codec.Event event, long version, boolean allowJoin) { + var current = mock(AccountSubscriptionCurrentRecord.class); + when(current.tenantId()).thenReturn(TENANT_UUID); + Instant now = Instant.parse("2026-11-02T00:00:00Z"); + return new AccountHostingSubscriptionCurrentReceipt( + current, + UUID.randomUUID(), + Status.ACTIVE, + true, + allowJoin, + true, + true, + version, + event.tenantBillingSequence(), + event.tenantBillingEventId(), + event.tenantBillingEventDigest(), + event, + "active", + now.minusSeconds(100), + now.plusSeconds(1000), + false, + null, + null, + now, + now.plusSeconds(60)); + } + private void denyLaterTenantSource(TenantAuthorityEventV1Codec.Event event) { Fixture fixture = new Fixture(); fixture.arrangePendingFirstJoin(); @@ -853,6 +1242,20 @@ private static final class Fixture { new PairAuthority( ACCOUNT_UUID, TENANT_UUID, provenance, false, 1L, 1L, 0L, null, null, false); + private void verifyNoOwnerInteractions() { + verifyNoInteractions( + accounts, + joinOperations, + memberships, + roles, + pairs, + authority, + outbox, + sourceEvidence, + tenantAuthorityEvents, + entitlements); + } + private void arrangePendingFirstJoin() { when(accounts.findByAccountUuid(ACCOUNT_UUID)).thenReturn(Optional.of(account)); when(joinOperations.findCanonicalEvidenceForUpdateByRequestId(REQUEST_ID)) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwnerTest.java index fc6bdb624c..e718012026 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwnerTest.java @@ -81,7 +81,8 @@ void returnsSortedPublicWorldsAfterCompleteStableReorderedSourceAndFinalCallerCh assertThat(worlds) .containsExactly( - new BootstrapWorldDto("alpha", "Alpha"), new BootstrapWorldDto("zulu", "Zulu")); + new BootstrapWorldDto("tenant-b", "alpha", "Alpha"), + new BootstrapWorldDto("tenant-a", "zulu", "Zulu")); verify(f.targets, times(2)).listVisiblePublicProductionAdmissionTargets(any()); verify(f.entitlements).evaluate(TENANT_A); verify(f.entitlements).evaluate(TENANT_B); @@ -101,7 +102,8 @@ void mixedPublicCreationPoliciesBothParticipateInCompleteWorldDiscovery() { .thenReturn(evaluation(TENANT_B, true, NOW.plusSeconds(30))); assertThat(f.owner.listWorlds(TOKEN)) .containsExactly( - new BootstrapWorldDto("created", "Created"), new BootstrapWorldDto("seeded", "Seeded")); + new BootstrapWorldDto("tenant-b", "created", "Created"), + new BootstrapWorldDto("tenant-a", "seeded", "Seeded")); verify(f.entitlements, times(1)).evaluate(TENANT_A); verify(f.entitlements, times(1)).evaluate(TENANT_B); } @@ -138,7 +140,7 @@ void changedCompleteTargetRefusesTheWholeList() { } @Test - void ambiguousWorldSlugAcrossTenantsRefusesWithoutReturningEitherWorld() { + void sharedWorldSlugAcrossTenantsReturnsBothQualifiedSelectors() { Fixture f = new Fixture(); Target first = target(TENANT_A, "tenant-a", "same-slug", "First", 1); Target second = target(TENANT_B, "tenant-b", "same-slug", "Second", 1); @@ -148,7 +150,10 @@ void ambiguousWorldSlugAcrossTenantsRefusesWithoutReturningEitherWorld() { when(f.entitlements.evaluate(TENANT_B)) .thenReturn(evaluation(TENANT_B, true, NOW.plusSeconds(30))); - assertCode("ADMISSION_POINTER_UNAVAILABLE", () -> f.owner.listWorlds(TOKEN)); + assertThat(f.owner.listWorlds(TOKEN)) + .containsExactly( + new BootstrapWorldDto("tenant-a", "same-slug", "First"), + new BootstrapWorldDto("tenant-b", "same-slug", "Second")); } @Test diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java index 8b9ae9da40..cd31baed7d 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java @@ -86,6 +86,10 @@ class AccountGrpcServiceTest { private static final String REALM_ID = "4c4b57d8-e3a2-48fe-9977-e7df0fdce901"; private static final String OTHER_REALM_ID = "57c58f36-c5ea-4aa8-8ef7-91a45e407f01"; private static final String PLAYABLE_STATE_NAMESPACE_ID = "c6ed6a44-c7e7-4f18-81fc-078a74e67c07"; + private static final UUID DIRECT_TENANT = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID DIRECT_INSTANCE = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final String DIRECT_SESSION = "00042"; private static final GrpcPeerIdentity GAME_SESSION_PEER = new GrpcPeerIdentity( "spiffe://firemud/ns/test/sa/game-session-service", @@ -105,12 +109,12 @@ class AccountGrpcServiceTest { private static PlayerExecutionContext validPlayerContext() { return PlayerExecutionContext.newBuilder() .setAccountId(ACCOUNT_UUID) - .setTenantId("20") + .setTenantId(DIRECT_TENANT.toString()) .setRealmId(REALM_ID) .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setPlayableStateScope("realm:30") - .setGameInstanceId("40") - .setSessionId("session-1") + .setPlayableStateScope("SHARED") + .setGameInstanceId(DIRECT_INSTANCE.toString()) + .setSessionId(DIRECT_SESSION) .setRequestId("request-1") .build(); } @@ -118,13 +122,13 @@ private static PlayerExecutionContext validPlayerContext() { private static IssueDirectTextConnectScopeRequest validScopeRequest() { return IssueDirectTextConnectScopeRequest.newBuilder() .setPlayerContext(validPlayerContext()) - .setTenantId("20") + .setTenantId(DIRECT_TENANT.toString()) .setRealmId(REALM_ID) .setWorldSlug("world") .setRealmSlug("public") .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setPlayableStateScope("realm:30") - .setGameInstanceId("40") + .setPlayableStateScope("SHARED") + .setGameInstanceId(DIRECT_INSTANCE.toString()) .setCatalogRevision(5) .setPointerVersion(8) .build(); @@ -228,29 +232,29 @@ void issueDirectTextConnectScopeAcceptsExactGameSessionPeerAndTypedTarget() { () -> service.issueDirectTextConnectScope(validScopeRequest(), observer)); assertTrue(observer.completed()); - Mockito.verify(accountService).resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID)); + Mockito.verify(accountService, Mockito.never()).resolveAccountStorageId(Mockito.any()); assertEquals("scope-1", observer.response().getConnectScopeId()); assertEquals("2026-09-24T12:00:00Z", observer.response().getConnectScopeExpiresAt()); assertEquals("2026-09-24T11:59:30Z", observer.response().getEvaluatedAt()); Mockito.verify(accountService) .issueDirectTextConnectScope( new DirectTextCallerContext( - 10L, - 20L, + UUID.fromString(ACCOUNT_UUID), + DIRECT_TENANT, UUID.fromString(REALM_ID), - PLAYABLE_STATE_NAMESPACE_ID, - "realm:30", - 40L, - "session-1", + UUID.fromString(PLAYABLE_STATE_NAMESPACE_ID), + "SHARED", + DIRECT_INSTANCE, + DIRECT_SESSION, "request-1"), new DirectTextJoinTarget( - 20L, + DIRECT_TENANT, UUID.fromString(REALM_ID), "world", "public", - PLAYABLE_STATE_NAMESPACE_ID, - "realm:30", - 40L, + UUID.fromString(PLAYABLE_STATE_NAMESPACE_ID), + "SHARED", + DIRECT_INSTANCE, 5L, 8L)); } @@ -320,8 +324,17 @@ void verifyEmailMapsMissingSourceToSafeUnavailableAndPreservesOtherExceptions() assertEquals("INVALID_ARGUMENT", invalid.response().getError().getCode()); } - @Test - void joinPublicProductionMembershipPreservesStoredFailureOutcome() { + @ParameterizedTest + @ValueSource( + strings = { + "CONNECT_SCOPE_MISMATCH", + "CONNECT_SCOPE_INVALID", + "PUBLIC_PRODUCTION_ADMISSION_DENIED", + "TENANT_BILLING_BLOCKED", + "IDEMPOTENCY_CONFLICT", + "ENTITLEMENT_UNAVAILABLE" + }) + void joinPublicProductionMembershipPreservesStoredFailureOutcome(String outcome) { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) @@ -332,7 +345,7 @@ void joinPublicProductionMembershipPreservesStoredFailureOutcome() { Mockito.any(JoinPublicProductionRequest.class))) .thenReturn( new JoinPublicProductionResult( - false, "ENTITLEMENT_UNAVAILABLE", ACCOUNT_UUID, 20L, 0L, 0L, 0L, true)); + false, outcome, ACCOUNT_UUID, DIRECT_TENANT, 0L, 0L, 0L, false, true)); AccountGrpcService service = new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); RecordingObserver observer = new RecordingObserver<>(); @@ -343,26 +356,56 @@ void joinPublicProductionMembershipPreservesStoredFailureOutcome() { assertTrue(observer.completed()); assertFalse(observer.response().getSuccess()); - assertEquals("ENTITLEMENT_UNAVAILABLE", observer.response().getOutcomeCode()); + assertEquals(outcome, observer.response().getOutcomeCode()); assertEquals(ACCOUNT_UUID, observer.response().getAccountId()); - assertEquals("20", observer.response().getTenantId()); + assertEquals(DIRECT_TENANT.toString(), observer.response().getTenantId()); assertEquals("0", observer.response().getMembershipId()); assertTrue(observer.response().getReplayed()); assertFalse(observer.response().hasError()); Mockito.verify(accountService) .joinPublicProductionFromGameSession( new DirectTextCallerContext( - 10L, - 20L, + UUID.fromString(ACCOUNT_UUID), + DIRECT_TENANT, UUID.fromString(REALM_ID), - PLAYABLE_STATE_NAMESPACE_ID, - "realm:30", - 40L, - "session-1", + UUID.fromString(PLAYABLE_STATE_NAMESPACE_ID), + "SHARED", + DIRECT_INSTANCE, + DIRECT_SESSION, "request-1"), new JoinPublicProductionRequest("scope-1", "request-1")); } + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void successfulJoinProjectsTheActualMembershipAdmissionFlag(boolean admitting) { + AccountService owner = Mockito.mock(AccountService.class); + Mockito.when(owner.joinPublicProductionFromGameSession(Mockito.any(), Mockito.any())) + .thenReturn( + new JoinPublicProductionResult( + true, + admitting ? "JOINED" : "ALREADY_ACTIVE", + ACCOUNT_UUID, + DIRECT_TENANT, + 7L, + 3L, + 2L, + admitting, + false)); + var service = + new AccountGrpcService(Mockito.mock(PingService.class), owner, null, WORKLOAD_NAMESPACE); + var observer = new RecordingObserver(); + withPeer( + GAME_SESSION_PEER, + () -> service.joinPublicProductionMembership(validJoinRequest(), observer)); + assertTrue(observer.response().getSuccess()); + assertEquals(admitting, observer.response().getGameplayAdmissionAllowed()); + assertEquals(DIRECT_TENANT.toString(), observer.response().getTenantId()); + assertEquals(3L, observer.response().getMembershipVersion()); + assertEquals(2L, observer.response().getMembershipAuthorityGeneration()); + assertFalse(observer.response().hasError()); + } + @Test void issueDirectTextConnectScopeMapsUnexpectedFailureToRetryableUnavailable() { PingService pingService = Mockito.mock(PingService.class); @@ -565,6 +608,60 @@ void directTextScopeRejectsNoncanonicalRealmIdsAtBothIngressFields(String realmI Mockito.verifyNoInteractions(accountService); } + @ParameterizedTest + @ValueSource( + strings = { + "tenantId", + "realmId", + "worldSlug", + "realmSlug", + "playableStateNamespaceId", + "playableStateScope", + "gameInstanceId" + }) + void directTextScopeRejectsMissingTargetFieldsEvenWhenCallerMatches(String field) { + AccountService owner = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(Mockito.mock(PingService.class), owner, null, WORKLOAD_NAMESPACE); + var target = validScopeRequest().toBuilder(); + var caller = validPlayerContext().toBuilder(); + switch (field) { + case "tenantId" -> { + target.clearTenantId(); + caller.clearTenantId(); + } + case "realmId" -> { + target.clearRealmId(); + caller.clearRealmId(); + } + case "worldSlug" -> target.clearWorldSlug(); + case "realmSlug" -> target.clearRealmSlug(); + case "playableStateNamespaceId" -> { + target.clearPlayableStateNamespaceId(); + caller.clearPlayableStateNamespaceId(); + } + case "playableStateScope" -> { + target.clearPlayableStateScope(); + caller.clearPlayableStateScope(); + } + case "gameInstanceId" -> { + target.clearGameInstanceId(); + caller.clearGameInstanceId(); + } + default -> throw new IllegalArgumentException("Unknown target field: " + field); + } + RecordingObserver observer = new RecordingObserver<>(); + + withPeer( + GAME_SESSION_PEER, + () -> + service.issueDirectTextConnectScope(target.setPlayerContext(caller).build(), observer)); + + assertTrue(observer.completed()); + assertEquals("INVALID_ARGUMENT", observer.response().getError().getCode()); + Mockito.verifyNoInteractions(owner); + } + @ParameterizedTest @ValueSource( strings = { @@ -646,10 +743,13 @@ void joinRejectsUuidResultThatDoesNotMatchValidatedCaller(boolean changedAccount false, "ENTITLEMENT_UNAVAILABLE", changedAccount ? OTHER_ACCOUNT_UUID : ACCOUNT_UUID, - changedAccount ? 20L : 21L, + changedAccount + ? DIRECT_TENANT + : UUID.fromString("33333333-3333-4333-8333-333333333333"), 0L, 0L, 0L, + false, true)); AccountGrpcService service = new AccountGrpcService(Mockito.mock(PingService.class), owner, null, WORKLOAD_NAMESPACE); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index ec8ae17445..ee0851233d 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.accountservice.service.impl; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -14,26 +15,26 @@ import ch.qos.logback.core.read.ListAppender; import de.mkammerer.argon2.Argon2; import de.mkammerer.argon2.Argon2Factory; +import java.time.Clock; +import java.time.Instant; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicReference; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.firedevops.firemud.account.AuthenticationErrorCodes; -import net.firedevops.firemud.accountservice.client.EntityManagementClient; -import net.firedevops.firemud.accountservice.client.GameSessionClient; +import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; import net.firedevops.firemud.accountservice.config.AccountTokenProperties; import net.firedevops.firemud.accountservice.config.MailProperties; import net.firedevops.firemud.accountservice.dto.AccountDto; import net.firedevops.firemud.accountservice.dto.AuthenticationResult; +import net.firedevops.firemud.accountservice.dto.BootstrapWorldDto; +import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; import net.firedevops.firemud.accountservice.dto.ConnectTokenRequest; -import net.firedevops.firemud.accountservice.dto.ConnectTokenResult; import net.firedevops.firemud.accountservice.dto.CreateAccountRequest; import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; -import net.firedevops.firemud.accountservice.dto.DirectTextJoinScope; import net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget; import net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest; import net.firedevops.firemud.accountservice.dto.JoinPublicProductionResult; @@ -41,7 +42,6 @@ import net.firedevops.firemud.accountservice.dto.PlayerBootstrapResult; import net.firedevops.firemud.accountservice.dto.RealmAccessGrantRequest; import net.firedevops.firemud.accountservice.dto.UpdateAccountLoginAuthModesRequest; -import net.firedevops.firemud.accountservice.dto.VerifiedJoinScope; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; @@ -51,7 +51,7 @@ import net.firedevops.firemud.accountservice.entity.EmailVerificationToken; import net.firedevops.firemud.accountservice.entity.Profile; import net.firedevops.firemud.accountservice.entity.ProfilePresenceVisibilityPolicy; -import net.firedevops.firemud.accountservice.entity.Subscription; +import net.firedevops.firemud.accountservice.entity.RetainedSubscriptionEvidence; import net.firedevops.firemud.accountservice.mapper.AccountMapper; import net.firedevops.firemud.accountservice.mapper.ProfileMapper; import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; @@ -60,36 +60,43 @@ import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionCurrentReceipt; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountRealmAccessGrantRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository.SourceKind; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; import net.firedevops.firemud.accountservice.repository.EmailVerificationTokenRepository; import net.firedevops.firemud.accountservice.repository.ExternalAccountRepository; import net.firedevops.firemud.accountservice.repository.PaymentTransactionRepository; import net.firedevops.firemud.accountservice.repository.ProfileRepository; -import net.firedevops.firemud.accountservice.repository.SubscriptionRepository; +import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; +import net.firedevops.firemud.accountservice.service.AccountCanonicalPublicRealmScopeOwner; +import net.firedevops.firemud.accountservice.service.AccountCanonicalPublicRealmScopeOwner.RealmScope; import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository; +import net.firedevops.firemud.accountservice.service.AccountPublicBootstrapEntitlementOwner; +import net.firedevops.firemud.accountservice.service.AccountPublicBootstrapWorldsOwner; import net.firedevops.firemud.accountservice.service.EmailService; import net.firedevops.firemud.accountservice.service.NotificationService; import net.firedevops.firemud.accountservice.service.exception.AccountAlreadyExistsException; import net.firedevops.firemud.accountservice.service.exception.AccountLifecycleException; import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.accountservice.service.session.AccountPlayerBootstrapCallerVerifier; import net.firedevops.firemud.accountservice.service.session.SessionService; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target; import net.firedevops.firemud.common.security.JwtAuthProperties; import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.common.security.ReloadableJwtUtil; -import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.common.security.SessionContext; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.EnumSource; -import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; import org.mapstruct.factory.Mappers; import org.mockito.Mock; @@ -98,16 +105,14 @@ import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; -import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; class AccountServiceImplTest { private static final String JWT_SECRET = "mysecretkey123456789012345678901"; private static final String REALM_ID = "4c4b57d8-e3a2-48fe-9977-e7df0fdce901"; private static final String PLAYABLE_STATE_NAMESPACE_ID = "c6ed6a44-c7e7-4f18-81fc-078a74e67c07"; - private static final String PLAYABLE_STATE_NAMESPACE_ID_TENANT_8 = - "a741a4b8-a2cb-405e-a330-8fbf3dfb841f"; @Mock private AccountRepository accountRepository; @Mock private AccountAuthorityGenerationRepository accountAuthorityGenerationRepository; @Mock private AccountAuthoritySourceEvidenceRepository accountAuthoritySourceEvidenceRepository; @@ -133,11 +138,9 @@ class AccountServiceImplTest { @Mock private MailProperties mailProperties; private final AccountTokenProperties tokenProperties = new AccountTokenProperties(); private final JwtAuthProperties jwtAuthProperties = new JwtAuthProperties(); - @Mock private GameSessionClient gameSessionClient; - @Mock private EntityManagementClient entityManagementClient; @Mock private SessionService sessionService; @Mock private PaymentTransactionRepository paymentTransactionRepository; - @Mock private SubscriptionRepository subscriptionRepository; + @Mock private RetainedSubscriptionEvidenceRepository retainedSubscriptionEvidenceRepository; @Mock private ExternalAccountRepository externalAccountRepository; @Mock private PlatformTransactionManager transactionManager; @@ -156,18 +159,6 @@ void setup() { when(transactionManager.getTransaction( org.mockito.ArgumentMatchers.any(TransactionDefinition.class))) .thenAnswer(invocation -> new SimpleTransactionStatus()); - Subscription explicitActiveEntitlement = new Subscription(); - explicitActiveEntitlement.setId(1L); - explicitActiveEntitlement.setTenantId(7L); - explicitActiveEntitlement.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)) - .thenReturn(java.util.List.of(explicitActiveEntitlement)); - Subscription explicitActiveEntitlementForSecondTenant = new Subscription(); - explicitActiveEntitlementForSecondTenant.setId(2L); - explicitActiveEntitlementForSecondTenant.setTenantId(8L); - explicitActiveEntitlementForSecondTenant.setStatus("active"); - when(subscriptionRepository.findByTenantId(8L)) - .thenReturn(java.util.List.of(explicitActiveEntitlementForSecondTenant)); AccountMapper mapper = Mappers.getMapper(AccountMapper.class); jwtUtil = org.mockito.Mockito.spy(new ReloadableJwtUtil(JWT_SECRET, 3600000L)); jwtAuthProperties.setJwtSecret(JWT_SECRET); @@ -175,51 +166,6 @@ void setup() { tokenProperties.setConnectScopeExpirationMs(120000L); tokenProperties.setConnectTokenExpirationMs(30000L); tokenProperties.setSessionExpirationMs(3600000L); - when(gameSessionClient.listGameplayWorlds()) - .thenReturn( - java.util.List.of( - net.firedevops.firemud.gamesession.v1.GameplayWorld.newBuilder() - .setWorldSlug("demo") - .setDisplayName("Demo World") - .build())); - when(gameSessionClient.listGameplayRealms("demo")) - .thenReturn( - java.util.List.of( - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("demo") - .setRealmSlug("production") - .setDisplayName("Live Realm") - .setTenantId("7") - .setGameInstanceId("44") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build())); - when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) - .thenReturn( - net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() - .setWorldSlug("demo") - .setWorldDisplayName("Demo World") - .setRealmSlug("production") - .setRealmDisplayName("Live Realm") - .setTenantId("7") - .setGameInstanceId("44") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build()); when(mailProperties.getResetUrl()).thenReturn("http://reset/%s"); when(mailProperties.getVerificationUrl()).thenReturn("http://verify/%s"); service = @@ -233,7 +179,6 @@ void setup() { accountSecurityStateOperationRepository, accountPasswordResetDraftSourceChangeRepository, accountAuditOutboxRepository, - accountConnectScopeRepository, accountJoinOperationRepository, accountEmailLoginChallengeRepository, accountRealmAccessGrantRepository, @@ -242,7 +187,7 @@ void setup() { profileRepository, profileMapper, paymentTransactionRepository, - subscriptionRepository, + retainedSubscriptionEvidenceRepository, externalAccountRepository, passwordResetTokenRepository, emailVerificationTokenRepository, @@ -251,8 +196,6 @@ void setup() { mailProperties, tokenProperties, jwtAuthProperties, - gameSessionClient, - entityManagementClient, jwtUtil, sessionService, transactionManager); @@ -265,6 +208,235 @@ private enum OrdinaryIssuance { PLAYER_BOOTSTRAP } + @Test + void bootstrapRealmsDelegatesWorldAndCredentialAndProjectsRetainedUuidScopeWithoutReminting() { + AccountCanonicalPublicRealmScopeOwner owner = + org.mockito.Mockito.mock(AccountCanonicalPublicRealmScopeOwner.class); + service.setCanonicalPublicRealmScopeOwner(owner); + UUID tenant = UUID.fromString("07aee9f3-a635-4b7f-aa66-86489320d7c3"); + UUID instance = UUID.fromString("3ddc3564-435b-479d-b14d-c91995e673cc"); + CanonicalJoinScopeV2 scope = + new CanonicalJoinScopeV2( + "already-retained-v2-signed-scope", + UUID.fromString("e9e3aa54-9712-4e01-8767-f23f3c662e64"), + tenant, + UUID.fromString(REALM_ID), + "source-tenant", + "demo", + "production", + UUID.fromString(PLAYABLE_STATE_NAMESPACE_ID), + "SHARED", + instance, + 23L, + 17L, + "2026-11-03T00:00:00Z", + "2026-11-03T00:02:00Z"); + Target target = org.mockito.Mockito.mock(Target.class); + when(target.realmDisplayName()).thenReturn("Canonical realm"); + when(target.characterCreationPolicy()).thenReturn("PRESEEDED_ONLY"); + RealmScope retained = org.mockito.Mockito.mock(RealmScope.class); + when(retained.target()).thenReturn(target); + when(retained.scope()).thenReturn(scope); + when(owner.listRealmScopes("canonical-bootstrap", "source-tenant", "demo")) + .thenReturn(List.of(retained)); + org.mockito.Mockito.clearInvocations( + accountRepository, sessionService, jwtUtil, retainedSubscriptionEvidenceRepository); + + var result = + service.listBootstrapRealms("canonical-bootstrap", "source-tenant", "demo").getFirst(); + + assertEquals(scope.worldSlug(), result.worldSlug()); + assertEquals(scope.realmSlug(), result.realmSlug()); + assertEquals(scope.realmId(), result.realmId()); + assertEquals(tenant, result.tenantId()); + assertEquals(instance, result.gameInstanceId()); + assertEquals(scope.playableStateNamespaceId(), result.playableStateNamespaceId()); + assertEquals(scope.pointerVersion(), result.pointerVersion()); + assertEquals(scope.catalogRevision(), result.catalogRevision()); + assertEquals("Canonical realm", result.displayName()); + assertEquals("PLAYABLE_STATE_SCOPE_SHARED", result.playableStateScope()); + assertEquals("SHARED", result.stateScope()); + assertEquals("PRESEEDED_ONLY", result.characterCreationPolicy()); + assertEquals(scope.evaluatedAt(), result.evaluatedAt()); + assertEquals(scope.connectScopeExpiresAt(), result.connectScopeExpiresAt()); + assertEquals(scope.connectScopeId(), result.connectScopeId()); + assertFalse(result.toString().contains(scope.connectScopeId())); + org.mockito.Mockito.verify(owner) + .listRealmScopes("canonical-bootstrap", "source-tenant", "demo"); + verifyNoInteractions( + accountRepository, sessionService, jwtUtil, retainedSubscriptionEvidenceRepository); + } + + @Test + void bootstrapRealmsWithoutCanonicalCompositionRefusesBeforeAccountOrSessionWork() { + org.mockito.Mockito.clearInvocations(accountRepository, sessionService); + + AuthenticationException failure = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapRealms("bootstrap", "source-tenant", "demo")); + + assertEquals("AUTH_UNAVAILABLE", failure.getCode()); + verifyNoInteractions(accountRepository, sessionService); + } + + @ParameterizedTest + @ValueSource( + strings = { + "CONNECT_CONTEXT_INVALID", + "AUTH_UNAVAILABLE", + "ENTITLEMENT_UNAVAILABLE", + "ADMISSION_POINTER_UNAVAILABLE" + }) + void bootstrapRealmsPreservesCanonicalSourceRefusal(String code) { + AccountCanonicalPublicRealmScopeOwner owner = + org.mockito.Mockito.mock(AccountCanonicalPublicRealmScopeOwner.class); + service.setCanonicalPublicRealmScopeOwner(owner); + AuthenticationException failure = new AuthenticationException(code, "Canonical source refusal"); + when(owner.listRealmScopes("bootstrap", "source-tenant", "demo")).thenThrow(failure); + org.mockito.Mockito.clearInvocations(accountRepository, sessionService); + + assertSame( + failure, + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapRealms("bootstrap", "source-tenant", "demo"))); + + verifyNoInteractions(accountRepository, sessionService); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void bootstrapRealmsRefusesAmbientSqlBeforeCanonicalSource(boolean synchronizationOnly) { + AccountCanonicalPublicRealmScopeOwner owner = + org.mockito.Mockito.mock(AccountCanonicalPublicRealmScopeOwner.class); + service.setCanonicalPublicRealmScopeOwner(owner); + if (synchronizationOnly) TransactionSynchronizationManager.initSynchronization(); + else TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThrows( + IllegalStateException.class, + () -> service.listBootstrapRealms("bootstrap", "source-tenant", "demo")); + verifyNoInteractions(owner); + } finally { + TransactionSynchronizationManager.clear(); + } + } + + @Test + void bootstrapRealmsKeepsPlayerContextForTheComposedOwnersWorkloadGuard() { + AccountCanonicalPublicRealmScopeOwner owner = + org.mockito.Mockito.mock(AccountCanonicalPublicRealmScopeOwner.class); + service.setCanonicalPublicRealmScopeOwner(owner); + SessionContext.setContext("e9e3aa54-9712-4e01-8767-f23f3c662e64", List.of(), Map.of()); + when(owner.listRealmScopes("bootstrap", "source-tenant", "demo")) + .thenAnswer( + invocation -> { + assertTrue(SessionContext.hasAuthenticatedCallerContext()); + throw new IllegalStateException("Canonical source requires workload-only context"); + }); + try { + assertThrows( + IllegalStateException.class, + () -> service.listBootstrapRealms("bootstrap", "source-tenant", "demo")); + assertTrue(SessionContext.hasAuthenticatedCallerContext()); + } finally { + SessionContext.clear(); + } + } + + @Test + void bootstrapWorldsDelegatesExactCredentialAndCompleteResultToCanonicalOwner() { + AccountPublicBootstrapWorldsOwner owner = + org.mockito.Mockito.mock(AccountPublicBootstrapWorldsOwner.class); + service.setPublicBootstrapWorldsOwner(owner); + List worlds = + List.of( + new BootstrapWorldDto("tenant-alpha", "alpha", "Alpha"), + new BootstrapWorldDto("tenant-zulu", "zulu", "Zulu")); + when(owner.listWorlds("canonical-bootstrap")).thenReturn(worlds); + org.mockito.Mockito.clearInvocations(accountRepository, sessionService); + + assertSame(worlds, service.listBootstrapWorlds("canonical-bootstrap")); + + org.mockito.Mockito.verify(owner).listWorlds("canonical-bootstrap"); + verifyNoInteractions(accountRepository, sessionService); + } + + @Test + void bootstrapWorldsWithoutCanonicalCompositionRefusesBeforeAccountOrSessionWork() { + org.mockito.Mockito.clearInvocations(accountRepository, sessionService); + + AuthenticationException failure = + assertThrows(AuthenticationException.class, () -> service.listBootstrapWorlds("bootstrap")); + + assertEquals("AUTH_UNAVAILABLE", failure.getCode()); + verifyNoInteractions(accountRepository, sessionService); + } + + @ParameterizedTest + @ValueSource( + strings = {"AUTH_UNAVAILABLE", "ENTITLEMENT_UNAVAILABLE", "ADMISSION_POINTER_UNAVAILABLE"}) + void bootstrapWorldsPreservesCanonicalSourceFailure(String code) { + AccountPublicBootstrapWorldsOwner owner = + org.mockito.Mockito.mock(AccountPublicBootstrapWorldsOwner.class); + service.setPublicBootstrapWorldsOwner(owner); + AuthenticationException unavailable = new AuthenticationException(code, "Source unavailable"); + when(owner.listWorlds("bootstrap")).thenThrow(unavailable); + org.mockito.Mockito.clearInvocations(accountRepository, sessionService); + + assertSame( + unavailable, + assertThrows( + AuthenticationException.class, () -> service.listBootstrapWorlds("bootstrap"))); + + verifyNoInteractions(accountRepository, sessionService); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void bootstrapWorldsRefusesAmbientTransactionOrSynchronizationBeforeCanonicalRead( + boolean synchronizationOnly) { + AccountPublicBootstrapWorldsOwner owner = + org.mockito.Mockito.mock(AccountPublicBootstrapWorldsOwner.class); + service.setPublicBootstrapWorldsOwner(owner); + if (synchronizationOnly) { + TransactionSynchronizationManager.initSynchronization(); + } else { + TransactionSynchronizationManager.setActualTransactionActive(true); + } + try { + IllegalStateException failure = + assertThrows(IllegalStateException.class, () -> service.listBootstrapWorlds("bootstrap")); + + assertTrue(failure.getMessage().contains("ambient SQL")); + verifyNoInteractions(owner); + } finally { + TransactionSynchronizationManager.clear(); + } + } + + @Test + void bootstrapWorldsRetainsPlayerContextAndCanonicalWorkloadGuard() { + var callerVerifier = org.mockito.Mockito.mock(AccountPlayerBootstrapCallerVerifier.class); + var targets = org.mockito.Mockito.mock(CanonicalGameplayAdmissionDecisionReadClient.class); + var entitlements = org.mockito.Mockito.mock(AccountPublicBootstrapEntitlementOwner.class); + service.setPublicBootstrapWorldsOwner( + new AccountPublicBootstrapWorldsOwner( + callerVerifier, targets, entitlements, Clock.systemUTC())); + SessionContext.setContext("account", List.of(), Map.of()); + try { + IllegalStateException failure = + assertThrows(IllegalStateException.class, () -> service.listBootstrapWorlds("bootstrap")); + + assertTrue(failure.getMessage().contains("workload-only")); + assertTrue(SessionContext.hasAuthenticatedCallerContext()); + verifyNoInteractions(callerVerifier, targets, entitlements); + } finally { + SessionContext.clear(); + } + } + private enum IdentityFailure { MISSING_UUID, NIL_UUID, @@ -685,5217 +857,3013 @@ void createAccountMapsSpringDataIntegrityConflict() { assertEquals("Account already exists", exception.getMessage()); } + /** + * These fixtures prove facade ordering/projection; physical owner atomicity is integration proof. + */ + @ParameterizedTest + @CsvSource({"JOINED,2,1", "ALREADY_ACTIVE,7,3", "JOINED,8,3"}) + void canonicalJoinProjectsFirstActiveAndRestoredOwnerSnapshots( + String outcome, long version, long generation) { + var f = canonicalJoinFixture(); + f.terminal(outcome, version, generation); + var result = f.browserJoin(); + assertTrue(result.success()); + assertEquals(outcome, result.outcomeCode()); + assertEquals(f.scope.accountId().toString(), result.accountId()); + assertEquals(f.scope.tenantId(), result.tenantId()); + assertEquals(701L, result.membershipId()); + assertEquals(version, result.membershipVersion()); + assertEquals(generation, result.membershipAuthorityGeneration()); + assertFalse(result.replayed()); + assertTrue(result.gameplayAdmissionAllowed()); + org.mockito.Mockito.verify(f.demos).revalidate(f.demo); + org.mockito.Mockito.verify(f.targets, org.mockito.Mockito.times(2)) + .readPublishedRealmAdmissionOwner(org.mockito.ArgumentMatchers.any()); + org.mockito.Mockito.verify(f.terminal) + .commitCanonicalJoin(f.scope, f.requestId, f.binding, null, null, null); + verifyNoInteractions(f.hosting, f.observer, accountAuditOutboxRepository); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) + .save(org.mockito.ArgumentMatchers.any()); + } + @Test - void joinPublicProductionRetainsReceiptAfterProjectionFailureAndReplaysWithoutDuplicateEffects() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(sessionService.isAccountSessionActive( - org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) - .thenReturn(true); - AtomicReference joinedMembership = new AtomicReference<>(); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenAnswer(invocation -> Optional.ofNullable(joinedMembership.get())); - when(accountTenantMembershipRepository.save(org.mockito.ArgumentMatchers.any())) - .thenAnswer( - invocation -> { - AccountTenantMembership membership = invocation.getArgument(0); - membership.setId(701L); - joinedMembership.set(membership); - return membership; - }); - Subscription active = new Subscription(); - active.setId(22L); - active.setTenantId(7L); - active.setStatus("active"); - when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenReturn(java.util.List.of(active)); + void canonicalCommittedRetryRevalidatesCurrentPolicyBeforeReturningRetainedTerminalProof() { + var f = canonicalJoinFixture(); + when(f.pending.status()).thenReturn("COMMITTED"); + f.terminal("JOINED", 2L, 1L); + var result = f.browserJoin(); + assertTrue(result.success()); + assertTrue(result.replayed()); + org.mockito.Mockito.verify(accountJoinOperationRepository) + .bindCanonicalPolicyEvidence(f.requestId, f.scope, f.binding, true, 1L); + org.mockito.Mockito.verify(f.sources, org.mockito.Mockito.times(2)) + .readCurrentSourceSelection(f.scope.tenantId()); + org.mockito.Mockito.verify(f.demos).revalidate(f.demo); + verifyNoInteractions(f.hosting, f.observer); + org.mockito.Mockito.verify(f.terminal) + .commitCanonicalJoin(f.scope, f.requestId, f.binding, null, null, null); + } - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - AtomicReference retainedScope = new AtomicReference<>(); - AtomicReference retainedOperation = - new AtomicReference<>(); - retainJoinEvidence(retainedScope, retainedOperation); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - String requestId = "j".repeat(128); - assertEquals(128, requestId.length()); - JoinPublicProductionRequest request = - new JoinPublicProductionRequest(connectScopeId, requestId); + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void canonicalConcurrentCommitUsesLockedReplayStateAndStillChecksCurrentPolicy(boolean gameplay) { + var f = canonicalJoinFixture(); + when(f.committed.status()).thenReturn("COMMITTED"); + when(accountJoinOperationRepository.findCanonicalEvidenceForUpdateByRequestId(f.requestId)) + .thenReturn(Optional.of(f.pending), Optional.of(f.committed)); + when(accountJoinOperationRepository.bindCanonicalPolicyEvidence( + f.requestId, f.scope, f.binding, true, 1L)) + .thenReturn(f.committed); + when(f.demo.gameplayAvailable()).thenReturn(gameplay); + + var result = f.browserJoin(); + + assertTrue(result.replayed()); + assertTrue(result.success()); + assertEquals("JOINED", result.outcomeCode()); + assertEquals(gameplay, result.gameplayAdmissionAllowed()); + org.mockito.Mockito.verify(f.demos).revalidate(f.demo); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) + .finishCanonicalFailure( + org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.anyString()); + org.mockito.Mockito.verify(f.terminal) + .commitCanonicalJoin(f.scope, f.requestId, f.binding, null, null, null); + } - org.mockito.Mockito.doAnswer( - invocation -> { - when(accountRepository.findByAccountUuid(account.getAccountUuid())) - .thenReturn(Optional.empty()); - return null; - }) - .when(transactionManager) - .commit(org.mockito.ArgumentMatchers.any()); - AuthenticationException firstProjectionFailure = - assertThrows( - AuthenticationException.class, - () -> service.joinPublicProduction(bootstrap.bootstrapToken(), request)); - assertEquals("AUTH_UNAVAILABLE", firstProjectionFailure.getCode()); - assertEquals("COMMITTED", retainedOperation.get().status()); - org.mockito.Mockito.verify(transactionManager, org.mockito.Mockito.never()) - .rollback(org.mockito.ArgumentMatchers.any()); - org.mockito.Mockito.doNothing() - .when(transactionManager) - .commit(org.mockito.ArgumentMatchers.any()); - when(accountRepository.findByAccountUuid(account.getAccountUuid())) - .thenReturn(Optional.of(account)); - JoinPublicProductionResult recovered = - service.joinPublicProduction(bootstrap.bootstrapToken(), request); - assertTrue(recovered.replayed()); - JoinPublicProductionResult first = recovered; - assertEquals(account.getAccountUuid().toString(), recovered.accountId()); - var committedOperation = retainedOperation.get(); - org.mockito.Mockito.clearInvocations(transactionManager, gameSessionClient); - JoinPublicProductionResult retried = - service.joinPublicProduction(bootstrap.bootstrapToken(), request); - - var normalReplayOrder = org.mockito.Mockito.inOrder(transactionManager, gameSessionClient); - normalReplayOrder - .verify(transactionManager) - .getTransaction(org.mockito.ArgumentMatchers.any(TransactionDefinition.class)); - normalReplayOrder.verify(transactionManager).commit(org.mockito.ArgumentMatchers.any()); - normalReplayOrder.verify(gameSessionClient).listGameplayRealms("demo"); + @ParameterizedTest + @ValueSource(strings = {"demo", "paid"}) + void canonicalCommittedReplayPreservesReceiptWhenCurrentGameplayIsUnavailable(String sourceKind) { + var f = canonicalJoinFixture(); + when(f.pending.status()).thenReturn("COMMITTED"); + f.joined.set(true); + f.currentMembership.setMembershipVersion(9L); + f.currentMembership.setMembershipAuthorityGeneration(4L); + f.currentMembership.setGameplayAdmissionAllowed(true); + var originalProof = f.committed.terminalProof(); + AccountHostingSubscriptionLifecycleRepository.ReadFence paidFence = null; + + if ("paid".equals(sourceKind)) { + when(f.source.kind()).thenReturn(SourceKind.PAID_HOSTING); + paidFence = + org.mockito.Mockito.mock(AccountHostingSubscriptionLifecycleRepository.ReadFence.class); + var receipt = org.mockito.Mockito.mock(AccountHostingSubscriptionCurrentReceipt.class); + when(f.hosting.prepareCurrentRead(f.scope.tenantId())).thenReturn(paidFence); + when(f.hosting.readCurrent( + org.mockito.ArgumentMatchers.eq(paidFence), org.mockito.ArgumentMatchers.isNull())) + .thenReturn(receipt); + when(receipt.gameplayAvailable()).thenReturn(false); + when(receipt.allowPublicJoin()).thenReturn(true); + when(receipt.entitlementVersion()).thenReturn(1L); + when(f.terminal.commitCanonicalJoin( + org.mockito.ArgumentMatchers.eq(f.scope), + org.mockito.ArgumentMatchers.eq(f.requestId), + org.mockito.ArgumentMatchers.eq(f.binding), + org.mockito.ArgumentMatchers.eq(f.hosting), + org.mockito.ArgumentMatchers.eq(paidFence), + org.mockito.ArgumentMatchers.isNull())) + .thenReturn(f.committed); + } else { + when(f.demo.gameplayAvailable()).thenReturn(false); + } - org.mockito.Mockito.doThrow( - new DataAccessResourceFailureException("terminal operation lock read failed")) - .when(accountJoinOperationRepository) - .findForUpdate(requestId); - org.mockito.Mockito.clearInvocations(transactionManager, gameSessionClient); - JoinPublicProductionResult readbackReplay = - service.joinPublicProduction(bootstrap.bootstrapToken(), request); - - var readbackReplayOrder = org.mockito.Mockito.inOrder(transactionManager, gameSessionClient); - readbackReplayOrder - .verify(transactionManager) - .getTransaction(org.mockito.ArgumentMatchers.any(TransactionDefinition.class)); - readbackReplayOrder.verify(transactionManager).rollback(org.mockito.ArgumentMatchers.any()); - readbackReplayOrder.verify(gameSessionClient).listGameplayRealms("demo"); + var result = f.browserJoin(); - org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.times(1)) - .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); - org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(4)) - .findByTenantIdForUpdate(7L); - org.mockito.Mockito.clearInvocations( - sessionService, - accountTenantMembershipRepository, - gameSessionClient, - subscriptionRepository); - AuthenticationException connectTokenUnavailable = - assertThrows( - AuthenticationException.class, - () -> - service.issueConnectToken( - bootstrap.bootstrapToken(), - new ConnectTokenRequest(connectScopeId, "first-play-after-join"))); - - assertTrue(first.success()); - assertEquals(account.getAccountUuid().toString(), first.accountId()); - assertEquals("JOINED", first.outcomeCode()); - assertEquals(701L, first.membershipId()); - assertEquals(1L, first.membershipVersion()); - assertTrue(retried.success()); - assertTrue(retried.replayed()); - assertTrue(readbackReplay.success()); - assertTrue(readbackReplay.replayed()); - assertEquals(committedOperation, retainedOperation.get()); - assertEquals("AUTH_UNAVAILABLE", connectTokenUnavailable.getCode()); - assertNoLegacyConnectTokenEffects(); - assertEquals(REALM_ID, retainedScope.get().realmId().toString()); + assertTrue(result.success()); + assertTrue(result.replayed()); + assertEquals("JOINED", result.outcomeCode()); + assertEquals("JOINED", f.committed.outcome()); + assertSame(originalProof, f.committed.terminalProof()); + assertEquals(originalProof.membershipId(), result.membershipId()); + assertEquals(originalProof.membershipVersion(), result.membershipVersion()); assertEquals( - first, - new JoinPublicProductionResult( - retried.success(), - retried.outcomeCode(), - retried.accountId(), - retried.tenantId(), - retried.membershipId(), - retried.membershipVersion(), - retried.membershipAuthorityGeneration(), - true)); - org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.times(1)) - .bindPolicyEvidence( - org.mockito.ArgumentMatchers.eq(requestId), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.eq(1L), - org.mockito.ArgumentMatchers.eq(true)); - org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.times(1)) - .finish( - org.mockito.ArgumentMatchers.eq(requestId), - org.mockito.ArgumentMatchers.eq("COMMITTED"), - org.mockito.ArgumentMatchers.eq("JOINED"), - org.mockito.ArgumentMatchers.eq(701L), - org.mockito.ArgumentMatchers.eq(1L), - org.mockito.ArgumentMatchers.eq(1L)); + originalProof.membershipAuthorityGeneration(), result.membershipAuthorityGeneration()); + assertFalse(result.gameplayAdmissionAllowed()); + assertTrue(f.currentMembership.isGameplayAdmissionAllowed()); + assertEquals(701L, f.currentMembership.getId()); + assertEquals("ACTIVE", f.currentMembership.getLifecycleState()); + assertEquals(9L, f.currentMembership.getMembershipVersion()); + assertEquals(4L, f.currentMembership.getMembershipAuthorityGeneration()); + + org.mockito.Mockito.verify(f.terminal) + .commitCanonicalJoin( + f.scope, + f.requestId, + f.binding, + "paid".equals(sourceKind) ? f.hosting : null, + paidFence, + null); + if ("paid".equals(sourceKind)) { + org.mockito.Mockito.verify(f.hosting).prepareCurrentRead(f.scope.tenantId()); + org.mockito.Mockito.verify(f.observer).observe(org.mockito.ArgumentMatchers.isNull()); + org.mockito.Mockito.verify(f.hosting) + .readCurrent(org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.isNull()); + verifyNoInteractions(f.demos); + } else { + org.mockito.Mockito.verify(f.demos).revalidate(f.demo); + verifyNoInteractions(f.hosting, f.observer); + } + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) + .finishCanonicalFailure( + org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.anyString()); org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) - .recordAttemptFailure( + .recordCanonicalAttemptFailure( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.anyString()); - org.mockito.Mockito.verify(accountAuditOutboxRepository, org.mockito.Mockito.times(1)) - .append( - org.mockito.ArgumentMatchers.any(java.util.UUID.class), - org.mockito.ArgumentMatchers.eq("tenant"), - org.mockito.ArgumentMatchers.eq(7L), - org.mockito.ArgumentMatchers.eq("ACCOUNT_JOINED_PUBLIC_PRODUCTION"), - org.mockito.ArgumentMatchers.contains(requestId)); - assertEquals("COMMITTED", retainedOperation.get().status()); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) + .save(org.mockito.ArgumentMatchers.any()); + verifyNoInteractions(accountAuditOutboxRepository); + } - AuthenticationException changedDigest = - assertThrows( - AuthenticationException.class, - () -> - service.joinPublicProduction( - bootstrap.bootstrapToken(), - new JoinPublicProductionRequest("different-scope", requestId))); - assertEquals("IDEMPOTENCY_CONFLICT", changedDigest.getCode()); + @Test + void canonicalCommittedAlreadyActiveRetryPreservesReceiptAfterMembershipBecomesInactive() { + var f = canonicalJoinFixture(); + f.terminal("ALREADY_ACTIVE", 7L, 3L); + when(f.pending.status()).thenReturn("COMMITTED"); + when(f.demo.allowPublicJoin()).thenReturn(false); + f.currentMembership.setLifecycleState("INACTIVE"); + f.currentMembership.setGameplayAdmissionAllowed(false); + f.currentMembership.setMembershipVersion(8L); + f.currentMembership.setMembershipAuthorityGeneration(4L); + f.joined.set(true); - when(accountRepository.findByAccountUuid(account.getAccountUuid())) - .thenReturn(Optional.of(account), Optional.empty()); - AuthenticationException projectionFailure = - assertThrows( - AuthenticationException.class, - () -> service.joinPublicProduction(bootstrap.bootstrapToken(), request)); - assertEquals("AUTH_UNAVAILABLE", projectionFailure.getCode()); - assertEquals(committedOperation, retainedOperation.get()); - when(accountRepository.findByAccountUuid(account.getAccountUuid())) - .thenReturn(Optional.of(account)); - assertEquals( - account.getAccountUuid().toString(), - service.joinPublicProduction(bootstrap.bootstrapToken(), request).accountId()); + var result = f.browserJoin(); + + assertTrue(result.success()); + assertTrue(result.replayed()); + assertEquals("ALREADY_ACTIVE", result.outcomeCode()); + assertEquals(7L, result.membershipVersion()); + assertEquals(3L, result.membershipAuthorityGeneration()); + assertFalse(result.gameplayAdmissionAllowed()); + org.mockito.Mockito.verify(accountJoinOperationRepository) + .bindCanonicalPolicyEvidence(f.requestId, f.scope, f.binding, false, 1L); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) + .finishCanonicalFailure( + org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.anyString()); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) + .save(org.mockito.ArgumentMatchers.any()); + org.mockito.Mockito.verify(f.terminal) + .commitCanonicalJoin(f.scope, f.requestId, f.binding, null, null, null); + verifyNoInteractions(accountAuditOutboxRepository); } @Test - void joinPublicProductionRejectsRequestIdLongerThan128BeforeIntentLookupOrMutation() { - Account account = directTextAccount(); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - String requestId = "j".repeat(129); - DirectTextCallerContext baseCaller = directTextCaller(); - DirectTextCallerContext caller = - new DirectTextCallerContext( - baseCaller.accountId(), - baseCaller.tenantId(), - baseCaller.realmId(), - baseCaller.playableStateNamespaceId(), - baseCaller.playableStateScope(), - baseCaller.gameInstanceId(), - baseCaller.sessionId(), - requestId); + void canonicalCommittedRetryCannotUseUnavailableCurrentEntitlementOrRewriteTerminalBytes() { + var f = canonicalJoinFixture(); + when(f.pending.status()).thenReturn("COMMITTED"); + when(f.demos.readCurrent(f.scope.tenantId())) + .thenThrow(new DataAccessResourceFailureException("controlled current source outage")); + assertEquals( + "ENTITLEMENT_UNAVAILABLE", + assertThrows(AuthenticationException.class, f::browserJoin).getCode()); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) + .recordCanonicalAttemptFailure( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString()); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) + .finishCanonicalFailure( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString()); + verifyNoInteractions(f.terminal); + } - AuthenticationException exception = + @Test + void canonicalJoinWithoutConsumerCompositionRefusesBeforeAccountIntentOrAuthorityWork() { + assertEquals( + "AUTH_UNAVAILABLE", assertThrows( - AuthenticationException.class, - () -> - service.joinPublicProductionFromGameSession( - caller, new JoinPublicProductionRequest("retained-scope", requestId))); - - assertEquals("INVALID_ARGUMENT", exception.getCode()); + AuthenticationException.class, + () -> + service.joinPublicProduction( + "bootstrap", new JoinPublicProductionRequest("scope", "request"))) + .getCode()); verifyNoInteractions( + accountRepository, accountJoinOperationRepository, accountTenantMembershipRepository, - accountAuditOutboxRepository); + retainedSubscriptionEvidenceRepository); } @ParameterizedTest - @CsvSource({ - "SECURITY_LOCKED, AUTH_ACCOUNT_LOCKED", - "DEACTIVATED_PENDING_DELETE, AUTH_INVALID_CREDENTIALS" - }) - void joinPublicProductionRejectsStillActiveBootstrapForIneligibleLifecycleState( - AccountLifecycleState lifecycleState, String expectedCode) { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(sessionService.isAccountSessionActive( - org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) - .thenReturn(true); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - account.setLifecycleState(lifecycleState); - - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> - service.joinPublicProduction( - bootstrap.bootstrapToken(), - new JoinPublicProductionRequest(connectScopeId, "join-ineligible-1"))); + @ValueSource( + strings = { + "PUBLIC_PRODUCTION_ADMISSION_DENIED", + "CONNECT_SCOPE_INVALID", + "REALM_UNAVAILABLE" + }) + void canonicalFailedRetryPreservesTheOriginalOutcomeWithoutMembershipOrPolicyMutation( + String outcome) { + var f = canonicalJoinFixture(); + when(f.pending.status()).thenReturn("FAILED"); + when(f.pending.outcome()).thenReturn(outcome); + when(accountJoinOperationRepository.finishCanonicalFailure( + f.requestId, f.scope, f.binding, outcome)) + .thenReturn(f.pending); + org.mockito.Mockito.doThrow(new IllegalStateException("Game Session unavailable")) + .when(f.targets) + .resolvePublishedRealmAdmissionTarget(org.mockito.ArgumentMatchers.any()); + var result = f.browserJoin(); + assertFalse(result.success()); + assertTrue(result.replayed()); + assertEquals(outcome, result.outcomeCode()); + verifyNoInteractions(f.targets, f.sources, f.demos, f.hosting, f.observer, f.terminal); + org.mockito.Mockito.verify(accountJoinOperationRepository) + .finishCanonicalFailure(f.requestId, f.scope, f.binding, outcome); + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.times(2)) + .isAccountSessionActive(f.account.getId(), f.bootstrap); + } - assertEquals(expectedCode, exception.getCode()); - verifyNoInteractions( - accountJoinOperationRepository, - accountTenantMembershipRepository, - accountAuditOutboxRepository); + @Test + void canonicalFailedRetryStillChecksLockedRequestIdentity() { + var f = canonicalJoinFixture(); + when(f.pending.status()).thenReturn("FAILED"); + when(f.pending.outcome()).thenReturn("PUBLIC_PRODUCTION_ADMISSION_DENIED"); + when(accountJoinOperationRepository.finishCanonicalFailure( + f.requestId, f.scope, f.binding, "PUBLIC_PRODUCTION_ADMISSION_DENIED")) + .thenThrow( + new AccountJoinOperationRepository.CanonicalJoinOperationConflictException( + "Controlled retained identity conflict")); + assertEquals( + "IDEMPOTENCY_CONFLICT", + assertThrows(AuthenticationException.class, f::browserJoin).getCode()); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.times(2)) + .findCanonicalEvidenceForUpdateByRequestId(f.requestId); + verifyNoInteractions(f.targets, f.sources, f.demos, f.hosting, f.observer, f.terminal); } @Test - void closedPublicJoinRetainsFailureAndCannotCreateMembershipOrAudit() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(sessionService.isAccountSessionActive( - org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) - .thenReturn(true); - Subscription grace = new Subscription(); - grace.setId(22L); - grace.setTenantId(7L); - grace.setStatus("grace"); - when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenReturn(java.util.List.of(grace)); + void canonicalFailedRetryStillRechecksCallerBeforeLockedReplay() { + var f = canonicalJoinFixture(); + when(f.pending.status()).thenReturn("FAILED"); + when(sessionService.isAccountSessionActive(f.account.getId(), f.bootstrap)) + .thenReturn(true, false); + assertEquals( + "CONNECT_CONTEXT_INVALID", + assertThrows(AuthenticationException.class, f::browserJoin).getCode()); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) + .finishCanonicalFailure( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString()); + verifyNoInteractions(f.targets, f.sources, f.demos, f.hosting, f.observer, f.terminal); + } - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - AtomicReference retainedScope = new AtomicReference<>(); - AtomicReference retainedOperation = - new AtomicReference<>(); - retainJoinEvidence(retainedScope, retainedOperation); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(grace)); - JoinPublicProductionRequest request = - new JoinPublicProductionRequest(connectScopeId, "join-closed-1"); - - JoinPublicProductionResult denied = - service.joinPublicProduction(bootstrap.bootstrapToken(), request); - JoinPublicProductionResult retry = - service.joinPublicProduction(bootstrap.bootstrapToken(), request); - - assertFalse(denied.success()); - assertEquals("PUBLIC_PRODUCTION_ADMISSION_DENIED", denied.outcomeCode()); - assertFalse(retry.success()); - assertTrue(retry.replayed()); - assertEquals(denied.outcomeCode(), retry.outcomeCode()); - assertEquals("FAILED", retainedOperation.get().status()); - var storedDeniedOperation = retainedOperation.get(); - when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenReturn(java.util.List.of()); - JoinPublicProductionResult unavailableAuthorityReplay = - service.joinPublicProduction(bootstrap.bootstrapToken(), request); - assertFalse(unavailableAuthorityReplay.success()); - assertFalse(unavailableAuthorityReplay.replayed()); - assertEquals("ENTITLEMENT_UNAVAILABLE", unavailableAuthorityReplay.outcomeCode()); - assertEquals(storedDeniedOperation, retainedOperation.get()); + @ParameterizedTest + @CsvSource({ + "true,false,PUBLIC_PRODUCTION_ADMISSION_DENIED", + "false,false,TENANT_BILLING_BLOCKED" + }) + void canonicalJoinRetainsAuthoritativePolicyDenialsWithoutCallingTransitionOwner( + boolean gameplay, boolean open, String code) { + var f = canonicalJoinFixture(); + when(f.demo.gameplayAvailable()).thenReturn(gameplay); + when(f.demo.allowPublicJoin()).thenReturn(open); + var result = f.browserJoin(); + assertFalse(result.success()); + assertEquals(code, result.outcomeCode()); + org.mockito.Mockito.verify(accountJoinOperationRepository) + .finishCanonicalFailure(f.requestId, f.scope, f.binding, code); + verifyNoInteractions(f.terminal); + } + + @Test + void canonicalActiveMemberCanReturnCurrentSnapshotWithClosedEnrollment() { + var f = canonicalJoinFixture(); + when(f.demo.allowPublicJoin()).thenReturn(false); + AccountTenantMembership current = f.currentMembership; + current.setLifecycleState("ACTIVE"); + current.setGameplayAdmissionAllowed(true); + current.setMembershipVersion(7L); + current.setMembershipAuthorityGeneration(3L); + org.mockito.Mockito.doReturn(Optional.of(current)) + .when(accountTenantMembershipRepository) + .findFreshMembershipForUpdate(f.scope.accountId(), f.scope.tenantId()); + f.terminal("ALREADY_ACTIVE", 7L, 3L); + var result = f.browserJoin(); + assertTrue(result.success()); + assertEquals("ALREADY_ACTIVE", result.outcomeCode()); + assertEquals(7L, result.membershipVersion()); + assertEquals(3L, result.membershipAuthorityGeneration()); + } + + @Test + void canonicalActiveControlOnlyMemberReturnsExactSnapshotWithoutGameplayOrRoleUpgrade() { + var f = canonicalJoinFixture(); + f.terminal("ALREADY_ACTIVE", 7L, 3L); + f.currentMembership.setGameplayAdmissionAllowed(false); + f.joined.set(true); + when(f.demo.allowPublicJoin()).thenReturn(false); + var result = f.browserJoin(); + assertTrue(result.success()); + assertEquals("ALREADY_ACTIVE", result.outcomeCode()); + assertEquals(7L, result.membershipVersion()); + assertEquals(3L, result.membershipAuthorityGeneration()); + assertFalse(result.gameplayAdmissionAllowed()); org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) - .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); - org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); - org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(2)) - .findByTenantIdForUpdate(7L); + .save(org.mockito.ArgumentMatchers.any()); + verifyNoInteractions(accountAuditOutboxRepository); } - @Test - void committedJoinRetryRejectsChangedPolicyWithoutMutatingStoredOutcomeOrMembership() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(sessionService.isAccountSessionActive( - org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) - .thenReturn(true); - AtomicReference joinedMembership = new AtomicReference<>(); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenAnswer(invocation -> Optional.ofNullable(joinedMembership.get())); - when(accountTenantMembershipRepository.save(org.mockito.ArgumentMatchers.any())) - .thenAnswer( - invocation -> { - AccountTenantMembership membership = invocation.getArgument(0); - membership.setId(701L); - joinedMembership.set(membership); - return membership; - }); - Subscription originalPolicy = new Subscription(); - originalPolicy.setId(22L); - originalPolicy.setTenantId(7L); - originalPolicy.setStatus("active"); - originalPolicy.setEntitlementVersion(5L); - Subscription changedPolicy = new Subscription(); - changedPolicy.setId(22L); - changedPolicy.setTenantId(7L); - changedPolicy.setStatus("active"); - changedPolicy.setEntitlementVersion(6L); - when(subscriptionRepository.findByTenantIdForUpdate(7L)) - .thenReturn(java.util.List.of(originalPolicy), java.util.List.of(changedPolicy)); + @ParameterizedTest + @ValueSource(strings = {"source", "demo", "final-demo", "member", "terminal"}) + void canonicalJoinOutageKeepsTheIntentRetryableAndRecoversTheSameRequest(String stage) { + var f = canonicalJoinFixture(); + RuntimeException unavailable = + new DataAccessResourceFailureException("controlled owner outage"); + switch (stage) { + case "source" -> + when(f.sources.readCurrentSourceSelection(f.scope.tenantId())) + .thenThrow(unavailable) + .thenReturn(f.source); + case "demo" -> + when(f.demos.readCurrent(f.scope.tenantId())).thenThrow(unavailable).thenReturn(f.demo); + case "final-demo" -> + when(f.demos.revalidate(f.demo)).thenThrow(unavailable).thenReturn(f.demo); + case "member" -> + org.mockito.Mockito.doThrow(unavailable) + .doAnswer( + invocation -> + f.joined.get() ? Optional.of(f.currentMembership) : Optional.empty()) + .when(accountTenantMembershipRepository) + .findFreshMembershipForUpdate(f.scope.accountId(), f.scope.tenantId()); + case "terminal" -> + org.mockito.Mockito.doThrow(unavailable) + .doAnswer( + invocation -> { + f.joined.set(true); + return f.committed; + }) + .when(f.terminal) + .commitCanonicalJoin(f.scope, f.requestId, f.binding, null, null, null); + default -> throw new AssertionError(stage); + } + assertEquals( + "ENTITLEMENT_UNAVAILABLE", + assertThrows(AuthenticationException.class, f::browserJoin).getCode()); + org.mockito.Mockito.verify(accountJoinOperationRepository) + .recordCanonicalAttemptFailure( + f.requestId, f.scope, f.binding, "UNAVAILABLE", "ENTITLEMENT_UNAVAILABLE"); + assertTrue(f.browserJoin().success()); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.times(2)) + .insertCanonicalIntent(f.requestId, f.scope, f.binding); + } - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - AtomicReference retainedScope = new AtomicReference<>(); - AtomicReference retainedOperation = - new AtomicReference<>(); - retainJoinEvidence(retainedScope, retainedOperation); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(originalPolicy)); - JoinPublicProductionRequest request = - new JoinPublicProductionRequest(connectScopeId, "join-terminal-policy-change-1"); - - JoinPublicProductionResult joined = - service.joinPublicProduction(bootstrap.bootstrapToken(), request); - var committedOperation = retainedOperation.get(); - AccountTenantMembership membership = joinedMembership.get(); - JoinPublicProductionResult retry = - service.joinPublicProduction(bootstrap.bootstrapToken(), request); - - assertTrue(joined.success()); - assertFalse(retry.success()); - assertFalse(retry.replayed()); - assertEquals("IDEMPOTENCY_CONFLICT", retry.outcomeCode()); - assertEquals(committedOperation, retainedOperation.get()); - assertEquals("COMMITTED", retainedOperation.get().status()); - assertEquals("JOINED", retainedOperation.get().outcome()); - assertEquals(5L, retainedOperation.get().entitlementVersion()); - assertEquals(membership, joinedMembership.get()); - assertEquals("ACTIVE", membership.getLifecycleState()); - assertEquals(1L, membership.getMembershipVersion()); - when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenReturn(java.util.List.of()); - JoinPublicProductionResult unavailableAuthorityRetry = - service.joinPublicProduction(bootstrap.bootstrapToken(), request); - assertFalse(unavailableAuthorityRetry.success()); - assertFalse(unavailableAuthorityRetry.replayed()); - assertEquals("ENTITLEMENT_UNAVAILABLE", unavailableAuthorityRetry.outcomeCode()); - assertEquals(committedOperation, retainedOperation.get()); - assertEquals(membership, joinedMembership.get()); - org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.times(1)) - .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); - org.mockito.Mockito.verify(accountAuditOutboxRepository, org.mockito.Mockito.times(1)) - .append( - org.mockito.ArgumentMatchers.any(java.util.UUID.class), - org.mockito.ArgumentMatchers.eq("tenant"), - org.mockito.ArgumentMatchers.eq(7L), - org.mockito.ArgumentMatchers.eq("ACCOUNT_JOINED_PUBLIC_PRODUCTION"), - org.mockito.ArgumentMatchers.contains("join-terminal-policy-change-1")); - org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(3)) - .findByTenantIdForUpdate(7L); + @Test + void canonicalJoinSourceCheckpointChangeRefusesBeforePolicyBindingOrTransition() { + var f = canonicalJoinFixture(); + when(f.source.matches(f.source.checkpoint())).thenReturn(false); + assertEquals( + "ENTITLEMENT_UNAVAILABLE", + assertThrows(AuthenticationException.class, f::browserJoin).getCode()); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) + .bindCanonicalPolicyEvidence( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyBoolean(), + org.mockito.ArgumentMatchers.anyLong()); + verifyNoInteractions(f.terminal); } @ParameterizedTest - @MethodSource("unavailableJoinReads") - void unavailableEntitlementRetainsJoinReceiptAndRecoversOnce( - boolean lockedRead, UnavailableEntitlement failure) { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(sessionService.isAccountSessionActive( - org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) - .thenReturn(true); - Subscription recovered = new Subscription(); - recovered.setId(22L); - recovered.setTenantId(7L); - recovered.setStatus("active"); - recovered.setEntitlementVersion(1L); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.empty()); - when(accountTenantMembershipRepository.save(org.mockito.ArgumentMatchers.any())) - .thenAnswer( - invocation -> { - AccountTenantMembership membership = invocation.getArgument(0); - membership.setId(701L); - return membership; - }); + @ValueSource(strings = {"CONNECT_SCOPE_INVALID", "AUTH_UNAVAILABLE", "CONNECT_SCOPE_MISMATCH"}) + void canonicalJoinReaderRefusalPrecedesDurableIntentAndAllAuthorityWork(String code) { + var f = canonicalJoinFixture(); + when(f.reader.read(f.scope.accountId(), f.scope.connectScopeId())) + .thenThrow(new AuthenticationException(code, "controlled reader refusal")); + assertEquals(code, assertThrows(AuthenticationException.class, f::browserJoin).getCode()); + verifyNoInteractions(accountJoinOperationRepository, f.sources, f.demos, f.terminal); + } - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - AtomicReference retainedScope = new AtomicReference<>(); - AtomicReference retainedOperation = - new AtomicReference<>(); - retainJoinEvidence(retainedScope, retainedOperation); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - AtomicBoolean authorityRecovered = new AtomicBoolean(); - when(subscriptionRepository.findByTenantId(7L)) - .thenAnswer( - invocation -> - lockedRead || authorityRecovered.get() - ? java.util.List.of(recovered) - : failure.rows()); - when(subscriptionRepository.findByTenantIdForUpdate(7L)) - .thenAnswer( - invocation -> authorityRecovered.get() ? java.util.List.of(recovered) : failure.rows()); - org.mockito.Mockito.clearInvocations(accountConnectScopeRepository); - JoinPublicProductionRequest request = - new JoinPublicProductionRequest(connectScopeId, "join-unavailable-1"); - - JoinPublicProductionResult first = - service.joinPublicProduction(bootstrap.bootstrapToken(), request); - assertFalse(first.success()); - assertEquals("ENTITLEMENT_UNAVAILABLE", first.outcomeCode()); - assertEquals("PENDING", retainedOperation.get().status()); - assertEquals(null, retainedOperation.get().outcome()); - assertEquals("ENTITLEMENT_UNAVAILABLE", retainedOperation.get().lastAttemptFailureCode()); - assertEquals("UNAVAILABLE", retainedOperation.get().lastAttemptAuthorityAvailability()); - assertNotNull(retainedOperation.get().intentDigest()); - String intentDigest = retainedOperation.get().intentDigest(); - String boundDigest = retainedOperation.get().requestDigest(); - if (lockedRead) { - assertEquals( - net.firedevops.firemud.accountservice.dto.AccountJoinDigest.request( - retainedScope.get(), retainedOperation.get().callerBinding(), true, 1L), - boundDigest); - assertEquals(1, retainedOperation.get().requestDigestVersion()); - assertEquals(true, retainedOperation.get().allowPublicJoin()); - assertEquals(1L, retainedOperation.get().entitlementVersion()); - assertEquals("AVAILABLE", retainedOperation.get().entitlementAuthorityAvailability()); + @ParameterizedTest + @ValueSource(strings = {"ADMISSION_POINTER_UNAVAILABLE", "CONNECT_SCOPE_MISMATCH"}) + void canonicalJoinTargetFailureRetainsTheOriginalIntentWithoutAWrite(String code) { + var f = canonicalJoinFixture(); + org.mockito.Mockito.doThrow(new AuthenticationException(code, "controlled target refusal")) + .when(f.targets) + .resolvePublishedRealmAdmissionTarget(org.mockito.ArgumentMatchers.any()); + assertEquals(code, assertThrows(AuthenticationException.class, f::browserJoin).getCode()); + if (code.equals("CONNECT_SCOPE_MISMATCH")) { + org.mockito.Mockito.verify(accountJoinOperationRepository) + .finishCanonicalFailure(f.requestId, f.scope, f.binding, code); } else { - assertNull(boundDigest); - assertNull(retainedOperation.get().requestDigestVersion()); - assertNull(retainedOperation.get().allowPublicJoin()); - assertNull(retainedOperation.get().entitlementVersion()); + org.mockito.Mockito.verify(accountJoinOperationRepository) + .recordCanonicalAttemptFailure(f.requestId, f.scope, f.binding, "NOT_EVALUATED", code); } - verifyNoInteractions(accountTenantMembershipRepository, accountAuditOutboxRepository); - org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) - .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); - - JoinPublicProductionResult stillUnavailable = - service.joinPublicProduction(bootstrap.bootstrapToken(), request); - assertEquals("ENTITLEMENT_UNAVAILABLE", stillUnavailable.outcomeCode()); - assertEquals("PENDING", retainedOperation.get().status()); - assertEquals(intentDigest, retainedOperation.get().intentDigest()); - assertEquals(boundDigest, retainedOperation.get().requestDigest()); - assertEquals(lockedRead ? Boolean.TRUE : null, retainedOperation.get().allowPublicJoin()); + verifyNoInteractions(f.terminal); + } + + @Test + void canonicalJoinChangedTargetBetweenStrictReadsIsTerminalWithoutMembershipEffects() { + var f = canonicalJoinFixture(); + var changed = + org.mockito.Mockito.mock(Target.class, org.mockito.AdditionalAnswers.delegatesTo(f.target)); + when(changed.activeWorldEpoch()).thenReturn(2L); + var reads = new java.util.concurrent.atomic.AtomicInteger(); + org.mockito.Mockito.doAnswer( + invocation -> + f.resolve( + invocation.getArgument(0), reads.incrementAndGet() == 1 ? f.target : changed)) + .when(f.targets) + .resolvePublishedRealmAdmissionTarget(org.mockito.ArgumentMatchers.any()); assertEquals( - lockedRead ? Long.valueOf(1L) : null, retainedOperation.get().entitlementVersion()); - verifyNoInteractions(accountTenantMembershipRepository, accountAuditOutboxRepository); + "CONNECT_SCOPE_MISMATCH", + assertThrows(AuthenticationException.class, f::browserJoin).getCode()); + org.mockito.Mockito.verify(accountJoinOperationRepository) + .finishCanonicalFailure(f.requestId, f.scope, f.binding, "CONNECT_SCOPE_MISMATCH"); + org.mockito.Mockito.verify(f.targets, org.mockito.Mockito.times(2)) + .readPublishedRealmAdmissionOwner(org.mockito.ArgumentMatchers.any()); + verifyNoInteractions(f.terminal); + } - authorityRecovered.set(true); - JoinPublicProductionResult retriedAfterRecovery = - service.joinPublicProduction(bootstrap.bootstrapToken(), request); - - assertTrue(retriedAfterRecovery.success()); - assertEquals("JOINED", retriedAfterRecovery.outcomeCode()); - assertEquals("COMMITTED", retainedOperation.get().status()); - assertEquals("AVAILABLE", retainedOperation.get().entitlementAuthorityAvailability()); - assertEquals(1L, retainedOperation.get().entitlementVersion()); - assertEquals(true, retainedOperation.get().allowPublicJoin()); - assertNotNull(retainedOperation.get().requestDigest()); - assertEquals(intentDigest, retainedOperation.get().intentDigest()); - if (lockedRead) { - assertEquals(boundDigest, retainedOperation.get().requestDigest()); + @ParameterizedTest + @ValueSource( + strings = {"retainedTarget", "resolvedSelector", "publishedSelector", "publishedTarget"}) + void canonicalJoinLocallyVerifiedTargetMismatchIsTerminal(String mismatch) { + var f = canonicalJoinFixture(); + if (mismatch.equals("retainedTarget") || mismatch.equals("resolvedSelector")) { + org.mockito.Mockito.doAnswer( + invocation -> { + var resolved = f.resolve(invocation.getArgument(0), f.target); + if (mismatch.equals("retainedTarget")) { + when(f.target.pointerVersion()).thenReturn(f.scope.pointerVersion() + 1L); + } else { + when(resolved.selector()) + .thenReturn( + org.mockito.Mockito.mock( + net.firedevops.firemud.common.gamesession + .CanonicalGameplayAdmissionDecisionReadGrpcCodec + .RetainedTargetSelector.class)); + } + return resolved; + }) + .when(f.targets) + .resolvePublishedRealmAdmissionTarget(org.mockito.ArgumentMatchers.any()); + } else { + org.mockito.Mockito.doAnswer( + invocation -> { + var published = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.gamesession + .CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence + .class); + when(published.selector()) + .thenReturn( + mismatch.equals("publishedSelector") + ? org.mockito.Mockito.mock( + net.firedevops.firemud.common.world + .CanonicalGameplayRosterOwnerReadEvidence.Request.class) + : invocation.getArgument(0)); + when(published.currentTarget()) + .thenReturn( + mismatch.equals("publishedTarget") + ? org.mockito.Mockito.mock(Target.class) + : f.target); + return published; + }) + .when(f.targets) + .readPublishedRealmAdmissionOwner(org.mockito.ArgumentMatchers.any()); } - JoinPublicProductionResult replay = - service.joinPublicProduction(bootstrap.bootstrapToken(), request); - assertTrue(replay.success()); - assertTrue(replay.replayed()); - org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.times(1)) - .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); - org.mockito.Mockito.verify(accountAuditOutboxRepository, org.mockito.Mockito.times(1)) - .append( - org.mockito.ArgumentMatchers.any(java.util.UUID.class), - org.mockito.ArgumentMatchers.eq("tenant"), - org.mockito.ArgumentMatchers.eq(7L), - org.mockito.ArgumentMatchers.eq("ACCOUNT_JOINED_PUBLIC_PRODUCTION"), - org.mockito.ArgumentMatchers.contains("join-unavailable-1")); - org.mockito.Mockito.verify( - subscriptionRepository, org.mockito.Mockito.times(lockedRead ? 4 : 2)) - .findByTenantIdForUpdate(7L); + + assertEquals( + "CONNECT_SCOPE_MISMATCH", + assertThrows(AuthenticationException.class, f::browserJoin).getCode()); + org.mockito.Mockito.verify(accountJoinOperationRepository) + .finishCanonicalFailure(f.requestId, f.scope, f.binding, "CONNECT_SCOPE_MISMATCH"); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) + .recordCanonicalAttemptFailure( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any()); + verifyNoInteractions(f.terminal); } - private static java.util.stream.Stream unavailableJoinReads() { - return java.util.stream.Stream.of(false, true) - .flatMap( - locked -> - java.util.Arrays.stream(UnavailableEntitlement.values()) - .filter(failure -> failure.cause == null) - .map(failure -> Arguments.of(locked, failure))); + @ParameterizedTest + @ValueSource(strings = {"resolver", "published"}) + void canonicalJoinRemoteValidationFailureRemainsRetryable(String owner) { + var f = canonicalJoinFixture(); + var failure = new IllegalArgumentException("Remote owner could not validate evidence"); + if (owner.equals("resolver")) { + org.mockito.Mockito.doThrow(failure) + .when(f.targets) + .resolvePublishedRealmAdmissionTarget(org.mockito.ArgumentMatchers.any()); + } else { + org.mockito.Mockito.doThrow(failure) + .when(f.targets) + .readPublishedRealmAdmissionOwner(org.mockito.ArgumentMatchers.any()); + } + var result = assertThrows(AuthenticationException.class, f::browserJoin); + assertEquals("ADMISSION_POINTER_UNAVAILABLE", result.getCode()); + assertEquals( + "Gameplay target authority is unavailable; retry the same request", result.getMessage()); + assertSame(failure, result.getCause()); + org.mockito.Mockito.verify(accountJoinOperationRepository) + .recordCanonicalAttemptFailure( + f.requestId, f.scope, f.binding, "NOT_EVALUATED", "ADMISSION_POINTER_UNAVAILABLE"); + verifyNoInteractions(f.terminal); } - private static java.util.stream.Stream storageJoinReads() { - return java.util.stream.Stream.of(false, true) - .flatMap( - locked -> - java.util.Arrays.stream(UnavailableEntitlement.values()) - .filter(failure -> failure.cause != null) - .map(failure -> Arguments.of(locked, failure))); + @Test + void canonicalJoinStrictPublishedSourceOutageCannotUseResolverOnlyAuthority() { + var f = canonicalJoinFixture(); + org.mockito.Mockito.doThrow( + new IllegalStateException("controlled unavailable World ACTIVE source")) + .when(f.targets) + .readPublishedRealmAdmissionOwner(org.mockito.ArgumentMatchers.any()); + assertEquals( + "ADMISSION_POINTER_UNAVAILABLE", + assertThrows(AuthenticationException.class, f::browserJoin).getCode()); + org.mockito.Mockito.verify(accountJoinOperationRepository) + .recordCanonicalAttemptFailure( + f.requestId, f.scope, f.binding, "NOT_EVALUATED", "ADMISSION_POINTER_UNAVAILABLE"); + verifyNoInteractions(f.terminal); } - @ParameterizedTest - @MethodSource("storageJoinReads") - void joinStorageOutageRollsBackBeforeRecordingFailureAndRecoversOriginalOnce( - boolean lockedRead, UnavailableEntitlement failure) { - Account account = directTextAccount(); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - AtomicReference retainedScope = new AtomicReference<>(); - AtomicReference retainedOperation = - new AtomicReference<>(); - retainJoinEvidence(retainedScope, retainedOperation); - String scope = - service - .issueDirectTextConnectScope(directTextCaller(), directTextTarget()) - .connectScopeId(); - AtomicBoolean recovered = new AtomicBoolean(); - Subscription available = new Subscription(); - available.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)) - .thenAnswer( - invocation -> lockedRead || recovered.get() ? List.of(available) : failure.rows()); - when(subscriptionRepository.findByTenantIdForUpdate(7L)) - .thenAnswer(invocation -> recovered.get() ? List.of(available) : failure.rows()); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.empty()); - when(accountTenantMembershipRepository.save(org.mockito.ArgumentMatchers.any())) - .thenAnswer( - invocation -> { - AccountTenantMembership membership = invocation.getArgument(0); - membership.setId(701L); - return membership; - }); - org.mockito.Mockito.clearInvocations( - transactionManager, accountConnectScopeRepository, accountJoinOperationRepository); - var request = new JoinPublicProductionRequest(scope, directTextCaller().requestId()); - - var unavailable = service.joinPublicProductionFromGameSession(directTextCaller(), request); - - assertFalse(unavailable.success()); - assertEquals("ENTITLEMENT_UNAVAILABLE", unavailable.outcomeCode()); - assertEquals("PENDING", retainedOperation.get().status()); - assertNull(retainedOperation.get().outcome()); - assertEquals("ENTITLEMENT_UNAVAILABLE", retainedOperation.get().lastAttemptFailureCode()); - assertEquals("UNAVAILABLE", retainedOperation.get().lastAttemptAuthorityAvailability()); - String originalIntent = retainedOperation.get().intentDigest(); - assertNotNull(originalIntent); - var order = org.mockito.Mockito.inOrder(transactionManager, accountJoinOperationRepository); - order.verify(transactionManager).rollback(org.mockito.ArgumentMatchers.any()); + @Test + void canonicalJoinNonEntitlementFailureAfterPolicyBindingKeepsPolicySeparateFromAttempt() { + var f = canonicalJoinFixture(); + var failure = new AuthenticationException("AUTH_UNAVAILABLE", "controlled member outage"); + when(accountTenantMembershipRepository.findFreshMembershipForUpdate( + f.scope.accountId(), f.scope.tenantId())) + .thenThrow(failure); + + assertSame(failure, assertThrows(AuthenticationException.class, f::browserJoin)); + + var order = org.mockito.Mockito.inOrder(accountJoinOperationRepository); order - .verify(transactionManager) - .getTransaction(org.mockito.ArgumentMatchers.any(TransactionDefinition.class)); - order.verify(accountJoinOperationRepository).findForUpdate(request.requestId()); + .verify(accountJoinOperationRepository) + .bindCanonicalPolicyEvidence(f.requestId, f.scope, f.binding, true, 1L); order .verify(accountJoinOperationRepository) - .recordAttemptFailure(request.requestId(), "UNAVAILABLE", "ENTITLEMENT_UNAVAILABLE"); - order.verify(transactionManager).commit(org.mockito.ArgumentMatchers.any()); - verifyNoInteractions(accountTenantMembershipRepository, accountAuditOutboxRepository); - org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) - .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); - // AtomicReference fixtures do not physically roll back policy writes; PostgreSQL proves that. - recovered.set(true); - var joined = service.joinPublicProductionFromGameSession(directTextCaller(), request); - assertTrue(joined.success()); - assertFalse(joined.replayed()); - assertEquals(originalIntent, retainedOperation.get().intentDigest()); - var committed = retainedOperation.get(); - assertTrue(service.joinPublicProductionFromGameSession(directTextCaller(), request).replayed()); - assertEquals(committed, retainedOperation.get()); - org.mockito.Mockito.verify(accountTenantMembershipRepository) - .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); - org.mockito.Mockito.verify(accountAuditOutboxRepository) - .append( - org.mockito.ArgumentMatchers.any(UUID.class), - org.mockito.ArgumentMatchers.eq("tenant"), - org.mockito.ArgumentMatchers.eq(7L), - org.mockito.ArgumentMatchers.eq("ACCOUNT_JOINED_PUBLIC_PRODUCTION"), - org.mockito.ArgumentMatchers.anyString()); + .recordCanonicalAttemptFailure( + f.requestId, f.scope, f.binding, "NOT_EVALUATED", "AUTH_UNAVAILABLE"); + verifyNoInteractions(f.terminal); } @ParameterizedTest - @MethodSource("terminalJoinReadFailures") - void terminalJoinEntitlementOutagePreservesCompleteOriginal( - UnavailableEntitlement failure, String programmingFault) { - Account account = directTextAccount(); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - AtomicReference retainedScope = new AtomicReference<>(); - AtomicReference retainedOperation = - new AtomicReference<>(); - retainJoinEvidence(retainedScope, retainedOperation); - String scope = - service - .issueDirectTextConnectScope(directTextCaller(), directTextTarget()) - .connectScopeId(); - Subscription available = new Subscription(); - available.setStatus("active"); - when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenReturn(List.of(available)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.empty()); - when(accountTenantMembershipRepository.save(org.mockito.ArgumentMatchers.any())) - .thenAnswer( - invocation -> { - AccountTenantMembership membership = invocation.getArgument(0); - membership.setId(701L); - return membership; - }); - var request = new JoinPublicProductionRequest(scope, directTextCaller().requestId()); - var originalResult = service.joinPublicProductionFromGameSession(directTextCaller(), request); - assertTrue(originalResult.success()); - var original = retainedOperation.get(); - var originalScope = retainedScope.get(); - AtomicBoolean recovered = new AtomicBoolean(); - when(subscriptionRepository.findByTenantIdForUpdate(7L)) - .thenAnswer( - invocation -> { - if (recovered.get()) { - return List.of(available); - } - if (programmingFault != null) { - throw entitlementProgrammingFault(programmingFault); - } - return failure.rows(); - }); - org.mockito.Mockito.clearInvocations( - accountTenantMembershipRepository, - accountAuditOutboxRepository, - accountJoinOperationRepository, - accountConnectScopeRepository); + @ValueSource(longs = {-1L, 120L}) + void canonicalJoinFutureOrExpiredScopeCannotReachMembershipCommit(long seconds) { + var f = canonicalJoinFixture(); + f.compose( + Clock.fixed( + Instant.parse(f.scope.evaluatedAt()).plusSeconds(seconds), java.time.ZoneOffset.UTC)); + assertEquals( + "CONNECT_SCOPE_INVALID", + assertThrows(AuthenticationException.class, f::browserJoin).getCode()); + verifyNoInteractions(f.terminal); + } - var unavailable = service.joinPublicProductionFromGameSession(directTextCaller(), request); + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void canonicalJoinExpiryAtCommitGatesDoesNotRewritePendingIntent(boolean afterCoordinator) { + var f = canonicalJoinFixture(); + var clock = org.mockito.Mockito.mock(Clock.class); + when(clock.instant()) + .thenAnswer( + invocation -> + Instant.parse(f.scope.evaluatedAt()) + .plusSeconds(!afterCoordinator || f.joined.get() ? 120 : 1)); + f.compose(clock); - assertFalse(unavailable.success()); - assertFalse(unavailable.replayed()); - assertEquals( - programmingFault == null ? "ENTITLEMENT_UNAVAILABLE" : "AUTH_UNAVAILABLE", - unavailable.outcomeCode()); - assertEquals(original, retainedOperation.get()); - assertEquals(originalScope, retainedScope.get()); - recovered.set(true); - var replay = service.joinPublicProductionFromGameSession(directTextCaller(), request); - assertTrue(replay.success()); - assertTrue(replay.replayed()); - assertEquals(originalResult.accountId(), replay.accountId()); - assertEquals(originalResult.membershipId(), replay.membershipId()); - assertEquals(originalResult.membershipVersion(), replay.membershipVersion()); assertEquals( - originalResult.membershipAuthorityGeneration(), replay.membershipAuthorityGeneration()); - assertEquals(originalResult.outcomeCode(), replay.outcomeCode()); - assertEquals(original, retainedOperation.get()); - verifyNoInteractions(accountTenantMembershipRepository, accountAuditOutboxRepository); + "CONNECT_SCOPE_INVALID", + assertThrows(AuthenticationException.class, f::browserJoin).getCode()); + org.mockito.Mockito.verify(accountJoinOperationRepository) + .insertCanonicalIntent(f.requestId, f.scope, f.binding); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) + .finishCanonicalFailure( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString()); org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) - .recordAttemptFailure( + .recordCanonicalAttemptFailure( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.anyString()); + // This mock-level proof observes rollback invocation, not physical SQL rollback. + org.mockito.Mockito.verify(transactionManager).rollback(org.mockito.ArgumentMatchers.any()); + if (afterCoordinator) { + org.mockito.Mockito.verify(f.terminal) + .commitCanonicalJoin(f.scope, f.requestId, f.binding, null, null, null); + } else { + verifyNoInteractions(f.terminal); + } + } + + @Test + void canonicalJoinReturnsCommittedReceiptWhenScopeExpiresAfterCommit() { + var f = canonicalJoinFixture(); + var committed = new AtomicBoolean(); + var clock = org.mockito.Mockito.mock(Clock.class); + when(clock.instant()) + .thenAnswer( + invocation -> + Instant.parse(f.scope.evaluatedAt()).plusSeconds(committed.get() ? 120 : 1)); + f.compose(clock); + org.mockito.Mockito.doAnswer( + invocation -> { + if (f.joined.get()) committed.set(true); + return null; + }) + .when(transactionManager) + .commit(org.mockito.ArgumentMatchers.any()); + + var result = f.browserJoin(); + + assertTrue(committed.get()); + assertTrue(result.success()); + assertEquals("JOINED", result.outcomeCode()); org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) - .bindPolicyEvidence( + .finishCanonicalFailure( org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyLong(), - org.mockito.ArgumentMatchers.anyBoolean()); - org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) - .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); + org.mockito.ArgumentMatchers.anyString()); + } + + @ParameterizedTest + @CsvSource({ + "AUTH_UNAVAILABLE,NOT_EVALUATED", + "ENTITLEMENT_UNAVAILABLE,UNAVAILABLE", + "ADMISSION_POINTER_UNAVAILABLE,NOT_EVALUATED" + }) + void canonicalJoinPreservesTypedFailureWhenRecordingFails( + String code, String authorityAvailability) { + var f = canonicalJoinFixture(); + var primary = new AuthenticationException(code, "controlled primary source failure"); + var recording = + new org.springframework.dao.DataAccessResourceFailureException( + "controlled recording failure"); + org.mockito.Mockito.doThrow(primary) + .when(f.targets) + .resolvePublishedRealmAdmissionTarget(org.mockito.ArgumentMatchers.any()); + org.mockito.Mockito.doThrow(recording) + .when(accountJoinOperationRepository) + .recordCanonicalAttemptFailure( + f.requestId, f.scope, f.binding, authorityAvailability, code); + + var failure = assertThrows(AuthenticationException.class, f::browserJoin); + + assertSame(primary, failure); + assertEquals(code, failure.getCode()); + assertArrayEquals(new Throwable[] {recording}, failure.getSuppressed()); + verifyNoInteractions(f.terminal); } - private static java.util.stream.Stream terminalJoinReadFailures() { - return java.util.stream.Stream.concat( - java.util.Arrays.stream(UnavailableEntitlement.values()) - .map(failure -> Arguments.of(failure, null)), - java.util.stream.Stream.of("mapping", "configuration") - .map(fault -> Arguments.of(null, fault))); + @Test + void canonicalJoinPreservesRetryableMappingAndCauseWhenRecordingFails() { + var f = canonicalJoinFixture(); + var primary = new IllegalStateException("controlled primary source failure"); + var recording = new AuthenticationException("ACCOUNT_LOCKED", "controlled recording refusal"); + org.mockito.Mockito.doThrow(primary) + .when(f.sources) + .readCurrentSourceSelection(f.scope.tenantId()); + org.mockito.Mockito.doThrow(recording) + .when(accountJoinOperationRepository) + .recordCanonicalAttemptFailure( + f.requestId, f.scope, f.binding, "UNAVAILABLE", "ENTITLEMENT_UNAVAILABLE"); + + var failure = assertThrows(AuthenticationException.class, f::browserJoin); + + assertEquals("ENTITLEMENT_UNAVAILABLE", failure.getCode()); + assertSame(primary, failure.getCause()); + assertArrayEquals(new Throwable[] {recording}, primary.getSuppressed()); + verifyNoInteractions(f.terminal); } @ParameterizedTest - @CsvSource({"false,mapping", "true,mapping", "false,configuration", "true,configuration"}) - void joinMappingAndConfigurationFaultsRetainUnexpectedFailureBoundary( - boolean lockedRead, String fault) { - Account account = directTextAccount(); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - AtomicReference retainedScope = new AtomicReference<>(); - AtomicReference retainedOperation = - new AtomicReference<>(); - retainJoinEvidence(retainedScope, retainedOperation); - String scope = - service - .issueDirectTextConnectScope(directTextCaller(), directTextTarget()) - .connectScopeId(); - RuntimeException cause = entitlementProgrammingFault(fault); - if (lockedRead) { - when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenThrow(cause); - } else { - when(subscriptionRepository.findByTenantId(7L)).thenThrow(cause); + @ValueSource(booleans = {false, true}) + void canonicalJoinRefusesAmbientTransactionsBeforeReadingTheCaller(boolean synchronization) { + var f = canonicalJoinFixture(); + try { + if (synchronization) TransactionSynchronizationManager.initSynchronization(); + else TransactionSynchronizationManager.setActualTransactionActive(true); + assertThrows(IllegalStateException.class, f::browserJoin); + verifyNoInteractions(f.reader, f.targets, f.sources, f.demos, f.terminal); + } finally { + TransactionSynchronizationManager.clear(); } - org.mockito.Mockito.clearInvocations(transactionManager, accountConnectScopeRepository); + } - AuthenticationException unavailable = + @ParameterizedTest + @ValueSource(strings = {"", " ", "too-long"}) + void canonicalJoinRejectsInvalidRequestBeforeScopeOrIntentWork(String request) { + var f = canonicalJoinFixture(); + String id = request.equals("too-long") ? "j".repeat(129) : request; + assertEquals( + request.equals("too-long") ? "INVALID_ARGUMENT" : "CONNECT_SCOPE_INVALID", assertThrows( - AuthenticationException.class, - () -> - service.joinPublicProductionFromGameSession( - directTextCaller(), - new JoinPublicProductionRequest(scope, directTextCaller().requestId()))); + AuthenticationException.class, + () -> + service.joinPublicProduction( + f.bootstrap, new JoinPublicProductionRequest(f.scope.connectScopeId(), id))) + .getCode()); + verifyNoInteractions(f.reader, accountJoinOperationRepository, f.terminal); + } - assertEquals("AUTH_UNAVAILABLE", unavailable.getCode()); - assertSame(cause, unavailable.getCause()); - assertEquals("PENDING", retainedOperation.get().status()); - assertNotNull(retainedOperation.get().intentDigest()); - assertNull(retainedOperation.get().outcome()); - assertEquals("AUTH_UNAVAILABLE", retainedOperation.get().lastAttemptFailureCode()); - org.mockito.Mockito.verify(transactionManager).rollback(org.mockito.ArgumentMatchers.any()); - verifyNoInteractions(accountTenantMembershipRepository, accountAuditOutboxRepository); - org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) - .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); + @Test + void canonicalJoinAcceptsTheFull128CharacterRequestIdentity() { + var f = canonicalJoinFixture("j".repeat(128)); + assertTrue(f.browserJoin().success()); + org.mockito.Mockito.verify(accountJoinOperationRepository) + .insertCanonicalIntent(f.requestId, f.scope, f.binding); } @Test - void lateDuplicateRealmKeepsJoinPendingWithoutMembershipEffects() { - Account account = directTextAccount(); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - AtomicReference retainedScope = new AtomicReference<>(); - AtomicReference retainedOperation = - new AtomicReference<>(); - retainJoinEvidence(retainedScope, retainedOperation); - String scope = - service - .issueDirectTextConnectScope(directTextCaller(), directTextTarget()) - .connectScopeId(); - var realm = gameSessionClient.listGameplayRealms("demo").getFirst(); - when(gameSessionClient.listGameplayRealms("demo")) - .thenReturn(List.of(realm), List.of(realm, realm)); - org.mockito.Mockito.clearInvocations(subscriptionRepository, accountConnectScopeRepository); - - JoinPublicProductionResult result = - service.joinPublicProductionFromGameSession( - directTextCaller(), - new JoinPublicProductionRequest(scope, directTextCaller().requestId())); + void canonicalJoinConflictingRequestDoesNotReplaceOriginalEvidence() { + var f = canonicalJoinFixture(); + when(accountJoinOperationRepository.insertCanonicalIntent(f.requestId, f.scope, f.binding)) + .thenThrow( + new AccountJoinOperationRepository.CanonicalJoinOperationConflictException( + "controlled different caller or selector")); + assertEquals( + "IDEMPOTENCY_CONFLICT", + assertThrows(AuthenticationException.class, f::browserJoin).getCode()); + verifyNoInteractions(f.sources, f.demos, f.terminal); + } - assertFalse(result.success()); - assertEquals("ADMISSION_POINTER_UNAVAILABLE", result.outcomeCode()); - assertEquals("PENDING", retainedOperation.get().status()); - assertEquals(true, retainedOperation.get().allowPublicJoin()); - assertEquals(1L, retainedOperation.get().entitlementVersion()); - assertNotNull(retainedOperation.get().requestDigest()); - assertEquals("ADMISSION_POINTER_UNAVAILABLE", retainedOperation.get().lastAttemptFailureCode()); - verifyNoInteractions(accountTenantMembershipRepository, accountAuditOutboxRepository); - org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.never()) - .findByTenantIdForUpdate(7L); - org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) - .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); + @ParameterizedTest + @EnumSource( + value = AccountLifecycleState.class, + names = {"DEACTIVATED_PENDING_DELETE", "SECURITY_LOCKED", "DELETED"}) + void canonicalJoinCurrentAccountLifecycleBlocksAStillLiveBootstrap(AccountLifecycleState state) { + var f = canonicalJoinFixture(); + f.account.setLifecycleState(state); + assertEquals( + state == AccountLifecycleState.SECURITY_LOCKED + ? "AUTH_ACCOUNT_LOCKED" + : "AUTH_INVALID_CREDENTIALS", + assertThrows(AuthenticationException.class, f::browserJoin).getCode()); + verifyNoInteractions(f.terminal); } - private static RuntimeException entitlementProgrammingFault(String fault) { - return "mapping".equals(fault) - ? new org.jooq.exception.MappingException("subscription mapping fault") - : new org.jooq.exception.ConfigurationException("subscription configuration fault"); + @Test + void canonicalJoinRechecksTheBrowserRegistryAfterTargetReadsBeforeCommit() { + var f = canonicalJoinFixture(); + when(sessionService.isAccountSessionActive(f.account.getId(), f.bootstrap)) + .thenReturn(true, false); + assertEquals( + "CONNECT_CONTEXT_INVALID", + assertThrows(AuthenticationException.class, f::browserJoin).getCode()); + verifyNoInteractions(f.terminal); } - private enum UnavailableEntitlement { - MISSING, - AMBIGUOUS, - NULL_LIST, - NULL_ROW, - ZERO_VERSION, - NEGATIVE_VERSION, - JOOQ_STORAGE(new org.jooq.exception.DataAccessException("subscription store unavailable")), - SPRING_STORAGE(new DataAccessResourceFailureException("subscription store unavailable")); + @Test + void canonicalDirectJoinUsesTheSameTerminalOwnerAndUuidTargetWithoutBootstrapSession() + throws Exception { + var f = canonicalJoinFixture(); + var caller = f.directCaller(f.requestId); + f.binding = caller.sessionId(); + when(accountJoinOperationRepository.bindCanonicalPolicyEvidence( + f.requestId, f.scope, caller.sessionId(), true, 1L)) + .thenReturn(f.pending); + org.mockito.Mockito.clearInvocations(sessionService); + var result = + canonicalGameSessionPeer() + .call( + () -> + service.joinPublicProductionFromGameSession( + caller, + new JoinPublicProductionRequest(f.scope.connectScopeId(), f.requestId))); + assertTrue(result.success()); + assertEquals(f.scope.tenantId(), result.tenantId()); + assertFalse(result.replayed()); + verifyNoInteractions(sessionService); + org.mockito.Mockito.verify(accountJoinOperationRepository) + .bindCanonicalPolicyEvidence(f.requestId, f.scope, caller.sessionId(), true, 1L); + org.mockito.Mockito.verify(f.terminal) + .commitCanonicalJoin(f.scope, f.requestId, f.binding, null, null, null); + } - private final RuntimeException cause; + @ParameterizedTest + @ValueSource(strings = {"absent", "namespace", "service"}) + void canonicalDirectJoinRejectsWrongWorkloadBeforeReadingScope(String mismatch) throws Exception { + var f = canonicalJoinFixture(); + var peer = io.grpc.Context.ROOT; + if (!mismatch.equals("absent")) { + String namespace = mismatch.equals("namespace") ? "other" : "test"; + String name = + mismatch.equals("service") ? "world-management-service" : "game-session-service"; + peer = + peer.withValue( + net.firedevops.firemud.common.grpc.GrpcPeerIdentity.CONTEXT_KEY, + new net.firedevops.firemud.common.grpc.GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + name, namespace, name)); + } + assertEquals( + "AUTH_UNAVAILABLE", + peer.call( + () -> + assertThrows( + AuthenticationException.class, + () -> + service.joinPublicProductionFromGameSession( + f.directCaller(f.requestId), + new JoinPublicProductionRequest( + f.scope.connectScopeId(), f.requestId)))) + .getCode()); + verifyNoInteractions(f.reader, accountJoinOperationRepository, f.terminal); + } - UnavailableEntitlement() { - this(null); + @ParameterizedTest + @ValueSource(strings = {"tenant", "realm", "namespace", "scope", "instance"}) + void canonicalDirectJoinRejectsAnyCallerTargetMismatchBeforeIntent(String field) + throws Exception { + var f = canonicalJoinFixture(); + var caller = + new DirectTextCallerContext( + f.scope.accountId(), + field.equals("tenant") ? UUID.randomUUID() : f.scope.tenantId(), + field.equals("realm") ? UUID.randomUUID() : f.scope.realmId(), + field.equals("namespace") ? UUID.randomUUID() : f.scope.playableStateNamespaceId(), + field.equals("scope") ? "ISOLATED" : f.scope.playableStateScope(), + field.equals("instance") ? UUID.randomUUID() : f.scope.gameInstanceId(), + "00042", + f.requestId); + assertEquals( + "CONNECT_SCOPE_MISMATCH", + canonicalGameSessionPeer() + .call( + () -> + assertThrows( + AuthenticationException.class, + () -> + service.joinPublicProductionFromGameSession( + caller, + new JoinPublicProductionRequest( + f.scope.connectScopeId(), f.requestId)))) + .getCode()); + verifyNoInteractions(accountJoinOperationRepository, f.terminal); + } + + private CanonicalJoinFixture canonicalJoinFixture() { + return canonicalJoinFixture("canonical-request"); + } + + private CanonicalJoinFixture canonicalJoinFixture(String requestId) { + return new CanonicalJoinFixture(requestId); + } + + private static io.grpc.Context canonicalGameSessionPeer() { + return io.grpc.Context.ROOT.withValue( + net.firedevops.firemud.common.grpc.GrpcPeerIdentity.CONTEXT_KEY, + new net.firedevops.firemud.common.grpc.GrpcPeerIdentity( + "spiffe://firemud/ns/test/sa/game-session-service", "test", "game-session-service")); + } + + private final class CanonicalJoinFixture { + private final Account account = new Account(); + private final CanonicalJoinScopeV2 scope; + private final String requestId; + private final String bootstrap; + private final AccountTenantMembership currentMembership = new AccountTenantMembership(); + private final AtomicBoolean joined = new AtomicBoolean(); + private String binding = UUID.randomUUID().toString(); + private final net.firedevops.firemud.accountservice.service.AccountCanonicalConnectScopeReader + reader = + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.service.AccountCanonicalConnectScopeReader + .class); + private final CanonicalGameplayAdmissionDecisionReadClient targets = + org.mockito.Mockito.mock(CanonicalGameplayAdmissionDecisionReadClient.class); + private final Target target = org.mockito.Mockito.mock(Target.class); + private final net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + roster = + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .class); + private Target resolvedTarget = target; + private byte[] policyBytes = + "controlled-unit-policy-set".getBytes(java.nio.charset.StandardCharsets.UTF_8); + private final net.firedevops.firemud.accountservice.repository + .AccountTenantAuthorityEventRepository + sources = + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountTenantAuthorityEventRepository.class); + private final net.firedevops.firemud.accountservice.repository + .AccountTenantAuthorityEventRepository.SourceSelection + source = + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountTenantAuthorityEventRepository.SourceSelection.class); + private final net.firedevops.firemud.accountservice.repository + .AccountDemoTenantEntitlementRepository + demos = + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountDemoTenantEntitlementRepository.class); + private final net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot demo = + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot.class); + private final net.firedevops.firemud.accountservice.repository + .AccountHostingSubscriptionLifecycleRepository + hosting = + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountHostingSubscriptionLifecycleRepository.class); + private final net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver + observer = + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver + .class); + private final net.firedevops.firemud.accountservice.service + .AccountCanonicalFirstJoinTerminalCoordinator + terminal = + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.service + .AccountCanonicalFirstJoinTerminalCoordinator.class); + private final AccountJoinOperationRepository.CanonicalJoinOperationEvidence pending = + org.mockito.Mockito.mock( + AccountJoinOperationRepository.CanonicalJoinOperationEvidence.class); + private final AccountJoinOperationRepository.CanonicalJoinOperationEvidence committed = + org.mockito.Mockito.mock( + AccountJoinOperationRepository.CanonicalJoinOperationEvidence.class); + + private CanonicalJoinFixture(String requestId) { + this.requestId = requestId; + account.setId(11L); + setPersistedAuthenticationIdentity(account); + when(accountRepository.findByAccountUuidForUpdate(account.getAccountUuid())) + .thenReturn(Optional.of(account)); + var now = Instant.now().truncatedTo(java.time.temporal.ChronoUnit.SECONDS); + scope = + new CanonicalJoinScopeV2( + "controlled-v2-token", + account.getAccountUuid(), + UUID.randomUUID(), + UUID.fromString(REALM_ID), + "tenant", + "demo", + "production", + UUID.fromString(PLAYABLE_STATE_NAMESPACE_ID), + "SHARED", + UUID.randomUUID(), + 23L, + 17L, + now.toString(), + now.plusSeconds(120).toString()); + bootstrap = + jwtUtil.generateToken( + account.getAccountUuid().toString(), + 300000L, + Map.of( + "aud", + "player-bootstrap", + "accountId", + account.getAccountUuid().toString(), + "jti", + binding)); + when(sessionService.isAccountSessionActive(account.getId(), bootstrap)).thenReturn(true); + when(reader.read(scope.accountId(), scope.connectScopeId())).thenReturn(scope); + when(target.targetNamespace()).thenReturn("test"); + when(target.canonicalTenantId()).thenReturn(scope.tenantId()); + when(target.tenantSlug()).thenReturn(scope.tenantSlug()); + when(target.worldSlug()).thenReturn(scope.worldSlug()); + when(target.realmId()).thenReturn(scope.realmId()); + when(target.realmSlug()).thenReturn(scope.realmSlug()); + when(target.playableStateNamespaceId()).thenReturn(scope.playableStateNamespaceId()); + when(target.playableStateScope()).thenReturn(scope.playableStateScope()); + when(target.canonicalGameInstanceId()).thenReturn(scope.gameInstanceId()); + when(target.canonicalVersionId()).thenReturn(UUID.randomUUID()); + when(target.catalogRevision()).thenReturn(scope.catalogRevision()); + when(target.pointerVersion()).thenReturn(scope.pointerVersion()); + when(target.activeWorldEpoch()).thenReturn(1L); + when(target.characterCreationPolicy()).thenReturn("PRESEEDED_ONLY"); + when(target.ownerProofOutcome()) + .thenReturn( + net.firedevops.firemud.common.gamesession + .CanonicalGameplayAdmissionDecisionReadGrpcCodec.OwnerProofOutcome.COMMITTED); + when(targets.resolvePublishedRealmAdmissionTarget(org.mockito.ArgumentMatchers.any())) + .thenAnswer(invocation -> resolve(invocation.getArgument(0), target)); + when(targets.readPublishedRealmAdmissionOwner(org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + var strict = + invocation.getArgument( + 0, + net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence + .Request.class); + Target currentTarget = resolvedTarget; + long activeWorldEpoch = currentTarget.activeWorldEpoch(); + var published = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.gamesession + .CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence + .class); + when(published.selector()).thenReturn(strict); + when(published.currentTarget()).thenReturn(currentTarget); + var sourceEvidence = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence + .class); + when(sourceEvidence.request()).thenReturn(strict); + var policies = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.publication + .PublishedRealmEntryPolicySetEvidence.class); + when(policies.canonicalBytes()).thenReturn(policyBytes); + when(sourceEvidence.publishedPolicySetEvidence()).thenReturn(policies); + when(published.sourceEvidence()).thenReturn(sourceEvidence); + var world = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence + .class); + when(world.lifecycleStatus()).thenReturn("ACTIVE"); + when(world.lifecycleEpoch()).thenReturn(activeWorldEpoch); + when(published.worldLifecycleEvidence()).thenReturn(world); + return published; + }); + when(pending.status()).thenReturn("PENDING"); + when(accountJoinOperationRepository.findCanonicalEvidenceForUpdateByRequestId(requestId)) + .thenReturn(Optional.of(pending)); + when(accountJoinOperationRepository.bindCanonicalPolicyEvidence( + org.mockito.ArgumentMatchers.eq(requestId), + org.mockito.ArgumentMatchers.eq(scope), + org.mockito.ArgumentMatchers.eq(binding), + org.mockito.ArgumentMatchers.anyBoolean(), + org.mockito.ArgumentMatchers.anyLong())) + .thenReturn(pending); + when(sources.readCurrentSourceSelection(scope.tenantId())).thenReturn(source); + when(source.kind()) + .thenReturn( + net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository + .SourceKind.NON_PAID_DEMO); + when(source.matches(source.checkpoint())).thenReturn(true); + when(demos.readCurrent(scope.tenantId())).thenReturn(demo); + when(demos.revalidate(demo)).thenReturn(demo); + when(demo.gameplayAvailable()).thenReturn(true); + when(demo.allowPublicJoin()).thenReturn(true); + when(demo.entitlementVersion()).thenReturn(1L); + terminal("JOINED", 2L, 1L); + when(accountTenantMembershipRepository.findFreshMembershipForUpdate( + scope.accountId(), scope.tenantId())) + .thenAnswer( + invocation -> joined.get() ? Optional.of(currentMembership) : Optional.empty()); + when(terminal.commitCanonicalJoin( + org.mockito.ArgumentMatchers.eq(scope), + org.mockito.ArgumentMatchers.eq(requestId), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.isNull(), + org.mockito.ArgumentMatchers.isNull(), + org.mockito.ArgumentMatchers.isNull())) + .thenAnswer( + invocation -> { + joined.set(true); + return committed; + }); + service.setAccountBootstrapRosterReadClient(roster); + compose(Clock.fixed(now.plusSeconds(1), java.time.ZoneOffset.UTC)); } - UnavailableEntitlement(RuntimeException cause) { - this.cause = cause; + private net.firedevops.firemud.common.gamesession + .CanonicalGameplayAdmissionDecisionReadGrpcCodec.ResolvedPublishedTarget + resolve( + net.firedevops.firemud.common.gamesession + .CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector + selector, + Target current) { + resolvedTarget = current; + var resolved = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.gamesession + .CanonicalGameplayAdmissionDecisionReadGrpcCodec.ResolvedPublishedTarget.class); + var strict = + new net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence.Request( + selector.readRequestId(), + selector.accountId(), + selector.targetNamespace(), + selector.tenantId(), + selector.worldSlug(), + selector.realmId(), + selector.realmSlug(), + selector.playableStateNamespaceId(), + selector.playableStateScope(), + selector.gameInstanceId(), + current.canonicalVersionId(), + selector.catalogRevision(), + selector.pointerVersion(), + current.activeWorldEpoch()); + when(resolved.selector()).thenReturn(selector); + when(resolved.currentTarget()).thenReturn(current); + when(resolved.strictSelector()).thenReturn(strict); + return resolved; } - private List rows() { - if (cause != null) { - throw cause; - } - return switch (this) { - case MISSING -> List.of(); - case AMBIGUOUS -> List.of(new Subscription(), new Subscription()); - case NULL_LIST -> null; - case NULL_ROW -> java.util.Collections.singletonList(null); - case ZERO_VERSION, NEGATIVE_VERSION -> { - Subscription invalid = new Subscription(); - invalid.setStatus("active"); - invalid.setEntitlementVersion(this == ZERO_VERSION ? 0L : -1L); - yield List.of(invalid); - } - default -> throw new IllegalStateException("Storage failure must have a cause"); - }; + private void terminal(String outcome, long version, long generation) { + currentMembership.setId(701L); + currentMembership.setAccount(account); + currentMembership.setTenantUuid(scope.tenantId()); + currentMembership.setTenantProvenanceKind("FRESH_GAME_DESIGN"); + currentMembership.setAuthorityProvenance("EXPLICIT_JOIN"); + currentMembership.setLifecycleState("ACTIVE"); + currentMembership.setGameplayAdmissionAllowed(true); + currentMembership.setMembershipVersion(version); + currentMembership.setMembershipAuthorityGeneration(generation); + when(committed.outcome()).thenReturn(outcome); + when(committed.terminalProof()) + .thenReturn( + new AccountJoinOperationRepository.CanonicalJoinTerminalProof( + "membership-stream", + 1L, + UUID.randomUUID().toString(), + "sha256:" + "a".repeat(64), + outcome.equals("ALREADY_ACTIVE") ? null : UUID.randomUUID(), + outcome.equals("ALREADY_ACTIVE") ? null : "sha256:" + "b".repeat(64), + outcome.equals("ALREADY_ACTIVE") ? null : Instant.now(), + 1L, + 701L, + version, + generation)); } - } - @Test - void joinPublicProductionRevalidatesPolicyAtTheMembershipCommitGate() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(sessionService.isAccountSessionActive( - org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) - .thenReturn(true); - Subscription initialPolicy = new Subscription(); - initialPolicy.setId(22L); - initialPolicy.setTenantId(7L); - initialPolicy.setStatus("active"); - initialPolicy.setEntitlementVersion(5L); - Subscription changedPolicy = new Subscription(); - changedPolicy.setId(22L); - changedPolicy.setTenantId(7L); - changedPolicy.setStatus("active"); - changedPolicy.setEntitlementVersion(6L); - when(subscriptionRepository.findByTenantIdForUpdate(7L)) - .thenReturn(java.util.List.of(changedPolicy)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.empty()); + private void compose(Clock clock) { + service.setCanonicalScopeConsumers( + reader, targets, sources, demos, hosting, observer, terminal, "test", clock); + } - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - AtomicReference retainedScope = new AtomicReference<>(); - AtomicReference retainedOperation = - new AtomicReference<>(); - retainJoinEvidence(retainedScope, retainedOperation); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(initialPolicy)); - org.mockito.Mockito.clearInvocations(gameSessionClient, subscriptionRepository); - - JoinPublicProductionResult result = - service.joinPublicProduction( - bootstrap.bootstrapToken(), - new JoinPublicProductionRequest(connectScopeId, "join-race-1")); + private JoinPublicProductionResult browserJoin() { + return service.joinPublicProduction( + bootstrap, new JoinPublicProductionRequest(scope.connectScopeId(), requestId)); + } - assertFalse(result.success()); - assertEquals("IDEMPOTENCY_CONFLICT", result.outcomeCode()); - assertEquals("FAILED", retainedOperation.get().status()); - assertEquals("IDEMPOTENCY_CONFLICT", retainedOperation.get().outcome()); - assertEquals(5L, retainedOperation.get().entitlementVersion()); - assertEquals(true, retainedOperation.get().allowPublicJoin()); - assertEquals(1, retainedOperation.get().requestDigestVersion()); - assertNotNull(retainedOperation.get().requestDigest()); - assertEquals(null, retainedOperation.get().lastAttemptFailureCode()); - org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) - .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); - org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); - org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(1)) - .findByTenantIdForUpdate(7L); - var order = org.mockito.Mockito.inOrder(gameSessionClient, subscriptionRepository); - order.verify(gameSessionClient).listGameplayRealms("demo"); - order.verify(gameSessionClient).getAdmissionPointer(7L, "demo", "production"); - order.verify(subscriptionRepository).findByTenantId(7L); - order.verify(gameSessionClient).listGameplayRealms("demo"); - order.verify(gameSessionClient).getAdmissionPointer(7L, "demo", "production"); - order.verify(subscriptionRepository).findByTenantIdForUpdate(7L); - org.mockito.Mockito.verifyNoMoreInteractions(gameSessionClient); - } - - @Test - void changedPolicyOnRetryTerminalizesPreviouslyBoundPendingJoin() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(sessionService.isAccountSessionActive( - org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) - .thenReturn(true); - Subscription initialPolicy = new Subscription(); - initialPolicy.setId(22L); - initialPolicy.setTenantId(7L); - initialPolicy.setStatus("active"); - initialPolicy.setEntitlementVersion(5L); - Subscription changedPolicy = new Subscription(); - changedPolicy.setId(22L); - changedPolicy.setTenantId(7L); - changedPolicy.setStatus("active"); - changedPolicy.setEntitlementVersion(6L); - when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenReturn(java.util.List.of()); + private List characters() { + return service.listBootstrapCharacters( + bootstrap, scope.worldSlug(), scope.realmSlug(), scope.connectScopeId()); + } - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - AtomicReference retainedScope = new AtomicReference<>(); - AtomicReference retainedOperation = - new AtomicReference<>(); - retainJoinEvidence(retainedScope, retainedOperation); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - when(subscriptionRepository.findByTenantId(7L)) - .thenReturn(java.util.List.of(initialPolicy), java.util.List.of(changedPolicy)); - JoinPublicProductionRequest request = - new JoinPublicProductionRequest(connectScopeId, "join-policy-retry-1"); - - JoinPublicProductionResult pending = - service.joinPublicProduction(bootstrap.bootstrapToken(), request); - String boundDigest = retainedOperation.get().requestDigest(); - String intentDigest = retainedOperation.get().intentDigest(); - - assertFalse(pending.success()); - assertEquals("ENTITLEMENT_UNAVAILABLE", pending.outcomeCode()); - assertEquals("PENDING", retainedOperation.get().status()); - assertEquals(5L, retainedOperation.get().entitlementVersion()); - assertEquals("ENTITLEMENT_UNAVAILABLE", retainedOperation.get().lastAttemptFailureCode()); - - JoinPublicProductionResult changedPolicyRetry = - service.joinPublicProduction(bootstrap.bootstrapToken(), request); - - assertFalse(changedPolicyRetry.success()); - assertEquals("IDEMPOTENCY_CONFLICT", changedPolicyRetry.outcomeCode()); - assertEquals("FAILED", retainedOperation.get().status()); - assertEquals("IDEMPOTENCY_CONFLICT", retainedOperation.get().outcome()); - assertEquals(intentDigest, retainedOperation.get().intentDigest()); - assertEquals(boundDigest, retainedOperation.get().requestDigest()); - assertEquals(5L, retainedOperation.get().entitlementVersion()); - assertEquals(true, retainedOperation.get().allowPublicJoin()); - assertEquals(null, retainedOperation.get().lastAttemptFailureCode()); - org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) - .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); - org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); - org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(1)) - .findByTenantIdForUpdate(7L); + private DirectTextCallerContext directCaller(String id) { + return new DirectTextCallerContext( + scope.accountId(), + scope.tenantId(), + scope.realmId(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + "00042", + id); + } } @Test - void unboundFailedJoinReplaysOnlyAfterCurrentScopeAndAuthorityChecks() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(sessionService.isAccountSessionActive( - org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) - .thenReturn(true); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - AtomicReference retainedScope = new AtomicReference<>(); - AtomicReference retainedOperation = - new AtomicReference<>(); - retainJoinEvidence(retainedScope, retainedOperation); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - var exactRealm = gameSessionClient.listGameplayRealms("demo").getFirst(); - var exactPointer = gameSessionClient.getAdmissionPointer(7L, "demo", "production"); - var changedRealm = exactRealm.toBuilder().setPointerVersion(18L).build(); - var changedPointer = exactPointer.toBuilder().setPointerVersion(18L).build(); - when(gameSessionClient.listGameplayRealms("demo")).thenReturn(java.util.List.of(changedRealm)); - when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) - .thenReturn(changedPointer); - Subscription active = new Subscription(); - active.setId(22L); - active.setTenantId(7L); - active.setStatus("active"); - when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenReturn(java.util.List.of(active)); - org.mockito.Mockito.clearInvocations(gameSessionClient, subscriptionRepository); - JoinPublicProductionRequest request = - new JoinPublicProductionRequest(connectScopeId, "join-unbound-failure-1"); - - JoinPublicProductionResult originalFailure = - service.joinPublicProduction(bootstrap.bootstrapToken(), request); - var storedFailure = retainedOperation.get(); - - assertFalse(originalFailure.success()); - assertEquals("CONNECT_SCOPE_MISMATCH", originalFailure.outcomeCode()); - assertEquals("FAILED", storedFailure.status()); - assertEquals(originalFailure.outcomeCode(), storedFailure.outcome()); - assertNull(storedFailure.requestDigest()); - - JoinPublicProductionResult changedTargetDenial = - service.joinPublicProduction(bootstrap.bootstrapToken(), request); - - assertFalse(changedTargetDenial.success()); - assertFalse(changedTargetDenial.replayed()); - assertEquals("CONNECT_SCOPE_MISMATCH", changedTargetDenial.outcomeCode()); - assertEquals(storedFailure, retainedOperation.get()); - - when(gameSessionClient.listGameplayRealms("demo")).thenReturn(java.util.List.of(exactRealm)); - when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")).thenReturn(exactPointer); - JoinPublicProductionResult replay = - service.joinPublicProduction(bootstrap.bootstrapToken(), request); - - assertFalse(replay.success()); - assertTrue(replay.replayed()); - assertEquals(originalFailure.outcomeCode(), replay.outcomeCode()); - assertEquals(storedFailure, retainedOperation.get()); - - VerifiedJoinScope originalScope = retainedScope.get(); - VerifiedJoinScope alteredScopeWithoutDigest = - new VerifiedJoinScope( - originalScope.connectScopeId(), - originalScope.accountId(), - originalScope.tenantId(), - originalScope.realmId(), - originalScope.worldSlug(), - originalScope.realmSlug(), - originalScope.playableStateNamespaceId(), - originalScope.playableStateScope(), - originalScope.gameInstanceId(), - originalScope.catalogRevision(), - originalScope.pointerVersion() + 1, - originalScope.evaluatedAt(), - originalScope.connectScopeExpiresAt(), - ""); - retainedScope.set( - new VerifiedJoinScope( - alteredScopeWithoutDigest.connectScopeId(), - alteredScopeWithoutDigest.accountId(), - alteredScopeWithoutDigest.tenantId(), - alteredScopeWithoutDigest.realmId(), - alteredScopeWithoutDigest.worldSlug(), - alteredScopeWithoutDigest.realmSlug(), - alteredScopeWithoutDigest.playableStateNamespaceId(), - alteredScopeWithoutDigest.playableStateScope(), - alteredScopeWithoutDigest.gameInstanceId(), - alteredScopeWithoutDigest.catalogRevision(), - alteredScopeWithoutDigest.pointerVersion(), - alteredScopeWithoutDigest.evaluatedAt(), - alteredScopeWithoutDigest.connectScopeExpiresAt(), - net.firedevops.firemud.accountservice.dto.AccountJoinDigest.scope( - alteredScopeWithoutDigest))); - - AuthenticationException changedScope = - assertThrows( - AuthenticationException.class, - () -> service.joinPublicProduction(bootstrap.bootstrapToken(), request)); - assertEquals("IDEMPOTENCY_CONFLICT", changedScope.getCode()); - assertEquals(storedFailure, retainedOperation.get()); - - retainedScope.set(originalScope); - when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenReturn(java.util.List.of()); - JoinPublicProductionResult unavailableAuthority = - service.joinPublicProduction(bootstrap.bootstrapToken(), request); - - assertFalse(unavailableAuthority.success()); - assertFalse(unavailableAuthority.replayed()); - assertEquals("ENTITLEMENT_UNAVAILABLE", unavailableAuthority.outcomeCode()); - assertEquals(storedFailure, retainedOperation.get()); - org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) - .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); - org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); - org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(2)) - .findByTenantIdForUpdate(7L); + void + canonicalBootstrapCharactersReturnsOnlyTheSelectedOwnersActorsSortedWithOwnerReportedLevels() { + var f = canonicalJoinFixture(); + f.joined.set(true); + UUID ada = UUID.randomUUID(), zed = UUID.randomUUID(); + when(f.roster.read( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.eq(f.scope.accountId()), + org.mockito.ArgumentMatchers.any())) + .thenReturn( + List.of( + new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .Actor(zed, "Zed", 37), + new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .Actor(ada, "Ada", 12))); + var actors = f.characters(); + assertEquals( + List.of("Ada", "Zed"), actors.stream().map(value -> value.characterName()).toList()); + assertEquals( + List.of(ada.toString(), zed.toString()), + actors.stream().map(value -> value.characterId()).toList()); + assertEquals(List.of(12, 37), actors.stream().map(value -> value.level()).toList()); + assertTrue( + actors.stream() + .allMatch( + value -> + "SHARED".equals(value.stateScope()) + && "PRESEEDED_ONLY".equals(value.characterCreationPolicy()))); + var target = + org.mockito.ArgumentCaptor.forClass( + net.firedevops.firemud.common.gamesession + .CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence.class); + org.mockito.Mockito.verify(f.roster) + .read( + org.mockito.ArgumentMatchers.any(UUID.class), + org.mockito.ArgumentMatchers.eq(f.scope.accountId()), + target.capture()); + assertEquals(f.scope.accountId(), target.getValue().selector().canonicalAccountUuid()); + assertEquals(f.scope.tenantId(), target.getValue().selector().canonicalTenantUuid()); + assertEquals(f.scope.realmId(), target.getValue().selector().realmUuid()); + assertEquals( + f.scope.playableStateNamespaceId(), + target.getValue().selector().playableStateNamespaceUuid()); + assertEquals( + f.scope.gameInstanceId(), target.getValue().selector().canonicalGameInstanceUuid()); + assertEquals(f.scope.catalogRevision(), target.getValue().selector().expectedCatalogRevision()); + assertEquals(f.scope.pointerVersion(), target.getValue().selector().expectedPointerVersion()); + org.mockito.Mockito.verify(f.targets, org.mockito.Mockito.atLeast(2)) + .readPublishedRealmAdmissionOwner(org.mockito.ArgumentMatchers.any()); + verifyNoInteractions(accountJoinOperationRepository, accountAuditOutboxRepository); } @Test - void joinIntentCommitsSeparatelyWhenPolicyTransactionRollsBack() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(sessionService.isAccountSessionActive( - org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) - .thenReturn(true); - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - AtomicReference retainedScope = new AtomicReference<>(); - AtomicReference retainedOperation = - new AtomicReference<>(); - retainJoinEvidence(retainedScope, retainedOperation); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - when(subscriptionRepository.findByTenantId(7L)) - .thenThrow(new IllegalStateException("entitlement storage unavailable")); - - AuthenticationException unavailable = - assertThrows( - AuthenticationException.class, - () -> - service.joinPublicProduction( - bootstrap.bootstrapToken(), - new JoinPublicProductionRequest(connectScopeId, "join-txn-boundary-1"))); + void canonicalBootstrapCharactersReturnsEmptyOnlyAfterSuccessfulSupportedOwnerRead() { + var f = canonicalJoinFixture(); + f.joined.set(true); + when(f.roster.read( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.eq(f.scope.accountId()), + org.mockito.ArgumentMatchers.any())) + .thenReturn(List.of()); + assertTrue(f.characters().isEmpty()); + org.mockito.Mockito.verify(f.roster) + .read( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.eq(f.scope.accountId()), + org.mockito.ArgumentMatchers.any()); + verifyNoInteractions(accountJoinOperationRepository, accountAuditOutboxRepository); + } - assertEquals("AUTH_UNAVAILABLE", unavailable.getCode()); - assertEquals("PENDING", retainedOperation.get().status()); - assertEquals(null, retainedOperation.get().outcome()); - assertNotNull(retainedOperation.get().intentDigest()); - assertEquals(null, retainedOperation.get().requestDigest()); - assertEquals("AUTH_UNAVAILABLE", retainedOperation.get().lastAttemptFailureCode()); - org.mockito.Mockito.verify(transactionManager, org.mockito.Mockito.times(2)) - .commit(org.mockito.ArgumentMatchers.any()); - org.mockito.Mockito.verify(transactionManager, org.mockito.Mockito.times(1)) - .rollback(org.mockito.ArgumentMatchers.any()); - org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) - .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); - org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); + @ParameterizedTest + @CsvSource({ + "MISSING,true,JOIN_REQUIRED", + "INACTIVE,true,JOIN_REQUIRED", + "MISSING,false,PUBLIC_PRODUCTION_ADMISSION_DENIED", + "INACTIVE,false,PUBLIC_PRODUCTION_ADMISSION_DENIED" + }) + void canonicalBootstrapCharactersClassifiesPublicMembershipOnlyAfterFreshPolicy( + String lifecycle, boolean open, String code) { + var f = canonicalJoinFixture(); + f.joined.set(!lifecycle.equals("MISSING")); + f.currentMembership.setLifecycleState(lifecycle); + f.currentMembership.setGameplayAdmissionAllowed(false); + when(f.demo.allowPublicJoin()).thenReturn(open); + assertEquals(code, assertThrows(AuthenticationException.class, f::characters).getCode()); + org.mockito.Mockito.verify(f.demos, org.mockito.Mockito.atLeastOnce()).revalidate(f.demo); + verifyNoInteractions(f.roster, accountJoinOperationRepository, accountAuditOutboxRepository); + } + + @Test + void canonicalBootstrapCharactersRejectsActiveControlOnlyMembershipWithoutRepair() { + var f = canonicalJoinFixture(); + f.joined.set(true); + f.currentMembership.setGameplayAdmissionAllowed(false); + assertEquals( + "PUBLIC_PRODUCTION_ADMISSION_DENIED", + assertThrows(AuthenticationException.class, f::characters).getCode()); + verifyNoInteractions(f.roster, accountJoinOperationRepository, accountAuditOutboxRepository); } @Test - void expiredPersistedPendingJoinFailsTerminallyWithoutAuthorityOrMembershipTransition() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(sessionService.isAccountSessionActive( - org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) - .thenReturn(true); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - AtomicReference retainedScope = new AtomicReference<>(); - AtomicReference retainedOperation = - new AtomicReference<>(); - retainJoinEvidence(retainedScope, retainedOperation); - String connectScopeId = "expired-connect-scope"; - JoinPublicProductionRequest request = - new JoinPublicProductionRequest(connectScopeId, "join-expired-pending-1"); - - VerifiedJoinScope expiredScope = - new VerifiedJoinScope( - connectScopeId, - 11L, - 7L, - UUID.fromString(REALM_ID), - "demo", - "production", - PLAYABLE_STATE_NAMESPACE_ID, - "SHARED", - 44L, - 23L, - 17L, - "1999-12-31T23:59:00Z", - "2000-01-01T00:00:00Z", - ""); - expiredScope = - new VerifiedJoinScope( - expiredScope.connectScopeId(), - expiredScope.accountId(), - expiredScope.tenantId(), - expiredScope.realmId(), - expiredScope.worldSlug(), - expiredScope.realmSlug(), - expiredScope.playableStateNamespaceId(), - expiredScope.playableStateScope(), - expiredScope.gameInstanceId(), - expiredScope.catalogRevision(), - expiredScope.pointerVersion(), - expiredScope.evaluatedAt(), - expiredScope.connectScopeExpiresAt(), - net.firedevops.firemud.accountservice.dto.AccountJoinDigest.scope(expiredScope)); - retainedScope.set(expiredScope); - String callerBinding = - new JwtUtil(JWT_SECRET, 300000L) - .parseToken(bootstrap.bootstrapToken()) - .getPayload() - .get("jti") - .toString(); - retainedOperation.set( - new AccountJoinOperationRepository.JoinOperation( - expiredScope.accountId(), - expiredScope.tenantId(), - expiredScope.realmId(), - callerBinding, - net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash(connectScopeId), - expiredScope.snapshotDigest(), - "UNAVAILABLE", - null, - null, - null, - null, - "PENDING", - null, - null, - null, - null, - 1, - net.firedevops.firemud.accountservice.dto.AccountJoinDigest.intent( - request.requestId(), expiredScope, callerBinding), - "ENTITLEMENT_UNAVAILABLE", - "UNAVAILABLE")); - - JoinPublicProductionResult expiredRetry = - service.joinPublicProduction(bootstrap.bootstrapToken(), request); - var expiredTerminalOperation = retainedOperation.get(); - JoinPublicProductionResult terminalReadback = - service.joinPublicProduction(bootstrap.bootstrapToken(), request); - - assertFalse(expiredRetry.success()); - assertEquals("CONNECT_SCOPE_INVALID", expiredRetry.outcomeCode()); - assertFalse(terminalReadback.success()); - assertFalse(terminalReadback.replayed()); - assertEquals("CONNECT_SCOPE_INVALID", terminalReadback.outcomeCode()); - assertEquals(expiredTerminalOperation, retainedOperation.get()); - assertEquals("FAILED", retainedOperation.get().status()); - assertEquals("CONNECT_SCOPE_INVALID", retainedOperation.get().outcome()); - org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.times(1)) - .finish( - org.mockito.ArgumentMatchers.eq(request.requestId()), - org.mockito.ArgumentMatchers.eq("FAILED"), - org.mockito.ArgumentMatchers.eq("CONNECT_SCOPE_INVALID"), - org.mockito.ArgumentMatchers.isNull(), - org.mockito.ArgumentMatchers.isNull(), - org.mockito.ArgumentMatchers.isNull()); - verifyNoInteractions( - subscriptionRepository, accountTenantMembershipRepository, accountAuditOutboxRepository); + void canonicalBootstrapCharactersCannotInterpretBillingOutageAsMissingMembershipOrEmptyRoster() { + var f = canonicalJoinFixture(); + when(f.demos.readCurrent(f.scope.tenantId())) + .thenThrow( + new DataAccessResourceFailureException("controlled canonical entitlement outage")); + assertEquals( + "ENTITLEMENT_UNAVAILABLE", + assertThrows(AuthenticationException.class, f::characters).getCode()); + verifyNoInteractions(f.roster, accountJoinOperationRepository); } @Test - void expiredTerminalJoinScopeFailsClosedWithoutReplayingStoredSuccess() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(sessionService.isAccountSessionActive( - org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) - .thenReturn(true); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - AtomicReference retainedScope = new AtomicReference<>(); - AtomicReference retainedOperation = - new AtomicReference<>(); - retainJoinEvidence(retainedScope, retainedOperation); - String connectScopeId = "expired-committed-connect-scope"; - JoinPublicProductionRequest request = - new JoinPublicProductionRequest(connectScopeId, "join-expired-committed-1"); - VerifiedJoinScope unsignedExpiredScope = - new VerifiedJoinScope( - connectScopeId, - 11L, - 7L, - UUID.fromString(REALM_ID), - "demo", - "production", - PLAYABLE_STATE_NAMESPACE_ID, - "SHARED", - 44L, - 23L, - 17L, - "1999-12-31T23:59:00Z", - "2000-01-01T00:00:00Z", - ""); - VerifiedJoinScope expiredScope = - new VerifiedJoinScope( - unsignedExpiredScope.connectScopeId(), - unsignedExpiredScope.accountId(), - unsignedExpiredScope.tenantId(), - unsignedExpiredScope.realmId(), - unsignedExpiredScope.worldSlug(), - unsignedExpiredScope.realmSlug(), - unsignedExpiredScope.playableStateNamespaceId(), - unsignedExpiredScope.playableStateScope(), - unsignedExpiredScope.gameInstanceId(), - unsignedExpiredScope.catalogRevision(), - unsignedExpiredScope.pointerVersion(), - unsignedExpiredScope.evaluatedAt(), - unsignedExpiredScope.connectScopeExpiresAt(), - net.firedevops.firemud.accountservice.dto.AccountJoinDigest.scope( - unsignedExpiredScope)); - retainedScope.set(expiredScope); - String callerBinding = - new JwtUtil(JWT_SECRET, 300000L) - .parseToken(bootstrap.bootstrapToken()) - .getPayload() - .get("jti") - .toString(); - var committedOperation = - new AccountJoinOperationRepository.JoinOperation( - expiredScope.accountId(), - expiredScope.tenantId(), - expiredScope.realmId(), - callerBinding, - net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash(connectScopeId), - expiredScope.snapshotDigest(), - "AVAILABLE", - true, - 1L, - 1, - net.firedevops.firemud.accountservice.dto.AccountJoinDigest.request( - expiredScope, callerBinding, true, 1L), - "COMMITTED", - "JOINED", - 701L, - 1L, - 1L, - 1, - net.firedevops.firemud.accountservice.dto.AccountJoinDigest.intent( - request.requestId(), expiredScope, callerBinding), - null, - "AVAILABLE"); - retainedOperation.set(committedOperation); - - JoinPublicProductionResult retry = - service.joinPublicProduction(bootstrap.bootstrapToken(), request); - - assertFalse(retry.success()); - assertFalse(retry.replayed()); - assertEquals("CONNECT_SCOPE_INVALID", retry.outcomeCode()); - assertEquals(committedOperation, retainedOperation.get()); - assertEquals("COMMITTED", retainedOperation.get().status()); - assertEquals("JOINED", retainedOperation.get().outcome()); - assertEquals(701L, retainedOperation.get().membershipId()); - org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) - .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); - org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) - .finish( - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.nullable(Long.class), - org.mockito.ArgumentMatchers.nullable(Long.class), - org.mockito.ArgumentMatchers.nullable(Long.class)); - verifyNoInteractions(subscriptionRepository, accountAuditOutboxRepository); + void canonicalBootstrapCharactersRejectsFreshBillingDenialBeforeDisclosure() { + var f = canonicalJoinFixture(); + f.joined.set(true); + when(f.demo.gameplayAvailable()).thenReturn(false); + assertEquals( + "TENANT_BILLING_BLOCKED", + assertThrows(AuthenticationException.class, f::characters).getCode()); + verifyNoInteractions(f.roster); } @ParameterizedTest - @ValueSource(strings = {"PENDING", "COMMITTED", "FAILED"}) - void joinPublicProductionHidesAnotherAccountsGlobalRequestIdEvidence(String originalStatus) { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(sessionService.isAccountSessionActive( - org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) - .thenReturn(true); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - AtomicReference retainedScope = new AtomicReference<>(); - AtomicReference retainedOperation = - new AtomicReference<>(); - retainJoinEvidence(retainedScope, retainedOperation); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - VerifiedJoinScope scope = retainedScope.get(); - String requestId = "join-global-collision-" + originalStatus.toLowerCase(); - String originalOutcome = - switch (originalStatus) { - case "COMMITTED" -> "JOINED"; - case "FAILED" -> "PUBLIC_PRODUCTION_ADMISSION_DENIED"; - default -> null; - }; - Long originalMembershipId = "COMMITTED".equals(originalStatus) ? 812L : null; - AccountJoinOperationRepository.JoinOperation originalOperation = - new AccountJoinOperationRepository.JoinOperation( - 12L, - scope.tenantId(), - scope.realmId(), - "different-caller", - net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash(connectScopeId), - scope.snapshotDigest(), - "COMMITTED".equals(originalStatus) || "FAILED".equals(originalStatus) - ? "AVAILABLE" - : "NOT_EVALUATED", - "PENDING".equals(originalStatus) ? null : true, - "PENDING".equals(originalStatus) ? null : 7L, - "PENDING".equals(originalStatus) ? null : 1, - "PENDING".equals(originalStatus) ? null : "original-request-digest", - originalStatus, - originalOutcome, - originalMembershipId, - originalMembershipId == null ? null : 9L, - originalMembershipId == null ? null : 5L, - 1, - net.firedevops.firemud.accountservice.dto.AccountJoinDigest.intent( - requestId, scope, "different-caller"), - null, - "AVAILABLE"); - retainedOperation.set(originalOperation); - - AuthenticationException conflict = + @ValueSource(strings = {"world", "realm"}) + void canonicalBootstrapCharactersRequiresTheExactScopeRoute(String changed) { + var f = canonicalJoinFixture(); + f.joined.set(true); + assertEquals( + "CONNECT_SCOPE_MISMATCH", assertThrows( - AuthenticationException.class, - () -> - service.joinPublicProduction( - bootstrap.bootstrapToken(), - new JoinPublicProductionRequest(connectScopeId, requestId))); - - assertEquals("IDEMPOTENCY_CONFLICT", conflict.getCode()); - assertEquals("JOIN request ID was reused with different input", conflict.getMessage()); - assertFalse(conflict.getMessage().contains("JOINED")); - assertFalse(conflict.getMessage().contains("PUBLIC_PRODUCTION_ADMISSION_DENIED")); - assertFalse(conflict.getMessage().contains("812")); - assertEquals(originalOperation, retainedOperation.get()); - assertEquals(originalStatus, retainedOperation.get().status()); - assertEquals(originalOutcome, retainedOperation.get().outcome()); - assertEquals(originalMembershipId, retainedOperation.get().membershipId()); - org.mockito.Mockito.verify(accountJoinOperationRepository) - .find(org.mockito.ArgumentMatchers.eq(requestId)); - org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) - .insertIntent( - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyString()); - org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) - .bindPolicyEvidence( - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyLong(), - org.mockito.ArgumentMatchers.anyBoolean()); - org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) - .finish( - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.nullable(Long.class), - org.mockito.ArgumentMatchers.nullable(Long.class), - org.mockito.ArgumentMatchers.nullable(Long.class)); - verifyNoInteractions(accountTenantMembershipRepository, accountAuditOutboxRepository); + AuthenticationException.class, + () -> + service.listBootstrapCharacters( + f.bootstrap, + changed.equals("world") ? "another-world" : f.scope.worldSlug(), + changed.equals("realm") ? "another-realm" : f.scope.realmSlug(), + f.scope.connectScopeId())) + .getCode()); + verifyNoInteractions(f.roster); } - @Test - void reclaimedScopeRaceReturnsConnectScopeInvalid() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(sessionService.isAccountSessionActive( - org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) - .thenReturn(true); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - AtomicReference retainedScope = new AtomicReference<>(); - AtomicReference retainedOperation = - new AtomicReference<>(); - retainJoinEvidence(retainedScope, retainedOperation); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - VerifiedJoinScope scope = retainedScope.get(); - org.mockito.Mockito.clearInvocations( - subscriptionRepository, accountTenantMembershipRepository, accountAuditOutboxRepository); - when(accountConnectScopeRepository.find(connectScopeId)) - .thenReturn(Optional.of(scope), Optional.empty()); - org.mockito.Mockito.doThrow(new org.jooq.exception.DataAccessException("scope reclaimed")) - .when(accountJoinOperationRepository) - .insertIntent( - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyString()); - - AuthenticationException exception = + @ParameterizedTest + @ValueSource(strings = {"control-ui", "bootstrap-connect-scope"}) + void canonicalBootstrapCharactersRequiresTheBrowserBootstrapCredentialProfile(String audience) { + var f = canonicalJoinFixture(); + String token = + jwtUtil.generateToken( + f.scope.accountId().toString(), + Map.of( + "aud", + audience, + "accountId", + f.scope.accountId().toString(), + "jti", + UUID.randomUUID().toString())); + assertEquals( + "CONNECT_CONTEXT_INVALID", assertThrows( - AuthenticationException.class, - () -> - service.joinPublicProduction( - bootstrap.bootstrapToken(), - new JoinPublicProductionRequest(connectScopeId, "join-reclaimed-scope"))); - - assertEquals("CONNECT_SCOPE_INVALID", exception.getCode()); - verifyNoInteractions( - subscriptionRepository, accountTenantMembershipRepository, accountAuditOutboxRepository); + AuthenticationException.class, + () -> + service.listBootstrapCharacters( + token, f.scope.worldSlug(), f.scope.realmSlug(), f.scope.connectScopeId())) + .getCode()); + verifyNoInteractions(f.reader, f.targets, f.roster); } @Test - void quarantinedLegacyMembershipIsNeverRestoredByPublicJoin() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(sessionService.isAccountSessionActive( - org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) - .thenReturn(true); - AccountTenantMembership quarantined = membership(account, 7L); - quarantined.setLifecycleState("LEGACY_UNVERIFIED"); - quarantined.setGameplayAdmissionAllowed(false); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(quarantined)); - Subscription active = new Subscription(); - active.setId(22L); - active.setTenantId(7L); - active.setStatus("active"); - when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenReturn(java.util.List.of(active)); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - AtomicReference retainedScope = new AtomicReference<>(); - AtomicReference retainedOperation = - new AtomicReference<>(); - retainJoinEvidence(retainedScope, retainedOperation); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - - JoinPublicProductionResult result = - service.joinPublicProduction( - bootstrap.bootstrapToken(), - new JoinPublicProductionRequest(connectScopeId, "join-legacy-1")); - - assertFalse(result.success()); - assertEquals("MEMBERSHIP_RECONCILIATION_REQUIRED", result.outcomeCode()); - assertEquals("LEGACY_UNVERIFIED", quarantined.getLifecycleState()); - assertFalse(quarantined.isGameplayAdmissionAllowed()); - org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) - .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); - org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); - } - - private void retainJoinEvidence( - AtomicReference retainedScope, - AtomicReference retainedOperation) { - org.mockito.Mockito.doAnswer( - invocation -> { - retainedScope.set(invocation.getArgument(0)); - return null; - }) - .when(accountConnectScopeRepository) - .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); - when(accountConnectScopeRepository.find(org.mockito.ArgumentMatchers.anyString())) - .thenAnswer(invocation -> Optional.ofNullable(retainedScope.get())); - when(accountJoinOperationRepository.find(org.mockito.ArgumentMatchers.anyString())) - .thenAnswer(invocation -> Optional.ofNullable(retainedOperation.get())); - when(accountJoinOperationRepository.findForUpdate(org.mockito.ArgumentMatchers.anyString())) - .thenAnswer(invocation -> Optional.ofNullable(retainedOperation.get())); - org.mockito.Mockito.doAnswer( - invocation -> { - String requestId = invocation.getArgument(0); - VerifiedJoinScope scope = invocation.getArgument(1); - String callerBinding = invocation.getArgument(2); - String intentDigest = invocation.getArgument(3); - retainedOperation.set( - new AccountJoinOperationRepository.JoinOperation( - scope.accountId(), - scope.tenantId(), - scope.realmId(), - callerBinding, - net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash( - scope.connectScopeId()), - scope.snapshotDigest(), - "NOT_EVALUATED", - null, - null, - null, - null, - "PENDING", - null, - null, - null, - null, - 1, - intentDigest, - null, - "NOT_EVALUATED")); - return true; - }) - .when(accountJoinOperationRepository) - .insertIntent( - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyString()); - org.mockito.Mockito.doAnswer( - invocation -> { - var pending = retainedOperation.get(); - retainedOperation.set( - new AccountJoinOperationRepository.JoinOperation( - pending.accountId(), - pending.tenantId(), - pending.realmId(), - pending.callerBinding(), - pending.scopeTokenHash(), - pending.connectScopeDigest(), - "AVAILABLE", - invocation.getArgument(3), - invocation.getArgument(2), - 1, - invocation.getArgument(1), - pending.status(), - pending.outcome(), - pending.membershipId(), - pending.membershipVersion(), - pending.membershipAuthorityGeneration(), - pending.intentDigestVersion(), - pending.intentDigest(), - null, - "AVAILABLE")); - return null; - }) - .when(accountJoinOperationRepository) - .bindPolicyEvidence( - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyLong(), - org.mockito.ArgumentMatchers.anyBoolean()); - org.mockito.Mockito.doAnswer( - invocation -> { - var pending = retainedOperation.get(); - String availability = invocation.getArgument(1); - retainedOperation.set( - new AccountJoinOperationRepository.JoinOperation( - pending.accountId(), - pending.tenantId(), - pending.realmId(), - pending.callerBinding(), - pending.scopeTokenHash(), - pending.connectScopeDigest(), - pending.requestDigest() == null - ? availability - : pending.entitlementAuthorityAvailability(), - pending.allowPublicJoin(), - pending.entitlementVersion(), - pending.requestDigestVersion(), - pending.requestDigest(), - pending.status(), - pending.outcome(), - pending.membershipId(), - pending.membershipVersion(), - pending.membershipAuthorityGeneration(), - pending.intentDigestVersion(), - pending.intentDigest(), - invocation.getArgument(2), - availability)); - return null; - }) - .when(accountJoinOperationRepository) - .recordAttemptFailure( - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyString()); - org.mockito.Mockito.doAnswer( - invocation -> { - var pending = retainedOperation.get(); - retainedOperation.set( - new AccountJoinOperationRepository.JoinOperation( - pending.accountId(), - pending.tenantId(), - pending.realmId(), - pending.callerBinding(), - pending.scopeTokenHash(), - pending.connectScopeDigest(), - pending.entitlementAuthorityAvailability(), - pending.allowPublicJoin(), - pending.entitlementVersion(), - pending.requestDigestVersion(), - pending.requestDigest(), - invocation.getArgument(1), - invocation.getArgument(2), - invocation.getArgument(3), - invocation.getArgument(4), - invocation.getArgument(5), - pending.intentDigestVersion(), - pending.intentDigest(), - null, - pending.lastAttemptAuthorityAvailability())); - return null; - }) - .when(accountJoinOperationRepository) - .finish( - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.nullable(Long.class), - org.mockito.ArgumentMatchers.nullable(Long.class), - org.mockito.ArgumentMatchers.nullable(Long.class)); + void canonicalBootstrapCharactersRejectsInactiveBrowserSessionBeforeTargetOrRosterWork() { + var f = canonicalJoinFixture(); + when(sessionService.isAccountSessionActive(f.account.getId(), f.bootstrap)).thenReturn(false); + assertEquals( + "CONNECT_CONTEXT_INVALID", + assertThrows(AuthenticationException.class, f::characters).getCode()); + verifyNoInteractions(f.reader, f.targets, f.roster); } @Test - void emailLoginOtpRequestIsNeutralForUnknownEmail() { - when(accountRepository.findByEmail("unknown@example.com")).thenReturn(Optional.empty()); - - service.requestEmailLoginOtp("unknown@example.com"); - - verifyNoInteractions(emailService, accountEmailLoginChallengeRepository); - } - - @ParameterizedTest - @EnumSource( - value = AccountLifecycleState.class, - names = {"SECURITY_LOCKED", "DEACTIVATED_PENDING_DELETE", "DELETED"}) - void emailLoginOtpRequestIsNeutralForIneligibleLifecycleState( - AccountLifecycleState lifecycleState) { - Account account = new Account(); - account.setId(9L); - account.setEmail("verified@example.com"); - account.setEmailVerified(true); - account.setLifecycleState(lifecycleState); - when(accountRepository.findByEmail("verified@example.com")).thenReturn(Optional.of(account)); - - service.requestEmailLoginOtp("verified@example.com"); - - verifyNoInteractions( - accountTenantMembershipRepository, accountEmailLoginChallengeRepository, emailService); + void canonicalBootstrapCharactersPreservesReaderIdentityRefusalBeforeRosterWork() { + var f = canonicalJoinFixture(); + when(f.reader.read(f.scope.accountId(), f.scope.connectScopeId())) + .thenThrow( + new AuthenticationException( + "CONNECT_SCOPE_INVALID", "controlled Account/scope mismatch")); + assertEquals( + "CONNECT_SCOPE_INVALID", + assertThrows(AuthenticationException.class, f::characters).getCode()); + verifyNoInteractions(f.targets, f.roster); } @Test - void emailLoginOtpRequestPersistsOnlyHashedChallengeAndSendsSixDigitCode() { - Account account = new Account(); - account.setId(9L); - account.setEmail("verified@example.com"); - account.setEmailVerified(true); - when(accountRepository.findByEmail("verified@example.com")).thenReturn(Optional.of(account)); - when(accountEmailLoginChallengeRepository.findByAccountId(9L)).thenReturn(Optional.empty()); - when(accountEmailLoginChallengeRepository.save(org.mockito.ArgumentMatchers.any())) + void canonicalBootstrapCharactersRejectsTargetDriftDuringEntityReadInsteadOfReturningActors() { + var f = canonicalJoinFixture(); + f.joined.set(true); + var changed = + org.mockito.Mockito.mock(Target.class, org.mockito.AdditionalAnswers.delegatesTo(f.target)); + when(changed.activeWorldEpoch()).thenReturn(2L); + AtomicBoolean drift = new AtomicBoolean(); + org.mockito.Mockito.doAnswer( + invocation -> f.resolve(invocation.getArgument(0), drift.get() ? changed : f.target)) + .when(f.targets) + .resolvePublishedRealmAdmissionTarget(org.mockito.ArgumentMatchers.any()); + when(f.roster.read( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any())) .thenAnswer( invocation -> { - net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = - invocation.getArgument(0); - challenge.setId(3L); - return challenge; + drift.set(true); + return List.of( + new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .Actor(UUID.randomUUID(), "Ada", 12)); }); - - service.requestEmailLoginOtp("verified@example.com"); - - org.mockito.ArgumentCaptor< - net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge> - challengeCaptor = - org.mockito.ArgumentCaptor.forClass( - net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge.class); - org.mockito.Mockito.verify(accountEmailLoginChallengeRepository) - .save(challengeCaptor.capture()); - org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).lockAccountChallenge(9L); - assertEquals(9L, challengeCaptor.getValue().getAccountId()); - assertFalse(challengeCaptor.getValue().getCodeHash().matches("\\d{6}")); - org.mockito.Mockito.verify(emailService) - .sendEmail( - org.mockito.ArgumentMatchers.eq("verified@example.com"), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.matches(".*\\b\\d{6}\\b.*")); - verifyNoInteractions(accountTenantMembershipRepository); - } - - @Test - void emailLoginOtpVerificationAuthenticatesAndConsumesMatchingChallenge() { - Account account = new Account(); - account.setId(9L); - setPersistedAuthenticationIdentity(account); - account.setEmail("verified@example.com"); - account.setEmailVerified(true); - account.setRole("player"); - when(accountRepository.findByEmail("verified@example.com")).thenReturn(Optional.of(account)); - when(accountEmailLoginChallengeRepository.findByAccountId(9L)).thenReturn(Optional.empty()); - when(accountEmailLoginChallengeRepository.save(org.mockito.ArgumentMatchers.any())) - .thenAnswer(invocation -> invocation.getArgument(0)); - - service.requestEmailLoginOtp("verified@example.com"); - - org.mockito.ArgumentCaptor< - net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge> - challengeCaptor = - org.mockito.ArgumentCaptor.forClass( - net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge.class); - org.mockito.Mockito.verify(accountEmailLoginChallengeRepository) - .save(challengeCaptor.capture()); - org.mockito.ArgumentCaptor emailBodyCaptor = - org.mockito.ArgumentCaptor.forClass(String.class); - org.mockito.Mockito.verify(emailService) - .sendEmail( - org.mockito.ArgumentMatchers.eq("verified@example.com"), - org.mockito.ArgumentMatchers.anyString(), - emailBodyCaptor.capture()); - Matcher codeMatcher = Pattern.compile("\\b(\\d{6})\\b").matcher(emailBodyCaptor.getValue()); - assertTrue(codeMatcher.find()); - when(accountEmailLoginChallengeRepository.findByAccountId(9L)) - .thenReturn(Optional.of(challengeCaptor.getValue())); - - AuthenticationResult result = - service.verifyEmailLoginOtp("verified@example.com", codeMatcher.group(1)); - - assertEquals(account.getAccountUuid().toString(), result.accountId()); - assertNotNull(result.authToken()); - org.mockito.Mockito.verify(accountEmailLoginChallengeRepository) - .delete(challengeCaptor.getValue()); - org.mockito.Mockito.verify(sessionService) - .storeAccountSession( - org.mockito.ArgumentMatchers.eq(9L), - org.mockito.ArgumentMatchers.eq(result.authToken()), - org.mockito.ArgumentMatchers.eq(jwtAuthProperties.getJwtExpirationMs())); - verifyNoInteractions(accountTenantMembershipRepository); - } - - @Test - void authenticateUsesMatchingEmailLoginOtpBeforePasswordFallback() { - Account account = new Account(); - account.setId(9L); - setPersistedAuthenticationIdentity(account); - account.setEmail("demo@example.com"); - account.setPasswordHash(hash("password")); - net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = - new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); - challenge.setId(3L); - challenge.setAccountId(9L); - challenge.setCodeHash(hash("123456")); - challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(5)); - when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); - when(accountEmailLoginChallengeRepository.findByAccountId(9L)) - .thenReturn(Optional.of(challenge)); - - AuthenticationResult result = service.authenticateForGameplay("demo@example.com", "123456"); - - assertEquals(account.getAccountUuid().toString(), result.accountId()); - org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).delete(challenge); - org.mockito.Mockito.verify(sessionService) - .storeAccountSession(9L, result.authToken(), jwtAuthProperties.getJwtExpirationMs()); - verifyNoInteractions(accountTenantMembershipRepository); - } - - @Test - void authenticateFallsBackToPasswordWithoutBurningUnmatchedEmailLoginOtp() { - Account account = new Account(); - account.setId(9L); - setPersistedAuthenticationIdentity(account); - account.setEmail("demo@example.com"); - account.setPasswordHash(hash("password")); - net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = - new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); - challenge.setId(3L); - challenge.setAccountId(9L); - challenge.setCodeHash(hash("123456")); - challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(5)); - when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); - when(accountEmailLoginChallengeRepository.findByAccountId(9L)) - .thenReturn(Optional.of(challenge)); - - AuthenticationResult result = service.authenticateForGameplay("demo@example.com", "password"); - - assertEquals(account.getAccountUuid().toString(), result.accountId()); - org.mockito.Mockito.verify(accountEmailLoginChallengeRepository, org.mockito.Mockito.never()) - .delete(challenge); - org.mockito.Mockito.verify(accountEmailLoginChallengeRepository, org.mockito.Mockito.never()) - .save(challenge); - } - - @Test - void authenticateCountsFailedMixedModeSecretAgainstActiveEmailLoginOtp() { - Account account = new Account(); - account.setId(9L); - setPersistedAuthenticationIdentity(account); - account.setEmail("demo@example.com"); - account.setPasswordHash(hash("password")); - net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = - new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); - challenge.setId(3L); - challenge.setAccountId(9L); - challenge.setCodeHash(hash("123456")); - challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(5)); - when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); - when(accountEmailLoginChallengeRepository.findByAccountId(9L)) - .thenReturn(Optional.of(challenge)); - when(accountEmailLoginChallengeRepository.save(challenge)).thenReturn(challenge); - - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> service.authenticateForGameplay("demo@example.com", "wrong")); - - assertEquals(AuthenticationErrorCodes.INVALID_CREDENTIALS, exception.getCode()); - assertEquals(1, challenge.getInvalidAttemptCount()); - org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).save(challenge); - verifyNoInteractions(sessionService); - } - - @Test - void passwordOnlyAccountsDoNotIssueEmailLoginChallenges() { - Account account = new Account(); - account.setId(9L); - account.setEmail("verified@example.com"); - account.setEmailVerified(true); - account.setLoginAuthModes("PASSWORD"); - when(accountRepository.findByEmail("verified@example.com")).thenReturn(Optional.of(account)); - - service.requestEmailLoginOtp("verified@example.com"); - - verifyNoInteractions( - accountTenantMembershipRepository, accountEmailLoginChallengeRepository, emailService); - } - - @ParameterizedTest - @EnumSource(AccountIdentityProvenance.class) - void gameplayAuthenticationAcceptsEveryRecognizedPersistedUuidProvenance( - AccountIdentityProvenance provenance) { - Account account = new Account(); - account.setId(31L); - account.setEmail("retained@example.com"); - account.setPasswordHash(hash("password")); - setPersistedAuthenticationIdentity(account, provenance); - when(accountRepository.findByEmail("retained@example.com")).thenReturn(Optional.of(account)); - - AuthenticationResult result = - service.authenticateForGameplay("retained@example.com", "password"); - var claims = new JwtUtil(JWT_SECRET, 3600000L).parseToken(result.authToken()).getPayload(); - - assertEquals(account.getAccountUuid().toString(), result.accountId()); - assertEquals(account.getAccountUuid().toString(), claims.getSubject()); - assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); - assertFalse(claims.containsKey("tenantId")); - org.mockito.Mockito.verify(sessionService) - .storeAccountSession(31L, result.authToken(), jwtAuthProperties.getJwtExpirationMs()); - } - - @ParameterizedTest - @EnumSource(InvalidAuthenticationIdentity.class) - void gameplayAuthenticationRejectsUnprovedIdentityBeforeConsumingOtpOrMinting( - InvalidAuthenticationIdentity invalidIdentity) { - Account account = new Account(); - account.setId(32L); - account.setEmail("unproved@example.com"); - assignInvalidAuthenticationIdentity(account, invalidIdentity); - var challenge = new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); - challenge.setId(8L); - challenge.setAccountId(32L); - challenge.setCodeHash(hash("123456")); - challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(5)); - when(accountRepository.findByEmail("unproved@example.com")).thenReturn(Optional.of(account)); - when(accountEmailLoginChallengeRepository.findByAccountId(32L)) - .thenReturn(Optional.of(challenge)); - - AuthenticationException unavailable = - assertThrows( - AuthenticationException.class, - () -> service.authenticateForGameplay("unproved@example.com", "123456")); - assertEquals("AUTH_UNAVAILABLE", unavailable.getCode()); - - org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).lockAccountChallenge(32L); - org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).findByAccountId(32L); - org.mockito.Mockito.verify(accountEmailLoginChallengeRepository, org.mockito.Mockito.never()) - .delete(challenge); - verifyNoInteractions(sessionService); - } - - @Test - void emailLoginOtpVerificationFailsClosedForUnknownEmail() { - when(accountRepository.findByEmail("unknown@example.com")).thenReturn(Optional.empty()); - - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> service.verifyEmailLoginOtp("unknown@example.com", "123456")); - - assertEquals(AuthenticationErrorCodes.INVALID_CREDENTIALS, exception.getCode()); - verifyNoInteractions(accountEmailLoginChallengeRepository, sessionService); - } - - @Test - void emailLoginOtpVerificationLocksChallengeBeforeConsumingIt() { - Account account = new Account(); - account.setId(9L); - setPersistedAuthenticationIdentity(account); - account.setEmail("verified@example.com"); - account.setRole("player"); - net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = - new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); - challenge.setId(5L); - challenge.setAccountId(9L); - challenge.setCodeHash(hash("123456")); - challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(10)); - challenge.setInvalidAttemptCount(0); - when(accountRepository.findByEmail("verified@example.com")).thenReturn(Optional.of(account)); - when(accountEmailLoginChallengeRepository.findByAccountId(9L)) - .thenReturn(Optional.of(challenge)); - - AuthenticationResult result = service.verifyEmailLoginOtp("verified@example.com", "123456"); - - assertEquals(account.getAccountUuid().toString(), result.accountId()); - var claims = new JwtUtil(JWT_SECRET, 3600000L).parseToken(result.authToken()).getPayload(); - assertEquals("account-service", claims.getAudience().iterator().next()); - assertEquals(account.getAccountUuid().toString(), claims.getSubject()); - assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); - org.mockito.InOrder inOrder = org.mockito.Mockito.inOrder(accountEmailLoginChallengeRepository); - inOrder.verify(accountEmailLoginChallengeRepository).lockAccountChallenge(9L); - inOrder.verify(accountEmailLoginChallengeRepository).findByAccountId(9L); - inOrder.verify(accountEmailLoginChallengeRepository).delete(challenge); - } - - @Test - void authenticateReturnsControlUiTokenWithoutGameplayMembership() { - Account account = new Account(); - account.setId(1L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - - AuthenticationResult result = service.authenticate("demo", "password"); - - assertNotNull(result.authToken()); - assertEquals(account.getAccountUuid().toString(), result.accountId()); - var claims = new JwtUtil(JWT_SECRET, 3600000L).parseToken(result.authToken()).getPayload(); - assertEquals("control-ui", claims.getAudience().iterator().next()); - assertEquals(account.getAccountUuid().toString(), claims.getSubject()); - assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); - assertEquals(java.util.List.of(), claims.get("globalRoles")); - assertNotNull(claims.get("jti")); - assertFalse(claims.containsKey("tenantId")); - org.mockito.Mockito.verify(sessionService) - .storeAccountSession(1L, result.authToken(), 3600000L); - verifyNoInteractions(accountTenantMembershipRepository); - } - - @ParameterizedTest - @CsvSource({ - "SECURITY_LOCKED, AUTH_ACCOUNT_LOCKED", - "DEACTIVATED_PENDING_DELETE, AUTH_INVALID_CREDENTIALS", - "DELETED, AUTH_INVALID_CREDENTIALS" - }) - void authenticateRejectsIneligibleLifecycleState( - AccountLifecycleState lifecycleState, String expectedCode) { - Account account = new Account(); - account.setId(1L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - account.setLifecycleState(lifecycleState); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - - AuthenticationException exception = - assertThrows(AuthenticationException.class, () -> service.authenticate("demo", "password")); - - assertEquals(expectedCode, exception.getCode()); - verifyNoInteractions(sessionService); - } - - @Test - void authenticateForGameplayReturnsTokenWhenPasswordMatches() { - Account account = new Account(); - account.setId(1L); - setPersistedAuthenticationIdentity(account); - account.setEmail("demo@example.com"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); - jwtAuthProperties.setJwtSecret(null); - - AuthenticationResult result = service.authenticateForGameplay("demo@example.com", "password"); - - assertNotNull(result.authToken()); - assertEquals(account.getAccountUuid().toString(), result.accountId()); - var claims = new JwtUtil(JWT_SECRET, 3600000L).parseToken(result.authToken()).getPayload(); - assertEquals("account-service", claims.getAudience().iterator().next()); - assertEquals(account.getAccountUuid().toString(), claims.getSubject()); - assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); - assertEquals(java.util.List.of(), claims.get("globalRoles")); - assertNotNull(claims.get("jti")); - org.mockito.Mockito.verify(sessionService) - .storeAccountSession(1L, result.authToken(), jwtAuthProperties.getJwtExpirationMs()); - verifyNoInteractions(accountTenantMembershipRepository); - } - - @Test - void issuePlayerBootstrapReturnsShortLivedToken() { - Account account = new Account(); - account.setId(7L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - account.setLoginAuthModes("PASSWORD"); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - jwtAuthProperties.setJwtSecret(null); - - PlayerBootstrapResult result = service.issuePlayerBootstrap("demo", "password"); - - assertEquals(account.getAccountUuid().toString(), result.accountId()); - assertNotNull(result.bootstrapToken()); - assertNotNull(result.issuedAt()); - assertNotNull(result.expiresAt()); - org.mockito.Mockito.verify(sessionService) - .storeAccountSession( - org.mockito.ArgumentMatchers.eq(7L), - org.mockito.ArgumentMatchers.eq(result.bootstrapToken()), - org.mockito.ArgumentMatchers.eq(300000L)); - var claims = new JwtUtil(JWT_SECRET, 300000L).parseToken(result.bootstrapToken()).getPayload(); - assertEquals("player-bootstrap", claims.getAudience().iterator().next()); - assertEquals(account.getAccountUuid().toString(), claims.getSubject()); - assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); - assertFalse(claims.containsKey("tenantId")); - assertEquals(300000L, claims.getExpiration().getTime() - claims.getIssuedAt().getTime()); - when(sessionService.isAccountSessionActive(7L, result.bootstrapToken())).thenReturn(true); - var worlds = service.listBootstrapWorlds(result.bootstrapToken()); - assertEquals("demo", worlds.getFirst().worldSlug()); - org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.times(2)) - .findByAccountUuid(account.getAccountUuid()); - org.mockito.Mockito.verify(sessionService).isAccountSessionActive(7L, result.bootstrapToken()); - verifyNoInteractions(accountEmailLoginChallengeRepository); - } - - @ParameterizedTest - @EnumSource(InvalidAuthenticationIdentity.class) - void issuePlayerBootstrapRejectsUnprovedIdentityBeforeConsumingOtpOrMinting( - InvalidAuthenticationIdentity invalidIdentity) { - Account account = new Account(); - account.setId(50L); - account.setUsername("demo"); - account.setLoginAuthModes("EMAIL_OTP"); - assignInvalidAuthenticationIdentity(account, invalidIdentity); - net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = - new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); - challenge.setAccountId(50L); - challenge.setCodeHash(hash("123456")); - challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(5)); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountEmailLoginChallengeRepository.findByAccountId(50L)) - .thenReturn(Optional.of(challenge)); - - AuthenticationException unavailable = - assertThrows( - AuthenticationException.class, () -> service.issuePlayerBootstrap("demo", "123456")); - assertEquals("AUTH_UNAVAILABLE", unavailable.getCode()); - - org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).lockAccountChallenge(50L); - org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).findByAccountId(50L); - org.mockito.Mockito.verify(accountEmailLoginChallengeRepository, org.mockito.Mockito.never()) - .delete(challenge); - verifyNoInteractions(sessionService); - } - - @Test - void issuePlayerBootstrapPrefersEmailLookupOverCollidingUsername() { - Account emailAccount = new Account(); - emailAccount.setId(7L); - setPersistedAuthenticationIdentity(emailAccount); - emailAccount.setUsername("email-owner"); - emailAccount.setEmail("player@example.com"); - emailAccount.setPasswordHash(hash("password")); - emailAccount.setLoginAuthModes("PASSWORD"); - when(accountRepository.findByEmail("player@example.com")).thenReturn(Optional.of(emailAccount)); - - PlayerBootstrapResult result = - service.issuePlayerBootstrap(" PLAYER@EXAMPLE.COM ", "password"); - - assertEquals(emailAccount.getAccountUuid().toString(), result.accountId()); - org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()) - .findByUsername(org.mockito.ArgumentMatchers.anyString()); - } - - @Test - void issuePlayerBootstrapAcceptsAndConsumesEmailLoginOtp() { - Account account = new Account(); - account.setId(7L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setEmail("demo@example.com"); - account.setLoginAuthModes("EMAIL_OTP"); - net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = - new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); - challenge.setAccountId(7L); - challenge.setCodeHash(hash("123456")); - challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(5)); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountEmailLoginChallengeRepository.findByAccountId(7L)) - .thenReturn(Optional.of(challenge)); - - PlayerBootstrapResult result = service.issuePlayerBootstrap("demo", "123456"); - - assertEquals(account.getAccountUuid().toString(), result.accountId()); - org.mockito.InOrder inOrder = org.mockito.Mockito.inOrder(accountEmailLoginChallengeRepository); - inOrder.verify(accountEmailLoginChallengeRepository).lockAccountChallenge(7L); - inOrder.verify(accountEmailLoginChallengeRepository).findByAccountId(7L); - inOrder.verify(accountEmailLoginChallengeRepository).delete(challenge); - org.mockito.Mockito.verify(sessionService) - .storeAccountSession(7L, result.bootstrapToken(), 300000L); - } - - private static java.util.stream.Stream - invalidBootstrapAccountClaims() { - String valid = "10000000-0000-4000-8000-00000000000a"; - return java.util.stream.Stream.of( - org.junit.jupiter.params.provider.Arguments.of("11", "11"), - org.junit.jupiter.params.provider.Arguments.of((String) null, valid), - org.junit.jupiter.params.provider.Arguments.of( - valid.toUpperCase(java.util.Locale.ROOT), valid), - org.junit.jupiter.params.provider.Arguments.of(" " + valid, valid), - org.junit.jupiter.params.provider.Arguments.of(valid, (Object) null), - org.junit.jupiter.params.provider.Arguments.of(valid, ""), - org.junit.jupiter.params.provider.Arguments.of(valid, 11L), - org.junit.jupiter.params.provider.Arguments.of(valid, "11"), - org.junit.jupiter.params.provider.Arguments.of( - valid, "00000000-0000-0000-0000-000000000000"), - org.junit.jupiter.params.provider.Arguments.of( - "00000000-0000-0000-0000-000000000000", valid), - org.junit.jupiter.params.provider.Arguments.of(valid, "not-a-uuid"), - org.junit.jupiter.params.provider.Arguments.of( - valid, valid.toUpperCase(java.util.Locale.ROOT)), - org.junit.jupiter.params.provider.Arguments.of(valid, " " + valid), - org.junit.jupiter.params.provider.Arguments.of( - valid, "10000000-0000-4000-8000-000000000002")); - } - - @ParameterizedTest - @org.junit.jupiter.params.provider.MethodSource("invalidBootstrapAccountClaims") - void bootstrapReaderRejectsNonUuidOrContradictoryIdentityBeforeOwnerOrSessionUse( - String subject, Object accountClaim) { - Map claims = new java.util.HashMap<>(); - claims.put("aud", "player-bootstrap"); - if (accountClaim != null) { - claims.put("accountId", accountClaim); - } - String token = new JwtUtil(JWT_SECRET, 300000L).generateToken(subject, claims); - - AuthenticationException denied = - assertThrows(AuthenticationException.class, () -> service.listBootstrapWorlds(token)); - - assertEquals("CONNECT_CONTEXT_INVALID", denied.getCode()); - verifyNoInteractions(accountRepository, sessionService); - } - - @ParameterizedTest - @ValueSource(strings = {"missing", "wrong-owner-uuid", "unavailable"}) - void bootstrapReaderReportsOwnerReadbackFailureBeforeSessionUse(String failure) { - UUID uuid = UUID.fromString("10000000-0000-4000-8000-000000000001"); - if (failure.equals("unavailable")) { - when(accountRepository.findByAccountUuid(uuid)) - .thenThrow( - new org.springframework.dao.DataAccessResourceFailureException("private detail")); - } else if (failure.equals("wrong-owner-uuid")) { - Account owner = new Account(); - owner.setId(11L); - owner.setAccountUuid(UUID.randomUUID()); - owner.setAccountUuidSourceNumericId(11L); - owner.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); - when(accountRepository.findByAccountUuid(uuid)).thenReturn(Optional.of(owner)); - } - String token = - new JwtUtil(JWT_SECRET, 300000L) - .generateToken( - uuid.toString(), Map.of("aud", "player-bootstrap", "accountId", uuid.toString())); - - AuthenticationException denied = - assertThrows(AuthenticationException.class, () -> service.listBootstrapWorlds(token)); - - assertEquals("AUTH_UNAVAILABLE", denied.getCode()); - assertEquals("Account authority is unavailable", denied.getMessage()); - verifyNoInteractions(sessionService); - } - - @Test - void bootstrapReaderResolvesUuidBeforeReadingPrivateAccountSession() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - String uuid = account.getAccountUuid().toString(); - String token = - new JwtUtil(JWT_SECRET, 300000L) - .generateToken(uuid, Map.of("aud", "player-bootstrap", "accountId", uuid)); - when(sessionService.isAccountSessionActive(11L, token)).thenReturn(true); - - assertFalse(service.listBootstrapWorlds(token).isEmpty()); - - org.mockito.InOrder reads = org.mockito.Mockito.inOrder(accountRepository, sessionService); - reads.verify(accountRepository).findByAccountUuid(account.getAccountUuid()); - reads.verify(sessionService).isAccountSessionActive(11L, token); - } - - @Test - void listBootstrapWorldsRejectsInactiveAccountBootstrapToken() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - String accountUuid = account.getAccountUuid().toString(); - String bootstrapToken = - new JwtUtil(JWT_SECRET, 300000L) - .generateToken( - accountUuid, Map.of("aud", "player-bootstrap", "accountId", accountUuid)); - - AuthenticationException ex = - assertThrows( - AuthenticationException.class, () -> service.listBootstrapWorlds(bootstrapToken)); - - assertEquals("CONNECT_CONTEXT_INVALID", ex.getCode()); - assertEquals("Bootstrap token expired", ex.getMessage()); - org.mockito.Mockito.verify(sessionService).isAccountSessionActive(11L, bootstrapToken); - } - - @ParameterizedTest - @ValueSource( - strings = { - "not-a-uuid", - "abc", - "0", - "00000000-0000-0000-0000-000000000000", - "4C4B57D8-E3A2-48FE-9977-E7DF0FDCE901", - " 4c4b57d8-e3a2-48fe-9977-e7df0fdce901", - "4c4b57d8-e3a2-48fe-9977-e7df0fdce901 " - }) - void listBootstrapWorldsRejectsMalformedOrNoncanonicalBootstrapAccountUuid(String accountUuid) { - String malformedBootstrapToken = - new JwtUtil(JWT_SECRET, 300000L) - .generateToken( - accountUuid, Map.of("aud", "player-bootstrap", "accountId", accountUuid)); - - AuthenticationException ex = - assertThrows( - AuthenticationException.class, - () -> service.listBootstrapWorlds(malformedBootstrapToken)); - - assertEquals("CONNECT_CONTEXT_INVALID", ex.getCode()); - verifyNoInteractions(accountRepository, sessionService); - } - - @Test - void listBootstrapWorldsRejectsBootstrapTokenAccountSubjectMismatch() { - String malformedBootstrapToken = - new JwtUtil(JWT_SECRET, 300000L) - .generateToken( - REALM_ID, - Map.of("aud", "player-bootstrap", "accountId", PLAYABLE_STATE_NAMESPACE_ID)); - - AuthenticationException ex = - assertThrows( - AuthenticationException.class, - () -> service.listBootstrapWorlds(malformedBootstrapToken)); - - assertEquals("CONNECT_CONTEXT_INVALID", ex.getCode()); - verifyNoInteractions(accountRepository, sessionService); - } - - @Test - void listBootstrapWorldsRejectsLegacyNumericBootstrapTokenClaims() { - String malformedBootstrapToken = - new JwtUtil(JWT_SECRET, 300000L) - .generateToken("11", Map.of("aud", "player-bootstrap", "accountId", "11")); - - AuthenticationException ex = - assertThrows( - AuthenticationException.class, - () -> service.listBootstrapWorlds(malformedBootstrapToken)); - - assertEquals("CONNECT_CONTEXT_INVALID", ex.getCode()); - } - - @Test - void listBootstrapWorldsRejectsBootstrapTokenWithoutAudience() { - String malformedBootstrapToken = - new JwtUtil(JWT_SECRET, 300000L).generateToken("11", Map.of("accountId", "11")); - - AuthenticationException ex = - assertThrows( - AuthenticationException.class, - () -> service.listBootstrapWorlds(malformedBootstrapToken)); - - assertEquals("CONNECT_CONTEXT_INVALID", ex.getCode()); - } - - @Test - void listBootstrapWorldsDoesNotMaskUnexpectedJwtParserRuntimeFailure() { - JwtUtil jwtUtil = org.mockito.Mockito.mock(JwtUtil.class); - when(jwtUtil.parseToken("boom-token")).thenThrow(new IllegalStateException("boom")); - service = - new AccountServiceImpl( - accountRepository, - accountAuthorityGenerationRepository, - accountAuthoritySourceEvidenceRepository, - accountAuthorityOutboxRepository, - accountPasswordResetOperationRepository, - accountLogoutAllOperationRepository, - accountSecurityStateOperationRepository, - accountPasswordResetDraftSourceChangeRepository, - accountAuditOutboxRepository, - accountConnectScopeRepository, - accountJoinOperationRepository, - accountEmailLoginChallengeRepository, - accountRealmAccessGrantRepository, - accountTenantMembershipRepository, - Mappers.getMapper(AccountMapper.class), - profileRepository, - profileMapper, - paymentTransactionRepository, - subscriptionRepository, - externalAccountRepository, - passwordResetTokenRepository, - emailVerificationTokenRepository, - notificationService, - emailService, - mailProperties, - tokenProperties, - jwtAuthProperties, - gameSessionClient, - entityManagementClient, - jwtUtil, - sessionService, - transactionManager); - - IllegalStateException ex = - assertThrows(IllegalStateException.class, () -> service.listBootstrapWorlds("boom-token")); - - assertEquals("boom", ex.getMessage()); - } - - @Test - void listBootstrapWorldsRejectsWorldWithMalformedRuntimeRealmRow() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(gameSessionClient.listGameplayRealms("demo")) - .thenReturn( - java.util.Arrays.asList( - null, - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("demo") - .setRealmSlug("broken") - .setDisplayName("Broken Realm") - .setTenantId("bad") - .setGameInstanceId("44") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build())); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> service.listBootstrapWorlds(bootstrap.bootstrapToken())); - - assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); - } - - @Test - void listBootstrapRealmsMapsZeroPublicAuthorityFromGameSession() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(gameSessionClient.listGameplayRealms("demo")) - .thenThrow( - new IllegalStateException( - "Gameplay realm discovery failed: invalid public realm cardinality")); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo")); - - assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); - } - - @Test - void listBootstrapWorldsRejectsWorldWithUnknownStateScope() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(gameSessionClient.listGameplayRealms("demo")) - .thenReturn( - java.util.List.of( - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("demo") - .setRealmSlug("production") - .setDisplayName("Live Realm") - .setTenantId("7") - .setGameInstanceId("44") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setRequiresCharacterSelection(false) - .setStateScope("UNKNOWN") - .setCharacterCreationPolicy("ALLOW_NEW") - .build())); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> service.listBootstrapWorlds(bootstrap.bootstrapToken())); - - assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); - } - - @Test - void listBootstrapRealmsRejectsMultipleVisiblePublicRealms() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - var firstPublicRealm = gameSessionClient.listGameplayRealms("demo").getFirst(); - var secondPublicRealm = - firstPublicRealm.toBuilder() - .setRealmSlug("production-alt") - .setRealmId("57c58f36-c5ea-4aa8-8ef7-91a45e407f01") - .setGameInstanceId("45") - .build(); - when(gameSessionClient.listGameplayRealms("demo")) - .thenReturn(java.util.List.of(firstPublicRealm, secondPublicRealm)); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo")); - - assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); - } - - @Test - void listBootstrapRealmsAcceptsExactlyOneVisiblePublicRealm() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - - var realms = service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo"); - - assertEquals(1, realms.size()); - assertEquals("production", realms.getFirst().realmSlug()); - } - - @Test - void bootstrapRealmDiscoveryAndDirectTextScopeIssuanceSuspendIncomingTransactions() - throws NoSuchMethodException { - Transactional listRealms = - AccountServiceImpl.class - .getMethod("listBootstrapRealms", String.class, String.class) - .getAnnotation(Transactional.class); - Transactional issueDirectTextScope = - AccountServiceImpl.class - .getMethod( - "issueDirectTextConnectScope", - DirectTextCallerContext.class, - DirectTextJoinTarget.class) - .getAnnotation(Transactional.class); - - assertNotNull(listRealms); - assertNotNull(issueDirectTextScope); - assertEquals(Propagation.NOT_SUPPORTED, listRealms.propagation()); - assertEquals(Propagation.NOT_SUPPORTED, issueDirectTextScope.propagation()); - } - - @Test - void listBootstrapRealmsDoesNotIssueScopeWhenPublicPointerBecomesPrivateBeforeFinalRead() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - when(accountRealmAccessGrantRepository.existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( - 11L, 7L, "demo", "production")) - .thenReturn(true); - - var initiallyPublic = gameSessionClient.listGameplayRealms("demo").getFirst(); - var currentlyPrivate = initiallyPublic.toBuilder().setPublicProductionRealm(false).build(); - when(gameSessionClient.listGameplayRealms("demo")) - .thenReturn(java.util.List.of(initiallyPublic), java.util.List.of(currentlyPrivate)); - when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) - .thenReturn( - admissionPointer( - 7L, "demo", "production", "44", 17L, true, false, "SHARED", "ALLOW_NEW")); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo")); - - assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); - org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) - .insert(org.mockito.ArgumentMatchers.any()); - } - - @Test - void listBootstrapRealmsDoesNotIssueScopeWhenPointerChangesDuringDiscovery() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - - var initiallyDiscovered = gameSessionClient.listGameplayRealms("demo").getFirst(); - var changedRealmId = "57c58f36-c5ea-4aa8-8ef7-91a45e407f01"; - var currentRealm = - initiallyDiscovered.toBuilder().setRealmId(changedRealmId).setPointerVersion(18L).build(); - when(gameSessionClient.listGameplayRealms("demo")) - .thenReturn(java.util.List.of(initiallyDiscovered), java.util.List.of(currentRealm)); - when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) - .thenReturn( - admissionPointer(7L, "demo", "production", "44", 18L, true, true, "SHARED", "ALLOW_NEW") - .toBuilder() - .setRealmId(changedRealmId) - .build()); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo")); - - assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); - org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) - .insert(org.mockito.ArgumentMatchers.any()); - } - - @ParameterizedTest - @ValueSource(strings = {"101", "not-a-uuid", "4C4B57D8-E3A2-48FE-9977-E7DF0FDCE901"}) - void listBootstrapRealmsRejectsNoncanonicalRealmIds(String realmId) { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(gameSessionClient.listGameplayRealms("demo")) - .thenReturn( - java.util.List.of( - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("demo") - .setRealmSlug("production") - .setDisplayName("Live Realm") - .setTenantId("7") - .setGameInstanceId("44") - .setRealmId(realmId) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build())); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo")); - - assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); - } - - @Test - void issueConnectTokenRejectsMalformedConnectScopeId() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - Subscription active = new Subscription(); - active.setId(22L); - active.setTenantId(7L); - active.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - - AuthenticationException ex = - assertThrows( - AuthenticationException.class, - () -> - service.issueConnectToken( - bootstrap.bootstrapToken(), new ConnectTokenRequest("bad", "req-err"))); - - assertEquals("CONNECT_SCOPE_INVALID", ex.getCode()); - } - - @Test - void issueConnectTokenRejectsNumericSignedConnectCarrierWithoutReplayMutation() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String numericConnectScopeId = - new JwtUtil(JWT_SECRET, 120000L) - .generateToken( - "11", - Map.ofEntries( - Map.entry("aud", "bootstrap-connect-scope"), - Map.entry("accountId", "11"), - Map.entry("tenantId", "7"), - Map.entry("realmId", REALM_ID), - Map.entry("worldSlug", "demo"), - Map.entry("realmSlug", "production"), - Map.entry("playableStateNamespaceId", PLAYABLE_STATE_NAMESPACE_ID), - Map.entry("playableStateScope", "SHARED"), - Map.entry("gameInstanceId", "44"), - Map.entry("catalogRevision", "23"), - Map.entry("pointerVersion", "17"), - Map.entry("evaluatedAt", java.time.Instant.now().toString()), - Map.entry( - "connectScopeExpiresAt", - java.time.Instant.now().plusSeconds(60).toString()), - Map.entry("jti", "numeric-account-id"))); - - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> - service.issueConnectToken( - bootstrap.bootstrapToken(), - new ConnectTokenRequest(numericConnectScopeId, "req-numeric-account-id"))); - - assertEquals("CONNECT_SCOPE_INVALID", exception.getCode()); - org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) - .getConnectTokenReplay( - org.mockito.ArgumentMatchers.anyLong(), - org.mockito.ArgumentMatchers.anyLong(), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyString()); - org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) - .storeConnectTokenReplay( - org.mockito.ArgumentMatchers.anyLong(), - org.mockito.ArgumentMatchers.anyLong(), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.any(), - org.mockito.ArgumentMatchers.anyLong()); - } - - @Test - void issueConnectTokenRejectsBlankConnectScopeId() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - Subscription active = new Subscription(); - active.setId(22L); - active.setTenantId(7L); - active.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - - AuthenticationException ex = - assertThrows( - AuthenticationException.class, - () -> - service.issueConnectToken( - bootstrap.bootstrapToken(), new ConnectTokenRequest(" ", "req-blank-scope"))); - - assertEquals("CONNECT_SCOPE_INVALID", ex.getCode()); - } - - @Test - void issueConnectTokenRejectsNonPositiveConnectScopeClaims() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - Subscription active = new Subscription(); - active.setId(22L); - active.setTenantId(7L); - active.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String malformedConnectScopeId = - new JwtUtil(JWT_SECRET, 120000L) - .generateToken( - account.getAccountUuid().toString(), - Map.of( - "aud", - "bootstrap-connect-scope", - "accountId", - account.getAccountUuid().toString(), - "tenantId", - "7", - "worldSlug", - "demo", - "realmSlug", - "production", - "gameInstanceId", - "0", - "pointerVersion", - "17", - "connectScopeExpiresAt", - java.time.Instant.now().plusSeconds(3600).toString(), - "jti", - "invalid")); - - AuthenticationException ex = - assertThrows( - AuthenticationException.class, - () -> - service.issueConnectToken( - bootstrap.bootstrapToken(), - new ConnectTokenRequest(malformedConnectScopeId, "req-err2"))); - - assertEquals("CONNECT_SCOPE_INVALID", ex.getCode()); - } - - @Test - void issueConnectTokenRejectsMalformedConnectScopeClaims() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - Subscription active = new Subscription(); - active.setId(22L); - active.setTenantId(7L); - active.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String malformedConnectScopeId = - new JwtUtil(JWT_SECRET, 120000L) - .generateToken( - account.getAccountUuid().toString(), - Map.of( - "aud", - "bootstrap-connect-scope", - "accountId", - "abc", - "tenantId", - "7", - "worldSlug", - "demo", - "realmSlug", - "production", - "gameInstanceId", - "44", - "pointerVersion", - "17", - "connectScopeExpiresAt", - java.time.Instant.now().plusSeconds(3600).toString(), - "jti", - "invalid")); - - AuthenticationException ex = - assertThrows( - AuthenticationException.class, - () -> - service.issueConnectToken( - bootstrap.bootstrapToken(), - new ConnectTokenRequest(malformedConnectScopeId, "req-err3"))); - - assertEquals("CONNECT_SCOPE_INVALID", ex.getCode()); - } - - @ParameterizedTest - @ValueSource(strings = {"101", "not-a-uuid", "4C4B57D8-E3A2-48FE-9977-E7DF0FDCE901"}) - void issueConnectTokenRejectsNoncanonicalRealmIdClaims(String realmId) { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - Subscription active = new Subscription(); - active.setId(22L); - active.setTenantId(7L); - active.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String malformedConnectScopeId = - new JwtUtil(JWT_SECRET, 120000L) - .generateToken( - account.getAccountUuid().toString(), - Map.ofEntries( - Map.entry("aud", "bootstrap-connect-scope"), - Map.entry("accountId", account.getAccountUuid().toString()), - Map.entry("tenantId", "7"), - Map.entry("realmId", realmId), - Map.entry("worldSlug", "demo"), - Map.entry("realmSlug", "production"), - Map.entry("playableStateNamespaceId", PLAYABLE_STATE_NAMESPACE_ID), - Map.entry("playableStateScope", "SHARED"), - Map.entry("gameInstanceId", "44"), - Map.entry("catalogRevision", "23"), - Map.entry("pointerVersion", "17"), - Map.entry("evaluatedAt", java.time.Instant.now().toString()), - Map.entry( - "connectScopeExpiresAt", - java.time.Instant.now().plusSeconds(3600).toString()), - Map.entry("jti", "invalid-realm-id"))); - - AuthenticationException ex = - assertThrows( - AuthenticationException.class, - () -> - service.issueConnectToken( - bootstrap.bootstrapToken(), - new ConnectTokenRequest(malformedConnectScopeId, "req-invalid-realm-id"))); - - assertEquals("CONNECT_SCOPE_INVALID", ex.getCode()); - verifyNoInteractions(accountConnectScopeRepository); - } - - @Test - void issueConnectTokenRejectsConnectScopeAccountSubjectMismatch() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - Subscription active = new Subscription(); - active.setId(22L); - active.setTenantId(7L); - active.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String malformedConnectScopeId = - new JwtUtil(JWT_SECRET, 120000L) - .generateToken( - "4d3e9d15-a02e-41db-8648-0d2c68d0f0a3", - Map.of( - "aud", - "bootstrap-connect-scope", - "accountId", - account.getAccountUuid().toString(), - "tenantId", - "7", - "worldSlug", - "demo", - "realmSlug", - "production", - "gameInstanceId", - "44", - "pointerVersion", - "17", - "connectScopeExpiresAt", - java.time.Instant.now().plusSeconds(3600).toString(), - "jti", - "invalid")); - - AuthenticationException ex = - assertThrows( - AuthenticationException.class, - () -> - service.issueConnectToken( - bootstrap.bootstrapToken(), - new ConnectTokenRequest(malformedConnectScopeId, "req-subject-mismatch"))); - - assertEquals("CONNECT_SCOPE_INVALID", ex.getCode()); - } - - @Test - void issueConnectTokenRejectsBlankWorldSlugConnectScopeClaims() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - Subscription active = new Subscription(); - active.setId(22L); - active.setTenantId(7L); - active.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String malformedConnectScopeId = - new JwtUtil(JWT_SECRET, 120000L) - .generateToken( - account.getAccountUuid().toString(), - Map.of( - "aud", - "bootstrap-connect-scope", - "accountId", - account.getAccountUuid().toString(), - "tenantId", - "7", - "worldSlug", - " ", - "realmSlug", - "production", - "gameInstanceId", - "44", - "pointerVersion", - "17", - "connectScopeExpiresAt", - java.time.Instant.now().plusSeconds(3600).toString(), - "jti", - "invalid")); - - AuthenticationException ex = - assertThrows( - AuthenticationException.class, - () -> - service.issueConnectToken( - bootstrap.bootstrapToken(), - new ConnectTokenRequest(malformedConnectScopeId, "req-err4"))); - - assertEquals("CONNECT_SCOPE_INVALID", ex.getCode()); - } - - @Test - void issueConnectTokenRejectsZeroPointerVersionInConnectScopeClaims() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - Subscription active = new Subscription(); - active.setId(22L); - active.setTenantId(7L); - active.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String malformedConnectScopeId = - new JwtUtil(JWT_SECRET, 120000L) - .generateToken( - account.getAccountUuid().toString(), - Map.of( - "aud", - "bootstrap-connect-scope", - "accountId", - account.getAccountUuid().toString(), - "tenantId", - "7", - "worldSlug", - "demo", - "realmSlug", - "production", - "gameInstanceId", - "44", - "pointerVersion", - "0", - "connectScopeExpiresAt", - java.time.Instant.now().plusSeconds(3600).toString(), - "jti", - "invalid")); - - AuthenticationException ex = - assertThrows( - AuthenticationException.class, - () -> - service.issueConnectToken( - bootstrap.bootstrapToken(), - new ConnectTokenRequest(malformedConnectScopeId, "req-err5"))); - - assertEquals("CONNECT_SCOPE_INVALID", ex.getCode()); - } - - @Test - void authenticateForGameplayUsesNormalizedEmailLookup() { - Account account = new Account(); - account.setId(1L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setEmail("demo@example.com"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); - - AuthenticationResult result = - service.authenticateForGameplay(" DEMO@example.com ", "password"); - - assertNotNull(result.authToken()); - assertEquals(account.getAccountUuid().toString(), result.accountId()); - org.mockito.Mockito.verify(sessionService) - .storeAccountSession(1L, result.authToken(), jwtAuthProperties.getJwtExpirationMs()); - verifyNoInteractions(accountTenantMembershipRepository); - org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()) - .findByUsername(org.mockito.ArgumentMatchers.anyString()); - } - - @Test - void authenticateThrowsWhenInvalid() { - when(accountRepository.findByEmail("demo")).thenReturn(Optional.empty()); - AuthenticationException exception = - assertThrows( - AuthenticationException.class, () -> service.authenticateForGameplay("demo", "bad")); - assertEquals(AuthenticationErrorCodes.INVALID_CREDENTIALS, exception.getCode()); - } - - @Test - void authenticateDoesNotUseGlobalAccountFallback() { - when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.empty()); - - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> service.authenticateForGameplay("demo@example.com", "password")); - - assertEquals(AuthenticationErrorCodes.INVALID_CREDENTIALS, exception.getCode()); - org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()) - .findByUsername(org.mockito.ArgumentMatchers.anyString()); - } - - @Test - void authenticateAllowsGlobalIdentityWithoutTenantMembership() { - Account account = new Account(); - account.setId(7L); - setPersistedAuthenticationIdentity(account); - account.setEmail("demo@example.com"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); - AuthenticationResult result = service.authenticateForGameplay("demo@example.com", "password"); - - assertEquals(account.getAccountUuid().toString(), result.accountId()); - assertNotNull(result.authToken()); - org.mockito.Mockito.verify(sessionService) - .storeAccountSession(7L, result.authToken(), jwtAuthProperties.getJwtExpirationMs()); - verifyNoInteractions(accountTenantMembershipRepository); - } - - @Test - void getTenantMembershipForRuntimeReturnsAdmissionAllowedForExistingAccount() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setEmail("demo@example.com"); - account.setPasswordHash(hash("password")); - AccountTenantMembership activeMembership = membership(account, 7L); - activeMembership.setMembershipVersion(17L); - activeMembership.setMembershipAuthorityGeneration(29L); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(activeMembership)); - - var dto = service.getTenantMembershipForRuntime(11L, 7L, "req-1"); - - assertEquals(11L, dto.accountId()); - assertEquals(7L, dto.tenantId()); - assertTrue(dto.membershipExists()); - assertTrue(dto.gameplayAdmissionAllowed()); - assertEquals(17L, dto.membershipVersion()); - assertEquals("ACTIVE", dto.membershipLifecycleState()); - assertEquals(29L, dto.membershipAuthorityGeneration()); - assertNotNull(dto.evaluatedAt()); - } - - @Test - void getTenantMembershipForRuntimeReturnsCoherentMissingMembershipForExistingAccount() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setEmail("demo@example.com"); - account.setPasswordHash(hash("password")); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.empty()); - - var dto = service.getTenantMembershipForRuntime(11L, 7L, "req-1"); - - assertEquals(11L, dto.accountId()); - assertEquals(7L, dto.tenantId()); - assertFalse(dto.membershipExists()); - assertFalse(dto.gameplayAdmissionAllowed()); - assertEquals(0L, dto.membershipVersion()); - assertEquals("MISSING", dto.membershipLifecycleState()); - assertEquals(0L, dto.membershipAuthorityGeneration()); - assertNotNull(dto.evaluatedAt()); - } - - @Test - void getTenantMembershipForRuntimeReturnsInactiveMembershipWithIndependentGenerations() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setEmail("demo@example.com"); - account.setPasswordHash(hash("password")); - AccountTenantMembership inactiveMembership = membership(account, 7L); - inactiveMembership.setGameplayAdmissionAllowed(false); - inactiveMembership.setLifecycleState("INACTIVE"); - inactiveMembership.setMembershipVersion(23L); - inactiveMembership.setMembershipAuthorityGeneration(41L); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(inactiveMembership)); - - var dto = service.getTenantMembershipForRuntime(11L, 7L, "req-1"); - - assertEquals(11L, dto.accountId()); - assertEquals(7L, dto.tenantId()); - assertTrue(dto.membershipExists()); - assertFalse(dto.gameplayAdmissionAllowed()); - assertEquals(23L, dto.membershipVersion()); - assertEquals("INACTIVE", dto.membershipLifecycleState()); - assertEquals(41L, dto.membershipAuthorityGeneration()); - assertNotNull(dto.evaluatedAt()); - } + assertEquals( + "CONNECT_SCOPE_MISMATCH", + assertThrows(AuthenticationException.class, f::characters).getCode()); + verifyNoInteractions(accountJoinOperationRepository, accountAuditOutboxRepository); + } @Test - void getTenantMembershipForRuntimeRejectsMissingAccount() { - when(accountRepository.findById(11L)).thenReturn(Optional.empty()); - - assertThrows( - IllegalArgumentException.class, - () -> service.getTenantMembershipForRuntime(11L, 7L, "req-1")); + void canonicalBootstrapCharactersRechecksMembershipAfterEntityRead() { + var f = canonicalJoinFixture(); + f.joined.set(true); + when(f.roster.read( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + f.currentMembership.setLifecycleState("INACTIVE"); + f.currentMembership.setGameplayAdmissionAllowed(false); + return List.of( + new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .Actor(UUID.randomUUID(), "Ada", 12)); + }); + var failure = assertThrows(AuthenticationException.class, f::characters); + assertEquals("AUTH_UNAVAILABLE", failure.getCode()); + assertEquals("Bootstrap membership changed during discovery", failure.getMessage()); + org.mockito.Mockito.verify(f.roster) + .read( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any()); + verifyNoInteractions(accountJoinOperationRepository, accountAuditOutboxRepository); } @ParameterizedTest - @CsvSource({ - "active,true,true", - "trialing,true,true", - "past_due,true,true", - "grace,true,false", - "canceled,false,false", - "unknown,false,false" - }) - void getTenantEntitlementsForRuntimeUsesCurrentSubscriptions( - String status, boolean gameplayAvailable, boolean allowPublicJoin) { - Subscription active = new Subscription(); - active.setId(31L); - active.setTenantId(7L); - active.setStatus(status); - active.setEntitlementVersion(9L); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); - - var dto = service.getTenantEntitlementsForRuntime(7L, "req-2"); - - assertEquals(7L, dto.tenantId()); - assertEquals(gameplayAvailable, dto.gameplayAvailable()); - assertEquals(allowPublicJoin, dto.allowPublicJoin()); - assertEquals(9L, dto.entitlementVersion()); - assertEquals(9L, dto.tenantBillingSequence()); - assertNotNull(dto.evaluatedAt()); + @ValueSource(strings = {"version", "generation", "membership-id"}) + void canonicalBootstrapCharactersRejectsChangedMembershipSnapshotAfterEntityRead(String changed) { + var f = canonicalJoinFixture(); + f.joined.set(true); + when(f.roster.read( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + switch (changed) { + case "version" -> + f.currentMembership.setMembershipVersion( + f.currentMembership.getMembershipVersion() + 1L); + case "generation" -> + f.currentMembership.setMembershipAuthorityGeneration( + f.currentMembership.getMembershipAuthorityGeneration() + 1L); + case "membership-id" -> f.currentMembership.setId(702L); + default -> throw new AssertionError(changed); + } + return List.of( + new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .Actor(UUID.randomUUID(), "Withheld", 12)); + }); + assertEquals( + "AUTH_UNAVAILABLE", assertThrows(AuthenticationException.class, f::characters).getCode()); + verifyNoInteractions(accountJoinOperationRepository, accountAuditOutboxRepository); } @Test - void getTenantEntitlementsForRuntimeTreatsMissingSubscriptionAsUnavailable() { - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of()); - - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> service.getTenantEntitlementsForRuntime(7L, "req-missing-entitlement")); - - assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); + void canonicalBootstrapCharactersRejectsChangedPublishedPolicyCaptureAfterEntityRead() { + var f = canonicalJoinFixture(); + f.joined.set(true); + when(f.roster.read( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + f.policyBytes = + "changed-controlled-policy-set".getBytes(java.nio.charset.StandardCharsets.UTF_8); + return List.of( + new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .Actor(UUID.randomUUID(), "Withheld", 12)); + }); + assertEquals( + "CONNECT_SCOPE_MISMATCH", + assertThrows(AuthenticationException.class, f::characters).getCode()); + verifyNoInteractions(accountJoinOperationRepository, accountAuditOutboxRepository); } @Test - void getTenantEntitlementsForRuntimeTreatsMixedSubscriptionRowsAsUnavailable() { - Subscription active = new Subscription(); - active.setId(31L); - active.setTenantId(7L); - active.setStatus("active"); - Subscription canceled = new Subscription(); - canceled.setId(32L); - canceled.setTenantId(7L); - canceled.setStatus("canceled"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active, canceled)); - - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> service.getTenantEntitlementsForRuntime(7L, "req-ambiguous-entitlement")); - - assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); + void canonicalBootstrapCharactersRechecksCurrentEntitlementAfterEntityRead() { + var f = canonicalJoinFixture(); + f.joined.set(true); + when(f.roster.read( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + when(f.demos.readCurrent(f.scope.tenantId())) + .thenThrow( + new DataAccessResourceFailureException("controlled late billing outage")); + when(f.demos.revalidate(f.demo)) + .thenThrow( + new DataAccessResourceFailureException("controlled late billing outage")); + return List.of( + new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .Actor(UUID.randomUUID(), "Ada", 12)); + }); + assertEquals( + "ENTITLEMENT_UNAVAILABLE", + assertThrows(AuthenticationException.class, f::characters).getCode()); + verifyNoInteractions(accountJoinOperationRepository, accountAuditOutboxRepository); } @Test - void issueDirectTextConnectScopeRejectsUnavailableEntitlementWithoutRetainingScope() { - Account account = directTextAccount(); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of()); - - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> service.issueDirectTextConnectScope(directTextCaller(), directTextTarget())); - - assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); - org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) - .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); + void canonicalBootstrapCharactersCannotTranslateEntityOutageIntoSuccessfulEmptyDiscovery() { + var f = canonicalJoinFixture(); + f.joined.set(true); + when(f.roster.read( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any())) + .thenThrow(new IllegalStateException("controlled Entity discovery unavailable")); + assertEquals( + "AUTH_UNAVAILABLE", assertThrows(AuthenticationException.class, f::characters).getCode()); + verifyNoInteractions(accountJoinOperationRepository, accountAuditOutboxRepository); + } + + @Test + void canonicalBootstrapCharactersRefusesScopeThatExpiresDuringEntityRead() { + var f = canonicalJoinFixture(); + f.joined.set(true); + var time = + new java.util.concurrent.atomic.AtomicReference<>( + Instant.parse(f.scope.evaluatedAt()).plusSeconds(1)); + f.compose( + new Clock() { + @Override + public java.time.ZoneId getZone() { + return java.time.ZoneOffset.UTC; + } + + @Override + public Clock withZone(java.time.ZoneId zone) { + return this; + } + + @Override + public Instant instant() { + return time.get(); + } + }); + when(f.roster.read( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + time.set(Instant.parse(f.scope.connectScopeExpiresAt())); + return List.of( + new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .Actor(UUID.randomUUID(), "Ada", 12)); + }); + assertEquals( + "CONNECT_SCOPE_INVALID", + assertThrows(AuthenticationException.class, f::characters).getCode()); + verifyNoInteractions(accountJoinOperationRepository, accountAuditOutboxRepository); } @ParameterizedTest - @ValueSource(strings = {"", " "}) - void issueDirectTextConnectScopeRejectsBlankRequestIdBeforeAuthorityOrScopeWork( - String requestId) { - DirectTextCallerContext caller = - new DirectTextCallerContext( - 11L, - 7L, - UUID.fromString(REALM_ID), - PLAYABLE_STATE_NAMESPACE_ID, - "SHARED", - 44L, - "session-1", - requestId); - - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> service.issueDirectTextConnectScope(caller, directTextTarget())); + @ValueSource(strings = {"tenant", "realm", "namespace", "instance", "catalog", "pointer"}) + void canonicalBootstrapCharactersCannotDiscloseForAChangedRetainedTargetField(String field) { + var f = canonicalJoinFixture(); + f.joined.set(true); + switch (field) { + case "tenant" -> when(f.target.canonicalTenantId()).thenReturn(UUID.randomUUID()); + case "realm" -> when(f.target.realmId()).thenReturn(UUID.randomUUID()); + case "namespace" -> when(f.target.playableStateNamespaceId()).thenReturn(UUID.randomUUID()); + case "instance" -> when(f.target.canonicalGameInstanceId()).thenReturn(UUID.randomUUID()); + case "catalog" -> when(f.target.catalogRevision()).thenReturn(f.scope.catalogRevision() + 1L); + case "pointer" -> when(f.target.pointerVersion()).thenReturn(f.scope.pointerVersion() + 1L); + default -> throw new AssertionError(field); + } + assertEquals( + "CONNECT_SCOPE_MISMATCH", + assertThrows(AuthenticationException.class, f::characters).getCode()); + verifyNoInteractions(f.roster); + } - assertEquals("CONNECT_SCOPE_INVALID", exception.getCode()); - verifyNoInteractions(accountRepository, subscriptionRepository, accountConnectScopeRepository); + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void canonicalBootstrapCharactersRefusesAmbientSqlBeforeCallerOrRemoteRead( + boolean synchronization) { + var f = canonicalJoinFixture(); + try { + if (synchronization) TransactionSynchronizationManager.initSynchronization(); + else TransactionSynchronizationManager.setActualTransactionActive(true); + assertThrows(IllegalStateException.class, f::characters); + verifyNoInteractions(f.reader, f.targets, f.roster); + } finally { + TransactionSynchronizationManager.clear(); + } } @Test - void issueDirectTextConnectScopeRejectsBillingBlockedEntitlementWithoutRetainingScope() { - Account account = directTextAccount(); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - Subscription canceled = new Subscription(); - canceled.setId(31L); - canceled.setTenantId(7L); - canceled.setStatus("canceled"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(canceled)); + void canonicalBootstrapCharactersRechecksTheBrowserRegistryAfterEntityRead() { + var f = canonicalJoinFixture(); + f.joined.set(true); + when(f.roster.read( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + when(sessionService.isAccountSessionActive(f.account.getId(), f.bootstrap)) + .thenReturn(false); + return List.of( + new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .Actor(UUID.randomUUID(), "Withheld", 12)); + }); + assertEquals( + "CONNECT_CONTEXT_INVALID", + assertThrows(AuthenticationException.class, f::characters).getCode()); + verifyNoInteractions(accountJoinOperationRepository, accountAuditOutboxRepository); + } - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> service.issueDirectTextConnectScope(directTextCaller(), directTextTarget())); + @ParameterizedTest + @CsvSource({"FAILED_PRECONDITION,CONNECT_SCOPE_MISMATCH", "UNAVAILABLE,AUTH_UNAVAILABLE"}) + void canonicalBootstrapCharactersPreservesEntityCurrentnessAndUnavailableFailureBoundaries( + String status, String code) { + var f = canonicalJoinFixture(); + f.joined.set(true); + when(f.roster.read( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any())) + .thenThrow( + io.grpc.Status.fromCode(io.grpc.Status.Code.valueOf(status)).asRuntimeException()); + assertEquals(code, assertThrows(AuthenticationException.class, f::characters).getCode()); + verifyNoInteractions(accountJoinOperationRepository, accountAuditOutboxRepository); + } + + /** + * ISOLATED positive discovery remains unfinished; a public V2 carrier cannot select its policy. + */ + @Test + void canonicalBootstrapCharactersExplicitlyRefusesUnsupportedIsolatedScope() { + var f = canonicalJoinFixture(); + var isolated = + new CanonicalJoinScopeV2( + f.scope.connectScopeId(), + f.scope.accountId(), + f.scope.tenantId(), + f.scope.realmId(), + f.scope.tenantSlug(), + f.scope.worldSlug(), + f.scope.realmSlug(), + f.scope.playableStateNamespaceId(), + "ISOLATED", + f.scope.gameInstanceId(), + f.scope.catalogRevision(), + f.scope.pointerVersion(), + f.scope.evaluatedAt(), + f.scope.connectScopeExpiresAt()); + when(f.reader.read(f.scope.accountId(), f.scope.connectScopeId())).thenReturn(isolated); + assertEquals( + "REALM_UNAVAILABLE", assertThrows(AuthenticationException.class, f::characters).getCode()); + verifyNoInteractions(f.targets, f.roster); + } - assertEquals("TENANT_BILLING_BLOCKED", exception.getCode()); - assertEquals("Gameplay is not available for this tenant", exception.getMessage()); - org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) - .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); + /** + * Controlled late-owner refusal only; retained resolution still rejects unsupported policies. + * PLAYER_CREATED/AUTO/private/ISOLATED positive branches remain unfinished. + */ + @ParameterizedTest + @ValueSource(strings = {"PLAYER_CREATED", "AUTO_PROVISIONED"}) + void canonicalBootstrapCharactersRejectsUnsupportedPolicyFromLateControlledOwnerRead( + String policy) { + var f = canonicalJoinFixture(); + f.joined.set(true); + // Retained resolution admits PRESEEDED_ONLY only. Change this controlled owner response + // after that check to exercise the facade's own unsupported-policy refusal, not the codec. + when(f.targets.readPublishedRealmAdmissionOwner(org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + when(f.target.characterCreationPolicy()).thenReturn(policy); + var published = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.gamesession + .CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence + .class); + when(published.selector()).thenReturn(invocation.getArgument(0)); + when(published.currentTarget()).thenReturn(f.target); + return published; + }); + var failure = assertThrows(AuthenticationException.class, f::characters); + assertEquals("REALM_UNAVAILABLE", failure.getCode()); + assertEquals( + "Bootstrap actor discovery does not yet support this realm policy", failure.getMessage()); + org.mockito.Mockito.verify(f.targets) + .readPublishedRealmAdmissionOwner(org.mockito.ArgumentMatchers.any()); + verifyNoInteractions(f.sources, f.demos, f.roster); } @Test - void issueDirectTextConnectScopeRetainsScopeForActiveEntitlement() { - Account account = directTextAccount(); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + void emailLoginOtpRequestIsNeutralForUnknownEmail() { + when(accountRepository.findByEmail("unknown@example.com")).thenReturn(Optional.empty()); - DirectTextJoinScope result = - service.issueDirectTextConnectScope(directTextCaller(), directTextTarget()); + service.requestEmailLoginOtp("unknown@example.com"); - var claims = jwtUtil.parseToken(result.connectScopeId()).getPayload(); - assertEquals(account.getAccountUuid().toString(), claims.getSubject()); - assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); - assertNotNull(result.connectScopeId()); - assertNotNull(result.connectScopeExpiresAt()); - assertEquals(result.evaluatedAt(), claims.get("evaluatedAt", String.class)); - var retained = org.mockito.ArgumentCaptor.forClass(VerifiedJoinScope.class); - org.mockito.Mockito.verify(accountConnectScopeRepository).insert(retained.capture()); - assertEquals(result.evaluatedAt(), retained.getValue().evaluatedAt()); - assertEquals(result.connectScopeExpiresAt(), retained.getValue().connectScopeExpiresAt()); + verifyNoInteractions(emailService, accountEmailLoginChallengeRepository); } - @Test - void graceAllowsDirectScopeDiscoveryWithoutPublicJoinAuthority() { - Account account = directTextAccount(); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - Subscription grace = new Subscription(); - grace.setTenantId(7L); - grace.setStatus("grace"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(List.of(grace)); - - var entitlement = service.getTenantEntitlementsForRuntime(7L, "grace-discovery"); - DirectTextJoinScope scope = - service.issueDirectTextConnectScope(directTextCaller(), directTextTarget()); - - assertTrue(entitlement.gameplayAvailable()); - assertFalse(entitlement.allowPublicJoin()); - assertNotNull(scope.connectScopeId()); - org.mockito.Mockito.verify(accountConnectScopeRepository) - .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); + @ParameterizedTest + @EnumSource( + value = AccountLifecycleState.class, + names = {"SECURITY_LOCKED", "DEACTIVATED_PENDING_DELETE", "DELETED"}) + void emailLoginOtpRequestIsNeutralForIneligibleLifecycleState( + AccountLifecycleState lifecycleState) { + Account account = new Account(); + account.setId(9L); + account.setEmail("verified@example.com"); + account.setEmailVerified(true); + account.setLifecycleState(lifecycleState); + when(accountRepository.findByEmail("verified@example.com")).thenReturn(Optional.of(account)); + + service.requestEmailLoginOtp("verified@example.com"); + verifyNoInteractions( - accountJoinOperationRepository, - accountTenantMembershipRepository, - accountAuditOutboxRepository); + accountTenantMembershipRepository, accountEmailLoginChallengeRepository, emailService); } @Test - void bothScopeProducersBindPersistedUuidWhileRetainedRowsKeepPrivateAccountKey() { - Account account = directTextAccount(); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String browser = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - String direct = - service - .issueDirectTextConnectScope(directTextCaller(), directTextTarget()) - .connectScopeId(); - for (String token : java.util.List.of(browser, direct)) { - var claims = jwtUtil.parseToken(token).getPayload(); - assertEquals(account.getAccountUuid().toString(), claims.getSubject()); - assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); - AuthenticationException held = - assertThrows( - AuthenticationException.class, - () -> - service.issueConnectToken( - bootstrap.bootstrapToken(), new ConnectTokenRequest(token, "held-proof"))); - assertEquals("AUTH_UNAVAILABLE", held.getCode()); - } - var retained = org.mockito.ArgumentCaptor.forClass(VerifiedJoinScope.class); - org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.times(2)) - .insert(retained.capture()); - for (VerifiedJoinScope row : retained.getAllValues()) { - assertEquals(11L, row.accountId()); - assertEquals( - net.firedevops.firemud.accountservice.dto.AccountJoinDigest.scope(row), - row.snapshotDigest()); - } + void emailLoginOtpRequestPersistsOnlyHashedChallengeAndSendsSixDigitCode() { + Account account = new Account(); + account.setId(9L); + account.setEmail("verified@example.com"); + account.setEmailVerified(true); + when(accountRepository.findByEmail("verified@example.com")).thenReturn(Optional.of(account)); + when(accountEmailLoginChallengeRepository.findByAccountId(9L)).thenReturn(Optional.empty()); + when(accountEmailLoginChallengeRepository.save(org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = + invocation.getArgument(0); + challenge.setId(3L); + return challenge; + }); + + service.requestEmailLoginOtp("verified@example.com"); + + org.mockito.ArgumentCaptor< + net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge> + challengeCaptor = + org.mockito.ArgumentCaptor.forClass( + net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge.class); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository) + .save(challengeCaptor.capture()); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).lockAccountChallenge(9L); + assertEquals(9L, challengeCaptor.getValue().getAccountId()); + assertFalse(challengeCaptor.getValue().getCodeHash().matches("\\d{6}")); + org.mockito.Mockito.verify(emailService) + .sendEmail( + org.mockito.ArgumentMatchers.eq("verified@example.com"), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.matches(".*\\b\\d{6}\\b.*")); + verifyNoInteractions(accountTenantMembershipRepository); } @Test - void scopeReaderOwnerFailureIsUnavailableAndNumericScopesNeverReachOwnerLookup() { - Account account = directTextAccount(); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - String scope = - service - .issueDirectTextConnectScope(directTextCaller(), directTextTarget()) - .connectScopeId(); - var decoded = new java.util.HashMap(jwtUtil.parseToken(scope).getPayload()); - decoded.remove("iat"); - decoded.remove("exp"); - decoded.put("sub", "11"); - decoded.put("accountId", "11"); - String numeric = new JwtUtil(JWT_SECRET, 120000L).generateToken("11", decoded); - org.mockito.Mockito.clearInvocations(accountRepository); - AuthenticationException invalid = - assertThrows( - AuthenticationException.class, - () -> - service.joinPublicProductionFromGameSession( - directTextCaller(), - new JoinPublicProductionRequest(numeric, directTextCaller().requestId()))); - assertEquals("CONNECT_SCOPE_INVALID", invalid.getCode()); - org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()) - .findByAccountUuid(org.mockito.ArgumentMatchers.any()); - when(accountRepository.findByAccountUuid(account.getAccountUuid())) - .thenThrow( - new org.springframework.dao.DataAccessResourceFailureException("private detail")); - AuthenticationException unavailable = - assertThrows( - AuthenticationException.class, - () -> - service.joinPublicProductionFromGameSession( - directTextCaller(), - new JoinPublicProductionRequest(scope, directTextCaller().requestId()))); - assertEquals("AUTH_UNAVAILABLE", unavailable.getCode()); - } + void emailLoginOtpVerificationAuthenticatesAndConsumesMatchingChallenge() { + Account account = new Account(); + account.setId(9L); + setPersistedAuthenticationIdentity(account); + account.setEmail("verified@example.com"); + account.setEmailVerified(true); + account.setRole("player"); + when(accountRepository.findByEmail("verified@example.com")).thenReturn(Optional.of(account)); + when(accountEmailLoginChallengeRepository.findByAccountId(9L)).thenReturn(Optional.empty()); + when(accountEmailLoginChallengeRepository.save(org.mockito.ArgumentMatchers.any())) + .thenAnswer(invocation -> invocation.getArgument(0)); - @ParameterizedTest - @EnumSource(UnavailableEntitlement.class) - void runtimeAndDirectScopeTreatUnsafeEntitlementAsUnavailable(UnavailableEntitlement failure) { - when(subscriptionRepository.findByTenantId(7L)).thenAnswer(invocation -> failure.rows()); + service.requestEmailLoginOtp("verified@example.com"); - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> service.getTenantEntitlementsForRuntime(7L, "req-entitlement-store-failure")); + org.mockito.ArgumentCaptor< + net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge> + challengeCaptor = + org.mockito.ArgumentCaptor.forClass( + net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge.class); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository) + .save(challengeCaptor.capture()); + org.mockito.ArgumentCaptor emailBodyCaptor = + org.mockito.ArgumentCaptor.forClass(String.class); + org.mockito.Mockito.verify(emailService) + .sendEmail( + org.mockito.ArgumentMatchers.eq("verified@example.com"), + org.mockito.ArgumentMatchers.anyString(), + emailBodyCaptor.capture()); + Matcher codeMatcher = Pattern.compile("\\b(\\d{6})\\b").matcher(emailBodyCaptor.getValue()); + assertTrue(codeMatcher.find()); + when(accountEmailLoginChallengeRepository.findByAccountId(9L)) + .thenReturn(Optional.of(challengeCaptor.getValue())); - assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); - assertSame(failure.cause, exception.getCause()); + AuthenticationResult result = + service.verifyEmailLoginOtp("verified@example.com", codeMatcher.group(1)); - Account account = directTextAccount(); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - AuthenticationException scopeFailure = - assertThrows( - AuthenticationException.class, - () -> service.issueDirectTextConnectScope(directTextCaller(), directTextTarget())); - assertEquals("ENTITLEMENT_UNAVAILABLE", scopeFailure.getCode()); - assertSame(failure.cause, scopeFailure.getCause()); - org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) - .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); - verifyNoInteractions(accountTenantMembershipRepository, accountAuditOutboxRepository); + assertEquals(account.getAccountUuid().toString(), result.accountId()); + assertNotNull(result.authToken()); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository) + .delete(challengeCaptor.getValue()); + org.mockito.Mockito.verify(sessionService) + .storeAccountSession( + org.mockito.ArgumentMatchers.eq(9L), + org.mockito.ArgumentMatchers.eq(result.authToken()), + org.mockito.ArgumentMatchers.eq(jwtAuthProperties.getJwtExpirationMs())); + verifyNoInteractions(accountTenantMembershipRepository); } - @ParameterizedTest - @ValueSource(strings = {"mapping", "configuration"}) - void runtimeAndDirectScopePropagateEntitlementProgrammingFaults(String fault) { - RuntimeException cause = entitlementProgrammingFault(fault); - when(subscriptionRepository.findByTenantId(7L)).thenThrow(cause); + @Test + void authenticateUsesMatchingEmailLoginOtpBeforePasswordFallback() { + Account account = new Account(); + account.setId(9L); + setPersistedAuthenticationIdentity(account); + account.setEmail("demo@example.com"); + account.setPasswordHash(hash("password")); + net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = + new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); + challenge.setId(3L); + challenge.setAccountId(9L); + challenge.setCodeHash(hash("123456")); + challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(5)); + when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); + when(accountEmailLoginChallengeRepository.findByAccountId(9L)) + .thenReturn(Optional.of(challenge)); + + AuthenticationResult result = service.authenticateForGameplay("demo@example.com", "123456"); - assertSame( - cause, - assertThrows( - cause.getClass(), () -> service.getTenantEntitlementsForRuntime(7L, "req-fault"))); - Account account = directTextAccount(); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - assertSame( - cause, - assertThrows( - cause.getClass(), - () -> service.issueDirectTextConnectScope(directTextCaller(), directTextTarget()))); - org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) - .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); - verifyNoInteractions(accountTenantMembershipRepository, accountAuditOutboxRepository); + assertEquals(account.getAccountUuid().toString(), result.accountId()); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).delete(challenge); + org.mockito.Mockito.verify(sessionService) + .storeAccountSession(9L, result.authToken(), jwtAuthProperties.getJwtExpirationMs()); + verifyNoInteractions(accountTenantMembershipRepository); } @Test - void issueConnectTokenFailsClosedBeforeLegacyIssuanceOrReplayState() { - ConnectScopeFixture fixture = prepareConnectScopeForIssue(); - org.mockito.Mockito.clearInvocations( - sessionService, - accountTenantMembershipRepository, - gameSessionClient, - subscriptionRepository); + void authenticateFallsBackToPasswordWithoutBurningUnmatchedEmailLoginOtp() { + Account account = new Account(); + account.setId(9L); + setPersistedAuthenticationIdentity(account); + account.setEmail("demo@example.com"); + account.setPasswordHash(hash("password")); + net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = + new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); + challenge.setId(3L); + challenge.setAccountId(9L); + challenge.setCodeHash(hash("123456")); + challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(5)); + when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); + when(accountEmailLoginChallengeRepository.findByAccountId(9L)) + .thenReturn(Optional.of(challenge)); - AuthenticationException unavailable = - assertThrows( - AuthenticationException.class, - () -> - service.issueConnectToken( - fixture.bootstrapToken(), - new ConnectTokenRequest(fixture.connectScopeId(), "req-unavailable"))); + AuthenticationResult result = service.authenticateForGameplay("demo@example.com", "password"); - assertEquals("AUTH_UNAVAILABLE", unavailable.getCode()); - assertNoLegacyConnectTokenEffects(); + assertEquals(account.getAccountUuid().toString(), result.accountId()); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository, org.mockito.Mockito.never()) + .delete(challenge); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository, org.mockito.Mockito.never()) + .save(challenge); } @Test - void issueConnectTokenDoesNotReturnCachedLegacySuccess() { - ConnectScopeFixture fixture = prepareConnectScopeForIssue(); - org.mockito.Mockito.clearInvocations( - sessionService, - accountTenantMembershipRepository, - gameSessionClient, - subscriptionRepository); - ConnectTokenResult cachedLegacySuccess = - new ConnectTokenResult( - 11L, - 7L, - 44L, - "production", - fixture.connectScopeId(), - "legacy-hmac-connect-token", - "legacy-jti", - "req-cached-success", - "2026-10-14T00:00:00Z", - "2026-10-14T00:00:30Z", - false); - when(sessionService.getConnectTokenReplay( - 7L, 11L, fixture.connectScopeId(), "req-cached-success")) - .thenReturn( - Optional.of(new SessionService.ConnectTokenReplay(true, cachedLegacySuccess, "", ""))); + void authenticateCountsFailedMixedModeSecretAgainstActiveEmailLoginOtp() { + Account account = new Account(); + account.setId(9L); + setPersistedAuthenticationIdentity(account); + account.setEmail("demo@example.com"); + account.setPasswordHash(hash("password")); + net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = + new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); + challenge.setId(3L); + challenge.setAccountId(9L); + challenge.setCodeHash(hash("123456")); + challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(5)); + when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); + when(accountEmailLoginChallengeRepository.findByAccountId(9L)) + .thenReturn(Optional.of(challenge)); + when(accountEmailLoginChallengeRepository.save(challenge)).thenReturn(challenge); - AuthenticationException unavailable = + AuthenticationException exception = assertThrows( AuthenticationException.class, - () -> - service.issueConnectToken( - fixture.bootstrapToken(), - new ConnectTokenRequest(fixture.connectScopeId(), "req-cached-success"))); + () -> service.authenticateForGameplay("demo@example.com", "wrong")); - assertEquals("AUTH_UNAVAILABLE", unavailable.getCode()); - assertNoLegacyConnectTokenEffects(); + assertEquals(AuthenticationErrorCodes.INVALID_CREDENTIALS, exception.getCode()); + assertEquals(1, challenge.getInvalidAttemptCount()); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).save(challenge); + verifyNoInteractions(sessionService); } - private ConnectScopeFixture prepareConnectScopeForIssue() { + @Test + void passwordOnlyAccountsDoNotIssueEmailLoginChallenges() { Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - Subscription active = new Subscription(); - active.setId(22L); - active.setTenantId(7L); - active.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); + account.setId(9L); + account.setEmail("verified@example.com"); + account.setEmailVerified(true); + account.setLoginAuthModes("PASSWORD"); + when(accountRepository.findByEmail("verified@example.com")).thenReturn(Optional.of(account)); - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - return new ConnectScopeFixture(bootstrap.bootstrapToken(), connectScopeId); - } + service.requestEmailLoginOtp("verified@example.com"); - private void assertNoLegacyConnectTokenEffects() { - org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) - .getConnectTokenReplay( - org.mockito.ArgumentMatchers.anyLong(), - org.mockito.ArgumentMatchers.anyLong(), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyString()); - org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) - .storeConnectTokenReplay( - org.mockito.ArgumentMatchers.anyLong(), - org.mockito.ArgumentMatchers.anyLong(), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.any(SessionService.ConnectTokenReplay.class), - org.mockito.ArgumentMatchers.anyLong()); - org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) - .storeSession( - org.mockito.ArgumentMatchers.anyLong(), - org.mockito.ArgumentMatchers.anyLong(), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyLong()); - verifyNoInteractions(accountTenantMembershipRepository); - org.mockito.Mockito.verify(gameSessionClient, org.mockito.Mockito.never()) - .getAdmissionPointer( - org.mockito.ArgumentMatchers.anyLong(), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyString()); - org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.never()) - .findByTenantId(org.mockito.ArgumentMatchers.anyLong()); + verifyNoInteractions( + accountTenantMembershipRepository, accountEmailLoginChallengeRepository, emailService); } - private record ConnectScopeFixture(String bootstrapToken, String connectScopeId) {} - - @Test - void listBootstrapCharactersUsesEntityManagementForResolvedRealm() { + @ParameterizedTest + @EnumSource(AccountIdentityProvenance.class) + void gameplayAuthenticationAcceptsEveryRecognizedPersistedUuidProvenance( + AccountIdentityProvenance provenance) { Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); + account.setId(31L); + account.setEmail("retained@example.com"); account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - Subscription active = new Subscription(); - active.setId(22L); - active.setTenantId(7L); - active.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); - net.firedevops.firemud.entitymanagement.v1.Character character = - net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() - .setId("char-1") - .setName("Mara") - .setLevel(12) - .build(); - when(entityManagementClient.listCharactersByAccount( - 7L, account.getAccountUuid(), 44L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) - .thenReturn(java.util.List.of(character)); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + setPersistedAuthenticationIdentity(account, provenance); + when(accountRepository.findByEmail("retained@example.com")).thenReturn(Optional.of(account)); - var characters = - service.listBootstrapCharacters( - bootstrap.bootstrapToken(), "demo", "production", connectScopeId); + AuthenticationResult result = + service.authenticateForGameplay("retained@example.com", "password"); + var claims = new JwtUtil(JWT_SECRET, 3600000L).parseToken(result.authToken()).getPayload(); - assertEquals(1, characters.size()); - assertEquals("char-1", characters.getFirst().characterId()); - assertEquals("Mara", characters.getFirst().characterName()); - assertEquals("SHARED", characters.getFirst().stateScope()); - assertEquals("ALLOW_NEW", characters.getFirst().characterCreationPolicy()); - org.mockito.Mockito.verify(entityManagementClient) - .listCharactersByAccount( - 7L, account.getAccountUuid(), 44L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + assertEquals(account.getAccountUuid().toString(), result.accountId()); + assertEquals(account.getAccountUuid().toString(), claims.getSubject()); + assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); + assertFalse(claims.containsKey("tenantId")); + org.mockito.Mockito.verify(sessionService) + .storeAccountSession(31L, result.authToken(), jwtAuthProperties.getJwtExpirationMs()); } @ParameterizedTest - @CsvSource({"false", "true"}) - void listBootstrapCharactersDistinguishesMissingAndNonAdmittingMembership( - boolean membershipExists) { + @EnumSource(InvalidAuthenticationIdentity.class) + void gameplayAuthenticationRejectsUnprovedIdentityBeforeConsumingOtpOrMinting( + InvalidAuthenticationIdentity invalidIdentity) { Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - if (membershipExists) { - AccountTenantMembership membership = membership(account, 7L); - membership.setGameplayAdmissionAllowed(false); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership)); - } else { - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.empty()); - } - Subscription active = new Subscription(); - active.setId(22L); - active.setTenantId(7L); - active.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); + account.setId(32L); + account.setEmail("unproved@example.com"); + assignInvalidAuthenticationIdentity(account, invalidIdentity); + var challenge = new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); + challenge.setId(8L); + challenge.setAccountId(32L); + challenge.setCodeHash(hash("123456")); + challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(5)); + when(accountRepository.findByEmail("unproved@example.com")).thenReturn(Optional.of(account)); + when(accountEmailLoginChallengeRepository.findByAccountId(32L)) + .thenReturn(Optional.of(challenge)); - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + AuthenticationException unavailable = + assertThrows( + AuthenticationException.class, + () -> service.authenticateForGameplay("unproved@example.com", "123456")); + assertEquals("AUTH_UNAVAILABLE", unavailable.getCode()); + + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).lockAccountChallenge(32L); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).findByAccountId(32L); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository, org.mockito.Mockito.never()) + .delete(challenge); + verifyNoInteractions(sessionService); + } + + @Test + void emailLoginOtpVerificationFailsClosedForUnknownEmail() { + when(accountRepository.findByEmail("unknown@example.com")).thenReturn(Optional.empty()); AuthenticationException exception = assertThrows( AuthenticationException.class, - () -> - service.listBootstrapCharacters( - bootstrap.bootstrapToken(), "demo", "production", connectScopeId)); + () -> service.verifyEmailLoginOtp("unknown@example.com", "123456")); - if (membershipExists) { - assertEquals("CONNECT_TOKEN_REJECTED", exception.getCode()); - assertEquals("Gameplay admission is not allowed for this account", exception.getMessage()); - } else { - assertEquals("JOIN_REQUIRED", exception.getCode()); - assertEquals("Join the selected world before discovering characters", exception.getMessage()); - } - verifyNoInteractions(entityManagementClient); - org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) - .saveAndFlush(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + assertEquals(AuthenticationErrorCodes.INVALID_CREDENTIALS, exception.getCode()); + verifyNoInteractions(accountEmailLoginChallengeRepository, sessionService); } @Test - void listBootstrapCharactersChecksPublicJoinPolicyBeforeReturningJoinRequired() { + void emailLoginOtpVerificationLocksChallengeBeforeConsumingIt() { Account account = new Account(); - account.setId(11L); + account.setId(9L); + setPersistedAuthenticationIdentity(account); + account.setEmail("verified@example.com"); + account.setRole("player"); + net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = + new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); + challenge.setId(5L); + challenge.setAccountId(9L); + challenge.setCodeHash(hash("123456")); + challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(10)); + challenge.setInvalidAttemptCount(0); + when(accountRepository.findByEmail("verified@example.com")).thenReturn(Optional.of(account)); + when(accountEmailLoginChallengeRepository.findByAccountId(9L)) + .thenReturn(Optional.of(challenge)); + + AuthenticationResult result = service.verifyEmailLoginOtp("verified@example.com", "123456"); + + assertEquals(account.getAccountUuid().toString(), result.accountId()); + var claims = new JwtUtil(JWT_SECRET, 3600000L).parseToken(result.authToken()).getPayload(); + assertEquals("account-service", claims.getAudience().iterator().next()); + assertEquals(account.getAccountUuid().toString(), claims.getSubject()); + assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); + org.mockito.InOrder inOrder = org.mockito.Mockito.inOrder(accountEmailLoginChallengeRepository); + inOrder.verify(accountEmailLoginChallengeRepository).lockAccountChallenge(9L); + inOrder.verify(accountEmailLoginChallengeRepository).findByAccountId(9L); + inOrder.verify(accountEmailLoginChallengeRepository).delete(challenge); + } + + @Test + void authenticateReturnsControlUiTokenWithoutGameplayMembership() { + Account account = new Account(); + account.setId(1L); setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - Subscription grace = new Subscription(); - grace.setId(22L); - grace.setTenantId(7L); - grace.setStatus("grace"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(grace)); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> - service.listBootstrapCharacters( - bootstrap.bootstrapToken(), "demo", "production", connectScopeId)); + AuthenticationResult result = service.authenticate("demo", "password"); - assertEquals("PUBLIC_PRODUCTION_ADMISSION_DENIED", exception.getCode()); - org.mockito.InOrder order = - org.mockito.Mockito.inOrder(subscriptionRepository, accountTenantMembershipRepository); - order.verify(subscriptionRepository, org.mockito.Mockito.times(2)).findByTenantId(7L); - order.verify(accountTenantMembershipRepository).findByAccountIdAndTenantId(11L, 7L); - verifyNoInteractions(entityManagementClient); + assertNotNull(result.authToken()); + assertEquals(account.getAccountUuid().toString(), result.accountId()); + var claims = new JwtUtil(JWT_SECRET, 3600000L).parseToken(result.authToken()).getPayload(); + assertEquals("control-ui", claims.getAudience().iterator().next()); + assertEquals(account.getAccountUuid().toString(), claims.getSubject()); + assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); + assertEquals(java.util.List.of(), claims.get("globalRoles")); + assertNotNull(claims.get("jti")); + assertFalse(claims.containsKey("tenantId")); + org.mockito.Mockito.verify(sessionService) + .storeAccountSession(1L, result.authToken(), 3600000L); + verifyNoInteractions(accountTenantMembershipRepository); } @ParameterizedTest - @CsvSource({"active, JOIN_REQUIRED", "grace, PUBLIC_PRODUCTION_ADMISSION_DENIED"}) - void listBootstrapCharactersClassifiesInactivePublicMembershipByJoinPolicy( - String subscriptionStatus, String expectedCode) { + @CsvSource({ + "SECURITY_LOCKED, AUTH_ACCOUNT_LOCKED", + "DEACTIVATED_PENDING_DELETE, AUTH_INVALID_CREDENTIALS", + "DELETED, AUTH_INVALID_CREDENTIALS" + }) + void authenticateRejectsIneligibleLifecycleState( + AccountLifecycleState lifecycleState, String expectedCode) { Account account = new Account(); - account.setId(11L); + account.setId(1L); setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); + account.setLifecycleState(lifecycleState); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - AccountTenantMembership inactiveMembership = membership(account, 7L); - inactiveMembership.setLifecycleState("INACTIVE"); - inactiveMembership.setGameplayAdmissionAllowed(false); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(inactiveMembership)); - Subscription subscription = new Subscription(); - subscription.setId(22L); - subscription.setTenantId(7L); - subscription.setStatus(subscriptionStatus); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(subscription)); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> - service.listBootstrapCharacters( - bootstrap.bootstrapToken(), "demo", "production", connectScopeId)); + assertThrows(AuthenticationException.class, () -> service.authenticate("demo", "password")); assertEquals(expectedCode, exception.getCode()); - if ("JOIN_REQUIRED".equals(expectedCode)) { - assertEquals("Join the selected world before discovering characters", exception.getMessage()); - } else { - assertEquals("Public joining is not allowed for the selected game", exception.getMessage()); - } - verifyNoInteractions(entityManagementClient); + verifyNoInteractions(sessionService); } @Test - void listBootstrapCharactersKeepsSelectedTargetFailClosedWhenEntitlementsAreUnavailable() { + void authenticateForGameplayReturnsTokenWhenPasswordMatches() { Account account = new Account(); - account.setId(11L); + account.setId(1L); setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); + account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - Subscription active = new Subscription(); - active.setId(22L); - active.setTenantId(7L); - active.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)) - .thenReturn(java.util.List.of(active), java.util.List.of()); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); + jwtAuthProperties.setJwtSecret(null); - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> - service.listBootstrapCharacters( - bootstrap.bootstrapToken(), "demo", "production", connectScopeId)); + AuthenticationResult result = service.authenticateForGameplay("demo@example.com", "password"); - assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); - org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(2)) - .findByTenantId(7L); - verifyNoInteractions(accountTenantMembershipRepository, entityManagementClient); + assertNotNull(result.authToken()); + assertEquals(account.getAccountUuid().toString(), result.accountId()); + var claims = new JwtUtil(JWT_SECRET, 3600000L).parseToken(result.authToken()).getPayload(); + assertEquals("account-service", claims.getAudience().iterator().next()); + assertEquals(account.getAccountUuid().toString(), claims.getSubject()); + assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); + assertEquals(java.util.List.of(), claims.get("globalRoles")); + assertNotNull(claims.get("jti")); + org.mockito.Mockito.verify(sessionService) + .storeAccountSession(1L, result.authToken(), jwtAuthProperties.getJwtExpirationMs()); + verifyNoInteractions(accountTenantMembershipRepository); } @Test - void listBootstrapCharactersDoesNotUsePublicJoinForPrivateMembershipLostAfterDiscovery() { + void issuePlayerBootstrapReturnsShortLivedToken() { + composeOrdinaryBootstrapWorldDiscovery(); Account account = new Account(); - account.setId(11L); + account.setId(7L); setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); + account.setLoginAuthModes("PASSWORD"); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L)), Optional.empty()); - when(accountRealmAccessGrantRepository.existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( - 11L, 7L, "demo", "production")) - .thenReturn(true); - var privateRealm = - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("demo") - .setRealmSlug("production") - .setDisplayName("Private Realm") - .setTenantId("7") - .setGameInstanceId("44") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(false) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build(); - when(gameSessionClient.listGameplayRealms("demo")).thenReturn(java.util.List.of(privateRealm)); - when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) - .thenReturn( - net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() - .setWorldSlug("demo") - .setWorldDisplayName("Demo World") - .setRealmSlug("production") - .setRealmDisplayName("Private Realm") - .setTenantId("7") - .setGameInstanceId("44") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(false) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build()); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + jwtAuthProperties.setJwtSecret(null); - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> - service.listBootstrapCharacters( - bootstrap.bootstrapToken(), "demo", "production", connectScopeId)); + PlayerBootstrapResult result = service.issuePlayerBootstrap("demo", "password"); - assertEquals("NON_PUBLIC_ENROLLMENT_REQUIRED", exception.getCode()); - assertEquals( - "Existing game membership is required for this non-public realm", exception.getMessage()); - verifyNoInteractions(entityManagementClient); + assertEquals(account.getAccountUuid().toString(), result.accountId()); + assertNotNull(result.bootstrapToken()); + assertNotNull(result.issuedAt()); + assertNotNull(result.expiresAt()); + org.mockito.Mockito.verify(sessionService) + .storeAccountSession( + org.mockito.ArgumentMatchers.eq(7L), + org.mockito.ArgumentMatchers.eq(result.bootstrapToken()), + org.mockito.ArgumentMatchers.eq(300000L)); + var claims = new JwtUtil(JWT_SECRET, 300000L).parseToken(result.bootstrapToken()).getPayload(); + assertEquals("player-bootstrap", claims.getAudience().iterator().next()); + assertEquals(account.getAccountUuid().toString(), claims.getSubject()); + assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); + assertFalse(claims.containsKey("tenantId")); + assertEquals(300000L, claims.getExpiration().getTime() - claims.getIssuedAt().getTime()); + when(sessionService.isAccountSessionActive(7L, result.bootstrapToken())).thenReturn(true); + var worlds = service.listBootstrapWorlds(result.bootstrapToken()); + assertEquals("demo", worlds.getFirst().worldSlug()); + org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.times(3)) + .findByAccountUuid(account.getAccountUuid()); + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.times(2)) + .isAccountSessionActive(7L, result.bootstrapToken()); + verifyNoInteractions(accountEmailLoginChallengeRepository); } - @Test - void listBootstrapCharactersRejectsAmbiguousRealmBeforeAdmissionFiltering() { + @ParameterizedTest + @EnumSource(InvalidAuthenticationIdentity.class) + void issuePlayerBootstrapRejectsUnprovedIdentityBeforeConsumingOtpOrMinting( + InvalidAuthenticationIdentity invalidIdentity) { Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); + account.setId(50L); account.setUsername("demo"); - account.setPasswordHash(hash("password")); + account.setLoginAuthModes("EMAIL_OTP"); + assignInvalidAuthenticationIdentity(account, invalidIdentity); + net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = + new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); + challenge.setAccountId(50L); + challenge.setCodeHash(hash("123456")); + challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(5)); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - Subscription active = new Subscription(); - active.setId(22L); - active.setTenantId(7L); - active.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - var visibleRealm = - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("demo") - .setRealmSlug("production") - .setDisplayName("Live Realm") - .setTenantId("7") - .setGameInstanceId("44") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build(); - var hiddenDuplicate = - visibleRealm.toBuilder().setVisible(false).setPublicProductionRealm(false).build(); - when(gameSessionClient.listGameplayRealms("demo")) - .thenReturn(java.util.List.of(visibleRealm, hiddenDuplicate)); + when(accountEmailLoginChallengeRepository.findByAccountId(50L)) + .thenReturn(Optional.of(challenge)); - AuthenticationException ex = + AuthenticationException unavailable = assertThrows( - AuthenticationException.class, - () -> - service.listBootstrapCharacters( - bootstrap.bootstrapToken(), "demo", "production", connectScopeId)); + AuthenticationException.class, () -> service.issuePlayerBootstrap("demo", "123456")); + assertEquals("AUTH_UNAVAILABLE", unavailable.getCode()); - assertEquals("ADMISSION_POINTER_UNAVAILABLE", ex.getCode()); - verifyNoInteractions(entityManagementClient); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).lockAccountChallenge(50L); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).findByAccountId(50L); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository, org.mockito.Mockito.never()) + .delete(challenge); + verifyNoInteractions(sessionService); } @Test - void listBootstrapCharactersSkipsMalformedUnrelatedRealm() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - Subscription active = new Subscription(); - active.setId(22L); - active.setTenantId(7L); - active.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); + void issuePlayerBootstrapPrefersEmailLookupOverCollidingUsername() { + Account emailAccount = new Account(); + emailAccount.setId(7L); + setPersistedAuthenticationIdentity(emailAccount); + emailAccount.setUsername("email-owner"); + emailAccount.setEmail("player@example.com"); + emailAccount.setPasswordHash(hash("password")); + emailAccount.setLoginAuthModes("PASSWORD"); + when(accountRepository.findByEmail("player@example.com")).thenReturn(Optional.of(emailAccount)); - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - var visibleRealm = - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("demo") - .setRealmSlug("production") - .setDisplayName("Live Realm") - .setTenantId("7") - .setGameInstanceId("44") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build(); - var malformedUnrelatedRealm = - visibleRealm.toBuilder().setRealmSlug("broken").setTenantId("bad").build(); - when(gameSessionClient.listGameplayRealms("demo")) - .thenReturn(java.util.List.of(malformedUnrelatedRealm, visibleRealm)); - - var characters = - service.listBootstrapCharacters( - bootstrap.bootstrapToken(), "demo", "production", connectScopeId); - - assertTrue(characters.isEmpty()); - } - - @Test - void listBootstrapRealmsIncludesRealmStatePolicy() { + PlayerBootstrapResult result = + service.issuePlayerBootstrap(" PLAYER@EXAMPLE.COM ", "password"); + + assertEquals(emailAccount.getAccountUuid().toString(), result.accountId()); + org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()) + .findByUsername(org.mockito.ArgumentMatchers.anyString()); + } + + @Test + void issuePlayerBootstrapAcceptsAndConsumesEmailLoginOtp() { Account account = new Account(); - account.setId(11L); + account.setId(7L); setPersistedAuthenticationIdentity(account); account.setUsername("demo"); - account.setPasswordHash(hash("password")); + account.setEmail("demo@example.com"); + account.setLoginAuthModes("EMAIL_OTP"); + net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = + new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); + challenge.setAccountId(7L); + challenge.setCodeHash(hash("123456")); + challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(5)); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); + when(accountEmailLoginChallengeRepository.findByAccountId(7L)) + .thenReturn(Optional.of(challenge)); - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + PlayerBootstrapResult result = service.issuePlayerBootstrap("demo", "123456"); - var realms = service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo"); + assertEquals(account.getAccountUuid().toString(), result.accountId()); + org.mockito.InOrder inOrder = org.mockito.Mockito.inOrder(accountEmailLoginChallengeRepository); + inOrder.verify(accountEmailLoginChallengeRepository).lockAccountChallenge(7L); + inOrder.verify(accountEmailLoginChallengeRepository).findByAccountId(7L); + inOrder.verify(accountEmailLoginChallengeRepository).delete(challenge); + org.mockito.Mockito.verify(sessionService) + .storeAccountSession(7L, result.bootstrapToken(), 300000L); + } - assertEquals(1, realms.size()); - assertEquals(REALM_ID, realms.getFirst().realmId()); - var scopeClaims = - new JwtUtil(JWT_SECRET, 300000L) - .parseToken(realms.getFirst().connectScopeId()) - .getPayload(); - assertEquals(account.getAccountUuid().toString(), scopeClaims.getSubject()); - assertEquals(account.getAccountUuid().toString(), scopeClaims.get("accountId", String.class)); - assertEquals( - REALM_ID, - new JwtUtil(JWT_SECRET, 300000L) - .parseToken(realms.getFirst().connectScopeId()) - .getPayload() - .get("realmId")); - assertEquals("SHARED", realms.getFirst().stateScope()); - assertEquals(23L, realms.getFirst().catalogRevision()); - assertEquals(PLAYABLE_STATE_NAMESPACE_ID, realms.getFirst().playableStateNamespaceId()); - assertEquals("PLAYABLE_STATE_SCOPE_SHARED", realms.getFirst().playableStateScope()); - assertEquals("ALLOW_NEW", realms.getFirst().characterCreationPolicy()); + private static java.util.stream.Stream + invalidBootstrapAccountClaims() { + String valid = "10000000-0000-4000-8000-00000000000a"; + return java.util.stream.Stream.of( + org.junit.jupiter.params.provider.Arguments.of("11", "11"), + org.junit.jupiter.params.provider.Arguments.of((String) null, valid), + org.junit.jupiter.params.provider.Arguments.of( + valid.toUpperCase(java.util.Locale.ROOT), valid), + org.junit.jupiter.params.provider.Arguments.of(" " + valid, valid), + org.junit.jupiter.params.provider.Arguments.of(valid, (Object) null), + org.junit.jupiter.params.provider.Arguments.of(valid, ""), + org.junit.jupiter.params.provider.Arguments.of(valid, 11L), + org.junit.jupiter.params.provider.Arguments.of(valid, "11"), + org.junit.jupiter.params.provider.Arguments.of( + valid, "00000000-0000-0000-0000-000000000000"), + org.junit.jupiter.params.provider.Arguments.of( + "00000000-0000-0000-0000-000000000000", valid), + org.junit.jupiter.params.provider.Arguments.of(valid, "not-a-uuid"), + org.junit.jupiter.params.provider.Arguments.of( + valid, valid.toUpperCase(java.util.Locale.ROOT)), + org.junit.jupiter.params.provider.Arguments.of(valid, " " + valid), + org.junit.jupiter.params.provider.Arguments.of( + valid, "10000000-0000-4000-8000-000000000002")); } @ParameterizedTest - @ValueSource( - strings = { - "shared-live", - "C6ED6A44-C7E7-4F18-81FC-078A74E67C07", - "c6ed6a44c7e74f1881fc078a74e67c07" - }) - void listBootstrapRealmsRejectsNoncanonicalPlayableStateNamespaceIdFromReachableRealm( - String namespaceId) { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - when(gameSessionClient.listGameplayRealms("demo")) - .thenReturn( - java.util.List.of( - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("demo") - .setRealmSlug("production") - .setDisplayName("Live Realm") - .setTenantId("7") - .setGameInstanceId("44") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(namespaceId) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build())); - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + @org.junit.jupiter.params.provider.MethodSource("invalidBootstrapAccountClaims") + void bootstrapReaderRejectsNonUuidOrContradictoryIdentityBeforeOwnerOrSessionUse( + String subject, Object accountClaim) { + composeOrdinaryBootstrapWorldDiscovery(); + Map claims = new java.util.HashMap<>(); + claims.put("aud", "player-bootstrap"); + if (accountClaim != null) { + claims.put("accountId", accountClaim); + } + String token = new JwtUtil(JWT_SECRET, 300000L).generateToken(subject, claims); - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo")); + AuthenticationException denied = + assertThrows(AuthenticationException.class, () -> service.listBootstrapWorlds(token)); - assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); - verifyNoInteractions(accountConnectScopeRepository); + assertEquals("CONNECT_CONTEXT_INVALID", denied.getCode()); + verifyNoInteractions(accountRepository, sessionService); } - @Test - void listBootstrapRealmsReadsFreshEntitlementsAndReusesVerifiedAccountIdentity() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(gameSessionClient.listGameplayRealms("demo")) - .thenReturn( - java.util.List.of( - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("demo") - .setRealmSlug("production") - .setDisplayName("Live Realm") - .setTenantId("7") - .setGameInstanceId("44") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build(), - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("demo") - .setRealmSlug("preview") - .setDisplayName("Private Preview Realm") - .setTenantId("7") - .setGameInstanceId("45") - .setRealmId("ce814357-64ad-44e8-b004-828a9ae37c13") - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(18L) - .setVisible(true) - .setPublicProductionRealm(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build())); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - when(accountRealmAccessGrantRepository.existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( - 11L, 7L, "demo", "preview")) - .thenReturn(true); - when(gameSessionClient.getAdmissionPointer(7L, "demo", "preview")) - .thenReturn( - net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() - .setWorldSlug("demo") - .setWorldDisplayName("Demo World") - .setRealmSlug("preview") - .setRealmDisplayName("Private Preview Realm") - .setTenantId("7") - .setGameInstanceId("45") - .setRealmId("ce814357-64ad-44e8-b004-828a9ae37c13") - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(18L) - .setVisible(true) - .setPublicProductionRealm(false) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build()); + @ParameterizedTest + @ValueSource(strings = {"missing", "wrong-owner-uuid", "unavailable"}) + void bootstrapReaderReportsOwnerReadbackFailureBeforeSessionUse(String failure) { + composeOrdinaryBootstrapWorldDiscovery(); + UUID uuid = UUID.fromString("10000000-0000-4000-8000-000000000001"); + if (failure.equals("unavailable")) { + when(accountRepository.findByAccountUuid(uuid)) + .thenThrow( + new org.springframework.dao.DataAccessResourceFailureException("private detail")); + } else if (failure.equals("wrong-owner-uuid")) { + Account owner = new Account(); + owner.setId(11L); + owner.setAccountUuid(UUID.randomUUID()); + owner.setAccountUuidSourceNumericId(11L); + owner.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + when(accountRepository.findByAccountUuid(uuid)).thenReturn(Optional.of(owner)); + } + String token = + new JwtUtil(JWT_SECRET, 300000L) + .generateToken( + uuid.toString(), Map.of("aud", "player-bootstrap", "accountId", uuid.toString())); - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AuthenticationException denied = + assertThrows(AuthenticationException.class, () -> service.listBootstrapWorlds(token)); - var firstCall = service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo"); - org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(1)) - .findByTenantId(7L); - org.mockito.Mockito.clearInvocations(accountRepository); - var secondCall = service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo"); - - assertEquals(2, firstCall.size()); - assertEquals(2, secondCall.size()); - org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(2)) - .findByTenantId(7L); - org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.times(1 + secondCall.size())) - .findByAccountUuid(account.getAccountUuid()); - org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()).findById(11L); - JwtUtil tokenReader = new JwtUtil(JWT_SECRET, 3600000L); - for (var realm : secondCall) { - var claims = tokenReader.parseToken(realm.connectScopeId()).getPayload(); - assertEquals(account.getAccountUuid().toString(), claims.getSubject()); - assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); - } + assertEquals("AUTH_UNAVAILABLE", denied.getCode()); + assertEquals("Account authority is unavailable", denied.getMessage()); + verifyNoInteractions(sessionService); } @Test - void listBootstrapWorldsReadsFreshEntitlementsOncePerTenantPerInvocation() { + void bootstrapReaderResolvesUuidBeforeReadingPrivateAccountSession() { + composeOrdinaryBootstrapWorldDiscovery(); Account account = new Account(); account.setId(11L); setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(gameSessionClient.listGameplayWorlds()) - .thenReturn( - java.util.List.of( - net.firedevops.firemud.gamesession.v1.GameplayWorld.newBuilder() - .setWorldSlug("demo") - .setDisplayName("Demo World") - .build(), - net.firedevops.firemud.gamesession.v1.GameplayWorld.newBuilder() - .setWorldSlug("sandbox") - .setDisplayName("Sandbox World") - .build())); - when(gameSessionClient.listGameplayRealms("sandbox")) - .thenReturn( - java.util.List.of( - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("sandbox") - .setRealmSlug("production") - .setDisplayName("Sandbox Realm") - .setTenantId("7") - .setGameInstanceId("45") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(18L) - .setVisible(true) - .setPublicProductionRealm(true) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build())); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String uuid = account.getAccountUuid().toString(); + String token = + new JwtUtil(JWT_SECRET, 300000L) + .generateToken(uuid, Map.of("aud", "player-bootstrap", "accountId", uuid)); + when(sessionService.isAccountSessionActive(11L, token)).thenReturn(true); - var firstCall = service.listBootstrapWorlds(bootstrap.bootstrapToken()); - var secondCall = service.listBootstrapWorlds(bootstrap.bootstrapToken()); + assertFalse(service.listBootstrapWorlds(token).isEmpty()); - assertEquals(2, firstCall.size()); - assertEquals(2, secondCall.size()); - org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(2)) - .findByTenantId(7L); + org.mockito.InOrder reads = org.mockito.Mockito.inOrder(accountRepository, sessionService); + reads.verify(accountRepository).findByAccountUuid(account.getAccountUuid()); + reads.verify(sessionService).isAccountSessionActive(11L, token); } @Test - void listBootstrapWorldsOmitsCanceledTenantAndFailsWhenEntitlementIsUnavailable() { + void listBootstrapWorldsRejectsInactiveAccountBootstrapToken() { + composeOrdinaryBootstrapWorldDiscovery(); Account account = new Account(); account.setId(11L); setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - Subscription activeDemo = new Subscription(); - activeDemo.setId(1L); - activeDemo.setTenantId(7L); - activeDemo.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(activeDemo)); - when(gameSessionClient.listGameplayWorlds()) - .thenReturn( - java.util.List.of( - net.firedevops.firemud.gamesession.v1.GameplayWorld.newBuilder() - .setWorldSlug("demo") - .setDisplayName("Demo World") - .build(), - net.firedevops.firemud.gamesession.v1.GameplayWorld.newBuilder() - .setWorldSlug("sandbox") - .setDisplayName("Sandbox World") - .build())); - when(gameSessionClient.listGameplayRealms("sandbox")) - .thenReturn( - java.util.List.of( - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("sandbox") - .setRealmSlug("production") - .setDisplayName("Sandbox Realm") - .setTenantId("8") - .setGameInstanceId("45") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID_TENANT_8) - .setCatalogRevision(23L) - .setPointerVersion(18L) - .setVisible(true) - .setPublicProductionRealm(true) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build())); - Subscription canceledSandbox = new Subscription(); - canceledSandbox.setId(2L); - canceledSandbox.setTenantId(8L); - canceledSandbox.setStatus("canceled"); - when(subscriptionRepository.findByTenantId(8L)).thenReturn(java.util.List.of(canceledSandbox)); + String accountUuid = account.getAccountUuid().toString(); + String bootstrapToken = + new JwtUtil(JWT_SECRET, 300000L) + .generateToken( + accountUuid, Map.of("aud", "player-bootstrap", "accountId", accountUuid)); - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AuthenticationException ex = + assertThrows( + AuthenticationException.class, () -> service.listBootstrapWorlds(bootstrapToken)); - var worldsWithCanceledTenant = service.listBootstrapWorlds(bootstrap.bootstrapToken()); + assertEquals("CONNECT_CONTEXT_INVALID", ex.getCode()); + assertEquals("Bootstrap token expired", ex.getMessage()); + org.mockito.Mockito.verify(sessionService).isAccountSessionActive(11L, bootstrapToken); + } - assertEquals( - java.util.List.of("demo"), - worldsWithCanceledTenant.stream().map(world -> world.worldSlug()).toList()); + @ParameterizedTest + @ValueSource( + strings = { + "not-a-uuid", + "abc", + "0", + "00000000-0000-0000-0000-000000000000", + "4C4B57D8-E3A2-48FE-9977-E7DF0FDCE901", + " 4c4b57d8-e3a2-48fe-9977-e7df0fdce901", + "4c4b57d8-e3a2-48fe-9977-e7df0fdce901 " + }) + void listBootstrapWorldsRejectsMalformedOrNoncanonicalBootstrapAccountUuid(String accountUuid) { + composeOrdinaryBootstrapWorldDiscovery(); + String malformedBootstrapToken = + new JwtUtil(JWT_SECRET, 300000L) + .generateToken( + accountUuid, Map.of("aud", "player-bootstrap", "accountId", accountUuid)); - when(subscriptionRepository.findByTenantId(8L)).thenReturn(java.util.List.of()); - AuthenticationException unavailableSandbox = + AuthenticationException ex = assertThrows( AuthenticationException.class, - () -> service.listBootstrapWorlds(bootstrap.bootstrapToken())); + () -> service.listBootstrapWorlds(malformedBootstrapToken)); - assertEquals("ENTITLEMENT_UNAVAILABLE", unavailableSandbox.getCode()); + assertEquals("CONNECT_CONTEXT_INVALID", ex.getCode()); + verifyNoInteractions(accountRepository, sessionService); + } - Subscription activeSandbox = new Subscription(); - activeSandbox.setId(3L); - activeSandbox.setTenantId(8L); - activeSandbox.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of()); - when(subscriptionRepository.findByTenantId(8L)).thenReturn(java.util.List.of(activeSandbox)); + @Test + void listBootstrapWorldsRejectsBootstrapTokenAccountSubjectMismatch() { + composeOrdinaryBootstrapWorldDiscovery(); + String malformedBootstrapToken = + new JwtUtil(JWT_SECRET, 300000L) + .generateToken( + REALM_ID, + Map.of("aud", "player-bootstrap", "accountId", PLAYABLE_STATE_NAMESPACE_ID)); - AuthenticationException unavailable = + AuthenticationException ex = assertThrows( AuthenticationException.class, - () -> service.listBootstrapWorlds(bootstrap.bootstrapToken())); + () -> service.listBootstrapWorlds(malformedBootstrapToken)); - assertEquals("ENTITLEMENT_UNAVAILABLE", unavailable.getCode()); - org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(3)) - .findByTenantId(7L); - org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(2)) - .findByTenantId(8L); + assertEquals("CONNECT_CONTEXT_INVALID", ex.getCode()); + verifyNoInteractions(accountRepository, sessionService); } @Test - void listBootstrapRealmsPropagatesUnavailableEntitlements() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of()); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + void listBootstrapWorldsRejectsLegacyNumericBootstrapTokenClaims() { + composeOrdinaryBootstrapWorldDiscovery(); + String malformedBootstrapToken = + new JwtUtil(JWT_SECRET, 300000L) + .generateToken("11", Map.of("aud", "player-bootstrap", "accountId", "11")); - AuthenticationException exception = + AuthenticationException ex = assertThrows( AuthenticationException.class, - () -> service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo")); + () -> service.listBootstrapWorlds(malformedBootstrapToken)); - assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); + assertEquals("CONNECT_CONTEXT_INVALID", ex.getCode()); } @Test - void listBootstrapWorldsFailsInsteadOfReturningIncompleteWorldDiscovery() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(gameSessionClient.listGameplayWorlds()) - .thenReturn( - java.util.List.of( - net.firedevops.firemud.gamesession.v1.GameplayWorld.newBuilder() - .setWorldSlug("demo") - .setDisplayName("Demo World") - .build(), - net.firedevops.firemud.gamesession.v1.GameplayWorld.newBuilder() - .setWorldSlug("sandbox") - .setDisplayName("Sandbox World") - .build())); - when(gameSessionClient.listGameplayRealms("sandbox")) - .thenReturn( - java.util.List.of( - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("sandbox") - .setRealmSlug("production") - .setDisplayName("Sandbox Realm") - .setTenantId("8") - .setGameInstanceId("45") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID_TENANT_8) - .setCatalogRevision(23L) - .setPointerVersion(18L) - .setVisible(true) - .setPublicProductionRealm(true) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build())); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of()); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + void listBootstrapWorldsRejectsBootstrapTokenWithoutAudience() { + composeOrdinaryBootstrapWorldDiscovery(); + String malformedBootstrapToken = + new JwtUtil(JWT_SECRET, 300000L).generateToken("11", Map.of("accountId", "11")); - AuthenticationException unavailable = + AuthenticationException ex = assertThrows( AuthenticationException.class, - () -> service.listBootstrapWorlds(bootstrap.bootstrapToken())); + () -> service.listBootstrapWorlds(malformedBootstrapToken)); - assertEquals("ENTITLEMENT_UNAVAILABLE", unavailable.getCode()); - org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(1)) - .findByTenantId(7L); - org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.never()) - .findByTenantId(8L); + assertEquals("CONNECT_CONTEXT_INVALID", ex.getCode()); } @Test - void listBootstrapRealmsRethrowsOtherAuthenticationErrors() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(gameSessionClient.listGameplayRealms("demo")) - .thenReturn( - java.util.List.of( - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("demo") - .setRealmSlug("preview") - .setDisplayName("Private Preview Realm") - .setTenantId("7") - .setGameInstanceId("45") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(18L) - .setVisible(true) - .setPublicProductionRealm(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build())); - AuthenticationException authorityError = - new AuthenticationException("AUTH_UNAVAILABLE", "Membership authority is unavailable"); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenThrow(authorityError); + void listBootstrapWorldsMapsUnexpectedJwtParserFailureToUnavailableWithCause() { + JwtUtil jwtUtil = org.mockito.Mockito.mock(JwtUtil.class); + IllegalStateException parserFailure = new IllegalStateException("boom"); + when(jwtUtil.parseToken("boom-token")).thenThrow(parserFailure); + this.jwtUtil = jwtUtil; + service = + new AccountServiceImpl( + accountRepository, + accountAuthorityGenerationRepository, + accountAuthoritySourceEvidenceRepository, + accountAuthorityOutboxRepository, + accountPasswordResetOperationRepository, + accountLogoutAllOperationRepository, + accountSecurityStateOperationRepository, + accountPasswordResetDraftSourceChangeRepository, + accountAuditOutboxRepository, + accountJoinOperationRepository, + accountEmailLoginChallengeRepository, + accountRealmAccessGrantRepository, + accountTenantMembershipRepository, + Mappers.getMapper(AccountMapper.class), + profileRepository, + profileMapper, + paymentTransactionRepository, + retainedSubscriptionEvidenceRepository, + externalAccountRepository, + passwordResetTokenRepository, + emailVerificationTokenRepository, + notificationService, + emailService, + mailProperties, + tokenProperties, + jwtAuthProperties, + jwtUtil, + sessionService, + transactionManager); - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + composeOrdinaryBootstrapWorldDiscovery(); - AuthenticationException exception = + AuthenticationException ex = assertThrows( - AuthenticationException.class, - () -> service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo")); + AuthenticationException.class, () -> service.listBootstrapWorlds("boom-token")); - assertEquals("AUTH_UNAVAILABLE", exception.getCode()); + assertEquals("AUTH_UNAVAILABLE", ex.getCode()); + assertSame(parserFailure, ex.getCause()); + verifyNoInteractions( + accountRepository, + sessionService, + accountTenantMembershipRepository, + accountAuditOutboxRepository); } - @Test - void listBootstrapRealmsRejectsRealmWithMalformedTenantId() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - when(gameSessionClient.listGameplayRealms("demo")) - .thenReturn( - java.util.List.of( - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("demo") - .setRealmSlug("broken") - .setDisplayName("Broken Realm") - .setTenantId("bad") - .setGameInstanceId("44") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build(), - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("demo") - .setRealmSlug("production") - .setDisplayName("Live Realm") - .setTenantId("7") - .setGameInstanceId("44") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build())); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - - AuthenticationException exception = + @ParameterizedTest + @ValueSource( + strings = { + "CONNECT_SCOPE_INVALID", + "CONNECT_SCOPE_MISMATCH", + "ADMISSION_POINTER_UNAVAILABLE", + "ENTITLEMENT_UNAVAILABLE", + "AUTH_UNAVAILABLE" + }) + void bootstrapRealmFacadePreservesCanonicalTargetAndPolicyRefusal(String code) { + var owner = org.mockito.Mockito.mock(AccountCanonicalPublicRealmScopeOwner.class); + service.setCanonicalPublicRealmScopeOwner(owner); + var refusal = new AuthenticationException(code, "controlled current canonical source refusal"); + when(owner.listRealmScopes("bootstrap", "source-tenant", "demo")).thenThrow(refusal); + assertSame( + refusal, assertThrows( AuthenticationException.class, - () -> service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo")); + () -> service.listBootstrapRealms("bootstrap", "source-tenant", "demo"))); + verifyNoInteractions(accountTenantMembershipRepository, accountRealmAccessGrantRepository); + } + + @Test + void bootstrapRealmDiscoveryAndDirectTextScopeIssuanceLeaveTransactionsToCanonicalOwners() + throws Exception { + for (var method : + List.of( + AccountServiceImpl.class.getMethod( + "listBootstrapRealms", String.class, String.class, String.class), + AccountServiceImpl.class.getMethod( + "issueDirectTextConnectScope", + DirectTextCallerContext.class, + DirectTextJoinTarget.class), + AccountServiceImpl.class.getMethod( + "joinPublicProduction", String.class, JoinPublicProductionRequest.class), + AccountServiceImpl.class.getMethod( + "listBootstrapCharacters", + String.class, + String.class, + String.class, + String.class))) { + assertNull(method.getAnnotation(Transactional.class)); + } + } + + @Test + void canonicalScopeReaderRejectsRetiredNumericSignedCarrierBeforeScopeLookup() { + var reader = + new net.firedevops.firemud.accountservice.service.AccountCanonicalConnectScopeReader( + jwtUtil, accountConnectScopeRepository, transactionManager, Clock.systemUTC()); + String numeric = + jwtUtil.generateToken( + "11", 120000L, Map.of("aud", "bootstrap-connect-scope", "accountId", "11")); + assertEquals( + "CONNECT_SCOPE_INVALID", + assertThrows(AuthenticationException.class, () -> reader.read(UUID.randomUUID(), numeric)) + .getCode()); + verifyNoInteractions(accountConnectScopeRepository); + } - assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); + @ParameterizedTest + @ValueSource( + strings = { + "account", + "tenant", + "realm", + "namespace", + "instance", + "catalog", + "pointer", + "target-class", + "version", + "audience", + "time", + "jti" + }) + void canonicalScopeReaderRejectsMalformedSignedAuthorityBeforeRetainedLookup(String field) { + UUID account = UUID.randomUUID(); + Instant now = Instant.now().truncatedTo(java.time.temporal.ChronoUnit.SECONDS); + Map claims = new java.util.HashMap<>(); + claims.put("aud", "bootstrap-connect-scope"); + claims.put("accountId", account.toString()); + claims.put("jti", UUID.randomUUID().toString()); + claims.put("targetClass", "PUBLIC_PRODUCTION"); + claims.put("scopeDigestVersion", 2); + claims.put("tenantId", UUID.randomUUID().toString()); + claims.put("realmId", REALM_ID); + claims.put("tenantSlug", "tenant"); + claims.put("worldSlug", "demo"); + claims.put("realmSlug", "production"); + claims.put("playableStateNamespaceId", PLAYABLE_STATE_NAMESPACE_ID); + claims.put("playableStateScope", "SHARED"); + claims.put("gameInstanceId", UUID.randomUUID().toString()); + claims.put("catalogRevision", 23L); + claims.put("pointerVersion", 17L); + claims.put("evaluatedAt", now.toString()); + claims.put("connectScopeExpiresAt", now.plusSeconds(120).toString()); + switch (field) { + case "account" -> claims.put("accountId", UUID.randomUUID().toString()); + case "tenant" -> claims.put("tenantId", "7"); + case "realm" -> claims.put("realmId", "not-a-uuid"); + case "namespace" -> claims.put("playableStateNamespaceId", "not-a-uuid"); + case "instance" -> claims.put("gameInstanceId", "44"); + case "catalog" -> claims.put("catalogRevision", 0L); + case "pointer" -> claims.put("pointerVersion", -1L); + case "target-class" -> claims.put("targetClass", "PRIVATE"); + case "version" -> claims.put("scopeDigestVersion", 1); + case "audience" -> claims.put("aud", List.of("bootstrap-connect-scope", "control-ui")); + case "time" -> claims.put("evaluatedAt", now.plusSeconds(60).toString()); + case "jti" -> claims.remove("jti"); + default -> throw new AssertionError(field); + } + String token = jwtUtil.generateToken(account.toString(), now.plusSeconds(120), claims); + var reader = + new net.firedevops.firemud.accountservice.service.AccountCanonicalConnectScopeReader( + jwtUtil, + accountConnectScopeRepository, + transactionManager, + Clock.fixed(now.plusSeconds(1), java.time.ZoneOffset.UTC)); + assertEquals( + "CONNECT_SCOPE_INVALID", + assertThrows(AuthenticationException.class, () -> reader.read(account, token)).getCode()); + verifyNoInteractions(accountConnectScopeRepository); } @Test - void listBootstrapRealmsRejectsRealmWithUnknownStateScope() { + void authenticateForGameplayUsesNormalizedEmailLookup() { Account account = new Account(); - account.setId(11L); + account.setId(1L); setPersistedAuthenticationIdentity(account); account.setUsername("demo"); + account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - when(gameSessionClient.listGameplayRealms("demo")) - .thenReturn( - java.util.List.of( - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("demo") - .setRealmSlug("production") - .setDisplayName("Live Realm") - .setTenantId("7") - .setGameInstanceId("44") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setRequiresCharacterSelection(false) - .setStateScope("UNKNOWN") - .setCharacterCreationPolicy("ALLOW_NEW") - .build())); + when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AuthenticationResult result = + service.authenticateForGameplay(" DEMO@example.com ", "password"); + + assertNotNull(result.authToken()); + assertEquals(account.getAccountUuid().toString(), result.accountId()); + org.mockito.Mockito.verify(sessionService) + .storeAccountSession(1L, result.authToken(), jwtAuthProperties.getJwtExpirationMs()); + verifyNoInteractions(accountTenantMembershipRepository); + org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()) + .findByUsername(org.mockito.ArgumentMatchers.anyString()); + } + + @Test + void authenticateThrowsWhenInvalid() { + when(accountRepository.findByEmail("demo")).thenReturn(Optional.empty()); + AuthenticationException exception = + assertThrows( + AuthenticationException.class, () -> service.authenticateForGameplay("demo", "bad")); + assertEquals(AuthenticationErrorCodes.INVALID_CREDENTIALS, exception.getCode()); + } + + @Test + void authenticateDoesNotUseGlobalAccountFallback() { + when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.empty()); AuthenticationException exception = assertThrows( AuthenticationException.class, - () -> service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo")); + () -> service.authenticateForGameplay("demo@example.com", "password")); - assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); + assertEquals(AuthenticationErrorCodes.INVALID_CREDENTIALS, exception.getCode()); + org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()) + .findByUsername(org.mockito.ArgumentMatchers.anyString()); } @Test - void listBootstrapCharactersUsesIsolatedRealmRoster() { + void authenticateAllowsGlobalIdentityWithoutTenantMembership() { Account account = new Account(); - account.setId(11L); + account.setId(7L); setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); + account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - - when(gameSessionClient.listGameplayRealms("demo")) - .thenReturn( - java.util.List.of( - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("demo") - .setRealmSlug("production") - .setDisplayName("Live Realm") - .setTenantId("7") - .setGameInstanceId("91") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setRequiresCharacterSelection(false) - .setStateScope("ISOLATED") - .setCharacterCreationPolicy("COPIED_ONLY") - .build())); - when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) - .thenReturn( - net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() - .setWorldSlug("demo") - .setWorldDisplayName("Demo World") - .setRealmSlug("production") - .setRealmDisplayName("Live Realm") - .setTenantId("7") - .setGameInstanceId("91") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setRequiresCharacterSelection(false) - .setStateScope("ISOLATED") - .setCharacterCreationPolicy("COPIED_ONLY") - .build()); - net.firedevops.firemud.entitymanagement.v1.Character character = - net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() - .setId("char-iso-1") - .setName("ForkMara") - .setLevel(4) - .build(); - when(entityManagementClient.listCharactersByAccount( - 7L, account.getAccountUuid(), 91L, PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) - .thenReturn(java.util.List.of(character)); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - - var characters = - service.listBootstrapCharacters( - bootstrap.bootstrapToken(), "demo", "production", connectScopeId); + when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); + AuthenticationResult result = service.authenticateForGameplay("demo@example.com", "password"); - assertEquals(1, characters.size()); - assertEquals("char-iso-1", characters.getFirst().characterId()); - assertEquals("ForkMara", characters.getFirst().characterName()); - assertEquals("ISOLATED", characters.getFirst().stateScope()); - assertEquals("COPIED_ONLY", characters.getFirst().characterCreationPolicy()); + assertEquals(account.getAccountUuid().toString(), result.accountId()); + assertNotNull(result.authToken()); + org.mockito.Mockito.verify(sessionService) + .storeAccountSession(7L, result.authToken(), jwtAuthProperties.getJwtExpirationMs()); + verifyNoInteractions(accountTenantMembershipRepository); } @Test - void listBootstrapCharactersRejectsAdmissionPointerWithMalformedGameInstanceId() { + void getTenantMembershipForRuntimeReturnsAdmissionAllowedForExistingAccount() { Account account = new Account(); account.setId(11L); setPersistedAuthenticationIdentity(account); account.setUsername("demo"); + account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + AccountTenantMembership activeMembership = membership(account, 7L); + activeMembership.setMembershipVersion(17L); + activeMembership.setMembershipAuthorityGeneration(29L); when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) - .thenReturn( - admissionPointer( - 7L, "demo", "production", "44", 17L, true, true, "SHARED", "ALLOW_NEW"), - net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() - .setWorldSlug("demo") - .setWorldDisplayName("Demo World") - .setRealmSlug("production") - .setRealmDisplayName("Live Realm") - .setTenantId("7") - .setGameInstanceId("bad") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build()); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + .thenReturn(Optional.of(activeMembership)); - AuthenticationException ex = - assertThrows( - AuthenticationException.class, - () -> - service.listBootstrapCharacters( - bootstrap.bootstrapToken(), "demo", "production", connectScopeId)); + var dto = service.getTenantMembershipForRuntime(11L, 7L, "req-1"); - assertEquals("ADMISSION_POINTER_UNAVAILABLE", ex.getCode()); - org.mockito.Mockito.verifyNoInteractions(entityManagementClient); + assertEquals(11L, dto.accountId()); + assertEquals(7L, dto.tenantId()); + assertTrue(dto.membershipExists()); + assertTrue(dto.gameplayAdmissionAllowed()); + assertEquals(17L, dto.membershipVersion()); + assertEquals("ACTIVE", dto.membershipLifecycleState()); + assertEquals(29L, dto.membershipAuthorityGeneration()); + assertNotNull(dto.evaluatedAt()); } @Test - void listBootstrapCharactersRejectsAdmissionPointerWithUnknownStateScope() { + void getTenantMembershipForRuntimeReturnsCoherentMissingMembershipForExistingAccount() { Account account = new Account(); account.setId(11L); setPersistedAuthenticationIdentity(account); account.setUsername("demo"); + account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) - .thenReturn( - admissionPointer( - 7L, "demo", "production", "44", 17L, true, true, "SHARED", "ALLOW_NEW"), - net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() - .setWorldSlug("demo") - .setWorldDisplayName("Demo World") - .setRealmSlug("production") - .setRealmDisplayName("Live Realm") - .setTenantId("7") - .setGameInstanceId("44") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setRequiresCharacterSelection(false) - .setStateScope("UNKNOWN") - .setCharacterCreationPolicy("ALLOW_NEW") - .build()); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + .thenReturn(Optional.empty()); - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> - service.listBootstrapCharacters( - bootstrap.bootstrapToken(), "demo", "production", connectScopeId)); + var dto = service.getTenantMembershipForRuntime(11L, 7L, "req-1"); - assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); - verifyNoInteractions(entityManagementClient); + assertEquals(11L, dto.accountId()); + assertEquals(7L, dto.tenantId()); + assertFalse(dto.membershipExists()); + assertFalse(dto.gameplayAdmissionAllowed()); + assertEquals(0L, dto.membershipVersion()); + assertEquals("MISSING", dto.membershipLifecycleState()); + assertEquals(0L, dto.membershipAuthorityGeneration()); + assertNotNull(dto.evaluatedAt()); } @Test - void listBootstrapCharactersUsesWorldQualifiedPointerLookupWhenRealmSlugDuplicatesAcrossWorlds() { + void getTenantMembershipForRuntimeReturnsInactiveMembershipWithIndependentGenerations() { Account account = new Account(); account.setId(11L); setPersistedAuthenticationIdentity(account); account.setUsername("demo"); + account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + AccountTenantMembership inactiveMembership = membership(account, 7L); + inactiveMembership.setGameplayAdmissionAllowed(false); + inactiveMembership.setLifecycleState("INACTIVE"); + inactiveMembership.setMembershipVersion(23L); + inactiveMembership.setMembershipAuthorityGeneration(41L); when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - - when(gameSessionClient.listGameplayRealms("sandbox")) - .thenReturn( - java.util.List.of( - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("sandbox") - .setRealmSlug("production") - .setDisplayName("Live Realm") - .setTenantId("7") - .setGameInstanceId("91") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setRequiresCharacterSelection(false) - .setStateScope("ISOLATED") - .setCharacterCreationPolicy("COPIED_ONLY") - .build())); - when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) - .thenReturn( - net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() - .setWorldSlug("demo") - .setWorldDisplayName("Demo World") - .setRealmSlug("production") - .setRealmDisplayName("Live Realm") - .setTenantId("7") - .setGameInstanceId("44") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build()); - when(gameSessionClient.getAdmissionPointer(7L, "sandbox", "production")) - .thenReturn( - net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() - .setWorldSlug("sandbox") - .setWorldDisplayName("Builder Sandbox") - .setRealmSlug("production") - .setRealmDisplayName("Live Realm") - .setTenantId("7") - .setGameInstanceId("91") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setRequiresCharacterSelection(false) - .setStateScope("ISOLATED") - .setCharacterCreationPolicy("COPIED_ONLY") - .build()); - net.firedevops.firemud.entitymanagement.v1.Character character = - net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() - .setId("char-sandbox-1") - .setName("BuilderMara") - .setLevel(9) - .build(); - when(entityManagementClient.listCharactersByAccount( - 7L, account.getAccountUuid(), 91L, PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) - .thenReturn(java.util.List.of(character)); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String connectScopeId = - service - .listBootstrapRealms(bootstrap.bootstrapToken(), "sandbox") - .getFirst() - .connectScopeId(); + .thenReturn(Optional.of(inactiveMembership)); - var characters = - service.listBootstrapCharacters( - bootstrap.bootstrapToken(), "sandbox", "production", connectScopeId); + var dto = service.getTenantMembershipForRuntime(11L, 7L, "req-1"); - assertEquals(1, characters.size()); - assertEquals("char-sandbox-1", characters.getFirst().characterId()); - assertEquals("BuilderMara", characters.getFirst().characterName()); - assertEquals("ISOLATED", characters.getFirst().stateScope()); - org.mockito.Mockito.verify(gameSessionClient, org.mockito.Mockito.times(2)) - .getAdmissionPointer(7L, "sandbox", "production"); + assertEquals(11L, dto.accountId()); + assertEquals(7L, dto.tenantId()); + assertTrue(dto.membershipExists()); + assertFalse(dto.gameplayAdmissionAllowed()); + assertEquals(23L, dto.membershipVersion()); + assertEquals("INACTIVE", dto.membershipLifecycleState()); + assertEquals(41L, dto.membershipAuthorityGeneration()); + assertNotNull(dto.evaluatedAt()); } @Test - void listBootstrapCharactersUsesSignedScopeToDisambiguateTenantIdentity() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId( - org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyLong())) - .thenReturn(Optional.of(membership(account, 7L))); - when(gameSessionClient.listGameplayRealms("demo")) - .thenReturn( - java.util.List.of( - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("demo") - .setRealmSlug("production") - .setDisplayName("Tenant Seven") - .setTenantId("7") - .setGameInstanceId("44") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build(), - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("demo") - .setRealmSlug("production") - .setDisplayName("Tenant Eight") - .setTenantId("8") - .setGameInstanceId("45") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID_TENANT_8) - .setCatalogRevision(23L) - .setPointerVersion(18L) - .setVisible(true) - .setPublicProductionRealm(true) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build())); - when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) - .thenReturn( - admissionPointer( - 7L, "demo", "production", "44", 17L, true, true, "SHARED", "ALLOW_NEW")); - when(gameSessionClient.getAdmissionPointer(8L, "demo", "production")) - .thenReturn( - admissionPointer( - 8L, "demo", "production", "45", 18L, true, true, "SHARED", "ALLOW_NEW")); - when(entityManagementClient.listCharactersByAccount( - 7L, account.getAccountUuid(), 44L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) - .thenReturn(java.util.List.of()); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").stream() - .filter(realm -> realm.tenantId() == 7L) - .findFirst() - .orElseThrow() - .connectScopeId(); - - var characters = - service.listBootstrapCharacters( - bootstrap.bootstrapToken(), "demo", "production", connectScopeId); + void getTenantMembershipForRuntimeRejectsMissingAccount() { + when(accountRepository.findById(11L)).thenReturn(Optional.empty()); - assertTrue(characters.isEmpty()); - org.mockito.Mockito.verify(gameSessionClient, org.mockito.Mockito.times(2)) - .getAdmissionPointer(7L, "demo", "production"); - org.mockito.Mockito.verify(gameSessionClient).getAdmissionPointer(8L, "demo", "production"); + assertThrows( + IllegalArgumentException.class, + () -> service.getTenantMembershipForRuntime(11L, 7L, "req-1")); } @Test - void listBootstrapCharactersRejectsPathThatDoesNotMatchSignedScope() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); + void getTenantEntitlementsForRuntimeFailsClosedBeforeReadingLegacyEvidence() { + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.getTenantEntitlementsForRuntime(7L, "req-current-entitlement")); - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); + verifyNoInteractions(retainedSubscriptionEvidenceRepository); + } + + @Test + void directScopeFacadePublishesTheExactCanonicalOwnersArtifactWithoutReminting() { + var f = canonicalJoinFixture(); + var owner = org.mockito.Mockito.mock(AccountCanonicalPublicRealmScopeOwner.class); + var retained = org.mockito.Mockito.mock(RealmScope.class); + when(retained.scope()).thenReturn(f.scope); + var caller = f.directCaller(f.requestId); + var target = + new DirectTextJoinTarget( + f.scope.tenantId(), + f.scope.realmId(), + f.scope.worldSlug(), + f.scope.realmSlug(), + f.scope.playableStateNamespaceId(), + f.scope.playableStateScope(), + f.scope.gameInstanceId(), + f.scope.catalogRevision(), + f.scope.pointerVersion()); + when(owner.issueDirectTextScope(caller, target)).thenReturn(retained); + service.setCanonicalPublicRealmScopeOwner(owner); + var result = service.issueDirectTextConnectScope(caller, target); + assertEquals(f.scope.connectScopeId(), result.connectScopeId()); + assertEquals(f.scope.evaluatedAt(), result.evaluatedAt()); + assertEquals(f.scope.connectScopeExpiresAt(), result.connectScopeExpiresAt()); + org.mockito.Mockito.verify(owner).issueDirectTextScope(caller, target); + verifyNoInteractions( + sessionService, f.sources, accountJoinOperationRepository, accountAuditOutboxRepository); + } - AuthenticationException ex = + @ParameterizedTest + @ValueSource( + strings = { + "CONNECT_SCOPE_INVALID", + "CONNECT_SCOPE_MISMATCH", + "AUTH_UNAVAILABLE", + "ENTITLEMENT_UNAVAILABLE", + "TENANT_BILLING_BLOCKED", + "ADMISSION_POINTER_UNAVAILABLE" + }) + void directScopeFacadePreservesCanonicalAuthenticationCurrentnessAndBillingRefusal(String code) { + var owner = org.mockito.Mockito.mock(AccountCanonicalPublicRealmScopeOwner.class); + service.setCanonicalPublicRealmScopeOwner(owner); + var refusal = new AuthenticationException(code, "controlled canonical scope owner refusal"); + when(owner.issueDirectTextScope( + org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any())) + .thenThrow(refusal); + var f = canonicalJoinFixture(); + assertSame( + refusal, assertThrows( AuthenticationException.class, () -> - service.listBootstrapCharacters( - bootstrap.bootstrapToken(), "sandbox", "production", connectScopeId)); - - assertEquals("CONNECT_SCOPE_MISMATCH", ex.getCode()); - verifyNoInteractions(entityManagementClient); + service.issueDirectTextConnectScope( + f.directCaller(f.requestId), + new DirectTextJoinTarget( + f.scope.tenantId(), + f.scope.realmId(), + f.scope.worldSlug(), + f.scope.realmSlug(), + f.scope.playableStateNamespaceId(), + f.scope.playableStateScope(), + f.scope.gameInstanceId(), + f.scope.catalogRevision(), + f.scope.pointerVersion())))); + verifyNoInteractions( + accountJoinOperationRepository, + accountTenantMembershipRepository, + accountAuditOutboxRepository); } @Test - void listBootstrapCharactersRejectsChangedCanonicalRealmId() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - net.firedevops.firemud.gamesession.v1.GameplayRealm changedRealm = - gameSessionClient.listGameplayRealms("demo").getFirst().toBuilder() - .setRealmId("57c58f36-c5ea-4aa8-8ef7-91a45e407f01") - .build(); - when(gameSessionClient.listGameplayRealms("demo")).thenReturn(java.util.List.of(changedRealm)); - net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer changedAdmissionPointer = - gameSessionClient.getAdmissionPointer(7L, "demo", "production").toBuilder() - .setRealmId("57c58f36-c5ea-4aa8-8ef7-91a45e407f01") - .build(); - when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) - .thenReturn(changedAdmissionPointer); + void directScopeWithoutCanonicalCompositionRefusesBeforeAccountWork() { + assertEquals( + "AUTH_UNAVAILABLE", + assertThrows( + AuthenticationException.class, + () -> service.issueDirectTextConnectScope(null, null)) + .getCode()); + verifyNoInteractions(accountRepository); + } - AuthenticationException ex = + @ParameterizedTest + @ValueSource(strings = {"malformed", "", "numeric-signed"}) + void issueConnectTokenRejectsInvalidScopeWithoutIssuanceOrReplayMutation(String artifact) { + var f = canonicalJoinFixture(); + service.setCanonicalScopeConsumers( + new net.firedevops.firemud.accountservice.service.AccountCanonicalConnectScopeReader( + jwtUtil, accountConnectScopeRepository, transactionManager, Clock.systemUTC()), + f.targets, + f.sources, + f.demos, + f.hosting, + f.observer, + f.terminal, + "test", + Clock.systemUTC()); + String token = + artifact.equals("numeric-signed") + ? jwtUtil.generateToken( + "11", Map.of("aud", "bootstrap-connect-scope", "accountId", "11")) + : artifact; + assertEquals( + "CONNECT_SCOPE_INVALID", assertThrows( - AuthenticationException.class, - () -> - service.listBootstrapCharacters( - bootstrap.bootstrapToken(), "demo", "production", connectScopeId)); + AuthenticationException.class, + () -> + service.issueConnectToken(f.bootstrap, new ConnectTokenRequest(token, "held"))) + .getCode()); + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) + .getConnectTokenReplay( + org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.anyString()); + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) + .storeConnectTokenReplay( + org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.anyLong()); + verifyNoInteractions(accountTenantMembershipRepository, accountAuditOutboxRepository); + } - assertEquals("CONNECT_SCOPE_MISMATCH", ex.getCode()); - verifyNoInteractions(entityManagementClient); + @Test + void issueConnectTokenValidatesCanonicalScopeThenKeepsIssuerHeldWithoutReplayOrSessionEffects() { + var f = canonicalJoinFixture(); + assertEquals( + "AUTH_UNAVAILABLE", + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + f.bootstrap, + new ConnectTokenRequest(f.scope.connectScopeId(), "held-issuer"))) + .getCode()); + org.mockito.Mockito.verify(f.reader).read(f.scope.accountId(), f.scope.connectScopeId()); + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) + .getConnectTokenReplay( + org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.anyString()); + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) + .storeConnectTokenReplay( + org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.anyLong()); + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) + .storeSession( + org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.anyLong()); + verifyNoInteractions( + accountTenantMembershipRepository, + accountAuditOutboxRepository, + f.targets, + f.sources, + f.demos, + f.hosting, + f.observer, + f.terminal); } @Test - void listBootstrapRealmsExcludesNonPublicRealmWithoutGrant() { + void listBootstrapWorldsReadsFreshEntitlementsOncePerCanonicalTenantPerInvocation() { Account account = new Account(); account.setId(11L); setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.empty()); - Subscription active = new Subscription(); - active.setId(22L); - active.setTenantId(7L); - active.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); - when(gameSessionClient.listGameplayRealms("demo")) - .thenReturn( - java.util.List.of( - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("demo") - .setRealmSlug("preview") - .setDisplayName("Preview Realm") - .setTenantId("7") - .setGameInstanceId("55") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(19L) - .setVisible(false) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build())); - when(gameSessionClient.getAdmissionPointer(7L, "demo", "preview")) - .thenReturn( - admissionPointer( - 7L, "demo", "preview", "55", 19L, false, false, "SHARED", "ALLOW_NEW")); + UUID demoTenant = UUID.fromString("22222222-2222-4222-8222-222222222222"); + UUID sandboxTenant = UUID.fromString("33333333-3333-4333-8333-333333333333"); + var sourceTargets = + List.of( + publicDiscoveryTarget(sandboxTenant, "sandbox", "Sandbox World"), + publicDiscoveryTarget(demoTenant, "demo", "Demo World")); + var discovery = composeCanonicalWorldDiscovery(sourceTargets); + var evaluatedAt = Instant.now().minusSeconds(1); + when(discovery.entitlements().evaluate(demoTenant)) + .thenReturn(publicDiscoveryEntitlement(demoTenant, true, evaluatedAt)); + when(discovery.entitlements().evaluate(sandboxTenant)) + .thenReturn(publicDiscoveryEntitlement(sandboxTenant, true, evaluatedAt)); PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + when(accountRepository.findByAccountUuid(account.getAccountUuid())) + .thenReturn(Optional.of(account)); - var realms = service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo"); + var firstCall = service.listBootstrapWorlds(bootstrap.bootstrapToken()); + var secondCall = service.listBootstrapWorlds(bootstrap.bootstrapToken()); - assertEquals(0, realms.size()); + var expectedWorlds = + List.of( + new BootstrapWorldDto("tenant-demo", "demo", "Demo World"), + new BootstrapWorldDto("tenant-sandbox", "sandbox", "Sandbox World")); + assertEquals(expectedWorlds, firstCall); + assertEquals(expectedWorlds, secondCall); + org.mockito.Mockito.verify(discovery.entitlements(), org.mockito.Mockito.times(2)) + .evaluate(demoTenant); + org.mockito.Mockito.verify(discovery.entitlements(), org.mockito.Mockito.times(2)) + .evaluate(sandboxTenant); + org.mockito.Mockito.verify(discovery.targets(), org.mockito.Mockito.times(4)) + .listVisiblePublicProductionAdmissionTargets(org.mockito.ArgumentMatchers.any(UUID.class)); } - @ParameterizedTest - @CsvSource({"true, false", "false, true"}) - void listBootstrapRealmsExcludesNonPublicRealmWithoutMembershipEvenWithGrant( - boolean visible, boolean publicProductionRealm) { + @Test + void listBootstrapWorldsFiltersGameplayUnavailableTenantAndFailsWhenEntitlementIsUnavailable() { Account account = new Account(); account.setId(11L); setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.empty()); - Subscription active = new Subscription(); - active.setId(22L); - active.setTenantId(7L); - active.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); - when(gameSessionClient.listGameplayRealms("demo")) - .thenReturn( - java.util.List.of( - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("demo") - .setRealmSlug("preview") - .setDisplayName("Preview Realm") - .setTenantId("7") - .setGameInstanceId("55") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(19L) - .setVisible(visible) - .setPublicProductionRealm(publicProductionRealm) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build())); - when(gameSessionClient.getAdmissionPointer(7L, "demo", "preview")) - .thenReturn( - net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() - .setWorldSlug("demo") - .setWorldDisplayName("Demo World") - .setRealmSlug("preview") - .setRealmDisplayName("Preview Realm") - .setTenantId("7") - .setGameInstanceId("55") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(19L) - .setVisible(visible) - .setPublicProductionRealm(publicProductionRealm) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build()); - when(accountRealmAccessGrantRepository.existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( - 11L, 7L, "demo", "preview")) - .thenReturn(true); + UUID demoTenant = UUID.fromString("22222222-2222-4222-8222-222222222222"); + UUID sandboxTenant = UUID.fromString("33333333-3333-4333-8333-333333333333"); + var sourceTargets = + List.of( + publicDiscoveryTarget(demoTenant, "demo", "Demo World"), + publicDiscoveryTarget(sandboxTenant, "sandbox", "Sandbox World")); + var discovery = composeCanonicalWorldDiscovery(sourceTargets); + var evaluatedAt = Instant.now().minusSeconds(1); + when(discovery.entitlements().evaluate(demoTenant)) + .thenReturn(publicDiscoveryEntitlement(demoTenant, true, evaluatedAt)) + .thenReturn(publicDiscoveryEntitlement(demoTenant, true, evaluatedAt)) + .thenThrow( + new AccountPublicBootstrapEntitlementOwner.UnavailableException( + new IllegalStateException("controlled current-source failure"))); + when(discovery.entitlements().evaluate(sandboxTenant)) + .thenReturn(publicDiscoveryEntitlement(sandboxTenant, false, evaluatedAt)) + .thenThrow( + new AccountPublicBootstrapEntitlementOwner.UnavailableException( + new IllegalStateException("controlled current-source failure"))); PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - assertTrue(service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").isEmpty()); - } + when(accountRepository.findByAccountUuid(account.getAccountUuid())) + .thenReturn(Optional.of(account)); - @ParameterizedTest - @CsvSource({"true, false", "false, true"}) - void listBootstrapRealmsIncludesNonPublicRealmWhenMembershipAndGrantPresent( - boolean visible, boolean publicProductionRealm) { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - Subscription active = new Subscription(); - active.setId(22L); - active.setTenantId(7L); - active.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); - when(gameSessionClient.listGameplayRealms("demo")) - .thenReturn( - java.util.List.of( - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("demo") - .setRealmSlug("preview") - .setDisplayName("Preview Realm") - .setTenantId("7") - .setGameInstanceId("55") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(19L) - .setVisible(visible) - .setPublicProductionRealm(publicProductionRealm) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build())); - when(gameSessionClient.getAdmissionPointer(7L, "demo", "preview")) - .thenReturn( - admissionPointer( - 7L, - "demo", - "preview", - "55", - 19L, - visible, - publicProductionRealm, - "SHARED", - "ALLOW_NEW")); - when(accountRealmAccessGrantRepository.existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( - 11L, 7L, "demo", "preview")) - .thenReturn(true); + var worldsWithUnavailableTenant = service.listBootstrapWorlds(bootstrap.bootstrapToken()); - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + assertEquals( + java.util.List.of("demo"), + worldsWithUnavailableTenant.stream().map(world -> world.worldSlug()).toList()); + AuthenticationException unavailableSandbox = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapWorlds(bootstrap.bootstrapToken())); + + assertEquals("ENTITLEMENT_UNAVAILABLE", unavailableSandbox.getCode()); + AuthenticationException unavailable = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapWorlds(bootstrap.bootstrapToken())); - var realms = service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo"); + assertEquals("ENTITLEMENT_UNAVAILABLE", unavailable.getCode()); + org.mockito.Mockito.verify(discovery.entitlements(), org.mockito.Mockito.times(3)) + .evaluate(demoTenant); + // Every discovery call joins all independent tenant reads, including a failed call. + org.mockito.Mockito.verify(discovery.entitlements(), org.mockito.Mockito.times(3)) + .evaluate(sandboxTenant); + } - assertEquals(1, realms.size()); - assertEquals("preview", realms.getFirst().realmSlug()); - assertFalse(realms.getFirst().connectScopeId().isBlank()); + @Test + void bootstrapPublicRealmFacadePreservesEmptyCanonicalOwnerResult() { + var owner = org.mockito.Mockito.mock(AccountCanonicalPublicRealmScopeOwner.class); + service.setCanonicalPublicRealmScopeOwner(owner); + when(owner.listRealmScopes("bootstrap", "source-tenant", "demo")).thenReturn(List.of()); + assertTrue(service.listBootstrapRealms("bootstrap", "source-tenant", "demo").isEmpty()); + verifyNoInteractions(accountRealmAccessGrantRepository, accountTenantMembershipRepository); } @Test @@ -6262,29 +4230,37 @@ void exportTenantDataUsesPublicAccountUuidAndRetainsTenantLocalFields() { void deleteAccountRefusesNonterminalSubscription() { Account account = new Account(); account.setId(2L); - Subscription subscription = new Subscription(); - subscription.setStatus("active"); - subscription.setAccount(account); - subscription.setTenantId(7L); + RetainedSubscriptionEvidence subscription = + new RetainedSubscriptionEvidence( + 91L, 2L, "unqualified", "active", null, null, 7L, 19L, UUID.randomUUID()); when(accountRepository.findById(2L)).thenReturn(Optional.of(account)); - when(subscriptionRepository.findByAccountId(2L)).thenReturn(java.util.List.of(subscription)); + when(retainedSubscriptionEvidenceRepository.findHistoryByAccountId(2L)) + .thenReturn(java.util.List.of(subscription)); AccountLifecycleException ex = assertThrows(AccountLifecycleException.class, () -> service.deleteAccount(2L)); assertEquals("ACCOUNT_DELETE_ACTIVE_BILLING_OWNER", ex.getCode()); + org.mockito.Mockito.verify(retainedSubscriptionEvidenceRepository).findHistoryByAccountId(2L); } @Test void deleteAccountRemainsUnavailableAfterTerminalSubscriptionsWithoutChildWrites() { Account account = new Account(); account.setId(2L); - Subscription subscription = new Subscription(); - subscription.setStatus("canceled"); - subscription.setEndedAt(java.time.LocalDateTime.now()); - subscription.setAccount(account); - subscription.setTenantId(7L); + RetainedSubscriptionEvidence subscription = + new RetainedSubscriptionEvidence( + 91L, + 2L, + "unqualified", + "canceled", + null, + java.time.LocalDateTime.now(), + 7L, + 19L, + UUID.randomUUID()); when(accountRepository.findById(2L)).thenReturn(Optional.of(account)); - when(subscriptionRepository.findByAccountId(2L)).thenReturn(java.util.List.of(subscription)); + when(retainedSubscriptionEvidenceRepository.findHistoryByAccountId(2L)) + .thenReturn(java.util.List.of(subscription)); AccountLifecycleException ex = assertThrows(AccountLifecycleException.class, () -> service.deleteAccount(2L)); @@ -6298,9 +4274,7 @@ void deleteAccountRemainsUnavailableAfterTerminalSubscriptionsWithoutChildWrites paymentTransactionRepository, profileRepository, accountTenantMembershipRepository); - org.mockito.Mockito.verify(subscriptionRepository).findByAccountId(2L); - org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.never()) - .deleteByAccountId(2L); + org.mockito.Mockito.verify(retainedSubscriptionEvidenceRepository).findHistoryByAccountId(2L); org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()).delete(account); } @@ -6914,14 +4888,6 @@ void updateLoginAuthModesFailsClosedBeforeReadingOrPersistingAccount() { org.mockito.Mockito.verifyNoInteractions(accountRepository); } - private Account directTextAccount() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - return account; - } - private void setPersistedAuthenticationIdentity(Account account) { setPersistedAuthenticationIdentity( account, AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); @@ -6957,29 +4923,62 @@ private enum InvalidAuthenticationIdentity { CONTRADICTORY_SOURCE_ROW } - private static DirectTextCallerContext directTextCaller() { - return new DirectTextCallerContext( - 11L, - 7L, - UUID.fromString(REALM_ID), - PLAYABLE_STATE_NAMESPACE_ID, - "SHARED", - 44L, - "session-1", - "direct-text-request-1"); - } - - private static DirectTextJoinTarget directTextTarget() { - return new DirectTextJoinTarget( - 7L, - UUID.fromString(REALM_ID), - "demo", - "production", - PLAYABLE_STATE_NAMESPACE_ID, - "SHARED", - 44L, - 23L, - 17L); + private void composeOrdinaryBootstrapWorldDiscovery() { + UUID tenant = UUID.fromString("22222222-2222-4222-8222-222222222222"); + var fixture = + composeCanonicalWorldDiscovery( + List.of(publicDiscoveryTarget(tenant, "demo", "Demo World"))); + when(fixture.entitlements().evaluate(tenant)) + .thenReturn(publicDiscoveryEntitlement(tenant, true, Instant.now().minusSeconds(1))); + } + + private record CanonicalWorldDiscoveryFixture( + CanonicalGameplayAdmissionDecisionReadClient targets, + AccountPublicBootstrapEntitlementOwner entitlements) {} + + private CanonicalWorldDiscoveryFixture composeCanonicalWorldDiscovery(List targets) { + CanonicalGameplayAdmissionDecisionReadClient targetReader = + org.mockito.Mockito.mock(CanonicalGameplayAdmissionDecisionReadClient.class); + var collection = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.gamesession + .CanonicalGameplayAdmissionDecisionReadGrpcCodec.VisiblePublicProductionTargets + .class); + when(collection.targets()).thenReturn(targets); + when(targetReader.listVisiblePublicProductionAdmissionTargets( + org.mockito.ArgumentMatchers.any(UUID.class))) + .thenReturn(collection); + AccountPublicBootstrapEntitlementOwner entitlements = + org.mockito.Mockito.mock(AccountPublicBootstrapEntitlementOwner.class); + var callerVerifier = + new AccountPlayerBootstrapCallerVerifier(jwtUtil, accountRepository, sessionService); + service.setPublicBootstrapWorldsOwner( + new AccountPublicBootstrapWorldsOwner( + callerVerifier, targetReader, entitlements, Clock.systemUTC())); + return new CanonicalWorldDiscoveryFixture(targetReader, entitlements); + } + + private static Target publicDiscoveryTarget(UUID tenantId, String worldSlug, String displayName) { + Target target = org.mockito.Mockito.mock(Target.class); + when(target.canonicalTenantId()).thenReturn(tenantId); + when(target.tenantSlug()).thenReturn("tenant-" + worldSlug); + when(target.worldSlug()).thenReturn(worldSlug); + when(target.worldDisplayName()).thenReturn(displayName); + return target; + } + + private static AccountPublicBootstrapEntitlementOwner.Evaluation publicDiscoveryEntitlement( + UUID tenantId, boolean gameplayAvailable, Instant evaluatedAt) { + return new AccountPublicBootstrapEntitlementOwner.Evaluation( + tenantId, + net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository + .SourceKind.NON_PAID_DEMO, + gameplayAvailable, + false, + 1L, + 1L, + evaluatedAt, + evaluatedAt.plusSeconds(30)); } private static String hash(String password) { @@ -6992,47 +4991,6 @@ private static String hash(String password) { } } - private static net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer admissionPointer( - long tenantId, - String worldSlug, - String realmSlug, - String gameInstanceId, - long pointerVersion, - boolean visible, - boolean publicProductionRealm, - String stateScope, - String characterCreationPolicy) { - return net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() - .setWorldSlug(worldSlug) - .setWorldDisplayName("demo".equals(worldSlug) ? "Demo World" : "Builder Sandbox") - .setRealmSlug(realmSlug) - .setRealmDisplayName("production".equals(realmSlug) ? "Live Realm" : "Preview Realm") - .setTenantId(Long.toString(tenantId)) - .setGameInstanceId(gameInstanceId) - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(playableStateNamespaceIdForTenant(tenantId)) - .setCatalogRevision(23L) - .setPointerVersion(pointerVersion) - .setVisible(visible) - .setPublicProductionRealm(publicProductionRealm) - .setRequiresCharacterSelection(false) - .setStateScope(stateScope) - .setCharacterCreationPolicy(characterCreationPolicy) - .build(); - } - - private static String playableStateNamespaceIdForTenant(long tenantId) { - return switch ((int) tenantId) { - case 7 -> PLAYABLE_STATE_NAMESPACE_ID; - case 8 -> PLAYABLE_STATE_NAMESPACE_ID_TENANT_8; - default -> - UUID.nameUUIDFromBytes( - ("playable-state-namespace-" + tenantId) - .getBytes(java.nio.charset.StandardCharsets.UTF_8)) - .toString(); - }; - } - private static AccountTenantMembership membership(Account account, long tenantId) { AccountTenantMembership membership = new AccountTenantMembership(); membership.setId(tenantId * 100 + (account.getId() == null ? 0L : account.getId())); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/LegacySubscriptionContainmentTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/LegacySubscriptionContainmentTest.java new file mode 100644 index 0000000000..51af089c77 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/LegacySubscriptionContainmentTest.java @@ -0,0 +1,176 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.stub.StreamObserver; +import java.lang.reflect.Modifier; +import java.time.LocalDateTime; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeRequest; +import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.RetainedSubscriptionEvidence; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; +import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; +import net.firedevops.firemud.accountservice.service.exception.AccountLifecycleException; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.transaction.PlatformTransactionManager; + +/** + * Local containment only; canonical positive producer and admission remain separate obligations. + */ +class LegacySubscriptionContainmentTest { + @Mock private AccountRepository accounts; + @Mock private AccountJoinOperationRepository joins; + @Mock private RetainedSubscriptionEvidenceRepository retained; + @Mock private AccountAuthorityOutboxRepository outbox; + @Mock private AccountPasswordResetOperationRepository resets; + @Mock private AccountLogoutAllOperationRepository logouts; + @Mock private AccountSecurityStateOperationRepository security; + @Mock private PlatformTransactionManager transactions; + @InjectMocks private AccountServiceImpl service; + private AutoCloseable mocks; + + @BeforeEach + void setUp() { + mocks = MockitoAnnotations.openMocks(this); + } + + @AfterEach + void tearDown() throws Exception { + mocks.close(); + } + + @ParameterizedTest + @ValueSource(strings = {"active", "trialing", "past_due", "grace", "canceled"}) + void retainedStatusAndCountersCannotProduceAPositiveServiceOrRuntimeRpc(String status) { + when(retained.findHistoryByAccountId(2L)).thenReturn(List.of(evidence(status, null))); + + AuthenticationException denied = + assertThrows( + AuthenticationException.class, + () -> service.getTenantEntitlementsForRuntime(7L, "retained-is-not-authority")); + assertThat(denied.getCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); + + AccountGrpcService rpc = new AccountGrpcService(null, service, null, "test"); + AtomicReference response = new AtomicReference<>(); + var observer = + new StreamObserver() { + @Override + public void onNext(GetTenantEntitlementsForRuntimeResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable failure) { + throw new AssertionError( + "Expected the existing response-level unavailable outcome", failure); + } + + @Override + public void onCompleted() {} + }; + for (String workload : List.of("game-session-service", "world-management-service")) { + response.set(null); + Context context = + Context.ROOT.withValue( + GrpcPeerIdentity.CONTEXT_KEY, + new GrpcPeerIdentity("spiffe://firemud/ns/test/sa/" + workload, "test", workload)); + context.run( + () -> + rpc.getTenantEntitlementsForRuntime( + GetTenantEntitlementsForRuntimeRequest.newBuilder() + .setTenantId("7") + .setRequestId("retained-is-not-authority") + .build(), + observer)); + assertThat(response.get()).isNotNull(); + assertThat(response.get().getError().getCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); + assertThat(response.get().getGameplayAvailable()).isFalse(); + assertThat(response.get().getAllowPublicJoin()).isFalse(); + assertThat(response.get().getEntitlementVersion()).isZero(); + assertThat(response.get().getTenantBillingSequence()).isZero(); + assertThat(response.get().getEvaluatedAt()).isEmpty(); + } + verifyNoInteractions( + retained, accounts, joins, outbox, resets, logouts, security, transactions); + } + + @ParameterizedTest + @CsvSource({ + "active,false,ACCOUNT_DELETE_ACTIVE_BILLING_OWNER", + "canceled,false,ACCOUNT_DELETE_ACTIVE_BILLING_OWNER", + "canceled,true,ACCOUNT_DELETE_UNAVAILABLE", + "expired,true,ACCOUNT_DELETE_UNAVAILABLE" + }) + void deletionStillReadsHistoricalBlockersAndNeverGainsErasureAuthority( + String status, boolean ended, String expectedCode) { + Account account = new Account(); + account.setId(2L); + when(accounts.findById(2L)).thenReturn(Optional.of(account)); + when(retained.findHistoryByAccountId(2L)) + .thenReturn(List.of(evidence(status, ended ? LocalDateTime.of(2025, 1, 2, 3, 4) : null))); + + AccountLifecycleException denied = + assertThrows(AccountLifecycleException.class, () -> service.deleteAccount(2L)); + + assertThat(denied.getCode()).isEqualTo(expectedCode); + verify(retained).findHistoryByAccountId(2L); + verify(joins).hasRetainedOperation(2L); + verifyNoInteractions(outbox, resets, logouts, security, transactions); + } + + @Test + void retainedJoinReceiptKeepsItsEarlierDeletionDenialBeforeHistoricalBillingReads() { + Account account = new Account(); + account.setId(2L); + when(accounts.findById(2L)).thenReturn(Optional.of(account)); + when(joins.hasRetainedOperation(2L)).thenReturn(true); + + AccountLifecycleException denied = + assertThrows(AccountLifecycleException.class, () -> service.deleteAccount(2L)); + + assertThat(denied.getCode()).isEqualTo("ACCOUNT_DELETE_JOIN_RECEIPT_RETAINED"); + verifyNoInteractions(retained, outbox, resets, logouts, security, transactions); + } + + @Test + void historicalOwnerHasNoGenericMutationOrCurrentTenantAuthorityApi() { + assertThat(RetainedSubscriptionEvidence.class.isRecord()).isTrue(); + assertThat( + Arrays.stream(RetainedSubscriptionEvidenceRepository.class.getDeclaredMethods()) + .filter(method -> Modifier.isPublic(method.getModifiers())) + .map(method -> method.getName()) + .toList()) + .containsExactly("findHistoryByAccountId"); + } + + private static RetainedSubscriptionEvidence evidence(String status, LocalDateTime ended) { + return new RetainedSubscriptionEvidence( + 91L, 2L, "unqualified", status, null, ended, 7L, 19L, UUID.randomUUID()); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifierTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifierTest.java index cde168fd95..86c606f8ee 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifierTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifierTest.java @@ -39,6 +39,7 @@ import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.GameplayLoginReplayState; import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationPendingIdentity; import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; import net.firedevops.firemud.accountservice.service.session.AccountGameplayCanonicalLoginOwner; @@ -107,8 +108,6 @@ class AccountGameplayPrimaryCredentialVerifierTest { net.firedevops.firemud.accountservice.service .AccountPasswordResetDraftSourceChangeRepository.class), mock(net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository.class), - mock( - net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository.class), mock( net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository .class), @@ -124,7 +123,7 @@ class AccountGameplayPrimaryCredentialVerifierTest { mock(net.firedevops.firemud.accountservice.repository.ProfileRepository.class), mock(net.firedevops.firemud.accountservice.mapper.ProfileMapper.class), mock(net.firedevops.firemud.accountservice.repository.PaymentTransactionRepository.class), - mock(net.firedevops.firemud.accountservice.repository.SubscriptionRepository.class), + org.mockito.Mockito.mock(RetainedSubscriptionEvidenceRepository.class), mock(net.firedevops.firemud.accountservice.repository.ExternalAccountRepository.class), mock(net.firedevops.firemud.accountservice.repository.PasswordResetTokenRepository.class), mock( @@ -135,8 +134,6 @@ class AccountGameplayPrimaryCredentialVerifierTest { mock(net.firedevops.firemud.accountservice.config.MailProperties.class), mock(net.firedevops.firemud.accountservice.config.AccountTokenProperties.class), mock(net.firedevops.firemud.common.security.JwtAuthProperties.class), - mock(net.firedevops.firemud.accountservice.client.GameSessionClient.class), - mock(net.firedevops.firemud.accountservice.client.EntityManagementClient.class), jwt, sessions, transactions); diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java index 34194c27cf..c08602aa0a 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java @@ -464,6 +464,29 @@ record IssuedCreator( CapturedEnvironmentBoundary environment, AccountControlUiOwnerSourcesFixture sources) {} + /** Same-package reuse of genuine certified ACCOUNT issuance, separate from tenant creation. */ + IssuedAccount issueCertifiedAccount(String password) { + var account = f.createCertifiedGlobalAccount(password); + var request = + new AccountControlUiIssuanceService.AccountSignInRequest( + UUID.randomUUID(), account.getEmail(), password, UUID.randomUUID()); + String compact; + try (var peer = + AccountControlUiOwnerSourcesFixture.withPeer( + AccountControlUiOwnerSourcesFixture.CALLER); + var issued = issuance.issueAccount(request)) { + compact = new String(issued.compactBytes(), StandardCharsets.US_ASCII); + } + assertThat(actors.authenticateAccount(compact).accountId()).isEqualTo(account.getAccountUuid()); + return new IssuedAccount(account, compact, actors, f); + } + + record IssuedAccount( + net.firedevops.firemud.accountservice.entity.Account account, + String compact, + AccountControlUiActorService actors, + AccountControlUiOwnerSourcesFixture sources) {} + // These fixture entry points use actual Account owners with test-only creator/legal, // environment, signer-platform and Redis inputs. They confer no production authority. public net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderGrpcCodec.Request diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java index db2d28a421..f3124dfc74 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java @@ -56,6 +56,7 @@ import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; import net.firedevops.firemud.accountservice.service.AccountCreatorMembershipSourceReader; import net.firedevops.firemud.accountservice.service.AccountTenantCreationBootstrapAuthorizationSource; import net.firedevops.firemud.accountservice.service.AccountTenantCreationBootstrapService; @@ -406,9 +407,6 @@ final class AccountControlUiOwnerSourcesFixture { net.firedevops.firemud.accountservice.service .AccountPasswordResetDraftSourceChangeRepository.class), mock(AccountAuditOutboxRepository.class), - mock( - net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository - .class), mock(AccountJoinOperationRepository.class), challenges, null, // Realm grants are not used by primary authentication. @@ -417,7 +415,8 @@ final class AccountControlUiOwnerSourcesFixture { null, // Profiles are not used by primary authentication. null, // Profile mapper is not used by primary authentication. null, // Payment transactions are not used by primary authentication. - null, // Subscriptions are not used by primary authentication. + // Retained evidence is not read by primary authentication. + org.mockito.Mockito.mock(RetainedSubscriptionEvidenceRepository.class), null, // External identities are not used by primary authentication. null, // Password reset tokens are not used by primary authentication. null, // Email verification tokens are not used by primary authentication. @@ -426,8 +425,6 @@ final class AccountControlUiOwnerSourcesFixture { null, // Mail properties are not used by primary authentication. null, // Token properties are not used by primary authentication. null, // JWT auth properties are not used by primary authentication. - null, // Game Session client is not used by primary authentication. - null, // Entity Management client is not used by primary authentication. null, // JWT utility is not used by primary authentication. null, // Session service is not used by primary authentication. manager); diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedEntitlementFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedEntitlementFixture.java new file mode 100644 index 0000000000..64c6e0907d --- /dev/null +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedEntitlementFixture.java @@ -0,0 +1,561 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import io.grpc.Context; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.security.SecureRandom; +import java.time.Clock; +import java.time.Instant; +import java.util.Arrays; +import java.util.Base64; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; +import net.firedevops.firemud.accountservice.config.AccountTokenProperties; +import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; +import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; +import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; +import net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget; +import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountCanonicalRuntimeMembershipSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinTerminalProof; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository.SourceKind; +import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantIdentityResolver; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.repository.LegacyTenantSourceEvidence; +import net.firedevops.firemud.accountservice.service.AccountCanonicalConnectScopeReader; +import net.firedevops.firemud.accountservice.service.AccountCanonicalFirstJoinTerminalCoordinator; +import net.firedevops.firemud.accountservice.service.AccountCanonicalPublicRealmScopeOwner; +import net.firedevops.firemud.accountservice.service.AccountCanonicalPublicRealmScopeOwner.RealmScope; +import net.firedevops.firemud.accountservice.service.AccountHostingSubscriptionLifecycleService; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer; +import net.firedevops.firemud.accountservice.service.AccountPlayerAdmissionEntitlementOwner; +import net.firedevops.firemud.accountservice.service.AccountPublicBootstrapEntitlementOwner; +import net.firedevops.firemud.accountservice.service.impl.AccountPlayerAdmissionEntitlementGrpcService; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Snapshot; +import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import org.springframework.aop.framework.ProxyFactory; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.annotation.AnnotationTransactionAttributeSource; +import org.springframework.transaction.interceptor.TransactionInterceptor; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Separate global-player composition over the original Account database and real protected target + * client. Repository insertion, absence enrollment, DEMO provisioning, LOGIN/currentness, canonical + * scope production and the entitlement receiver use their actual owners. The player has no tenant + * membership, no roles and no admission permission until the explicit first-JOIN method runs; the + * original creator is never rewritten. + * + *

Construct only after the original creator/operator authoring sequence is finished: DEMO + * advances tenant authority, which deliberately makes the creator's historical baseline unsuitable + * for current runtime membership evidence. Scope peer/context custody, demo policy, enrollment/OTP + * delivery and test signing-key custody remain controlled. Paid and browser-only dependencies fail + * on every call and cannot supply successful evidence. This helper borrows connections, registers + * no runtime beans, opens no listener and claims no public ingress, World hold or PLAY authority. + * Its optional first JOIN proves only Account-local atomic membership/event/audit/receipt + * ownership. + */ +public final class AccountPlayerAdmissionSharedEntitlementFixture { + private static final SecureRandom RANDOM = new SecureRandom(); + private final AccountControlUiOwnerSourcesFixture sources; + private final AccountPlayerAdmissionSharedOwnerFixture login; + private final AccountCanonicalRuntimeMembershipSnapshotRepository snapshots; + private final AccountDemoTenantEntitlementRepository demos; + private final DemoTenantEntitlementSnapshot demo; + private final AccountCanonicalPublicRealmScopeOwner scopes; + private final AccountCanonicalConnectScopeReader scopeReader; + private final CanonicalGameplayAdmissionDecisionReadClient targets; + private final AccountAuthoritySourceEvidenceRepository authority; + private final AccountAuthorityOutboxRepository outbox; + private final AccountTenantMembershipRepository members; + private final AccountMembershipPairAuthorityRepository pairs; + private final AccountJoinOperationRepository operations; + private final AccountAuditOutboxRepository audits; + private final AccountCanonicalFirstJoinTerminalCoordinator firstJoin; + private final TransactionTemplate joinTransaction; + private final AccountPlayerAdmissionEntitlementGrpcService receiver; + private final AccountHostingSubscriptionLifecycleRepository unusedPaidRepository; + private final StripeHostingSubscriptionObserver unusedProvider; + private final SessionService unusedBrowserSessions; + private final Clock clock; + private final String namespace; + + public AccountPlayerAdmissionSharedEntitlementFixture( + AccountControlUiOriginalOrderFixture original, + Path temporary, + CanonicalGameplayAdmissionDecisionReadClient genuineTargets, + DemoTenantEntitlementRequest demoRequest) + throws Exception { + this(original, temporary, genuineTargets, demoRequest, Clock.systemUTC()); + } + + public AccountPlayerAdmissionSharedEntitlementFixture( + AccountControlUiOriginalOrderFixture original, + Path temporary, + CanonicalGameplayAdmissionDecisionReadClient genuineTargets, + DemoTenantEntitlementRequest demoRequest, + Clock clock) + throws Exception { + Objects.requireNonNull(original, "Original Account fixture is required"); + targets = + Objects.requireNonNull( + genuineTargets, "Actual initialized protected target client is required"); + this.clock = Objects.requireNonNull(clock, "Clock is required"); + FreshTenantCreationEvidence creation = original.creationEvidence(); + requireFirstDemoRequest(demoRequest, creation); + namespace = creation.targetNamespace(); + sources = original.preparedOriginalCreator().sources(); + login = AccountPlayerAdmissionSharedOwnerFixture.freshGlobalPlayer(original, temporary, clock); + + var generations = new AccountAuthorityGenerationRepository(sources.dsl); + outbox = new AccountAuthorityOutboxRepository(sources.dsl); + authority = new AccountAuthoritySourceEvidenceRepository(sources.dsl, generations, outbox); + var fresh = new FreshTenantIdentityAssociationRepository(sources.dsl, namespace); + pairs = new AccountMembershipPairAuthorityRepository(sources.dsl); + members = new AccountTenantMembershipRepository(sources.dsl, sources.accounts, fresh, pairs); + var roles = new AccountTenantMembershipRoleSnapshotRepository(sources.dsl); + var billing = new AccountTenantEntitlementOutboxRepository(sources.dsl); + var tenantEvents = + new AccountTenantAuthorityEventRepository(sources.dsl, outbox, billing, fresh, generations); + demos = + new AccountDemoTenantEntitlementRepository( + sources.dsl, fresh, generations, billing, tenantEvents); + snapshots = + new AccountCanonicalRuntimeMembershipSnapshotRepository( + sources.accounts, + generations, + authority, + tenantEvents, + fresh, + members, + pairs, + roles, + outbox); + // Missing rows alone are not evidence. Enroll the exact account-fenced absence baseline. + demo = + sources.tx( + () -> { + sources.accounts.findByAccountUuidForUpdate(login.accountId()).orElseThrow(); + generations.initialize(AuthorityScope.membership(login.accountId(), sources.tenant)); + members.prepareFreshCreatorAbsence(login.accountId(), sources.tenant); + return demos.provision(demoRequest, creation); + }); + + var retainedScopes = + new AccountConnectScopeRepository( + sources.dsl, + new AccountTenantIdentityResolver( + new ApprovedLegacyTenantAssociationRepository( + sources.dsl, new LegacyTenantSourceEvidence(sources.dsl), namespace), + namespace), + fresh); + unusedPaidRepository = excluded(AccountHostingSubscriptionLifecycleRepository.class); + unusedProvider = excluded(StripeHostingSubscriptionObserver.class); + unusedBrowserSessions = excluded(SessionService.class); + var hosting = + new AccountHostingSubscriptionLifecycleService( + unusedPaidRepository, unusedProvider, sources.manager); + var publicEntitlements = + new AccountPublicBootstrapEntitlementOwner( + tenantEvents, hosting, demos, sources.manager, clock); + var tokens = new AccountTokenProperties(); + var jwt = new JwtUtil(scopeSigningKey(), tokens.getConnectScopeExpirationMs()); + scopeReader = + new AccountCanonicalConnectScopeReader(jwt, retainedScopes, sources.manager, clock); + operations = new AccountJoinOperationRepository(sources.dsl, retainedScopes); + audits = new AccountAuditOutboxRepository(sources.dsl); + var membershipEvents = + transactional( + new AccountMembershipAuthorityEventProducer( + operations, + sources.accounts, + pairs, + members, + roles, + generations, + outbox, + authority, + tenantEvents, + demos), + AccountMembershipAuthorityEventProducer.class); + firstJoin = + transactional( + new AccountCanonicalFirstJoinTerminalCoordinator( + sources.accounts, + operations, + members, + roles, + outbox, + pairs, + audits, + membershipEvents), + AccountCanonicalFirstJoinTerminalCoordinator.class); + joinTransaction = new TransactionTemplate(sources.manager); + joinTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + joinTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + joinTransaction.setReadOnly(false); + scopes = + new AccountCanonicalPublicRealmScopeOwner( + new AccountPlayerBootstrapCallerVerifier(jwt, sources.accounts, unusedBrowserSessions), + genuineTargets, + publicEntitlements, + sources.accounts, + members, + fresh, + tenantEvents, + retainedScopes, + jwt, + tokens, + clock, + sources.manager, + namespace); + var owner = + new AccountPlayerAdmissionEntitlementOwner( + sources.dsl, + sources.accounts, + login.admissionCallerVerifier(), + login.issuanceRepository(), + snapshots, + retainedScopes, + unusedPaidRepository, + unusedProvider, + demos, + tenantEvents, + genuineTargets, + sources.manager, + clock, + namespace); + receiver = new AccountPlayerAdmissionEntitlementGrpcService(owner, namespace); + assertAbsentMembership(); + } + + public AccountPlayerAdmissionSharedOwnerFixture login() { + return login; + } + + public AccountJwtJwksTrustedSource trustedJwksSource() { + return login.trustedJwksSource(); + } + + /** The receiver creates only an explicit private mTLS listener when its caller requests one. */ + public AccountPlayerAdmissionEntitlementGrpcService receiver() { + return receiver; + } + + /** + * Uses the real scope owner, signed token, retained readback and protected target client. Only + * this scope-invocation peer is stipulated; no authenticated socket or public ingress is proved. + */ + public RealmScope issueScopeWithControlledGameSessionCaller( + DirectTextCallerContext caller, DirectTextJoinTarget target) { + Objects.requireNonNull(caller, "Controlled direct-text caller is required"); + Objects.requireNonNull(target, "Actual selected target is required"); + if (!login.accountId().equals(caller.accountId()) + || !sources.tenant.equals(caller.tenantId()) + || !sources.tenant.equals(target.tenantId())) { + throw new IllegalArgumentException("Scope must use the separate player and shared tenant"); + } + var peer = + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/game-session-service") + .orElseThrow(); + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + RealmScope result = scopes.issueDirectTextScope(caller, target); + assertThat(result.membership().accountId()).isEqualTo(login.accountId()); + assertThat(result.membership().tenantId()).isEqualTo(sources.tenant); + assertThat(result.membership().current()).isEmpty(); + assertThat(result.entitlement().sourceKind()).isEqualTo(SourceKind.NON_PAID_DEMO); + assertThat(result.entitlement().entitlementVersion()).isEqualTo(demo.entitlementVersion()); + assertAbsentMembership(); + return result; + } finally { + context.detach(previous); + } + } + + /** + * Explicit owner-local first JOIN. Request and caller binding are controlled correlation inputs, + * not authentication supplied by this coordinator. Signed scope/current target checks precede + * SQL; they establish no cross-service hold through commit. Replay uses the identical inputs. + */ + public CanonicalJoinTerminalProof commitFirstJoin( + RealmScope issued, String requestId, String controlledCallerBinding) { + Objects.requireNonNull(issued, "Actual issued realm scope is required"); + var scope = scopeReader.read(login.accountId(), issued.scope().connectScopeId()); + assertThat(scope).isEqualTo(issued.scope()); + assertThat(scope.tenantId()).isEqualTo(sources.tenant); + requireCurrentTarget(issued, scope); + var before = + joinTransaction.execute( + status -> { + sources.accounts.findByAccountUuidForUpdate(login.accountId()).orElseThrow(); + operations.insertCanonicalIntent(requestId, scope, controlledCallerBinding); + return authority.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, login.accountId()); + }); + // The second actual target read detects pre-commit drift, but is intentionally not a hold. + requireCurrentTarget(issued, scope); + CanonicalJoinTerminalProof proof = + joinTransaction.execute( + status -> { + sources.accounts.findByAccountUuidForUpdate(login.accountId()).orElseThrow(); + requireLiveScope(scope); + var currentDemo = demos.revalidate(demo); + operations.bindCanonicalPolicyEvidence( + requestId, + scope, + controlledCallerBinding, + currentDemo.allowPublicJoin(), + currentDemo.entitlementVersion()); + var committed = + firstJoin.commitCanonicalFirstJoin(scope, requestId, controlledCallerBinding); + assertFirstJoinReceipt(scope, requestId, controlledCallerBinding, committed); + requireLiveScope(scope); + return committed; + }); + Objects.requireNonNull(proof, "Committed first-JOIN receipt is required"); + // Independent transaction proves durable terminal replay, not merely same-transaction reads. + var replay = + joinTransaction.execute( + status -> { + sources.accounts.findByAccountUuidForUpdate(login.accountId()).orElseThrow(); + requireLiveScope(scope); + assertThat( + operations.insertCanonicalIntent(requestId, scope, controlledCallerBinding)) + .isFalse(); + var repeated = + firstJoin.commitCanonicalFirstJoin(scope, requestId, controlledCallerBinding); + assertFirstJoinReceipt(scope, requestId, controlledCallerBinding, repeated); + return repeated; + }); + assertThat(replay).isEqualTo(proof); + assertThat(scopeReader.read(login.accountId(), scope.connectScopeId())).isEqualTo(scope); + var after = + sources.tx( + () -> + authority.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, login.accountId())); + Objects.requireNonNull(before, "Original LOGIN authority sources are required"); + assertThat(after.issuer()).isEqualTo(before.issuer()); + assertThat(after.account()).isEqualTo(before.account()); + assertThat(after.issuanceFence()).isEqualTo(before.issuanceFence()); + login.assertCreatorRemainsNonAdmitting(); + verifyNoInteractions(unusedPaidRepository, unusedProvider, unusedBrowserSessions); + return proof; + } + + /** Positive membership source evidence only, after the same real receiver/client reread. */ + public void assertAdmittingEvidence(RuntimePlayerAdmissionEntitlementEvidence evidence) { + Objects.requireNonNull(evidence, "Actual Account receiver evidence is required"); + evidence.requireCurrentAt(clock.instant()); + var current = sources.tx(() -> snapshots.readCurrent(login.accountId(), sources.tenant)); + assertThat(evidence.membershipSource()).isEqualTo(current); + assertAdmittingSnapshot(current); + sources.tx(() -> demos.revalidate(demo)); + login.assertCreatorRemainsNonAdmitting(); + verifyNoInteractions(unusedPaidRepository, unusedProvider, unusedBrowserSessions); + } + + private void requireCurrentTarget(RealmScope issued, CanonicalJoinScopeV2 scope) { + var selector = + new RetainedTargetSelector( + UUID.nameUUIDFromBytes( + ("first-join-target-selector/v1:" + scope.connectScopeId()) + .getBytes(StandardCharsets.UTF_8)), + scope.accountId(), + namespace, + scope.tenantId(), + scope.tenantSlug(), + scope.worldSlug(), + scope.realmId(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion()); + var resolved = targets.resolvePublishedRealmAdmissionTarget(selector); + CanonicalGameplayAdmissionDecisionReadGrpcCodec.requireRetainedTargetMatches( + selector, resolved.currentTarget()); + assertThat(resolved.selector()).isEqualTo(selector); + var current = targets.readPublishedRealmAdmissionOwner(resolved.strictSelector()); + assertThat(current.selector()).isEqualTo(resolved.strictSelector()); + assertThat(current.currentTarget()) + .isEqualTo(resolved.currentTarget()) + .isEqualTo(issued.target()); + requireLiveScope(scope); + } + + private void requireLiveScope(CanonicalJoinScopeV2 scope) { + Instant now = clock.instant(); + if (now.isBefore(Instant.parse(scope.evaluatedAt())) + || !now.isBefore(Instant.parse(scope.connectScopeExpiresAt()))) { + throw new IllegalStateException("Original signed first-JOIN scope is no longer current"); + } + } + + /** All rows are read beneath the same Account fence as the actual terminal owner. */ + private void assertFirstJoinReceipt( + CanonicalJoinScopeV2 scope, + String requestId, + String callerBinding, + CanonicalJoinTerminalProof proof) { + var operation = operations.findCanonicalEvidenceForUpdateByRequestId(requestId).orElseThrow(); + assertThat(operation.status()).isEqualTo("COMMITTED"); + assertThat(operation.outcome()).isEqualTo("JOINED"); + assertThat(operation.callerBinding()).isEqualTo(callerBinding); + assertThat(operation.scopeTokenHash()) + .isEqualTo(AccountJoinDigest.tokenHash(scope.connectScopeId())); + assertThat(operation.connectScopeDigest()).isEqualTo(AccountJoinDigest.scopeV2(scope)); + assertThat(operation.intentDigest()) + .isEqualTo(AccountJoinDigest.intentV2(requestId, scope, callerBinding)); + assertThat(operation.terminalProof()).isEqualTo(proof); + assertThat(proof.entitlementVersion()).isEqualTo(demo.entitlementVersion()); + assertThat(proof.membershipVersion()).isEqualTo(2L); + assertThat(proof.membershipAuthorityGeneration()).isEqualTo(1L); + assertThat(proof.eventSequence()).isEqualTo(1L); + var member = + members.findFreshMembershipForUpdate(login.accountId(), sources.tenant).orElseThrow(); + assertThat(member.getId()).isEqualTo(proof.membershipId()); + assertThat(member.getAuthorityProvenance()).isEqualTo("EXPLICIT_JOIN"); + var pair = pairs.readForUpdate(login.accountId(), sources.tenant).orElseThrow(); + assertThat(pair.membershipExists()).isTrue(); + assertThat(pair.membershipVersion()).isEqualTo(proof.membershipVersion()); + assertThat(pair.membershipAuthorityGeneration()) + .isEqualTo(proof.membershipAuthorityGeneration()); + assertThat(pair.eventSequence()).isEqualTo(proof.eventSequence()); + assertThat(pair.eventId()).isEqualTo(proof.eventId()); + assertThat(pair.eventDigest()).isEqualTo(proof.eventDigest()); + assertThat(pair.lastTransitionInvalidated()).isFalse(); + var checkpoint = outbox.readCheckpoint(proof.eventStreamKey()).orElseThrow(); + assertThat(checkpoint.outboxSequence()).isEqualTo(proof.eventSequence()); + assertThat(checkpoint.sourceEventId()).isEqualTo(proof.eventId()); + assertThat(checkpoint.sourceEventDigest()).isEqualTo(proof.eventDigest()); + var event = outbox.findEvent(proof.eventStreamKey(), proof.eventSequence()).orElseThrow(); + assertThat(event.requestId()).isEqualTo(requestId); + assertThat(event.eventId()).isEqualTo(proof.eventId()); + assertThat(event.eventDigest()).isEqualTo(proof.eventDigest()); + var decoded = + MembershipAuthorityEventV1Codec.verify(new String(event.payload(), StandardCharsets.UTF_8)); + assertThat(event.payload()).containsExactly(decoded.canonicalJsonUtf8()); + var audit = audits.findCanonicalTenantEnvelopeForUpdate(proof.auditEventId()).orElseThrow(); + assertThat(audit.tenantUuid()).isEqualTo(sources.tenant); + assertThat(audit.tenantIdentityVersion()).isEqualTo(2); + assertThat(audit.eventType()).isEqualTo("ACCOUNT_JOINED_PUBLIC_PRODUCTION"); + assertThat(audit.producerService()).isEqualTo("account-service"); + assertThat(audit.payloadDigest()).isEqualTo(proof.auditPayloadDigest()); + assertThat(audit.occurredAt()).isEqualTo(proof.auditOccurredAt()); + assertAdmittingSnapshot(snapshots.readCurrent(login.accountId(), sources.tenant)); + } + + private void assertAdmittingSnapshot(Snapshot current) { + assertThat(current.accountId()).isEqualTo(login.accountId().toString()); + assertThat(current.tenantId()).isEqualTo(sources.tenant.toString()); + assertThat(current.membershipExists()).isTrue(); + assertThat(current.membershipLifecycleState()).isEqualTo("ACTIVE"); + assertThat(current.gameplayAdmissionAllowed()).isTrue(); + assertThat(current.roles()).containsExactly("player"); + assertThat(current.membershipVersion()).containsEntry(sources.tenant.toString(), "2"); + assertThat(current.membershipAuthorityGeneration()).isEqualTo("1"); + } + + private T transactional(T target, Class type) { + var proxy = new ProxyFactory(target); + proxy.setProxyTargetClass(true); + proxy.addAdvice( + new TransactionInterceptor(sources.manager, new AnnotationTransactionAttributeSource())); + return type.cast(proxy.getProxy(type.getClassLoader())); + } + + /** Exact current source comparison after the receiving client has authenticated the response. */ + public void assertNonAdmittingEvidence(RuntimePlayerAdmissionEntitlementEvidence evidence) { + Objects.requireNonNull(evidence, "Actual Account receiver evidence is required"); + evidence.requireCurrentAt(clock.instant()); + var current = sources.tx(() -> snapshots.readCurrent(login.accountId(), sources.tenant)); + assertThat(evidence.membershipSource()).isEqualTo(current); + assertAbsentMembership(); + } + + /** Confirms actual absence enrollment and current tenant DEMO source without editing history. */ + public void assertAbsentMembership() { + sources.tx( + () -> { + var current = snapshots.readCurrent(login.accountId(), sources.tenant); + assertThat(current.accountId()).isEqualTo(login.accountId().toString()); + assertThat(current.tenantId()).isEqualTo(sources.tenant.toString()); + assertThat(current.membershipExists()).isFalse(); + assertThat(current.membershipLifecycleState()).isEqualTo("MISSING"); + assertThat(current.gameplayAdmissionAllowed()).isFalse(); + assertThat(current.roles()).isEmpty(); + assertThat(current.membershipVersion()).containsEntry(sources.tenant.toString(), "1"); + assertThat(current.membershipAuthorityGeneration()).isEqualTo("1"); + assertThat(demos.revalidate(demo)).isEqualTo(demo); + return null; + }); + login.assertCreatorRemainsNonAdmitting(); + verifyNoInteractions(unusedPaidRepository, unusedProvider, unusedBrowserSessions); + } + + private static void requireFirstDemoRequest( + DemoTenantEntitlementRequest request, FreshTenantCreationEvidence creation) { + Objects.requireNonNull(request, "Explicit controlled demo policy is required"); + if (!creation.canonicalTenantId().equals(request.canonicalTenantId()) + || !creation.creationRequestId().equals(request.tenantCreationRequestId()) + || !creation.requestDigest().equals(request.tenantCreationRequestDigest()) + || request.expectedEntitlementVersion() != null + || request.expectedTenantAuthorityGeneration() != null + || request.expectedTenantAuthoritySourceVersion() != null) { + throw new IllegalArgumentException( + "First DEMO request must preserve exact creation provenance"); + } + } + + private static String scopeSigningKey() { + byte[] bytes = new byte[32]; + RANDOM.nextBytes(bytes); + try { + return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); + } finally { + Arrays.fill(bytes, (byte) 0); + } + } + + private static T excluded(Class type) { + return mock( + type, + invocation -> { + throw new AssertionError( + "Excluded paid/browser dependency invoked: " + type.getSimpleName()); + }); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java index 324abdf114..968fa7e2c5 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java @@ -32,7 +32,7 @@ import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.security.JwtClaims; -import net.firedevops.firemud.common.security.RequestIdValidation; +import net.firedevops.firemud.gamesession.service.SessionIdParsing; import net.firedevops.firemud.shared.v1.ErrorDetail; import net.firedevops.firemud.shared.v1.PlayerExecutionContext; import org.slf4j.Logger; @@ -306,14 +306,17 @@ private boolean hasDirectTextCallerShape(PlayerExecutionContext context) { } try { JwtClaims.requireCanonicalAccountUuid(context.getAccountId(), "accountId"); - RequestIdValidation.requirePositiveLong(context.getTenantId(), "tenantId"); + DirectTextConnectScopeTarget.requireUuid(context.getTenantId(), "tenantId"); DirectTextConnectScopeTarget.requireUuid(context.getRealmId(), "realmId"); DirectTextConnectScopeTarget.requireUuid( context.getPlayableStateNamespaceId(), "playableStateNamespaceId"); DirectTextConnectScopeTarget.requireScope(context.getPlayableStateScope()); - RequestIdValidation.requirePositiveLong(context.getGameInstanceId(), "gameInstanceId"); - return isBoundedText(context.getSessionId(), 128) - && isBoundedText(context.getRequestId(), 128); + DirectTextConnectScopeTarget.requireUuid(context.getGameInstanceId(), "gameInstanceId"); + if (!isBoundedText(context.getSessionId(), 32) || !context.getSessionId().matches("[0-9]+")) { + return false; + } + SessionIdParsing.require(context.getSessionId()); + return isBoundedText(context.getRequestId(), 128); } catch (IllegalArgumentException ex) { return false; } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/DirectTextConnectScopeTarget.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/DirectTextConnectScopeTarget.java index 625f8e4880..9ed370dbe3 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/DirectTextConnectScopeTarget.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/DirectTextConnectScopeTarget.java @@ -1,7 +1,6 @@ package net.firedevops.firemud.gamesession.client; import java.util.UUID; -import net.firedevops.firemud.common.security.RequestIdValidation; /** Server-resolved routing evidence, not authentication or gameplay admission authority. */ public record DirectTextConnectScopeTarget( @@ -15,13 +14,13 @@ public record DirectTextConnectScopeTarget( long catalogRevision, long pointerVersion) { public DirectTextConnectScopeTarget { - RequestIdValidation.requirePositiveLong(tenantId, "tenantId"); + requireUuid(tenantId, "tenantId"); requireText(worldSlug, "worldSlug", 128); requireText(realmSlug, "realmSlug", 128); requireUuid(realmId, "realmId"); requireUuid(playableStateNamespaceId, "playableStateNamespaceId"); requireScope(playableStateScope); - RequestIdValidation.requirePositiveLong(gameInstanceId, "gameInstanceId"); + requireUuid(gameInstanceId, "gameInstanceId"); if (catalogRevision < 1 || pointerVersion < 1) { throw new IllegalArgumentException("routing revisions must be positive"); } @@ -34,7 +33,9 @@ static void requireText(String value, String name, int maxLength) { } static void requireUuid(String value, String name) { - if (value == null || !UUID.fromString(value).toString().equals(value)) { + if (value == null + || !UUID.fromString(value).toString().equals(value) + || new UUID(0L, 0L).equals(UUID.fromString(value))) { throw new IllegalArgumentException(name + " must be a canonical UUID"); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyScope.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyScope.java index 40b7f5a350..93902d97a3 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyScope.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyScope.java @@ -175,13 +175,13 @@ public static DirectTextAuthenticatedLobbyScope decode(byte[] bytes) { public static DirectTextConnectScopeTarget targetFor(CanonicalPlayableTarget target) { Objects.requireNonNull(target); return new DirectTextConnectScopeTarget( - Long.toString(target.gameSessionTenantId()), + target.canonicalTenantId().toString(), target.worldSlug(), target.realmSlug(), target.realmId().toString(), target.playableStateNamespaceId().toString(), target.playableStateScope(), - Long.toString(target.gameInstanceId()), + target.canonicalGameInstanceId().toString(), target.catalogRevision(), target.pointerVersion()); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java index e621041c0e..812f909908 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java @@ -284,6 +284,35 @@ void actualOwnerReadsCommittedExactRequestBeforeAccountAndRetainsPositiveReply() verify(account, times(1)).joinPublicProductionMembership(any(), any(), any(), any()); } + @Test + void alreadyActiveNonAdmittingReceiptReplaysExactlyWithoutBecomingGameplayAdmission() { + var scope = realms(); + var response = + positive().toBuilder() + .setOutcomeCode("ALREADY_ACTIVE") + .setGameplayAdmissionAllowed(false) + .setMembershipVersion(8L) + .setMembershipAuthorityGeneration(4L) + .setReplayed(true) + .build(); + when(account.joinPublicProductionMembership(any(), any(), any(), any())).thenReturn(response); + + var completed = owner.join(original, verified, custody); + assertThat(completed.status()) + .isEqualTo(DirectTextAuthenticatedLobbyOwner.Status.COMPLETED_CURRENT_NON_ADMITTING); + assertThat(completed.currentReply()).contains(response); + assertThat(completed.currentReply().orElseThrow().getGameplayAdmissionAllowed()).isFalse(); + var row = + dsl.fetchSingle( + "SELECT reply_bytes FROM " + JOIN + " WHERE scope_record_id = ?", scope.recordId()); + assertThat(row.get("reply_bytes", byte[].class)).containsExactly(response.toByteArray()); + + var continuation = owner(repository, manager).join(original, verified, custody); + assertThat(continuation.requestId()).isEqualTo(completed.requestId()); + assertThat(continuation.currentReply()).contains(response); + verify(account, times(1)).joinPublicProductionMembership(any(), any(), any(), any()); + } + @Test void independentConnectionsAllocateOneFrozenWinnerAndOnlyOneDispatchClaim() throws Exception { realms(); @@ -785,10 +814,11 @@ private static JoinPublicProductionMembershipResponse positive() { .setSuccess(true) .setOutcomeCode("JOINED") .setAccountId(ACCOUNT.toString()) - .setTenantId("101") + .setTenantId("22222222-2222-4222-8222-222222222222") .setMembershipId("90") .setMembershipVersion(3) .setMembershipAuthorityGeneration(1) + .setGameplayAdmissionAllowed(true) .build(); } @@ -803,7 +833,7 @@ private static CanonicalPlayableTarget target() { return new CanonicalPlayableTarget( "gameplay", "studio", - UUID.randomUUID(), + UUID.fromString("22222222-2222-4222-8222-222222222222"), "forest", "Forest", UUID.randomUUID(), diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java index b10193f3d5..ff8aed9ff4 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java @@ -66,10 +66,10 @@ void directTextScopeCapturesExactCompleteRequest() throws Exception { .setConnectScopeExpiresAt("2030-01-01T00:00:00Z") .build(); when(fixture.initialStub().issueDirectTextConnectScope(any())).thenReturn(expected); - // Session/request are bounded opaque text, not numeric IDs. Preserve their exact bytes. + // The numeric transport session retains its exact bytes, including leading zeros. var context = directTextContext().toBuilder() - .setSessionId(" transport-session ") + .setSessionId("00042") .setRequestId(" scope-request ") .build(); var target = directTextTarget(); @@ -82,13 +82,13 @@ void directTextScopeCapturesExactCompleteRequest() throws Exception { .isEqualTo( IssueDirectTextConnectScopeRequest.newBuilder() .setPlayerContext(context) - .setTenantId("22") + .setTenantId("22222222-2222-4222-8222-222222222222") .setWorldSlug("demo-world") .setRealmSlug("production") .setRealmId(target.realmId()) .setPlayableStateNamespaceId(target.playableStateNamespaceId()) .setPlayableStateScope("SHARED") - .setGameInstanceId("9") + .setGameInstanceId("44444444-4444-4444-8444-444444444444") .setCatalogRevision(7L) .setPointerVersion(4L) .build()); @@ -169,6 +169,30 @@ void directTextMethodsRejectMissingAndMalformedCallerFieldsBeforeDispatch() thro org.mockito.Mockito.verifyNoInteractions(stub); } + @ParameterizedTest + @ValueSource( + strings = { + "abc", + "-1", + " 42", + "+1", + "0", + "000", + "000000000000000000000000000000001", + "9223372036854775808" + }) + void directTextMethodsRejectMalformedNumericSessionIdsBeforeDispatch(String sessionId) + throws Exception { + var stub = mock(AccountServiceGrpc.AccountServiceBlockingStub.class); + var client = newClient(stub); + var context = directTextContext().toBuilder().setSessionId(sessionId).build(); + + assertThat(client.issueDirectTextConnectScope(context, directTextTarget()).getError().getCode()) + .isEqualTo("INVALID_ARGUMENT"); + assertThat(join(client, context).getError().getCode()).isEqualTo("INVALID_ARGUMENT"); + org.mockito.Mockito.verifyNoInteractions(stub); + } + @Test void scopeIssuanceRejectsEachIndependentContextTargetMismatch() throws Exception { var stub = mock(AccountServiceGrpc.AccountServiceBlockingStub.class); @@ -176,13 +200,15 @@ void scopeIssuanceRejectsEachIndependentContextTargetMismatch() throws Exception var context = directTextContext(); for (var mismatched : List.of( - context.toBuilder().setTenantId("23").build(), + context.toBuilder().setTenantId("33333333-3333-4333-8333-333333333333").build(), context.toBuilder().setRealmId("4c4b57d8-e3a2-48fe-9977-e7df0fdce902").build(), context.toBuilder() .setPlayableStateNamespaceId("42d234a2-7487-4dda-a7e5-a3831214328f") .build(), context.toBuilder().setPlayableStateScope("ISOLATED").build(), - context.toBuilder().setGameInstanceId("10").build())) { + context.toBuilder() + .setGameInstanceId("55555555-5555-4555-8555-555555555555") + .build())) { assertThat( client .issueDirectTextConnectScope(mismatched, directTextTarget()) @@ -197,7 +223,15 @@ void scopeIssuanceRejectsEachIndependentContextTargetMismatch() throws Exception void directTextTargetRejectsMalformedRoutingEvidenceWithoutNormalizing() { var target = directTextTarget(); String[][] malformed = { - {"0", "world", "realm", target.realmId(), target.playableStateNamespaceId(), "SHARED", "9"}, + { + "0", + "world", + "realm", + target.realmId(), + target.playableStateNamespaceId(), + "SHARED", + "44444444-4444-4444-8444-444444444444" + }, { "tenant", "world", @@ -205,31 +239,71 @@ void directTextTargetRejectsMalformedRoutingEvidenceWithoutNormalizing() { target.realmId(), target.playableStateNamespaceId(), "SHARED", - "9" + "44444444-4444-4444-8444-444444444444" }, - {"22", " ", "realm", target.realmId(), target.playableStateNamespaceId(), "SHARED", "9"}, { - "22", + "22222222-2222-4222-8222-222222222222", + " ", + "realm", + target.realmId(), + target.playableStateNamespaceId(), + "SHARED", + "44444444-4444-4444-8444-444444444444" + }, + { + "22222222-2222-4222-8222-222222222222", "w".repeat(129), "realm", target.realmId(), target.playableStateNamespaceId(), "SHARED", - "9" + "44444444-4444-4444-8444-444444444444" }, { - "22", + "22222222-2222-4222-8222-222222222222", "world", "r".repeat(129), target.realmId(), target.playableStateNamespaceId(), "SHARED", - "9" + "44444444-4444-4444-8444-444444444444" + }, + { + "22222222-2222-4222-8222-222222222222", + "world", + "realm", + "realm", + target.playableStateNamespaceId(), + "SHARED", + "44444444-4444-4444-8444-444444444444" + }, + { + "22222222-2222-4222-8222-222222222222", + "world", + "realm", + target.realmId(), + "namespace", + "SHARED", + "44444444-4444-4444-8444-444444444444" }, - {"22", "world", "realm", "realm", target.playableStateNamespaceId(), "SHARED", "9"}, - {"22", "world", "realm", target.realmId(), "namespace", "SHARED", "9"}, - {"22", "world", "realm", target.realmId(), target.playableStateNamespaceId(), "shared", "9"}, - {"22", "world", "realm", target.realmId(), target.playableStateNamespaceId(), "SHARED", "0"} + { + "22222222-2222-4222-8222-222222222222", + "world", + "realm", + target.realmId(), + target.playableStateNamespaceId(), + "shared", + "44444444-4444-4444-8444-444444444444" + }, + { + "22222222-2222-4222-8222-222222222222", + "world", + "realm", + target.realmId(), + target.playableStateNamespaceId(), + "SHARED", + "0" + } }; for (var fields : malformed) { assertThatThrownBy( @@ -242,26 +316,26 @@ void directTextTargetRejectsMalformedRoutingEvidenceWithoutNormalizing() { assertThatThrownBy( () -> new DirectTextConnectScopeTarget( - "22", + "22222222-2222-4222-8222-222222222222", "world", "realm", target.realmId(), target.playableStateNamespaceId(), "SHARED", - "9", + "44444444-4444-4444-8444-444444444444", 0L, 4L)) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy( () -> new DirectTextConnectScopeTarget( - "22", + "22222222-2222-4222-8222-222222222222", "world", "realm", target.realmId(), target.playableStateNamespaceId(), "SHARED", - "9", + "44444444-4444-4444-8444-444444444444", 7L, -1L)) .isInstanceOf(IllegalArgumentException.class); @@ -369,6 +443,37 @@ void joinPreservesProducerSuccessAndReplayEvidence(String outcome) throws Except .buildChannel(anyString(), anyInt(), any(), anyBoolean()); } + @Test + void joinPreservesAlreadyActiveNonAdmittingReceipt() throws Exception { + var fixture = newRetryFixture(new TestClock(JOIN_TEST_NOW)); + var expected = + joinSuccess("ALREADY_ACTIVE", true).toBuilder().setGameplayAdmissionAllowed(false).build(); + when(fixture.initialStub().joinPublicProductionMembership(any())).thenReturn(expected); + + assertThat(join(fixture.client(), directTextContext())).isSameAs(expected); + assertThat(expected.getReplayed()).isTrue(); + verify(fixture.initialStub()).joinPublicProductionMembership(any()); + verify(fixture.retryStub(), never()).joinPublicProductionMembership(any()); + verify(fixture.channelFactory(), never()) + .buildChannel(anyString(), anyInt(), any(), anyBoolean()); + } + + @Test + void joinPreservesJoinedNonAdmittingReplayReceipt() throws Exception { + var fixture = newRetryFixture(new TestClock(JOIN_TEST_NOW)); + var expected = + joinSuccess("JOINED", true).toBuilder().setGameplayAdmissionAllowed(false).build(); + when(fixture.initialStub().joinPublicProductionMembership(any())).thenReturn(expected); + + var result = join(fixture.client(), directTextContext()); + + assertThat(result).isSameAs(expected); + assertThat(result.getGameplayAdmissionAllowed()).isFalse(); + assertThat(result.getReplayed()).isTrue(); + verify(fixture.initialStub()).joinPublicProductionMembership(any()); + verify(fixture.retryStub(), never()).joinPublicProductionMembership(any()); + } + @Test void joinPreservesTypedNonSuccessWithOrWithoutErrorWithoutRetry() throws Exception { var fixture = newRetryFixture(new TestClock(JOIN_TEST_NOW)); @@ -377,7 +482,7 @@ void joinPreservesTypedNonSuccessWithOrWithoutErrorWithoutRetry() throws Excepti .setSuccess(false) .setOutcomeCode("PUBLIC_PRODUCTION_ADMISSION_DENIED") .setAccountId(ACCOUNT_UUID) - .setTenantId("22") + .setTenantId("22222222-2222-4222-8222-222222222222") .setMembershipId("0") .build(); for (var expected : @@ -399,13 +504,14 @@ void joinPreservesTypedNonSuccessWithOrWithoutErrorWithoutRetry() throws Excepti } @Test - void joinAcceptsBoundedOpaqueIdentityWithoutTrimmingOrRegeneration() throws Exception { + void joinPreservesBoundedNumericTransportIdentityWithoutTrimmingOrRegeneration() + throws Exception { var fixture = newRetryFixture(new TestClock(JOIN_TEST_NOW)); var requestId = " " + "r".repeat(126) + " "; var scopeId = " " + "s".repeat(2046) + " "; var context = directTextContext().toBuilder() - .setSessionId("s".repeat(128)) + .setSessionId("0".repeat(30) + "42") .setRequestId(requestId) .build(); var expected = joinSuccess("JOINED", false); @@ -447,7 +553,15 @@ void joinRejectsForeignOrMalformedSuccessfulIdentityWithoutRetry() throws Except assertThat(join(fixture.client(), directTextContext()).getError().getCode()) .isEqualTo("AUTH_UNAVAILABLE"); } - for (String tenant : List.of("", "tenant", "0", "23", " 22", "022")) { + for (String tenant : + List.of( + "", + "tenant", + "22", + "00000000-0000-0000-0000-000000000000", + "22222222-2222-4222-8222-22222222222A", + " " + directTextTarget().tenantId(), + "33333333-3333-4333-8333-333333333333")) { when(fixture.initialStub().joinPublicProductionMembership(any())) .thenReturn(success.toBuilder().setTenantId(tenant).build()); assertThat(join(fixture.client(), directTextContext()).getError().getCode()) @@ -464,7 +578,8 @@ void joinRetriesOnceWithSameImmutableRequestAfterChannelRebuild(String status) t var fixture = newRetryFixture(new TestClock(JOIN_TEST_NOW)); when(fixture.initialStub().joinPublicProductionMembership(any())) .thenThrow(Status.fromCode(Status.Code.valueOf(status)).asRuntimeException()); - var expected = joinSuccess("JOINED", true); + var expected = + joinSuccess("JOINED", true).toBuilder().setGameplayAdmissionAllowed(false).build(); when(fixture.retryStub().joinPublicProductionMembership(any())).thenReturn(expected); assertThat(join(fixture.client(), directTextContext())).isSameAs(expected); @@ -525,7 +640,10 @@ void joinAlsoCorrelatesSuccessfulRetryBeforeReturningIt() throws Exception { when(fixture.initialStub().joinPublicProductionMembership(any())) .thenThrow(Status.UNAVAILABLE.asRuntimeException()); when(fixture.retryStub().joinPublicProductionMembership(any())) - .thenReturn(joinSuccess("JOINED", true).toBuilder().setTenantId("23").build()); + .thenReturn( + joinSuccess("JOINED", true).toBuilder() + .setTenantId("33333333-3333-4333-8333-333333333333") + .build()); assertThat(join(fixture.client(), directTextContext()).getError().getCode()) .isEqualTo("AUTH_UNAVAILABLE"); @@ -662,13 +780,13 @@ void joinRechecksExpiryDuringChannelReloadBeforeRetry() throws Exception { private static DirectTextConnectScopeTarget directTextTarget() { return new DirectTextConnectScopeTarget( - "22", + "22222222-2222-4222-8222-222222222222", "demo-world", "production", "4c4b57d8-e3a2-48fe-9977-e7df0fdce901", "42d234a2-7487-4dda-a7e5-a3831214328e", "SHARED", - "9", + "44444444-4444-4444-8444-444444444444", 7L, 4L); } @@ -677,7 +795,7 @@ private static PlayerExecutionContext directTextContext() { var target = directTextTarget(); return PlayerExecutionContext.newBuilder() .setAccountId(ACCOUNT_UUID) - .setSessionId("transport-session") + .setSessionId("00042") .setTenantId(target.tenantId()) .setRealmId(target.realmId()) .setPlayableStateNamespaceId(target.playableStateNamespaceId()) @@ -693,11 +811,12 @@ private static JoinPublicProductionMembershipResponse joinSuccess( .setSuccess(true) .setOutcomeCode(outcome) .setAccountId(ACCOUNT_UUID) - .setTenantId("22") + .setTenantId("22222222-2222-4222-8222-222222222222") .setMembershipId("81") .setMembershipVersion(12L) .setMembershipAuthorityGeneration(3L) .setReplayed(replayed) + .setGameplayAdmissionAllowed(true) .build(); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/DirectTextIssuedConnectScopeTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/DirectTextIssuedConnectScopeTest.java index 23eb9a459e..91158e2764 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/DirectTextIssuedConnectScopeTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/DirectTextIssuedConnectScopeTest.java @@ -148,13 +148,13 @@ private static IssueDirectTextConnectScopeResponse response( private static DirectTextConnectScopeTarget target() { return new DirectTextConnectScopeTarget( - "22", + "22222222-2222-4222-8222-222222222222", "demo-world", "production", "00000000-0000-4000-8000-000000000101", "00000000-0000-4000-8000-000000000102", "SHARED", - "9", + "44444444-4444-4444-8444-444444444444", 7L, 4L); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java index f63063eb72..28f884ee4e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java @@ -135,6 +135,31 @@ void positiveReplyPreservesTheFullPositiveAccountBigintBoundary() { .isEqualTo(response); } + @ParameterizedTest + @ValueSource(strings = {"JOINED", "ALREADY_ACTIVE"}) + void nonAdmittingMembershipIsRetainedAsAnExactNonAdmissionReceipt(String outcome) { + var f = new Fixture(); + var response = + positive().toBuilder() + .setOutcomeCode(outcome) + .setGameplayAdmissionAllowed(false) + .setMembershipVersion(8L) + .setMembershipAuthorityGeneration(4L) + .setReplayed(true) + .build(); + + assertThat(DirectTextAuthenticatedLobbyJoin.decodeReply(f.scope, response.toByteArray())) + .isEqualTo(response); + assertThat(response.getGameplayAdmissionAllowed()).isFalse(); + assertThat(response.getMembershipVersion()).isEqualTo(8L); + assertThat(response.getMembershipAuthorityGeneration()).isEqualTo(4L); + var completed = + new DirectTextAuthenticatedLobbyJoin( + f.scope, f.frozen.request(), State.COMPLETED, Optional.of(response)); + assertThat(completed.reply()).contains(response); + assertThat(completed.reply().orElseThrow().getGameplayAdmissionAllowed()).isFalse(); + } + @Test void frozenRequestKeepsTransportCorrelationSeparateFromProxyOriginalContextAndJoinIds() { var f = new Fixture(); @@ -638,10 +663,11 @@ private static JoinPublicProductionMembershipResponse positive() { .setSuccess(true) .setOutcomeCode("JOINED") .setAccountId(ACCOUNT.toString()) - .setTenantId("101") + .setTenantId("22222222-2222-4222-8222-222222222222") .setMembershipId("90") .setMembershipVersion(3) .setMembershipAuthorityGeneration(1) + .setGameplayAdmissionAllowed(true) .build(); } @@ -649,7 +675,7 @@ private static CanonicalPlayableTarget target(String display) { return new CanonicalPlayableTarget( "gameplay", "studio", - UUID.randomUUID(), + UUID.fromString("22222222-2222-4222-8222-222222222222"), "forest", display, UUID.randomUUID(), diff --git a/services/game-session-service/websocket-login-look-smoke.sh b/services/game-session-service/websocket-login-look-smoke.sh index f0daab88b8..79d92129cc 100644 --- a/services/game-session-service/websocket-login-look-smoke.sh +++ b/services/game-session-service/websocket-login-look-smoke.sh @@ -61,6 +61,7 @@ repo_root = Path(os.environ["FIREMUD_REPO_ROOT"]) sys.path.insert(0, str(repo_root / "dev-tools" / "smoke")) from smoke_common import ( + PlayEntitlementUnavailable, gameplay_item_container_equipment_steps, login_play_look_steps, run_websocket_smoke_session, @@ -130,19 +131,25 @@ else: look_timeout=look_timeout_seconds, ) steps += [("LOGOUT", ["OK LOGOUT", "Logged out."], "LOGOUT")] -run_websocket_smoke_session( - lambda: websocket.create_connection( - websocket_url, - timeout=timeout_seconds, - header=[ - f"X-Game-Instance-Id: {session_id}", - f"X-Tenant-Id: {tenant_id}", - ], - ), - steps, - timeout_seconds, - retriable_exceptions=(OSError, websocket.WebSocketException), - session_label=f"WebSocket session {websocket_url}", - discovery_selector=world, -) +try: + run_websocket_smoke_session( + lambda: websocket.create_connection( + websocket_url, + timeout=timeout_seconds, + header=[ + f"X-Game-Instance-Id: {session_id}", + f"X-Tenant-Id: {tenant_id}", + ], + ), + steps, + timeout_seconds, + retriable_exceptions=(OSError, websocket.WebSocketException), + session_label=f"WebSocket session {websocket_url}", + discovery_selector=world, + step_results=[], + ) +except PlayEntitlementUnavailable as exc: + print(f"Known direct backend PLAY failure after LOGIN: {exc}", file=sys.stderr) + raise SystemExit(86) from exc + PYTHON