From 73e19d7f8e74f8fa684c56ca0139ddac0751d31e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 07:49:37 +1300 Subject: [PATCH 01/11] Converge profile and session ownership on canonical Account UUIDs --- .github/workflows/ci.yml | 17 +- .../account-service/api-contracts.md | 2 + .../account-service/runtime-and-data.md | 2 + .../game-session-service/api-contracts.md | 14 +- .../game-session-service/runtime-and-data.md | 2 + .../player-access-and-session.md | 8 + .../controller/ProfileController.java | 7 +- .../accountservice/dto/ProfileDto.java | 2 +- .../dto/UpdateProfileRequest.java | 2 +- .../accountservice/mapper/ProfileMapper.java | 6 +- .../service/AccountService.java | 4 +- .../service/impl/AccountGrpcService.java | 18 +- .../service/impl/AccountServiceImpl.java | 78 +++++- .../src/main/resources/openapi.yaml | 17 +- ...ountAuthenticationUuidIntegrationTest.java | 139 +++++++++- .../controller/ProfileControllerTest.java | 76 +++++- .../service/impl/AccountGrpcServiceTest.java | 17 +- .../service/impl/AccountServiceImplTest.java | 150 ++++++++++- .../gamesession/data/TestDataSeeder.java | 19 +- .../gamesession/dto/GameInstanceDto.java | 4 +- .../gamesession/dto/StartSessionRequest.java | 3 +- .../gamesession/entity/GameInstance.java | 3 +- .../mapper/GameInstanceMapper.java | 9 - .../repository/GameInstanceRepository.java | 56 ++-- .../GameSessionRetainedTenantSnapshot.java | 19 +- ...ssionRetainedTenantSnapshotRepository.java | 8 +- .../service/impl/GameInstanceServiceImpl.java | 67 +++-- .../service/impl/GameSessionGrpcService.java | 23 +- .../V10__game_instance_owner_account_uuid.sql | 20 ++ .../src/main/resources/openapi.yaml | 6 +- ...GameSessionApplicationIntegrationTest.java | 5 +- .../GameSessionLoginIntegrationTest.java | 3 +- .../GameInstanceControllerTest.java | 51 +++- ...anceOwnerUuidMigrationIntegrationTest.java | 137 ++++++++++ ...nantSnapshotRepositoryIntegrationTest.java | 60 ++++- ...stanceServiceLifecycleIntegrationTest.java | 22 +- ...essionWebSocketHandlerIntegrationTest.java | 9 +- .../command/text/LoginCommandHandlerTest.java | 96 +++---- .../text/SessionResumptionFlowTest.java | 5 +- .../text/TextCommandInterpreterTest.java | 3 +- .../gamesession/data/TestDataSeederTest.java | 10 +- ...GameSessionRetainedTenantSnapshotTest.java | 118 ++++++++- .../impl/GameInstanceServiceImplTest.java | 200 +++++++++----- ...ameSessionControlPlaneGrpcServiceTest.java | 8 +- .../impl/GameSessionGrpcServiceTest.java | 243 ++++++++++++++---- .../service/impl/TcpProxyServiceImplTest.java | 4 +- .../test/GameInstanceTestFixturesTest.java | 10 +- .../gamesession/CrossServiceAppHarness.java | 4 +- .../test/GameInstanceTestFixtures.java | 7 +- .../GameplayCrossServiceStack.java | 11 +- 50 files changed, 1436 insertions(+), 368 deletions(-) create mode 100644 services/game-session-service/src/main/resources/db/migration/V10__game_instance_owner_account_uuid.sql create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameInstanceOwnerUuidMigrationIntegrationTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index efa5fbb068..d4cf20a0a8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -980,6 +980,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()' \ @@ -988,6 +989,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: | @@ -1003,7 +1016,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()' \ @@ -1013,6 +1026,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()' \ diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 7e0cc38129..6b88b367c0 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -54,6 +54,8 @@ This target contract is not complete in the current service. The existing `secur ## Implementation Status +`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). + Explicit playtest grants remain partial: current Account persistence and internal lookup can support a grant-backed admission read, but 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 are not implemented or end-to-end proved. 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 0ff96140e4..f2b7cc2c3b 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). + The account lifecycle state machine, global deletion preconditions, account-scoped versus tenant-scoped portable-data export split, separate safety-restriction lifecycles, hosting-billing authority, and future-marketplace `purchase_entitlement` substrate are the canonical target design. The current service has live identity/authentication, profile, external-link persistence, recovery/verification, payment, subscription, notification, and virtual-currency foundations, but lifecycle state transitions, genuine provider authentication, cross-service export, retained-record handling, complete account lock/platform-ban enforcement, purchased-entitlement fulfillment, and complete billing/subscription follow-through remain partial. The current account export returns only Account and profile rows, the tenant export includes excessive global Account fields, and the legacy synchronous deletion path is now blocked before any row deletion because complete provider/transfer clearance and retained-record handling are absent. The partial export behaviors still conflict with [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) and the bounded erasure workflow below. Account V22/V23 rewrite retained email values to canonical form and validate a canonical-email check, but compatibility with older binaries is unproved; the retained-data and rollout proof gap is tracked in [Shared Runtime Contracts and Persistence](../../../project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md#unit-5b-persistence-review-consequences). diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index db610f8ad2..2ded0f3bdd 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -48,18 +48,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. @@ -194,19 +194,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 ``` @@ -216,7 +216,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 87392bf33a..78860d9aad 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -10,6 +10,8 @@ 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. 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. Focused validation and actual PostgreSQL execution for this candidate are pending. + - V9 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 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/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 4bf879df5a..be52660dee 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,6 +6,14 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +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 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. 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. The corrected local Account/Game Session/Common Test Support full checks, both service JARs, formatting/static analysis and docs passed166tasks(25executed/141up-to-date). Game Session executed1,764unit,18non-PostgreSQL integration and1cross-service cases with zero failures/errors;17unit,133integration and33cross-service cases skipped. Account's508unit and Common Test Support's43unit executions passed in the preceding same-code run and were up-to-date in the final gate; all159Account PostgreSQL cases compiled/discovered but skipped locally. The first combined gate failed only in an unchanged World stub's unreserved free-port bind before its assertion; the three tests now use the existing port-zero/actual-bound-port interface and all passed. See the dated [AI observation](../ai-observations.md). These are local component checks, not fresh-image or live runtime proof. 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 7e7ab50552..355369f84a 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 @@ -830,6 +830,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(); } } @@ -908,9 +915,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( @@ -936,6 +944,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 07d20ef961..18924dd476 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; @@ -2060,12 +2061,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 @@ -2092,22 +2097,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) { @@ -2139,9 +2188,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 de8271449a..7ce59c6923 100644 --- a/services/account-service/src/main/resources/openapi.yaml +++ b/services/account-service/src/main/resources/openapi.yaml @@ -232,25 +232,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..1d383adf66 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-carrier-" + 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 = "profile-source-first-" + suffix; + String secondUsername = "profile-source-second-" + 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 3ce3da4826..8109dc0e4a 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 @@ -842,7 +842,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); @@ -880,6 +880,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)); } @@ -1445,10 +1452,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()); } @@ -1458,7 +1465,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<>(); @@ -1480,7 +1487,7 @@ 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 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 4cade89bb7..82b54869eb 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 @@ -5014,21 +5014,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 @@ -5049,31 +5089,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", @@ -5085,8 +5166,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); @@ -5094,12 +5180,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()); @@ -5118,19 +5212,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/TestDataSeeder.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/TestDataSeeder.java index 7a961bc516..170a24bbf9 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 @@ -2,11 +2,11 @@ import lombok.RequiredArgsConstructor; import net.firedevops.firemud.gamesession.entity.FeatureFlag; -import net.firedevops.firemud.gamesession.entity.GameInstance; import net.firedevops.firemud.gamesession.entity.GameManifest; import net.firedevops.firemud.gamesession.repository.FeatureFlagRepository; -import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; import net.firedevops.firemud.gamesession.repository.GameManifestRepository; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @@ -22,9 +22,10 @@ matchIfMissing = false) @RequiredArgsConstructor public class TestDataSeeder implements ApplicationRunner { + private static final Logger LOGGER = LoggerFactory.getLogger(TestDataSeeder.class); + private final GameManifestRepository gameManifestRepository; private final FeatureFlagRepository featureFlagRepository; - private final GameInstanceRepository gameInstanceRepository; @Override @Transactional @@ -45,14 +46,8 @@ public void run(ApplicationArguments args) { flag.setEnabled(true); featureFlagRepository.save(flag); - GameInstance instance = - gameInstanceRepository - .findFirstByTenantIdAndOwnerAccountIdAndStatus(1L, 1L, "RUNNING") - .orElseGet(GameInstance::new); - instance.setTenantId(1L); - instance.setRuntimeVersion("v1.0.0"); - instance.setOwnerAccountId(1L); - instance.setStatus("RUNNING"); - gameInstanceRepository.save(instance); + LOGGER.warn( + "Skipping demo game instance seed: TestDataSeeder has no authoritative Account UUID" + + " source"); } } 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 8c140100dc..1e3aa5014e 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; } 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 3b73a0c8a9..23874b86ad 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 @@ -12,13 +12,4 @@ public interface GameInstanceMapper { source = "scriptPatchPinnedControlPlaneRequestId") @Mapping(target = "scriptPatchBaseVersionId", source = "scriptPatchBaseVersionId") GameInstanceDto toDto(GameInstance entity); - - @Mapping(target = "scriptPatchBaseVersionId", source = "scriptPatchBaseVersionId") - @Mapping(target = "scriptPatchPinnedAt", ignore = true) - @Mapping(target = "scriptPinEpoch", ignore = true) - @Mapping(target = "scriptPatchPinnedBy", ignore = true) - @Mapping(target = "scriptPatchPinnedReason", ignore = true) - @Mapping(target = "scriptPatchPinnedControlPlaneRequestId", ignore = true) - @Mapping(target = "rowVersion", 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 8e886dc271..d3eeea9a7d 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 }; @@ -88,13 +90,14 @@ 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); @@ -107,30 +110,25 @@ public List findByStatus(String status) { .fetch(this::toEntity); } - public List findByTenantIdAndOwnerAccountIdInAndStatus( - Long tenantId, Collection ownerAccountIds, String status) { - if (ownerAccountIds == null || ownerAccountIds.isEmpty()) { - return List.of(); - } - return selectGameInstances() - .where( - GAME_INSTANCES - .TENANT_ID - .eq(tenantId) - .and(GAME_INSTANCES.OWNER_ACCOUNT_ID.in(ownerAccountIds)) - .and(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(); @@ -161,7 +159,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.ROW_VERSION, nextRowVersion) .where( @@ -838,7 +836,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()); @@ -856,7 +854,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()); } @@ -880,9 +879,18 @@ 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)); 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 e9ed0ced6b..97cfd671b7 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 @@ -20,6 +20,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.SessionStateService; import net.firedevops.firemud.worldmanagement.v1.ActivatePreparedWorldInstanceResponse; @@ -141,6 +142,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(), @@ -167,7 +174,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 = @@ -230,7 +239,9 @@ public GameInstanceDto startSession(StartSessionRequest request, boolean replace @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 { @@ -258,7 +269,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; } } @@ -266,8 +277,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 { @@ -275,7 +287,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; } } @@ -284,7 +296,7 @@ private StartSessionStage stageStartSession( StartSessionRequest request, ResolvedLaunchDescriptor resolvedLaunchDescriptor, boolean replaceExistingFirst) { - GameInstanceDto existingRunningState = null; + GameInstanceSnapshot existingRunningState = null; if (replaceExistingFirst) { existingRunningState = repository @@ -295,7 +307,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); @@ -316,7 +328,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) { @@ -337,12 +349,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; @@ -357,12 +369,12 @@ 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); + GameInstanceSnapshot previousState = snapshot(instance); instance.setStatus(STATUS_STARTING); repository.save(instance); return previousState; @@ -408,7 +420,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", @@ -422,7 +436,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")); @@ -492,9 +506,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", @@ -518,7 +533,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")); @@ -529,7 +544,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", @@ -544,13 +560,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(), @@ -570,7 +590,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()); @@ -585,6 +607,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); } @@ -980,8 +1003,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 896ca96837..4962e3be54 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 @@ -16,6 +16,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; @@ -137,7 +138,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"); @@ -228,8 +229,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) { @@ -238,7 +242,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; @@ -437,7 +441,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"); @@ -782,6 +788,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__game_instance_owner_account_uuid.sql b/services/game-session-service/src/main/resources/db/migration/V10__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__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 b1f030b8eb..b409dff4f6 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..5e9252d34c --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameInstanceOwnerUuidMigrationIntegrationTest.java @@ -0,0 +1,137 @@ +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.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("9")) + .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"); + } + } + + 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/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 8c49a8113f..e8934c9fad 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 @@ -122,6 +122,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; @@ -400,22 +401,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(22L); - 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/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 e837236084..c02102c9a6 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 @@ -49,6 +49,7 @@ @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 final GameInstanceRepository gameInstanceRepository = Mockito.mock(GameInstanceRepository.class); @@ -104,7 +105,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); @@ -144,7 +145,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()); @@ -163,7 +164,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( @@ -255,7 +256,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); @@ -280,7 +281,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); @@ -308,7 +309,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); @@ -368,7 +369,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, @@ -426,7 +427,7 @@ void bareLoginDoesNotPromoteVerifiedFirstPartyContextWithoutAccountExchange() { assertEquals("shell-realm", 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() @@ -455,7 +456,7 @@ void bareLoginForDifferentVerifiedSubjectClearsOldAccountBeforeReturningUnavaila "gateway-account-b"); when(firstPartyConnectContextRegistry.find(1L)) .thenReturn(Optional.of(verifiedAccountBContext)); - GameInstance instance = buildInstance(2L, 33L, 77L); + GameInstance instance = buildInstance(2L, 33L, OWNER_ACCOUNT_UUID); when(gameInstanceRepository.findById(2L)).thenReturn(Optional.of(instance)); when(gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(33L, 2L)) .thenReturn(List.of(pointer("demo", "production", 33L, 2L, 1L))); @@ -510,7 +511,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); @@ -547,7 +548,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))); @@ -584,7 +585,7 @@ void credentialLoginPreservesBootstrapTargetButDropsSubjectBoundConnectScope() { 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); stubSessionContext( new SessionContext( 1L, @@ -630,7 +631,7 @@ void credentialLoginPreservesBootstrapTargetButDropsSubjectBoundConnectScope() { @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, @@ -701,7 +702,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, @@ -749,7 +750,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); @@ -776,7 +778,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); @@ -801,7 +804,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); @@ -817,7 +821,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); @@ -828,7 +833,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( @@ -863,7 +868,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); @@ -889,7 +894,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)); @@ -912,7 +917,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); @@ -931,7 +936,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( @@ -999,7 +1004,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( @@ -1089,7 +1094,8 @@ void verifiedConnectForDifferentTenantClearsPriorGameplayBindingWithoutPromoting "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, OWNER_ACCOUNT_UUID))); LoginCommandHandlingResult result = handler.handle("1", command, false); @@ -1123,7 +1129,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( @@ -1150,7 +1156,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))); @@ -1194,7 +1200,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); @@ -1227,7 +1233,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( @@ -1268,7 +1274,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( @@ -1282,7 +1288,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 @@ -1300,7 +1306,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); @@ -1327,7 +1333,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); @@ -1353,7 +1359,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); @@ -1385,7 +1391,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); @@ -1420,7 +1426,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); @@ -1448,7 +1454,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); @@ -1475,7 +1481,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); @@ -1499,7 +1505,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); @@ -1526,7 +1532,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); @@ -1553,7 +1559,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); @@ -1576,7 +1582,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); @@ -1598,7 +1604,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); @@ -1617,7 +1623,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); @@ -1625,7 +1631,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); 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 6bd5db2d25..278d75e577 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 @@ -73,6 +73,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"; private static final String LOOK_PAYLOAD = "LOOK"; @@ -155,7 +156,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())) @@ -565,7 +566,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 6b58e72501..336ee036cb 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 @@ -87,6 +87,7 @@ @SuppressWarnings("unchecked") class TextCommandInterpreterTest { + private static final String OWNER_ACCOUNT_UUID = "123e4567-e89b-12d3-a456-426614174000"; private final CommandService commandService = Mockito.mock(CommandService.class); private final GameLogicClient gameLogicClient = Mockito.mock(GameLogicClient.class); private final EntityManagementClient entityManagementClient = @@ -340,7 +341,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/TestDataSeederTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/TestDataSeederTest.java index 0ec9ea647c..260adbbfe9 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 @@ -5,10 +5,8 @@ import static org.mockito.Mockito.when; import net.firedevops.firemud.gamesession.entity.FeatureFlag; -import net.firedevops.firemud.gamesession.entity.GameInstance; import net.firedevops.firemud.gamesession.entity.GameManifest; import net.firedevops.firemud.gamesession.repository.FeatureFlagRepository; -import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; import net.firedevops.firemud.gamesession.repository.GameManifestRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -21,14 +19,12 @@ class TestDataSeederTest { @Mock GameManifestRepository gameManifestRepository; @Mock FeatureFlagRepository featureFlagRepository; - @Mock GameInstanceRepository gameInstanceRepository; private TestDataSeeder seeder; @BeforeEach void setup() { - seeder = - new TestDataSeeder(gameManifestRepository, featureFlagRepository, gameInstanceRepository); + seeder = new TestDataSeeder(gameManifestRepository, featureFlagRepository); } @Test @@ -36,13 +32,9 @@ void runSeedsAndReassertsCanonicalRuntimeData() throws Exception { when(gameManifestRepository.findAll()).thenReturn(java.util.List.of()); when(featureFlagRepository.findByTenantIdAndName(1L, "double_xp")) .thenReturn(java.util.Optional.empty()); - when(gameInstanceRepository.findFirstByTenantIdAndOwnerAccountIdAndStatus(1L, 1L, "RUNNING")) - .thenReturn(java.util.Optional.empty()); - seeder.run(new DefaultApplicationArguments(new String[] {})); verify(gameManifestRepository).save(any(GameManifest.class)); verify(featureFlagRepository).save(any(FeatureFlag.class)); - verify(gameInstanceRepository).save(any(GameInstance.class)); } } 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 8fe731a62a..9f6e32aa16 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 @@ -46,6 +46,8 @@ import org.mockito.ArgumentCaptor; class GameInstanceServiceImplTest { + private static final String OWNER_ACCOUNT_UUID = "123e4567-e89b-12d3-a456-426614174000"; + private GameInstanceRepository repository; private GameInstanceMapper mapper; private SessionStateService stateService; @@ -73,7 +75,7 @@ void legacyDtoConstructorRejectsNonblankPatchWithoutCompleteTuple() { 12L, 13L, "generation-1", - 42L, + OWNER_ACCOUNT_UUID, "RUNNING")); assertEquals( @@ -112,12 +114,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()); @@ -125,6 +128,23 @@ 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()); + } + @Test void startSessionLeavesScriptPinTupleAbsentUntilOwnerPinTransition() { doReturn( @@ -147,7 +167,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()); @@ -189,7 +210,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); @@ -200,7 +222,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 @@ -226,7 +249,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")); @@ -242,7 +266,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 -> { @@ -271,7 +296,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)); @@ -293,7 +319,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(), @@ -327,7 +353,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(), @@ -356,7 +383,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")); @@ -372,7 +400,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(), @@ -397,7 +426,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(), @@ -425,7 +455,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(), @@ -452,7 +483,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(), @@ -482,7 +514,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(), @@ -509,7 +542,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( @@ -559,9 +593,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)); @@ -577,7 +612,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 @@ -592,7 +628,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( @@ -608,14 +644,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); @@ -636,17 +674,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); @@ -661,7 +700,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( @@ -681,7 +720,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( @@ -707,7 +746,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 -> { @@ -729,7 +768,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)); @@ -741,10 +780,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( @@ -777,9 +818,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())) @@ -805,9 +847,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( @@ -828,9 +872,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( @@ -860,9 +905,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( @@ -889,9 +935,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( @@ -924,8 +971,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 @@ -950,20 +998,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( @@ -984,7 +1039,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() @@ -1010,7 +1065,7 @@ void stopSessionRestoresExistingStateWhenWorldLifecyclePreflightFails() { @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")); @@ -1024,7 +1079,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() @@ -1061,7 +1116,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)); @@ -1093,11 +1148,11 @@ private void configureRepositoryPersistence() { return stored == null ? Optional.empty() : Optional.of(copyOf(stored)); }); 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())) @@ -1207,7 +1262,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() @@ -1235,7 +1290,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( @@ -1279,7 +1335,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() @@ -1304,7 +1360,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( @@ -1347,7 +1403,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()); @@ -1509,7 +1566,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); @@ -1520,7 +1577,7 @@ private GameInstance persistExisting( Long tenantId, String runtimeVersion, String scriptPatchVersion, - Long ownerAccountId, + String ownerAccountId, String status, Long scriptPinEpoch, String scriptPatchPinnedControlPlaneRequestId) { @@ -1541,7 +1598,7 @@ private GameInstance persistExisting( Long tenantId, String runtimeVersion, String scriptPatchVersion, - Long ownerAccountId, + String ownerAccountId, String status, Long scriptPatchBaseVersionId, Long scriptPinEpoch, @@ -1571,6 +1628,7 @@ private static GameInstance copyOf(GameInstance instance) { copy.setScriptPatchPinnedControlPlaneRequestId( instance.getScriptPatchPinnedControlPlaneRequestId()); copy.setOwnerAccountId(instance.getOwnerAccountId()); + copy.setLegacyOwnerAccountId(instance.getLegacyOwnerAccountId()); copy.setStatus(instance.getStatus()); return copy; } 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 33d48d2244..e8184fdde2 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 @@ -117,6 +117,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); @@ -234,7 +236,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(); @@ -400,7 +402,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)); @@ -444,7 +446,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 5fb3627876..f3b750a238 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 @@ -62,9 +62,14 @@ import net.firedevops.firemud.gamesession.v1.ToggleFeatureFlagResponse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +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(); @@ -837,14 +842,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, @@ -863,7 +879,7 @@ void startSessionReturnsId() { .setGameTemplateId("7") .setControlPlaneRequestId("cp-1") .setClientIp("127.0.0.1") - .setOwnerAccountId("42") + .setOwnerAccountId(OWNER_ACCOUNT_UUID) .build(), new StreamObserver() { @Override @@ -889,7 +905,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)); } @@ -981,14 +997,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( @@ -1007,7 +1034,7 @@ void startSessionWithoutClientIpSkipsRegistration() { .setTenantId("1") .setGameTemplateId("7") .setControlPlaneRequestId("cp-1") - .setOwnerAccountId("42") + .setOwnerAccountId(OWNER_ACCOUNT_UUID) .build(), new StreamObserver() { @Override @@ -1040,14 +1067,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, @@ -1066,7 +1104,7 @@ void startSessionRejectedWhenIpReservationFailsStopsInstance() { .setGameTemplateId("7") .setControlPlaneRequestId("cp-1") .setClientIp("1.2.3.4") - .setOwnerAccountId("42") + .setOwnerAccountId(OWNER_ACCOUNT_UUID) .build(), new StreamObserver() { @Override @@ -1099,15 +1137,15 @@ void startSessionRejectsAtIpPreflightWithoutStoppingExistingSession() { 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(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"))); GameSessionGrpcService service = newService( pingService, @@ -1126,7 +1164,7 @@ void startSessionRejectsAtIpPreflightWithoutStoppingExistingSession() { .setGameTemplateId("7") .setControlPlaneRequestId("cp-1") .setClientIp("1.2.3.4") - .setOwnerAccountId("42") + .setOwnerAccountId(OWNER_ACCOUNT_UUID) .build(), new StreamObserver() { @Override @@ -1164,11 +1202,11 @@ void startSessionReplacementTransfersIpAndStopsOldSessionAfterSuccess() { 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(true); @@ -1178,9 +1216,20 @@ void startSessionReplacementTransfersIpAndStopsOldSessionAfterSuccess() { 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")); 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, @@ -1199,7 +1248,7 @@ void startSessionReplacementTransfersIpAndStopsOldSessionAfterSuccess() { .setGameTemplateId("7") .setControlPlaneRequestId("cp-1") .setClientIp("1.2.3.4") - .setOwnerAccountId("42") + .setOwnerAccountId(OWNER_ACCOUNT_UUID) .build(), new StreamObserver() { @Override @@ -1235,11 +1284,11 @@ void startSessionKeepsNewSessionWhenOldReplacementTeardownFails() { 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(true); @@ -1249,12 +1298,23 @@ void startSessionKeepsNewSessionWhenOldReplacementTeardownFails() { 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")); 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, @@ -1273,7 +1333,7 @@ void startSessionKeepsNewSessionWhenOldReplacementTeardownFails() { .setGameTemplateId("7") .setControlPlaneRequestId("cp-1") .setClientIp("1.2.3.4") - .setOwnerAccountId("42") + .setOwnerAccountId(OWNER_ACCOUNT_UUID) .build(), new StreamObserver() { @Override @@ -1307,11 +1367,11 @@ 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); @@ -1322,9 +1382,20 @@ void startSessionFailedReplacementDoesNotStopExistingSession() { 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")); 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, @@ -1343,7 +1414,7 @@ void startSessionFailedReplacementDoesNotStopExistingSession() { .setGameTemplateId("7") .setControlPlaneRequestId("cp-1") .setClientIp("1.2.3.4") - .setOwnerAccountId("42") + .setOwnerAccountId(OWNER_ACCOUNT_UUID) .build(), new StreamObserver() { @Override @@ -1376,7 +1447,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), @@ -1399,7 +1470,7 @@ void startSessionRuntimeFailureReturnsInBandInternalError() { .setTenantId("1") .setGameTemplateId("7") .setControlPlaneRequestId("cp-1") - .setOwnerAccountId("42") + .setOwnerAccountId(OWNER_ACCOUNT_UUID) .build(), new StreamObserver() { @Override @@ -1430,7 +1501,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), @@ -1455,7 +1526,7 @@ void startSessionLifecycleConflictReturnsStructuredErrorDetail() { .setTenantId("1") .setGameTemplateId("7") .setControlPlaneRequestId("cp-lifecycle") - .setOwnerAccountId("42") + .setOwnerAccountId(OWNER_ACCOUNT_UUID) .build(), new StreamObserver<>() { @Override @@ -1504,7 +1575,7 @@ void startSessionRejectsMalformedTenantId() { .setTenantId("abc") .setGameTemplateId("7") .setControlPlaneRequestId("cp-1") - .setOwnerAccountId("42") + .setOwnerAccountId(OWNER_ACCOUNT_UUID) .build(), new StreamObserver() { @Override @@ -1554,7 +1625,7 @@ void startSessionRejectsZeroTenantId() { .setTenantId("0") .setGameTemplateId("7") .setControlPlaneRequestId("cp-1") - .setOwnerAccountId("42") + .setOwnerAccountId(OWNER_ACCOUNT_UUID) .build(), new StreamObserver() { @Override @@ -1577,8 +1648,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); @@ -1604,7 +1676,7 @@ void startSessionRejectsZeroOwnerAccountId() { .setTenantId("1") .setGameTemplateId("7") .setControlPlaneRequestId("cp-1") - .setOwnerAccountId("0") + .setOwnerAccountId(ownerAccountId) .build(), new StreamObserver() { @Override @@ -1622,9 +1694,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 @@ -1637,7 +1714,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)); @@ -1692,7 +1769,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)); @@ -1839,7 +1916,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)); @@ -1893,7 +1970,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)); @@ -1952,11 +2029,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())) @@ -2013,11 +2090,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())) @@ -2122,7 +2199,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)); @@ -2220,7 +2297,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)); @@ -2434,7 +2511,7 @@ void startSessionRejectsUnscopedCaller() { .setTenantId("1") .setGameTemplateId("7") .setControlPlaneRequestId("cp-1") - .setOwnerAccountId("42") + .setOwnerAccountId(OWNER_ACCOUNT_UUID) .build(), new StreamObserver() { @Override @@ -2456,6 +2533,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()); } @@ -2469,7 +2549,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, @@ -2487,7 +2567,7 @@ void startSessionRejectsOwnerMismatchWithinTenant() { .setTenantId("1") .setGameTemplateId("7") .setControlPlaneRequestId("cp-1") - .setOwnerAccountId("42") + .setOwnerAccountId(OWNER_ACCOUNT_UUID) .build(), new StreamObserver() { @Override @@ -2509,6 +2589,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 @@ -2565,7 +2649,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)); @@ -2605,6 +2689,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); @@ -2615,7 +2750,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..0b4fb1f6fc 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 @@ -22,7 +22,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 +35,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 +51,7 @@ void insertRunningGameInstanceSeedsCoherentScriptPinTuple() { 700L, "genrev:test:7", null, - 41L, + 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 050c62a4e0..c3251035b1 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 @@ -342,13 +342,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"); } }; } 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..8f009ca591 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 @@ -5,13 +5,14 @@ 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 +29,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 +46,7 @@ INSERT INTO game_instances ( 700L, "genrev:test:" + gameTemplateId, null, - ownerAccountId, + 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 680cb0cbc3..4f6fb2d1d6 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 @@ -3,9 +3,11 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.IOException; import java.time.Instant; +import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; +import java.util.UUID; import javax.sql.DataSource; import net.firedevops.firemud.cache.ScreenBufferService; import net.firedevops.firemud.gamesession.CrossServiceAppHarness; @@ -39,6 +41,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; @@ -183,7 +186,7 @@ public long freshGameplayBaseline( } long gameInstanceId = GameInstanceTestFixtures.insertRunningGameInstance( - jdbc, tenantId, ownerAccountId, gameTemplateId); + jdbc, tenantId, GameInstanceTestFixtures.TEST_OWNER_ACCOUNT_UUID, gameTemplateId); seedRuntimeOwnership(tenantId, gameInstanceId); return gameInstanceId; } @@ -288,7 +291,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; } From 96fb1b803d4dd1c6a3cc8f39bda91ae537e25bb6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 08:13:38 +1300 Subject: [PATCH 02/11] Repair executed PostgreSQL profile and owner UUID fixtures --- design/project-management/ai-observations.md | 5 +++++ .../implementation-tracking/player-access-and-session.md | 2 ++ .../service/AccountAuthenticationUuidIntegrationTest.java | 6 +++--- .../gamesession/test/GameInstanceTestFixturesTest.java | 3 ++- .../firemud/gamesession/test/GameInstanceTestFixtures.java | 3 ++- 5 files changed, 14 insertions(+), 5 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index d9b489fea8..b5347bddff 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -199,3 +199,8 @@ 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. 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 be52660dee..f147f1ec08 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +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 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. 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. 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 1d383adf66..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 @@ -472,7 +472,7 @@ void unmappedUuidDeniesProfileMutationWithoutTouchingAnExistingPrivateRow() { @Test void persistedProfileGetUpdateAndExportCarryTheCanonicalAccountUuid() { String suffix = UUID.randomUUID().toString(); - String username = "profile-carrier-" + suffix; + String username = "profile-uuid-" + suffix; var created = accountService.createAccount( new CreateAccountRequest(username, username + "@example.com", PASSWORD)); @@ -556,8 +556,8 @@ void persistedProfileGetUpdateAndExportCarryTheCanonicalAccountUuid() { @Test void profileUpdateRejectsSourceUuidMismatchWithoutSavingOrNotifying() { String suffix = UUID.randomUUID().toString(); - String firstUsername = "profile-source-first-" + suffix; - String secondUsername = "profile-source-second-" + suffix; + String firstUsername = "source-a-" + suffix; + String secondUsername = "source-b-" + suffix; var first = accountService.createAccount( new CreateAccountRequest(firstUsername, firstUsername + "@example.com", PASSWORD)); 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 0b4fb1f6fc..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; @@ -51,7 +52,7 @@ void insertRunningGameInstanceSeedsCoherentScriptPinTuple() { 700L, "genrev:test:7", null, - GameInstanceTestFixtures.TEST_OWNER_ACCOUNT_UUID, + UUID.fromString(GameInstanceTestFixtures.TEST_OWNER_ACCOUNT_UUID), "ACTIVE"); } } 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 8f009ca591..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,6 +1,7 @@ package net.firedevops.firemud.gamesession.test; import java.util.Optional; +import java.util.UUID; import org.springframework.jdbc.core.JdbcTemplate; public final class GameInstanceTestFixtures { @@ -46,7 +47,7 @@ INSERT INTO game_instances ( 700L, "genrev:test:" + gameTemplateId, null, - ownerAccountUuid, + UUID.fromString(ownerAccountUuid), "ACTIVE")) .orElseThrow(() -> new IllegalStateException("Game instance insert did not return an id")); } From bfca5cebb6605025c09b724a6a5b85f9c57946d6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 08:51:29 +1300 Subject: [PATCH 03/11] Record owner UUID runner proof and bounded artifact diagnosis limits --- design/project-management/ai-observations.md | 8 ++++++++ .../implementation-tracking/player-access-and-session.md | 2 ++ 2 files changed, 10 insertions(+) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index b5347bddff..5ec5fec467 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -204,3 +204,11 @@ Entry format: - 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/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index f147f1ec08..16051eebe6 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +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 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. 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. From b2230e0759a8bd9bcd8ac8764d8ebebfa6a233eb Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 23:32:30 +1300 Subject: [PATCH 04/11] Report closed demo runtime-owner provisioning accurately --- .../platform-operations-and-delivery.md | 2 +- .../firedevops/firemud/gamesession/data/TestDataSeeder.java | 5 ++++- .../firemud/gamesession/data/TestDataSeederTest.java | 2 +- 3 files changed, 6 insertions(+), 3 deletions(-) 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 b41d021269..ebf5fefbca 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/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 170a24bbf9..a98f743156 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 @@ -13,7 +13,10 @@ import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; -/** Seeds deterministic smoke/runtime records when local compose explicitly enables them. */ +/** + * 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/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 260adbbfe9..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,7 +28,7 @@ void setup() { } @Test - void runSeedsAndReassertsCanonicalRuntimeData() 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()); From 2e3a6879bad6680224f95ed13b86dda8ad2e512a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 00:21:25 +1300 Subject: [PATCH 05/11] Prove profile source-validation errors at gRPC boundary --- .../service/impl/AccountGrpcServiceTest.java | 72 +++++++++++++++++++ 1 file changed, 72 insertions(+) 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 8109dc0e4a..5ee001e39b 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 @@ -913,6 +913,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); @@ -1490,6 +1520,42 @@ void updateProfileMapsServiceRuntimeFailuresToApplicationErrors() { 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 void updateProfileRejectsMissingOrWrongPeerBeforeUpdate() { List rejectedPeers = @@ -2338,12 +2404,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 @@ -2360,6 +2428,10 @@ private T response() { return response; } + private int responseCount() { + return responseCount; + } + private boolean receivedTransportError() { return receivedTransportError; } From 7afcd7e76adb94fbbaad06eab12f61ccc0a0b753 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 04:49:24 +1300 Subject: [PATCH 06/11] Contain unproved running-session replacement before mutation --- .../player-access-and-session.md | 4 +- .../service/impl/GameSessionGrpcService.java | 39 ++- .../impl/GameSessionGrpcServiceTest.java | 285 ++++-------------- 3 files changed, 72 insertions(+), 256 deletions(-) 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 413112d9a0..024fd6ed73 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -291,7 +291,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 @@ -339,7 +339,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, REST denial of non-public admission from legacy grant rows, cross-tenant membership enforcement, and the contained export/deletion/recovery boundaries. `DeleteAccount` now denies before account or financial-row mutation rather than relying on a partial active-subscription guard. Explicit `JOIN`/`Join & Play` and its bounded readback worker are local, while PostgreSQL lost-acknowledgement/concurrency, the connect-token membership-authority-generation reread, lifecycle-qualified grant authority, and canonical tenant-role, lifecycle-state, and authority-generation follow-through remain partial or unproved. 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 4962e3be54..99bd8cdc8b 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 @@ -72,6 +72,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; @@ -147,10 +149,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( @@ -165,13 +179,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() @@ -184,20 +193,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); 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 f3b750a238..f83bb8df81 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 @@ -63,6 +63,7 @@ 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; @@ -1126,237 +1127,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(OWNER_ACCOUNT_UUID); - existing.setStatus("RUNNING"); - Mockito.when( - gameInstanceRepository.findFirstByTenantIdAndOwnerAccountIdAndStatus( - 1L, OWNER_ACCOUNT_UUID, "RUNNING")) - .thenReturn(java.util.Optional.of(existing)); - Mockito.when(ipLimiter.canAccept("1.2.3.4", 77L)).thenReturn(false); - SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - SessionContext.setContext(OWNER_ACCOUNT_UUID, 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(OWNER_ACCOUNT_UUID) - .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(OWNER_ACCOUNT_UUID); - existing.setStatus("RUNNING"); - Mockito.when( - gameInstanceRepository.findFirstByTenantIdAndOwnerAccountIdAndStatus( - 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(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", - OWNER_ACCOUNT_UUID, - "RUNNING")); - SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - SessionContext.setContext(OWNER_ACCOUNT_UUID, 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(OWNER_ACCOUNT_UUID) - .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(OWNER_ACCOUNT_UUID); - existing.setStatus("RUNNING"); - Mockito.when( - gameInstanceRepository.findFirstByTenantIdAndOwnerAccountIdAndStatus( - 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(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", - OWNER_ACCOUNT_UUID, - "RUNNING")); - Mockito.doThrow(new IllegalStateException("Failed to stop old session")) - .when(gameInstanceService) - .stopSession(77L); - SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - SessionContext.setContext(OWNER_ACCOUNT_UUID, 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(OWNER_ACCOUNT_UUID) - .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); @@ -1373,9 +1175,13 @@ void startSessionFailedReplacementDoesNotStopExistingSession() { gameInstanceRepository.findFirstByTenantIdAndOwnerAccountIdAndStatus( 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), @@ -1394,6 +1200,11 @@ void startSessionFailedReplacementDoesNotStopExistingSession() { "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(OWNER_ACCOUNT_UUID, List.of(), Map.of("1", List.of("tenantAdmin"))); GameSessionGrpcService service = @@ -1408,14 +1219,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(OWNER_ACCOUNT_UUID) - .build(), + .setOwnerAccountId(OWNER_ACCOUNT_UUID); + if (clientIp != null) { + requestBuilder.setClientIp(clientIp); + } + service.startSession( + requestBuilder.build(), new StreamObserver() { @Override public void onNext(StartSessionResponse value) { @@ -1431,10 +1245,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 From f0ca03ebedf10785e122f40845135464a33064d3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 06:15:05 +1300 Subject: [PATCH 07/11] Preserve parent launch ledger and place owner UUID schema at V10.1 --- .../microservices/game-session-service/runtime-and-data.md | 2 +- .../implementation-tracking/player-access-and-session.md | 2 +- ...unt_uuid.sql => V10.1__game_instance_owner_account_uuid.sql} | 0 .../GameInstanceOwnerUuidMigrationIntegrationTest.java | 2 +- 4 files changed, 3 insertions(+), 3 deletions(-) rename services/game-session-service/src/main/resources/db/migration/{V10__game_instance_owner_account_uuid.sql => V10.1__game_instance_owner_account_uuid.sql} (100%) 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 c8f115f8ba..a15ec49b5a 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -10,7 +10,7 @@ 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 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. 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. +- 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 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. 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 024fd6ed73..05ac033e1c 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -12,7 +12,7 @@ Exact corrected #2929 source `96fb1b803d4dd1c6a3cc8f39bda91ae537e25bb6` [CI36912 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 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. Demo seeding no longer invents an Account owner without an authoritative source. This does not activate catalog enrollment, the membership RPC or credentials, nor implement Account operator-reference/digest authorization. The separate gameplay session/presence child remains unpublished at108files; overlapping paths do not prove its remaining unique hunks fit the ceiling. +The canonical 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. diff --git a/services/game-session-service/src/main/resources/db/migration/V10__game_instance_owner_account_uuid.sql b/services/game-session-service/src/main/resources/db/migration/V10.1__game_instance_owner_account_uuid.sql similarity index 100% rename from services/game-session-service/src/main/resources/db/migration/V10__game_instance_owner_account_uuid.sql rename to services/game-session-service/src/main/resources/db/migration/V10.1__game_instance_owner_account_uuid.sql 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 index beb9806936..6e66caa4a8 100644 --- 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 @@ -38,7 +38,7 @@ void migrationPreservesNumericHistoryAndStoresCanonicalOwnerUuid() { Flyway.configure() .dataSource(dataSource) .locations(MIGRATION_LOCATION) - .target(MigrationVersion.fromVersion("9")) + .target(MigrationVersion.fromVersion("10")) .load() .migrate(); From c8daf56aa947f883fdee308959c557e747039f8a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 12:38:29 +1300 Subject: [PATCH 08/11] Use persisted login fixture state across subject invalidation --- .../gamesession/command/text/LoginCommandHandlerTest.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) 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 ae2f814661..4e736ad8af 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 @@ -601,7 +601,7 @@ void credentialLoginAsDifferentAccountInvalidatesFirstPartyContextBeforeBareLogi }) .when(firstPartyConnectContextRegistry) .unregister(1L); - stubSessionContext( + stubMutableSessionContext( new SessionContext( 1L, 22L, @@ -650,8 +650,7 @@ void credentialLoginAsDifferentAccountInvalidatesFirstPartyContextBeforeBareLogi assertNull(credentialIdentity.playableStateScope()); assertNull(credentialIdentity.connectScopeId()); assertNull(credentialIdentity.connectRequestId()); - // Keep the persisted selector revision, not the invalidated account-A connect revision. - assertClearedSessionContext(captor.getAllValues().get(1), 3L, null, null); + assertClearedSessionContext(captor.getAllValues().get(1), 0L, null, null); } @Test From ce057022f48137b861025a47795640a90a4a82de Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 12:42:40 +1300 Subject: [PATCH 09/11] Assert cleared login context against the newly persisted subject --- .../command/text/LoginCommandHandlerTest.java | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) 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 4e736ad8af..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 @@ -643,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()); @@ -650,7 +651,7 @@ void credentialLoginAsDifferentAccountInvalidatesFirstPartyContextBeforeBareLogi assertNull(credentialIdentity.playableStateScope()); assertNull(credentialIdentity.connectScopeId()); assertNull(credentialIdentity.connectRequestId()); - assertClearedSessionContext(captor.getAllValues().get(1), 0L, null, null); + assertClearedSessionContext(captor.getAllValues().get(1), 0L, null, null, null); } @Test @@ -1980,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()); @@ -1989,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()); From 8e2344dcbbc0cde751f8d727a66d7242a28935c6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 12:23:49 +1300 Subject: [PATCH 10/11] Allow Validation for stacked pull requests --- .github/workflows/ci.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8ffe77bb8f..7a90f08063 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: From 054350441d266d8ad4e7f5c6e9c128c0265806bb Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 17:35:04 +1300 Subject: [PATCH 11/11] Carry forward reviewed CI safety corrections --- .github/workflows/ci.yml | 2 +- .../workflows/publish-pr-runtime-images.yml | 4 +- .github/workflows/security.yml | 3 +- .github/workflows/smoke.yml | 51 +++++++++++- .github/workflows/static-analysis-summary.yml | 3 +- .../preview/resolve-preview-image-tag.sh | 2 +- .../tests/ci-validation-summary-contract.sh | 12 +++ .../pr-required-gate-context-contract.sh | 83 +++++++++++++++++++ .../tests/pr-retarget-workflow-contract.sh | 79 +++++++++++++++++- .../pr-runtime-image-publication-contract.sh | 29 ++++++- dev-tools/tests/security-summary-contract.sh | 51 ++++++++++++ .../tests/static-analysis-summary-contract.sh | 11 ++- 12 files changed, 314 insertions(+), 16 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7a90f08063..15afae6f35 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1255,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/dev-tools/hosted/preview/resolve-preview-image-tag.sh b/dev-tools/hosted/preview/resolve-preview-image-tag.sh index f9d00f5fd6..442eb9e33c 100644 --- a/dev-tools/hosted/preview/resolve-preview-image-tag.sh +++ b/dev-tools/hosted/preview/resolve-preview-image-tag.sh @@ -33,7 +33,7 @@ runtime_relevant() { .github/workflows/runtime-images.yml | .github/workflows/publish-pr-runtime-images.yml | .github/workflows/smoke.yml | .github/workflows/smoke-full.yml | .dockerignore) return 0 ;; - .github/actions/setup-python/* | .github/actions/load-workflow-tool-versions/* | buildSrc/* | gradle/* | protos/* | docker/* | services/* | dev-tools/smoke/*) + .github/actions/setup-python/* | .github/actions/load-workflow-tool-versions/* | buildSrc/* | gradle/* | protos/* | docker/* | services/* | dev-tools/smoke/* | dev-tools/minio/*) return 0 ;; config/python/smoke-requirements.txt | config/python/smoke-requirements.in | \ diff --git a/dev-tools/tests/ci-validation-summary-contract.sh b/dev-tools/tests/ci-validation-summary-contract.sh index fdb265d732..3bf11d75f7 100644 --- a/dev-tools/tests/ci-validation-summary-contract.sh +++ b/dev-tools/tests/ci-validation-summary-contract.sh @@ -41,6 +41,18 @@ if script.index("github.rest.pulls.get") > script.index("github.paginate(github. raise SystemExit("validation-summary must verify the current PR before listing comments") PY +python3 - "$ROOT_DIR/.github/workflows/ci.yml" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +condition = workflow["jobs"]["validation-summary"]["if"] +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +if condition != expected: + raise SystemExit("Optional summary must preserve cancellation, native-PR trust and substantive-event predicates") +PYTHON + script_b64="$({ python3 - "$CI_WORKFLOW" <<'PY' import base64 diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 926cb684a4..fd063f377b 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -498,6 +498,89 @@ grep -Fq "name: \${{ github.event_name == 'pull_request' && github.event.action tmp_dir="$(mktemp -d)" trap 'rm -rf "$tmp_dir"' EXIT + +# The Smoke consumer must outlive its producer and still terminate fail closed. +smoke_clock_fixture="$tmp_dir/smoke-clock.js" +python3 - "$ROOT_DIR" "$smoke_clock_fixture" <<'PY' +from pathlib import Path +import re +import sys +import yaml + +root = Path(sys.argv[1]) +smoke = yaml.load((root / ".github/workflows/smoke.yml").read_text(), Loader=yaml.BaseLoader) +producer = yaml.load((root / ".github/workflows/runtime-images.yml").read_text(), Loader=yaml.BaseLoader) +job = smoke["jobs"]["smoke-gate"] +script = next(step["with"]["script"] for step in job["steps"] if step.get("name") == "Track full-stack smoke result from Build Runtime Images") +producer_minutes = int(re.search(r"const producerTimeoutMinutes = ([0-9]+);", script)[1]) +overhead_minutes = int(re.search(r"const prerequisiteAndQueueAllowanceMinutes = ([0-9]+);", script)[1]) +if producer_minutes != int(producer["jobs"]["pr-local-smoke"]["timeout-minutes"]): + raise SystemExit("Smoke polling producer budget must match the actual full-stack producer timeout") +if overhead_minutes != 45 or int(job["timeout-minutes"]) < producer_minutes + overhead_minutes + 5: + raise SystemExit("Smoke polling must retain bounded scheduling overhead and five-minute job margin") +if "const timeoutMs = (producerTimeoutMinutes + prerequisiteAndQueueAllowanceMinutes) * 60 * 1000;" not in script: + raise SystemExit("Smoke polling deadline must use the checked producer and overhead authorities") +Path(sys.argv[2]).write_text(script) +PY + +node - "$smoke_clock_fixture" <<'NODE' +const assert = require("node:assert/strict"); +const script = require("node:fs").readFileSync(process.argv[2], "utf8"); +const head = "a".repeat(40), base = "b".repeat(40), merge = "c".repeat(40); +const title = `Build Runtime Images secure-pr-artifact pr-42 base-${base} head-${head} merge-${merge} mode-required`; +const context = { repo: { owner: "example", repo: "firemud" }, sha: merge, + payload: { pull_request: { number: 42, head: { sha: head }, base: { ref: "develop", sha: base }, created_at: "2026-09-01T00:00:00Z" } } }; +const execute = new Function("github", "context", "core", "Date", "setTimeout", `return (async () => {\n${script}\n})()`); +async function scenario(outcome, completedAtMinutes) { + let now = 1000; + const start = now; + const failures = []; + const listRuns = async () => {}, listJobs = async () => {}; + const github = { rest: { + pulls: { get: async () => ({ data: { state: "open", head: { sha: head }, base: { ref: "develop", sha: base }, merge_commit_sha: merge } }) }, + repos: { getCommit: async () => ({ data: { sha: merge, parents: [{ sha: base }, { sha: head }] } }) }, + actions: { listWorkflowRuns: listRuns, listJobsForWorkflowRun: listJobs }, + }, paginate: async (method, input) => { + assert.equal(method, listJobs); + assert.equal(input.run_id, 42); + return [{ name: "PR Full-Stack Smoke", status: "completed", conclusion: "success", + steps: [{ name: "Run credential-free full-stack smoke", status: "completed", conclusion: "success" }] }]; + } }; + github.paginate.iterator = async function* (method, input) { + assert.equal(method, listRuns); + assert.equal(input.workflow_id, "runtime-images.yml"); + if (input.event === "repository_dispatch") { yield { data: [] }; return; } + assert.equal(input.head_sha, head); + const complete = now - start >= completedAtMinutes * 60 * 1000; + yield { data: [{ id: 42, event: "pull_request", head_sha: head, display_title: title, pull_requests: [], + status: complete ? "completed" : "in_progress", conclusion: complete ? outcome : null }] }; + }; + const core = { info: () => {}, warning: () => {}, setFailed: message => failures.push(message) }; + const clock = { now: () => now, parse: Date.parse }; + const sleep = (callback, duration) => { now += duration; queueMicrotask(callback); }; + await execute(github, context, core, clock, sleep); + return { failures, minutes: (now - start) / 60000 }; +} +(async () => { + const success = await scenario("success", 30); + assert.deepEqual(success.failures, [], "exact producer success after 25 minutes must be admitted"); + assert.equal(success.minutes, 30); + const failed = await scenario("failure", 30); + assert.equal(failed.failures.length, 1); + assert.match(failed.failures[0], /did not complete successfully/); + assert.equal(failed.minutes, 30, "terminal failure must stop polling promptly"); + const cancelled = await scenario("cancelled", 0); + assert.equal(cancelled.failures.length, 1); + assert.match(cancelled.failures[0], /cancelled/i); + assert.ok(cancelled.minutes <= 5.25, "cancelled source without an exact replacement remains bounded"); + const deadline = await scenario("success", Infinity); + assert.equal(deadline.failures.length, 1); + assert.match(deadline.failures[0], /Timed out waiting for the exact/); + assert.equal(deadline.minutes, 90, "active producers cannot escape the total deadline"); + console.log("Smoke clock contract passed: late success, prompt failure, bounded cancellation and deadline"); +})().catch(error => { console.error(error); process.exitCode = 1; }); +NODE + cat >"$tmp_dir/gh" <<'EOF' #!/usr/bin/env bash set -euo pipefail diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index e27cbf79e0..affc4ae136 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -334,6 +334,44 @@ for path in "$ci_path" "$security_path" "$smoke_path"; do require_contains "$path" 'types: [opened, synchronize, reopened, edited]' done +# Optional native-PR comments cannot delay cancellation or require fork/bot write tokens. +python3 - "$ROOT_DIR" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +root = Path(sys.argv[1]) +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +for filename, jobs in { + "ci.yml": ("validation-summary",), + "security.yml": ("security-summary",), + "smoke.yml": ("smoke-summary-pending", "smoke-summary"), +}.items(): + workflow = yaml.load((root / ".github/workflows" / filename).read_text(), Loader=yaml.BaseLoader) + for job in jobs: + condition = workflow["jobs"][job]["if"] + if condition != expected: + raise SystemExit(f"{filename}/{job} must retain the cancellation, trust and substantive-event condition") + def eligible(cancelled=False, event="pull_request", head_repo="example/repo", actor="contributor", action="synchronize", base_ref=None): + expression = condition[3:-3].replace("!cancelled()", str(not cancelled)) + values = { + "github.event.pull_request.head.repo.full_name": head_repo, + "github.event.changes.base.ref": base_ref, + "github.event_name": event, + "github.repository": "example/repo", + "github.actor": actor, + "github.event.action": action, + } + for key, value in values.items(): + expression = expression.replace(key, repr(value)) + return eval(expression.replace("&&", "and").replace("||", "or").replace("null", "None"), {"__builtins__": {}}) + if not eligible() or not eligible(action="edited", base_ref="develop"): + raise SystemExit(f"{job} must report ordinary results and base retargets") + for arguments in ({"cancelled": True}, {"head_repo": "fork/repo"}, {"actor": "dependabot[bot]"}, {"action": "edited"}, {"event": "push"}): + if eligible(**arguments): + raise SystemExit(f"{job} permits an ineligible comment mutation: {arguments}") +PYTHON + # Metadata-only edits get distinct optional summary contexts; substantive events # retain each summary's canonical name. # shellcheck disable=SC2016 # Assert literal GitHub expression syntax. @@ -1503,6 +1541,15 @@ runtime_service = "services/account-service/src/Main.java" assert run_scope([controller_service]) == {"run_smoke_full": "false"} assert run_scope([controller_smoke_script]) == {"run_smoke_full": "false"} +# Source-built MinIO helpers must require runtime proof even when no Dockerfile changes. +root = Path(sys.argv[1]).resolve().parents[2] +preview_resolver = (root / "dev-tools/hosted/preview/resolve-preview-image-tag.sh").read_text() +preview_predicate = preview_resolver[preview_resolver.index("runtime_relevant() {"):preview_resolver.index('\nif [[ -n "${pr_number}"')] +for helper in ("dev-tools/minio/base_image_refs.py", "dev-tools/minio/build-and-smoke-images.sh"): + assert run_scope([helper]) == {"run_smoke_full": "true"}, helper + preview = subprocess.run(["bash", "-c", preview_predicate + '\nruntime_relevant "$1"', "preview-scope", helper], check=False) + assert preview.returncode == 0, helper +assert subprocess.run(["bash", "-c", preview_predicate + '\nruntime_relevant "$1"', "preview-scope", "design/example.md"], check=False).returncode != 0 assert run_scope([runtime_service]) == {"run_smoke_full": "true"} assert run_scope([controller_service, runtime_service]) == {"run_smoke_full": "true"} PY @@ -1973,6 +2020,7 @@ const scripts = JSON.parse(process.env.SMOKE_SUMMARY_SCRIPTS); const context = { repo: { owner: "example", repo: "firemud" }, issue: { number: 42 }, + payload: { pull_request: { head: { sha: "h" }, base: { ref: "develop", sha: "b" } } }, }; async function checkSummary(jobName, script) { @@ -2005,13 +2053,16 @@ async function checkSummary(jobName, script) { created_at: "2026-08-01T00:00:00Z", }, ]; - const calls = { paginate: [], operations: [], creates: [] }; + const calls = { paginate: [], operations: [], creates: [], bodies: [] }; + let currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request) }; + let readError = null; const listComments = async () => undefined; const github = { rest: { + pulls: { get: async () => { if (readError) throw readError; return { data: currentPullRequest }; } }, issues: { listComments, - updateComment: async ({ comment_id }) => calls.operations.push(`update:${comment_id}`), + updateComment: async ({ comment_id, body }) => { calls.operations.push(`update:${comment_id}`); calls.bodies.push(body); }, deleteComment: async ({ comment_id }) => calls.operations.push(`delete:${comment_id}`), createComment: async (request) => calls.creates.push(request), }, @@ -2025,8 +2076,24 @@ async function checkSummary(jobName, script) { process.env.CHANGES_RESULT = "success"; process.env.RUN_SMOKE_FULL = "true"; process.env.SMOKE_GATE_RESULT = "success"; - const run = new Function("github", "context", `return (async () => {\n${script}\n})()`); - await run(github, context); + const run = new Function("github", "context", "core", `return (async () => {\n${script}\n})()`); + const core = { info: () => {} }; + for (const changed of [ + { state: "closed" }, { head: { sha: "new" } }, + { base: { ref: "main", sha: "b" } }, { base: { ref: "develop", sha: "new" } }, + ]) { + currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request), ...changed }; + await run(github, context, core); + assert.deepEqual(calls.paginate, [], `${jobName} must not list stale comments`); + assert.deepEqual(calls.operations, [], `${jobName} must not mutate stale comments`); + assert.deepEqual(calls.creates, [], `${jobName} must not create stale comments`); + } + readError = new Error("PR guard unavailable"); + await assert.rejects(run(github, context, core), /PR guard unavailable/); + assert.deepEqual(calls.paginate, [], `${jobName} guard errors must fail closed`); + readError = null; + currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request) }; + await run(github, context, core); assert.equal(calls.paginate.length, 1, `${jobName} must paginate once`); assert.equal(calls.paginate[0].method, listComments, `${jobName} must paginate issue comments`); @@ -2037,6 +2104,10 @@ async function checkSummary(jobName, script) { `${jobName} must update the oldest bot summary before deleting later duplicates`, ); assert.deepEqual(calls.creates, [], `${jobName} must not create another summary`); + process.env.CHANGES_RESULT = "failure"; + process.env.SMOKE_GATE_RESULT = "failure"; + await run(github, context, core); + assert.ok(calls.bodies.at(-1).includes("failure"), `${jobName} must report failed dependencies`); } (async () => { diff --git a/dev-tools/tests/pr-runtime-image-publication-contract.sh b/dev-tools/tests/pr-runtime-image-publication-contract.sh index 1bbb114fab..c8a2009a3c 100644 --- a/dev-tools/tests/pr-runtime-image-publication-contract.sh +++ b/dev-tools/tests/pr-runtime-image-publication-contract.sh @@ -159,7 +159,7 @@ cat > "$artifact_dir/pr-runtime-provenance.json" < "$fixture_dir/source-run.json" < "$fixture_dir/pull-request.json" <&2 + exit 1 + fi + python3 - "$fixture_dir/source-run.json" "$source_title" <<'PY' +import json +import sys +from pathlib import Path +p = Path(sys.argv[1]); data = json.loads(p.read_text()); data["name"] = "Build Runtime Images"; data["display_title"] = sys.argv[2]; p.write_text(json.dumps(data)) +PY +done run_validation grep -Fxq "IMAGE_TAG=pr-merge-$merge_sha" "$fixture_dir/github-env" grep -Fxq "PR_RUNTIME_ARTIFACT_DIR=$artifact_dir" "$fixture_dir/github-env" diff --git a/dev-tools/tests/security-summary-contract.sh b/dev-tools/tests/security-summary-contract.sh index 1164ed55ee..56120dc56b 100644 --- a/dev-tools/tests/security-summary-contract.sh +++ b/dev-tools/tests/security-summary-contract.sh @@ -15,6 +15,18 @@ grep -Fq 'currentPullRequest.head.sha !== expectedHeadSha' "$workflow" grep -Fq 'currentPullRequest.base.ref !== expectedBaseRef' "$workflow" grep -Fq 'currentPullRequest.base.sha !== expectedBaseSha' "$workflow" +python3 - "$repo_root/.github/workflows/security.yml" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +condition = workflow["jobs"]["security-summary"]["if"] +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +if condition != expected: + raise SystemExit("Optional summary must preserve cancellation, native-PR trust and substantive-event predicates") +PYTHON + test_root="$(mktemp -d)" trap 'rm -rf -- "$test_root"' EXIT script_path="$test_root/security-summary.js" @@ -164,4 +176,43 @@ run(github, context, core).then(async () => { }); NODE +# Execute the checked-in scanner step using the explicit Actions Bash shell. +# The fake scanner and reports stay in one disposable directory; no scan/network occurs. +python3 - "$workflow" "$repo_root/config/security/trivy.yaml" <<'PYTHON' +from pathlib import Path +import os +import subprocess +import sys +import tempfile +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +steps = workflow["jobs"]["trivy-scan"]["steps"] +scanner = next(step for step in steps if step.get("name") == "🔍 Run Trivy and Save Report") +upload = next(step for step in steps if step.get("name") == "📤 Upload Trivy Report") +if scanner.get("shell") != "bash" or upload.get("if") != "always()": + raise SystemExit("Trivy must use explicit pipefail Bash and retain always-uploaded reports") +settings = yaml.safe_load(Path(sys.argv[2]).read_text()) +if settings.get("exit-code") != 1 or settings.get("severity") != ["CRITICAL", "HIGH"] or settings.get("ignore-unfixed") is not True: + raise SystemExit("Trivy failure policy and filters must remain intact") +with tempfile.TemporaryDirectory(prefix="firemud-trivy-pipeline-") as directory: + root = Path(directory) + scanner_path = root / "trivy" + scanner_path.write_text('#!/bin/sh\nprintf "scanner-result-%s\\n" "$FAKE_TRIVY_EXIT"\nexit "$FAKE_TRIVY_EXIT"\n') + scanner_path.chmod(0o755) + for exit_status in (0, 1, 2): + environment = dict(os.environ, PATH=str(root) + os.pathsep + os.environ["PATH"], FAKE_TRIVY_EXIT=str(exit_status)) + # actions/runner explicit shell:bash -> bash --noprofile --norc -e -o pipefail {0}. + script = root / "step.sh" + script.write_text(scanner["run"]) + result = subprocess.run(["bash", "--noprofile", "--norc", "-e", "-o", "pipefail", str(script)], cwd=root, env=environment, capture_output=True, text=True) + if result.returncode != exit_status: + raise SystemExit(f"Trivy exit {exit_status} was masked: {result.returncode}") + if (root / "trivy-report.txt").read_text() != f"scanner-result-{exit_status}\n": + raise SystemExit("tee must retain the report even when the scanner fails") + if ("::endgroup::" in result.stdout) != (exit_status == 0): + raise SystemExit("Failed scanner pipelines must stop the step") +print("Trivy pipeline contract passed: scanner success/vulnerability/error with reports retained") +PYTHON + echo "security summary contract passed" diff --git a/dev-tools/tests/static-analysis-summary-contract.sh b/dev-tools/tests/static-analysis-summary-contract.sh index 14165090c5..17edc16a3a 100644 --- a/dev-tools/tests/static-analysis-summary-contract.sh +++ b/dev-tools/tests/static-analysis-summary-contract.sh @@ -262,7 +262,7 @@ const context = { payload: { workflow_run: { event: "pull_request", - name: `CodeQL Analysis pr-42 base-${baseSha} head-${headSha}`, + name: "CodeQL Analysis", path: ".github/workflows/codeql.yml", head_sha: headSha, head_branch: "feature", @@ -273,7 +273,7 @@ const context = { }; const core = { info: () => {} }; const run = new Function("github", "context", "core", `return (async () => {\n${script}\n})()`); -run(github, context, core).then(() => { +run(github, context, core).then(async () => { if (calls.paginate.length !== 4) throw new Error(`expected four paginated calls, got ${calls.paginate.length}`); if (!calls.paginate.every(({ input }) => input.per_page === 100)) throw new Error("all API listings must request page size 100"); if (calls.updated.length !== 1 || calls.updated[0].comment_id !== 2) throw new Error("oldest bot summary was not updated"); @@ -281,6 +281,12 @@ run(github, context, core).then(() => { if (calls.created.length !== 0) throw new Error("existing bot summary should be updated"); if (!calls.updated[0].body.includes("❌ Static analysis checks failed")) throw new Error("new failure was masked by the older success"); if (!calls.updated[0].body.includes("CodeQL gate: `failure`")) throw new Error("latest CodeQL gate result was not selected"); + context.payload.workflow_run.name = "Forged workflow name"; + await run(github, context, core); + if (calls.paginate.length !== 4 || calls.updated.length !== 1 || calls.deleted.length !== 1) { + throw new Error("unrelated source names must not query runs or alter comments"); + } + context.payload.workflow_run.name = "CodeQL Analysis"; currentHeadSha = "d".repeat(40); return run(github, context, core).then(() => { if (calls.paginate.length !== 4 || calls.updated.length !== 1 || calls.deleted.length !== 1) { @@ -316,6 +322,7 @@ run(github, context, core).then(() => { calls.deleted.length = 0; calls.updated.length = 0; calls.created.length = 0; + context.payload.workflow_run.name = `CodeQL Analysis pr-42 base-${baseSha} head-${headSha}`; deleteStatus = 404; return run(github, context, core).then(() => { if (calls.deleted.length !== 1 || calls.deleted[0] !== 3) {