diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a73a43b834..15afae6f35 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,7 +4,6 @@ on: push: branches: [ main, develop ] pull_request: - branches: [ main, develop ] types: [opened, synchronize, reopened, edited] workflow_dispatch: @@ -982,6 +981,7 @@ jobs: --require-suite integration.net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantSnapshotRepositoryIntegrationTest \ --require-suite integration.net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepositoryIntegrationTest \ --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantSnapshotRepositoryIntegrationTest#capturesExactOrderedTenantProjectionAndStableDigestUnderReadCommittedOwnerTransaction()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantSnapshotRepositoryIntegrationTest#capturesRawAndCanonicalOwnersAndBindsCanonicalOwnerChangesToSnapshotDigest()' \ --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantSnapshotRepositoryIntegrationTest#captureUsesNowaitToRejectAnExistingWriterThenSucceedsAfterRollback()' \ --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantSnapshotRepositoryIntegrationTest#shareFenceBlocksConcurrentInsertUpdateDeleteAcrossEverySourceFamilyAndReleasesAfterCommitOrRollback()' \ --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepositoryIntegrationTest#exactRetryReturnsHistoricalReceiptWithoutRecapturingChangedSource()' \ @@ -990,6 +990,18 @@ jobs: --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepositoryIntegrationTest#concurrentExactFirstWritersReturnSameImmutableReceipt()' \ game-session-service + - name: Run Game Session management owner UUID PostgreSQL component proof + if: ${{ matrix.module == 'game-session-service' }} + run: | + ./gradlew :game-session-service:integrationTest \ + --tests net.firedevops.firemud.gamesession.repository.GameInstanceOwnerUuidMigrationIntegrationTest \ + -PfullCheck --no-build-cache --no-configuration-cache + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite net.firedevops.firemud.gamesession.repository.GameInstanceOwnerUuidMigrationIntegrationTest \ + --require-case 'net.firedevops.firemud.gamesession.repository.GameInstanceOwnerUuidMigrationIntegrationTest#migrationPreservesNumericHistoryAndStoresCanonicalOwnerUuid()' \ + game-session-service + - name: Run Account persisted UUID authentication PostgreSQL component proof if: ${{ matrix.module == 'account-service' }} run: | @@ -1005,7 +1017,7 @@ jobs: --require-suite net.firedevops.firemud.accountservice.AccountApplicationIntegrationTest \ --require-case 'net.firedevops.firemud.accountservice.service.AccountAuthenticationUuidIntegrationTest#repositoryInsertAuthenticationUsesExactPersistedUuidAndPrivateStorageKey()' \ --require-case 'net.firedevops.firemud.accountservice.service.AccountAuthenticationUuidIntegrationTest#databaseInsertAuthenticationUsesTriggerProvedUuidAndCannotRemapItsSource()' \ - --require-case 'net.firedevops.firemud.accountservice.service.AccountAuthenticationUuidIntegrationTest#unmappedUuidDeniesProfileMutationEvenWhenBodyNamesAnExistingPrivateRow()' \ + --require-case 'net.firedevops.firemud.accountservice.service.AccountAuthenticationUuidIntegrationTest#unmappedUuidDeniesProfileMutationWithoutTouchingAnExistingPrivateRow()' \ --require-case 'net.firedevops.firemud.accountservice.service.AccountAuthenticationUuidIntegrationTest#emailOtpAuthenticationIssuesPersistedUuidAndConsumesTheChallengeExactlyOnce()' \ --require-case 'net.firedevops.firemud.accountservice.service.AccountAuthenticationUuidIntegrationTest#playerBootstrapEmailOtpCarriesPersistedUuidAndConsumesChallengeExactlyOnce()' \ --require-case 'net.firedevops.firemud.accountservice.service.AccountAuthenticationUuidIntegrationTest#bootstrapConsumerRejectsUnmappedAccountUuidBeforeSessionLookup()' \ @@ -1015,6 +1027,8 @@ jobs: --require-case 'net.firedevops.firemud.accountservice.service.AccountAuthenticationUuidIntegrationTest#rejectedEmailOtpPersistsChallengeAttemptForOtpCompletion()' \ --require-case 'net.firedevops.firemud.accountservice.service.AccountAuthenticationUuidIntegrationTest#rejectedEmailOtpPersistsChallengeAttemptForPlayerBootstrap()' \ --require-case 'net.firedevops.firemud.accountservice.service.AccountAuthenticationUuidIntegrationTest#nonAuthenticationSessionFailureRollsBackOtpConsumption()' \ + --require-case 'net.firedevops.firemud.accountservice.service.AccountAuthenticationUuidIntegrationTest#persistedProfileGetUpdateAndExportCarryTheCanonicalAccountUuid()' \ + --require-case 'net.firedevops.firemud.accountservice.service.AccountAuthenticationUuidIntegrationTest#profileUpdateRejectsSourceUuidMismatchWithoutSavingOrNotifying()' \ --require-case 'net.firedevops.firemud.accountservice.AccountApplicationIntegrationTest#exportAccountRejectsMalformedAccountIdWithInvalidArgumentEnvelope()' \ --require-case 'net.firedevops.firemud.accountservice.AccountApplicationIntegrationTest#updateProfileRejectsZeroTenantIdWithInvalidArgumentEnvelope()' \ --require-case 'net.firedevops.firemud.accountservice.AccountApplicationIntegrationTest#publicRegistrationCreatesGlobalIdentityAndDurablePlatformAuditOnly()' \ @@ -1241,7 +1255,7 @@ jobs: contents: read pull-requests: write needs: [buf-check, docker-lint, shellcheck, python-script-validation, dev-tool-contract-checks, dev-tools-readme-contract, yaml-lint, metrics-cardinality-check, flyway-migration-sanity-checks, grpc-transport-config-sanity-checks, workflow-lint, helm-lint, helm-render-validation, helm-transaction-proof, docs-check, frontend-checks, build-and-test, validation-gate] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 diff --git a/.github/workflows/publish-pr-runtime-images.yml b/.github/workflows/publish-pr-runtime-images.yml index 19c5fa387a..412f34e874 100644 --- a/.github/workflows/publish-pr-runtime-images.yml +++ b/.github/workflows/publish-pr-runtime-images.yml @@ -179,8 +179,8 @@ jobs: fail("source workflow run API id does not match the event") if source_run.get("workflow_id") != int(workflow_id_text): fail("source workflow identity changed between event and API") - if source_run.get("name") != source_title: - fail("source workflow API name differs from its exact run title") + if source_run.get("name") not in {"Build Runtime Images", source_title}: + fail("source workflow API name is neither its owning name nor exact run title") if source_run.get("path") != SOURCE_WORKFLOW_PATH: fail("source workflow API path is not the trusted runtime-images workflow") if source_run.get("event") != source_event: diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index 67013db104..df21260621 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -113,6 +113,7 @@ jobs: uses: ./.github/actions/setup-trivy - name: 🔍 Run Trivy and Save Report + shell: bash run: | echo "::group::Run Trivy" trivy fs --config config/security/trivy.yaml . | tee trivy-report.txt @@ -207,7 +208,7 @@ jobs: contents: read pull-requests: write # Publishes the consolidated security result on the PR. needs: [changes, trivy-scan, secret-compliance, security-gate] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index c65b36fb4f..b7e861e41a 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -88,6 +88,7 @@ jobs: ".github/actions/load-workflow-tool-versions/", ".github/actions/setup-python/", "dev-tools/smoke/", + "dev-tools/minio/", ]; const fullRelevantFiles = new Set([ "build.gradle.kts", @@ -145,7 +146,7 @@ jobs: contents: read pull-requests: write needs: [changes] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 @@ -198,6 +199,26 @@ jobs: `- ${statusIcon(fullResult)} PR Full-Stack Smoke: \`${fullResult}\``, ].join("\n"); + const expectedHeadSha = context.payload.pull_request.head.sha; + const expectedBaseRef = context.payload.pull_request.base.ref; + const expectedBaseSha = context.payload.pull_request.base.sha; + const { data: currentPullRequest } = await github.rest.pulls.get({ + ...context.repo, + pull_number: context.issue.number, + }); + if ( + currentPullRequest.state !== "open" || + currentPullRequest.head.sha !== expectedHeadSha || + currentPullRequest.base.ref !== expectedBaseRef || + currentPullRequest.base.sha !== expectedBaseSha + ) { + core.info( + `Skipping stale smoke summary for ${expectedBaseRef}@${expectedBaseSha}...${expectedHeadSha}; ` + + `current PR state/base/head is ${currentPullRequest.state}/${currentPullRequest.base.ref}@${currentPullRequest.base.sha}/${currentPullRequest.head.sha}` + ); + return; + } + const comments = await github.paginate( github.rest.issues.listComments, { @@ -277,7 +298,7 @@ jobs: contents: read pull-requests: write needs: [changes, smoke-gate, smoke-summary-pending] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 @@ -334,6 +355,26 @@ jobs: `- ${statusIcon(fullResult)} PR Full-Stack Smoke: \`${fullResult}\``, ].join("\n"); + const expectedHeadSha = context.payload.pull_request.head.sha; + const expectedBaseRef = context.payload.pull_request.base.ref; + const expectedBaseSha = context.payload.pull_request.base.sha; + const { data: currentPullRequest } = await github.rest.pulls.get({ + ...context.repo, + pull_number: context.issue.number, + }); + if ( + currentPullRequest.state !== "open" || + currentPullRequest.head.sha !== expectedHeadSha || + currentPullRequest.base.ref !== expectedBaseRef || + currentPullRequest.base.sha !== expectedBaseSha + ) { + core.info( + `Skipping stale smoke summary for ${expectedBaseRef}@${expectedBaseSha}...${expectedHeadSha}; ` + + `current PR state/base/head is ${currentPullRequest.state}/${currentPullRequest.base.ref}@${currentPullRequest.base.sha}/${currentPullRequest.head.sha}` + ); + return; + } + const comments = await github.paginate( github.rest.issues.listComments, { @@ -476,7 +517,11 @@ jobs: const eventMergeSha = context.sha; const prNumber = String(context.payload.pull_request.number); const started = Date.now(); - const timeoutMs = 25 * 60 * 1000; + // Contract-checked against pr-local-smoke; bounded overhead covers metadata, + // runner scheduling and API convergence, not unbounded queue delays. + const producerTimeoutMinutes = 45; + const prerequisiteAndQueueAllowanceMinutes = 45; + const timeoutMs = (producerTimeoutMinutes + prerequisiteAndQueueAllowanceMinutes) * 60 * 1000; const cancelledReplacementTimeoutMs = 5 * 60 * 1000; const sleepMs = 15000; const pullRequestCheckInterval = 4; diff --git a/.github/workflows/static-analysis-summary.yml b/.github/workflows/static-analysis-summary.yml index 4a89119f45..b4c906f7b3 100644 --- a/.github/workflows/static-analysis-summary.yml +++ b/.github/workflows/static-analysis-summary.yml @@ -65,7 +65,8 @@ jobs: if ( currentPullRequest.state !== "open" || !sourceWorkflowName || - context.payload.workflow_run.name !== expectedSourceTitle || + (context.payload.workflow_run.name !== sourceWorkflowName && + context.payload.workflow_run.name !== expectedSourceTitle) || context.payload.workflow_run.display_title !== expectedSourceTitle ) { core.info("The source run is not bound to the current open pull-request base and head."); diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index c9a79163af..a345dcfe0d 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -54,7 +54,11 @@ This target contract is not complete in the current service. The existing `secur ## Implementation Status -The local `/auth/bootstrap/join` controller and operation are implemented, but the Gateway route guard blocks external exposure and the route is absent from `publicOpenAPI`; first-party `Join & Play` remains unavailable. Local policy-digest revalidation does not prove the exact target remains valid through Account commit, so the strict ADR 0025 commit gate remains incomplete. The bounded JOIN worker is readback-only: only exact positive operation, scope, membership, role, transition receipt, authority event, and version-1 `COMMITTED` audit receipt/projection evidence can terminalize; absent, minimized, unsupported, or uncertain evidence remains pending, and expiry/attempt limits never resubmit or terminalize. See [Runtime & Data](./runtime-and-data.md#current-join-readback-behavior) for the owner-local details. Explicit playtest grants remain partial: legacy four-field persistence does not authorize non-public discovery or admission, and runtime reads plus legacy mutations fail closed before data access or mutation. Lifecycle-qualified expiry, tenant-admin mutation, distinct audited platform break-glass, idempotent outcomes, retained tombstones, and active-binding ejection remain unimplemented or unproved. See [Account-Owned Playtest Grant Contract](#account-owned-playtest-grant-contract). +`ProfileDto.accountId` and the explicit profile-update Account selector carry the proved canonical Account UUID, never the private Account row key; REST body/path mismatch is rejected. Profile's own `id` and the current numeric tenant selector remain distinct. This correction does not complete tenant-qualified/delegated routes or Social Groups' numeric callers; current proof and activation limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). + +The local `/auth/bootstrap/join` controller and operation are implemented, but the Gateway route guard blocks external exposure and the route is absent from `publicOpenAPI`; first-party `Join & Play` remains unavailable. Local policy-digest revalidation does not prove the exact target remains valid through Account commit, so the strict ADR 0025 commit gate remains incomplete. The bounded JOIN worker is readback-only: only exact positive operation, scope, membership, role, transition receipt, authority event, and version-1 `COMMITTED` audit receipt/projection evidence can terminalize; absent, minimized, unsupported, or uncertain evidence remains pending, and expiry/attempt limits never resubmit or terminalize. See [Runtime & Data](./runtime-and-data.md#current-join-readback-behavior) for the owner-local details. + +Explicit playtest grants remain partial. Legacy four-field persistence is retained, but current runtime grant RPC reads deny before data access and those rows do not authorize non-public discovery or admission. Legacy `POST` and `DELETE /internal/runtime/realm-access-grants` retain their authentication and malformed-input checks, then return `AUTH_UNAVAILABLE` before service dispatch; the corresponding direct service mutators also deny before reads or writes. A global privileged-role claim is not the lifecycle-qualified tenant-admin or Account-authorized operator evidence required by the target contract. No legacy grant row is created, revised or deleted through these unsupported mutations. Expiry bounded by fork lifecycle, tenant-admin create/extend/list/revoke, distinct audited platform break-glass, stable request-idempotent outcomes, retained revocation tombstones, and active-binding ejection remain unimplemented or unproved. 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. The hosted Creator Party, terms catalog, acceptance/currentness evidence, and changed-term lifecycle are target-only. No current Account route, proto/schema, storage, signer/transfer operation, creator UI, or focused proof implements them; Game Design must not maintain a copied catalog or authorize a creator mutation from a tenant-local flag. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index c7e97bb659..cf26b69e0c 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -8,6 +8,8 @@ Account owns platform identity, hosted Creator Party/operator and terms currentn ## Implementation Status +Profile mapping receives the exact provenance-checked Account UUID explicitly rather than treating an ID-only profile relation as identity evidence. Numeric foreign keys stay private and retained rows are unchanged; reads, updates and local export verify exact Account/profile ownership. Proof and the separate tenant-qualified/delegated and Social Groups gaps remain in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). + JOIN reconciliation also requires explicit version-1 COMMITTED receipt/projection evidence and nonblank receiver identities on the exact locked JOIN outbox row. A pending JOIN whose retained COMMITTED outbox row lacks that marker remains pending with retry diagnostics; the historical row is not upgraded or inferred as current projection proof. Deploying the receiver child alone does not promote these historical rows: current exact receipt/projection readback and a guarded evidence-recording path must be proved before they can enable recovery. An unavailable, minimized, or unsupported receiver response cannot enable recovery. Membership-transition receipt tables are introduced by Account V40, after the published V28 audit-delivery migration and the child V39/V39.1 migration history; the published V28 definition remains unchanged. No live migration inventory establishes whether any target applied the earlier child-only V28 receipt description/checksum. Before an affected deployment, Account must read back the exact Flyway history and inventory any existing receipt heads/rows, then record a verified no-data boundary or explicit retained-row disposition/mapping. Do not repair migration history, apply this migration out of order, infer receipt provenance, discard existing evidence, or reinterpret it. PostgreSQL migration execution remains gated until focused Docker-backed proof is available. diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 7cb3a43f95..5c30d56eb8 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -54,18 +54,18 @@ This source intake records no numeric tenant alias, instance, realm, pointer, le ### Retained tenant identity snapshot and local association -Game Session owns the evidence behind `gameSessionEvidenceDigest` in [Game Design's audited association](../game-design-service/api-contracts.md#audited-retained-game-session-tenant-association). It captures an exact, declared identity projection of its retained rows, not a complete runtime backup or proof of historical lifecycle, effects or admission. The closed version-1 snapshot contains `schemaVersion=1`, the exact `targetNamespace`, canonical positive BIGINT decimal-string `legacyGameSessionTenantId`, and all six arrays below. Each array includes every row for that tenant, in ascending numeric primary-key order; the shared namespace uses its tenant primary key. Row objects contain exactly their listed SQL field names. SQL integer values are canonical decimal strings, UUIDs are canonical lowercase strings, booleans are JSON booleans, text is exact valid Unicode, and absent nullable fields are explicit JSON null. No timestamp, display label, actor/reason or participant-result payload is reconstructed or asserted by this projection. +Game Session owns the evidence behind `gameSessionEvidenceDigest` in [Game Design's audited association](../game-design-service/api-contracts.md#audited-retained-game-session-tenant-association). It captures an exact, declared identity projection of its retained rows, not a complete runtime backup or proof of historical lifecycle, effects or admission. The closed version-2 snapshot contains `schemaVersion=2`, the exact `targetNamespace`, canonical positive BIGINT decimal-string `legacyGameSessionTenantId`, and all six arrays below. Each array includes every row for that tenant, in ascending numeric primary-key order; the shared namespace uses its tenant primary key. Row objects contain exactly their listed SQL field names. SQL integer values are canonical decimal strings, UUIDs are canonical lowercase strings, booleans are JSON booleans, text is exact valid Unicode, and absent nullable fields are explicit JSON null. Each instance binds both its nullable retained numeric `owner_account_id` and nullable canonical `owner_account_uuid`; at least one must be present. Capturing those exact slots does not prove an association between them, authorize a guessed mapping, or make a retained numeric owner a canonical Account identity. No timestamp, display label, actor/reason or participant-result payload is reconstructed or asserted by this projection. | Snapshot array / source table | Exact projected fields | | --- | --- | -| `instances` / `game_instances` | `id`, `tenant_id`, `runtime_version`, `script_patch_version`, `owner_account_id`, `status`, `row_version`, `game_template_id`, `launch_descriptor_id`, `version_id`, `release_bundle_id`, `version_state_epoch`, `generation_config_revision`, `remap_set_id`, `script_patch_pinned_control_plane_request_id`, `script_pin_epoch` | +| `instances` / `game_instances` | `id`, `tenant_id`, `runtime_version`, `script_patch_version`, `owner_account_id`, `owner_account_uuid`, `status`, `row_version`, `game_template_id`, `launch_descriptor_id`, `version_id`, `release_bundle_id`, `version_state_epoch`, `generation_config_revision`, `remap_set_id`, `script_patch_pinned_control_plane_request_id`, `script_pin_epoch` | | `pointers` / `gameplay_admission_pointer` | `id`, `tenant_id`, `game_instance_id`, `world_slug`, `realm_slug`, `pointer_version`, `catalog_revision`, `visible`, `requires_character_selection`, `state_scope`, `character_creation_policy`, `public_production_realm`, `realm_id`, `playable_state_namespace_id` | | `sharedNamespaces` / `gameplay_tenant_shared_playable_state_namespace` | `tenant_id`, `playable_state_namespace_id` | | `backfillIssues` / `gameplay_admission_pointer_identity_backfill_issue` | Must be empty; any matching unresolved issue denies capture | | `pointerEvents` / `gameplay_admission_pointer_event` | `id`, `tenant_id`, `game_instance_id`, `world_slug`, `realm_slug`, `pointer_version`, `visible`, `requires_character_selection`, `state_scope`, `character_creation_policy`, `control_plane_request_id`, `prepared_version_upgrade_id`, `public_production_realm` | | `preparedUpgrades` / `prepared_version_upgrade` | `id`, `tenant_id`, `preparation_id`, `control_plane_request_id`, `source_game_instance_id`, `source_version_id`, `target_version_id`, `target_launch_descriptor_id`, `remap_set_id`, `result`, `executed_target_game_instance_id`, `executed_pointer_version`, `execution_control_plane_request_id` | -The owner encodes this closed object using RFC 8785 canonical JSON. The SHA-256 preimage consists of two UTF-8 segments, the exact domain `game-session/retained-tenant-identity-snapshot/v1` and that canonical JSON, each prefixed by its decimal UTF-8 byte length and a colon. The digest is lowercase `sha256:` plus 64 hexadecimal digits. Unknown fields, noncanonical values, duplicate or out-of-order rows, changed scope or digest, and empty retained evidence deny use. Every current pointer must refer to a captured instance of that same tenant, have complete realm/namespace UUIDs and an exact `SHARED` or `ISOLATED` scope; a SHARED pointer must match the captured tenant-shared namespace. Historical pointer events can survive their former runtime instance; they do not acquire missing realm, namespace, catalog revision or World lifecycle evidence through this capture. +The owner encodes this closed object using RFC 8785 canonical JSON. The SHA-256 preimage consists of two UTF-8 segments, the exact domain `game-session/retained-tenant-identity-snapshot/v2` and that canonical JSON, each prefixed by its decimal UTF-8 byte length and a colon. The digest is lowercase `sha256:` plus 64 hexadecimal digits. Unknown fields, noncanonical values, duplicate or out-of-order rows, changed scope or digest, unsupported schema versions, and empty retained evidence deny use. There is no fallback to the unmerged version-1 snapshot. The separately versioned association request and receipt bind this exact snapshot digest without changing their own identity or retry contract. Every current pointer must refer to a captured instance of that same tenant, have complete realm/namespace UUIDs and an exact `SHARED` or `ISOLATED` scope; a SHARED pointer must match the captured tenant-shared namespace. Historical pointer events can survive their former runtime instance; they do not acquire missing realm, namespace, catalog revision or World lifecycle evidence through this capture. Capture requires a non-read-only Game Session owner transaction at PostgreSQL READ COMMITTED. Before any source read it acquires one fixed-order `SHARE MODE NOWAIT` relation-lock statement for all six source tables. Those locks prevent concurrent insertion, mutation, deletion and truncation, including empty-range phantom inserts, and remain held through the local association commit or rollback. Ordinary reads remain possible. An existing writer causes immediate retryable capture failure, not a durable terminal receipt or an assertion of absence. This short, global source-write barrier is limited to the one-time retained-data association; it is not a per-request gameplay lock or an automated runtime quiescence policy. Operational and live use remain gated until the complete capture/receiver proof passes. A prior unlocked preview may prepare approval evidence, but only the receiver's fenced recapture can authorize first commit. @@ -93,6 +93,8 @@ An exact retry or post-restart recovery reuses the same attempt and hold identit The local run-owned Compose fixture path now reaches this owner transaction through a scheduled Game Session coordinator, explicitly disabled by default. It accepts only a read-only capability file bound to the claimed run and Compose project, one stable operation ID, the fixed demo/production fixture, and the exact development Game Session workload leaf and CA fingerprints; host input supplies no runtime ID, lifecycle epoch, catalog revision, pointer, or World hold identity. Game Session resolves and validates the published Game Design launch descriptor, durably reserves the matching launch identity, and drives World prepare/activate with exact epoch readback so a restart resumes the same launch. The coordinator persists the initial-bind intent before requesting the World hold, then uses the owner-local pointer/audit/outcome transaction and World’s authenticated owner-proof reconciliation; bounded retries reuse the same operation identity, and ambiguous evidence keeps the World termination fence closed. This path is a local Compose fixture bootstrap, not the accepted Account `JOIN` transaction or a production activation path; realm identity and admission-pointer authority remain defined by the [Multi-Tenancy contract](../../system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract), and explicit join remains owned by [ADR 0025](../../decisions/adr-0025-explicit-open-enrollment-membership.md). See the [run-owned player-flow smoke boundary](../../system-architecture-testing.md#player-flow-smoke-and-reset-boundaries). Cross-service database race/restart proof remains outstanding; implementation and proof state are tracked in the [Game Session runtime tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md) and [validation workflow](../../../developer-workflows/validation-and-runtime-proof.md). The existing cutover transaction and [replacement hold contract](../world-management-service/api-contracts.md#replacement-cutover-hold-contract) remain distinct; the canonical initial-bind contract is owned by [World](../world-management-service/api-contracts.md#initial-admission-bind-hold-contract). +The run-bound fixture's `ownerAccountId` is a canonical non-nil UUID string, included unchanged in launch and bind digests and exact target readback. Numeric, nil and noncanonical values are rejected, not converted. The Compose helper supplies an explicitly synthetic fixture UUID; this is not Account authentication, an inferred retained-owner mapping, or production admission evidence. New run-owned candidates also reject active or uncertain rows without canonical owner identity, while exact retained launch replay preserves its original identity. + ## Session Front-End and Lease-Owner Routing Game Session deliberately separates socket ownership from region execution ownership: @@ -210,19 +212,19 @@ To start a session via REST: curl -X POST http://localhost:8086/sessions \ -H 'Content-Type: application/json' \ -H 'Authorization: Bearer ' \ - -d '{"tenantId":42,"gameTemplateId":7,"controlPlaneRequestId":"cp-req-1001","ownerAccountId":1001}' + -d '{"tenantId":42,"gameTemplateId":7,"controlPlaneRequestId":"cp-req-1001","ownerAccountId":"f2ed193b-12c1-4c96-bcad-c162229af440"}' ``` ### gRPC examples -The plaintext commands below are current-contract, local-development examples only. Their numeric `tenantId`, `gameTemplateId`, and `ownerAccountId` values intentionally match the current DTO/OpenAPI contract; a future UUID-shaped example would be target-state only and must be labeled separately. Shared and player-facing environments must use the configured mTLS trust bundle and workload certificate, replacing `-plaintext` with `-cacert`, `-cert`, and `-key` arguments as shown in the [gRPC architecture](../../system-architecture-grpc.md). +The plaintext commands below are owner-local development examples, not a complete external operator path. `tenantId` and `gameTemplateId` remain the current numeric selectors; `ownerAccountId` is the exact Account-issued canonical non-nil UUID, not Account's private row key. The example UUID is illustrative and must be replaced with proved owner identity, never inferred from a retained numeric owner. Shared and player-facing environments must use the configured mTLS trust bundle and workload certificate, replacing `-plaintext` with `-cacert`, `-cert`, and `-key` arguments as shown in the [gRPC architecture](../../system-architecture-grpc.md). ```bash grpcurl -plaintext localhost:6565 game_session.v1.GameSessionService/Ping ``` ```bash -grpcurl -plaintext -d '{"tenantId":42,"gameTemplateId":7,"controlPlaneRequestId":"cp-req-1001","ownerAccountId":1001}' \ +grpcurl -plaintext -d '{"tenantId":"42","gameTemplateId":"7","controlPlaneRequestId":"cp-req-1001","ownerAccountId":"f2ed193b-12c1-4c96-bcad-c162229af440"}' \ localhost:6565 game_session.v1.GameSessionService/StartSession ``` @@ -232,7 +234,7 @@ grpcurl -plaintext -d '{"tenantId":42,"gameTemplateId":7,"controlPlaneRequestId" - `tenantId` - `gameTemplateId` - `controlPlaneRequestId` - - `ownerAccountId` + - `ownerAccountId`: canonical non-nil Account UUID; numeric aliases, noncanonical spellings and missing identity deny before owner lookup or mutation - optional `clientIp` - behavior: - Game Session must call Game Design `ResolveLaunchDescriptor(...)` before creating any `gameInstanceId` row diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index fdd1d3fff6..aa1c520159 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -10,9 +10,11 @@ The service runtime model assumes replaceable workers, not authoritative in-proc The sections below define the target-state runtime contract. Current implementation and proof status is: +- The management-owner UUID candidate adds `game_instances.owner_account_uuid` for the exact canonical Account identity and keeps every retained `owner_account_id` BIGINT unchanged as internal historical evidence. Unmapped retained rows have no canonical owner and cannot satisfy owner-self checks; no UUID is derived from a numeric value. New owner requests reject numeric, nil or noncanonical Account selectors before dependency calls or mutation. Inside the owner transaction, `StartSession` locks tenant rows with no canonical UUID and any status other than exact `STOPPED`, then fails with `OWNER_ACCOUNT_IDENTITY_UNAVAILABLE` if such active or uncertain legacy-owner evidence exists; this conservative refusal does not assert that a row belongs to the requesting Account. `RestartSession` rejects a missing or noncanonical owner UUID before changing the row or Redis runtime state. Stop, readback, and pre-termination compensation remain available and preserve raw numeric evidence. This is app-layer containment, not owner mapping or activation: V10.1 still permits an older binary to insert numeric-only rows or reactivate retained rows, so deployment must quiesce or otherwise fence every pre-UUID numeric-owner writer before this path is enabled. Enablement also remains gated on the owner-run deployed migration-history inventory and exact retained-owner readback recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). UUID owner storage and DTO/readback convergence do not supply the missing Account operator authorization-reference, mutation-digest or durable operator-result contracts. The separate gameplay session/presence carrier remains unpublished, and runtime catalog, membership and credential activation remain held back. The focused service and repository unit classes passed with 55 and 4 cases; both Docker-backed PostgreSQL cases were skipped locally, so guard execution, row preservation and lock behavior remain unverified against PostgreSQL. + - V9.1 adds a nullable, non-nil `gameplay_command.account_uuid` storage slot and exact repository readback for a verified producer's canonical Account identity. It preserves the complete existing row and numeric `account_id` evidence without deriving or backfilling a UUID. The current command ingress still uses its older carrier until the consumer correction is integrated; retained rows without authenticated mapping cannot become canonical UUID evidence. Storage availability alone does not prove caller authorization, retained-command replay, or activation of the denied credential and membership paths. -- The current Game Session migration order preserves the parent's V7 catalog-revision audit, V8 legacy-bootstrap repair, and V9 initial-admission ledger; this candidate's authored-world source intake, retained tenant association, and command UUID storage are V7.1, V8.1, and V9.1 respectively. These filename changes resolve source-tree version collisions only and do not establish any deployed Flyway history. Before dependent catalog or command paths activate, verify the exact deployed Game Session history and owner-readback of retained source, snapshot, association, and command rows. Preserve all rows and evidence; unknown provenance remains unresolved. Do not use Flyway repair, out-of-order execution, identity casting, or data cleanup to reconcile prior history. No deployed-history or retained-row readback proof is claimed here. +- The current Game Session migration order preserves the parent's V7 catalog-revision audit, V8 legacy-bootstrap repair, and V9 initial-admission ledger; this candidate's authored-world source intake, retained tenant association, and command UUID storage are V7.1, V8.1, and V9.1 respectively. The parent V10 run-owned launch ledger is preserved, followed by this child's byte-identical owner UUID migration at V10.1. These filename changes resolve source-tree version collisions only and do not establish any deployed Flyway history. Before dependent catalog or command paths activate, verify the exact deployed Game Session history and owner-readback of retained source, snapshot, association, and command rows. Preserve all rows and evidence; unknown provenance remains unresolved. Do not use Flyway repair, out-of-order execution, identity casting, or data cleanup to reconcile prior history. No deployed-history or retained-row readback proof is claimed here. - The shared Gateway connect-context codec now declares and verifies the complete signed-context shape and has local vectors, but first-party runtime parsing remains fail-closed. It does not admit the target context until the independent Gateway Ed25519 verification key is published, Account-to-tenant UUID mapping is available, and the real Account exchange/source-evidence path is proved. Codec and vector presence is not a live issuer/consumer handoff or gameplay-admission proof. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index a43cbcf1b3..280cdbb542 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -312,3 +312,16 @@ Entry format: - Context: the consolidated Unit 1B Game Session check failed `WorldManagementStubServerTest.unknownRoomInstanceIdReturnsNotFound` before its behavior assertion with `Address already in use` on a port selected by `TestSocketUtils.findAvailableTcpPort`. - Observation: checking a free port and releasing it before the actual bind leaves a race. The existing stub already accepts port zero and reports its bound port; its three tests now use that interface without changing their domain assertions. The colliding process was not identified. All three tests and the complete corrected Account/Game Session/Common Test Support check subsequently passed, establishing local recovery without a domain-assertion change. - Expected pattern: use kernel-assigned port-zero binding and the started server's actual port when the fixture supports it, rather than an unreserved free-port probe. Do not weaken an assertion or label a failure as flaky without its exact bind evidence. + +- `2026-10-02`: JDBC UUID fixture bindings need executed PostgreSQL proof + - Context: #2929's local module checks passed with PostgreSQL/cross-service cases skipped, but exact [CI36909989685](https://github.com/benhook1013/FireMUD/actions/runs/36909989685) failed 34 of 35 Game Session cross-service cases during shared fixture insertion. The report explicitly rejected a `character varying` expression for `game_instances.owner_account_uuid`. + - Observation: the fixture passed a canonical UUID string to `JdbcTemplate`, whose JDBC binding remained a string despite the correct domain value. The fixture now binds a `java.util.UUID`, and its focused mock assertion requires that typed value. Local compilation or mock agreement is not proof that PostgreSQL accepts a bind; corrected runner execution remains pending. + - Expected pattern: bind UUID columns with typed UUID values or an explicit, owner-appropriate SQL cast. Preserve the exact canonical domain checks and require executed PostgreSQL/setup proof before attributing subsequent assertions to the changed behavior. + +- `2026-10-02`: Corrected JDBC UUID fixture runner readback + - Outcome: exact #2929 source `96fb1b803d4dd1c6a3cc8f39bda91ae537e25bb6` [CI36912843232](https://github.com/benhook1013/FireMUD/actions/runs/36912843232) strictly passed the owner migration and changed-owner snapshot cases and both Account profile cases, each executed once without skips/failures/errors. Game Session passed the old fixture insertion failure and reached16behavioral assertions before cancellation. This closes the typed-bind setup and profile-username recovery questions above, not the wider behavior or aggregate CI gate. + +- `2026-10-02`: Constrain artifact downloads and prove temporary-directory ownership before cleanup + - Context: a bounded CI investigation authorized only the named Game Session artifact in a fresh `mktemp` directory. The helper instead invoked an unfiltered download into `/tmp/not-used`, receiving three unrelated coverage artifact folders, then removed that directory without proving it was absent before the command. No repository files changed; the helper reported only the three downloaded coverage folders were present, but prior exclusivity was not established. + - Consequence: neither unrelated artifacts nor inferred prior directory ownership supplies valid diagnostic evidence. The directory was removed; its earlier state cannot be established from that inspection. Root stopped further cleanup and restricted the continuation to a new exclusive directory and the exact named artifact. + - Expected pattern: use an artifact-name filter and a freshly created exclusive temporary directory, separate read-only evidence retrieval from cleanup, and never recursively delete a generic output directory merely because a preceding tool wrote into it. Report a scope violation before recovery; do not broaden a read-only task with unapproved cleanup. diff --git a/design/project-management/implementation-tracking/platform-operations-and-delivery.md b/design/project-management/implementation-tracking/platform-operations-and-delivery.md index 884bb1a094..7084537ef8 100644 --- a/design/project-management/implementation-tracking/platform-operations-and-delivery.md +++ b/design/project-management/implementation-tracking/platform-operations-and-delivery.md @@ -116,7 +116,7 @@ The authoritative external-monitoring ownership and target-state detail remain i ### Canonical Demo and Runtime Seed State -Smoke and hosted preview seeders reassert canonical state by stable business identity instead of relying on empty tables. Preview/dev-demo bootstrap uses the canonical Account bootstrap flow and the same demo runtime-seeding contract as local Compose. Account reasserts the demo account and membership; Game Design reasserts the published game/template/version/revision/release-bundle/asset-artifact proof rows; Game Session reasserts manifest, feature-flag, and running-instance rows; Logging & Admin reasserts smoke-facing log/report/moderation rows; and World Management reasserts authored starter topology by natural demo identity before layering runtime topology on it. +Smoke and hosted preview seeders reassert canonical state by stable business identity instead of relying on empty tables. Preview/dev-demo bootstrap uses the canonical Account bootstrap flow and shares local Compose's target runtime-seeding contract. Account reasserts the demo account and membership; Game Design reasserts the published game/template/version/revision/release-bundle/asset-artifact proof rows; current Game Session demo seeding reasserts only manifest and feature-flag metadata; Logging & Admin reasserts smoke-facing log/report/moderation rows; and World Management reasserts authored starter topology by natural demo identity before layering runtime topology on it. Game Session deliberately skips the running-instance row because no authoritative Account UUID source is available. Configured demo/sandbox target IDs do not create that row or establish its owner. UUID-owned runtime provisioning remains required before this seed setup can support playable smoke; current containment and wider producer/consumer gates are recorded in [Player Access and Session](./player-access-and-session.md). No guessed UUID, numeric-owner mapping, or smoke-readiness claim substitutes for that authority. World Management runtime-target seeding is isolated behind `SmokeDemoRuntimeSeedProperties` and consumes explicit `{tenantId, gameInstanceId}` targets. It no longer imports `GameplayCatalogProperties` in main-code smoke seeding, declares canonical demo and sandbox targets explicitly, and honors the shared `FIREMUD_BOOTSTRAP_*` overrides. The fresh-bootstrap script invokes helper scripts explicitly so file-mode drift cannot break the repo-owned proof path. The seed boundary does not attempt to become a general fixture framework or seed authored content beyond the smoke/demo contract. 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 74a9d0f7f0..c499397d2c 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,7 +6,19 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status -The known legacy realm-grant mutation boundary now fails closed: otherwise-valid authenticated privileged POST/DELETE requests return `AUTH_UNAVAILABLE` before service dispatch, and direct grant/revoke service calls reject before repository access. Malformed and unauthorized requests retain their existing denial checks. This preserves retained four-field grant rows rather than revising them without lifecycle authority or hard-deleting their history. The Account full check, formatting/static analysis, service JAR and documentation passed70tasks(23executed/47up-to-date), with511unit cases executed without skips/failures/errors. Strict readback confirms the two HTTP and two direct-service denial cases each executed once, including changed payload under the same request ID and both verbs' unauthenticated/nonprivileged denial. All159PostgreSQL cases skipped without local Docker; this is unit/no-dispatch proof, not database or deployed runtime proof. It does not implement ADR 0138's lifecycle-qualified authorization, bounded expiry, idempotent mutation, tombstones, event delivery or active-binding ejection; those remain required pre-v1 owner work. No runtime path or Account ring mount is enabled. +The known legacy realm-grant mutation boundary now fails closed: otherwise-valid authenticated privileged POST/DELETE requests return `AUTH_UNAVAILABLE` before service dispatch, and direct grant/revoke service calls reject before repository access. Malformed and unauthorized requests retain their existing denial checks. This preserves retained four-field grant rows rather than revising them without lifecycle authority or hard-deleting their history. On owning #2923, the Account full check, formatting/static analysis, service JAR and documentation passed70tasks(23executed/47up-to-date), with511unit cases executed without skips/failures/errors. Strict readback confirms the two HTTP and two direct-service denial cases each executed once, including changed payload under the same request ID and both verbs' unauthenticated/nonprivileged denial. All159PostgreSQL cases skipped without local Docker; this is unit/no-dispatch proof, not database or deployed runtime proof. It does not implement ADR 0138's lifecycle-qualified authorization, bounded expiry, idempotent mutation, tombstones, event delivery or active-binding ejection; those remain required pre-v1 owner work. No runtime path or Account ring mount is enabled. The normally composed management child passed full Account/Game Session/shared-support checks, both service JARs and docs164tasks(29executed/135up-to-date), with517Account unit cases newly executed without skips/failures/errors; Game Session and shared-support test tasks were up-to-date. All161Account PostgreSQL cases skipped locally. The following source-head reports retain their historical attribution, not current-head runner or activation proof. + +Exact corrected #2929 source `96fb1b803d4dd1c6a3cc8f39bda91ae537e25bb6` [CI36912843232](https://github.com/benhook1013/FireMUD/actions/runs/36912843232) completed aggregate FAILURE but strictly passed the V10 migration, changed-owner snapshot and two Account profile cases, each executed once with zero skips/failures/errors. The Account UUID suite14, snapshot suite4 and owner migration suite1 were clean. This proves the corrected PostgreSQL component behavior and recovery from the fixture username/binding failures below. Wider Game Session reached16CommunicationWebSocket behavioral assertions before cancellation; expected/actual values were absent from emitted logs and remain under bounded artifact diagnosis, not presumed fixed by the unpublished108-file carrier. Other aggregate jobs remain red; runtime activation and merge readiness are not established. See the dated runner readback and artifact-download safety follow-up in [AI observations](../ai-observations.md). + +Exact #2929 source `73e19d7f8e74f8fa684c56ca0139ddac0751d31e` [CI36909989685](https://github.com/benhook1013/FireMUD/actions/runs/36909989685) completed aggregate FAILURE. The new management-owner migration case executed once and passed strict PostgreSQL verification, as did the four-case retained snapshot suite including exact changed-owner digest binding. Both new Account profile cases executed but failed during creation because their generated usernames exceeded `accounts.username VARCHAR(50)`; the artifact proves that constraint violation, not an identity/readback assertion failure. The longer Game Session cross-service task failed34of35cases during shared fixture setup because PostgreSQL rejected a string JDBC bind for the UUID owner column. Those fixtures now keep the full random suffix with shorter usernames and use a typed UUID bind with a focused assertion. The affected full Account/Game Session/shared-support checks and both JARs passed162tasks(36executed/126up-to-date); local PostgreSQL cases remain skipped, so corrected-head runner recovery proof is still required. Python, shared dev-tool and other module failures remain separately open, and none of these results enables runtime paths. See the dated [JDBC UUID observation](../ai-observations.md). + +The canonical Account-identity candidate is based on exact #2923 `b93efaedbaec8a36294a594a946a010641e345b4`. Game Session owner requests, storage, readback and owner-self comparison use canonical UUIDs while V10.1 retains numeric owner evidence unchanged and unmapped. The closed version-2 retained-tenant snapshot binds both truthful owner slots; source locks, exact approval and immutable association readback remain required. Before enablement, the owner must inventory deployed migration history and read back the exact retained numeric and UUID owner slots; deployed-history provenance and readback are not established here. Demo seeding no longer invents an Account owner without an authoritative source. This does not activate catalog enrollment, the membership RPC or credentials, nor implement Account operator-reference/digest authorization. The separate gameplay session/presence child remains unpublished at108files; overlapping paths do not prove its remaining unique hunks fit the ceiling. + +Account profile responses, updates and local export now carry the exact provenance-checked Account UUID, not the private row key. Before profile access the service verifies the requested Account source/readback; it then checks exact profile Account/tenant ownership. REST rejects a body/path Account mismatch, malformed/numeric/nil selectors and unauthorized callers without dispatch. Profile IDs and the current numeric tenant selector remain distinct; retained rows are not rewritten. Tenant-qualified/delegated profile routes, membership-generation authorization, Social Groups' numeric profile/presence callers and complete export semantics remain open owner work, not completed by this carrier correction. + +The composed Account/Game Session/Common Test Support checks, both service JARs, formatting/static analysis and documentation passed164tasks(28executed/136up-to-date). Account514unit cases and Game Session1,770unit,18non-PostgreSQL integration and1cross-service case executed without failures/errors in the preceding same-code run; final unit and Game Session test tasks were up-to-date, not fresh executions. Game Session skipped17unit,135integration and33cross-service cases; all161Account PostgreSQL cases skipped locally without Docker. This includes the new V10 migration, snapshot owner-change binding and two Account profile source/readback cases: they compile and are mandatory in early strict CI but have not executed. Shared43unit results were reused, not newly executed. Actionlint,23CI-scope contracts, Flyway sanity(12sets/128files) and diff hygiene passed. Fresh-image, current-head runner database and authenticated live handoff/activation proof remain required. + +Exact published #2923 `b93efaedbaec8a36294a594a946a010641e345b4` [CI36900324924](https://github.com/benhook1013/FireMUD/actions/runs/36900324924) completed aggregate FAILURE, with the full Account job SUCCESS. Strict Account UUID/OTP12, HTTP3 including exact registration UUID/audit, authority-generation3 and fresh UUID snapshot11 all executed with zero skips/failures/errors. Game Session early authored-world5, retained-snapshot3, retained-association9 and command-storage/migration5 also executed cleanly. Its wider check reached cross-service tests, reported19Communication WebSocket assertion failures and was cancelled; the later general strict verifier skipped. Those logs contain no expected/actual assertion text and do not prove their cause. The15availability unit cases lack a separate strict per-case artifact, so they are not independently credited as runner proof. Common Test Support full check passed without an asserted case count. Wider Python/dev-tool, Automation, Game Design, TCP and aggregate gates remain open. This exact source proof does not prove the new local management migration or version-2 snapshot. The held-back Account runtime membership encoder now carries explicit `authorityAvailability=AVAILABLE` only after the existing complete snapshot checks. Game Session requires that exact value before admission, `JOIN_REQUIRED` or non-public enrollment outcomes; missing, unknown and `UNAVAILABLE` values remain `AUTH_UNAVAILABLE`, never absent membership. Fifteen new public/non-public lifecycle negative cases prove no downstream admission or mutation, while the existing ACTIVE/INACTIVE/never-joined producer assertions carry availability. Canonical UUID request/response echoes remain unchanged, and unsupported advanced authority still denies. The live RPC remains disabled: this component does not supply authenticated positive producer/consumer or full authority-bundle proof. @@ -283,7 +295,7 @@ First-party selector state used as connect or admission authority is also comple `PLAY` is the gameplay-binding step after authentication or verified first-party bootstrap identity. Its canonical admission semantics and outcome mappings are owned by [Authentication and authorization](../../architecture/system-architecture-authentication.md); current implementation and proof status are recorded under `AA-2.1`. First-party `PLAY` uses the same runtime authority as generic reconnect. -The canonical gRPC `GameSessionGrpcService.startSession` path preflights IP admission before replacing an existing session. Replacement transfers/reserves the IP slot safely, leaves the existing session alive until the new session and reservation succeed, and on failed admission stops only the tentative session. The shared `GameInstanceService.startSession` default is non-destructive; replacement is explicit. Once replacement is admitted, failure to tear down the old session is warning/cleanup follow-up rather than grounds to revoke the newly accepted session. REST `/sessions` is explicitly noncanonical operator/bootstrap behavior. +The canonical gRPC `GameSessionGrpcService.startSession` path rejects a request when the same owner already has a `RUNNING` session, returning `SESSION_REPLACEMENT_UNAVAILABLE` before candidate creation, session mutation or IP reservation changes. Initial admission retains its IP preflight and tentative-session cleanup after a failed registration. This is approved containment, not an implemented replacement protocol: the former candidate-first flow conflicts with the running-owner uniqueness constraint, and stopping the existing runtime early would violate the failed-candidate preservation contract. A phased candidate reservation, verified World activation, reversible IP reservation and guarded atomic cutover remain unfinished; existing `RUNNING` state must survive failed admission. The shared `GameInstanceService.startSession` default remains non-destructive, and its separately proved lifecycle/replay behavior is unchanged. REST `/sessions` remains explicitly noncanonical operator/bootstrap behavior. ### Session Lifecycle and Logout @@ -333,7 +345,7 @@ Equivalent HTTP, WebSocket, and gRPC failures use stable boundary semantics. The The evidence records focused unit, controller, gRPC, WebSocket, cross-service, and restart/rebind proofs for text parsing and Telnet parity; credential-bearing Account-backed login and generic authenticated `PLAY`; takeover, resume, logout, and replay cleanup; public-production membership idempotency; session-start IP ordering; malformed claim and positive-ID rejection; replay identity/payload mismatch; current REST/gRPC error envelopes; and Gateway upstream/process restart continuity. It does not yet prove the owner gRPC typed-result/non-OK classification across every adopter or a positive first-party signed-context path against the current fail-closed guard. The Telnet cross-service harness uses a lightweight Gateway stub only as a test fixture and has a successful `TelnetGatewayGameSessionCrossServiceIntegrationTest`; the maintained runtime path is not the stub. -The focused admission proofs cover fresh generic-path 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. Current first-party proof is limited to fail-closed behavior; the corrected bare-`LOGIN` denial assertion was not executed in its Docker-backed integration classes locally. Earlier positive fixtures using obsolete HMAC/incomplete context are historical and noncanonical, and do not count as first-party proof after the current guard. Required positive integration proof remains open for structured `WORLD_BROWSE`, `WHO`, and fresh-`PLAY` outputs, authored aliases, first-party policy redaction, and first-party source/scope/cutover/reconnect binding. Generic or internal tests do not substitute for those first-party cases. +The focused admission proof boundary is fresh generic-path acceptance, rejection without destroying the old session or changing candidate/IP state, and the non-destructive operator path. Successful gRPC replacement and its phased reservation/cutover are unimplemented and unproved; old mock-only transfer fixtures are not database uniqueness or live cutover proof. 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. Current first-party proof is limited to fail-closed behavior; the corrected bare-`LOGIN` denial assertion was not executed in its Docker-backed integration classes locally. Earlier positive fixtures using obsolete HMAC/incomplete context are historical and noncanonical, and do not count as first-party proof after the current guard. Required positive integration proof remains open for structured `WORLD_BROWSE`, `WHO`, and fresh-`PLAY` outputs, authored aliases, first-party policy redaction, and first-party source/scope/cutover/reconnect binding. Generic or internal tests do not substitute for those first-party cases. Account authority proof covers account-first tenantless bootstrap authentication and account-scoped session state, the current membership seam, Account-owned non-public grant handling, cross-tenant membership enforcement, and contained export/deletion/recovery boundaries. Every current `DeleteAccount` entry denies before account or financial-row mutation; provider/transfer clearance and retained-data handling remain successor requirements. Explicit JOIN and its bounded readback worker are local: `JOINED` requires exact transition receipt and matching version-1 COMMITTED audit receipt/projection evidence; exact prior-history `ALREADY_ACTIVE` is event-free. Expired or uncertain `PENDING` intents remain retryable and nonterminal despite the diagnostic threshold. PostgreSQL lost-acknowledgement/concurrency, direct text-client proof, connect-token membership-version/authority-generation baseline reread, lifecycle-qualified grant authority, and canonical tenant-role/lifecycle/generation follow-through remain partial or unproved. diff --git a/dev-tools/hosted/preview/resolve-preview-image-tag.sh b/dev-tools/hosted/preview/resolve-preview-image-tag.sh index f9d00f5fd6..442eb9e33c 100644 --- a/dev-tools/hosted/preview/resolve-preview-image-tag.sh +++ b/dev-tools/hosted/preview/resolve-preview-image-tag.sh @@ -33,7 +33,7 @@ runtime_relevant() { .github/workflows/runtime-images.yml | .github/workflows/publish-pr-runtime-images.yml | .github/workflows/smoke.yml | .github/workflows/smoke-full.yml | .dockerignore) return 0 ;; - .github/actions/setup-python/* | .github/actions/load-workflow-tool-versions/* | buildSrc/* | gradle/* | protos/* | docker/* | services/* | dev-tools/smoke/*) + .github/actions/setup-python/* | .github/actions/load-workflow-tool-versions/* | buildSrc/* | gradle/* | protos/* | docker/* | services/* | dev-tools/smoke/* | dev-tools/minio/*) return 0 ;; config/python/smoke-requirements.txt | config/python/smoke-requirements.in | \ diff --git a/dev-tools/smoke/run-owned-compose.sh b/dev-tools/smoke/run-owned-compose.sh index b1ae0f8f9b..f093b6c253 100644 --- a/dev-tools/smoke/run-owned-compose.sh +++ b/dev-tools/smoke/run-owned-compose.sh @@ -2,6 +2,9 @@ # Validate and retain the explicit per-run binding before smoke mutation or # destructive Compose access. This file is sourceable by smoke entrypoints. +# This fixed UUID names only the synthetic run-owned smoke fixture; it is not an +# Account-authenticated identity or a mapping from retained numeric owner data. +FIREMUD_SMOKE_SYNTHETIC_FIXTURE_OWNER_ACCOUNT_UUID="123e4567-e89b-12d3-a456-426614174000" _firemud_smoke_fail() { echo "Refusing run-owned smoke access: $*" >&2 @@ -344,7 +347,8 @@ _firemud_smoke_validate_initial_admission_capability() { fi if ! python3 - "$path" "$FIREMUD_SMOKE_RUN_ID" \ - "$FIREMUD_SMOKE_COMPOSE_PROJECT_NAME" "$operation_id" "$leaf_sha256" "$ca_sha256" <<'PY' + "$FIREMUD_SMOKE_COMPOSE_PROJECT_NAME" "$operation_id" "$leaf_sha256" "$ca_sha256" \ + "$FIREMUD_SMOKE_SYNTHETIC_FIXTURE_OWNER_ACCOUNT_UUID" <<'PY' import json import os import re @@ -352,7 +356,15 @@ import stat import sys import uuid -path, run_id, project_name, operation_id, leaf_sha256, ca_sha256 = sys.argv[1:] +( + path, + run_id, + project_name, + operation_id, + leaf_sha256, + ca_sha256, + synthetic_fixture_owner_account_uuid, +) = sys.argv[1:] allowed = { "schema", "runId", "composeProjectName", "operationId", "tenantId", "gameTemplateId", "ownerAccountId", "worldSlug", "worldDisplayName", @@ -417,7 +429,7 @@ expected = { "operationId": operation_id, "tenantId": 1, "gameTemplateId": 1, - "ownerAccountId": 1, + "ownerAccountId": synthetic_fixture_owner_account_uuid, "worldSlug": "demo", "worldDisplayName": "Demo World", "realmSlug": "production", @@ -532,12 +544,21 @@ ensure_run_owned_initial_admission_capability() { return 1 } if ! python3 - "$temporary" "$FIREMUD_SMOKE_RUN_ID" \ - "$FIREMUD_SMOKE_COMPOSE_PROJECT_NAME" "$operation_id" "$leaf_sha256" "$ca_sha256" <<'PY' + "$FIREMUD_SMOKE_COMPOSE_PROJECT_NAME" "$operation_id" "$leaf_sha256" "$ca_sha256" \ + "$FIREMUD_SMOKE_SYNTHETIC_FIXTURE_OWNER_ACCOUNT_UUID" <<'PY' import json import pathlib import sys -path, run_id, project_name, operation_id, leaf_sha256, ca_sha256 = sys.argv[1:] +( + path, + run_id, + project_name, + operation_id, + leaf_sha256, + ca_sha256, + synthetic_fixture_owner_account_uuid, +) = sys.argv[1:] value = { "schema": "firemud.run-owned-initial-admission-fixture.v1", "runId": run_id, @@ -545,7 +566,7 @@ value = { "operationId": operation_id, "tenantId": 1, "gameTemplateId": 1, - "ownerAccountId": 1, + "ownerAccountId": synthetic_fixture_owner_account_uuid, "worldSlug": "demo", "worldDisplayName": "Demo World", "realmSlug": "production", diff --git a/dev-tools/tests/ci-validation-summary-contract.sh b/dev-tools/tests/ci-validation-summary-contract.sh index fdb265d732..3bf11d75f7 100644 --- a/dev-tools/tests/ci-validation-summary-contract.sh +++ b/dev-tools/tests/ci-validation-summary-contract.sh @@ -41,6 +41,18 @@ if script.index("github.rest.pulls.get") > script.index("github.paginate(github. raise SystemExit("validation-summary must verify the current PR before listing comments") PY +python3 - "$ROOT_DIR/.github/workflows/ci.yml" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +condition = workflow["jobs"]["validation-summary"]["if"] +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +if condition != expected: + raise SystemExit("Optional summary must preserve cancellation, native-PR trust and substantive-event predicates") +PYTHON + script_b64="$({ python3 - "$CI_WORKFLOW" <<'PY' import base64 diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 926cb684a4..fd063f377b 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -498,6 +498,89 @@ grep -Fq "name: \${{ github.event_name == 'pull_request' && github.event.action tmp_dir="$(mktemp -d)" trap 'rm -rf "$tmp_dir"' EXIT + +# The Smoke consumer must outlive its producer and still terminate fail closed. +smoke_clock_fixture="$tmp_dir/smoke-clock.js" +python3 - "$ROOT_DIR" "$smoke_clock_fixture" <<'PY' +from pathlib import Path +import re +import sys +import yaml + +root = Path(sys.argv[1]) +smoke = yaml.load((root / ".github/workflows/smoke.yml").read_text(), Loader=yaml.BaseLoader) +producer = yaml.load((root / ".github/workflows/runtime-images.yml").read_text(), Loader=yaml.BaseLoader) +job = smoke["jobs"]["smoke-gate"] +script = next(step["with"]["script"] for step in job["steps"] if step.get("name") == "Track full-stack smoke result from Build Runtime Images") +producer_minutes = int(re.search(r"const producerTimeoutMinutes = ([0-9]+);", script)[1]) +overhead_minutes = int(re.search(r"const prerequisiteAndQueueAllowanceMinutes = ([0-9]+);", script)[1]) +if producer_minutes != int(producer["jobs"]["pr-local-smoke"]["timeout-minutes"]): + raise SystemExit("Smoke polling producer budget must match the actual full-stack producer timeout") +if overhead_minutes != 45 or int(job["timeout-minutes"]) < producer_minutes + overhead_minutes + 5: + raise SystemExit("Smoke polling must retain bounded scheduling overhead and five-minute job margin") +if "const timeoutMs = (producerTimeoutMinutes + prerequisiteAndQueueAllowanceMinutes) * 60 * 1000;" not in script: + raise SystemExit("Smoke polling deadline must use the checked producer and overhead authorities") +Path(sys.argv[2]).write_text(script) +PY + +node - "$smoke_clock_fixture" <<'NODE' +const assert = require("node:assert/strict"); +const script = require("node:fs").readFileSync(process.argv[2], "utf8"); +const head = "a".repeat(40), base = "b".repeat(40), merge = "c".repeat(40); +const title = `Build Runtime Images secure-pr-artifact pr-42 base-${base} head-${head} merge-${merge} mode-required`; +const context = { repo: { owner: "example", repo: "firemud" }, sha: merge, + payload: { pull_request: { number: 42, head: { sha: head }, base: { ref: "develop", sha: base }, created_at: "2026-09-01T00:00:00Z" } } }; +const execute = new Function("github", "context", "core", "Date", "setTimeout", `return (async () => {\n${script}\n})()`); +async function scenario(outcome, completedAtMinutes) { + let now = 1000; + const start = now; + const failures = []; + const listRuns = async () => {}, listJobs = async () => {}; + const github = { rest: { + pulls: { get: async () => ({ data: { state: "open", head: { sha: head }, base: { ref: "develop", sha: base }, merge_commit_sha: merge } }) }, + repos: { getCommit: async () => ({ data: { sha: merge, parents: [{ sha: base }, { sha: head }] } }) }, + actions: { listWorkflowRuns: listRuns, listJobsForWorkflowRun: listJobs }, + }, paginate: async (method, input) => { + assert.equal(method, listJobs); + assert.equal(input.run_id, 42); + return [{ name: "PR Full-Stack Smoke", status: "completed", conclusion: "success", + steps: [{ name: "Run credential-free full-stack smoke", status: "completed", conclusion: "success" }] }]; + } }; + github.paginate.iterator = async function* (method, input) { + assert.equal(method, listRuns); + assert.equal(input.workflow_id, "runtime-images.yml"); + if (input.event === "repository_dispatch") { yield { data: [] }; return; } + assert.equal(input.head_sha, head); + const complete = now - start >= completedAtMinutes * 60 * 1000; + yield { data: [{ id: 42, event: "pull_request", head_sha: head, display_title: title, pull_requests: [], + status: complete ? "completed" : "in_progress", conclusion: complete ? outcome : null }] }; + }; + const core = { info: () => {}, warning: () => {}, setFailed: message => failures.push(message) }; + const clock = { now: () => now, parse: Date.parse }; + const sleep = (callback, duration) => { now += duration; queueMicrotask(callback); }; + await execute(github, context, core, clock, sleep); + return { failures, minutes: (now - start) / 60000 }; +} +(async () => { + const success = await scenario("success", 30); + assert.deepEqual(success.failures, [], "exact producer success after 25 minutes must be admitted"); + assert.equal(success.minutes, 30); + const failed = await scenario("failure", 30); + assert.equal(failed.failures.length, 1); + assert.match(failed.failures[0], /did not complete successfully/); + assert.equal(failed.minutes, 30, "terminal failure must stop polling promptly"); + const cancelled = await scenario("cancelled", 0); + assert.equal(cancelled.failures.length, 1); + assert.match(cancelled.failures[0], /cancelled/i); + assert.ok(cancelled.minutes <= 5.25, "cancelled source without an exact replacement remains bounded"); + const deadline = await scenario("success", Infinity); + assert.equal(deadline.failures.length, 1); + assert.match(deadline.failures[0], /Timed out waiting for the exact/); + assert.equal(deadline.minutes, 90, "active producers cannot escape the total deadline"); + console.log("Smoke clock contract passed: late success, prompt failure, bounded cancellation and deadline"); +})().catch(error => { console.error(error); process.exitCode = 1; }); +NODE + cat >"$tmp_dir/gh" <<'EOF' #!/usr/bin/env bash set -euo pipefail diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index e27cbf79e0..affc4ae136 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -334,6 +334,44 @@ for path in "$ci_path" "$security_path" "$smoke_path"; do require_contains "$path" 'types: [opened, synchronize, reopened, edited]' done +# Optional native-PR comments cannot delay cancellation or require fork/bot write tokens. +python3 - "$ROOT_DIR" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +root = Path(sys.argv[1]) +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +for filename, jobs in { + "ci.yml": ("validation-summary",), + "security.yml": ("security-summary",), + "smoke.yml": ("smoke-summary-pending", "smoke-summary"), +}.items(): + workflow = yaml.load((root / ".github/workflows" / filename).read_text(), Loader=yaml.BaseLoader) + for job in jobs: + condition = workflow["jobs"][job]["if"] + if condition != expected: + raise SystemExit(f"{filename}/{job} must retain the cancellation, trust and substantive-event condition") + def eligible(cancelled=False, event="pull_request", head_repo="example/repo", actor="contributor", action="synchronize", base_ref=None): + expression = condition[3:-3].replace("!cancelled()", str(not cancelled)) + values = { + "github.event.pull_request.head.repo.full_name": head_repo, + "github.event.changes.base.ref": base_ref, + "github.event_name": event, + "github.repository": "example/repo", + "github.actor": actor, + "github.event.action": action, + } + for key, value in values.items(): + expression = expression.replace(key, repr(value)) + return eval(expression.replace("&&", "and").replace("||", "or").replace("null", "None"), {"__builtins__": {}}) + if not eligible() or not eligible(action="edited", base_ref="develop"): + raise SystemExit(f"{job} must report ordinary results and base retargets") + for arguments in ({"cancelled": True}, {"head_repo": "fork/repo"}, {"actor": "dependabot[bot]"}, {"action": "edited"}, {"event": "push"}): + if eligible(**arguments): + raise SystemExit(f"{job} permits an ineligible comment mutation: {arguments}") +PYTHON + # Metadata-only edits get distinct optional summary contexts; substantive events # retain each summary's canonical name. # shellcheck disable=SC2016 # Assert literal GitHub expression syntax. @@ -1503,6 +1541,15 @@ runtime_service = "services/account-service/src/Main.java" assert run_scope([controller_service]) == {"run_smoke_full": "false"} assert run_scope([controller_smoke_script]) == {"run_smoke_full": "false"} +# Source-built MinIO helpers must require runtime proof even when no Dockerfile changes. +root = Path(sys.argv[1]).resolve().parents[2] +preview_resolver = (root / "dev-tools/hosted/preview/resolve-preview-image-tag.sh").read_text() +preview_predicate = preview_resolver[preview_resolver.index("runtime_relevant() {"):preview_resolver.index('\nif [[ -n "${pr_number}"')] +for helper in ("dev-tools/minio/base_image_refs.py", "dev-tools/minio/build-and-smoke-images.sh"): + assert run_scope([helper]) == {"run_smoke_full": "true"}, helper + preview = subprocess.run(["bash", "-c", preview_predicate + '\nruntime_relevant "$1"', "preview-scope", helper], check=False) + assert preview.returncode == 0, helper +assert subprocess.run(["bash", "-c", preview_predicate + '\nruntime_relevant "$1"', "preview-scope", "design/example.md"], check=False).returncode != 0 assert run_scope([runtime_service]) == {"run_smoke_full": "true"} assert run_scope([controller_service, runtime_service]) == {"run_smoke_full": "true"} PY @@ -1973,6 +2020,7 @@ const scripts = JSON.parse(process.env.SMOKE_SUMMARY_SCRIPTS); const context = { repo: { owner: "example", repo: "firemud" }, issue: { number: 42 }, + payload: { pull_request: { head: { sha: "h" }, base: { ref: "develop", sha: "b" } } }, }; async function checkSummary(jobName, script) { @@ -2005,13 +2053,16 @@ async function checkSummary(jobName, script) { created_at: "2026-08-01T00:00:00Z", }, ]; - const calls = { paginate: [], operations: [], creates: [] }; + const calls = { paginate: [], operations: [], creates: [], bodies: [] }; + let currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request) }; + let readError = null; const listComments = async () => undefined; const github = { rest: { + pulls: { get: async () => { if (readError) throw readError; return { data: currentPullRequest }; } }, issues: { listComments, - updateComment: async ({ comment_id }) => calls.operations.push(`update:${comment_id}`), + updateComment: async ({ comment_id, body }) => { calls.operations.push(`update:${comment_id}`); calls.bodies.push(body); }, deleteComment: async ({ comment_id }) => calls.operations.push(`delete:${comment_id}`), createComment: async (request) => calls.creates.push(request), }, @@ -2025,8 +2076,24 @@ async function checkSummary(jobName, script) { process.env.CHANGES_RESULT = "success"; process.env.RUN_SMOKE_FULL = "true"; process.env.SMOKE_GATE_RESULT = "success"; - const run = new Function("github", "context", `return (async () => {\n${script}\n})()`); - await run(github, context); + const run = new Function("github", "context", "core", `return (async () => {\n${script}\n})()`); + const core = { info: () => {} }; + for (const changed of [ + { state: "closed" }, { head: { sha: "new" } }, + { base: { ref: "main", sha: "b" } }, { base: { ref: "develop", sha: "new" } }, + ]) { + currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request), ...changed }; + await run(github, context, core); + assert.deepEqual(calls.paginate, [], `${jobName} must not list stale comments`); + assert.deepEqual(calls.operations, [], `${jobName} must not mutate stale comments`); + assert.deepEqual(calls.creates, [], `${jobName} must not create stale comments`); + } + readError = new Error("PR guard unavailable"); + await assert.rejects(run(github, context, core), /PR guard unavailable/); + assert.deepEqual(calls.paginate, [], `${jobName} guard errors must fail closed`); + readError = null; + currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request) }; + await run(github, context, core); assert.equal(calls.paginate.length, 1, `${jobName} must paginate once`); assert.equal(calls.paginate[0].method, listComments, `${jobName} must paginate issue comments`); @@ -2037,6 +2104,10 @@ async function checkSummary(jobName, script) { `${jobName} must update the oldest bot summary before deleting later duplicates`, ); assert.deepEqual(calls.creates, [], `${jobName} must not create another summary`); + process.env.CHANGES_RESULT = "failure"; + process.env.SMOKE_GATE_RESULT = "failure"; + await run(github, context, core); + assert.ok(calls.bodies.at(-1).includes("failure"), `${jobName} must report failed dependencies`); } (async () => { diff --git a/dev-tools/tests/pr-runtime-image-publication-contract.sh b/dev-tools/tests/pr-runtime-image-publication-contract.sh index 1bbb114fab..c8a2009a3c 100644 --- a/dev-tools/tests/pr-runtime-image-publication-contract.sh +++ b/dev-tools/tests/pr-runtime-image-publication-contract.sh @@ -159,7 +159,7 @@ cat > "$artifact_dir/pr-runtime-provenance.json" < "$fixture_dir/source-run.json" < "$fixture_dir/pull-request.json" <&2 + exit 1 + fi + python3 - "$fixture_dir/source-run.json" "$source_title" <<'PY' +import json +import sys +from pathlib import Path +p = Path(sys.argv[1]); data = json.loads(p.read_text()); data["name"] = "Build Runtime Images"; data["display_title"] = sys.argv[2]; p.write_text(json.dumps(data)) +PY +done run_validation grep -Fxq "IMAGE_TAG=pr-merge-$merge_sha" "$fixture_dir/github-env" grep -Fxq "PR_RUNTIME_ARTIFACT_DIR=$artifact_dir" "$fixture_dir/github-env" diff --git a/dev-tools/tests/run-owned-initial-admission-capability-contract.sh b/dev-tools/tests/run-owned-initial-admission-capability-contract.sh index cf8d9714ab..476b2db080 100644 --- a/dev-tools/tests/run-owned-initial-admission-capability-contract.sh +++ b/dev-tools/tests/run-owned-initial-admission-capability-contract.sh @@ -5,6 +5,9 @@ ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" TEST_ROOT="$(mktemp -d "${TMPDIR:-/tmp}/firemud-run-owned-admission-contract.XXXXXX")" trap 'rm -rf -- "$TEST_ROOT"' EXIT chmod 700 "$TEST_ROOT" +# This owner value proves only the synthetic run-owned fixture shape; it does not +# claim Account authentication or derive provenance from a retained numeric ID. +SYNTHETIC_FIXTURE_OWNER_ACCOUNT_UUID="123e4567-e89b-12d3-a456-426614174000" docker() { case "$1 $2" in @@ -37,7 +40,7 @@ expect_failure() { } load_operation_id() { - python3 - "$1" <<'PY' + python3 - "$1" "$SYNTHETIC_FIXTURE_OWNER_ACCOUNT_UUID" <<'PY' import json import pathlib import sys @@ -54,7 +57,8 @@ assert set(value) == expected_fields, set(value) assert value["schema"] == "firemud.run-owned-initial-admission-fixture.v1" assert value["tenantId"] == 1 assert value["gameTemplateId"] == 1 -assert value["ownerAccountId"] == 1 +assert type(value["ownerAccountId"]) is str +assert value["ownerAccountId"] == sys.argv[2] assert value["worldSlug"] == "demo" assert value["worldDisplayName"] == "Demo World" assert value["realmSlug"] == "production" @@ -179,6 +183,24 @@ expect_failure replaced_capability reject_replaced_capability mv -- "$capability_backup" "$base_capability" [[ "$(load_operation_id "$base_capability")" == "$base_operation_id" ]] +capability_backup="$TEST_ROOT/capability-before-numeric-owner.json" +cp -p -- "$base_capability" "$capability_backup" +python3 - "$TEST_ROOT/numeric-owner-capability.json" "$base_capability" <<'PY' +import json +import pathlib +import sys + +source = pathlib.Path(sys.argv[2]) +value = json.loads(source.read_text(encoding="utf-8")) +value["ownerAccountId"] = 1 +pathlib.Path(sys.argv[1]).write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") +PY +chmod 444 "$TEST_ROOT/numeric-owner-capability.json" +mv -- "$TEST_ROOT/numeric-owner-capability.json" "$base_capability" +expect_failure numeric_owner_account_id reject_replaced_capability +mv -- "$capability_backup" "$base_capability" +[[ "$(load_operation_id "$base_capability")" == "$base_operation_id" ]] + capability_backup="$TEST_ROOT/capability-before-missing-restart.json" mv -- "$base_capability" "$capability_backup" expect_failure missing_restart_capability reject_missing_restart_capability diff --git a/dev-tools/tests/security-summary-contract.sh b/dev-tools/tests/security-summary-contract.sh index 1164ed55ee..56120dc56b 100644 --- a/dev-tools/tests/security-summary-contract.sh +++ b/dev-tools/tests/security-summary-contract.sh @@ -15,6 +15,18 @@ grep -Fq 'currentPullRequest.head.sha !== expectedHeadSha' "$workflow" grep -Fq 'currentPullRequest.base.ref !== expectedBaseRef' "$workflow" grep -Fq 'currentPullRequest.base.sha !== expectedBaseSha' "$workflow" +python3 - "$repo_root/.github/workflows/security.yml" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +condition = workflow["jobs"]["security-summary"]["if"] +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +if condition != expected: + raise SystemExit("Optional summary must preserve cancellation, native-PR trust and substantive-event predicates") +PYTHON + test_root="$(mktemp -d)" trap 'rm -rf -- "$test_root"' EXIT script_path="$test_root/security-summary.js" @@ -164,4 +176,43 @@ run(github, context, core).then(async () => { }); NODE +# Execute the checked-in scanner step using the explicit Actions Bash shell. +# The fake scanner and reports stay in one disposable directory; no scan/network occurs. +python3 - "$workflow" "$repo_root/config/security/trivy.yaml" <<'PYTHON' +from pathlib import Path +import os +import subprocess +import sys +import tempfile +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +steps = workflow["jobs"]["trivy-scan"]["steps"] +scanner = next(step for step in steps if step.get("name") == "🔍 Run Trivy and Save Report") +upload = next(step for step in steps if step.get("name") == "📤 Upload Trivy Report") +if scanner.get("shell") != "bash" or upload.get("if") != "always()": + raise SystemExit("Trivy must use explicit pipefail Bash and retain always-uploaded reports") +settings = yaml.safe_load(Path(sys.argv[2]).read_text()) +if settings.get("exit-code") != 1 or settings.get("severity") != ["CRITICAL", "HIGH"] or settings.get("ignore-unfixed") is not True: + raise SystemExit("Trivy failure policy and filters must remain intact") +with tempfile.TemporaryDirectory(prefix="firemud-trivy-pipeline-") as directory: + root = Path(directory) + scanner_path = root / "trivy" + scanner_path.write_text('#!/bin/sh\nprintf "scanner-result-%s\\n" "$FAKE_TRIVY_EXIT"\nexit "$FAKE_TRIVY_EXIT"\n') + scanner_path.chmod(0o755) + for exit_status in (0, 1, 2): + environment = dict(os.environ, PATH=str(root) + os.pathsep + os.environ["PATH"], FAKE_TRIVY_EXIT=str(exit_status)) + # actions/runner explicit shell:bash -> bash --noprofile --norc -e -o pipefail {0}. + script = root / "step.sh" + script.write_text(scanner["run"]) + result = subprocess.run(["bash", "--noprofile", "--norc", "-e", "-o", "pipefail", str(script)], cwd=root, env=environment, capture_output=True, text=True) + if result.returncode != exit_status: + raise SystemExit(f"Trivy exit {exit_status} was masked: {result.returncode}") + if (root / "trivy-report.txt").read_text() != f"scanner-result-{exit_status}\n": + raise SystemExit("tee must retain the report even when the scanner fails") + if ("::endgroup::" in result.stdout) != (exit_status == 0): + raise SystemExit("Failed scanner pipelines must stop the step") +print("Trivy pipeline contract passed: scanner success/vulnerability/error with reports retained") +PYTHON + echo "security summary contract passed" diff --git a/dev-tools/tests/static-analysis-summary-contract.sh b/dev-tools/tests/static-analysis-summary-contract.sh index 14165090c5..17edc16a3a 100644 --- a/dev-tools/tests/static-analysis-summary-contract.sh +++ b/dev-tools/tests/static-analysis-summary-contract.sh @@ -262,7 +262,7 @@ const context = { payload: { workflow_run: { event: "pull_request", - name: `CodeQL Analysis pr-42 base-${baseSha} head-${headSha}`, + name: "CodeQL Analysis", path: ".github/workflows/codeql.yml", head_sha: headSha, head_branch: "feature", @@ -273,7 +273,7 @@ const context = { }; const core = { info: () => {} }; const run = new Function("github", "context", "core", `return (async () => {\n${script}\n})()`); -run(github, context, core).then(() => { +run(github, context, core).then(async () => { if (calls.paginate.length !== 4) throw new Error(`expected four paginated calls, got ${calls.paginate.length}`); if (!calls.paginate.every(({ input }) => input.per_page === 100)) throw new Error("all API listings must request page size 100"); if (calls.updated.length !== 1 || calls.updated[0].comment_id !== 2) throw new Error("oldest bot summary was not updated"); @@ -281,6 +281,12 @@ run(github, context, core).then(() => { if (calls.created.length !== 0) throw new Error("existing bot summary should be updated"); if (!calls.updated[0].body.includes("❌ Static analysis checks failed")) throw new Error("new failure was masked by the older success"); if (!calls.updated[0].body.includes("CodeQL gate: `failure`")) throw new Error("latest CodeQL gate result was not selected"); + context.payload.workflow_run.name = "Forged workflow name"; + await run(github, context, core); + if (calls.paginate.length !== 4 || calls.updated.length !== 1 || calls.deleted.length !== 1) { + throw new Error("unrelated source names must not query runs or alter comments"); + } + context.payload.workflow_run.name = "CodeQL Analysis"; currentHeadSha = "d".repeat(40); return run(github, context, core).then(() => { if (calls.paginate.length !== 4 || calls.updated.length !== 1 || calls.deleted.length !== 1) { @@ -316,6 +322,7 @@ run(github, context, core).then(() => { calls.deleted.length = 0; calls.updated.length = 0; calls.created.length = 0; + context.payload.workflow_run.name = `CodeQL Analysis pr-42 base-${baseSha} head-${headSha}`; deleteStatus = 404; return run(github, context, core).then(() => { if (calls.deleted.length !== 1 || calls.deleted[0] !== 3) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java index eb2626c23a..6e45e31f53 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java @@ -48,6 +48,10 @@ public ResponseEntity> updateProfile( UUID parsedAccountUuid = AccountRequestReaders.requireAccountUuid(accountId); long parsedTenantId = AccountRequestReaders.requireTenantId(request.tenantId()); requireProfileOwner(parsedAccountUuid); + UUID requestAccountUuid = AccountRequestReaders.requireAccountUuid(request.accountId()); + if (!parsedAccountUuid.equals(requestAccountUuid)) { + throw new IllegalArgumentException("accountId must match the profile path"); + } if (request.presenceVisibilityPolicy() == null) { throw new IllegalArgumentException("presenceVisibilityPolicy must be provided"); } @@ -55,9 +59,10 @@ public ResponseEntity> updateProfile( Long parsedAccountId = accountService.resolveAccountStorageId(parsedAccountUuid); ProfileDto dto = accountService.updateProfile( + parsedAccountId, new UpdateProfileRequest( parsedTenantId, - parsedAccountId, + requestAccountUuid.toString(), request.displayName(), request.bio(), request.presenceVisibilityPolicy())); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/ProfileDto.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/ProfileDto.java index 4a2ededcd4..8c7c3c25bd 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/ProfileDto.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/ProfileDto.java @@ -7,7 +7,7 @@ public record ProfileDto( Long id, @NotNull Long tenantId, - @NotNull Long accountId, + @NotNull String accountId, @Size(max = 100) String displayName, @Size(max = 255) String bio, @NotNull ProfilePresenceVisibilityPolicy presenceVisibilityPolicy) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/UpdateProfileRequest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/UpdateProfileRequest.java index b24378b729..9d6e0e4184 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/UpdateProfileRequest.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/UpdateProfileRequest.java @@ -6,7 +6,7 @@ public record UpdateProfileRequest( @NotNull Long tenantId, - @NotNull Long accountId, + @NotNull String accountId, @Size(max = 100) String displayName, @Size(max = 255) String bio, @NotNull ProfilePresenceVisibilityPolicy presenceVisibilityPolicy) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/mapper/ProfileMapper.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/mapper/ProfileMapper.java index 18137c1d66..ca080db0de 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/mapper/ProfileMapper.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/mapper/ProfileMapper.java @@ -3,11 +3,11 @@ import net.firedevops.firemud.accountservice.dto.ProfileDto; import net.firedevops.firemud.accountservice.entity.Profile; import org.mapstruct.Mapper; +import org.mapstruct.Mapping; import org.mapstruct.ReportingPolicy; @Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE) public interface ProfileMapper { - ProfileDto toDto(Profile entity); - - Profile toEntity(ProfileDto dto); + @Mapping(target = "accountId", source = "accountUuid") + ProfileDto toDto(Profile entity, String 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 f55e8f7d1c..35988d7afd 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 @@ -77,12 +77,14 @@ RealmAccessGrantResult getRealmAccessGrantForRuntime( /** Resolves a proved canonical Account UUID to its private Account-local storage key. */ Long resolveAccountStorageId(UUID accountUuid); + /** Reads a tenant profile with an Account-local storage selector after owner-side UUID proof. */ ProfileDto getProfile(Long tenantId, Long accountId); java.util.Map listPresenceVisibilityPolicies( Long tenantId, java.util.List accountIds); - ProfileDto updateProfile(UpdateProfileRequest request); + /** Updates a profile using an Account-local selector and the request's canonical Account UUID. */ + ProfileDto updateProfile(Long accountStorageId, UpdateProfileRequest request); AccountLoginAuthModesDto getLoginAuthModes(Long accountId); 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 62cd249489..77bbdf7547 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 @@ -859,6 +859,13 @@ public void getProfile( .build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (IllegalStateException ex) { + GetProfileResponse response = + GetProfileResponse.newBuilder() + .setError(appError("GetProfile", "INTERNAL", "Profile source validation failed")) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); } } @@ -937,9 +944,10 @@ public void updateProfile( String bio = node.path("bio").asText(null); String presenceVisibilityPolicy = node.path("presenceVisibilityPolicy").asText(null); accountService.updateProfile( + accountId, new net.firedevops.firemud.accountservice.dto.UpdateProfileRequest( tenantId, - accountId, + accountUuid.toString(), displayName, bio, ProfilePresenceVisibilityPolicy.valueOf( @@ -965,6 +973,14 @@ public void updateProfile( .build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (IllegalStateException ex) { + UpdateProfileResponse response = + UpdateProfileResponse.newBuilder() + .setSuccess(false) + .setError(appError("UpdateProfile", "INTERNAL", "Profile source validation failed")) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); } catch (Exception ex) { UpdateProfileResponse response = UpdateProfileResponse.newBuilder() 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 d39c0be074..83b68a3a01 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 @@ -17,6 +17,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.account.AuthenticationErrorCodes; @@ -2366,12 +2367,16 @@ public Long resolveAccountStorageId(UUID accountUuid) { @Transactional(readOnly = true) @Timed(value = "account.get_profile") public ProfileDto getProfile(Long tenantId, Long accountId) { + Account account = requireAccount(accountId); + requireExactAccountStorageId(account, accountId); + UUID accountUuid = requirePersistedAccountUuid(account); requireProfileMembership(tenantId, accountId); Profile profile = profileRepository .findByAccountIdAndTenantId(accountId, tenantId) .orElseThrow(() -> new IllegalArgumentException("Profile not found")); - return profileMapper.toDto(profile); + requireProfileBelongsTo(profile, accountId, tenantId); + return profileMapper.toDto(profile, accountUuid.toString()); } @Override @@ -2398,22 +2403,66 @@ public Map listPresenceVisibilityPolicies @Override @Transactional @Timed(value = "account.update_profile") - public ProfileDto updateProfile(UpdateProfileRequest request) { + public ProfileDto updateProfile(Long accountStorageId, UpdateProfileRequest request) { + UUID requestedAccountUuid = requireProfileAccountUuid(request.accountId()); + Account account = requireAccount(accountStorageId); + requireExactAccountStorageId(account, accountStorageId); + UUID persistedAccountUuid = requirePersistedAccountUuid(account); + if (!persistedAccountUuid.equals(requestedAccountUuid)) { + throw new IllegalArgumentException("Profile account identity does not match its source"); + } request.presenceVisibilityPolicy().requireSelectableByAccountHolder(); - requireProfileMembership(request.tenantId(), request.accountId()); + requireProfileMembership(request.tenantId(), accountStorageId); Profile profile = profileRepository - .findByAccountIdAndTenantId(request.accountId(), request.tenantId()) + .findByAccountIdAndTenantId(accountStorageId, request.tenantId()) .orElseThrow(() -> new IllegalArgumentException("Profile not found")); + requireProfileBelongsTo(profile, accountStorageId, request.tenantId()); profile.setDisplayName(request.displayName()); profile.setBio(request.bio()); profile.setPresenceVisibilityPolicy(request.presenceVisibilityPolicy()); profile = profileRepository.save(profile); + requireProfileBelongsTo(profile, accountStorageId, request.tenantId()); runAfterCommit( () -> notificationService.sendNotification( - request.tenantId(), request.accountId(), "Profile updated")); - return profileMapper.toDto(profile); + request.tenantId(), accountStorageId, "Profile updated")); + return profileMapper.toDto(profile, persistedAccountUuid.toString()); + } + + private UUID requireProfileAccountUuid(String accountId) { + if (accountId == null || accountId.isBlank()) { + throw new IllegalArgumentException("accountId must be a canonical non-nil UUID"); + } + try { + UUID accountUuid = UUID.fromString(accountId); + if (NIL_ACCOUNT_UUID.equals(accountUuid) || !accountUuid.toString().equals(accountId)) { + throw new IllegalArgumentException("accountId must be a canonical non-nil UUID"); + } + return accountUuid; + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("accountId must be a canonical non-nil UUID", exception); + } + } + + private void requireProfileBelongsTo(Profile profile, Long accountId, Long tenantId) { + if (profile == null + || accountId == null + || accountId <= 0 + || tenantId == null + || tenantId <= 0 + || profile.getAccount() == null + || !Objects.equals(profile.getAccount().getId(), accountId) + || !Objects.equals(profile.getTenantId(), tenantId)) { + throw new IllegalStateException("Profile source does not match its exact Account and tenant"); + } + } + + private void requireExactAccountStorageId(Account account, Long requestedAccountStorageId) { + if (!Objects.equals(account.getId(), requestedAccountStorageId)) { + throw new IllegalStateException( + "Account readback did not match its exact requested storage row"); + } } private void requireProfileMembership(Long tenantId, Long accountId) { @@ -2445,9 +2494,22 @@ public AccountLoginAuthModesDto updateLoginAuthModes( @Timed(value = "account.export") public AccountDataExportDto exportAccountData(Long accountId) { Account account = requireAccount(accountId); - requirePersistedAccountUuid(account); + requireExactAccountStorageId(account, accountId); + UUID accountUuid = requirePersistedAccountUuid(account); List profiles = - profileRepository.findByAccountId(accountId).stream().map(profileMapper::toDto).toList(); + profileRepository.findByAccountId(accountId).stream() + .map( + profile -> { + if (profile == null + || profile.getTenantId() == null + || profile.getTenantId() <= 0) { + throw new IllegalStateException( + "Profile export row is missing its tenant source"); + } + requireProfileBelongsTo(profile, accountId, profile.getTenantId()); + return profileMapper.toDto(profile, accountUuid.toString()); + }) + .toList(); return new AccountDataExportDto(accountMapper.toDto(account), profiles); } diff --git a/services/account-service/src/main/resources/openapi.yaml b/services/account-service/src/main/resources/openapi.yaml index 2f4d03c591..95a476dd32 100644 --- a/services/account-service/src/main/resources/openapi.yaml +++ b/services/account-service/src/main/resources/openapi.yaml @@ -237,25 +237,36 @@ components: id: type: integer tenantId: - type: string + type: integer + format: int64 accountId: type: string + format: uuid displayName: type: string bio: type: string + presenceVisibilityPolicy: + type: string + enum: [PUBLIC, FRIENDS_ONLY, PRIVATE, HIDDEN_STAFF] + required: [tenantId, accountId, presenceVisibilityPolicy] UpdateProfileRequest: type: object properties: tenantId: - type: string + type: integer + format: int64 accountId: type: string + format: uuid displayName: type: string bio: type: string - required: [tenantId, accountId] + presenceVisibilityPolicy: + type: string + enum: [PUBLIC, FRIENDS_ONLY, PRIVATE] + required: [tenantId, accountId, presenceVisibilityPolicy] PasswordResetRequest: type: object properties: diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountAuthenticationUuidIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountAuthenticationUuidIntegrationTest.java index 12c314f744..a798750989 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountAuthenticationUuidIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountAuthenticationUuidIntegrationTest.java @@ -20,6 +20,7 @@ import net.firedevops.firemud.accountservice.controller.ProfileController; import net.firedevops.firemud.accountservice.dto.AuthenticationResult; import net.firedevops.firemud.accountservice.dto.CreateAccountRequest; +import net.firedevops.firemud.accountservice.dto.ProfileDto; import net.firedevops.firemud.accountservice.dto.UpdateProfileRequest; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; @@ -424,7 +425,7 @@ void nonAuthenticationSessionFailureRollsBackOtpConsumption() { } @Test - void unmappedUuidDeniesProfileMutationEvenWhenBodyNamesAnExistingPrivateRow() { + void unmappedUuidDeniesProfileMutationWithoutTouchingAnExistingPrivateRow() { String suffix = UUID.randomUUID().toString(); String username = "profile-" + suffix; String email = username + "@example.com"; @@ -456,7 +457,7 @@ void unmappedUuidDeniesProfileMutationEvenWhenBodyNamesAnExistingPrivateRow() { UpdateProfileRequest request = new UpdateProfileRequest( PROFILE_TENANT_ID, - accountId, + unmappedUuid.toString(), "must-not-be-written", "must-not-be-written", ProfilePresenceVisibilityPolicy.PRIVATE); @@ -468,6 +469,140 @@ void unmappedUuidDeniesProfileMutationEvenWhenBodyNamesAnExistingPrivateRow() { assertThat(profileRowJson(accountId)).isEqualTo(profileBefore); } + @Test + void persistedProfileGetUpdateAndExportCarryTheCanonicalAccountUuid() { + String suffix = UUID.randomUUID().toString(); + String username = "profile-uuid-" + suffix; + var created = + accountService.createAccount( + new CreateAccountRequest(username, username + "@example.com", PASSWORD)); + UUID accountUuid = UUID.fromString(created.id()); + long accountStorageId = accountService.resolveAccountStorageId(accountUuid); + dsl.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, 'EXPLICIT_JOIN')", + accountStorageId, + PROFILE_TENANT_ID); + long profileStorageId = + Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO profiles (account_id, tenant_id, display_name, bio) " + + "VALUES (?, ?, ?, ?) RETURNING id", + accountStorageId, + PROFILE_TENANT_ID, + "before-update", + "before-bio") + .fetchOne(0, Long.class), + "Expected inserted profile storage id"); + + SessionContext.setContext(accountUuid.toString(), List.of(), Map.of()); + ProfileController controller = new ProfileController(accountService); + ProfileDto initial = + Objects.requireNonNull( + Objects.requireNonNull( + controller + .getProfile(accountUuid.toString(), Long.toString(PROFILE_TENANT_ID)) + .getBody(), + "Expected profile GET response") + .data(), + "Expected profile GET data"); + + assertThat(initial.id()).isEqualTo(profileStorageId); + assertThat(initial.tenantId()).isEqualTo(PROFILE_TENANT_ID); + assertThat(initial.accountId()).isEqualTo(accountUuid.toString()); + assertThat(initial.accountId()).isNotEqualTo(Long.toString(accountStorageId)); + + ProfileDto updated = + Objects.requireNonNull( + Objects.requireNonNull( + controller + .updateProfile( + accountUuid.toString(), + new UpdateProfileRequest( + PROFILE_TENANT_ID, + accountUuid.toString(), + "after-update", + "after-bio", + ProfilePresenceVisibilityPolicy.PRIVATE)) + .getBody(), + "Expected profile update response") + .data(), + "Expected updated profile data"); + + assertThat(updated.id()).isEqualTo(profileStorageId); + assertThat(updated.tenantId()).isEqualTo(PROFILE_TENANT_ID); + assertThat(updated.accountId()).isEqualTo(accountUuid.toString()); + assertThat(profileRowJson(accountStorageId)) + .contains("after-update") + .contains("after-bio") + .contains("PRIVATE"); + + var exported = accountService.exportAccountData(accountStorageId); + assertThat(exported.account().id()).isEqualTo(accountUuid.toString()); + assertThat(exported.profiles()) + .singleElement() + .satisfies( + profile -> { + assertThat(profile.id()).isEqualTo(profileStorageId); + assertThat(profile.tenantId()).isEqualTo(PROFILE_TENANT_ID); + assertThat(profile.accountId()).isEqualTo(accountUuid.toString()); + }); + org.mockito.Mockito.verify(notificationService) + .sendNotification(PROFILE_TENANT_ID, accountStorageId, "Profile updated"); + } + + @Test + void profileUpdateRejectsSourceUuidMismatchWithoutSavingOrNotifying() { + String suffix = UUID.randomUUID().toString(); + String firstUsername = "source-a-" + suffix; + String secondUsername = "source-b-" + suffix; + var first = + accountService.createAccount( + new CreateAccountRequest(firstUsername, firstUsername + "@example.com", PASSWORD)); + var second = + accountService.createAccount( + new CreateAccountRequest(secondUsername, secondUsername + "@example.com", PASSWORD)); + long firstAccountStorageId = + accountService.resolveAccountStorageId(UUID.fromString(first.id())); + UUID secondAccountUuid = UUID.fromString(second.id()); + dsl.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, 'EXPLICIT_JOIN')", + firstAccountStorageId, + PROFILE_TENANT_ID); + dsl.execute( + "INSERT INTO profiles (account_id, tenant_id, display_name, bio) VALUES (?, ?, ?, ?)", + firstAccountStorageId, + PROFILE_TENANT_ID, + "original-display-name", + "original-bio"); + String profileBefore = profileRowJson(firstAccountStorageId); + + assertThatThrownBy( + () -> + accountService.updateProfile( + firstAccountStorageId, + new UpdateProfileRequest( + PROFILE_TENANT_ID, + secondAccountUuid.toString(), + "must-not-be-written", + "must-not-be-written", + ProfilePresenceVisibilityPolicy.PRIVATE))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Profile account identity does not match its source"); + + assertThat(profileRowJson(firstAccountStorageId)).isEqualTo(profileBefore); + org.mockito.Mockito.verify(notificationService, org.mockito.Mockito.never()) + .sendNotification( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString()); + } + private void assertAuthenticationAndPrivateLookup( String username, long accountId, UUID expectedAccountUuid) { AuthenticationResult result = accountService.authenticate(username, PASSWORD); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java index a8b74c6efa..878c6f19ae 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java @@ -52,7 +52,8 @@ void clear() { @Test void getProfileReturnsDto() throws Exception { ProfileDto dto = - new ProfileDto(1L, 1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.FRIENDS_ONLY); + new ProfileDto( + 1L, 1L, ACCOUNT_UUID, "demo", "bio", ProfilePresenceVisibilityPolicy.FRIENDS_ONLY); when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))).thenReturn(2L); when(accountService.getProfile(1L, 2L)).thenReturn(dto); @@ -64,17 +65,20 @@ void getProfileReturnsDto() throws Exception { .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isOk()) .andExpect(jsonPath("$.status").value("SUCCESS")) + .andExpect(jsonPath("$.data.accountId").value(ACCOUNT_UUID)) .andExpect(jsonPath("$.data.displayName").value("demo")); } @Test void updateProfileReturnsDto() throws Exception { UpdateProfileRequest req = - new UpdateProfileRequest(1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); + new UpdateProfileRequest( + 1L, ACCOUNT_UUID, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); ProfileDto dto = - new ProfileDto(1L, 1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); + new ProfileDto( + 1L, 1L, ACCOUNT_UUID, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))).thenReturn(2L); - when(accountService.updateProfile(req)).thenReturn(dto); + when(accountService.updateProfile(2L, req)).thenReturn(dto); String token = jwtUtil.generateToken(ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID)); mockMvc @@ -85,6 +89,7 @@ void updateProfileReturnsDto() throws Exception { .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isOk()) .andExpect(jsonPath("$.status").value("SUCCESS")) + .andExpect(jsonPath("$.data.accountId").value(ACCOUNT_UUID)) .andExpect(jsonPath("$.data.displayName").value("demo")) .andExpect(jsonPath("$.data.presenceVisibilityPolicy").value("PRIVATE")); } @@ -199,11 +204,13 @@ void getProfileRejectsZeroTenantIdBeforeDispatch() throws Exception { @Test void updateProfileAllowsCurrentAccountWithoutPrivilegedTenantRole() throws Exception { UpdateProfileRequest req = - new UpdateProfileRequest(1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); + new UpdateProfileRequest( + 1L, ACCOUNT_UUID, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); ProfileDto dto = - new ProfileDto(1L, 1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); + new ProfileDto( + 1L, 1L, ACCOUNT_UUID, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))).thenReturn(2L); - when(accountService.updateProfile(req)).thenReturn(dto); + when(accountService.updateProfile(2L, req)).thenReturn(dto); String token = jwtUtil.generateToken(ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID)); mockMvc @@ -216,11 +223,50 @@ void updateProfileAllowsCurrentAccountWithoutPrivilegedTenantRole() throws Excep .andExpect(jsonPath("$.status").value("SUCCESS")); } + @Test + void updateProfileRejectsBodyAccountMismatchBeforeIdentityLookup() throws Exception { + UpdateProfileRequest request = + new UpdateProfileRequest( + 1L, OTHER_ACCOUNT_UUID, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); + String token = jwtUtil.generateToken(ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID)); + + mockMvc + .perform( + put("/profiles/" + ACCOUNT_UUID) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(request)) + .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error.message").value("accountId must match the profile path")); + + verifyNoInteractions(accountService); + } + + @Test + void updateProfileRejectsNumericNilAndMalformedBodyAccountIdsBeforeIdentityLookup() + throws Exception { + String token = jwtUtil.generateToken(ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID)); + for (String bodyAccountId : List.of("2", "00000000-0000-0000-0000-000000000000", "bad")) { + UpdateProfileRequest request = + new UpdateProfileRequest( + 1L, bodyAccountId, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); + mockMvc + .perform( + put("/profiles/" + ACCOUNT_UUID) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(request)) + .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + .andExpect(status().isBadRequest()); + } + + verifyNoInteractions(accountService); + } + @Test void updateProfileRejectsReservedHiddenStaffPolicyBeforeDispatch() throws Exception { UpdateProfileRequest request = new UpdateProfileRequest( - 1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.HIDDEN_STAFF); + 1L, ACCOUNT_UUID, "demo", "bio", ProfilePresenceVisibilityPolicy.HIDDEN_STAFF); String token = jwtUtil.generateToken(ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID)); mockMvc @@ -242,7 +288,7 @@ void updateProfileRejectsReservedHiddenStaffPolicyBeforeDispatch() throws Except void updateProfileRejectsUnauthorizedCallerBeforeReservedPolicyValidation() throws Exception { UpdateProfileRequest request = new UpdateProfileRequest( - 1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.HIDDEN_STAFF); + 1L, ACCOUNT_UUID, "demo", "bio", ProfilePresenceVisibilityPolicy.HIDDEN_STAFF); String token = jwtUtil.generateToken(OTHER_ACCOUNT_UUID, Map.of("accountId", OTHER_ACCOUNT_UUID)); @@ -260,7 +306,8 @@ void updateProfileRejectsUnauthorizedCallerBeforeReservedPolicyValidation() thro @Test void updateProfileRejectsSameTenantAdminForAnotherAccount() throws Exception { UpdateProfileRequest request = - new UpdateProfileRequest(1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); + new UpdateProfileRequest( + 1L, ACCOUNT_UUID, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); String token = jwtUtil.generateToken( OTHER_ACCOUNT_UUID, Map.of("scopedRoles", Map.of("1", List.of("tenantAdmin")))); @@ -279,7 +326,8 @@ void updateProfileRejectsSameTenantAdminForAnotherAccount() throws Exception { @Test void updateProfileRejectsGlobalAdminForAnotherAccount() throws Exception { UpdateProfileRequest request = - new UpdateProfileRequest(1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); + new UpdateProfileRequest( + 1L, ACCOUNT_UUID, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); String token = jwtUtil.generateToken(OTHER_ACCOUNT_UUID, Map.of("globalRoles", List.of("platformAdmin"))); @@ -297,7 +345,8 @@ void updateProfileRejectsGlobalAdminForAnotherAccount() throws Exception { @Test void updateProfileRejectsZeroAccountIdBeforeDispatch() throws Exception { UpdateProfileRequest req = - new UpdateProfileRequest(1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); + new UpdateProfileRequest( + 1L, ACCOUNT_UUID, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); mockMvc @@ -316,7 +365,8 @@ void updateProfileRejectsZeroAccountIdBeforeDispatch() throws Exception { @Test void updateProfileRejectsZeroTenantIdBeforeDispatch() throws Exception { UpdateProfileRequest req = - new UpdateProfileRequest(0L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); + new UpdateProfileRequest( + 0L, ACCOUNT_UUID, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); String token = jwtUtil.generateToken(ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID)); mockMvc 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 1006c493d2..0db10aec79 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 @@ -995,7 +995,7 @@ void getProfileReturnsProfile() throws Exception { Mockito.when(accountService.getProfile(1L, 2L)) .thenReturn( new net.firedevops.firemud.accountservice.dto.ProfileDto( - 1L, 1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE)); + 1L, 1L, ACCOUNT_UUID, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE)); AccountGrpcService service = new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); @@ -1033,6 +1033,13 @@ public void onCompleted() {} .readTree(ref.get().getProfileJson()) .path("presenceVisibilityPolicy") .asText()); + assertEquals( + ACCOUNT_UUID, + tools.jackson.databind.json.JsonMapper.builder() + .build() + .readTree(ref.get().getProfileJson()) + .path("accountId") + .asText()); Mockito.verify(accountService).resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID)); } @@ -1059,6 +1066,36 @@ void getProfileRejectsUnmappedUuidBeforeProfileRead() { Mockito.verify(accountService, Mockito.never()).getProfile(1L, 2L); } + @Test + void getProfileMapsSourceValidationFailuresToSanitizedApplicationErrors() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(2L); + Mockito.when(accountService.getProfile(1L, 2L)) + .thenThrow(new IllegalStateException("private source validation detail")); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + SessionContext.setContext(ACCOUNT_UUID, List.of("player"), Map.of()); + + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.getProfile( + GetProfileRequest.newBuilder().setTenantId("1").setAccountId(ACCOUNT_UUID).build(), + observer)); + + assertEquals(1, observer.responseCount()); + assertEquals("INTERNAL", observer.response().getError().getCode()); + assertEquals("Profile source validation failed", observer.response().getError().getMessage()); + assertEquals("", observer.response().getProfileJson()); + assertTrue(observer.completed()); + assertFalse(observer.receivedTransportError()); + Mockito.verify(accountService).resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID)); + Mockito.verify(accountService).getProfile(1L, 2L); + } + @Test void getProfileRejectsZeroAccountIdBeforeLookup() { PingService pingService = Mockito.mock(PingService.class); @@ -1598,10 +1635,10 @@ void updateProfileAllowsExactSocialPeerWithMatchingSubject() { captor = org.mockito.ArgumentCaptor.forClass( net.firedevops.firemud.accountservice.dto.UpdateProfileRequest.class); - Mockito.verify(accountService).updateProfile(captor.capture()); + Mockito.verify(accountService).updateProfile(Mockito.eq(2L), captor.capture()); Mockito.verify(accountService).resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID)); assertEquals(1L, captor.getValue().tenantId()); - assertEquals(2L, captor.getValue().accountId()); + assertEquals(ACCOUNT_UUID, captor.getValue().accountId()); assertEquals("demo", captor.getValue().displayName()); } @@ -1611,7 +1648,7 @@ void updateProfileMapsServiceRuntimeFailuresToApplicationErrors() { AccountService accountService = Mockito.mock(AccountService.class); Mockito.doThrow(new IllegalArgumentException("bad")) .when(accountService) - .updateProfile(Mockito.any()); + .updateProfile(Mockito.anyLong(), Mockito.any()); AccountGrpcService service = new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); RecordingObserver observer = new RecordingObserver<>(); @@ -1633,7 +1670,43 @@ void updateProfileMapsServiceRuntimeFailuresToApplicationErrors() { assertEquals("INVALID_ARGUMENT", observer.response().getError().getCode()); assertTrue(observer.completed()); - Mockito.verify(accountService).updateProfile(Mockito.any()); + Mockito.verify(accountService).updateProfile(Mockito.anyLong(), Mockito.any()); + } + + @Test + void updateProfileMapsSourceValidationFailuresToSanitizedApplicationErrors() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(2L); + Mockito.doThrow(new IllegalStateException("private source validation detail")) + .when(accountService) + .updateProfile(Mockito.eq(2L), Mockito.any()); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + SessionContext.setContext(ACCOUNT_UUID, List.of("player"), Map.of()); + + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.updateProfile( + UpdateProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId(ACCOUNT_UUID) + .setProfileJson( + "{\"displayName\":\"demo\",\"bio\":\"bio\",\"presenceVisibilityPolicy\":\"PRIVATE\"}") + .build(), + observer)); + + assertEquals(1, observer.responseCount()); + assertFalse(observer.response().getSuccess()); + assertEquals("INTERNAL", observer.response().getError().getCode()); + assertEquals("Profile source validation failed", observer.response().getError().getMessage()); + assertTrue(observer.completed()); + assertFalse(observer.receivedTransportError()); + Mockito.verify(accountService).resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID)); + Mockito.verify(accountService).updateProfile(Mockito.eq(2L), Mockito.any()); } @Test @@ -2515,12 +2588,14 @@ void runtimeOutboxSourceEvidenceRejectsChangedContentOrDigest() { private static final class RecordingObserver implements StreamObserver { private T response; + private int responseCount; private boolean receivedTransportError; private boolean completed; @Override public void onNext(T value) { response = value; + responseCount++; } @Override @@ -2537,6 +2612,10 @@ private T response() { return response; } + private int responseCount() { + return responseCount; + } + private boolean receivedTransportError() { return receivedTransportError; } 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 00101d3c08..768faf2608 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 @@ -7011,21 +7011,61 @@ void getRealmAccessGrantForRuntimeReturnsGrantState() { void getProfileReturnsDto() { Account account = new Account(); account.setId(2L); + setPersistedAuthenticationIdentity(account); Profile profile = new Profile(); profile.setAccount(account); profile.setTenantId(1L); profile.setDisplayName("demo"); profile.setPresenceVisibilityPolicy(ProfilePresenceVisibilityPolicy.FRIENDS_ONLY); + when(accountRepository.findById(2L)).thenReturn(Optional.of(account)); when(accountTenantMembershipRepository.existsByAccountIdAndTenantId(2L, 1L)).thenReturn(true); when(profileRepository.findByAccountIdAndTenantId(2L, 1L)).thenReturn(Optional.of(profile)); - when(profileMapper.toDto(profile)) + when(profileMapper.toDto(profile, account.getAccountUuid().toString())) .thenReturn( new net.firedevops.firemud.accountservice.dto.ProfileDto( - 1L, 1L, 2L, "demo", null, ProfilePresenceVisibilityPolicy.FRIENDS_ONLY)); + 1L, + 1L, + account.getAccountUuid().toString(), + "demo", + null, + ProfilePresenceVisibilityPolicy.FRIENDS_ONLY)); var dto = service.getProfile(1L, 2L); assertEquals("demo", dto.displayName()); + assertEquals(account.getAccountUuid().toString(), dto.accountId()); + } + + @Test + void profileReadsRejectContradictoryExactAccountLookupBeforeReadingProfiles() { + Account contradictoryAccount = new Account(); + contradictoryAccount.setId(3L); + setPersistedAuthenticationIdentity(contradictoryAccount); + when(accountRepository.findById(2L)).thenReturn(Optional.of(contradictoryAccount)); + + assertThrows(IllegalStateException.class, () -> service.getProfile(1L, 2L)); + assertThrows(IllegalStateException.class, () -> service.exportAccountData(2L)); + + verifyNoInteractions(accountTenantMembershipRepository, profileRepository, profileMapper); + } + + @Test + void getProfileRejectsForeignAccountRelationBeforeMapping() { + Account account = new Account(); + account.setId(2L); + setPersistedAuthenticationIdentity(account); + Account foreignAccount = new Account(); + foreignAccount.setId(3L); + Profile profile = new Profile(); + profile.setAccount(foreignAccount); + profile.setTenantId(1L); + when(accountRepository.findById(2L)).thenReturn(Optional.of(account)); + when(accountTenantMembershipRepository.existsByAccountIdAndTenantId(2L, 1L)).thenReturn(true); + when(profileRepository.findByAccountIdAndTenantId(2L, 1L)).thenReturn(Optional.of(profile)); + + assertThrows(IllegalStateException.class, () -> service.getProfile(1L, 2L)); + + verifyNoInteractions(profileMapper); } @Test @@ -7046,31 +7086,72 @@ void listPresenceVisibilityPoliciesOmitsProfilesWithoutAPolicy() { @Test void updateProfileStoresChanges() { + Account account = new Account(); + account.setId(2L); + setPersistedAuthenticationIdentity(account); Profile profile = new Profile(); - profile.setAccount(new Account()); + profile.setAccount(account); profile.setTenantId(1L); profile.setPresenceVisibilityPolicy(ProfilePresenceVisibilityPolicy.FRIENDS_ONLY); + when(accountRepository.findById(2L)).thenReturn(Optional.of(account)); when(accountTenantMembershipRepository.existsByAccountIdAndTenantId(2L, 1L)).thenReturn(true); when(profileRepository.findByAccountIdAndTenantId(2L, 1L)).thenReturn(Optional.of(profile)); when(profileRepository.save(profile)).thenReturn(profile); - when(profileMapper.toDto(profile)) + when(profileMapper.toDto(profile, account.getAccountUuid().toString())) .thenReturn( new net.firedevops.firemud.accountservice.dto.ProfileDto( - 1L, 1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE)); + 1L, + 1L, + account.getAccountUuid().toString(), + "demo", + "bio", + ProfilePresenceVisibilityPolicy.PRIVATE)); var dto = service.updateProfile( + 2L, new net.firedevops.firemud.accountservice.dto.UpdateProfileRequest( - 1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE)); + 1L, + account.getAccountUuid().toString(), + "demo", + "bio", + ProfilePresenceVisibilityPolicy.PRIVATE)); assertEquals("demo", dto.displayName()); + assertEquals(account.getAccountUuid().toString(), dto.accountId()); assertEquals(ProfilePresenceVisibilityPolicy.PRIVATE, profile.getPresenceVisibilityPolicy()); org.mockito.Mockito.verify(notificationService).sendNotification(1L, 2L, "Profile updated"); } + @Test + void updateProfileRejectsMismatchedSourceUuidBeforeMembershipOrProfileAccess() { + Account account = new Account(); + account.setId(2L); + setPersistedAuthenticationIdentity(account); + when(accountRepository.findById(2L)).thenReturn(Optional.of(account)); + var request = + new net.firedevops.firemud.accountservice.dto.UpdateProfileRequest( + 1L, + UUID.randomUUID().toString(), + "demo", + "bio", + ProfilePresenceVisibilityPolicy.PRIVATE); + + assertEquals( + "Profile account identity does not match its source", + assertThrows(IllegalArgumentException.class, () -> service.updateProfile(2L, request)) + .getMessage()); + + verifyNoInteractions(accountTenantMembershipRepository, profileRepository, notificationService); + } + @Test void profileReadAndUpdateFailClosedWithoutCurrentTenantMembership() { when(accountTenantMembershipRepository.existsByAccountIdAndTenantId(2L, 1L)).thenReturn(false); + Account account = new Account(); + account.setId(2L); + setPersistedAuthenticationIdentity(account); + when(accountRepository.findById(2L)).thenReturn(Optional.of(account)); assertEquals( "Profile not found", @@ -7082,8 +7163,13 @@ void profileReadAndUpdateFailClosedWithoutCurrentTenantMembership() { IllegalArgumentException.class, () -> service.updateProfile( + 2L, new net.firedevops.firemud.accountservice.dto.UpdateProfileRequest( - 1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE))) + 1L, + account.getAccountUuid().toString(), + "demo", + "bio", + ProfilePresenceVisibilityPolicy.PRIVATE))) .getMessage()); verifyNoInteractions(profileRepository, profileMapper, notificationService); @@ -7091,12 +7177,20 @@ void profileReadAndUpdateFailClosedWithoutCurrentTenantMembership() { @Test void updateProfileRejectsReservedHiddenStaffPolicyBeforePersistence() { + Account account = new Account(); + account.setId(2L); + setPersistedAuthenticationIdentity(account); + when(accountRepository.findById(2L)).thenReturn(Optional.of(account)); var request = new net.firedevops.firemud.accountservice.dto.UpdateProfileRequest( - 1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.HIDDEN_STAFF); + 1L, + account.getAccountUuid().toString(), + "demo", + "bio", + ProfilePresenceVisibilityPolicy.HIDDEN_STAFF); IllegalArgumentException exception = - assertThrows(IllegalArgumentException.class, () -> service.updateProfile(request)); + assertThrows(IllegalArgumentException.class, () -> service.updateProfile(2L, request)); assertEquals( "Profile presence visibility policy HIDDEN_STAFF is reserved", exception.getMessage()); @@ -7115,19 +7209,49 @@ void exportAccountDataIncludesProfilesAcrossTenants() { Profile tenantTwo = profile(account, 2L, "two"); when(accountRepository.findById(2L)).thenReturn(Optional.of(account)); when(profileRepository.findByAccountId(2L)).thenReturn(java.util.List.of(tenantOne, tenantTwo)); - when(profileMapper.toDto(tenantOne)) + when(profileMapper.toDto(tenantOne, accountUuid.toString())) .thenReturn( new net.firedevops.firemud.accountservice.dto.ProfileDto( - 10L, 1L, 2L, "one", null, ProfilePresenceVisibilityPolicy.FRIENDS_ONLY)); - when(profileMapper.toDto(tenantTwo)) + 10L, + 1L, + accountUuid.toString(), + "one", + null, + ProfilePresenceVisibilityPolicy.FRIENDS_ONLY)); + when(profileMapper.toDto(tenantTwo, accountUuid.toString())) .thenReturn( new net.firedevops.firemud.accountservice.dto.ProfileDto( - 20L, 2L, 2L, "two", null, ProfilePresenceVisibilityPolicy.FRIENDS_ONLY)); + 20L, + 2L, + accountUuid.toString(), + "two", + null, + ProfilePresenceVisibilityPolicy.FRIENDS_ONLY)); var export = service.exportAccountData(2L); assertEquals(accountUuid.toString(), export.account().id()); assertEquals(2, export.profiles().size()); + assertTrue( + export.profiles().stream().allMatch(p -> accountUuid.toString().equals(p.accountId()))); + } + + @Test + void exportAccountDataRejectsProfileFromAnotherAccountBeforeMapping() { + Account account = new Account(); + account.setId(2L); + setPersistedAuthenticationIdentity(account); + Account foreignAccount = new Account(); + foreignAccount.setId(3L); + Profile foreignProfile = new Profile(); + foreignProfile.setAccount(foreignAccount); + foreignProfile.setTenantId(1L); + when(accountRepository.findById(2L)).thenReturn(Optional.of(account)); + when(profileRepository.findByAccountId(2L)).thenReturn(java.util.List.of(foreignProfile)); + + assertThrows(IllegalStateException.class, () -> service.exportAccountData(2L)); + + verifyNoInteractions(profileMapper); } @Test diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapability.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapability.java index beaade5843..441831f9f5 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapability.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapability.java @@ -30,6 +30,7 @@ import java.util.regex.Pattern; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamesession.service.AccountIds; import org.springframework.core.io.ClassPathResource; import tools.jackson.core.JacksonException; import tools.jackson.core.StreamReadFeature; @@ -44,7 +45,7 @@ record RunOwnedInitialAdmissionFixtureCapability( String operationId, long tenantId, long gameTemplateId, - long ownerAccountId, + String ownerAccountId, String worldSlug, String worldDisplayName, String realmSlug, @@ -141,7 +142,7 @@ static RunOwnedInitialAdmissionFixtureCapability parseAndValidate( String operationId = requiredText(root, "operationId"); long tenantId = requiredPositiveLong(root, "tenantId"); long gameTemplateId = requiredPositiveLong(root, "gameTemplateId"); - long ownerAccountId = requiredPositiveLong(root, "ownerAccountId"); + String ownerAccountId = requiredText(root, "ownerAccountId"); String worldSlug = requiredText(root, "worldSlug"); String worldDisplayName = requiredText(root, "worldDisplayName"); String realmSlug = requiredText(root, "realmSlug"); @@ -161,6 +162,7 @@ static RunOwnedInitialAdmissionFixtureCapability parseAndValidate( || !SAFE_ID.matcher(runId).matches() || !SAFE_ID.matcher(composeProjectName).matches() || !isCanonicalUuid(operationId) + || !AccountIds.isCanonicalNonNilUuid(ownerAccountId) || !WORLD_SLUG.equals(worldSlug) || !WORLD_DISPLAY_NAME.equals(worldDisplayName) || !REALM_SLUG.equals(realmSlug) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java index 807932a8cd..4017d70215 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java @@ -240,7 +240,7 @@ private static GameInstanceDto requireExactRunningTarget( || target.gameTemplateId() == null || target.gameTemplateId() != capability.gameTemplateId() || target.ownerAccountId() == null - || target.ownerAccountId() != capability.ownerAccountId() + || !target.ownerAccountId().equals(capability.ownerAccountId()) || target.versionId() == null || target.versionId() <= 0L || target.launchDescriptorId() == null @@ -424,7 +424,7 @@ private static String requestDigest( appendDigestField(canonical, "operationId", capability.operationId()); appendDigestField(canonical, "tenantId", Long.toString(capability.tenantId())); appendDigestField(canonical, "gameTemplateId", Long.toString(capability.gameTemplateId())); - appendDigestField(canonical, "ownerAccountId", Long.toString(capability.ownerAccountId())); + appendDigestField(canonical, "ownerAccountId", capability.ownerAccountId()); appendDigestField(canonical, "worldSlug", capability.worldSlug()); appendDigestField(canonical, "worldDisplayName", capability.worldDisplayName()); appendDigestField(canonical, "realmSlug", capability.realmSlug()); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/TestDataSeeder.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/TestDataSeeder.java index 29f6017fd4..d51ec6b9ef 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/TestDataSeeder.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/TestDataSeeder.java @@ -11,7 +11,10 @@ import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; -/** Seeds deterministic smoke metadata when local compose explicitly enables it. */ +/** + * Seeds demo metadata only; runtime instance ownership remains unavailable without Account UUID + * authority. + */ @Component @ConditionalOnProperty( prefix = "firemud.smoke.seed-demo-runtime", diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/GameInstanceDto.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/GameInstanceDto.java index b2cfbebced..5b6d3ce60a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/GameInstanceDto.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/GameInstanceDto.java @@ -20,7 +20,7 @@ public record GameInstanceDto( Long versionStateEpoch, String generationConfigRevision, String remapSetId, - @NotNull Long ownerAccountId, + String ownerAccountId, @NotNull @Size(max = 20) String status) implements Serializable { private static final long serialVersionUID = 1L; @@ -43,7 +43,7 @@ public GameInstanceDto( Long releaseBundleId, Long versionStateEpoch, String generationConfigRevision, - @NotNull Long ownerAccountId, + String ownerAccountId, @NotNull @Size(max = 20) String status) { this( id, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/StartSessionRequest.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/StartSessionRequest.java index 3df11f620b..e89eff0302 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/StartSessionRequest.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/StartSessionRequest.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.gamesession.dto; +import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Positive; @@ -8,4 +9,4 @@ public record StartSessionRequest( @NotNull @Positive Long tenantId, @NotNull @Positive Long gameTemplateId, @NotNull String controlPlaneRequestId, - @NotNull @Positive Long ownerAccountId) {} + @NotBlank String ownerAccountId) {} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/GameInstance.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/GameInstance.java index ea0d5a26d1..5cf08a6f40 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/GameInstance.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/GameInstance.java @@ -22,7 +22,8 @@ public class GameInstance { private String scriptPatchPinnedBy; private String scriptPatchPinnedReason; private String scriptPatchPinnedControlPlaneRequestId; - private Long ownerAccountId; + private String ownerAccountId; + private Long legacyOwnerAccountId; private String status; private Long rowVersion; private String runOwnedStartRequestId; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/mapper/GameInstanceMapper.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/mapper/GameInstanceMapper.java index 24d939a2ee..42fd0f7861 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/mapper/GameInstanceMapper.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/mapper/GameInstanceMapper.java @@ -19,6 +19,12 @@ public interface GameInstanceMapper { @Mapping(target = "scriptPatchPinnedBy", ignore = true) @Mapping(target = "scriptPatchPinnedReason", ignore = true) @Mapping(target = "scriptPatchPinnedControlPlaneRequestId", ignore = true) + @Mapping(target = "legacyOwnerAccountId", ignore = true) @Mapping(target = "rowVersion", ignore = true) + @Mapping(target = "runOwnedStartRequestId", ignore = true) + @Mapping(target = "runOwnedStartRequestDigest", ignore = true) + @Mapping(target = "runOwnedStartPublishedReleaseBundleRef", ignore = true) + @Mapping(target = "runOwnedStartPreparingEpoch", ignore = true) + @Mapping(target = "runOwnedStartActiveEpoch", ignore = true) GameInstance toEntity(GameInstanceDto dto); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameInstanceRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameInstanceRepository.java index 84907ee1a3..87c810d4ad 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameInstanceRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameInstanceRepository.java @@ -10,11 +10,12 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.time.Instant; -import java.util.Collection; import java.util.List; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.gamesession.entity.GameInstance; import net.firedevops.firemud.gamesession.jooq.tables.records.GameInstancesRecord; +import net.firedevops.firemud.gamesession.service.AccountIds; import net.firedevops.firemud.gamesession.service.RuntimeVersionIdResolver; import net.firedevops.firemud.gamesession.service.ScriptPinTupleCoherence; import org.jooq.DSLContext; @@ -50,6 +51,7 @@ public class GameInstanceRepository { GAME_INSTANCES.SCRIPT_PATCH_PINNED_REASON, GAME_INSTANCES.SCRIPT_PATCH_PINNED_CONTROL_PLANE_REQUEST_ID, GAME_INSTANCES.OWNER_ACCOUNT_ID, + GAME_INSTANCES.OWNER_ACCOUNT_UUID, GAME_INSTANCES.STATUS, GAME_INSTANCES.ROW_VERSION, GAME_INSTANCES.RUN_OWNED_START_REQUEST_ID, @@ -115,49 +117,66 @@ public List findAll() { } public Optional findFirstByTenantIdAndOwnerAccountIdAndStatus( - Long tenantId, Long ownerAccountId, String status) { + Long tenantId, String ownerAccountId, String status) { + UUID ownerAccountUuid = parseCanonicalOwnerAccountId(ownerAccountId); return selectGameInstances() .where( GAME_INSTANCES .TENANT_ID .eq(tenantId) - .and(GAME_INSTANCES.OWNER_ACCOUNT_ID.eq(ownerAccountId)) + .and(GAME_INSTANCES.OWNER_ACCOUNT_UUID.eq(ownerAccountUuid)) .and(GAME_INSTANCES.STATUS.eq(status))) .limit(1) .fetchOptional(this::toEntity); } - public List findByStatus(String status) { + /** + * Reads and locks unresolved owner rows that are active or not known to be inert. + * + *

Callers must invoke this method inside the owner transaction that stages a new runtime. Rows + * without a canonical owner UUID are not matched to the requesting Account; they remain ambiguous + * evidence until a separately authorized reconciliation resolves them. + */ + @Transactional(propagation = Propagation.MANDATORY) + public List findUnresolvedActiveOwnerRowsByTenantIdForUpdate(Long tenantId) { return selectGameInstances() - .where(GAME_INSTANCES.STATUS.eq(status)) + .where( + GAME_INSTANCES + .TENANT_ID + .eq(tenantId) + .and(GAME_INSTANCES.OWNER_ACCOUNT_UUID.isNull()) + .and(GAME_INSTANCES.STATUS.isNull().or(GAME_INSTANCES.STATUS.ne("STOPPED")))) .orderBy(GAME_INSTANCES.ID.asc()) + .forUpdate() .fetch(this::toEntity); } - public List findByTenantIdAndOwnerAccountIdInAndStatus( - Long tenantId, Collection ownerAccountIds, String status) { - if (ownerAccountIds == null || ownerAccountIds.isEmpty()) { - return List.of(); - } + public List findByStatus(String status) { return selectGameInstances() - .where( - GAME_INSTANCES - .TENANT_ID - .eq(tenantId) - .and(GAME_INSTANCES.OWNER_ACCOUNT_ID.in(ownerAccountIds)) - .and(GAME_INSTANCES.STATUS.eq(status))) + .where(GAME_INSTANCES.STATUS.eq(status)) .orderBy(GAME_INSTANCES.ID.asc()) .fetch(this::toEntity); } public GameInstance save(GameInstance entity) { + UUID ownerAccountUuid = + entity.getOwnerAccountId() == null + ? null + : parseCanonicalOwnerAccountId(entity.getOwnerAccountId()); + if (entity.getId() == null && ownerAccountUuid == null) { + throw new IllegalArgumentException( + "New game instances require a canonical ownerAccountId UUID"); + } + if (entity.getId() == null && entity.getLegacyOwnerAccountId() != null) { + throw new IllegalArgumentException("New game instances cannot use a legacy numeric owner"); + } ScriptPinTupleCoherence.requireCoherent( entity.getScriptPatchVersion(), entity.getScriptPinEpoch(), entity.getScriptPatchPinnedControlPlaneRequestId()); if (entity.getId() == null) { GameInstancesRecord record = dsl.newRecord(GAME_INSTANCES); - populate(record, entity); + populate(record, entity, ownerAccountUuid); long initialRowVersion = entity.getRowVersion() == null ? 0L : entity.getRowVersion(); record.setRowVersion(initialRowVersion); record.store(); @@ -188,7 +207,7 @@ public GameInstance save(GameInstance entity) { .set( GAME_INSTANCES.SCRIPT_PATCH_PINNED_CONTROL_PLANE_REQUEST_ID, entity.getScriptPatchPinnedControlPlaneRequestId()) - .set(GAME_INSTANCES.OWNER_ACCOUNT_ID, entity.getOwnerAccountId()) + .set(GAME_INSTANCES.OWNER_ACCOUNT_UUID, ownerAccountUuid) .set(GAME_INSTANCES.STATUS, entity.getStatus()) .set( GAME_INSTANCES.RUN_OWNED_START_PREPARING_EPOCH, @@ -869,7 +888,7 @@ private String normalizePatch(String value) { return isAbsent(value) ? null : value; } - private void populate(GameInstancesRecord record, GameInstance entity) { + private void populate(GameInstancesRecord record, GameInstance entity, UUID ownerAccountUuid) { record.setTenantId(entity.getTenantId()); record.setRuntimeVersion(entity.getRuntimeVersion()); record.setScriptPatchVersion(entity.getScriptPatchVersion()); @@ -887,7 +906,8 @@ private void populate(GameInstancesRecord record, GameInstance entity) { record.setScriptPatchPinnedReason(entity.getScriptPatchPinnedReason()); record.setScriptPatchPinnedControlPlaneRequestId( entity.getScriptPatchPinnedControlPlaneRequestId()); - record.setOwnerAccountId(entity.getOwnerAccountId()); + record.setOwnerAccountId(null); + record.setOwnerAccountUuid(ownerAccountUuid); record.setStatus(entity.getStatus()); record.setRunOwnedStartRequestId(entity.getRunOwnedStartRequestId()); record.setRunOwnedStartRequestDigest(entity.getRunOwnedStartRequestDigest()); @@ -917,7 +937,9 @@ private GameInstance toEntity(Record record) { entity.setScriptPatchPinnedReason(record.get(GAME_INSTANCES.SCRIPT_PATCH_PINNED_REASON)); entity.setScriptPatchPinnedControlPlaneRequestId( record.get(GAME_INSTANCES.SCRIPT_PATCH_PINNED_CONTROL_PLANE_REQUEST_ID)); - entity.setOwnerAccountId(record.get(GAME_INSTANCES.OWNER_ACCOUNT_ID)); + UUID ownerAccountUuid = record.get(GAME_INSTANCES.OWNER_ACCOUNT_UUID); + entity.setOwnerAccountId(ownerAccountUuid == null ? null : ownerAccountUuid.toString()); + entity.setLegacyOwnerAccountId(record.get(GAME_INSTANCES.OWNER_ACCOUNT_ID)); entity.setStatus(record.get(GAME_INSTANCES.STATUS)); entity.setRowVersion(record.get(GAME_INSTANCES.ROW_VERSION)); entity.setRunOwnedStartRequestId(record.get(GAME_INSTANCES.RUN_OWNED_START_REQUEST_ID)); @@ -929,4 +951,11 @@ private GameInstance toEntity(Record record) { entity.setRunOwnedStartActiveEpoch(record.get(GAME_INSTANCES.RUN_OWNED_START_ACTIVE_EPOCH)); return entity; } + + private static UUID parseCanonicalOwnerAccountId(String ownerAccountId) { + if (!AccountIds.isCanonicalNonNilUuid(ownerAccountId)) { + throw new IllegalArgumentException("ownerAccountId must be a canonical non-nil UUID"); + } + return UUID.fromString(ownerAccountId); + } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshot.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshot.java index 3ea095fe83..e1f43edf3a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshot.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshot.java @@ -26,7 +26,7 @@ public record GameSessionRetainedTenantSnapshot( String legacyGameSessionTenantId, String canonicalJson, String evidenceDigest) { - private static final String DIGEST_DOMAIN = "game-session/retained-tenant-identity-snapshot/v1"; + private static final String DIGEST_DOMAIN = "game-session/retained-tenant-identity-snapshot/v2"; private static final Pattern CANONICAL_DECIMAL = Pattern.compile("(?:0|[1-9][0-9]*|-[1-9][0-9]*)"); private static final Pattern CANONICAL_UUID = @@ -57,6 +57,7 @@ public record GameSessionRetainedTenantSnapshot( "runtime_version", "script_patch_version", "owner_account_id", + "owner_account_uuid", "status", "row_version", "game_template_id", @@ -118,6 +119,8 @@ public record GameSessionRetainedTenantSnapshot( "execution_control_plane_request_id"); private static final Set NULLABLE_INSTANCE_FIELDS = Set.of( + "owner_account_id", + "owner_account_uuid", "script_patch_version", "game_template_id", "launch_descriptor_id", @@ -216,8 +219,8 @@ private static void validateCanonicalSnapshot( if (schemaVersion == null || !schemaVersion.isIntegralNumber() || !schemaVersion.canConvertToInt() - || schemaVersion.intValue() != 1) { - throw new IllegalArgumentException("snapshot.schemaVersion must be integer 1"); + || schemaVersion.intValue() != 2) { + throw new IllegalArgumentException("snapshot.schemaVersion must be integer 2"); } requireExactText(object, "targetNamespace", targetNamespace, "snapshot"); requireExactText(object, "legacyGameSessionTenantId", legacyGameSessionTenantId, "snapshot"); @@ -249,7 +252,7 @@ private static void validateCanonicalSnapshot( "version_state_epoch", "script_pin_epoch"), Set.of("row_version"), - Set.of(), + Set.of("owner_account_uuid"), Set.of(), NULLABLE_INSTANCE_FIELDS, "id", @@ -382,6 +385,12 @@ private static void validateRows( throw new IllegalArgumentException(path + " must be strictly sorted by " + sortField); } previousSortValue = sortValue; + if ("instances".equals(path) + && object.get("owner_account_id").isNull() + && object.get("owner_account_uuid").isNull()) { + throw new IllegalArgumentException( + rowPath + " must preserve a raw or canonical owner account identity"); + } } } @@ -465,7 +474,7 @@ private static void requireExactFields(ObjectNode object, Set expected, String field = fields.next(); if (!expected.contains(field)) { throw new IllegalArgumentException( - path + "." + field + " is not declared by schema version 1"); + path + "." + field + " is not declared by schema version 2"); } } for (String field : expected) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotRepository.java index 66c3f11a53..ddb79965aa 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotRepository.java @@ -59,7 +59,7 @@ public GameSessionRetainedTenantSnapshot capture( } ObjectNode envelope = JSON.createObjectNode(); - envelope.put("schemaVersion", 1); + envelope.put("schemaVersion", 2); envelope.put("targetNamespace", targetNamespace); envelope.put("legacyGameSessionTenantId", legacyGameSessionTenantId); envelope.set("instances", readInstances(tenantId)); @@ -116,7 +116,8 @@ private boolean hasBackfillIssue(long tenantId) { private ArrayNode readInstances(long tenantId) { return readRows( - "SELECT id, tenant_id, runtime_version, script_patch_version, owner_account_id, status, " + "SELECT id, tenant_id, runtime_version, script_patch_version, owner_account_id, " + + "owner_account_uuid, status, " + "row_version, game_template_id, launch_descriptor_id, version_id, release_bundle_id, " + "version_state_epoch, generation_config_revision, remap_set_id, " + "script_patch_pinned_control_plane_request_id, script_pin_epoch " @@ -128,7 +129,8 @@ record -> { putLong(row, record, "tenant_id"); putText(row, record, "runtime_version"); putNullableText(row, record, "script_patch_version"); - putLong(row, record, "owner_account_id"); + putNullableLong(row, record, "owner_account_id"); + putUuid(row, record, "owner_account_uuid"); putText(row, record, "status"); putLong(row, record, "row_version"); putNullableLong(row, record, "game_template_id"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java index b090816e15..0bbc6a735c 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java @@ -26,6 +26,7 @@ import net.firedevops.firemud.gamesession.entity.GameInstance; import net.firedevops.firemud.gamesession.mapper.GameInstanceMapper; import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; +import net.firedevops.firemud.gamesession.service.AccountIds; import net.firedevops.firemud.gamesession.service.GameInstanceService; import net.firedevops.firemud.gamesession.service.RunOwnedInitialLaunchResult; import net.firedevops.firemud.gamesession.service.SessionStateService; @@ -150,6 +151,12 @@ public GameInstanceServiceImpl( @Override @Timed(value = "gamesession.start") public GameInstanceDto startSession(StartSessionRequest request, boolean replaceExistingFirst) { + if (request == null) { + throw new IllegalArgumentException("request is required"); + } + if (!AccountIds.isCanonicalNonNilUuid(request.ownerAccountId())) { + throw new IllegalArgumentException("ownerAccountId must be a canonical non-nil UUID"); + } logger.info( "Starting game session for tenant {} template {} controlPlaneRequestId {}", request.tenantId(), @@ -176,7 +183,9 @@ public GameInstanceDto startSession(StartSessionRequest request, boolean replace prepareWorldInstance(stage.startingState(), resolvedLaunchDescriptor, request); sessionStateService.saveState(runtimeState); newStateSaved = true; - GameInstanceDto existingRunningState = stage.existingRunningState(); + GameInstanceSnapshot existingRunningSnapshot = stage.existingRunningState(); + GameInstanceDto existingRunningState = + existingRunningSnapshot == null ? null : existingRunningSnapshot.dto(); if (existingRunningState != null) { sessionStateService.deleteState(existingRunningState.tenantId(), existingRunningState.id()); WorldInstanceLifecycleSnapshot existingLifecycle = @@ -268,7 +277,7 @@ public RunOwnedInitialLaunchResult startRunOwnedInitialLaunch(StartSessionReques throw runOwnedWorldStatusFailure(current.getStatus()); } requireRunOwnedActiveEpoch(current, activeEpoch); - sessionStateService.saveState(withStatus(snapshot(reserved), STATUS_RUNNING)); + sessionStateService.saveState(withStatus(snapshot(reserved).dto(), STATUS_RUNNING)); GameInstance completed = inTransaction( () -> @@ -279,7 +288,7 @@ public RunOwnedInitialLaunchResult startRunOwnedInitialLaunch(StartSessionReques gameInstanceId, activeEpoch), "complete run-owned initial launch retry"); - return new RunOwnedInitialLaunchResult(snapshot(completed), activeEpoch); + return new RunOwnedInitialLaunchResult(snapshot(completed).dto(), activeEpoch); } validateStartDependencies(); @@ -324,7 +333,7 @@ public RunOwnedInitialLaunchResult startRunOwnedInitialLaunch(StartSessionReques "WORLD_LIFECYCLE_EPOCH_MISMATCH: PREPARING epoch differs from the durable launch fence"); } if (STATUS_STARTING.equals(reserved.getStatus())) { - sessionStateService.saveState(withStatus(snapshot(reserved), STATUS_STARTING)); + sessionStateService.saveState(withStatus(snapshot(reserved).dto(), STATUS_STARTING)); } activateAndReadBackRunOwnedWorld( reserved, request, resolvedLaunchDescriptor, preparingEpoch, activeEpoch); @@ -342,7 +351,7 @@ public RunOwnedInitialLaunchResult startRunOwnedInitialLaunch(StartSessionReques throw runOwnedWorldStatusFailure(current.getStatus()); } - GameInstanceDto runningState = withStatus(snapshot(reserved), STATUS_RUNNING); + GameInstanceDto runningState = withStatus(snapshot(reserved).dto(), STATUS_RUNNING); sessionStateService.saveState(runningState); GameInstance completed = inTransaction( @@ -350,13 +359,15 @@ public RunOwnedInitialLaunchResult startRunOwnedInitialLaunch(StartSessionReques completeRunOwnedInitialLaunch( request, requestDigest, resolvedLaunchDescriptor, gameInstanceId, activeEpoch), "complete run-owned initial launch"); - return new RunOwnedInitialLaunchResult(snapshot(completed), activeEpoch); + return new RunOwnedInitialLaunchResult(snapshot(completed).dto(), activeEpoch); } @Override @Timed(value = "gamesession.stop") public GameInstanceDto stopSession(long sessionId) { - GameInstanceDto runningState = inTransaction(() -> stageStopSession(sessionId), "stage stop"); + GameInstanceSnapshot runningSnapshot = + inTransaction(() -> stageStopSession(sessionId), "stage stop"); + GameInstanceDto runningState = runningSnapshot.dto(); boolean worldTerminationRequested = false; boolean worldTerminationCompleted = false; try { @@ -384,7 +395,7 @@ public GameInstanceDto stopSession(long sessionId) { } return inTransaction(() -> finalizeStoppedSession(sessionId), "finalize stop"); } catch (RuntimeException ex) { - compensateStopFailure(runningState, worldTerminationRequested, worldTerminationCompleted); + compensateStopFailure(runningSnapshot, worldTerminationRequested, worldTerminationCompleted); throw ex; } } @@ -392,8 +403,9 @@ public GameInstanceDto stopSession(long sessionId) { @Override @Timed(value = "gamesession.restart") public GameInstanceDto restartSession(long sessionId) { - GameInstanceDto previousState = + GameInstanceSnapshot previousSnapshot = inTransaction(() -> stageRestartSession(sessionId), "stage restart"); + GameInstanceDto previousState = previousSnapshot.dto(); GameInstanceDto runtimeState = withStatus(previousState, STATUS_RUNNING); boolean stateSaved = false; try { @@ -401,7 +413,7 @@ public GameInstanceDto restartSession(long sessionId) { stateSaved = true; return inTransaction(() -> finalizeRestartedSession(sessionId), "finalize restart"); } catch (RuntimeException ex) { - compensateRestartFailure(previousState, stateSaved); + compensateRestartFailure(previousSnapshot, stateSaved); throw ex; } } @@ -410,7 +422,15 @@ private StartSessionStage stageStartSession( StartSessionRequest request, ResolvedLaunchDescriptor resolvedLaunchDescriptor, boolean replaceExistingFirst) { - GameInstanceDto existingRunningState = null; + if (!repository + .findUnresolvedActiveOwnerRowsByTenantIdForUpdate(request.tenantId()) + .isEmpty()) { + throw new LifecycleOutcomeException( + "OWNER_ACCOUNT_IDENTITY_UNAVAILABLE", + "cannot start a session while tenant owner identity evidence is active or uncertain"); + } + + GameInstanceSnapshot existingRunningState = null; if (replaceExistingFirst) { existingRunningState = repository @@ -421,7 +441,7 @@ private StartSessionStage stageStartSession( if (existingRunningState != null) { GameInstance existingRunning = repository - .findById(existingRunningState.id()) + .findById(existingRunningState.dto().id()) .orElseThrow(() -> new IllegalArgumentException("Session not found")); existingRunning.setStatus(STATUS_STOPPING); repository.save(existingRunning); @@ -442,7 +462,7 @@ private StartSessionStage stageStartSession( instance.setRemapSetId(resolvedLaunchDescriptor.remapSetId()); instance.setOwnerAccountId(request.ownerAccountId()); instance.setStatus(STATUS_STARTING); - return new StartSessionStage(snapshot(repository.save(instance)), existingRunningState); + return new StartSessionStage(snapshot(repository.save(instance)).dto(), existingRunningState); } private GameInstanceDto finalizeStartedSession(StartSessionStage stage) { @@ -463,12 +483,12 @@ private void markSessionStopped(long sessionId) { repository.save(existingRunning); } - private GameInstanceDto stageStopSession(long sessionId) { + private GameInstanceSnapshot stageStopSession(long sessionId) { GameInstance instance = repository .findById(sessionId) .orElseThrow(() -> new IllegalArgumentException("Session not found")); - GameInstanceDto runningState = snapshot(instance); + GameInstanceSnapshot runningState = snapshot(instance); instance.setStatus(STATUS_STOPPING); repository.save(instance); return runningState; @@ -483,12 +503,17 @@ private GameInstanceDto finalizeStoppedSession(long sessionId) { return mapper.toDto(repository.save(instance)); } - private GameInstanceDto stageRestartSession(long sessionId) { + private GameInstanceSnapshot stageRestartSession(long sessionId) { GameInstance instance = repository .findById(sessionId) .orElseThrow(() -> new IllegalArgumentException("Session not found")); - GameInstanceDto previousState = snapshot(instance); + if (!AccountIds.isCanonicalNonNilUuid(instance.getOwnerAccountId())) { + throw new LifecycleOutcomeException( + "OWNER_ACCOUNT_IDENTITY_UNAVAILABLE", + "cannot restart an instance without a canonical owner Account UUID"); + } + GameInstanceSnapshot previousState = snapshot(instance); instance.setStatus(STATUS_STARTING); repository.save(instance); return previousState; @@ -534,7 +559,9 @@ private void compensateStartFailure( "delete failed started session state", () -> sessionStateService.deleteState(runtimeState.tenantId(), runtimeState.id())); } - GameInstanceDto existingRunningState = stage.existingRunningState(); + GameInstanceSnapshot existingRunningSnapshot = stage.existingRunningState(); + GameInstanceDto existingRunningState = + existingRunningSnapshot == null ? null : existingRunningSnapshot.dto(); if (existingRunningState != null && !oldWorldTerminationRequested) { runRollbackSafely( "restore replaced session runtime state", @@ -548,7 +575,7 @@ private void compensateStartFailure( repository .findById(existingRunningState.id()) .orElseThrow(() -> new IllegalArgumentException("Session not found")); - restoreSessionSnapshot(existingRunning, existingRunningState); + restoreSessionSnapshot(existingRunning, existingRunningSnapshot); return null; }, "restore replaced session row")); @@ -618,9 +645,10 @@ private void compensateStartFailure( } private void compensateStopFailure( - GameInstanceDto runningState, + GameInstanceSnapshot runningSnapshot, boolean worldTerminationRequested, boolean worldTerminationCompleted) { + GameInstanceDto runningState = runningSnapshot.dto(); if (worldTerminationCompleted) { runRollbackSafely( "finalize terminated session row", @@ -644,7 +672,7 @@ private void compensateStopFailure( repository .findById(runningState.id()) .orElseThrow(() -> new IllegalArgumentException("Session not found")); - restoreSessionSnapshot(instance, runningState); + restoreSessionSnapshot(instance, runningSnapshot); return null; }, "restore stopping session row")); @@ -655,7 +683,8 @@ private void compensateStopFailure( } } - private void compensateRestartFailure(GameInstanceDto previousState, boolean stateSaved) { + private void compensateRestartFailure(GameInstanceSnapshot previousSnapshot, boolean stateSaved) { + GameInstanceDto previousState = previousSnapshot.dto(); if (stateSaved) { runRollbackSafely( "delete restarted session state", @@ -670,13 +699,17 @@ private void compensateRestartFailure(GameInstanceDto previousState, boolean sta repository .findById(previousState.id()) .orElseThrow(() -> new IllegalArgumentException("Session not found")); - restoreSessionSnapshot(instance, previousState); + restoreSessionSnapshot(instance, previousSnapshot); return null; }, "restore restarted session row")); } - private GameInstanceDto snapshot(GameInstance instance) { + private GameInstanceSnapshot snapshot(GameInstance instance) { + return new GameInstanceSnapshot(snapshotDto(instance), instance.getLegacyOwnerAccountId()); + } + + private GameInstanceDto snapshotDto(GameInstance instance) { return new GameInstanceDto( instance.getId(), instance.getTenantId(), @@ -696,7 +729,9 @@ private GameInstanceDto snapshot(GameInstance instance) { instance.getStatus()); } - private void restoreSessionSnapshot(GameInstance instance, GameInstanceDto snapshot) { + private void restoreSessionSnapshot( + GameInstance instance, GameInstanceSnapshot internalSnapshot) { + GameInstanceDto snapshot = internalSnapshot.dto(); instance.setStatus(snapshot.status()); instance.setRuntimeVersion(snapshot.runtimeVersion()); instance.setScriptPatchVersion(snapshot.scriptPatchVersion()); @@ -711,6 +746,7 @@ private void restoreSessionSnapshot(GameInstance instance, GameInstanceDto snaps instance.setGenerationConfigRevision(snapshot.generationConfigRevision()); instance.setRemapSetId(snapshot.remapSetId()); instance.setOwnerAccountId(snapshot.ownerAccountId()); + instance.setLegacyOwnerAccountId(internalSnapshot.legacyOwnerAccountId()); instance.setTenantId(snapshot.tenantId()); repository.save(instance); } @@ -721,7 +757,9 @@ private void validateRunOwnedLaunchRequest(StartSessionRequest request) { } RequestIdValidation.requirePositiveLong(request.tenantId(), "tenantId"); RequestIdValidation.requirePositiveLong(request.gameTemplateId(), "gameTemplateId"); - RequestIdValidation.requirePositiveLong(request.ownerAccountId(), "ownerAccountId"); + if (!AccountIds.isCanonicalNonNilUuid(request.ownerAccountId())) { + throw new IllegalArgumentException("ownerAccountId must be a canonical non-nil UUID"); + } if (request.controlPlaneRequestId() == null || request.controlPlaneRequestId().isBlank() || request.controlPlaneRequestId().length() > 128) { @@ -736,7 +774,7 @@ private static String runOwnedLaunchRequestDigest(StartSessionRequest request) { appendDigestField(preimage, "tenantId", Long.toString(request.tenantId())); appendDigestField(preimage, "gameTemplateId", Long.toString(request.gameTemplateId())); appendDigestField(preimage, "controlPlaneRequestId", request.controlPlaneRequestId()); - appendDigestField(preimage, "ownerAccountId", Long.toString(request.ownerAccountId())); + appendDigestField(preimage, "ownerAccountId", request.ownerAccountId()); appendDigestField(preimage, "replaceExistingFirst", "false"); try { return HexFormat.of() @@ -795,6 +833,13 @@ private GameInstance reserveRunOwnedInitialLaunch( requireSameRunOwnedInitialLaunch(existing.get(), request, descriptor, requestDigest); return existing.get(); } + if (!repository + .findUnresolvedActiveOwnerRowsByTenantIdForUpdate(request.tenantId()) + .isEmpty()) { + throw new LifecycleOutcomeException( + "OWNER_ACCOUNT_IDENTITY_UNAVAILABLE", + "cannot start a session while tenant owner identity evidence is active or uncertain"); + } GameInstance instance = new GameInstance(); instance.setTenantId(request.tenantId()); @@ -1590,8 +1635,10 @@ private String releaseBundleRef(long tenantId, long versionId, long releaseBundl return "prb:" + tenantId + ":" + versionId + ":" + releaseBundleId; } + private record GameInstanceSnapshot(GameInstanceDto dto, @Nullable Long legacyOwnerAccountId) {} + private record StartSessionStage( - GameInstanceDto startingState, @Nullable GameInstanceDto existingRunningState) {} + GameInstanceDto startingState, @Nullable GameInstanceSnapshot existingRunningState) {} private record PreparedWorldInstance(long tenantId, long gameInstanceId, long lifecycleEpoch) {} } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java index a337669398..20d52a312e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java @@ -17,6 +17,7 @@ import net.firedevops.firemud.gamesession.dto.StartSessionRequest; import net.firedevops.firemud.gamesession.entity.GameInstance; import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; +import net.firedevops.firemud.gamesession.service.AccountIds; import net.firedevops.firemud.gamesession.service.AccountPresenceQueryService; import net.firedevops.firemud.gamesession.service.FeatureFlagService; import net.firedevops.firemud.gamesession.service.GameInstanceService; @@ -74,6 +75,8 @@ public final class GameSessionGrpcService extends GameSessionServiceGrpc.GameSessionServiceImplBase { private static final Logger LOG = LoggerFactory.getLogger(GameSessionGrpcService.class); + private static final String SESSION_REPLACEMENT_UNAVAILABLE_MESSAGE = + "Replacing an active session is not supported"; private final PingService pingService; private final GameInstanceService gameInstanceService; private final FeatureFlagService featureFlagService; @@ -140,7 +143,7 @@ public void startSession( String clientIp = request.getClientIp(); long tenantId = ControlPlaneRequestParser.parsePositiveLong(request.getTenantId(), "tenantId"); - long ownerAccountId = parseOwnerAccountId(request.getOwnerAccountId()); + String ownerAccountId = parseOwnerAccountUuid(request.getOwnerAccountId()); long gameTemplateId = ControlPlaneRequestParser.parsePositiveLong( request.getGameTemplateId(), "gameTemplateId"); @@ -149,10 +152,22 @@ public void startSession( gameInstanceRepository .findFirstByTenantIdAndOwnerAccountIdAndStatus(tenantId, ownerAccountId, "RUNNING") .orElse(null); + if (existingRunningSession != null) { + StartSessionResponse response = + StartSessionResponse.newBuilder() + .setError( + GrpcAppErrors.error( + meterRegistry, + "SESSION_REPLACEMENT_UNAVAILABLE", + SESSION_REPLACEMENT_UNAVAILABLE_MESSAGE)) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); + return; + } if (clientIp != null && !clientIp.isBlank() - && !ipConnectionLimiter.canAccept( - clientIp, existingRunningSession != null ? existingRunningSession.getId() : null)) { + && !ipConnectionLimiter.canAccept(clientIp, null)) { StartSessionResponse response = StartSessionResponse.newBuilder() .setError( @@ -167,13 +182,8 @@ public void startSession( new StartSessionRequest( tenantId, gameTemplateId, request.getControlPlaneRequestId(), ownerAccountId); GameInstanceDto instance = gameInstanceService.startSession(dto, false); - boolean transferredRegistration = false; if (clientIp != null && !clientIp.isBlank()) { - transferredRegistration = - existingRunningSession != null - && ipConnectionLimiter.transferRegistration( - clientIp, existingRunningSession.getId(), instance.id()); - if (!transferredRegistration && !ipConnectionLimiter.tryRegister(clientIp, instance.id())) { + if (!ipConnectionLimiter.tryRegister(clientIp, instance.id())) { gameInstanceService.stopSession(instance.id()); StartSessionResponse response = StartSessionResponse.newBuilder() @@ -186,20 +196,6 @@ public void startSession( return; } } - if (existingRunningSession != null) { - if (!transferredRegistration) { - ipConnectionLimiter.release(existingRunningSession.getId()); - } - try { - gameInstanceService.stopSession(existingRunningSession.getId()); - } catch (IllegalStateException ex) { - LOG.warn( - "Replacement session {} admitted, but teardown of previous session {} failed", - instance.id(), - existingRunningSession.getId(), - ex); - } - } StartSessionResponse response = StartSessionResponse.newBuilder().setSessionId(instance.id().toString()).build(); responseObserver.onNext(response); @@ -231,8 +227,11 @@ public void startSession( } } - private long parseOwnerAccountId(String ownerAccountIdText) { - return ControlPlaneRequestParser.parsePositiveLong(ownerAccountIdText, "ownerAccountId"); + private String parseOwnerAccountUuid(String ownerAccountId) { + if (!AccountIds.isCanonicalNonNilUuid(ownerAccountId)) { + throw new IllegalArgumentException("ownerAccountId must be a canonical non-nil UUID"); + } + return ownerAccountId; } private List parseAccountIds(List accountIds) { @@ -241,7 +240,7 @@ private List parseAccountIds(List accountIds) { .toList(); } - private void requireTenantAndOwnerAccess(long tenantId, long ownerAccountId) { + private void requireTenantAndOwnerAccess(long tenantId, String ownerAccountId) { requireTenantAccess(tenantId); if (isCurrentAccount(ownerAccountId)) { return; @@ -440,7 +439,9 @@ public void queryAccountPresence( try { long tenantId = ControlPlaneRequestParser.parsePositiveLong(request.getTenantId(), "tenantId"); - long viewerAccountId = parseOwnerAccountId(request.getViewerAccountId()); + long viewerAccountId = + ControlPlaneRequestParser.parsePositiveLong( + request.getViewerAccountId(), "viewerAccountId"); requireTenantOrCurrentAccountAccess(tenantId, viewerAccountId); if (request.getAccountIdsCount() > 100) { throw new IllegalArgumentException("accountIds must contain at most 100 entries"); @@ -890,6 +891,13 @@ private boolean isCurrentAccount(GameInstance instance) { return isCurrentAccount(instance.getOwnerAccountId()); } + private boolean isCurrentAccount(String ownerAccountId) { + String currentAccountId = SessionContext.getAccountId(); + return AccountIds.isCanonicalNonNilUuid(ownerAccountId) + && AccountIds.isCanonicalNonNilUuid(currentAccountId) + && ownerAccountId.equals(currentAccountId); + } + private boolean isCurrentAccount(long ownerAccountId) { return SessionContext.isCurrentAccount(ownerAccountId); } diff --git a/services/game-session-service/src/main/resources/db/migration/V10.1__game_instance_owner_account_uuid.sql b/services/game-session-service/src/main/resources/db/migration/V10.1__game_instance_owner_account_uuid.sql new file mode 100644 index 0000000000..4e09f499bf --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V10.1__game_instance_owner_account_uuid.sql @@ -0,0 +1,20 @@ +-- Retain historical numeric owner keys exactly; no Account UUID reverse mapping is available. +ALTER TABLE game_instances + ALTER COLUMN owner_account_id DROP NOT NULL; + +ALTER TABLE game_instances + ADD COLUMN owner_account_uuid uuid; + +ALTER TABLE game_instances + ADD CONSTRAINT game_instances_owner_identity_present_and_valid + CHECK ( + (owner_account_id IS NOT NULL OR owner_account_uuid IS NOT NULL) + AND ( + owner_account_uuid IS NULL + OR owner_account_uuid <> '00000000-0000-0000-0000-000000000000'::uuid + ) + ); + +CREATE UNIQUE INDEX uq_game_instances_running_tenant_owner_uuid + ON game_instances (tenant_id, owner_account_uuid) + WHERE status = 'RUNNING' AND owner_account_uuid IS NOT NULL; diff --git a/services/game-session-service/src/main/resources/openapi.yaml b/services/game-session-service/src/main/resources/openapi.yaml index db419a6961..0ca9610841 100644 --- a/services/game-session-service/src/main/resources/openapi.yaml +++ b/services/game-session-service/src/main/resources/openapi.yaml @@ -27,7 +27,8 @@ components: controlPlaneRequestId: type: string ownerAccountId: - type: integer + type: string + format: uuid clientIp: type: string required: @@ -57,7 +58,8 @@ components: generationConfigRevision: type: string ownerAccountId: - type: integer + type: [string, 'null'] + format: uuid status: type: string ResultStatus: diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java index 5d27ddca8a..7dc13bd70a 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java @@ -206,7 +206,8 @@ void startSessionUsesRealHttpAndPersistencePath() throws Exception { .WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE) .build()) .build()); - StartSessionRequest request = new StartSessionRequest(42L, 7L, "cp-1", 100L); + StartSessionRequest request = + new StartSessionRequest(42L, 7L, "cp-1", "123e4567-e89b-12d3-a456-426614174000"); String responseBody = HttpTestSupport.postJsonBodyUnchecked( @@ -245,7 +246,7 @@ void startSessionUsesRealHttpAndPersistencePath() throws Exception { assertThat(body.data().releaseBundleId()).isEqualTo(77L); assertThat(body.data().versionStateEpoch()).isEqualTo(77L); assertThat(body.data().generationConfigRevision()).isEqualTo("genrev-11"); - assertThat(body.data().ownerAccountId()).isEqualTo(100L); + assertThat(body.data().ownerAccountId()).isEqualTo("123e4567-e89b-12d3-a456-426614174000"); assertThat(body.data().status()).isEqualTo("RUNNING"); assertThat(body.data().id()).isPositive(); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java index 39b104b419..52dcd33fed 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java @@ -49,6 +49,7 @@ }) @Import({NoGrpcServerTestConfiguration.class, InMemorySessionContextTestConfiguration.class}) class GameSessionLoginIntegrationTest { + private static final String OWNER_ACCOUNT_UUID = "123e4567-e89b-12d3-a456-426614174000"; @LocalServerPort private int port; @MockitoBean private AccountClient accountClient; @@ -106,7 +107,7 @@ void setUp() { GameInstance instance = new GameInstance(); instance.setId(1L); instance.setTenantId(42L); - instance.setOwnerAccountId(7L); + instance.setOwnerAccountId(OWNER_ACCOUNT_UUID); when(gameInstanceRepository.findById(anyLong())).thenReturn(Optional.of(instance)); when(gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(42L, 1L)) .thenReturn( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/controller/GameInstanceControllerTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/controller/GameInstanceControllerTest.java index d918a26b11..e617ae2c6c 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/controller/GameInstanceControllerTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/controller/GameInstanceControllerTest.java @@ -46,13 +46,25 @@ class GameInstanceControllerTest { void startSessionReturnsDto() throws Exception { GameInstanceDto dto = new GameInstanceDto( - 1L, 1L, "11", null, 7L, "ld-1", 11L, 77L, 77L, "genrev-11", 1L, "RUNNING"); + 1L, + 1L, + "11", + null, + 7L, + "ld-1", + 11L, + 77L, + 77L, + "genrev-11", + "123e4567-e89b-12d3-a456-426614174000", + "RUNNING"); org.mockito.Mockito.when( gameInstanceService.startSession( org.mockito.ArgumentMatchers.any(StartSessionRequest.class), org.mockito.ArgumentMatchers.eq(false))) .thenReturn(dto); - StartSessionRequest request = new StartSessionRequest(1L, 7L, "cp-1", 1L); + StartSessionRequest request = + new StartSessionRequest(1L, 7L, "cp-1", "123e4567-e89b-12d3-a456-426614174000"); mockMvc .perform( post("/sessions") @@ -69,7 +81,18 @@ void startSessionReturnsDto() throws Exception { void stopSessionReturnsDto() throws Exception { GameInstanceDto dto = new GameInstanceDto( - 1L, 1L, "11", null, 7L, "ld-1", 11L, 77L, 77L, "genrev-11", 1L, "STOPPED"); + 1L, + 1L, + "11", + null, + 7L, + "ld-1", + 11L, + 77L, + 77L, + "genrev-11", + "123e4567-e89b-12d3-a456-426614174000", + "STOPPED"); org.mockito.Mockito.when(gameInstanceService.stopSession(1L)).thenReturn(dto); mockMvc .perform( @@ -85,7 +108,18 @@ void stopSessionReturnsDto() throws Exception { void restartSessionReturnsDto() throws Exception { GameInstanceDto dto = new GameInstanceDto( - 1L, 1L, "11", null, 7L, "ld-1", 11L, 77L, 77L, "genrev-11", 1L, "RUNNING"); + 1L, + 1L, + "11", + null, + 7L, + "ld-1", + 11L, + 77L, + 77L, + "genrev-11", + "123e4567-e89b-12d3-a456-426614174000", + "RUNNING"); org.mockito.Mockito.when(gameInstanceService.restartSession(1L)).thenReturn(dto); mockMvc .perform( @@ -99,7 +133,8 @@ void restartSessionReturnsDto() throws Exception { @Test void startSessionRejectsScopedTenantAdmin() throws Exception { - StartSessionRequest request = new StartSessionRequest(1L, 7L, "cp-1", 1L); + StartSessionRequest request = + new StartSessionRequest(1L, 7L, "cp-1", "123e4567-e89b-12d3-a456-426614174000"); String token = jwtUtil.generateToken("user", Map.of("scopedRoles", Map.of("1", List.of("tenantAdmin")))); @@ -113,8 +148,8 @@ void startSessionRejectsScopedTenantAdmin() throws Exception { } @Test - void startSessionRejectsZeroOwnerAccountIdBeforeDispatch() throws Exception { - StartSessionRequest request = new StartSessionRequest(1L, 7L, "cp-1", 0L); + void startSessionRejectsBlankOwnerAccountIdBeforeDispatch() throws Exception { + StartSessionRequest request = new StartSessionRequest(1L, 7L, "cp-1", ""); mockMvc .perform( @@ -126,7 +161,7 @@ void startSessionRejectsZeroOwnerAccountIdBeforeDispatch() throws Exception { "Bearer " + PlatformAdminJwtTestSupport.privilegedToken(jwtUtil))) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.error.code").value("INVALID_ARGUMENT")) - .andExpect(jsonPath("$.error.message").value("ownerAccountId must be positive")); + .andExpect(jsonPath("$.error.message").value("ownerAccountId must not be blank")); verifyNoInteractions(gameInstanceService); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameInstanceOwnerUuidMigrationIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameInstanceOwnerUuidMigrationIntegrationTest.java new file mode 100644 index 0000000000..6e66caa4a8 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameInstanceOwnerUuidMigrationIntegrationTest.java @@ -0,0 +1,212 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.file.Path; +import java.sql.Connection; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.gamesession.entity.GameInstance; +import net.firedevops.firemud.gamesession.mapper.GameInstanceMapper; +import net.firedevops.firemud.gamesession.mapper.GameInstanceMapperImpl; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +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.Testcontainers; + +@SuppressWarnings("resource") +@Testcontainers(disabledWithoutDocker = true) +class GameInstanceOwnerUuidMigrationIntegrationTest { + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + private static final long LEGACY_OWNER_ACCOUNT_ID = 9_007_199_254_740_993L; + private static final String OWNER_ACCOUNT_UUID = "123e4567-e89b-12d3-a456-426614174000"; + + @Test + void migrationPreservesNumericHistoryAndStoresCanonicalOwnerUuid() { + try (PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine")) { + postgres.start(); + DriverManagerDataSource dataSource = dataSource(postgres); + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION) + .target(MigrationVersion.fromVersion("10")) + .load() + .migrate(); + + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + dsl.execute( + "INSERT INTO game_instances (id, tenant_id, runtime_version, owner_account_id, status) " + + "VALUES (7001, 77, '1.0.0', ?, 'RUNNING')", + LEGACY_OWNER_ACCOUNT_ID); + String legacyRowBeforeMigration = + dsl.resultQuery( + "SELECT to_jsonb(game_instance)::text FROM game_instances AS game_instance " + + "WHERE id = 7001") + .fetchOne(0, String.class); + + Flyway.configure().dataSource(dataSource).locations(MIGRATION_LOCATION).load().migrate(); + + String legacyRowAfterMigration = + dsl.resultQuery( + "SELECT (to_jsonb(game_instance) - 'owner_account_uuid')::text " + + "FROM game_instances AS game_instance WHERE id = 7001") + .fetchOne(0, String.class); + assertThat(legacyRowAfterMigration).isEqualTo(legacyRowBeforeMigration); + Record legacyStorage = + dsl.fetchOne( + "SELECT owner_account_id, owner_account_uuid FROM game_instances WHERE id = 7001"); + assertThat(legacyStorage.get("owner_account_id", Long.class)) + .isEqualTo(LEGACY_OWNER_ACCOUNT_ID); + assertThat(legacyStorage.get("owner_account_uuid", UUID.class)).isNull(); + + GameInstanceRepository repository = new GameInstanceRepository(dsl); + GameInstanceMapper mapper = new GameInstanceMapperImpl(); + var retained = repository.findById(7001L).orElseThrow(); + assertThat(retained.getOwnerAccountId()).isNull(); + assertThat(retained.getLegacyOwnerAccountId()).isEqualTo(LEGACY_OWNER_ACCOUNT_ID); + assertThat(mapper.toDto(retained).ownerAccountId()).isNull(); + + retained.setStatus("STOPPED"); + repository.save(retained); + assertThat( + dsl.resultQuery("SELECT owner_account_id FROM game_instances WHERE id = 7001") + .fetchOne(0, Long.class)) + .isEqualTo(LEGACY_OWNER_ACCOUNT_ID); + + GameInstance uuidOwned = new GameInstance(); + uuidOwned.setTenantId(77L); + uuidOwned.setRuntimeVersion("1.0.0"); + uuidOwned.setStatus("RUNNING"); + uuidOwned.setOwnerAccountId(OWNER_ACCOUNT_UUID); + GameInstance saved = repository.save(uuidOwned); + Record uuidStorage = + dsl.fetchOne( + "SELECT owner_account_id, owner_account_uuid FROM game_instances WHERE id = ?", + saved.getId()); + assertThat(uuidStorage.get("owner_account_id", Long.class)).isNull(); + assertThat(uuidStorage.get("owner_account_uuid", UUID.class)) + .isEqualTo(UUID.fromString(OWNER_ACCOUNT_UUID)); + assertThat(repository.findById(saved.getId()).orElseThrow().getOwnerAccountId()) + .isEqualTo(OWNER_ACCOUNT_UUID); + + assertThatThrownBy( + () -> { + GameInstance duplicate = new GameInstance(); + duplicate.setTenantId(77L); + duplicate.setRuntimeVersion("1.0.0"); + duplicate.setStatus("RUNNING"); + duplicate.setOwnerAccountId(OWNER_ACCOUNT_UUID); + repository.save(duplicate); + }) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("uq_game_instances_running_tenant_owner_uuid"); + + assertThat(dsl.fetch("SELECT indexname FROM pg_indexes WHERE tablename = 'game_instances'")) + .extracting(row -> row.get("indexname", String.class)) + .contains( + "uq_game_instances_running_tenant_owner", + "uq_game_instances_running_tenant_owner_uuid"); + + assertThatThrownBy( + () -> + dsl.execute( + "INSERT INTO game_instances (id, tenant_id, runtime_version, " + + "owner_account_uuid, status) VALUES " + + "(7002, 77, '1.0.0', '00000000-0000-0000-0000-000000000000', " + + "'STOPPED')")) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("game_instances_owner_identity_present_and_valid"); + } + } + + @Test + void unresolvedOwnerQueryLocksActiveAndUncertainRowsAndPreservesNumericEvidence() + throws Exception { + try (PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine")) { + postgres.start(); + DriverManagerDataSource dataSource = dataSource(postgres); + Flyway.configure().dataSource(dataSource).locations(MIGRATION_LOCATION).load().migrate(); + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + long[] instanceIds = {7103L, 7101L, 7105L, 7104L, 7102L}; + String[] statuses = {"STOPPING", "RUNNING", "STOPPED", "UNRECOGNIZED", "STARTING"}; + for (int index = 0; index < instanceIds.length; index++) { + dsl.execute( + "INSERT INTO game_instances (id, tenant_id, runtime_version, owner_account_id, " + + "status) VALUES (?, 77, '1.0.0', ?, ?)", + instanceIds[index], + LEGACY_OWNER_ACCOUNT_ID + index + 1, + statuses[index]); + } + + List unresolved = + dsl.transactionResult( + configuration -> + new GameInstanceRepository(DSL.using(configuration)) + .findUnresolvedActiveOwnerRowsByTenantIdForUpdate(77L)); + assertThat(unresolved) + .extracting(GameInstance::getId) + .containsExactly(7101L, 7102L, 7103L, 7104L); + assertThat(unresolved) + .allSatisfy(instance -> assertThat(instance.getOwnerAccountId()).isNull()); + assertThat(unresolved) + .extracting(GameInstance::getLegacyOwnerAccountId) + .containsExactly( + LEGACY_OWNER_ACCOUNT_ID + 2, + LEGACY_OWNER_ACCOUNT_ID + 5, + LEGACY_OWNER_ACCOUNT_ID + 1, + LEGACY_OWNER_ACCOUNT_ID + 4); + assertThat( + dsl.resultQuery("SELECT owner_account_id FROM game_instances WHERE id = 7101") + .fetchOne(0, Long.class)) + .isEqualTo(LEGACY_OWNER_ACCOUNT_ID + 2); + + try (Connection guardConnection = dataSource.getConnection(); + Connection competingWriterConnection = dataSource.getConnection()) { + guardConnection.setAutoCommit(false); + DSLContext guardDsl = DSL.using(guardConnection, SQLDialect.POSTGRES); + new GameInstanceRepository(guardDsl).findUnresolvedActiveOwnerRowsByTenantIdForUpdate(77L); + + DSLContext competingWriterDsl = DSL.using(competingWriterConnection, SQLDialect.POSTGRES); + competingWriterDsl.execute("SET lock_timeout = '150ms'"); + assertThatThrownBy( + () -> + competingWriterDsl.execute( + "UPDATE game_instances SET status = 'STOPPED' WHERE id = 7101")) + .isInstanceOf(DataAccessException.class); + + guardConnection.commit(); + competingWriterDsl.execute("SET lock_timeout = '0'"); + competingWriterDsl.execute("UPDATE game_instances SET status = 'STOPPED' WHERE id = 7101"); + } + + Record stoppedLegacyRow = + dsl.fetchOne( + "SELECT owner_account_id, owner_account_uuid FROM game_instances WHERE id = 7101"); + assertThat(stoppedLegacyRow.get("owner_account_id", Long.class)) + .isEqualTo(LEGACY_OWNER_ACCOUNT_ID + 2); + assertThat(stoppedLegacyRow.get("owner_account_uuid", UUID.class)).isNull(); + assertThat( + new GameInstanceRepository(dsl).findUnresolvedActiveOwnerRowsByTenantIdForUpdate(77L)) + .extracting(GameInstance::getId) + .containsExactly(7102L, 7103L, 7104L); + } + } + + private static DriverManagerDataSource dataSource(PostgreSQLContainer postgres) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(postgres.getDriverClassName()); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + return dataSource; + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotRepositoryIntegrationTest.java index 5194ae5af6..c2ecc1139c 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotRepositoryIntegrationTest.java @@ -48,6 +48,10 @@ class GameSessionRetainedTenantSnapshotRepositoryIntegrationTest { private static final UUID REALM_SHARED = UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); private static final UUID REALM_ISOLATED = UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd"); + private static final UUID CANONICAL_OWNER = + UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"); + private static final UUID CHANGED_CANONICAL_OWNER = + UUID.fromString("ffffffff-ffff-4fff-8fff-ffffffffffff"); private static final String COMMITTED_INSTANCE_PHANTOM_INSERT = "INSERT INTO game_instances (id, tenant_id, runtime_version, owner_account_id, status, row_version) " + "VALUES (901, " @@ -87,7 +91,7 @@ void capturesExactOrderedTenantProjectionAndStableDigestUnderReadCommittedOwnerT GameSessionRetainedTenantSnapshot snapshot = fixture.capture(); JsonNode root = JSON.readTree(snapshot.canonicalJson()); - assertThat(root.get("schemaVersion").intValue()).isEqualTo(1); + assertThat(root.get("schemaVersion").intValue()).isEqualTo(2); assertThat(root.get("targetNamespace").textValue()).isEqualTo(NAMESPACE); assertThat(root.get("legacyGameSessionTenantId").textValue()).isEqualTo(TENANT_ID); assertThat(textValues(root.get("instances"), "id")).containsExactly("2", "10", "20"); @@ -95,6 +99,8 @@ void capturesExactOrderedTenantProjectionAndStableDigestUnderReadCommittedOwnerT .isEqualTo("Café 🐉"); assertThat(root.get("instances").get(1).get("row_version").textValue()) .isEqualTo("9223372036854775807"); + assertThat(root.get("instances").get(1).get("owner_account_id").textValue()).isEqualTo("90010"); + assertThat(root.get("instances").get(1).get("owner_account_uuid").isNull()).isTrue(); assertThat(textValues(root.get("pointers"), "id")).containsExactly("2", "10"); assertThat(root.get("pointers").get(1).get("catalog_revision").textValue()) .isEqualTo("9223372036854775807"); @@ -150,6 +156,58 @@ void capturesExactOrderedTenantProjectionAndStableDigestUnderReadCommittedOwnerT .hasMessageContaining("backfill issue"); } + @Test + void capturesRawAndCanonicalOwnersAndBindsCanonicalOwnerChangesToSnapshotDigest() + throws Exception { + Fixture fixture = fixture(); + fixture.seedProjection(); + fixture.dsl.execute( + "INSERT INTO game_instances " + + "(id, tenant_id, runtime_version, owner_account_uuid, status, row_version) " + + "VALUES (?, ?, ?, ?, ?, ?)", + 22L, + TENANT, + "fresh-uuid-owner", + CANONICAL_OWNER, + "STOPPED", + 0L); + + GameSessionRetainedTenantSnapshot snapshot = fixture.capture(); + JsonNode instances = JSON.readTree(snapshot.canonicalJson()).get("instances"); + JsonNode retainedNumericOwner = instances.get(1); + JsonNode newCanonicalOwner = instances.get(3); + assertThat(retainedNumericOwner.get("id").textValue()).isEqualTo("10"); + assertThat(retainedNumericOwner.get("owner_account_id").textValue()).isEqualTo("90010"); + assertThat(retainedNumericOwner.get("owner_account_uuid").isNull()).isTrue(); + assertThat(newCanonicalOwner.get("id").textValue()).isEqualTo("22"); + assertThat(newCanonicalOwner.get("owner_account_id").isNull()).isTrue(); + assertThat(newCanonicalOwner.get("owner_account_uuid").textValue()) + .isEqualTo(CANONICAL_OWNER.toString()); + assertThat( + GameSessionRetainedTenantSnapshot.fromCanonicalJson( + NAMESPACE, TENANT_ID, snapshot.canonicalJson(), snapshot.evidenceDigest())) + .isEqualTo(snapshot); + + fixture.dsl.execute("UPDATE game_instances SET owner_account_id = ? WHERE id = ?", 90011L, 10L); + GameSessionRetainedTenantSnapshot changedRawSnapshot = fixture.capture(); + assertThat(changedRawSnapshot.evidenceDigest()).isNotEqualTo(snapshot.evidenceDigest()); + JsonNode changedRawOwner = + JSON.readTree(changedRawSnapshot.canonicalJson()).get("instances").get(1); + assertThat(changedRawOwner.get("owner_account_id").textValue()).isEqualTo("90011"); + assertThat(changedRawOwner.get("owner_account_uuid").isNull()).isTrue(); + + fixture.dsl.execute( + "UPDATE game_instances SET owner_account_uuid = ? WHERE id = ?", + CHANGED_CANONICAL_OWNER, + 22L); + GameSessionRetainedTenantSnapshot changedSnapshot = fixture.capture(); + assertThat(changedSnapshot.evidenceDigest()).isNotEqualTo(changedRawSnapshot.evidenceDigest()); + JsonNode changedCanonicalOwner = + JSON.readTree(changedSnapshot.canonicalJson()).get("instances").get(3); + assertThat(changedCanonicalOwner.get("owner_account_uuid").textValue()) + .isEqualTo(CHANGED_CANONICAL_OWNER.toString()); + } + @Test void captureUsesNowaitToRejectAnExistingWriterThenSucceedsAfterRollback() throws Exception { Fixture fixture = fixture(); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java index cc43052120..9716918e4b 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java @@ -29,6 +29,7 @@ class InitialAdmissionBindPostgresIntegrationTest { private static final String MIGRATION_LOCATION = "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + private static final String OWNER_ACCOUNT_UUID = "123e4567-e89b-12d3-a456-426614174000"; @Container static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); @@ -160,7 +161,7 @@ private static GameInstance gameInstance() { GameInstance gameInstance = new GameInstance(); gameInstance.setTenantId(41L); gameInstance.setRuntimeVersion("smoke-1"); - gameInstance.setOwnerAccountId(1001L); + gameInstance.setOwnerAccountId(OWNER_ACCOUNT_UUID); gameInstance.setStatus("RUNNING"); gameInstance.setGameTemplateId(810L); gameInstance.setVersionId(902L); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RunOwnedInitialLaunchPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RunOwnedInitialLaunchPostgresIntegrationTest.java index d6766d3d57..151be53ce4 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RunOwnedInitialLaunchPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RunOwnedInitialLaunchPostgresIntegrationTest.java @@ -33,6 +33,8 @@ class RunOwnedInitialLaunchPostgresIntegrationTest { private static final long TENANT_ID = 41L; private static final String REQUEST_ID = "run-owned-pg-race"; private static final String REQUEST_DIGEST = "c".repeat(64); + private static final String OWNER_ACCOUNT_UUID = "123e4567-e89b-12d3-a456-426614174000"; + private static final String SECOND_OWNER_ACCOUNT_UUID = "723c126e-4159-493b-ad15-36a67d673031"; @Container static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); @@ -91,8 +93,8 @@ void concurrentExactIdentityAllocationConvergesAndOrdinaryRowsRemainNullable() t .isTrue(); }); - GameInstance savedOrdinaryOne = repository.save(ordinaryInstance(1001L)); - GameInstance savedOrdinaryTwo = repository.save(ordinaryInstance(1002L)); + GameInstance savedOrdinaryOne = repository.save(ordinaryInstance(OWNER_ACCOUNT_UUID)); + GameInstance savedOrdinaryTwo = repository.save(ordinaryInstance(SECOND_OWNER_ACCOUNT_UUID)); assertThat(savedOrdinaryOne.getRunOwnedStartRequestId()).isNull(); assertThat(savedOrdinaryTwo.getRunOwnedStartRequestId()).isNull(); assertThat( @@ -189,7 +191,7 @@ private static GameInstance runOwnedInstance() { instance.setReleaseBundleId(20L); instance.setVersionStateEpoch(13L); instance.setGenerationConfigRevision("genrev-1"); - instance.setOwnerAccountId(1001L); + instance.setOwnerAccountId(OWNER_ACCOUNT_UUID); instance.setStatus("STARTING"); instance.setRunOwnedStartRequestId(REQUEST_ID); instance.setRunOwnedStartRequestDigest(REQUEST_DIGEST); @@ -197,7 +199,7 @@ private static GameInstance runOwnedInstance() { return instance; } - private static GameInstance ordinaryInstance(long ownerAccountId) { + private static GameInstance ordinaryInstance(String ownerAccountId) { GameInstance instance = new GameInstance(); instance.setTenantId(TENANT_ID); instance.setRuntimeVersion("ordinary-runtime"); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java index 5466115bab..511eb52e71 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java @@ -70,6 +70,8 @@ GameInstanceServiceLifecycleIntegrationTest.Config.class }) class GameInstanceServiceLifecycleIntegrationTest { + private static final String OWNER_ACCOUNT_UUID = "123e4567-e89b-12d3-a456-426614174000"; + @Container static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); @@ -365,7 +367,9 @@ void startSessionRollsBackWhenStatePropagationFails() { .when(sessionStateService) .saveState(any()); - assertThatThrownBy(() -> service.startSession(new StartSessionRequest(42L, 7L, "cp-1", 100L))) + assertThatThrownBy( + () -> + service.startSession(new StartSessionRequest(42L, 7L, "cp-1", OWNER_ACCOUNT_UUID))) .isInstanceOf(IllegalStateException.class) .hasMessage("state propagation failed"); @@ -381,7 +385,7 @@ void stopSessionRollsBackWhenStatePropagationFails() { instance.setScriptPatchVersion("patch-1"); instance.setScriptPinEpoch(1L); instance.setScriptPatchPinnedControlPlaneRequestId("pin-request-1"); - instance.setOwnerAccountId(100L); + instance.setOwnerAccountId(OWNER_ACCOUNT_UUID); instance.setStatus("RUNNING"); instance = repository.saveAndFlush(instance); long instanceId = instance.getId(); @@ -408,7 +412,7 @@ void restartSessionRollsBackWhenStatePropagationFails() { instance.setScriptPatchBaseVersionId(77L); instance.setScriptPinEpoch(1L); instance.setScriptPatchPinnedControlPlaneRequestId("pin-request-1"); - instance.setOwnerAccountId(100L); + instance.setOwnerAccountId(OWNER_ACCOUNT_UUID); instance.setStatus("STOPPED"); instance = repository.saveAndFlush(instance); long instanceId = instance.getId(); @@ -438,7 +442,7 @@ void replacingExistingSessionRestoresPriorRunningSessionWhenNewStartFails() { existing.setScriptPatchVersion("patch-1"); existing.setScriptPinEpoch(1L); existing.setScriptPatchPinnedControlPlaneRequestId("pin-request-1"); - existing.setOwnerAccountId(100L); + existing.setOwnerAccountId(OWNER_ACCOUNT_UUID); existing.setStatus("RUNNING"); existing = repository.saveAndFlush(existing); long existingId = existing.getId(); @@ -448,7 +452,9 @@ void replacingExistingSessionRestoresPriorRunningSessionWhenNewStartFails() { .saveState(any()); assertThatThrownBy( - () -> service.startSession(new StartSessionRequest(42L, 7L, "cp-2", 100L), true)) + () -> + service.startSession( + new StartSessionRequest(42L, 7L, "cp-2", OWNER_ACCOUNT_UUID), true)) .isInstanceOf(IllegalStateException.class) .hasMessage("state propagation failed"); @@ -459,7 +465,7 @@ void replacingExistingSessionRestoresPriorRunningSessionWhenNewStartFails() { assertThat(restored.getScriptPatchVersion()).isEqualTo("patch-1"); assertThat(restored.getScriptPinEpoch()).isEqualTo(1L); assertThat(restored.getScriptPatchPinnedControlPlaneRequestId()).isEqualTo("pin-request-1"); - assertThat(restored.getOwnerAccountId()).isEqualTo(100L); + assertThat(restored.getOwnerAccountId()).isEqualTo(OWNER_ACCOUNT_UUID); } @Test @@ -470,13 +476,13 @@ void replacingExistingSessionTerminatesPriorWorldBeforeFinalizingReplacement() { existing.setScriptPatchVersion("patch-1"); existing.setScriptPinEpoch(1L); existing.setScriptPatchPinnedControlPlaneRequestId("pin-request-1"); - existing.setOwnerAccountId(100L); + existing.setOwnerAccountId(OWNER_ACCOUNT_UUID); existing.setStatus("RUNNING"); existing = repository.saveAndFlush(existing); long existingId = existing.getId(); GameInstanceDto started = - service.startSession(new StartSessionRequest(42L, 7L, "cp-2", 100L), true); + service.startSession(new StartSessionRequest(42L, 7L, "cp-2", OWNER_ACCOUNT_UUID), true); assertThat(started.status()).isEqualTo("RUNNING"); assertThat(repository.findById(existingId)).isPresent(); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java index 17986693aa..12e807c6c7 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java @@ -120,6 +120,7 @@ @ActiveProfiles("test") @Import({NoGrpcServerTestConfiguration.class, InMemorySessionContextTestConfiguration.class}) class GameSessionWebSocketHandlerIntegrationTest { + private static final String OWNER_ACCOUNT_UUID = "123e4567-e89b-12d3-a456-426614174000"; // Runtime target 2 belongs to the sandbox route in this fixture. private static final long CUTOVER_GAME_INSTANCE_ID = 3L; @@ -407,22 +408,22 @@ void setUp() { GameInstance instance = new GameInstance(); instance.setId(41L); instance.setTenantId(22L); - instance.setOwnerAccountId(123L); + instance.setOwnerAccountId(OWNER_ACCOUNT_UUID); org.mockito.Mockito.doReturn(Optional.of(instance)).when(gameInstanceRepository).findById(41L); instance = new GameInstance(); instance.setId(42L); instance.setTenantId(22L); - instance.setOwnerAccountId(123L); + instance.setOwnerAccountId(OWNER_ACCOUNT_UUID); org.mockito.Mockito.doReturn(Optional.of(instance)).when(gameInstanceRepository).findById(42L); instance = new GameInstance(); instance.setId(1L); instance.setTenantId(22L); - instance.setOwnerAccountId(123L); + instance.setOwnerAccountId(OWNER_ACCOUNT_UUID); org.mockito.Mockito.doReturn(Optional.of(instance)).when(gameInstanceRepository).findById(1L); instance = new GameInstance(); instance.setId(2L); instance.setTenantId(23L); - instance.setOwnerAccountId(123L); + instance.setOwnerAccountId(OWNER_ACCOUNT_UUID); org.mockito.Mockito.doReturn(Optional.of(instance)).when(gameInstanceRepository).findById(2L); when(worldManagementClient.getWorldInstanceLifecycle( org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyLong())) diff --git a/services/game-session-service/src/test/java/unit/db/migration/V11__enforce_tenant_public_realm_cardinalityTest.java b/services/game-session-service/src/test/java/unit/db/migration/V11__enforce_tenant_public_realm_cardinalityTest.java index d6ff65dc05..50d22bc6bb 100644 --- a/services/game-session-service/src/test/java/unit/db/migration/V11__enforce_tenant_public_realm_cardinalityTest.java +++ b/services/game-session-service/src/test/java/unit/db/migration/V11__enforce_tenant_public_realm_cardinalityTest.java @@ -52,6 +52,7 @@ void keepsAdmissionPointerMigrationsUniqueAndOrderedFromTheV7AuditThroughV12() "V9__initial_admission_bind_owner_ledger.sql", "V9.1__gameplay_command_account_uuid.sql", "V10__run_owned_initial_launch_identity.sql", + "V10.1__game_instance_owner_account_uuid.sql", "V11__enforce_tenant_public_realm_cardinality.sql", "V12__index_gameplay_admission_pointer_event_tenant_lookup.sql"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/CrossServiceAppHarnessTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/CrossServiceAppHarnessTest.java index 818c6986fb..dfe6da9a7d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/CrossServiceAppHarnessTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/CrossServiceAppHarnessTest.java @@ -20,8 +20,9 @@ import org.springframework.core.env.MapPropertySource; class CrossServiceAppHarnessTest { + private static final String OWNER_ACCOUNT_UUID = "123e4567-e89b-12d3-a456-426614174000"; private static final StartSessionRequest REQUEST = - new StartSessionRequest(41L, 810L, "cross-service-fixture", 1001L); + new StartSessionRequest(41L, 810L, "cross-service-fixture", OWNER_ACCOUNT_UUID); @Test void databaseDisabledOrMissingReplacesTheRealServiceWithTheStub() { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java index 3c3f6ea1c0..ed9dbcfe85 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java @@ -51,6 +51,13 @@ @SuppressWarnings("unchecked") class LoginCommandHandlerTest { private static final String AUTH_TOKEN = "mock-jwt"; + private static final String OWNER_ACCOUNT_UUID = "123e4567-e89b-12d3-a456-426614174000"; + private static final String SECOND_GAME_OWNER_ACCOUNT_UUID = + "723c126e-4159-493b-ad15-36a67d673031"; + private static final String THIRD_GAME_OWNER_ACCOUNT_UUID = + "b651d5ad-21d0-47af-9558-0c07a42bd903"; + private static final String DIFFERENT_GAME_OWNER_ACCOUNT_UUID = + "f8217bf3-511a-4dfb-9bd9-3d085a6f86da"; private final GameInstanceRepository gameInstanceRepository = Mockito.mock(GameInstanceRepository.class); @@ -106,7 +113,7 @@ void parameterizedLoginPersistsAccountContextWithoutEnqueueingGameplayCommand() TextCommandType.LOGIN, List.of("DEMO@EXAMPLE.COM", "swordfish"), "LOGIN DEMO@EXAMPLE.COM swordfish"); - GameInstance instance = buildInstance(1L, 22L, 77L); + GameInstance instance = buildInstance(1L, 22L, OWNER_ACCOUNT_UUID); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); LoginCommandHandlingResult result = handler.handle("1", command, false); @@ -146,7 +153,7 @@ void oneArgumentLoginRequestsNeutralEmailChallengeWithoutAuthenticating() { TextCommand command = new TextCommand( TextCommandType.LOGIN, List.of("DEMO@EXAMPLE.COM"), "LOGIN DEMO@EXAMPLE.COM"); - GameInstance instance = buildInstance(1L, 22L, 77L); + GameInstance instance = buildInstance(1L, 22L, OWNER_ACCOUNT_UUID); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); when(accountClient.requestEmailLoginOtp("demo@example.com")) .thenReturn(RequestEmailLoginOtpResponse.newBuilder().setAccepted(true).build()); @@ -165,7 +172,7 @@ void oneArgumentLoginDoesNotExposeEmailChallengeFailures() { TextCommand command = new TextCommand( TextCommandType.LOGIN, List.of("demo@example.com"), "LOGIN demo@example.com"); - GameInstance instance = buildInstance(1L, 22L, 77L); + GameInstance instance = buildInstance(1L, 22L, OWNER_ACCOUNT_UUID); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); when(accountClient.requestEmailLoginOtp("demo@example.com")) .thenReturn( @@ -257,7 +264,7 @@ void invalidAccountIdZeroReturnsInvalidAccount() { when(accountClient.authenticate(Mockito.anyString(), Mockito.anyString())) .thenReturn( AuthenticateResponse.newBuilder().setAuthToken(AUTH_TOKEN).setAccountId("0").build()); - GameInstance instance = buildInstance(1L, 22L, 77L); + GameInstance instance = buildInstance(1L, 22L, OWNER_ACCOUNT_UUID); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); LoginCommandHandlingResult result = handler.handle("1", command, false); @@ -282,7 +289,7 @@ void invalidAccountIdNegativeReturnsInvalidAccount() { when(accountClient.authenticate(Mockito.anyString(), Mockito.anyString())) .thenReturn( AuthenticateResponse.newBuilder().setAuthToken(AUTH_TOKEN).setAccountId("-1").build()); - GameInstance instance = buildInstance(1L, 22L, 77L); + GameInstance instance = buildInstance(1L, 22L, OWNER_ACCOUNT_UUID); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); LoginCommandHandlingResult result = handler.handle("1", command, false); @@ -310,7 +317,7 @@ void invalidAccountIdMalformedReturnsInvalidAccount() { .setAuthToken(AUTH_TOKEN) .setAccountId("not-a-number") .build()); - GameInstance instance = buildInstance(1L, 22L, 77L); + GameInstance instance = buildInstance(1L, 22L, OWNER_ACCOUNT_UUID); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); LoginCommandHandlingResult result = handler.handle("1", command, false); @@ -370,7 +377,7 @@ void missingCredentialsReturnsPromptError() { @Test void bareLoginDoesNotPromoteVerifiedFirstPartyContextWithoutAccountExchange() { TextCommand command = new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"); - GameInstance instance = buildInstance(1L, 22L, 77L); + GameInstance instance = buildInstance(1L, 22L, OWNER_ACCOUNT_UUID); SessionContext shell = new SessionContext( 1L, @@ -428,7 +435,7 @@ void bareLoginDoesNotPromoteVerifiedFirstPartyContextWithoutAccountExchange() { assertEquals("production", shell.realmSlug()); assertEquals("shell-scope", shell.connectScopeId()); assertEquals("shell-request", shell.connectRequestId()); - assertEquals(77L, instance.getOwnerAccountId()); + assertEquals(OWNER_ACCOUNT_UUID, instance.getOwnerAccountId()); PlayCommandHandlingResult playResult = createPlayCommandHandler() @@ -497,7 +504,7 @@ void bareLoginForSameVerifiedSubjectPreservesRetryableSessionState() { "jti-account-a", "request-account-a", "gateway-account-a"))); - GameInstance instance = buildInstance(1L, 22L, 77L); + GameInstance instance = buildInstance(1L, 22L, OWNER_ACCOUNT_UUID); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); LoginCommandHandlingResult result = handler.handle("1", command, false); @@ -534,7 +541,7 @@ void bareLoginForSameAccountInDifferentTenantClearsOldTenantBeforeReturningUnava "gateway-tenant-b"); when(firstPartyConnectContextRegistry.find(1L)).thenReturn(Optional.of(verifiedTenantBContext)); when(gameInstanceRepository.findById(2L)) - .thenReturn(Optional.of(buildInstance(2L, 33L, accountA.accountId()))); + .thenReturn(Optional.of(buildInstance(2L, 33L, OWNER_ACCOUNT_UUID))); when(gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(33L, 2L)) .thenReturn(List.of(pointer("demo", "production", 33L, 2L, 1L))); @@ -572,7 +579,7 @@ void credentialLoginAsDifferentAccountInvalidatesFirstPartyContextBeforeBareLogi TextCommandType.LOGIN, List.of("demo@example.com", "swordfish"), "LOGIN demo@example.com swordfish"); - GameInstance instance = buildInstance(1L, 22L, 77L); + GameInstance instance = buildInstance(1L, 22L, OWNER_ACCOUNT_UUID); FirstPartyConnectContext accountAContext = new FirstPartyConnectContext( 99L, 22L, "demo", "production", 1L, 1L, "scope-1", "jti-1", "req-1", "gateway-1"); @@ -594,6 +601,25 @@ void credentialLoginAsDifferentAccountInvalidatesFirstPartyContextBeforeBareLogi }) .when(firstPartyConnectContextRegistry) .unregister(1L); + stubMutableSessionContext( + new SessionContext( + 1L, + 22L, + 0L, + null, + 0L, + null, + 0L, + null, + null, + "en-NZ", + 1L, + "demo", + "production", + 3L, + "SHARED", + "subject-99-scope", + "subject-99-request")); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); LoginCommandHandlingResult firstPartyResult = handler.handle("1", bareLogin, false); @@ -617,6 +643,7 @@ void credentialLoginAsDifferentAccountInvalidatesFirstPartyContextBeforeBareLogi assertEquals(77L, credentialIdentity.accountId()); assertEquals("demo@example.com", credentialIdentity.loginName()); assertEquals(AUTH_TOKEN, credentialIdentity.jwt()); + assertNull(credentialIdentity.localeTag()); assertEquals(1L, credentialIdentity.bootstrapGameInstanceId()); assertNull(credentialIdentity.worldSlug()); assertNull(credentialIdentity.realmSlug()); @@ -624,7 +651,7 @@ void credentialLoginAsDifferentAccountInvalidatesFirstPartyContextBeforeBareLogi assertNull(credentialIdentity.playableStateScope()); assertNull(credentialIdentity.connectScopeId()); assertNull(credentialIdentity.connectRequestId()); - assertClearedSessionContext(captor.getAllValues().get(1), 1L, null, null); + assertClearedSessionContext(captor.getAllValues().get(1), 0L, null, null, null); } @Test @@ -660,7 +687,7 @@ void staleFirstPartyRegistryCannotReplacePersistedCredentialIdentity() { @Test void bareLoginFailsUnavailableForPersistedFirstPartyContextFallback() { TextCommand command = new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"); - GameInstance instance = buildInstance(1L, 22L, 77L); + GameInstance instance = buildInstance(1L, 22L, OWNER_ACCOUNT_UUID); SessionContext persisted = new SessionContext( 1L, @@ -731,7 +758,7 @@ void bareLoginRejectsIncompletePersistedFirstPartyContextWhenRegistryEntryIsMiss @Test void bareLoginDoesNotFallBackToRawPersistedFirstPartyContextWhenTenantScopedSessionIsMissing() { TextCommand command = new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"); - GameInstance instance = buildInstance(1L, 22L, 77L); + GameInstance instance = buildInstance(1L, 22L, OWNER_ACCOUNT_UUID); SessionContext rawOnly = new SessionContext( 1L, @@ -779,7 +806,8 @@ void bareLoginDoesNotProceedWhenCurrentAdmissionPointerTenantIsInvalid() { "jti-1", "req-1", "gateway-1"))); - when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(buildInstance(1L, 0L, 77L))); + when(gameInstanceRepository.findById(1L)) + .thenReturn(Optional.of(buildInstance(1L, 0L, OWNER_ACCOUNT_UUID))); LoginCommandHandlingResult result = handler.handle("1", command, false); @@ -806,7 +834,8 @@ void bareLoginDoesNotProceedWhenCurrentAdmissionPointerGameInstanceIdIsInvalid() "gateway-1"))); when(gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(22L, 1L)) .thenReturn(List.of(pointer("demo", "production", 22L, 0L, 1L))); - when(gameInstanceRepository.findById(0L)).thenReturn(Optional.of(buildInstance(0L, 22L, 77L))); + when(gameInstanceRepository.findById(0L)) + .thenReturn(Optional.of(buildInstance(0L, 22L, OWNER_ACCOUNT_UUID))); LoginCommandHandlingResult result = handler.handle("1", command, false); @@ -831,7 +860,8 @@ void bareLoginDoesNotProceedWhenCurrentAdmissionPointerWorldOrRealmIsMissing() { "jti-1", "req-1", "gateway-1"))); - when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(buildInstance(1L, 22L, 77L))); + when(gameInstanceRepository.findById(1L)) + .thenReturn(Optional.of(buildInstance(1L, 22L, OWNER_ACCOUNT_UUID))); LoginCommandHandlingResult result = handler.handle("1", command, false); @@ -847,7 +877,8 @@ void bareLoginDoesNotProceedWhenCurrentAdmissionPointerRealmIsMissing() { Optional.of( new FirstPartyConnectContext( 77L, 22L, "demo", " ", 1L, 1L, "scope-1", "jti-1", "req-1", "gateway-1"))); - when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(buildInstance(1L, 22L, 77L))); + when(gameInstanceRepository.findById(1L)) + .thenReturn(Optional.of(buildInstance(1L, 22L, OWNER_ACCOUNT_UUID))); LoginCommandHandlingResult result = handler.handle("1", command, false); @@ -858,7 +889,7 @@ void bareLoginDoesNotProceedWhenCurrentAdmissionPointerRealmIsMissing() { @Test void bareLoginRejectsStalePointerVersion() { TextCommand command = new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"); - GameInstance instance = buildInstance(1L, 22L, 77L); + GameInstance instance = buildInstance(1L, 22L, OWNER_ACCOUNT_UUID); stubSessionContext(staleGameplayContext(1L)); when(firstPartyConnectContextRegistry.find(1L)) .thenReturn( @@ -893,7 +924,7 @@ void successfulLoginStoresSessionContext() { List.of("demo@example.com", "swordfish"), "LOGIN demo@example.com swordfish"); - GameInstance instance = buildInstance(1L, 22L, 77L); + GameInstance instance = buildInstance(1L, 22L, OWNER_ACCOUNT_UUID); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); handler.handle("1", command, false); @@ -919,7 +950,7 @@ void loginUsesBootstrappedGameInstanceInsteadOfTransportSessionId() { List.of("demo@example.com", "swordfish"), "LOGIN demo@example.com swordfish"); - GameInstance instance = buildInstance(99L, 22L, 77L); + GameInstance instance = buildInstance(99L, 22L, OWNER_ACCOUNT_UUID); SessionContext bootstrapContext = new SessionContext(12345L, 22L, 0L, null, 0L, null, 99L, null, null); when(sessionContextService.findBySessionId(12345L)).thenReturn(Optional.of(bootstrapContext)); @@ -942,7 +973,7 @@ void loginFailsClosedWhenNoBootstrapAuthorityExistsEvenIfTransportIdMatchesRunti List.of("demo@example.com", "swordfish"), "LOGIN demo@example.com swordfish"); - GameInstance collidingRuntime = buildInstance(12345L, 22L, 77L); + GameInstance collidingRuntime = buildInstance(12345L, 22L, OWNER_ACCOUNT_UUID); when(gameInstanceRepository.findById(12345L)).thenReturn(Optional.of(collidingRuntime)); LoginCommandHandlingResult result = handler.handle("12345", command, false); @@ -961,7 +992,7 @@ void reloginPreservesExistingGameplayBindingForSameSession() { List.of("demo@example.com", "swordfish"), "LOGIN demo@example.com swordfish"); - GameInstance instance = buildInstance(1L, 22L, 77L); + GameInstance instance = buildInstance(1L, 22L, OWNER_ACCOUNT_UUID); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); when(sessionContextService.findByTenantAndSessionId(22L, 1L)) .thenReturn( @@ -1028,7 +1059,7 @@ void loginAsDifferentAccountClearsCrossTenantProjectedPresenceBeforeSaving() { TextCommandType.LOGIN, List.of("other@example.com", "swordfish"), "LOGIN other@example.com swordfish"); - GameInstance instance = buildInstance(1L, 23L, 88L); + GameInstance instance = buildInstance(1L, 23L, SECOND_GAME_OWNER_ACCOUNT_UUID); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); when(accountClient.authenticate(anyString(), anyString())) .thenReturn( @@ -1076,7 +1107,7 @@ void loginAsDifferentAccountClearsCrossTenantPresenceAfterProjectionNormalizatio TextCommandType.LOGIN, List.of("other@example.com", "swordfish"), "LOGIN other@example.com swordfish"); - GameInstance instance = buildInstance(1L, 23L, 88L); + GameInstance instance = buildInstance(1L, 23L, SECOND_GAME_OWNER_ACCOUNT_UUID); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); when(accountClient.authenticate(anyString(), anyString())) .thenReturn( @@ -1108,7 +1139,7 @@ void loginAsSameAccountClearsCrossTenantPresenceBeforeSaving() { TextCommandType.LOGIN, List.of("demo@example.com", "swordfish"), "LOGIN demo@example.com swordfish"); - GameInstance instance = buildInstance(1L, 23L, 88L); + GameInstance instance = buildInstance(1L, 23L, SECOND_GAME_OWNER_ACCOUNT_UUID); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); when(accountClient.authenticate(anyString(), anyString())) .thenReturn( @@ -1157,7 +1188,7 @@ void loginAsSameAccountClearsCrossTenantPresenceAfterProjectionNormalization() { TextCommandType.LOGIN, List.of("demo@example.com", "swordfish"), "LOGIN demo@example.com swordfish"); - GameInstance instance = buildInstance(1L, 23L, 88L); + GameInstance instance = buildInstance(1L, 23L, SECOND_GAME_OWNER_ACCOUNT_UUID); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); when(accountClient.authenticate(anyString(), anyString())) .thenReturn( @@ -1190,7 +1221,7 @@ void reloginAsDifferentAccountClearsExistingGameplayBinding() { List.of("other@example.com", "swordfish"), "LOGIN other@example.com swordfish"); - GameInstance instance = buildInstance(1L, 22L, 77L); + GameInstance instance = buildInstance(1L, 22L, OWNER_ACCOUNT_UUID); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); when(accountClient.authenticate(anyString(), anyString())) .thenReturn( @@ -1310,7 +1341,7 @@ void reloginAsDifferentAccountDoesNotReplaceContextWhenPresenceClearFails() { TextCommandType.LOGIN, List.of("other@example.com", "swordfish"), "LOGIN other@example.com swordfish"); - GameInstance instance = buildInstance(1L, 22L, 77L); + GameInstance instance = buildInstance(1L, 22L, OWNER_ACCOUNT_UUID); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); when(accountClient.authenticate(anyString(), anyString())) .thenReturn( @@ -1337,7 +1368,7 @@ void reloginClearsStaleGameplayBindingBeforeRefreshingLoginContext() { List.of("demo@example.com", "swordfish"), "LOGIN demo@example.com swordfish"); - GameInstance instance = buildInstance(1L, 22L, 77L); + GameInstance instance = buildInstance(1L, 22L, OWNER_ACCOUNT_UUID); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); when(sessionContextService.findByTenantAndSessionId(22L, 1L)) .thenReturn(Optional.of(staleGameplayContext(7L))); @@ -1381,7 +1412,7 @@ void invalidCredentialsClearsStaleAuthenticatedSessionState() { TextCommandType.LOGIN, List.of("demo@example.com", "swordfish"), "LOGIN demo@example.com swordfish"); - GameInstance instance = buildInstance(1L, 22L, 77L); + GameInstance instance = buildInstance(1L, 22L, OWNER_ACCOUNT_UUID); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); stubSessionContext(staleGameplayContext(3L)); when(accountClient.authenticate(anyString(), anyString())).thenReturn(authError); @@ -1414,7 +1445,7 @@ void invalidCredentialsDropPartialProjectedRoutingBundleDuringFailedLoginCleanup TextCommandType.LOGIN, List.of("demo@example.com", "swordfish"), "LOGIN demo@example.com swordfish"); - GameInstance instance = buildInstance(1L, 22L, 77L); + GameInstance instance = buildInstance(1L, 22L, OWNER_ACCOUNT_UUID); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); SessionContext partialRoutingProjection = new SessionContext( @@ -1455,7 +1486,7 @@ void authenticatedNonOwnerAccountIsAcceptedAndStored() { TextCommandType.LOGIN, List.of("demo@example.com", "swordfish"), "LOGIN demo@example.com swordfish"); - GameInstance instance = buildInstance(1L, 22L, 77L); + GameInstance instance = buildInstance(1L, 22L, OWNER_ACCOUNT_UUID); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); when(accountClient.authenticate(anyString(), anyString())) .thenReturn( @@ -1469,7 +1500,7 @@ void authenticatedNonOwnerAccountIsAcceptedAndStored() { verify(sessionContextService).save(captor.capture()); assertEquals(99L, captor.getValue().accountId()); assertEquals("demo@example.com", captor.getValue().loginName()); - assertEquals(77L, instance.getOwnerAccountId()); + assertEquals(OWNER_ACCOUNT_UUID, instance.getOwnerAccountId()); } @Test @@ -1487,7 +1518,7 @@ void accountErrorUsesCanonicalCode() { TextCommandType.LOGIN, List.of("demo@example.com", "swordfish"), "LOGIN demo@example.com swordfish"); - GameInstance instance = buildInstance(1L, 22L, 77L); + GameInstance instance = buildInstance(1L, 22L, OWNER_ACCOUNT_UUID); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); when(accountClient.authenticate(anyString(), anyString())).thenReturn(authError); @@ -1514,7 +1545,7 @@ void accountLockedUsesCanonicalCode() { TextCommandType.LOGIN, List.of("demo@example.com", "swordfish"), "LOGIN demo@example.com swordfish"); - GameInstance instance = buildInstance(1L, 22L, 77L); + GameInstance instance = buildInstance(1L, 22L, OWNER_ACCOUNT_UUID); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); when(accountClient.authenticate(anyString(), anyString())).thenReturn(authError); @@ -1540,7 +1571,7 @@ void retryLaterUsesStableProtocolCodeAndLocalizedPresentation() { TextCommandType.LOGIN, List.of("demo@example.com", "swordfish"), "LOGIN demo@example.com swordfish"); - GameInstance instance = buildInstance(1L, 22L, 77L); + GameInstance instance = buildInstance(1L, 22L, OWNER_ACCOUNT_UUID); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); when(accountClient.authenticate(anyString(), anyString())).thenReturn(authError); @@ -1572,7 +1603,7 @@ void abuseControlUnavailableUsesStableProtocolCodeAndLocalizedPresentation() { TextCommandType.LOGIN, List.of("demo@example.com", "swordfish"), "LOGIN demo@example.com swordfish"); - GameInstance instance = buildInstance(1L, 22L, 77L); + GameInstance instance = buildInstance(1L, 22L, OWNER_ACCOUNT_UUID); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); when(accountClient.authenticate(anyString(), anyString())).thenReturn(authError); @@ -1607,7 +1638,7 @@ void unavailableReturnsUnavailableCode() { TextCommandType.LOGIN, List.of("demo@example.com", "swordfish"), "LOGIN demo@example.com swordfish"); - GameInstance instance = buildInstance(1L, 22L, 77L); + GameInstance instance = buildInstance(1L, 22L, OWNER_ACCOUNT_UUID); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); when(accountClient.authenticate(anyString(), anyString())).thenReturn(authError); @@ -1635,7 +1666,7 @@ void normalizedAuthenticationTransportFailureUsesUnavailable() { TextCommandType.LOGIN, List.of("demo@example.com", "swordfish"), "LOGIN demo@example.com swordfish"); - GameInstance instance = buildInstance(1L, 22L, 77L); + GameInstance instance = buildInstance(1L, 22L, OWNER_ACCOUNT_UUID); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); when(accountClient.authenticate(anyString(), anyString())).thenReturn(authError); @@ -1662,7 +1693,7 @@ void unmappedAuthenticationCodeUsesUnavailablePublicVocabulary() { TextCommandType.LOGIN, List.of("demo@example.com", "swordfish"), "LOGIN demo@example.com swordfish"); - GameInstance instance = buildInstance(1L, 22L, 77L); + GameInstance instance = buildInstance(1L, 22L, OWNER_ACCOUNT_UUID); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); when(accountClient.authenticate(anyString(), anyString())).thenReturn(authError); @@ -1686,7 +1717,7 @@ void unrecognizedAccountErrorUsesUnavailable() { TextCommandType.LOGIN, List.of("demo@example.com", "swordfish"), "LOGIN demo@example.com swordfish"); - GameInstance instance = buildInstance(1L, 22L, 77L); + GameInstance instance = buildInstance(1L, 22L, OWNER_ACCOUNT_UUID); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); when(accountClient.authenticate(anyString(), anyString())).thenReturn(authError); @@ -1713,7 +1744,7 @@ void unrecognizedNonblankAuthenticationCodeUsesUnavailable() { TextCommandType.LOGIN, List.of("demo@example.com", "swordfish"), "LOGIN demo@example.com swordfish"); - GameInstance instance = buildInstance(1L, 22L, 77L); + GameInstance instance = buildInstance(1L, 22L, OWNER_ACCOUNT_UUID); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); when(accountClient.authenticate(anyString(), anyString())).thenReturn(authError); @@ -1740,7 +1771,7 @@ void unauthenticatedDoesNotInferCanonicalCodeFromMessage() { TextCommandType.LOGIN, List.of("demo@example.com", "swordfish"), "LOGIN demo@example.com swordfish"); - GameInstance instance = buildInstance(1L, 22L, 77L); + GameInstance instance = buildInstance(1L, 22L, OWNER_ACCOUNT_UUID); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); when(accountClient.authenticate(anyString(), anyString())).thenReturn(authError); @@ -1763,7 +1794,7 @@ void repeatedLoginStillStoresContext() { GameInstance instance = new GameInstance(); instance.setId(1L); instance.setTenantId(22L); - instance.setOwnerAccountId(77L); + instance.setOwnerAccountId(OWNER_ACCOUNT_UUID); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); handler.handle("1", command, false); @@ -1785,7 +1816,7 @@ void loginDoesNotTakeOverGameplayBindingBeforePlay() { GameInstance instance = new GameInstance(); instance.setId(2L); instance.setTenantId(22L); - instance.setOwnerAccountId(77L); + instance.setOwnerAccountId(OWNER_ACCOUNT_UUID); when(sessionContextService.findBySessionId(2L)).thenReturn(Optional.of(bootstrapShell(2L, 2L))); when(gameInstanceRepository.findById(2L)).thenReturn(Optional.of(instance)); handler.handle("2", command, false); @@ -1804,7 +1835,7 @@ void repeatedLoginRefreshesLoginContextWithoutGameplayResume() { GameInstance instance = new GameInstance(); instance.setId(1L); instance.setTenantId(22L); - instance.setOwnerAccountId(77L); + instance.setOwnerAccountId(OWNER_ACCOUNT_UUID); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); handler.handle("1", command, false); @@ -1812,7 +1843,7 @@ void repeatedLoginRefreshesLoginContextWithoutGameplayResume() { verify(sessionContextService).save(any(SessionContext.class)); } - private GameInstance buildInstance(long id, long tenantId, long ownerAccountId) { + private GameInstance buildInstance(long id, long tenantId, String ownerAccountId) { GameInstance instance = new GameInstance(); instance.setId(id); instance.setTenantId(tenantId); @@ -1950,6 +1981,16 @@ private static void assertClearedSessionContext( long pointerVersion, String expectedConnectScopeId, String expectedConnectRequestId) { + assertClearedSessionContext( + context, pointerVersion, expectedConnectScopeId, expectedConnectRequestId, "en-NZ"); + } + + private static void assertClearedSessionContext( + SessionContext context, + long pointerVersion, + String expectedConnectScopeId, + String expectedConnectRequestId, + String expectedLocaleTag) { assertEquals(1L, context.sessionId()); assertEquals(22L, context.tenantId()); assertEquals(0L, context.accountId()); @@ -1959,7 +2000,7 @@ private static void assertClearedSessionContext( assertEquals(0L, context.gameInstanceId()); assertNull(context.roomInstanceId()); assertNull(context.jwt()); - assertEquals("en-NZ", context.localeTag()); + assertEquals(expectedLocaleTag, context.localeTag()); assertEquals(1L, context.bootstrapGameInstanceId()); if (pointerVersion > 0) { assertEquals("demo", context.worldSlug()); @@ -1993,7 +2034,7 @@ void credentialLoginPreservesCurrentBootstrapTargetButDropsSubjectBoundConnectSc TextCommandType.LOGIN, List.of("other@example.com", "swordfish"), "LOGIN other@example.com swordfish"); - GameInstance instance = buildInstance(1L, 22L, 77L); + GameInstance instance = buildInstance(1L, 22L, THIRD_GAME_OWNER_ACCOUNT_UUID); stubSessionContext( new SessionContext( 1L, @@ -2045,7 +2086,7 @@ void credentialLoginDropsStaleBootstrapTargetAndSubjectBoundConnectScope() { TextCommandType.LOGIN, List.of("other@example.com", "swordfish"), "LOGIN other@example.com swordfish"); - GameInstance instance = buildInstance(1L, 22L, 77L); + GameInstance instance = buildInstance(1L, 22L, THIRD_GAME_OWNER_ACCOUNT_UUID); stubSessionContext( new SessionContext( 1L, @@ -2127,7 +2168,8 @@ void verifiedConnectForDifferentTenantClearsPriorBindingWithoutReusingItsBootstr "jti-1", "new-request", "gateway-1"))); - when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(buildInstance(1L, 22L, 99L))); + when(gameInstanceRepository.findById(1L)) + .thenReturn(Optional.of(buildInstance(1L, 22L, DIFFERENT_GAME_OWNER_ACCOUNT_UUID))); LoginCommandHandlingResult result = handler.handle("1", command, false); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index 75086a8288..6e5d31ce4e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -79,6 +79,7 @@ @SuppressWarnings("unchecked") class SessionResumptionFlowTest { + private static final String OWNER_ACCOUNT_UUID = "123e4567-e89b-12d3-a456-426614174000"; private static final String LOGIN_PAYLOAD = "LOGIN demo@example.com swordfish"; private static final String PLAY_PAYLOAD = "PLAY demo production"; private static final String LOOK_PAYLOAD = "LOOK"; @@ -162,7 +163,7 @@ void setUp() { GameInstance perCall = new GameInstance(); perCall.setId(sessionId); perCall.setTenantId(22L); - perCall.setOwnerAccountId(77L); + perCall.setOwnerAccountId(OWNER_ACCOUNT_UUID); return Optional.of(perCall); }); when(commandService.enqueue(anyString(), anyString(), anyBoolean())) @@ -605,7 +606,7 @@ void staleIdentityMappingFallsBackToFreshSession() { GameInstance perCall = new GameInstance(); perCall.setId(sessionId); perCall.setTenantId(22L); - perCall.setOwnerAccountId(77L); + perCall.setOwnerAccountId(OWNER_ACCOUNT_UUID); return Optional.of(perCall); }); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java index d64521ef4b..84df150688 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java @@ -90,8 +90,8 @@ @SuppressWarnings("unchecked") class TextCommandInterpreterTest { + private static final String OWNER_ACCOUNT_UUID = "123e4567-e89b-12d3-a456-426614174000"; private static final String PLAY_DEMO_PRODUCTION = "PLAY demo production"; - private final CommandService commandService = Mockito.mock(CommandService.class); private final GameLogicClient gameLogicClient = Mockito.mock(GameLogicClient.class); private final EntityManagementClient entityManagementClient = @@ -354,7 +354,7 @@ void setUp() { GameInstance instance = new GameInstance(); instance.setId(sessionId); instance.setTenantId(22L); - instance.setOwnerAccountId(123L); + instance.setOwnerAccountId(OWNER_ACCOUNT_UUID); return Optional.of(instance); }); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java index ae05ad6384..454c3a913c 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java @@ -20,6 +20,8 @@ class RunOwnedInitialAdmissionFixtureCapabilityTest { private static final String RUN_ID = "compose-smoke-2939"; private static final String PROJECT_NAME = "firemud-smoke-compose-smoke-2939"; private static final String OPERATION_ID = "d2db8478-9c56-42ab-99c2-9fbead6841ba"; + // Synthetic unit-fixture value only; it does not prove Account-service issuance or mapping. + private static final String TEST_OWNER_ACCOUNT_ID = "123e4567-e89b-12d3-a456-426614174000"; private static final String LEAF_SHA = "a".repeat(64); private static final String CA_SHA = "b".repeat(64); @@ -37,7 +39,7 @@ void parsesExactCapabilityAndBindsRunProjectSelectorsAndTlsPins() { assertThat(capability.operationId()).isEqualTo(OPERATION_ID); assertThat(capability.tenantId()).isEqualTo(7L); assertThat(capability.gameTemplateId()).isEqualTo(17L); - assertThat(capability.ownerAccountId()).isEqualTo(27L); + assertThat(capability.ownerAccountId()).isEqualTo(TEST_OWNER_ACCOUNT_ID); assertThat(capability.worldSlug()).isEqualTo("demo"); assertThat(capability.realmSlug()).isEqualTo("production"); assertThat(capability.visible()).isTrue(); @@ -53,6 +55,19 @@ void rejectsUnknownDuplicateMismatchedAndNoncanonicalCapabilityFields() { assertInvalid(validJson().replace("\"schema\":", "\"schema\":\"wrong\",\"schema\":")); assertInvalid(validJson().replace(RUN_ID, "different-run")); assertInvalid(validJson().replace(OPERATION_ID, "not-a-uuid")); + assertInvalid( + validJson() + .replace( + "\"ownerAccountId\": \"" + TEST_OWNER_ACCOUNT_ID + "\"", "\"ownerAccountId\": 27")); + assertInvalid( + validJson() + .replace( + "\"ownerAccountId\": \"" + TEST_OWNER_ACCOUNT_ID + "\"", + "\"ownerAccountId\": \"27\"")); + assertInvalid( + validJson().replace(TEST_OWNER_ACCOUNT_ID, "00000000-0000-0000-0000-000000000000")); + assertInvalid( + validJson().replace(TEST_OWNER_ACCOUNT_ID, "123E4567-E89B-12D3-A456-426614174000")); assertInvalid( validJson().replace("\"operationId\": \"" + OPERATION_ID + "\"", "\"operationId\": null")); assertInvalid(validJson().replace("\"tenantId\": 7", "\"tenantId\": \"7\"")); @@ -131,7 +146,7 @@ private static String validJson() { "operationId": "%s",%n\ "tenantId": 7,%n\ "gameTemplateId": 17,%n\ - "ownerAccountId": 27,%n\ + "ownerAccountId": "%s",%n\ "worldSlug": "demo",%n\ "worldDisplayName": "Demo World",%n\ "realmSlug": "production",%n\ @@ -151,6 +166,7 @@ private static String validJson() { RUN_ID, PROJECT_NAME, OPERATION_ID, + TEST_OWNER_ACCOUNT_ID, LEAF_SHA, RunOwnedInitialAdmissionFixtureCapability.GAME_SESSION_URI_SAN, CA_SHA); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java index 83a07c8aae..81037b1d2c 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java @@ -55,6 +55,8 @@ class RunOwnedInitialAdmissionFixtureCoordinatorTest { private static final String PROJECT_NAME = "firemud-smoke-compose-smoke-2939"; private static final String CAPABILITY_PATH = "fixture/capability.json"; private static final String OPERATION_ID = "d2db8478-9c56-42ab-99c2-9fbead6841ba"; + // Synthetic unit-fixture value only; it does not prove Account-service issuance or mapping. + private static final String TEST_OWNER_ACCOUNT_ID = "123e4567-e89b-12d3-a456-426614174000"; private static final UUID REALM_ID = UUID.fromString("23d39978-9d44-4e1a-8659-998ff9239b01"); private static final UUID NAMESPACE_ID = UUID.fromString("ed1b4d88-81f8-4404-af7c-9a5dc91d3043"); private static final UUID HOLD_ID = UUID.fromString("5fdd38a3-09e3-46bb-b11a-e2ff2a096211"); @@ -481,7 +483,7 @@ private static Fixture fixture(InitialAdmissionBindHoldStatus holdStatus) { OPERATION_ID, 7L, 17L, - 27L, + TEST_OWNER_ACCOUNT_ID, "demo", "Demo World", "production", @@ -510,7 +512,7 @@ private static Fixture fixture(InitialAdmissionBindHoldStatus holdStatus) { 3L, "config-1", null, - 27L, + new String(TEST_OWNER_ACCOUNT_ID.toCharArray()), "RUNNING"); when(gameInstanceService.startRunOwnedInitialLaunch(any())) .thenReturn(new RunOwnedInitialLaunchResult(target, 4L)); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/TestDataSeederTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/TestDataSeederTest.java index 11cb584668..4b3cf22f28 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/TestDataSeederTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/TestDataSeederTest.java @@ -28,11 +28,10 @@ void setup() { } @Test - void runSeedsCanonicalNonRuntimeData() throws Exception { + void runSeedsManifestAndFeatureFlagMetadata() throws Exception { when(gameManifestRepository.findAll()).thenReturn(java.util.List.of()); when(featureFlagRepository.findByTenantIdAndName(1L, "double_xp")) .thenReturn(java.util.Optional.empty()); - seeder.run(new DefaultApplicationArguments(new String[] {})); verify(gameManifestRepository).save(any(GameManifest.class)); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/mapper/GameInstanceMapperTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/mapper/GameInstanceMapperTest.java index c0de0c3156..3a871d924e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/mapper/GameInstanceMapperTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/mapper/GameInstanceMapperTest.java @@ -8,6 +8,8 @@ import org.mapstruct.factory.Mappers; class GameInstanceMapperTest { + private static final String OWNER_ACCOUNT_UUID = "123e4567-e89b-12d3-a456-426614174000"; + private final GameInstanceMapper mapper = Mappers.getMapper(GameInstanceMapper.class); @Test @@ -28,7 +30,7 @@ void serverControlledScriptPatchBaseIsIgnoredOnEntityMappingAndExposedOnDtoMappi 7L, "generation-1", null, - 8L, + OWNER_ACCOUNT_UUID, "RUNNING"); GameInstance mappedEntity = mapper.toEntity(dto); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotTest.java index 5dca3d5108..bfb64cacec 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotTest.java @@ -3,11 +3,15 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import java.io.IOException; import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantSnapshot; import org.junit.jupiter.api.Test; @@ -16,10 +20,12 @@ class GameSessionRetainedTenantSnapshotTest { private static final ObjectMapper JSON = new ObjectMapper(); private static final String NAMESPACE = "retained-snapshot-test"; private static final String TENANT_ID = "7"; + private static final String SNAPSHOT_DIGEST_DOMAIN = + "game-session/retained-tenant-identity-snapshot/v2"; private static final String SNAPSHOT_DIGEST = - "sha256:66c92bb8e82371c03d24d9cfaa14c7e7c033b8a4a53d081bc05214cf501e22a1"; + "sha256:7aa718259dd0dbf7395f62691013c3fdd2fa0f9d21e9280090ae8bc8ddb7c757"; private static final String CHANGED_SNAPSHOT_DIGEST = - "sha256:5652fc676448cc7dc8e45453f2577915d6ded0a0f1b00bbf1ee84b59673b27e6"; + "sha256:ef6e4dd638dfd2892fe219fc84489f7c3a97a312c0a19831878e723627bebb94"; private static final String IRRELEVANT_DIGEST = "sha256:" + "0".repeat(64); @Test @@ -53,6 +59,87 @@ void emitsCanonicalOrderedUnicodeAndLargeCounterVectorAndBindsChangedFields() { .hasMessageContaining("digest"); } + @Test + void retainsRawAndCanonicalOwnerSlotsIndependentlyAndBindsBothToTheDigest() { + ObjectNode projection = envelopeWithInstances("runtime"); + ArrayNode instances = projection.withArray("instances"); + ObjectNode mixedOwner = (ObjectNode) instances.get(0); + mixedOwner.put("owner_account_uuid", "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"); + ObjectNode canonicalOnlyOwner = (ObjectNode) instances.get(1); + canonicalOnlyOwner.putNull("owner_account_id"); + canonicalOnlyOwner.put("owner_account_uuid", "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + instances.add(instance("20", "legacy-owner", "20")); + + GameSessionRetainedTenantSnapshot snapshot = snapshot(projection); + JsonNode rows; + try { + rows = JSON.readTree(snapshot.canonicalJson()).get("instances"); + } catch (IOException exception) { + throw new AssertionError("Unable to read canonical snapshot test vector", exception); + } + assertThat(rows.get(0).get("owner_account_id").textValue()).isEqualTo("9"); + assertThat(rows.get(0).get("owner_account_uuid").textValue()) + .isEqualTo("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"); + assertThat(rows.get(1).get("owner_account_id").isNull()).isTrue(); + assertThat(rows.get(1).get("owner_account_uuid").textValue()) + .isEqualTo("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + assertThat(rows.get(2).get("owner_account_id").textValue()).isEqualTo("9"); + assertThat(rows.get(2).get("owner_account_uuid").isNull()).isTrue(); + + ObjectNode changedOwner = projection.deepCopy(); + ((ObjectNode) changedOwner.withArray("instances").get(0)) + .put("owner_account_uuid", "ffffffff-ffff-4fff-8fff-ffffffffffff"); + GameSessionRetainedTenantSnapshot changedSnapshot = snapshot(changedOwner); + assertThat(changedSnapshot.evidenceDigest()).isNotEqualTo(snapshot.evidenceDigest()); + } + + @Test + void rejectsMissingMalformedNilAndLegacyVersionOwnerEvidence() { + ObjectNode missingSlot = envelopeWithInstances("runtime"); + ((ObjectNode) missingSlot.withArray("instances").get(0)).remove("owner_account_uuid"); + assertThatThrownBy(() -> revalidate(missingSlot)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("missing or undeclared fields"); + + ObjectNode bothMissing = envelopeWithInstances("runtime"); + ObjectNode ownerless = (ObjectNode) bothMissing.withArray("instances").get(0); + ownerless.putNull("owner_account_id"); + assertThatThrownBy(() -> revalidate(bothMissing)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("raw or canonical owner account identity"); + + ObjectNode malformedUuid = envelopeWithInstances("runtime"); + ((ObjectNode) malformedUuid.withArray("instances").get(0)) + .put("owner_account_uuid", "EEEEEEEE-EEEE-4EEE-8EEE-EEEEEEEEEEEE"); + assertThatThrownBy(() -> revalidate(malformedUuid)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("lowercase canonical UUID"); + + ObjectNode nilUuid = envelopeWithInstances("runtime"); + ((ObjectNode) nilUuid.withArray("instances").get(0)) + .put("owner_account_uuid", "00000000-0000-0000-0000-000000000000"); + assertThatThrownBy(() -> revalidate(nilUuid)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("nil UUID"); + + ObjectNode malformedRawId = envelopeWithInstances("runtime"); + ObjectNode rawIdRow = (ObjectNode) malformedRawId.withArray("instances").get(0); + rawIdRow.put("owner_account_id", "09"); + rawIdRow.put("owner_account_uuid", "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"); + assertThatThrownBy(() -> revalidate(malformedRawId)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical decimal"); + + ObjectNode oldSchema = envelopeWithInstances("runtime"); + oldSchema.put("schemaVersion", 1); + for (JsonNode row : oldSchema.withArray("instances")) { + ((ObjectNode) row).remove("owner_account_uuid"); + } + assertThatThrownBy(() -> revalidate(oldSchema)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("schemaVersion must be integer 2"); + } + @Test void rejectsEmptyUnknownMalformedAndDuplicateMemberEvidence() { ObjectNode empty = envelope(); @@ -150,7 +237,7 @@ private static ObjectNode envelopeWithInstances(String runtimeVersion) { private static ObjectNode envelope() { ObjectNode envelope = JSON.createObjectNode(); envelope.put("targetNamespace", NAMESPACE); - envelope.put("schemaVersion", 1); + envelope.put("schemaVersion", 2); envelope.put("legacyGameSessionTenantId", TENANT_ID); envelope.set("instances", JSON.createArrayNode()); envelope.set("pointers", JSON.createArrayNode()); @@ -168,6 +255,7 @@ private static ObjectNode instance(String id, String runtimeVersion, String rowV instance.put("runtime_version", runtimeVersion); instance.putNull("script_patch_version"); instance.put("owner_account_id", "9"); + instance.putNull("owner_account_uuid"); instance.put("status", "STOPPED"); instance.put("row_version", rowVersion); instance.putNull("game_template_id"); @@ -210,4 +298,28 @@ private static String canonicalJson(ObjectNode projection) { throw new AssertionError("Unable to build canonical snapshot test vector", exception); } } + + private static GameSessionRetainedTenantSnapshot snapshot(ObjectNode projection) { + String canonicalJson = canonicalJson(projection); + return GameSessionRetainedTenantSnapshot.fromCanonicalJson( + NAMESPACE, TENANT_ID, canonicalJson, expectedDigest(canonicalJson)); + } + + private static String expectedDigest(String canonicalJson) { + try { + MessageDigest hash = MessageDigest.getInstance("SHA-256"); + updateFrame(hash, SNAPSHOT_DIGEST_DOMAIN); + updateFrame(hash, canonicalJson); + return "sha256:" + HexFormat.of().formatHex(hash.digest()); + } catch (NoSuchAlgorithmException exception) { + throw new AssertionError("SHA-256 unavailable for snapshot test vector", exception); + } + } + + private static void updateFrame(MessageDigest hash, String value) { + byte[] bytes = value.getBytes(StandardCharsets.UTF_8); + hash.update(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + hash.update((byte) ':'); + hash.update(bytes); + } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java index f3f26bc9b6..26e70b3c0d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java @@ -48,9 +48,13 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; class GameInstanceServiceImplTest { + private static final String OWNER_ACCOUNT_UUID = "123e4567-e89b-12d3-a456-426614174000"; + private static final String OTHER_OWNER_ACCOUNT_UUID = "123e4567-e89b-12d3-a456-426614174001"; + private GameInstanceRepository repository; private GameInstanceMapper mapper; private SessionStateService stateService; @@ -78,7 +82,7 @@ void legacyDtoConstructorRejectsNonblankPatchWithoutCompleteTuple() { 12L, 13L, "generation-1", - 42L, + OWNER_ACCOUNT_UUID, "RUNNING")); assertEquals( @@ -117,12 +121,13 @@ void setup() { @Test void startSessionSavesState() { - StartSessionRequest request = new StartSessionRequest(1L, 3L, "cp-1", 42L); + StartSessionRequest request = new StartSessionRequest(1L, 3L, "cp-1", OWNER_ACCOUNT_UUID); GameInstanceDto dto = service.startSession(request); assertEquals("RUNNING", dto.status()); - verify(repository, never()).findFirstByTenantIdAndOwnerAccountIdAndStatus(1L, 42L, "RUNNING"); + verify(repository, never()) + .findFirstByTenantIdAndOwnerAccountIdAndStatus(1L, OWNER_ACCOUNT_UUID, "RUNNING"); ArgumentCaptor states = ArgumentCaptor.forClass(GameInstanceDto.class); verify(stateService, times(2)).saveState(states.capture()); assertEquals("STARTING", states.getAllValues().get(0).status()); @@ -130,9 +135,124 @@ void startSessionSavesState() { assertNull(store.get(10L).getScriptPinEpoch()); } + @Test + void startSessionRejectsNonCanonicalOwnerBeforeDependenciesOrMutation() { + for (String invalidOwner : + List.of( + "42", "00000000-0000-0000-0000-000000000000", "123E4567-E89B-12D3-A456-426614174000")) { + assertThrows( + IllegalArgumentException.class, + () -> + service.startSession( + new StartSessionRequest(1L, 3L, "cp-invalid-owner", invalidOwner), true)); + } + + verify(gameDesignClient, never()).resolveLaunchDescriptor(anyLong(), anyLong(), anyString()); + verify(repository, never()).save(any(GameInstance.class)); + assertEquals(0, store.size()); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void startSessionRejectsUnresolvedLegacyOwnerBeforeMutation(boolean replaceExistingFirst) { + persistLegacyOwner(7L, 1L, "v1", "RUNNING", 9_007_199_254_740_993L); + + LifecycleOutcomeException error = + assertThrows( + LifecycleOutcomeException.class, + () -> + service.startSession( + new StartSessionRequest(1L, 3L, "cp-legacy-owner", OWNER_ACCOUNT_UUID), + replaceExistingFirst)); + + assertEquals("OWNER_ACCOUNT_IDENTITY_UNAVAILABLE", error.code()); + assertEquals( + "cannot start a session while tenant owner identity evidence is active or uncertain", + error.detailMessage()); + assertEquals("RUNNING", store.get(7L).getStatus()); + assertEquals(9_007_199_254_740_993L, store.get(7L).getLegacyOwnerAccountId()); + assertEquals(1, store.size()); + verify(repository).findUnresolvedActiveOwnerRowsByTenantIdForUpdate(1L); + verify(repository, never()).save(any(GameInstance.class)); + verify(repository, never()) + .findFirstByTenantIdAndOwnerAccountIdAndStatus(1L, OWNER_ACCOUNT_UUID, "RUNNING"); + verifyNoInteractions(stateService); + verifyNoInteractions(worldManagementClient); + } + + @Test + void startSessionRejectsEveryUncertainLegacyOwnerStatus() { + String[] uncertainStatuses = {"STARTING", "STOPPING", "UNRECOGNIZED", null}; + long id = 20L; + for (String status : uncertainStatuses) { + persistLegacyOwner(id, 1L, "v1", status, 100L + id); + + LifecycleOutcomeException error = + assertThrows( + LifecycleOutcomeException.class, + () -> + service.startSession( + new StartSessionRequest(1L, 3L, "cp-uncertain-owner", OWNER_ACCOUNT_UUID))); + + assertEquals("OWNER_ACCOUNT_IDENTITY_UNAVAILABLE", error.code()); + assertEquals(status, store.get(id).getStatus()); + assertEquals(100L + id, store.get(id).getLegacyOwnerAccountId()); + store.remove(id); + id++; + } + + verify(repository, times(uncertainStatuses.length)) + .findUnresolvedActiveOwnerRowsByTenantIdForUpdate(1L); + verify(repository, never()).save(any(GameInstance.class)); + verifyNoInteractions(stateService); + verifyNoInteractions(worldManagementClient); + } + + @Test + void startSessionAllowsTenantWithOnlyStoppedLegacyOwnerEvidence() { + persistLegacyOwner(7L, 1L, "v1", "STOPPED", 9_007_199_254_740_993L); + + GameInstanceDto dto = + service.startSession( + new StartSessionRequest(1L, 3L, "cp-stopped-legacy-owner", OWNER_ACCOUNT_UUID)); + + assertEquals("RUNNING", dto.status()); + assertEquals("STOPPED", store.get(7L).getStatus()); + assertEquals(9_007_199_254_740_993L, store.get(7L).getLegacyOwnerAccountId()); + assertEquals("RUNNING", store.get(dto.id()).getStatus()); + } + + @Test + void restartSessionRejectsMissingOrNonCanonicalOwnerBeforeMutation() { + String[] unresolvedOwnerIds = { + null, "42", "00000000-0000-0000-0000-000000000000", "123E4567-E89B-12D3-A456-426614174000" + }; + long id = 20L; + for (String ownerAccountId : unresolvedOwnerIds) { + GameInstance instance = persistLegacyOwner(id, 1L, "v1", "STOPPED", 200L + id); + instance.setOwnerAccountId(ownerAccountId); + store.put(id, copyOf(instance)); + long sessionId = id; + + LifecycleOutcomeException error = + assertThrows(LifecycleOutcomeException.class, () -> service.restartSession(sessionId)); + + assertEquals("OWNER_ACCOUNT_IDENTITY_UNAVAILABLE", error.code()); + assertEquals("STOPPED", store.get(sessionId).getStatus()); + assertEquals(ownerAccountId, store.get(sessionId).getOwnerAccountId()); + assertEquals(200L + sessionId, store.get(sessionId).getLegacyOwnerAccountId()); + id++; + } + + verify(repository, never()).save(any(GameInstance.class)); + verifyNoInteractions(stateService); + verifyNoInteractions(worldManagementClient); + } + @Test void runOwnedInitialLaunchExactRetryReturnsSameActiveTargetWithoutReplayingActivation() { - StartSessionRequest request = new StartSessionRequest(1L, 3L, "run-owned-1", 42L); + StartSessionRequest request = + new StartSessionRequest(1L, 3L, "run-owned-1", OWNER_ACCOUNT_UUID); configureRunOwnedWorld(request); var first = service.startRunOwnedInitialLaunch(request); @@ -147,7 +267,7 @@ void runOwnedInitialLaunchExactRetryReturnsSameActiveTargetWithoutReplayingActiv assertEquals(1L, store.get(10L).getRunOwnedStartPreparingEpoch()); assertEquals(2L, store.get(10L).getRunOwnedStartActiveEpoch()); assertEquals( - "edb9ae538f4a9c8e74053c2a7f6d0bc251353b64afc367defab5b5369785e708", + "b906f1e8c611679a00a2fa30ae11438bc5ce540b18995a9efbd607e6891cc720", store.get(10L).getRunOwnedStartRequestDigest()); ArgumentCaptor repairedState = ArgumentCaptor.forClass(GameInstanceDto.class); verify(stateService).saveState(repairedState.capture()); @@ -158,7 +278,8 @@ void runOwnedInitialLaunchExactRetryReturnsSameActiveTargetWithoutReplayingActiv @Test void runOwnedRunningRetryRejectsContradictoryPreparingWorldWithoutRuntimeMutation() { - StartSessionRequest request = new StartSessionRequest(1L, 3L, "run-owned-preparing", 42L); + StartSessionRequest request = + new StartSessionRequest(1L, 3L, "run-owned-preparing", OWNER_ACCOUNT_UUID); AtomicReference worldState = configureRunOwnedWorld(request); service.startRunOwnedInitialLaunch(request); clearInvocations(stateService, worldManagementClient); @@ -185,7 +306,8 @@ void runOwnedRunningRetryRejectsContradictoryPreparingWorldWithoutRuntimeMutatio @Test void runOwnedInitialLaunchRetryReconcilesAmbiguousPrepareOnTheSameInstance() { - StartSessionRequest request = new StartSessionRequest(1L, 3L, "run-owned-prepare-timeout", 42L); + StartSessionRequest request = + new StartSessionRequest(1L, 3L, "run-owned-prepare-timeout", OWNER_ACCOUNT_UUID); AtomicReference worldState = configureRunOwnedWorld(request); AtomicInteger prepareCalls = new AtomicInteger(); when(worldManagementClient.prepareWorldInstance( @@ -253,7 +375,8 @@ void runOwnedInitialLaunchRetryReconcilesAmbiguousPrepareOnTheSameInstance() { @Test void runOwnedInitialLaunchRetryReconcilesAmbiguousActivationOnTheSameInstance() { - StartSessionRequest request = new StartSessionRequest(1L, 3L, "run-owned-timeout", 42L); + StartSessionRequest request = + new StartSessionRequest(1L, 3L, "run-owned-timeout", OWNER_ACCOUNT_UUID); AtomicReference worldState = configureRunOwnedWorld(request); doThrow(new IllegalStateException("activation response timed out")) .when(worldManagementClient) @@ -283,7 +406,8 @@ void runOwnedInitialLaunchRetryReconcilesAmbiguousActivationOnTheSameInstance() @Test void runOwnedInitialLaunchRequestIdConflictsOnChangedOwnerOrTemplate() { - StartSessionRequest request = new StartSessionRequest(1L, 3L, "run-owned-conflict", 42L); + StartSessionRequest request = + new StartSessionRequest(1L, 3L, "run-owned-conflict", OWNER_ACCOUNT_UUID); configureRunOwnedWorld(request); service.startRunOwnedInitialLaunch(request); @@ -291,12 +415,12 @@ void runOwnedInitialLaunchRequestIdConflictsOnChangedOwnerOrTemplate() { IllegalStateException.class, () -> service.startRunOwnedInitialLaunch( - new StartSessionRequest(1L, 3L, "run-owned-conflict", 43L))); + new StartSessionRequest(1L, 3L, "run-owned-conflict", OTHER_OWNER_ACCOUNT_UUID))); assertThrows( IllegalStateException.class, () -> service.startRunOwnedInitialLaunch( - new StartSessionRequest(1L, 4L, "run-owned-conflict", 42L))); + new StartSessionRequest(1L, 4L, "run-owned-conflict", OWNER_ACCOUNT_UUID))); assertEquals(1, store.size()); assertEquals(10L, store.get(10L).getId()); @@ -319,7 +443,8 @@ void runOwnedInitialLaunchRequestIdConflictsOnChangedOwnerOrTemplate() { @Test void runOwnedInitialLaunchRejectsWorldDescriptorMismatchAndRetainsIdentity() { - StartSessionRequest request = new StartSessionRequest(1L, 3L, "run-owned-mismatch", 42L); + StartSessionRequest request = + new StartSessionRequest(1L, 3L, "run-owned-mismatch", OWNER_ACCOUNT_UUID); AtomicReference worldState = configureRunOwnedWorld(request); doAnswer( invocation -> @@ -348,7 +473,8 @@ void runOwnedInitialLaunchRejectsWorldDescriptorMismatchAndRetainsIdentity() { @Test void runOwnedInitialLaunchRetainsTerminalIdentityAfterPreActivationFailure() { - StartSessionRequest request = new StartSessionRequest(1L, 3L, "run-owned-failed", 42L); + StartSessionRequest request = + new StartSessionRequest(1L, 3L, "run-owned-failed", OWNER_ACCOUNT_UUID); AtomicReference worldState = configureRunOwnedWorld(request); worldState.set( runOwnedWorldSnapshot( @@ -367,6 +493,49 @@ void runOwnedInitialLaunchRetainsTerminalIdentityAfterPreActivationFailure() { .activatePreparedWorldInstance(anyLong(), anyLong(), anyLong()); } + @Test + void runOwnedInitialLaunchRejectsNonCanonicalOwnerBeforeDependenciesOrMutation() { + for (String invalidOwner : + List.of( + "42", "00000000-0000-0000-0000-000000000000", "123E4567-E89B-12D3-A456-426614174000")) { + assertThrows( + IllegalArgumentException.class, + () -> + service.startRunOwnedInitialLaunch( + new StartSessionRequest(1L, 3L, "run-owned-invalid-owner", invalidOwner))); + } + + verify(gameDesignClient, never()).resolveLaunchDescriptor(anyLong(), anyLong(), anyString()); + verify(repository, never()).lockRunOwnedStartIdentity(anyLong(), anyString()); + verify(repository, never()).save(any(GameInstance.class)); + assertEquals(0, store.size()); + verifyNoInteractions(stateService); + verifyNoInteractions(worldManagementClient); + } + + @Test + void runOwnedInitialLaunchRejectsUnresolvedLegacyOwnerBeforeCreatingCandidate() { + StartSessionRequest request = + new StartSessionRequest(1L, 3L, "run-owned-legacy-owner", OWNER_ACCOUNT_UUID); + configureRunOwnedWorld(request); + persistLegacyOwner(7L, 1L, "v1", "RUNNING", 9_007_199_254_740_993L); + + LifecycleOutcomeException error = + assertThrows( + LifecycleOutcomeException.class, () -> service.startRunOwnedInitialLaunch(request)); + + assertEquals("OWNER_ACCOUNT_IDENTITY_UNAVAILABLE", error.code()); + assertEquals( + "cannot start a session while tenant owner identity evidence is active or uncertain", + error.detailMessage()); + assertEquals(1, store.size()); + assertEquals(9_007_199_254_740_993L, store.get(7L).getLegacyOwnerAccountId()); + verify(repository).findUnresolvedActiveOwnerRowsByTenantIdForUpdate(1L); + verify(repository, never()).save(any(GameInstance.class)); + verifyNoInteractions(stateService); + verifyNoInteractions(worldManagementClient); + } + @Test void startSessionLeavesScriptPinTupleAbsentUntilOwnerPinTransition() { doReturn( @@ -389,7 +558,8 @@ void startSessionLeavesScriptPinTupleAbsentUntilOwnerPinTransition() { .when(gameDesignClient) .resolveLaunchDescriptor(any(Long.class), any(Long.class), any()); - GameInstanceDto dto = service.startSession(new StartSessionRequest(1L, 3L, "cp-pinned", 42L)); + GameInstanceDto dto = + service.startSession(new StartSessionRequest(1L, 3L, "cp-pinned", OWNER_ACCOUNT_UUID)); assertNull(dto.scriptPatchVersion()); assertNull(dto.scriptPinEpoch()); @@ -431,7 +601,8 @@ void startSessionDoesNotCompensateWhenStartedMetricFails() { failingMeterRegistry, immediateTransactionOperations()); - StartSessionRequest request = new StartSessionRequest(1L, 3L, "cp-metric-failure", 42L); + StartSessionRequest request = + new StartSessionRequest(1L, 3L, "cp-metric-failure", OWNER_ACCOUNT_UUID); GameInstanceDto dto = service.startSession(request); @@ -442,7 +613,8 @@ void startSessionDoesNotCompensateWhenStartedMetricFails() { @Test void startSessionQuarantinesOwnerWhenWorldActivationFails() { - StartSessionRequest request = new StartSessionRequest(1L, 3L, "cp-activation-failure", 42L); + StartSessionRequest request = + new StartSessionRequest(1L, 3L, "cp-activation-failure", OWNER_ACCOUNT_UUID); when(worldManagementClient.activatePreparedWorldInstance(anyLong(), anyLong(), anyLong())) .thenReturn( net.firedevops.firemud.worldmanagement.v1.ActivatePreparedWorldInstanceResponse @@ -468,7 +640,8 @@ void startSessionQuarantinesOwnerWhenWorldActivationFails() { @Test void startSessionQuarantinesOwnerAfterAmbiguousWorldActivationResponse() { - StartSessionRequest request = new StartSessionRequest(1L, 3L, "cp-activation-timeout", 42L); + StartSessionRequest request = + new StartSessionRequest(1L, 3L, "cp-activation-timeout", OWNER_ACCOUNT_UUID); when(worldManagementClient.activatePreparedWorldInstance(anyLong(), anyLong(), anyLong())) .thenThrow(new IllegalStateException("activation response timed out")); @@ -484,7 +657,8 @@ void startSessionQuarantinesOwnerAfterAmbiguousWorldActivationResponse() { @Test void startSessionQuarantinesOwnerWhenRuntimeStateSaveFailsAfterActivation() { - StartSessionRequest request = new StartSessionRequest(1L, 3L, "cp-runtime-save-failure", 42L); + StartSessionRequest request = + new StartSessionRequest(1L, 3L, "cp-runtime-save-failure", OWNER_ACCOUNT_UUID); AtomicInteger saveCount = new AtomicInteger(); doAnswer( invocation -> { @@ -513,7 +687,8 @@ void startSessionQuarantinesOwnerWhenRuntimeStateSaveFailsAfterActivation() { @Test void startSessionQuarantinesOwnerWhenLocalFinalizationFailsAfterActivation() { - StartSessionRequest request = new StartSessionRequest(1L, 3L, "cp-finalization-failure", 42L); + StartSessionRequest request = + new StartSessionRequest(1L, 3L, "cp-finalization-failure", OWNER_ACCOUNT_UUID); doThrow(new IllegalStateException("local finalization failed")) .when(mapper) .toDto(any(GameInstance.class)); @@ -535,7 +710,7 @@ void startSessionQuarantinesOwnerWhenLocalFinalizationFailsAfterActivation() { @Test void startSessionFailsWhenWorldPreparationFails() { - StartSessionRequest request = new StartSessionRequest(1L, 3L, "cp-6", 42L); + StartSessionRequest request = new StartSessionRequest(1L, 3L, "cp-6", OWNER_ACCOUNT_UUID); when(worldManagementClient.prepareWorldInstance( anyLong(), anyLong(), @@ -569,7 +744,8 @@ void startSessionFailsWhenWorldPreparationFails() { @Test void startSessionUsesPreparationAuthorityErrorWhenPreparationTransportFails() { - StartSessionRequest request = new StartSessionRequest(1L, 3L, "cp-preparation-timeout", 42L); + StartSessionRequest request = + new StartSessionRequest(1L, 3L, "cp-preparation-timeout", OWNER_ACCOUNT_UUID); when(worldManagementClient.prepareWorldInstance( anyLong(), anyLong(), @@ -598,7 +774,8 @@ void startSessionUsesPreparationAuthorityErrorWhenPreparationTransportFails() { @Test void startSessionPreservesStartFailureWhenPreparedWorldCleanupTransportFails() { - StartSessionRequest request = new StartSessionRequest(1L, 3L, "cp-fail-prepared", 42L); + StartSessionRequest request = + new StartSessionRequest(1L, 3L, "cp-fail-prepared", OWNER_ACCOUNT_UUID); doThrow(new IllegalStateException("state save failed")).when(stateService).saveState(any()); when(worldManagementClient.failPreparedWorldInstance(anyLong(), anyLong(), anyLong(), any())) .thenThrow(new IllegalStateException("fail-prepared response timed out")); @@ -614,7 +791,8 @@ void startSessionPreservesStartFailureWhenPreparedWorldCleanupTransportFails() { @Test void startSessionFailsClosedWhenWorldPreparationResponseIsNull() { - StartSessionRequest request = new StartSessionRequest(1L, 3L, "cp-null-world", 42L); + StartSessionRequest request = + new StartSessionRequest(1L, 3L, "cp-null-world", OWNER_ACCOUNT_UUID); when(worldManagementClient.prepareWorldInstance( anyLong(), anyLong(), @@ -639,7 +817,8 @@ void startSessionFailsClosedWhenWorldPreparationResponseIsNull() { @Test void startSessionFailsClosedWhenWorldPreparationOmitsSnapshotAndError() { - StartSessionRequest request = new StartSessionRequest(1L, 3L, "cp-empty-world", 42L); + StartSessionRequest request = + new StartSessionRequest(1L, 3L, "cp-empty-world", OWNER_ACCOUNT_UUID); when(worldManagementClient.prepareWorldInstance( anyLong(), anyLong(), @@ -667,7 +846,8 @@ void startSessionFailsClosedWhenWorldPreparationOmitsSnapshotAndError() { @Test void startSessionFailsClosedWhenWorldPreparationScopeDoesNotMatch() { - StartSessionRequest request = new StartSessionRequest(1L, 3L, "cp-mismatched-world", 42L); + StartSessionRequest request = + new StartSessionRequest(1L, 3L, "cp-mismatched-world", OWNER_ACCOUNT_UUID); when(worldManagementClient.prepareWorldInstance( anyLong(), anyLong(), @@ -694,7 +874,8 @@ void startSessionFailsClosedWhenWorldPreparationScopeDoesNotMatch() { @Test void startSessionFailsClosedWhenWorldPreparationEpochIsNotPositive() { - StartSessionRequest request = new StartSessionRequest(1L, 3L, "cp-zero-world-epoch", 42L); + StartSessionRequest request = + new StartSessionRequest(1L, 3L, "cp-zero-world-epoch", OWNER_ACCOUNT_UUID); when(worldManagementClient.prepareWorldInstance( anyLong(), anyLong(), @@ -724,7 +905,8 @@ void startSessionFailsClosedWhenWorldPreparationEpochIsNotPositive() { }) void startSessionPrefixesMalformedWorldIdentifiersAndRetainsCause( String tenantId, String gameInstanceId, String fieldName) { - StartSessionRequest request = new StartSessionRequest(1L, 3L, "cp-malformed-world-id", 42L); + StartSessionRequest request = + new StartSessionRequest(1L, 3L, "cp-malformed-world-id", OWNER_ACCOUNT_UUID); when(worldManagementClient.prepareWorldInstance( anyLong(), anyLong(), @@ -751,7 +933,8 @@ void startSessionPrefixesMalformedWorldIdentifiersAndRetainsCause( @Test void startSessionFailsClosedWhenWorldPreparationStatusIsAlreadyActive() { - StartSessionRequest request = new StartSessionRequest(1L, 3L, "cp-active-world", 42L); + StartSessionRequest request = + new StartSessionRequest(1L, 3L, "cp-active-world", OWNER_ACCOUNT_UUID); doReturn( net.firedevops.firemud.worldmanagement.v1.PrepareWorldInstanceResponse.newBuilder() .setWorldInstance( @@ -801,9 +984,10 @@ void startSessionFailsClosedWhenWorldPreparationStatusIsAlreadyActive() { void startSessionWithReplacementRejectsKnownNonActiveWorldLifecycle( WorldInstanceLifecycleStatus status) { StartSessionRequest request = - new StartSessionRequest(2L, 3L, "cp-known-non-active-" + status.name(), 42L); - GameInstance existing = persistExisting(7L, 2L, "v1", null, 42L, "RUNNING"); - when(repository.findFirstByTenantIdAndOwnerAccountIdAndStatus(2L, 42L, "RUNNING")) + new StartSessionRequest(2L, 3L, "cp-known-non-active-" + status.name(), OWNER_ACCOUNT_UUID); + GameInstance existing = persistExisting(7L, 2L, "v1", null, OWNER_ACCOUNT_UUID, "RUNNING"); + when(repository.findFirstByTenantIdAndOwnerAccountIdAndStatus( + 2L, OWNER_ACCOUNT_UUID, "RUNNING")) .thenReturn(Optional.of(existing)); when(worldManagementClient.getWorldInstanceLifecycle(2L, 7L)) .thenReturn(worldLifecycleSnapshot("2", "7", 3L, status)); @@ -819,7 +1003,8 @@ void startSessionWithReplacementRejectsKnownNonActiveWorldLifecycle( @Test void startSessionFailsClosedWhenWorldActivationOmitsSnapshotAndError() { - StartSessionRequest request = new StartSessionRequest(1L, 3L, "cp-empty-activation", 42L); + StartSessionRequest request = + new StartSessionRequest(1L, 3L, "cp-empty-activation", OWNER_ACCOUNT_UUID); when(worldManagementClient.activatePreparedWorldInstance(anyLong(), anyLong(), anyLong())) .thenReturn( net.firedevops.firemud.worldmanagement.v1.ActivatePreparedWorldInstanceResponse @@ -834,7 +1019,7 @@ void startSessionFailsClosedWhenWorldActivationOmitsSnapshotAndError() { @Test void stopSessionFailsClosedWhenWorldTerminationOmitsSnapshotAndError() { - persistExisting(10L, 1L, "v1", null, 42L, "RUNNING"); + persistExisting(10L, 1L, "v1", null, OWNER_ACCOUNT_UUID, "RUNNING"); when(worldManagementClient.terminateWorldInstance( anyLong(), anyLong(), anyLong(), any(), any())) .thenReturn( @@ -850,14 +1035,16 @@ void stopSessionFailsClosedWhenWorldTerminationOmitsSnapshotAndError() { @Test void startSessionStopsExistingRunningSessionOnlyWithinTenantAndOwner() { - StartSessionRequest request = new StartSessionRequest(2L, 3L, "cp-2", 42L); - GameInstance existing = persistExisting(7L, 2L, "v1", null, 42L, "RUNNING"); - when(repository.findFirstByTenantIdAndOwnerAccountIdAndStatus(2L, 42L, "RUNNING")) + StartSessionRequest request = new StartSessionRequest(2L, 3L, "cp-2", OWNER_ACCOUNT_UUID); + GameInstance existing = persistExisting(7L, 2L, "v1", null, OWNER_ACCOUNT_UUID, "RUNNING"); + when(repository.findFirstByTenantIdAndOwnerAccountIdAndStatus( + 2L, OWNER_ACCOUNT_UUID, "RUNNING")) .thenReturn(Optional.of(existing)); GameInstanceDto dto = service.startSession(request, true); - verify(repository).findFirstByTenantIdAndOwnerAccountIdAndStatus(2L, 42L, "RUNNING"); + verify(repository) + .findFirstByTenantIdAndOwnerAccountIdAndStatus(2L, OWNER_ACCOUNT_UUID, "RUNNING"); verify(stateService, times(2)).saveState(any(GameInstanceDto.class)); verify(stateService).deleteState(2L, 7L); verify(worldManagementClient).getWorldInstanceLifecycle(2L, 7L); @@ -878,17 +1065,18 @@ void startSessionStopsExistingRunningSessionOnlyWithinTenantAndOwner() { @Test void startSessionWithoutReplacementLeavesExistingSessionRunning() { - StartSessionRequest request = new StartSessionRequest(2L, 3L, "cp-3", 42L); + StartSessionRequest request = new StartSessionRequest(2L, 3L, "cp-3", OWNER_ACCOUNT_UUID); service.startSession(request, false); - verify(repository, never()).findFirstByTenantIdAndOwnerAccountIdAndStatus(2L, 42L, "RUNNING"); + verify(repository, never()) + .findFirstByTenantIdAndOwnerAccountIdAndStatus(2L, OWNER_ACCOUNT_UUID, "RUNNING"); verify(stateService, times(2)).saveState(any(GameInstanceDto.class)); } @Test void stopSessionDeletesState() { - persistExisting(10L, 1L, "v1", null, 42L, "RUNNING"); + persistExisting(10L, 1L, "v1", null, OWNER_ACCOUNT_UUID, "RUNNING"); GameInstanceDto dto = service.stopSession(10L); @@ -903,7 +1091,7 @@ void stopSessionDeletesState() { @Test void stopSessionFinalizesLocallyWhenWorldIsAlreadyTerminated() { - persistExisting(10L, 1L, "v1", null, 42L, "RUNNING"); + persistExisting(10L, 1L, "v1", null, OWNER_ACCOUNT_UUID, "RUNNING"); when(worldManagementClient.getWorldInstanceLifecycle(1L, 10L)) .thenReturn( worldLifecycleSnapshot( @@ -923,7 +1111,7 @@ void stopSessionFinalizesLocallyWhenWorldIsAlreadyTerminated() { @Test void stopSessionMapsTerminationInProgressResponseToLifecycleOutcome() { - persistExisting(10L, 1L, "v1", null, 42L, "RUNNING"); + persistExisting(10L, 1L, "v1", null, OWNER_ACCOUNT_UUID, "RUNNING"); when(worldManagementClient.terminateWorldInstance( anyLong(), anyLong(), anyLong(), any(), any())) .thenReturn( @@ -949,7 +1137,7 @@ void stopSessionMapsTerminationInProgressResponseToLifecycleOutcome() { @Test void stopSessionKeepsSessionStoppedWhenFinalizationFailsAfterWorldTermination() { - persistExisting(10L, 1L, "v1", null, 42L, "RUNNING"); + persistExisting(10L, 1L, "v1", null, OWNER_ACCOUNT_UUID, "RUNNING"); AtomicInteger mapperCalls = new AtomicInteger(); doAnswer( invocation -> { @@ -971,7 +1159,7 @@ void stopSessionKeepsSessionStoppedWhenFinalizationFailsAfterWorldTermination() @Test void startSessionFailsFastWhenStateSaveFails() { - StartSessionRequest request = new StartSessionRequest(1L, 3L, "cp-4", 42L); + StartSessionRequest request = new StartSessionRequest(1L, 3L, "cp-4", OWNER_ACCOUNT_UUID); doThrow(new IllegalStateException("redis down")).when(stateService).saveState(any()); assertThrows(IllegalStateException.class, () -> service.startSession(request)); @@ -983,10 +1171,12 @@ void startSessionFailsFastWhenStateSaveFails() { @Test void startSessionWithReplacementRestoresExistingRunningStateWhenNewStateSaveFails() { - StartSessionRequest request = new StartSessionRequest(2L, 3L, "cp-5", 42L); + StartSessionRequest request = new StartSessionRequest(2L, 3L, "cp-5", OWNER_ACCOUNT_UUID); GameInstance existing = - persistExisting(7L, 2L, "v1", "patch-1", 42L, "RUNNING", 100L, 3L, "pin-request-1"); - when(repository.findFirstByTenantIdAndOwnerAccountIdAndStatus(2L, 42L, "RUNNING")) + persistExisting( + 7L, 2L, "v1", "patch-1", OWNER_ACCOUNT_UUID, "RUNNING", 100L, 3L, "pin-request-1"); + when(repository.findFirstByTenantIdAndOwnerAccountIdAndStatus( + 2L, OWNER_ACCOUNT_UUID, "RUNNING")) .thenReturn(Optional.of(existing)); AtomicInteger saveCount = new AtomicInteger(); doAnswer( @@ -1019,9 +1209,10 @@ void startSessionWithReplacementRestoresExistingRunningStateWhenNewStateSaveFail @Test void startSessionWithReplacementLeavesExistingSessionStoppingWhenTerminationFails() { - StartSessionRequest request = new StartSessionRequest(2L, 3L, "cp-5", 42L); - GameInstance existing = persistExisting(7L, 2L, "v1", null, 42L, "RUNNING"); - when(repository.findFirstByTenantIdAndOwnerAccountIdAndStatus(2L, 42L, "RUNNING")) + StartSessionRequest request = new StartSessionRequest(2L, 3L, "cp-5", OWNER_ACCOUNT_UUID); + GameInstance existing = persistExisting(7L, 2L, "v1", null, OWNER_ACCOUNT_UUID, "RUNNING"); + when(repository.findFirstByTenantIdAndOwnerAccountIdAndStatus( + 2L, OWNER_ACCOUNT_UUID, "RUNNING")) .thenReturn(Optional.of(existing)); when(worldManagementClient.terminateWorldInstance( anyLong(), anyLong(), anyLong(), any(), any())) @@ -1047,9 +1238,11 @@ void startSessionWithReplacementLeavesExistingSessionStoppingWhenTerminationFail @Test void startSessionWithReplacementFinalizesAlreadyTerminatedExistingSession() { - StartSessionRequest request = new StartSessionRequest(2L, 3L, "cp-terminated-replacement", 42L); - GameInstance existing = persistExisting(7L, 2L, "v1", null, 42L, "RUNNING"); - when(repository.findFirstByTenantIdAndOwnerAccountIdAndStatus(2L, 42L, "RUNNING")) + StartSessionRequest request = + new StartSessionRequest(2L, 3L, "cp-terminated-replacement", OWNER_ACCOUNT_UUID); + GameInstance existing = persistExisting(7L, 2L, "v1", null, OWNER_ACCOUNT_UUID, "RUNNING"); + when(repository.findFirstByTenantIdAndOwnerAccountIdAndStatus( + 2L, OWNER_ACCOUNT_UUID, "RUNNING")) .thenReturn(Optional.of(existing)); when(worldManagementClient.getWorldInstanceLifecycle(2L, 7L)) .thenReturn( @@ -1070,9 +1263,10 @@ void startSessionWithReplacementFinalizesAlreadyTerminatedExistingSession() { @Test void startSessionWithReplacementDoesNotRestoreAlreadyTerminatedExistingSessionOnFailure() { StartSessionRequest request = - new StartSessionRequest(2L, 3L, "cp-terminated-replacement-failure", 42L); - GameInstance existing = persistExisting(7L, 2L, "v1", null, 42L, "RUNNING"); - when(repository.findFirstByTenantIdAndOwnerAccountIdAndStatus(2L, 42L, "RUNNING")) + new StartSessionRequest(2L, 3L, "cp-terminated-replacement-failure", OWNER_ACCOUNT_UUID); + GameInstance existing = persistExisting(7L, 2L, "v1", null, OWNER_ACCOUNT_UUID, "RUNNING"); + when(repository.findFirstByTenantIdAndOwnerAccountIdAndStatus( + 2L, OWNER_ACCOUNT_UUID, "RUNNING")) .thenReturn(Optional.of(existing)); when(worldManagementClient.getWorldInstanceLifecycle(2L, 7L)) .thenReturn( @@ -1102,9 +1296,10 @@ void startSessionWithReplacementDoesNotRestoreAlreadyTerminatedExistingSessionOn @Test void startSessionWithReplacementLeavesExistingSessionStoppingWhenTerminationIsInProgress() { StartSessionRequest request = - new StartSessionRequest(2L, 3L, "cp-terminating-replacement", 42L); - GameInstance existing = persistExisting(7L, 2L, "v1", null, 42L, "RUNNING"); - when(repository.findFirstByTenantIdAndOwnerAccountIdAndStatus(2L, 42L, "RUNNING")) + new StartSessionRequest(2L, 3L, "cp-terminating-replacement", OWNER_ACCOUNT_UUID); + GameInstance existing = persistExisting(7L, 2L, "v1", null, OWNER_ACCOUNT_UUID, "RUNNING"); + when(repository.findFirstByTenantIdAndOwnerAccountIdAndStatus( + 2L, OWNER_ACCOUNT_UUID, "RUNNING")) .thenReturn(Optional.of(existing)); when(worldManagementClient.getWorldInstanceLifecycle(2L, 7L)) .thenReturn( @@ -1131,9 +1326,10 @@ void startSessionWithReplacementLeavesExistingSessionStoppingWhenTerminationIsIn @Test void startSessionWithReplacementRestoresExistingStateWhenWorldLifecyclePreflightFails() { StartSessionRequest request = - new StartSessionRequest(2L, 3L, "cp-world-preflight-failure", 42L); - GameInstance existing = persistExisting(7L, 2L, "v1", null, 42L, "RUNNING"); - when(repository.findFirstByTenantIdAndOwnerAccountIdAndStatus(2L, 42L, "RUNNING")) + new StartSessionRequest(2L, 3L, "cp-world-preflight-failure", OWNER_ACCOUNT_UUID); + GameInstance existing = persistExisting(7L, 2L, "v1", null, OWNER_ACCOUNT_UUID, "RUNNING"); + when(repository.findFirstByTenantIdAndOwnerAccountIdAndStatus( + 2L, OWNER_ACCOUNT_UUID, "RUNNING")) .thenReturn(Optional.of(existing)); when(worldManagementClient.getWorldInstanceLifecycle(2L, 7L)) .thenReturn( @@ -1166,8 +1362,9 @@ void startSessionWithReplacementRestoresExistingStateWhenWorldLifecyclePreflight @Test void startSessionDoesNotResurrectReplacedSessionWhenActivationFails() { - StartSessionRequest request = new StartSessionRequest(2L, 3L, "cp-activation-failure", 42L); - persistExisting(7L, 2L, "v1", null, 42L, "RUNNING"); + StartSessionRequest request = + new StartSessionRequest(2L, 3L, "cp-activation-failure", OWNER_ACCOUNT_UUID); + persistExisting(7L, 2L, "v1", null, OWNER_ACCOUNT_UUID, "RUNNING"); when(worldManagementClient.activatePreparedWorldInstance(anyLong(), anyLong(), anyLong())) .thenReturn( net.firedevops.firemud.worldmanagement.v1.ActivatePreparedWorldInstanceResponse @@ -1192,20 +1389,27 @@ void startSessionDoesNotResurrectReplacedSessionWhenActivationFails() { @Test void stopSessionFailsFastWhenStateDeleteFails() { - persistExisting(10L, 1L, "v1", null, 42L, "RUNNING"); + GameInstance retained = persistExisting(10L, 1L, "v1", null, OWNER_ACCOUNT_UUID, "RUNNING"); + retained.setOwnerAccountId(null); + retained.setLegacyOwnerAccountId(42L); + store.put(10L, copyOf(retained)); doThrow(new IllegalStateException("redis down")).when(stateService).deleteState(1L, 10L); assertThrows(IllegalStateException.class, () -> service.stopSession(10L)); verify(stateService).deleteState(1L, 10L); verify(worldManagementClient, never()).getWorldInstanceLifecycle(anyLong(), anyLong()); - verify(stateService).saveState(any(GameInstanceDto.class)); + ArgumentCaptor restoredState = ArgumentCaptor.forClass(GameInstanceDto.class); + verify(stateService).saveState(restoredState.capture()); + assertNull(restoredState.getValue().ownerAccountId()); assertEquals("RUNNING", store.get(10L).getStatus()); + assertNull(store.get(10L).getOwnerAccountId()); + assertEquals(42L, store.get(10L).getLegacyOwnerAccountId()); } @Test void stopSessionLeavesStoppingStateWhenWorldTerminationFailsAfterRequest() { - persistExisting(10L, 1L, "v1", null, 42L, "RUNNING"); + persistExisting(10L, 1L, "v1", null, OWNER_ACCOUNT_UUID, "RUNNING"); when(worldManagementClient.terminateWorldInstance( anyLong(), anyLong(), anyLong(), any(), any())) .thenReturn( @@ -1226,7 +1430,7 @@ void stopSessionLeavesStoppingStateWhenWorldTerminationFailsAfterRequest() { @Test void stopSessionRestoresExistingStateWhenWorldLifecyclePreflightFails() { - persistExisting(10L, 1L, "v1", null, 42L, "RUNNING"); + persistExisting(10L, 1L, "v1", null, OWNER_ACCOUNT_UUID, "RUNNING"); when(worldManagementClient.getWorldInstanceLifecycle(1L, 10L)) .thenReturn( net.firedevops.firemud.worldmanagement.v1.GetWorldInstanceLifecycleResponse.newBuilder() @@ -1250,9 +1454,34 @@ void stopSessionRestoresExistingStateWhenWorldLifecyclePreflightFails() { .terminateWorldInstance(anyLong(), anyLong(), anyLong(), anyString(), anyString()); } + @Test + void stopSessionCompensationPreservesUnmappedNumericOwnerEvidence() { + persistLegacyOwner(10L, 1L, "v1", "RUNNING", 9_007_199_254_740_993L); + when(worldManagementClient.getWorldInstanceLifecycle(1L, 10L)) + .thenReturn( + GetWorldInstanceLifecycleResponse.newBuilder() + .setError( + net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() + .setCode("WORLD_LIFECYCLE_UNAVAILABLE") + .setMessage("lifecycle read failed") + .build()) + .build()); + + assertThrows(IllegalStateException.class, () -> service.stopSession(10L)); + + assertEquals("RUNNING", store.get(10L).getStatus()); + assertNull(store.get(10L).getOwnerAccountId()); + assertEquals(9_007_199_254_740_993L, store.get(10L).getLegacyOwnerAccountId()); + verify(stateService).deleteState(1L, 10L); + verify(stateService) + .saveState(argThat(state -> state.id() == 10L && "RUNNING".equals(state.status()))); + verify(worldManagementClient, never()) + .terminateWorldInstance(anyLong(), anyLong(), anyLong(), anyString(), anyString()); + } + @Test void stopSessionUsesLifecycleAuthorityConstantWhenLifecycleReadTransportFails() { - persistExisting(10L, 1L, "v1", null, 42L, "RUNNING"); + persistExisting(10L, 1L, "v1", null, OWNER_ACCOUNT_UUID, "RUNNING"); when(worldManagementClient.getWorldInstanceLifecycle(1L, 10L)) .thenThrow(new IllegalStateException("lifecycle read timed out")); @@ -1266,7 +1495,7 @@ void stopSessionUsesLifecycleAuthorityConstantWhenLifecycleReadTransportFails() @Test void stopSessionLeavesStoppingStateWhenWorldTerminationIsInProgress() { - persistExisting(10L, 1L, "v1", null, 42L, "RUNNING"); + persistExisting(10L, 1L, "v1", null, OWNER_ACCOUNT_UUID, "RUNNING"); when(worldManagementClient.getWorldInstanceLifecycle(1L, 10L)) .thenReturn( net.firedevops.firemud.worldmanagement.v1.GetWorldInstanceLifecycleResponse.newBuilder() @@ -1303,7 +1532,7 @@ void stopSessionLeavesStoppingStateWhenWorldTerminationIsInProgress() { "WORLD_INSTANCE_LIFECYCLE_STATUS_FAILED_PRE_ACTIVATION" }) void stopSessionRejectsKnownNonActiveWorldLifecycle(WorldInstanceLifecycleStatus status) { - persistExisting(10L, 1L, "v1", null, 42L, "RUNNING"); + persistExisting(10L, 1L, "v1", null, OWNER_ACCOUNT_UUID, "RUNNING"); when(worldManagementClient.getWorldInstanceLifecycle(1L, 10L)) .thenReturn(worldLifecycleSnapshot("1", "10", 3L, status)); @@ -1355,12 +1584,25 @@ private void configureRepositoryPersistence() { ? Optional.of(copyOf(stored)) : Optional.empty(); }); + when(repository.findUnresolvedActiveOwnerRowsByTenantIdForUpdate(anyLong())) + .thenAnswer( + invocation -> { + Long tenantId = invocation.getArgument(0); + return store.values().stream() + .filter(instance -> tenantId.equals(instance.getTenantId())) + .filter(instance -> instance.getOwnerAccountId() == null) + .filter( + instance -> + instance.getStatus() == null || !"STOPPED".equals(instance.getStatus())) + .map(GameInstanceServiceImplTest::copyOf) + .toList(); + }); when(repository.findFirstByTenantIdAndOwnerAccountIdAndStatus( - any(Long.class), any(Long.class), any())) + any(Long.class), anyString(), any())) .thenAnswer( invocation -> { Long tenantId = invocation.getArgument(0); - Long ownerAccountId = invocation.getArgument(1); + String ownerAccountId = invocation.getArgument(1); String status = invocation.getArgument(2); return store.values().stream() .filter(instance -> tenantId.equals(instance.getTenantId())) @@ -1470,7 +1712,7 @@ private void configureLaunchPreflight() { @Test void startSessionFailsWhenPublishedAssetProofDoesNotMatchReleaseBundle() { - StartSessionRequest request = new StartSessionRequest(1L, 3L, "cp-proof", 42L); + StartSessionRequest request = new StartSessionRequest(1L, 3L, "cp-proof", OWNER_ACCOUNT_UUID); when(gameDesignClient.getVersionAssetArtifactState(any(Long.class), any(Long.class))) .thenReturn( GetVersionAssetArtifactStateResponse.newBuilder() @@ -1498,7 +1740,8 @@ void startSessionFailsWhenPublishedAssetProofDoesNotMatchReleaseBundle() { @Test void startSessionRejectsNonPositiveLaunchDescriptorTenantIdBeforeWorldPreparation() { - StartSessionRequest request = new StartSessionRequest(1L, 3L, "cp-launch-tenant", 42L); + StartSessionRequest request = + new StartSessionRequest(1L, 3L, "cp-launch-tenant", OWNER_ACCOUNT_UUID); doReturn( ResolveLaunchDescriptorResponse.newBuilder() .setLaunchDescriptor( @@ -1542,7 +1785,7 @@ void startSessionRejectsNonPositiveLaunchDescriptorTenantIdBeforeWorldPreparatio @Test void startSessionFailsWhenReleaseBundleSchemaIsUnsupported() { - StartSessionRequest request = new StartSessionRequest(1L, 3L, "cp-schema", 42L); + StartSessionRequest request = new StartSessionRequest(1L, 3L, "cp-schema", OWNER_ACCOUNT_UUID); when(gameDesignClient.getPublishedReleaseBundle(any(Long.class), any(Long.class))) .thenReturn( GetPublishedReleaseBundleResponse.newBuilder() @@ -1567,7 +1810,7 @@ void startSessionFailsWhenReleaseBundleSchemaIsUnsupported() { @Test void startSessionRejectsMalformedPreparedWorldInstanceGameInstanceIdBeforeActivation() { - StartSessionRequest request = new StartSessionRequest(1L, 3L, "cp-prep-id", 42L); + StartSessionRequest request = new StartSessionRequest(1L, 3L, "cp-prep-id", OWNER_ACCOUNT_UUID); doReturn( net.firedevops.firemud.worldmanagement.v1.PrepareWorldInstanceResponse.newBuilder() .setWorldInstance( @@ -1610,7 +1853,8 @@ void startSessionRejectsMalformedPreparedWorldInstanceGameInstanceIdBeforeActiva @Test void persistExistingPreservesScriptPinOwnerRequestIdInCopiedTuple() { GameInstance existing = - persistExisting(7L, 2L, "v1", "patch-1", 42L, "RUNNING", 100L, 3L, "pin-request-1"); + persistExisting( + 7L, 2L, "v1", "patch-1", OWNER_ACCOUNT_UUID, "RUNNING", 100L, 3L, "pin-request-1"); assertEquals(100L, existing.getScriptPatchBaseVersionId()); assertEquals(3L, existing.getScriptPinEpoch()); @@ -1848,7 +2092,7 @@ private GameInstance persistExisting( Long tenantId, String runtimeVersion, String scriptPatchVersion, - Long ownerAccountId, + String ownerAccountId, String status) { return persistExisting( id, tenantId, runtimeVersion, scriptPatchVersion, ownerAccountId, status, null, null); @@ -1859,7 +2103,7 @@ private GameInstance persistExisting( Long tenantId, String runtimeVersion, String scriptPatchVersion, - Long ownerAccountId, + String ownerAccountId, String status, Long scriptPinEpoch, String scriptPatchPinnedControlPlaneRequestId) { @@ -1875,12 +2119,24 @@ private GameInstance persistExisting( scriptPatchPinnedControlPlaneRequestId); } + private GameInstance persistLegacyOwner( + Long id, Long tenantId, String runtimeVersion, String status, Long legacyOwnerAccountId) { + GameInstance instance = new GameInstance(); + instance.setId(id); + instance.setTenantId(tenantId); + instance.setRuntimeVersion(runtimeVersion); + instance.setStatus(status); + instance.setLegacyOwnerAccountId(legacyOwnerAccountId); + store.put(id, copyOf(instance)); + return copyOf(instance); + } + private GameInstance persistExisting( Long id, Long tenantId, String runtimeVersion, String scriptPatchVersion, - Long ownerAccountId, + String ownerAccountId, String status, Long scriptPatchBaseVersionId, Long scriptPinEpoch, @@ -1918,6 +2174,7 @@ private static GameInstance copyOf(GameInstance instance) { copy.setGenerationConfigRevision(instance.getGenerationConfigRevision()); copy.setRemapSetId(instance.getRemapSetId()); copy.setOwnerAccountId(instance.getOwnerAccountId()); + copy.setLegacyOwnerAccountId(instance.getLegacyOwnerAccountId()); copy.setStatus(instance.getStatus()); copy.setRowVersion(instance.getRowVersion()); copy.setRunOwnedStartRequestId(instance.getRunOwnedStartRequestId()); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java index 6710e33f35..34f7587690 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java @@ -119,6 +119,8 @@ import org.springframework.transaction.support.TransactionOperations; class GameSessionControlPlaneGrpcServiceTest { + private static final String OWNER_ACCOUNT_UUID = "123e4567-e89b-12d3-a456-426614174000"; + private static AutomationScriptingControlPlaneClient automationScriptingControlPlaneClient() { AutomationScriptingControlPlaneClient client = Mockito.mock(AutomationScriptingControlPlaneClient.class); @@ -230,7 +232,7 @@ void setPinnedScriptPatchVersionAllowsAdminCaller() { instance.setScriptPatchPinnedBy("old-user"); instance.setScriptPatchPinnedReason("old-reason"); instance.setScriptPatchPinnedControlPlaneRequestId("req-0"); - instance.setOwnerAccountId(99L); + instance.setOwnerAccountId(OWNER_ACCOUNT_UUID); instance.setStatus("RUNNING"); Mockito.when(repository.findById(7L)).thenReturn(Optional.of(instance)); GameDesignClient gameDesign = gameDesignClient(); @@ -396,7 +398,7 @@ void getPinnedScriptPatchVersionReturnsPersistedRequestId() { instance.setScriptPatchPinnedAt(Instant.parse("2026-04-22T00:00:00Z")); instance.setScriptPatchPinnedBy("operator-1"); instance.setScriptPatchPinnedControlPlaneRequestId("req-99"); - instance.setOwnerAccountId(99L); + instance.setOwnerAccountId(OWNER_ACCOUNT_UUID); instance.setStatus("RUNNING"); Mockito.when(repository.findById(7L)).thenReturn(Optional.of(instance)); @@ -440,7 +442,7 @@ void getPinnedScriptPatchVersionRetainsMissingBaseErrorForLegacyPersistedPin() { instance.setScriptPatchPinnedAt(Instant.parse("2026-04-22T00:00:00Z")); instance.setScriptPatchPinnedBy("operator-1"); instance.setScriptPatchPinnedControlPlaneRequestId("req-99"); - instance.setOwnerAccountId(99L); + instance.setOwnerAccountId(OWNER_ACCOUNT_UUID); instance.setStatus("RUNNING"); Mockito.when(repository.findById(7L)).thenReturn(Optional.of(instance)); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java index 2a3018d957..14e42f91eb 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java @@ -67,9 +67,15 @@ import org.jooq.exception.DataAccessException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullSource; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.Mockito; class GameSessionGrpcServiceTest { + private static final String OWNER_ACCOUNT_UUID = "123e4567-e89b-12d3-a456-426614174000"; + private static final String OTHER_ACCOUNT_UUID = "f720d1f5-7f16-4e02-9340-d0a5e2345f67"; + @AfterEach void tearDown() { SessionContext.clear(); @@ -1889,14 +1895,25 @@ void startSessionReturnsId() { Mockito.when(ipLimiter.canAccept("127.0.0.1", null)).thenReturn(true); Mockito.when(ipLimiter.tryRegister(Mockito.anyString(), Mockito.anyLong())).thenReturn(true); SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - SessionContext.setContext("42", List.of(), Map.of("1", List.of("tenantAdmin"))); + SessionContext.setContext(OWNER_ACCOUNT_UUID, List.of(), Map.of("1", List.of("tenantAdmin"))); Mockito.when( gameInstanceService.startSession( Mockito.any(net.firedevops.firemud.gamesession.dto.StartSessionRequest.class), Mockito.eq(false))) .thenReturn( new GameInstanceDto( - 1L, 1L, "11", null, 7L, "ld-1", 11L, 77L, 77L, "genrev-11", 42L, "RUNNING")); + 1L, + 1L, + "11", + null, + 7L, + "ld-1", + 11L, + 77L, + 77L, + "genrev-11", + OWNER_ACCOUNT_UUID, + "RUNNING")); GameSessionGrpcService service = newService( pingService, @@ -1915,7 +1932,7 @@ void startSessionReturnsId() { .setGameTemplateId("7") .setControlPlaneRequestId("cp-1") .setClientIp("127.0.0.1") - .setOwnerAccountId("42") + .setOwnerAccountId(OWNER_ACCOUNT_UUID) .build(), new StreamObserver() { @Override @@ -1941,7 +1958,7 @@ public void onCompleted() {} request.tenantId().equals(1L) && request.gameTemplateId().equals(7L) && request.controlPlaneRequestId().equals("cp-1") - && request.ownerAccountId().equals(42L)), + && request.ownerAccountId().equals(OWNER_ACCOUNT_UUID)), Mockito.eq(false)); } @@ -2033,14 +2050,25 @@ void startSessionWithoutClientIpSkipsRegistration() { GameInstanceRepository gameInstanceRepository = Mockito.mock(GameInstanceRepository.class); TickService tickService = Mockito.mock(TickService.class); IpConnectionLimiter ipLimiter = Mockito.mock(IpConnectionLimiter.class); - SessionContext.setContext("42", List.of(), Map.of("1", List.of("tenantAdmin"))); + SessionContext.setContext(OWNER_ACCOUNT_UUID, List.of(), Map.of("1", List.of("tenantAdmin"))); Mockito.when( gameInstanceService.startSession( Mockito.any(net.firedevops.firemud.gamesession.dto.StartSessionRequest.class), Mockito.eq(false))) .thenReturn( new GameInstanceDto( - 1L, 1L, "11", null, 7L, "ld-1", 11L, 77L, 77L, "genrev-11", 42L, "RUNNING")); + 1L, + 1L, + "11", + null, + 7L, + "ld-1", + 11L, + 77L, + 77L, + "genrev-11", + OWNER_ACCOUNT_UUID, + "RUNNING")); SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); GameSessionGrpcService service = newService( @@ -2059,7 +2087,7 @@ void startSessionWithoutClientIpSkipsRegistration() { .setTenantId("1") .setGameTemplateId("7") .setControlPlaneRequestId("cp-1") - .setOwnerAccountId("42") + .setOwnerAccountId(OWNER_ACCOUNT_UUID) .build(), new StreamObserver() { @Override @@ -2092,14 +2120,25 @@ void startSessionRejectedWhenIpReservationFailsStopsInstance() { Mockito.when(ipLimiter.canAccept("1.2.3.4", null)).thenReturn(true); Mockito.when(ipLimiter.tryRegister("1.2.3.4", 1L)).thenReturn(false); SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - SessionContext.setContext("42", List.of(), Map.of("1", List.of("tenantAdmin"))); + SessionContext.setContext(OWNER_ACCOUNT_UUID, List.of(), Map.of("1", List.of("tenantAdmin"))); Mockito.when( gameInstanceService.startSession( Mockito.any(net.firedevops.firemud.gamesession.dto.StartSessionRequest.class), Mockito.eq(false))) .thenReturn( new GameInstanceDto( - 1L, 1L, "11", null, 7L, "ld-1", 11L, 77L, 77L, "genrev-11", 42L, "RUNNING")); + 1L, + 1L, + "11", + null, + 7L, + "ld-1", + 11L, + 77L, + 77L, + "genrev-11", + OWNER_ACCOUNT_UUID, + "RUNNING")); GameSessionGrpcService service = newService( pingService, @@ -2118,7 +2157,7 @@ void startSessionRejectedWhenIpReservationFailsStopsInstance() { .setGameTemplateId("7") .setControlPlaneRequestId("cp-1") .setClientIp("1.2.3.4") - .setOwnerAccountId("42") + .setOwnerAccountId(OWNER_ACCOUNT_UUID) .build(), new StreamObserver() { @Override @@ -2140,215 +2179,38 @@ public void onCompleted() {} } @Test - void startSessionRejectsAtIpPreflightWithoutStoppingExistingSession() { - PingService pingService = Mockito.mock(PingService.class); - GameInstanceService gameInstanceService = Mockito.mock(GameInstanceService.class); - FeatureFlagService featureFlagService = Mockito.mock(FeatureFlagService.class); - TextCommandInterpreter textCommandInterpreter = Mockito.mock(TextCommandInterpreter.class); - GameInstanceRepository gameInstanceRepository = Mockito.mock(GameInstanceRepository.class); - TickService tickService = Mockito.mock(TickService.class); - IpConnectionLimiter ipLimiter = Mockito.mock(IpConnectionLimiter.class); - GameInstance existing = new GameInstance(); - existing.setId(77L); - existing.setTenantId(1L); - existing.setOwnerAccountId(42L); - existing.setStatus("RUNNING"); - Mockito.when( - gameInstanceRepository.findFirstByTenantIdAndOwnerAccountIdAndStatus( - 1L, 42L, "RUNNING")) - .thenReturn(java.util.Optional.of(existing)); - Mockito.when(ipLimiter.canAccept("1.2.3.4", 77L)).thenReturn(false); - SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - SessionContext.setContext("42", List.of(), Map.of("1", List.of("tenantAdmin"))); - GameSessionGrpcService service = - newService( - pingService, - gameInstanceService, - featureFlagService, - textCommandInterpreter, - gameInstanceRepository, - tickService, - meterRegistry, - ipLimiter); - - AtomicReference ref = new AtomicReference<>(); - service.startSession( - StartSessionRequest.newBuilder() - .setTenantId("1") - .setGameTemplateId("7") - .setControlPlaneRequestId("cp-1") - .setClientIp("1.2.3.4") - .setOwnerAccountId("42") - .build(), - new StreamObserver() { - @Override - public void onNext(StartSessionResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) { - fail(t); - } - - @Override - public void onCompleted() {} - }); - - assertEquals("CONNECTION_LIMIT", ref.get().getError().getCode()); - Mockito.verify(gameInstanceService, Mockito.never()) - .startSession( - Mockito.any(net.firedevops.firemud.gamesession.dto.StartSessionRequest.class), - Mockito.anyBoolean()); - Mockito.verify(gameInstanceService, Mockito.never()).stopSession(Mockito.anyLong()); - Mockito.verify(ipLimiter, Mockito.never()).tryRegister(Mockito.anyString(), Mockito.anyLong()); + void startSessionReplacementRejectedBeforeIpAdmission() { + assertRunningSessionReplacementUnavailable("1.2.3.4", false, true, true, false); } @Test - void startSessionReplacementTransfersIpAndStopsOldSessionAfterSuccess() { - PingService pingService = Mockito.mock(PingService.class); - GameInstanceService gameInstanceService = Mockito.mock(GameInstanceService.class); - FeatureFlagService featureFlagService = Mockito.mock(FeatureFlagService.class); - TextCommandInterpreter textCommandInterpreter = Mockito.mock(TextCommandInterpreter.class); - GameInstanceRepository gameInstanceRepository = Mockito.mock(GameInstanceRepository.class); - TickService tickService = Mockito.mock(TickService.class); - IpConnectionLimiter ipLimiter = Mockito.mock(IpConnectionLimiter.class); - GameInstance existing = new GameInstance(); - existing.setId(77L); - existing.setTenantId(1L); - existing.setOwnerAccountId(42L); - existing.setStatus("RUNNING"); - Mockito.when( - gameInstanceRepository.findFirstByTenantIdAndOwnerAccountIdAndStatus( - 1L, 42L, "RUNNING")) - .thenReturn(java.util.Optional.of(existing)); - Mockito.when(ipLimiter.canAccept("1.2.3.4", 77L)).thenReturn(true); - Mockito.when(ipLimiter.transferRegistration("1.2.3.4", 77L, 88L)).thenReturn(true); - Mockito.when( - gameInstanceService.startSession( - Mockito.any(net.firedevops.firemud.gamesession.dto.StartSessionRequest.class), - Mockito.eq(false))) - .thenReturn( - new GameInstanceDto( - 88L, 1L, "11", null, 7L, "ld-1", 11L, 77L, 77L, "genrev-11", 42L, "RUNNING")); - SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - SessionContext.setContext("42", List.of(), Map.of("1", List.of("tenantAdmin"))); - GameSessionGrpcService service = - newService( - pingService, - gameInstanceService, - featureFlagService, - textCommandInterpreter, - gameInstanceRepository, - tickService, - meterRegistry, - ipLimiter); - - AtomicReference ref = new AtomicReference<>(); - service.startSession( - StartSessionRequest.newBuilder() - .setTenantId("1") - .setGameTemplateId("7") - .setControlPlaneRequestId("cp-1") - .setClientIp("1.2.3.4") - .setOwnerAccountId("42") - .build(), - new StreamObserver() { - @Override - public void onNext(StartSessionResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) { - fail(t); - } - - @Override - public void onCompleted() {} - }); - - assertEquals("88", ref.get().getSessionId()); - Mockito.verify(ipLimiter).transferRegistration("1.2.3.4", 77L, 88L); - Mockito.verify(ipLimiter, Mockito.never()).tryRegister(Mockito.anyString(), Mockito.anyLong()); - Mockito.verify(ipLimiter, Mockito.never()).release(77L); - Mockito.verify(gameInstanceService).stopSession(77L); + void startSessionReplacementRejectedBeforeIpTransferOrOldSessionTeardown() { + assertRunningSessionReplacementUnavailable("1.2.3.4", true, true, true, false); } @Test - void startSessionKeepsNewSessionWhenOldReplacementTeardownFails() { - PingService pingService = Mockito.mock(PingService.class); - GameInstanceService gameInstanceService = Mockito.mock(GameInstanceService.class); - FeatureFlagService featureFlagService = Mockito.mock(FeatureFlagService.class); - TextCommandInterpreter textCommandInterpreter = Mockito.mock(TextCommandInterpreter.class); - GameInstanceRepository gameInstanceRepository = Mockito.mock(GameInstanceRepository.class); - TickService tickService = Mockito.mock(TickService.class); - IpConnectionLimiter ipLimiter = Mockito.mock(IpConnectionLimiter.class); - GameInstance existing = new GameInstance(); - existing.setId(77L); - existing.setTenantId(1L); - existing.setOwnerAccountId(42L); - existing.setStatus("RUNNING"); - Mockito.when( - gameInstanceRepository.findFirstByTenantIdAndOwnerAccountIdAndStatus( - 1L, 42L, "RUNNING")) - .thenReturn(java.util.Optional.of(existing)); - Mockito.when(ipLimiter.canAccept("1.2.3.4", 77L)).thenReturn(true); - Mockito.when(ipLimiter.transferRegistration("1.2.3.4", 77L, 88L)).thenReturn(true); - Mockito.when( - gameInstanceService.startSession( - Mockito.any(net.firedevops.firemud.gamesession.dto.StartSessionRequest.class), - Mockito.eq(false))) - .thenReturn( - new GameInstanceDto( - 88L, 1L, "11", null, 7L, "ld-1", 11L, 77L, 77L, "genrev-11", 42L, "RUNNING")); - Mockito.doThrow(new IllegalStateException("Failed to stop old session")) - .when(gameInstanceService) - .stopSession(77L); - SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - SessionContext.setContext("42", List.of(), Map.of("1", List.of("tenantAdmin"))); - GameSessionGrpcService service = - newService( - pingService, - gameInstanceService, - featureFlagService, - textCommandInterpreter, - gameInstanceRepository, - tickService, - meterRegistry, - ipLimiter); - - AtomicReference ref = new AtomicReference<>(); - service.startSession( - StartSessionRequest.newBuilder() - .setTenantId("1") - .setGameTemplateId("7") - .setControlPlaneRequestId("cp-1") - .setClientIp("1.2.3.4") - .setOwnerAccountId("42") - .build(), - new StreamObserver() { - @Override - public void onNext(StartSessionResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) { - fail(t); - } + void startSessionReplacementRejectedBeforeOldSessionTeardownFailure() { + assertRunningSessionReplacementUnavailable("1.2.3.4", true, true, true, true); + } - @Override - public void onCompleted() {} - }); + @Test + void startSessionReplacementRejectedBeforeCandidateReservationFailure() { + assertRunningSessionReplacementUnavailable("1.2.3.4", true, false, false, false); + } - assertEquals("88", ref.get().getSessionId()); - assertFalse(ref.get().hasError()); - Mockito.verify(gameInstanceService).stopSession(77L); + @ParameterizedTest + @NullSource + @ValueSource(strings = {"", " "}) + void startSessionReplacementRejectedWithoutClientIp(String clientIp) { + assertRunningSessionReplacementUnavailable(clientIp, true, true, false, false); } - @Test - void startSessionFailedReplacementDoesNotStopExistingSession() { + private void assertRunningSessionReplacementUnavailable( + String clientIp, + boolean ipWouldAccept, + boolean transferWouldSucceed, + boolean candidateRegistrationWouldSucceed, + boolean oldSessionTeardownWouldFail) { PingService pingService = Mockito.mock(PingService.class); GameInstanceService gameInstanceService = Mockito.mock(GameInstanceService.class); FeatureFlagService featureFlagService = Mockito.mock(FeatureFlagService.class); @@ -2359,24 +2221,44 @@ void startSessionFailedReplacementDoesNotStopExistingSession() { GameInstance existing = new GameInstance(); existing.setId(77L); existing.setTenantId(1L); - existing.setOwnerAccountId(42L); + existing.setOwnerAccountId(OWNER_ACCOUNT_UUID); existing.setStatus("RUNNING"); Mockito.when( gameInstanceRepository.findFirstByTenantIdAndOwnerAccountIdAndStatus( - 1L, 42L, "RUNNING")) + 1L, OWNER_ACCOUNT_UUID, "RUNNING")) .thenReturn(java.util.Optional.of(existing)); - Mockito.when(ipLimiter.canAccept("1.2.3.4", 77L)).thenReturn(true); - Mockito.when(ipLimiter.transferRegistration("1.2.3.4", 77L, 88L)).thenReturn(false); - Mockito.when(ipLimiter.tryRegister("1.2.3.4", 88L)).thenReturn(false); + if (clientIp != null && !clientIp.isBlank()) { + Mockito.when(ipLimiter.canAccept(clientIp, 77L)).thenReturn(ipWouldAccept); + Mockito.when(ipLimiter.transferRegistration(clientIp, 77L, 88L)) + .thenReturn(transferWouldSucceed); + Mockito.when(ipLimiter.tryRegister(clientIp, 88L)) + .thenReturn(candidateRegistrationWouldSucceed); + } Mockito.when( gameInstanceService.startSession( Mockito.any(net.firedevops.firemud.gamesession.dto.StartSessionRequest.class), Mockito.eq(false))) .thenReturn( new GameInstanceDto( - 88L, 1L, "11", null, 7L, "ld-1", 11L, 77L, 77L, "genrev-11", 42L, "RUNNING")); + 88L, + 1L, + "11", + null, + 7L, + "ld-1", + 11L, + 77L, + 77L, + "genrev-11", + OWNER_ACCOUNT_UUID, + "RUNNING")); + if (oldSessionTeardownWouldFail) { + Mockito.doThrow(new IllegalStateException("Failed to stop old session")) + .when(gameInstanceService) + .stopSession(77L); + } SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - SessionContext.setContext("42", List.of(), Map.of("1", List.of("tenantAdmin"))); + SessionContext.setContext(OWNER_ACCOUNT_UUID, List.of(), Map.of("1", List.of("tenantAdmin"))); GameSessionGrpcService service = newService( pingService, @@ -2389,14 +2271,17 @@ void startSessionFailedReplacementDoesNotStopExistingSession() { ipLimiter); AtomicReference ref = new AtomicReference<>(); - service.startSession( + net.firedevops.firemud.gamesession.v1.StartSessionRequest.Builder requestBuilder = StartSessionRequest.newBuilder() .setTenantId("1") .setGameTemplateId("7") .setControlPlaneRequestId("cp-1") - .setClientIp("1.2.3.4") - .setOwnerAccountId("42") - .build(), + .setOwnerAccountId(OWNER_ACCOUNT_UUID); + if (clientIp != null) { + requestBuilder.setClientIp(clientIp); + } + service.startSession( + requestBuilder.build(), new StreamObserver() { @Override public void onNext(StartSessionResponse value) { @@ -2412,10 +2297,17 @@ public void onError(Throwable t) { public void onCompleted() {} }); - assertEquals("CONNECTION_LIMIT", ref.get().getError().getCode()); - Mockito.verify(gameInstanceService).stopSession(88L); - Mockito.verify(gameInstanceService, Mockito.never()).stopSession(77L); - Mockito.verify(ipLimiter, Mockito.never()).release(77L); + assertEquals("SESSION_REPLACEMENT_UNAVAILABLE", ref.get().getError().getCode()); + assertEquals("Replacing an active session is not supported", ref.get().getError().getMessage()); + assertEquals("", ref.get().getSessionId()); + assertEquals(77L, existing.getId()); + assertEquals(1L, existing.getTenantId()); + assertEquals(OWNER_ACCOUNT_UUID, existing.getOwnerAccountId()); + assertEquals("RUNNING", existing.getStatus()); + Mockito.verify(gameInstanceRepository) + .findFirstByTenantIdAndOwnerAccountIdAndStatus(1L, OWNER_ACCOUNT_UUID, "RUNNING"); + Mockito.verifyNoMoreInteractions(gameInstanceRepository); + Mockito.verifyNoInteractions(gameInstanceService, ipLimiter); } @Test @@ -2428,7 +2320,7 @@ void startSessionRuntimeFailureReturnsInBandInternalError() { TickService tickService = Mockito.mock(TickService.class); IpConnectionLimiter ipLimiter = Mockito.mock(IpConnectionLimiter.class); SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - SessionContext.setContext("42", List.of(), Map.of("1", List.of("tenantAdmin"))); + SessionContext.setContext(OWNER_ACCOUNT_UUID, List.of(), Map.of("1", List.of("tenantAdmin"))); Mockito.when( gameInstanceService.startSession( Mockito.any(net.firedevops.firemud.gamesession.dto.StartSessionRequest.class), @@ -2451,7 +2343,7 @@ void startSessionRuntimeFailureReturnsInBandInternalError() { .setTenantId("1") .setGameTemplateId("7") .setControlPlaneRequestId("cp-1") - .setOwnerAccountId("42") + .setOwnerAccountId(OWNER_ACCOUNT_UUID) .build(), new StreamObserver() { @Override @@ -2482,7 +2374,7 @@ void startSessionLifecycleConflictReturnsStructuredErrorDetail() { TickService tickService = Mockito.mock(TickService.class); IpConnectionLimiter ipLimiter = Mockito.mock(IpConnectionLimiter.class); SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - SessionContext.setContext("42", List.of(), Map.of("1", List.of("tenantAdmin"))); + SessionContext.setContext(OWNER_ACCOUNT_UUID, List.of(), Map.of("1", List.of("tenantAdmin"))); Mockito.when( gameInstanceService.startSession( Mockito.any(net.firedevops.firemud.gamesession.dto.StartSessionRequest.class), @@ -2507,7 +2399,7 @@ void startSessionLifecycleConflictReturnsStructuredErrorDetail() { .setTenantId("1") .setGameTemplateId("7") .setControlPlaneRequestId("cp-lifecycle") - .setOwnerAccountId("42") + .setOwnerAccountId(OWNER_ACCOUNT_UUID) .build(), new StreamObserver<>() { @Override @@ -2556,7 +2448,7 @@ void startSessionRejectsMalformedTenantId() { .setTenantId("abc") .setGameTemplateId("7") .setControlPlaneRequestId("cp-1") - .setOwnerAccountId("42") + .setOwnerAccountId(OWNER_ACCOUNT_UUID) .build(), new StreamObserver() { @Override @@ -2606,7 +2498,7 @@ void startSessionRejectsZeroTenantId() { .setTenantId("0") .setGameTemplateId("7") .setControlPlaneRequestId("cp-1") - .setOwnerAccountId("42") + .setOwnerAccountId(OWNER_ACCOUNT_UUID) .build(), new StreamObserver() { @Override @@ -2629,8 +2521,9 @@ public void onCompleted() {} .startSession(Mockito.any(), Mockito.anyBoolean()); } - @Test - void startSessionRejectsZeroOwnerAccountId() { + @ParameterizedTest + @ValueSource(strings = {"42", "not-a-uuid", "00000000-0000-0000-0000-000000000000"}) + void startSessionRejectsNonCanonicalOwnerAccountId(String ownerAccountId) { PingService pingService = Mockito.mock(PingService.class); GameInstanceService gameInstanceService = Mockito.mock(GameInstanceService.class); FeatureFlagService featureFlagService = Mockito.mock(FeatureFlagService.class); @@ -2656,7 +2549,7 @@ void startSessionRejectsZeroOwnerAccountId() { .setTenantId("1") .setGameTemplateId("7") .setControlPlaneRequestId("cp-1") - .setOwnerAccountId("0") + .setOwnerAccountId(ownerAccountId) .build(), new StreamObserver() { @Override @@ -2674,9 +2567,14 @@ public void onCompleted() {} }); assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("ownerAccountId must be positive", ref.get().getError().getMessage()); + assertEquals( + "ownerAccountId must be a canonical non-nil UUID", ref.get().getError().getMessage()); Mockito.verify(gameInstanceService, Mockito.never()) .startSession(Mockito.any(), Mockito.anyBoolean()); + Mockito.verify(gameInstanceRepository, Mockito.never()) + .findFirstByTenantIdAndOwnerAccountIdAndStatus( + Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); + Mockito.verify(ipLimiter, Mockito.never()).tryRegister(Mockito.anyString(), Mockito.anyLong()); } @Test @@ -2689,7 +2587,7 @@ void stopSessionRuntimeFailureReturnsInBandInternalError() { GameInstance instance = new GameInstance(); instance.setId(7L); instance.setTenantId(9L); - instance.setOwnerAccountId(42L); + instance.setOwnerAccountId(OWNER_ACCOUNT_UUID); instance.setRuntimeVersion("v1"); instance.setStatus("RUNNING"); Mockito.when(gameInstanceRepository.findById(7L)).thenReturn(java.util.Optional.of(instance)); @@ -2744,7 +2642,7 @@ void stopSessionLifecycleConflictReturnsStructuredErrorDetail() { GameInstance instance = new GameInstance(); instance.setId(7L); instance.setTenantId(9L); - instance.setOwnerAccountId(42L); + instance.setOwnerAccountId(OWNER_ACCOUNT_UUID); instance.setRuntimeVersion("v1"); instance.setStatus("RUNNING"); Mockito.when(gameInstanceRepository.findById(7L)).thenReturn(java.util.Optional.of(instance)); @@ -2891,7 +2789,7 @@ void restartSessionRuntimeFailureReturnsInBandInternalError() { GameInstance instance = new GameInstance(); instance.setId(7L); instance.setTenantId(9L); - instance.setOwnerAccountId(42L); + instance.setOwnerAccountId(OWNER_ACCOUNT_UUID); instance.setRuntimeVersion("v1"); instance.setStatus("RUNNING"); Mockito.when(gameInstanceRepository.findById(7L)).thenReturn(java.util.Optional.of(instance)); @@ -2945,7 +2843,7 @@ void restartSessionLifecycleConflictReturnsStructuredErrorDetail() { GameInstance instance = new GameInstance(); instance.setId(7L); instance.setTenantId(9L); - instance.setOwnerAccountId(42L); + instance.setOwnerAccountId(OWNER_ACCOUNT_UUID); instance.setRuntimeVersion("v1"); instance.setStatus("RUNNING"); Mockito.when(gameInstanceRepository.findById(7L)).thenReturn(java.util.Optional.of(instance)); @@ -3004,11 +2902,11 @@ void enqueueCommandRespectsRateLimit() { GameInstance instance = new GameInstance(); instance.setId(99L); instance.setTenantId(9L); - instance.setOwnerAccountId(42L); + instance.setOwnerAccountId(OWNER_ACCOUNT_UUID); instance.setRuntimeVersion("v1"); instance.setStatus("RUNNING"); Mockito.when(gameInstanceRepository.findById(99L)).thenReturn(java.util.Optional.of(instance)); - SessionContext.setContext("42", List.of(), Map.of()); + SessionContext.setContext(OWNER_ACCOUNT_UUID, List.of(), Map.of()); Mockito.when( textCommandInterpreter.interpret( Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean())) @@ -3065,11 +2963,11 @@ void enqueueCommandRuntimeFailureReturnsInternalErrorDetail() { GameInstance instance = new GameInstance(); instance.setId(99L); instance.setTenantId(9L); - instance.setOwnerAccountId(42L); + instance.setOwnerAccountId(OWNER_ACCOUNT_UUID); instance.setRuntimeVersion("v1"); instance.setStatus("RUNNING"); Mockito.when(gameInstanceRepository.findById(99L)).thenReturn(java.util.Optional.of(instance)); - SessionContext.setContext("42", List.of(), Map.of()); + SessionContext.setContext(OWNER_ACCOUNT_UUID, List.of(), Map.of()); Mockito.when( textCommandInterpreter.interpret( Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean())) @@ -3174,7 +3072,7 @@ void queryStateMissingSessionReturnsNotFoundErrorDetail() { GameInstance instance = new GameInstance(); instance.setId(7L); instance.setTenantId(9L); - instance.setOwnerAccountId(42L); + instance.setOwnerAccountId(OWNER_ACCOUNT_UUID); instance.setRuntimeVersion("v1"); instance.setStatus("RUNNING"); Mockito.when(gameInstanceRepository.findById(7L)).thenReturn(java.util.Optional.of(instance)); @@ -3272,7 +3170,7 @@ void queryStateRuntimeFailureReturnsInternalErrorDetail() { GameInstance instance = new GameInstance(); instance.setId(7L); instance.setTenantId(9L); - instance.setOwnerAccountId(42L); + instance.setOwnerAccountId(OWNER_ACCOUNT_UUID); instance.setRuntimeVersion("v1"); instance.setStatus("RUNNING"); Mockito.when(gameInstanceRepository.findById(7L)).thenReturn(java.util.Optional.of(instance)); @@ -3486,7 +3384,7 @@ void startSessionRejectsUnscopedCaller() { .setTenantId("1") .setGameTemplateId("7") .setControlPlaneRequestId("cp-1") - .setOwnerAccountId("42") + .setOwnerAccountId(OWNER_ACCOUNT_UUID) .build(), new StreamObserver() { @Override @@ -3508,6 +3406,9 @@ public void onCompleted() {} .startSession( Mockito.any(net.firedevops.firemud.gamesession.dto.StartSessionRequest.class), Mockito.anyBoolean()); + Mockito.verify(gameInstanceRepository, Mockito.never()) + .findFirstByTenantIdAndOwnerAccountIdAndStatus( + Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); Mockito.verify(ipLimiter, Mockito.never()).tryRegister(Mockito.anyString(), Mockito.anyLong()); } @@ -3521,7 +3422,7 @@ void startSessionRejectsOwnerMismatchWithinTenant() { TickService tickService = Mockito.mock(TickService.class); IpConnectionLimiter ipLimiter = Mockito.mock(IpConnectionLimiter.class); SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - SessionContext.setContext("99", List.of(), Map.of("1", List.of("tenantAdmin"))); + SessionContext.setContext(OTHER_ACCOUNT_UUID, List.of(), Map.of("1", List.of("tenantAdmin"))); GameSessionGrpcService service = newService( pingService, @@ -3539,7 +3440,7 @@ void startSessionRejectsOwnerMismatchWithinTenant() { .setTenantId("1") .setGameTemplateId("7") .setControlPlaneRequestId("cp-1") - .setOwnerAccountId("42") + .setOwnerAccountId(OWNER_ACCOUNT_UUID) .build(), new StreamObserver() { @Override @@ -3561,6 +3462,10 @@ public void onCompleted() {} .startSession( Mockito.any(net.firedevops.firemud.gamesession.dto.StartSessionRequest.class), Mockito.anyBoolean()); + Mockito.verify(gameInstanceRepository, Mockito.never()) + .findFirstByTenantIdAndOwnerAccountIdAndStatus( + Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); + Mockito.verify(ipLimiter, Mockito.never()).tryRegister(Mockito.anyString(), Mockito.anyLong()); } @Test @@ -3617,7 +3522,7 @@ void stopSessionRejectsWrongOwner() { GameInstance instance = new GameInstance(); instance.setId(7L); instance.setTenantId(9L); - instance.setOwnerAccountId(42L); + instance.setOwnerAccountId(OWNER_ACCOUNT_UUID); instance.setRuntimeVersion("v1"); instance.setStatus("RUNNING"); Mockito.when(gameInstanceRepository.findById(7L)).thenReturn(java.util.Optional.of(instance)); @@ -3657,6 +3562,57 @@ public void onCompleted() {} Mockito.verify(gameInstanceService, Mockito.never()).stopSession(Mockito.anyLong()); } + @Test + void stopSessionDoesNotMapRetainedNumericOwnerToCurrentAccount() { + PingService pingService = Mockito.mock(PingService.class); + GameInstanceService gameInstanceService = Mockito.mock(GameInstanceService.class); + FeatureFlagService featureFlagService = Mockito.mock(FeatureFlagService.class); + TextCommandInterpreter textCommandInterpreter = Mockito.mock(TextCommandInterpreter.class); + GameInstanceRepository gameInstanceRepository = Mockito.mock(GameInstanceRepository.class); + GameInstance instance = new GameInstance(); + instance.setId(7L); + instance.setTenantId(9L); + instance.setOwnerAccountId(null); + instance.setLegacyOwnerAccountId(42L); + instance.setRuntimeVersion("v1"); + instance.setStatus("RUNNING"); + Mockito.when(gameInstanceRepository.findById(7L)).thenReturn(java.util.Optional.of(instance)); + SessionContext.setContext(OWNER_ACCOUNT_UUID, List.of(), Map.of()); + TickService tickService = Mockito.mock(TickService.class); + IpConnectionLimiter ipLimiter = Mockito.mock(IpConnectionLimiter.class); + SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); + GameSessionGrpcService service = + newService( + pingService, + gameInstanceService, + featureFlagService, + textCommandInterpreter, + gameInstanceRepository, + tickService, + meterRegistry, + ipLimiter); + + service.stopSession( + net.firedevops.firemud.gamesession.v1.StopSessionRequest.newBuilder() + .setSessionId("7") + .build(), + new StreamObserver() { + @Override + public void onNext(net.firedevops.firemud.gamesession.v1.StopSessionResponse value) { + assertEquals("PERMISSION_DENIED", value.getError().getCode()); + } + + @Override + public void onError(Throwable t) { + fail(t); + } + + @Override + public void onCompleted() {} + }); + Mockito.verify(gameInstanceService, Mockito.never()).stopSession(Mockito.anyLong()); + } + @Test void stopSessionRejectsMalformedCurrentAccountClaim() { PingService pingService = Mockito.mock(PingService.class); @@ -3667,7 +3623,7 @@ void stopSessionRejectsMalformedCurrentAccountClaim() { GameInstance instance = new GameInstance(); instance.setId(7L); instance.setTenantId(9L); - instance.setOwnerAccountId(42L); + instance.setOwnerAccountId(OWNER_ACCOUNT_UUID); instance.setRuntimeVersion("v1"); instance.setStatus("RUNNING"); Mockito.when(gameInstanceRepository.findById(7L)).thenReturn(java.util.Optional.of(instance)); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TcpProxyServiceImplTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TcpProxyServiceImplTest.java index 0683c57483..6f837370b2 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TcpProxyServiceImplTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TcpProxyServiceImplTest.java @@ -25,6 +25,8 @@ @ExtendWith(OutputCaptureExtension.class) class TcpProxyServiceImplTest { + private static final String OWNER_ACCOUNT_UUID = "123e4567-e89b-12d3-a456-426614174000"; + @Test void notifyDisconnectWithUnprovedBindingLeavesLifecycleStateUnchanged() { GameInstanceRepository repository = Mockito.mock(GameInstanceRepository.class); @@ -489,7 +491,7 @@ private static GameInstance buildEntity(long sessionId, long tenantId) { entity.setScriptPatchVersion("patch"); entity.setScriptPinEpoch(3L); entity.setScriptPatchPinnedControlPlaneRequestId("pin-request-3"); - entity.setOwnerAccountId(99L); + entity.setOwnerAccountId(OWNER_ACCOUNT_UUID); entity.setStatus("RUNNING"); return entity; } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/GameInstanceTestFixturesTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/GameInstanceTestFixturesTest.java index 238bff4b37..b9bae13711 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/GameInstanceTestFixturesTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/GameInstanceTestFixturesTest.java @@ -7,6 +7,7 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.util.UUID; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; @@ -22,7 +23,10 @@ class GameInstanceTestFixturesTest { void insertRunningGameInstanceSeedsCoherentScriptPinTuple() { when(jdbc.queryForObject(anyString(), eq(Long.class), any(Object[].class))).thenReturn(1L); - assertThat(GameInstanceTestFixtures.insertRunningGameInstance(jdbc, 1L, 41L, 7L)).isEqualTo(1L); + assertThat( + GameInstanceTestFixtures.insertRunningGameInstance( + jdbc, 1L, GameInstanceTestFixtures.TEST_OWNER_ACCOUNT_UUID, 7L)) + .isEqualTo(1L); ArgumentCaptor sqlCaptor = ArgumentCaptor.forClass(String.class); ArgumentCaptor argumentsCaptor = ArgumentCaptor.forClass(Object[].class); @@ -32,7 +36,8 @@ void insertRunningGameInstanceSeedsCoherentScriptPinTuple() { .contains( "script_patch_version", "script_pin_epoch", - "script_patch_pinned_control_plane_request_id"); + "script_patch_pinned_control_plane_request_id", + "owner_account_uuid"); assertThat(argumentsCaptor.getValue()) .containsExactly( 1L, @@ -47,7 +52,7 @@ void insertRunningGameInstanceSeedsCoherentScriptPinTuple() { 700L, "genrev:test:7", null, - 41L, + UUID.fromString(GameInstanceTestFixtures.TEST_OWNER_ACCOUNT_UUID), "ACTIVE"); } } diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java index e404cbf03b..da1f1446c4 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java @@ -404,13 +404,13 @@ public GameInstanceDto startSession( @Override public GameInstanceDto stopSession(long sessionId) { return new GameInstanceDto( - sessionId, 0L, "stub", null, null, null, null, null, null, null, 0L, "STOPPED"); + sessionId, 0L, "stub", null, null, null, null, null, null, null, null, "STOPPED"); } @Override public GameInstanceDto restartSession(long sessionId) { return new GameInstanceDto( - sessionId, 0L, "stub", null, null, null, null, null, null, null, 0L, "RUNNING"); + sessionId, 0L, "stub", null, null, null, null, null, null, null, null, "RUNNING"); } @Override diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/GameInstanceTestFixtures.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/GameInstanceTestFixtures.java index a7308c3168..cf84ab0ade 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/GameInstanceTestFixtures.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/GameInstanceTestFixtures.java @@ -1,17 +1,19 @@ package net.firedevops.firemud.gamesession.test; import java.util.Optional; +import java.util.UUID; import org.springframework.jdbc.core.JdbcTemplate; public final class GameInstanceTestFixtures { public static final long PUBLISHED_RELEASE_BUNDLE_ID = 700L; + public static final String TEST_OWNER_ACCOUNT_UUID = "123e4567-e89b-12d3-a456-426614174000"; private static final long INITIAL_SCRIPT_PIN_EPOCH = 1L; private static final String INITIAL_SCRIPT_PIN_REQUEST_ID = "test-fixture-initial"; private GameInstanceTestFixtures() {} public static long insertRunningGameInstance( - JdbcTemplate jdbc, long tenantId, long ownerAccountId, long gameTemplateId) { + JdbcTemplate jdbc, long tenantId, String ownerAccountUuid, long gameTemplateId) { return Optional.ofNullable( jdbc.queryForObject( """ @@ -28,7 +30,7 @@ INSERT INTO game_instances ( version_state_epoch, generation_config_revision, remap_set_id, - owner_account_id, + owner_account_uuid, status ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id """, @@ -45,7 +47,7 @@ INSERT INTO game_instances ( 700L, "genrev:test:" + gameTemplateId, null, - ownerAccountId, + UUID.fromString(ownerAccountUuid), "ACTIVE")) .orElseThrow(() -> new IllegalStateException("Game instance insert did not return an id")); } diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java index 0ff9fc897c..8f492d97ce 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java @@ -8,6 +8,7 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.time.Instant; +import java.util.HashMap; import java.util.HexFormat; import java.util.LinkedHashMap; import java.util.List; @@ -63,6 +64,7 @@ public final class GameplayCrossServiceStack implements AutoCloseable { private final net.firedevops.firemud.entitymanagement.v1.ListRoomEntitiesResponse baselineRoomEntities; private final ListFriendPresenceResponse baselineFriendPresenceResponse; + private final Map syntheticManagementOwnerUuids = new HashMap<>(); private CrossServiceAppHarness.GameLogicHolder gameLogic; private final CrossServiceAppHarness.GameSessionHolder gameSession; private final boolean useDefaultDemoCatalogFixture; @@ -217,7 +219,7 @@ public long freshGameplayBaseline( } long gameInstanceId = GameInstanceTestFixtures.insertRunningGameInstance( - jdbc, tenantId, ownerAccountId, gameTemplateId); + jdbc, tenantId, GameInstanceTestFixtures.TEST_OWNER_ACCOUNT_UUID, gameTemplateId); seedRuntimeOwnership(tenantId, gameInstanceId); if (useDefaultDemoCatalogFixture) { bindDefaultDemoPointer(tenantId, gameInstanceId, ownerAccountId, gameTemplateId); @@ -916,7 +918,11 @@ public long insertRunningGameInstance( } long gameInstanceId = GameInstanceTestFixtures.insertRunningGameInstance( - jdbc, tenantId, accountId, gameTemplateId); + jdbc, + tenantId, + syntheticManagementOwnerUuids.computeIfAbsent( + accountId, ignored -> UUID.randomUUID().toString()), + gameTemplateId); seedRuntimeOwnership(tenantId, gameInstanceId); return gameInstanceId; }