From ac71ec7a6ce20ba805c39e4e55711389776222e1 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 20:00:08 +1300 Subject: [PATCH 01/13] Bind launch descriptors to authenticated authored source and immutable outcomes --- .github/workflows/ci.yml | 46 + .../game-design-service/README.md | 5 +- .../game-design-service/api-contracts.md | 18 +- .../game-design-service/game-templates.md | 14 +- .../game-design-service/version-control.md | 2 +- .../game-session-service/README.md | 2 + .../world-management-service/api-contracts.md | 12 + .../system-architecture-versioning-runtime.md | 3 +- ...ame-authoring-publishing-and-activation.md | 8 +- .../world-runtime-and-movement.md | 4 +- .../game-design/v1/game_design_service.proto | 50 +- .../AuthoredWorldLaunchDescriptorClient.java | 178 +++ ...AuthoredWorldLaunchDescriptorEvidence.java | 568 ++++++++ ...uthoredWorldLaunchDescriptorGrpcCodec.java | 256 ++++ ...thoredWorldLaunchDescriptorClientTest.java | 165 +++ ...oredWorldLaunchDescriptorEvidenceTest.java | 109 ++ ...redWorldLaunchDescriptorGrpcCodecTest.java | 391 ++++++ services/game-design-service/build.gradle.kts | 1 + .../dto/ResolvedLaunchDescriptorDto.java | 34 +- .../gamedesign/entity/LaunchDescriptor.java | 16 + .../LaunchDescriptorRepository.java | 171 ++- .../service/LaunchDescriptorService.java | 16 +- ...FrozenLaunchDescriptorDenialException.java | 23 + .../service/impl/GameDesignGrpcService.java | 214 ++- .../impl/LaunchDescriptorServiceImpl.java | 657 ++++++--- .../src/main/resources/application-prod.yml | 2 + .../src/main/resources/application.yml | 2 + ...hored_source_launch_descriptor_binding.sql | 147 ++ ...aunchDescriptorServiceIntegrationTest.java | 896 ++++++++++++- ...AuthoredWorldLaunchDescriptorMtlsTest.java | 908 +++++++++++++ .../impl/GameDesignGrpcServiceAuthTest.java | 150 ++- .../impl/GameDesignGrpcServiceTest.java | 269 ++-- .../impl/LaunchDescriptorServiceImplTest.java | 945 +++++++++---- .../gamesession/client/GameDesignClient.java | 27 - .../service/impl/GameInstanceServiceImpl.java | 67 +- ...stanceCutoverCompatibilityServiceImpl.java | 99 +- ...GameSessionApplicationIntegrationTest.java | 170 +-- ...stanceServiceLifecycleIntegrationTest.java | 82 +- .../impl/GameInstanceServiceImplTest.java | 1187 +---------------- ...ceCutoverCompatibilityServiceImplTest.java | 65 +- 40 files changed, 5720 insertions(+), 2259 deletions(-) create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodec.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClientTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorEvidenceTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodecTest.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/FrozenLaunchDescriptorDenialException.java create mode 100644 services/game-design-service/src/main/resources/db/migration/V35__authored_source_launch_descriptor_binding.sql create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldLaunchDescriptorMtlsTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6969aede71..2a2d797d3c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -955,6 +955,52 @@ jobs: --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepositoryIntegrationTest#databaseRejectsAssociationUpdatesDeletesTruncatesAndContradictorySourceInsert()' \ game-design-service + - name: Run Game Design authored-source launch descriptor PostgreSQL and socket mTLS proof + if: ${{ matrix.module == 'game-design-service' }} + run: | + ./gradlew :game-design-service:integrationTest \ + --tests integration.net.firedevops.firemud.gamedesign.service.LaunchDescriptorServiceIntegrationTest \ + -PfullCheck --no-build-cache --no-configuration-cache + ./gradlew :game-design-service:test \ + --tests net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldLaunchDescriptorMtlsTest \ + -PfullCheck --no-build-cache --no-configuration-cache + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite integration.net.firedevops.firemud.gamedesign.service.LaunchDescriptorServiceIntegrationTest \ + --require-suite net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldLaunchDescriptorMtlsTest \ + --require-case 'integration.net.firedevops.firemud.gamedesign.service.LaunchDescriptorServiceIntegrationTest#resolvesPersistedSourceAndReplaysOriginalDescriptorAfterDefaultsAndVersionChange()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.service.LaunchDescriptorServiceIntegrationTest#concurrentExactRetriesPersistOneOriginalDescriptor()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.service.LaunchDescriptorServiceIntegrationTest#deterministicFailureIsFrozenAcrossDependencyChangeAndConcurrentExactRetries()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.service.LaunchDescriptorServiceIntegrationTest#corruptFailureReadbackRollsBackTheOutcomeInsert()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.service.LaunchDescriptorServiceIntegrationTest#concurrentSuccessAndFailureCandidatesPersistOnlyTheFirstOutcome()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.service.LaunchDescriptorServiceIntegrationTest#rolledBackDescriptorInsertLeavesNoCanonicalOrPrivateRequestClaim()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.service.LaunchDescriptorServiceIntegrationTest#v35MigrationPreservesRetainedUnboundDescriptorAndCanonicalResolveDeniesIt()' \ + --require-case 'net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldLaunchDescriptorMtlsTest#exactGameSessionPeerResolvesAndEchoesTheFullCanonicalDescriptor()' \ + --require-case 'net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldLaunchDescriptorMtlsTest#gameSessionAndWorldPeersReadExactDescriptorAndEchoReadRequestIdentity()' \ + --require-case 'net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldLaunchDescriptorMtlsTest#worldPeerCannotResolveBeforeDescriptorProducerAccess()' \ + --require-case 'net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldLaunchDescriptorMtlsTest#missingClientCertificateFailsWithTlsHandshakeEvidenceBeforeProducerAccess()' \ + --require-case 'net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldLaunchDescriptorMtlsTest#jwtOnlyCallerWithoutClientCertificateFailsWithTlsHandshakeEvidence()' \ + --require-case 'net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldLaunchDescriptorMtlsTest#wrongServiceCertificateCannotResolveOrReadEvenWithBearerMetadata()' \ + --require-case 'net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldLaunchDescriptorMtlsTest#wrongNamespaceCertificateCannotResolveOrReadEvenWithBearerMetadata()' \ + --require-case 'net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldLaunchDescriptorMtlsTest#sharedCertificateWithoutWorkloadUriCannotResolveOrRead()' \ + --require-case 'net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldLaunchDescriptorMtlsTest#malformedAndUnknownClosedRequestsFailBeforeDescriptorProducerAccess()' \ + --require-case 'net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldLaunchDescriptorMtlsTest#bothProductionProfilesKeepOnlyExactLaunchDescriptorMethodsInGameDesignJwtBypass()' \ + --require-case 'net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldLaunchDescriptorMtlsTest#sharedClientResolvesAndReadsExactDescriptorOverPhysicalMtlsSocket(Path)' \ + --require-case 'net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldLaunchDescriptorMtlsTest#sharedClientRejectsWrongGameDesignServerWorkloadAndNamespaceBeforeReturningEvidence(Path)' \ + --require-case 'net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldLaunchDescriptorMtlsTest#sharedClientCodecRejectsChangedDescriptorReadEchoAndDigestOverPhysicalSocket(Path)' \ + game-design-service + + - name: Upload Game Design authored-source launch descriptor proof results + if: ${{ always() && matrix.module == 'game-design-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: game-design-authored-source-launch-descriptor-proof-${{ github.sha }} + path: | + services/game-design-service/build/test-results/integrationTest/TEST-*LaunchDescriptorServiceIntegrationTest.xml + services/game-design-service/build/test-results/test/TEST-*AuthoredWorldLaunchDescriptorMtlsTest.xml + if-no-files-found: warn + retention-days: 7 + - name: Run Game Session authored-world intake PostgreSQL component proof if: ${{ matrix.module == 'game-session-service' }} run: | diff --git a/design/architecture/microservices/game-design-service/README.md b/design/architecture/microservices/game-design-service/README.md index 11f22bf7b5..7745805eba 100644 --- a/design/architecture/microservices/game-design-service/README.md +++ b/design/architecture/microservices/game-design-service/README.md @@ -45,8 +45,7 @@ Tenant identity status is narrower: V30 gives each `game` row an opaque canonica - Design assets are stored per `tenantId` so multiple games can coexist in the same database schema. Queries and version publishing workflows enforce this tenant filter. See [Multi-Tenancy](../../system-architecture-multi-tenancy.md). -- All control-plane (design-time) gRPC APIs require JWT authentication. REST authentication is supported. Runtime gameplay services do not call the Game Design Service during ticks; they load published templates and manifests from the owning domain services and object storage and authenticate internal runtime traffic using mutual TLS plus propagated `SessionContext` rather than per-request JWT parsing. - Tokens are parsed by a shared `AuthTokenInterceptor` configured in `GrpcConfig`, which stores claims in `SessionContext` for role checks. Service-to-service traffic uses mutual TLS certificates managed by cert-manager as described in the [Security Architecture](../../system-architecture-security.md). +- Authentication is method-specific. Creator-facing design-time gRPC APIs use the shared `AuthTokenInterceptor` and `SessionContext` role checks; REST authentication is also supported. Purpose-specific owner handoffs use verified workload certificates and their exact method allowlists, including [tenant/source identity](api-contracts.md#authored-world-source-registration-and-game-session-readback) and [launch descriptor resolution/readback](api-contracts.md#authored-source-bound-launch-descriptor-and-exact-readback); a JWT claim is not a substitute for that peer identity. Runtime gameplay services do not call Game Design during ticks; they load published templates and manifests from the owning domain services and object storage. Service-to-service mutual TLS certificate delivery remains governed by the [Security Architecture](../../system-architecture-security.md). - Utilizes the [Shared Libraries](../../system-architecture-shared-libraries.md) for DTO definitions, logging interceptors, and Micrometer metrics. ### Script Patch Lifecycle and Runtime Coordination @@ -60,7 +59,7 @@ The Game Design Service owns the **authoring** view of script patches, while the - **Target state:** Notifies Automation & Scripting of the published patch so it can ingest the compiled definitions and bindings for the target `` and, for an eligible non-empty handler notification, start or reuse the durable Temporal `script-patch-readiness` workflow. Target state permits a verifiable immutable manifest with zero `onLoad` handlers to instead create the terminal `READY` pin-readiness record with its pinned manifest reference/digest and zero declared and terminal handler counts, without a Temporal workflow or synthetic handler work. The current publication notification sends only `affectedScripts`, and current status responses have no manifest-proof or declared/terminal-count fields, so the current wire/runtime cannot supply or expose this proof; the empty notification is rejected before readiness mutation and causes Game Design publication to fail before finalization. - **Target state:** Treats the publish as **asynchronous** from a runtime perspective: after successful publication, readiness for execution is determined by the Automation & Scripting Service. The current empty-notification failure means this normal path does not record the patch as published. - **Target state:** For each `` with an eligible `NotifyScriptVersionUpdate` notification, including a valid affected-script set (or a manifest-proven zero-handler set), the Automation & Scripting Service tracks a tenant readiness lifecycle (`PENDING_VALIDATION`, `ONLOAD_RUNNING`, `READY`, `FAILED`, and terminal `SUPERSEDED`) as described in `design/architecture/system-architecture-scripting-dsl-reference-and-lifecycle.md#script-patch-lifecycle`. An empty `affectedScripts` list without immutable manifest proof cannot establish `READY`: for an identifiable tenant/patch notification, Automation records durable `FAILED` readiness with bounded reason `zero_handler_manifest_unverifiable` and status/audit evidence; an unidentifiable malformed notification may fail transport validation without fabricating a readiness identity. `SUPERSEDED` applies only to a displaced, unpinned record in `PENDING_VALIDATION` or `ONLOAD_RUNNING`; an already-pinned `READY` record is not relabeled `SUPERSEDED` merely because a newer publish arrives. Already-admitted work remains governed by its captured Game Session `(scriptPatchVersion, scriptPinEpoch)` tuple and normal persistence, handoff, and execution fences until explicit repin or rollback, or fence rejection. -- **Current implementation status:** `PublishScriptPatchVersion` accepts the caller-supplied `baseVersionId` without proving same-tenant ownership, an eligible published state, or release evidence. `LaunchDescriptor` denies every nonblank requested, template-selected, version-selected, or replayed persisted patch with `SCRIPT_PATCH_NOT_READY`; unpatched launches may continue. This fails closed but does not prove patch publication, base-version ownership/compatibility, or Automation readiness. `GetPublishedScriptPatchVersion` and its patch digest lookup require the exact `(tenantId, baseVersionId, scriptPatchVersion)` tuple and one script-only `PUBLISHED` row. Automation projections that do not yet retain base identity fail this lookup closed rather than selecting by patch name. These read filters do not establish complete publication or readiness; the remaining write, projection, and launch gaps are target-state work. +- **Current implementation status:** `PublishScriptPatchVersion` accepts the caller-supplied `baseVersionId` without proving same-tenant ownership, an eligible published state, or release evidence. Launch resolution denies every nonblank requested, template-selected or version-selected patch with `SCRIPT_PATCH_NOT_READY`. Owner-local unpatched descriptor resolution is narrower than runtime launch: Game Session's unsupported numeric start/cutover paths deny pending the canonical source-bound handoff, and immutable descriptor retry does not authorize activation. This fails closed but does not prove patch publication, base-version ownership/compatibility, or Automation readiness. `GetPublishedScriptPatchVersion` and its patch digest lookup require the exact `(tenantId, baseVersionId, scriptPatchVersion)` tuple and one script-only `PUBLISHED` row. Automation projections that do not yet retain base identity fail this lookup closed rather than selecting by patch name. These read filters do not establish complete publication or readiness; the remaining write, projection, and launch gaps are target-state work. - **Target state:** The Game Design Service queries readiness via a read-only API such as `GetScriptPatchStatus(tenantId, scriptPatchVersion)` and consumes the owner-provided rollout read for creator visibility so that UIs can show: - That a patch is published but still **pending runtime validation**. - The patch's `baseVersionId` and `abilitySchemaDigest` used for runtime compatibility gates and pinning checks. diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 7c3d22df77..937cd62a4b 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -40,6 +40,22 @@ The readback request binds a distinct canonical non-nil read `requestId` to the **Implementation and activation boundary:** The source repository/codec/readback is a prerequisite candidate, not a protected product creator or a live catalog handoff. Normal official-hosted authoring remains subject to the Account-owned commit-bound creator/terms gate below, which cannot be replaced by the source transaction or a caller-supplied authorization flag. No new public creation route or catalog admission is enabled before its producer, receiver, owner authorization and negative proof pass. Retained Game Session tenant keys need a separate audited, Game Design-authenticated association and Game Session's own exact retained-row readback; Account's manifest and numeric/slug similarity cannot establish it. The [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md) owns the remaining implementation and proof. +### Authored-source-bound launch descriptor and exact readback + +Game Design's existing immutable launch-descriptor boundary binds selector provenance to a resolved release; it does not turn selector registration into publication. Game Session remains the launch orchestrator. A canonical launch request names the exact authored-source operation and evidence digest, canonical tenant UUID and tenant-scoped `worldSlug`, together with its stable request identity and requested template/version inputs. Game Design reads and verifies its actual persisted source and template/version ownership before resolving. A private Game Design source key is usable only inside that proved owner association, never as a World or Game Session tenant alias. + +The committed descriptor retains those source fields and the exact resolved template, version, release bundle and Game Design version-state epoch, plus every other resolved launch field and the original request identity/digest. New canonical request and result digests use distinct versioned domains, fixed exhaustive field order, strict UTF-8 byte-length framing and explicit optional presence/value encoding as in [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md). A digest excludes only its own derived value, not an applicable source, request or result field. Source identity, release attestation and the launch result remain independently verified evidence; none substitutes for another. + +The closed binding schema has `schemaVersion=1`. Its request preimage begins with the segment `game-design-authored-world-launch-descriptor-request/v1`, followed by field-name/value segment pairs in this order: `schemaVersion`, `targetNamespace`, `controlPlaneRequestId`, `canonicalTenantId`, `worldSlug`, `authoredWorldSourceOperationId`, `authoredWorldSourceEvidenceDigest`, `gameTemplateId`, then presence/value pairs for `requestedScriptPatchVersion`, `sourceVersionId`, `targetVersionId` and `requestedRuntimeFlagsJson`. Each optional pair uses the exact field names `.present` and `.value`; presence is lowercase `true` or `false`, absent values are empty, and present-empty text is distinct from absence. The result preimage begins with `game-design-authored-world-launch-descriptor-result/v1`, carries the same ordered request pairs, then `requestDigest`, `launchDescriptorId`, `versionId`, presence/value for `scriptPatchVersion`, `runtimeFlagsJson`, `generationConfigRevision`, `versionStateEpoch`, `releaseBundleId`, `publishedReleaseBundleRef`, and presence/value for `remapSetId`. Only `resultDigest` is excluded from that result preimage. Every segment is decimal UTF-8 byte length, `:`, and its exact strict UTF-8 bytes; no trimming, case folding or Unicode normalization occurs. UUIDs are canonical non-nil text, counters use positive canonical decimal text, and each digest is `sha256:` plus 64 lowercase hexadecimal digits. Numeric template/version/release representation in this candidate remains the explicitly tracked owner-graph limitation, not a new canonical identity rule. + +Only the exact same-namespace Game Session workload may resolve a new canonical descriptor. Its request claim and immutable result commit atomically in the existing descriptor family. An identical retry returns the stored descriptor without resolving changed defaults, another version or another release. Conflicting source, scope or request input denies without replacing the original. Retained unbound or unmapped rows cannot be interpreted as canonical evidence. Exact committed readback is non-mutating and checks the complete stored binding; it cannot create a descriptor or repair an association. Only the exact same-namespace Game Session and World workloads may consume that owner readback, and consumers authenticate Game Design rather than trusting a forwarded digest or JWT service claim. + +A committed deterministic business denial is also an immutable launch-request outcome: exact `ResolveLaunchDescriptor` retries return its original error code/message even after template, readiness or release state changes. The same owner family retains the exact request digest and verified source evidence; an unsuccessful resolution does not fabricate a descriptor, version, release or successful-result digest. A new attempt requires a new `controlPlaneRequestId`. Wrong caller, invalid request/source, storage corruption, transient unavailability and ambiguous transaction outcomes are not converted into terminal business receipts. `GetLaunchDescriptor` remains exact successful-descriptor readback rather than a synthetic failed descriptor. + +Before reporting `PREPARING`, World verifies that exact descriptor against its requested scope and separate release attestation, durably retains the binding with its lifecycle result, and proves exact retry/readback. Game Design's version-state epoch is not World's lifecycle epoch. Changed, missing, contradictory or unauthenticated evidence fails closed, and historical descriptor recovery alone is not current activation eligibility. The [World API](../world-management-service/api-contracts.md) owns local lifecycle/materialization consequences; Game Session remains catalog/instance and launch orchestration owner. + +**Implementation and proof status:** This extension is being prepared behind the canonical JOIN/audit checkpoint. Current numeric template/version and owner graph representations remain the separate drift recorded by [Versioning Runtime](../../system-architecture-versioning-runtime.md#implementation-status); this binding is not proof of their completed canonical migration. Producer, receiver, substitution, concurrent exact-retry, immutable readback, fresh/retained isolation and actual PostgreSQL proof remain required. No runtime, catalog or credential activation is authorized. Capability evidence belongs to the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md) and [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md), not this target contract. + ### Audited retained Game Session tenant association This is a distinct, one-time retained-data association, not the Account migration manifest or the normal fresh-creation path. Game Design's approved tenant owner must explicitly attest that one retained Game Session tenant key denotes its persisted canonical tenant. Existing source rows on either side, similar selectors or numeric values do not establish that relation. With no such attestation, the association remains absent and denied. Normal new creation and source intake remain automated owner work; this retained-data approval does not introduce a routine creation-time operator step. @@ -102,7 +118,7 @@ The release-attestation, launch-resolution, version-state, settings, asset-purge The following implementation and proof gaps remain in these live paths: - Automation's internal full-version digest builder still selects tenant-wide definitions/bindings, and its patch builder omits the base from the content digest. The protected `GetDraftDesignDigest` RPC now returns `UNSUPPORTED_SCOPE` for both instead of exposing either inaccurate attestation. Exact version mapping, a versioned base-bound patch digest, cross-version isolation, and wrong-scope digest proof remain required before re-enabling the participant. -- `GetPublishedReleaseBundle`, `ResolveLaunchDescriptor`, `GetVersionState`, and `GetVersionAssetArtifactState` share `requireLaunchAttestationReadAccess`, which accepts any `isInternalService` caller. Concrete per-RPC workload allowlists, caller-to-tenant binding, and wrong-workload/cross-tenant negative proof remain absent; the target matrix is recorded in [version control](version-control.md#launch-and-attestation-read-authorization-target-state). +- `GetPublishedReleaseBundle`, `GetVersionState`, and `GetVersionAssetArtifactState` still share `requireLaunchAttestationReadAccess`, which accepts any `isInternalService` caller. Concrete per-RPC workload allowlists, caller-to-tenant binding, and wrong-workload/cross-tenant negative proof remain absent for those reads; the target matrix is recorded in [version control](version-control.md#launch-and-attestation-read-authorization-target-state). The separately prepared `ResolveLaunchDescriptor` and `GetLaunchDescriptor` instead require the exact verified peers in the [source-bound descriptor contract](#authored-source-bound-launch-descriptor-and-exact-readback); this does not repair or prove the sibling attestation reads. - `PublishPluginVersion` has no stable request identity or normalized request digest, serializes neither publication nor supersession, and has no database CAS/one-active constraint. Concurrent publication attempts can therefore both report `PUBLISHED`; deterministic winner/loser and retry proof remain absent. The target contract makes supersession one serialized owner decision, but it is a normal-path attempt attached to the winning publication, not a guarantee that every competing publication attempt supersedes another version. - `VersionServiceImpl` rejects an uploaded plugin row in terminal `SUPERSEDED` or `REVOKED_DESIGN` state before export or status mutation, so it cannot return to `PUBLISHED` under the same immutable `pluginVersionId`. Rollback/replacement still requires a new `pluginVersionId`, while the prior terminal row remains an immutable audit record; focused `VersionServiceImplTest` proof covers terminal-state rejection, but new-version rollback proof remains absent. - The live `PublishPluginVersionRequest` carries `distribution_manifest_hash` and `distribution_manifest_path`, but the idempotent comparison self-compares stored values and the normal path replaces both with newly exported values. Those inputs are neither removed nor bound as exact expected values, so a changed retry can replay success. The target write contract must choose one path explicitly: remove generated manifest fields from the request, or include them in the request identity/digest and exact validation. diff --git a/design/architecture/microservices/game-design-service/game-templates.md b/design/architecture/microservices/game-design-service/game-templates.md index 5fe7c4e939..84ac99aff8 100644 --- a/design/architecture/microservices/game-design-service/game-templates.md +++ b/design/architecture/microservices/game-design-service/game-templates.md @@ -158,7 +158,7 @@ Template defaults are design-time inputs only. A resolved `scriptPatchVersion` i ### Resolved Launch Descriptor -Template-driven instance creation must materialize one immutable resolved launch descriptor before any `gameInstanceId` rows are created. The complete tuple and admission contract is canonical in [Versioning & Runtime Configuration](../../system-architecture-versioning-runtime.md#launch-descriptor-version-resolution-rules); this document records the Game Design consequence that template references and defaults are resolved once, then passed through unchanged. Runtime services must not independently reinterpret `GameTemplateDto.config`, re-resolve defaults, or fetch moving-target control-plane state during launch. +Template-driven instance creation must materialize one immutable resolved launch descriptor before any `gameInstanceId` rows are created. The complete tuple and admission contract is canonical in [Versioning & Runtime Configuration](../../system-architecture-versioning-runtime.md#launch-descriptor-version-resolution-rules); the [source-bound descriptor API](./api-contracts.md#authored-source-bound-launch-descriptor-and-exact-readback) owns exact authored-source, request and digest evidence. This document records the Game Design consequence that template references and defaults are resolved once, then passed through unchanged. Runtime services must not independently reinterpret `GameTemplateDto.config`, re-resolve defaults, or fetch moving-target control-plane state during launch. Canonical minimum fields: @@ -218,20 +218,22 @@ Required deterministic failure vocabulary for the first implementation slice: These are application-level launch-preflight outcomes, not transport failures. Retries for the same `controlPlaneRequestId` must return the same deterministic business result until callers intentionally start a new launch attempt with a new `controlPlaneRequestId`. -Illustrative control-plane schema: +The current closed request/result and exact readback schemas are owned by the [source-bound descriptor API](./api-contracts.md#authored-source-bound-launch-descriptor-and-exact-readback). Every launch request binds the canonical authored source; a private numeric owner key is not its public tenant identity. The plugin-selection additions below remain target-only and are absent from the current closed transport and digest schema: -- Request: `ResolveLaunchDescriptorRequest { tenantId, gameTemplateId, controlPlaneRequestId, requestedRuntimeFlags?, requestedScriptPatchVersion?, requestedPluginSelection?: { mode: EMPTY | EXPLICIT | REUSE_ROLLBACK_TARGET, enabledPluginVersions[]? { pluginId, pluginVersionId } }, sourceVersionId?, targetVersionId?, rollbackTargetLaunchDescriptorId? }` -- Response: `ResolveLaunchDescriptorResponse { launchDescriptorId, tenantId, gameTemplateId, versionId, scriptPatchVersion (nullable; explicit null when no patch is pinned), pluginSelectionMode, enabledPluginVersions[] { pluginId, pluginVersionId }, runtimeFlags, generationConfigRevision, versionStateEpoch, remapSetId?, publishedReleaseBundleRef }` +- Target request additions: `requestedPluginSelection?: { mode: EMPTY | EXPLICIT | REUSE_ROLLBACK_TARGET, enabledPluginVersions[]? { pluginId, pluginVersionId } }` and `rollbackTargetLaunchDescriptorId?`. +- Target resolved additions: `pluginSelectionMode` and ordered `enabledPluginVersions[] { pluginId, pluginVersionId }`, retained with exact publication/compatibility evidence. + +Introducing these additions requires coherent closed wire, persistence, digest and proof convergence; unknown fields in the current schema remain rejected. The source-bound descriptor prerequisite does not implement or prove the complete plugin-selected launch contract. The exact transport schema may evolve, but every implementation must preserve the same contract shape: -- request fields identify the template, the launch attempt identity, and any caller-supplied runtime overrides that are allowed to participate in deterministic resolution; +- request fields bind the exact authored-source identity, template, launch attempt, and caller-supplied runtime overrides allowed to participate in deterministic resolution; - response fields are the immutable resolved values consumed by launch-time workflows; - Target contract: `enabledPluginVersions[] { pluginId, pluginVersionId }` is the complete deterministically ordered immutable requested plugin selection for launch and rollback, not proof that Automation has activated runtime state. A presence-capable `requestedPluginSelection` wrapper (or equivalent `oneof`/optional-presence transport) is required; a bare repeated list cannot distinguish rollback omission from explicit empty. The normalized modes are `EMPTY` (fresh omission or explicit `[]`, and rollback explicit `[]`), `REUSE_ROLLBACK_TARGET` (rollback omission with a named target), and `EXPLICIT` (an explicit non-empty set). Fresh omission and explicit empty therefore resolve to the same immutable effective selection `enabledPluginVersions=[]`; rollback omission copies the named target's exact recorded selection, while rollback explicit empty resolves to an empty selection. No mode may infer template plugin defaults, `latest`, or another moving target. The Game Design-owned persisted launch-descriptor record binds this mode and selection to immutable publication and compatibility evidence; the response need not duplicate that evidence or transport mutable/current policy evidence. Before persistence, Game Design sorts tuples ascending by `pluginId` and then `pluginVersionId`, comparing the canonical UTF-8 byte representation of each already validated opaque identifier with no locale collation, case folding, or alternate normalization. The selection must contain at most one entry per `pluginId`; a duplicate `pluginId` is a deterministic validation failure because the scoped Automation registry has one active version per plugin. Tenant `READY` is the selected script patch's gate, not a plugin lifecycle state. Every plugin selection must prove publication as `PUBLISHED` and exact compatibility with the resolved base `versionId`, its `abilitySchemaDigest`, and the descriptor's release attestation. Signed and operator-permitted unsigned provenance evidence is defined by the [Modding Framework](./modding-framework.md#signing-and-key-lifecycle-required). These are design-time eligibility predicates, not plugin runtime readiness. The persisted mode, selection, order, and bound evidence are reused unchanged for retries with the same `controlPlaneRequestId`. A fresh rollback that reuses a prior selection must name its exact Game Design-owned `rollbackTargetLaunchDescriptorId`; Game Design verifies that descriptor's tenant, template, and `versionId` match the requested rollback target, copies its ordered plugin selection into the new rollback descriptor, and revalidates every selected plugin against the recorded target release. It does not locate the selection from `sourceVersionId`/`targetVersionId` or a mutable alias. A `SUPERSEDED` or otherwise ineligible recorded selection fails deterministically unless the new request supplies a complete explicit replacement set as described below. An exact retry of an already-bound request returns its stored result without re-resolving or revalidating against newer publication state. That descriptor replay does not bypass runtime checks: before any activation or runtime-state change, Automation rechecks current Game Design publication and rejects every state other than `PUBLISHED`, including `REVOKED_DESIGN`. After launch, Automation performs the separate activation step and validates each selected exact `(pluginId, pluginVersionId, bindingId)` tuple against its runtime-state/activation fence. - A new launch or rollback request's `requestedPluginSelection` mode and selection are normalized before validation and included together in the request's idempotency digest. For a fresh launch without `rollbackTargetLaunchDescriptorId`, an omitted wrapper normalizes to `EMPTY` and an explicitly present empty wrapper also normalizes to `EMPTY`; both produce immutable `enabledPluginVersions=[]`. Every rollback request carries a named `rollbackTargetLaunchDescriptorId` to bind the recorded target and audit history. With that named target, an omitted wrapper normalizes to `REUSE_ROLLBACK_TARGET` and copies that descriptor's exact recorded selection; an explicitly empty wrapper normalizes to `EMPTY` and creates a new empty selection; an explicit non-empty wrapper normalizes to `EXPLICIT` and creates a new descriptor selection. The digest includes the normalized mode, the complete canonicalized selection, and the named rollback target identity when present, so presence semantics cannot be lost even when effective selections are equal. The canonical sorting, one-entry-per-`pluginId`, publication, ability-schema compatibility, and release-attestation rules above apply before computing the digest. A new request replacing an ineligible recorded plugin must therefore supply the full desired set; an exact retry returns the stored result, mode, and selection without re-resolution. - Current implementation behavior: `GetPublishedReleaseBundle` returns the bundle `id` and `generationConfigRevision` rather than a separate reference field, so the compatibility path reconstructs `prb:::` from request scope and the returned `bundle.id`. It must compare that value byte-for-byte with the descriptor reference and separately compare the attested `generationConfigRevision`; this format is not the target API contract. - Target convergence: `GetPublishedReleaseBundle` returns an owner-generated opaque `publishedReleaseBundleRef`. Consumers preserve and compare that value byte-for-byte without parsing its format, reconstructing it from identifiers, treating it as a raw UUID, or inventing another release alias. -- A request with the same `(tenantId, gameTemplateId, controlPlaneRequestId)` and the same input fields must return the same descriptor values; a request with a different `controlPlaneRequestId` is a new launch attempt and may resolve against newer valid state. +- A request with the same canonical namespace/tenant-qualified `controlPlaneRequestId` and exact input fields must return the same descriptor values under the [source-bound API](./api-contracts.md#authored-source-bound-launch-descriptor-and-exact-readback); a different `controlPlaneRequestId` is a new launch attempt and may resolve against newer valid state. Changing the template, world or source cannot bypass the original request claim. - Idempotent retries that previously produced a deterministic business failure must return the same failure code and resolved context (where applicable) rather than re-evaluating against newer publish, patch, or template state. - If callers change any semantically relevant input field while reusing the same `controlPlaneRequestId`, the request must fail deterministically as an idempotency-key misuse rather than silently creating a second descriptor record. diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index c366d89015..10272ededd 100644 --- a/design/architecture/microservices/game-design-service/version-control.md +++ b/design/architecture/microservices/game-design-service/version-control.md @@ -131,7 +131,7 @@ Game Logic's owner-local full-version manifest and provenance remain unproved. I #### Launch and attestation read authorization (target state) -Launch and release-attestation reads are owner-to-owner control-plane APIs, not a generic internal-service read class. Each RPC must have an explicit authenticated workload allowlist and bind the caller's authorized tenant/scope to the request before reading data; a bearer that merely declares `isInternalService` is insufficient. The target launch/read allowlist is: `ResolveLaunchDescriptor` — Game Session only; `GetTemplateReferencePhase` — Game Session for launch preflight and the explicitly named Game Design/retirement-control-plane workload for cutover tooling; `GetPublishedReleaseBundle` — Game Session, World Management, and Automation & Scripting; `GetVersionState` and `GetVersionAssetArtifactState` — Game Session and World Management for launch/activation reads. `GetVersionAssetArtifactState` also has a separate operator-diagnostic use: Logging & Admin may broker an authenticated read for operators, and CI/runbook automation may use only a dedicated named operator-read workload identity (or the Logging & Admin operator surface), never a generic internal-service bearer. That operator path is diagnostic evidence and does not grant launch or mutation authority. Each request must exact-bind its tenant and version/template/request scope (including source/target versions where present), and the owner must reject a wrong workload, cross-tenant scope, omitted scope, or changed replay identity before returning a descriptor, attestation, lifecycle state, or artifact state. Focused proof must exercise every allowlisted caller and a denied internal workload plus cross-tenant requests for each RPC, including the separate operator-read path where it is implemented. +Launch and release-attestation reads are owner-to-owner control-plane APIs, not a generic internal-service read class. Each RPC must have an explicit authenticated workload allowlist and bind the caller's authorized tenant/scope to the request before reading data; a bearer that merely declares `isInternalService` is insufficient. The target launch/read allowlist is: `ResolveLaunchDescriptor` — Game Session only; `GetLaunchDescriptor` — Game Session and World Management for the [exact source-bound descriptor readback](api-contracts.md#authored-source-bound-launch-descriptor-and-exact-readback); `GetTemplateReferencePhase` — Game Session for launch preflight and the explicitly named Game Design/retirement-control-plane workload for cutover tooling; `GetPublishedReleaseBundle` — Game Session, World Management, and Automation & Scripting; `GetVersionState` and `GetVersionAssetArtifactState` — Game Session and World Management for launch/activation reads. `GetVersionAssetArtifactState` also has a separate operator-diagnostic use: Logging & Admin may broker an authenticated read for operators, and CI/runbook automation may use only a dedicated named operator-read workload identity (or the Logging & Admin operator surface), never a generic internal-service bearer. That operator path is diagnostic evidence and does not grant launch or mutation authority. Each request must exact-bind its tenant and version/template/request scope (including source/target versions where present), and the owner must reject a wrong workload, cross-tenant scope, omitted scope, or changed replay identity before returning a descriptor, attestation, lifecycle state, or artifact state. Focused proof must exercise every allowlisted caller and a denied internal workload plus cross-tenant requests for each RPC, including the separate operator-read path where it is implemented. In addition to domain-service digests, publish safety requires a Game Design control-plane digest: diff --git a/design/architecture/microservices/game-session-service/README.md b/design/architecture/microservices/game-session-service/README.md index c13327621a..32342839de 100644 --- a/design/architecture/microservices/game-session-service/README.md +++ b/design/architecture/microservices/game-session-service/README.md @@ -32,6 +32,8 @@ Target state makes Game Session the authoritative owner of region/tick coordinat First-party context admission currently fails closed. The complete codec is a component boundary, not an enabled bare-`LOGIN` exchange or first-party gameplay proof; independent Gateway keys, canonical identity mapping, and Account producer/consumer proof remain required in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). +The source-bound launch candidate also denies the legacy numeric `StartSession` preflight and numeric cutover compatibility lookup before owner resolution or mutation. Those requests cannot supply the [canonical authored-source descriptor binding](../game-design-service/api-contracts.md#authored-source-bound-launch-descriptor-and-exact-readback); neither retained Game Session associations nor the private Game Design key establishes a World association. Retained-instance stop, restart and lifecycle reads remain separate behavior. Their local proof is not successful canonical launch, replacement, World `PREPARING`, or activation proof; the canonical Game Session/World handoff remains required owner work. + Current seams are narrower: patch/request convergence reads, instance-scoped pause/resume, region-epoch fencing, and existing version-fence paths do not yet prove complete `scriptPinEpoch` propagation, final-effect enforcement, or Game-Session-owned append-only history. Track those implementation and proof gaps in the [Game Session runtime and tick coordination tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#active-gaps). ## Terminology diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 173df32110..4f345bad48 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -245,8 +245,20 @@ The current `worldSnapshotId` remains the deterministic same-scope marker descri The unresolved target work is tracked in [World Runtime and Movement](../../../project-management/implementation-tracking/world-runtime-and-movement.md#active-gaps): Game Session floor allocation from durable region commit authority and Game Logic propagation are target obligations, while World participant floor satisfaction and the opaque component-version plus scoped `servedThroughTickId` response remain unimplemented and unproved. The current proto/request and focused proof do not carry or demonstrate this contract; the exact coordinated wire shape and proof encoding remain implementation gaps. +## Authenticated Authored-Content Intake and Tenant Association + +Fresh World content enters automatically through authenticated Game Design source evidence. World authenticates the Game Design workload and verifies the complete canonical namespace, tenant UUID, world selector and source operation/evidence digest before accepting that association. Draft content remains governed by the existing Game Design-coordinated mutation contract; intake does not fabricate a published release or require a descriptor before that content can be published. Before canonical preparation selects published content, World separately verifies the [immutable launch descriptor](../game-design-service/api-contracts.md#authored-source-bound-launch-descriptor-and-exact-readback), its resolved template/version/release/version-state-epoch binding and the exact local content readback. A forwarded digest, selector receipt or caller-supplied numeric key is not that authority. Normal creation and intake require no operator migration step. + +World owns allocation and retention of its private local storage selectors. It atomically persists the association to the canonical tenant UUID and exact accepted content binding with its intake outcome, then reads back the complete original association and result before acknowledging success. Exact retries preserve the original source, descriptor, content and local association; a changed binding conflicts rather than silently selecting another tenant or release. This association does not itself prove current ACTIVE state or permit gameplay admission. + +Retained World rows use a separate owner-approved, audited association operation, following the existing provenance-backed association pattern but binding World's exact retained-row evidence. World verifies and durably reads back that evidence and the one-to-one canonical association. Account's migration manifest, matching numeric keys, selector similarity and absent history are not World ownership proof. Unmapped, ambiguous or contradictory retained rows remain denied. This exceptional retained-data migration is not part of routine fresh intake, and no association is inferred or repaired during a launch retry. + +The producer, authenticated receiver, exact local content readback, rollback/concurrent retry and fresh/retained isolation proof must pass before this boundary is used by canonical preparation. Private numeric selectors remain internal. Implementation and proof status is recorded in [World Runtime and Movement](../../../project-management/implementation-tracking/world-runtime-and-movement.md#current-status). + ## Initial Admission Hold Contract +Canonical preparation first verifies and durably retains Game Design's exact [authored-source-bound launch descriptor](../game-design-service/api-contracts.md#authored-source-bound-launch-descriptor-and-exact-readback), with authenticated owner readback and immutable retry checks, before reporting `PREPARING`. A source selector receipt does not replace release attestation, and a private source key does not establish a World tenant association. Game Design's version-state epoch remains distinct from this owner's lifecycle epoch; descriptor recovery alone does not prove current ACTIVE eligibility. + [Versioning and Runtime](../../system-architecture-versioning-runtime.md#first-open-from-never-opened-authority) owns the first-OPEN transition and its tagged prior-pointer preconditions. World owns the durable initial-admission hold and authoritative target lifecycle proof. The hold binds one stable initial-admission request/digest, the complete canonical namespace/tenant/realm/playable-namespace/scope, exact target instance/version/ACTIVE epoch, and the precondition tag with its applicable pointer/catalog versions. Private World storage selectors do not replace those identities: any association must come from exact persisted authenticated owner evidence, never numeric equality, slugs or Account's migration manifest. Acquire locks and verifies the exact ACTIVE lifecycle row and commits one immutable hold identity/fence; an exact retry reuses it, and changed bindings conflict without another hold. A nonterminal hold blocks every applicable target termination CAS. World finalizes only from authenticated Game Session readback of the exact hold-bound pointer/audit/outcome commit, or terminalizes an abort only from positive proof that this operation did not commit and its expected prior routing authority remains intact. Missing, contradictory or unavailable evidence remains reconciliation-required and termination-blocking. Expiry is diagnostic input, never automatic release or proof of abort. diff --git a/design/architecture/system-architecture-versioning-runtime.md b/design/architecture/system-architecture-versioning-runtime.md index 9133ef3c2c..ebab20aba8 100644 --- a/design/architecture/system-architecture-versioning-runtime.md +++ b/design/architecture/system-architecture-versioning-runtime.md @@ -293,13 +293,14 @@ Tooling in the Game Design and Logging & Admin services should surface these rel ### Launch Descriptor Version-Resolution Rules +- A canonical authored-world launch consumes the exact [Game Design source-bound descriptor and readback](./microservices/game-design-service/api-contracts.md#authored-source-bound-launch-descriptor-and-exact-readback). Selector-source registration is not publication or release attestation. Game Session orchestrates launch; World verifies and durably retains the descriptor binding before `PREPARING`. Game Design's version-state epoch remains separate from World's lifecycle epoch, and an exact retry cannot replace the stored source/release with newer defaults. This requirement does not declare the numeric identity-representation drift above migrated or activate a runtime path. - A launchable game template resolves to exactly one base `versionId`. - The resolved descriptor pins one complete legal runtime tuple: the base version, immutable published release bundle and manifest, selected `scriptPatchVersion` (if any), and each deterministically ordered enabled `(pluginId, pluginVersionId)` selection. A tuple is launchable only after the selected script patch proves compatibility and tenant readiness, each plugin proves immutable publication and compatibility, and the release attestation, required artifact set, and remap proof pass. Plugin runtime readiness, binding resolution, and current signer, component, and capability policy remain Automation activation/resume gates rather than launch-descriptor predicates. Post-launch `bindingId` is exact plugin provenance and contributes to the canonical stable handler-order identity used before `handlerSequence` assignment; it is retained in the full handler Trigger Identity and audit, but is not itself runtime ordering, deduplication, or replay authority. Assigned `handlerSequence` controls fan-out order, while the complete Command-Handoff Identity controls child deduplication and replay. It remains neither launch-descriptor identity nor execution-fence evidence. Automation-owned `pluginActivationEpoch` and captured `lifecycleRevision` are the separate post-launch runtime fences and are likewise not launch-descriptor identity. See the [Game Templates resolved launch descriptor](./microservices/game-design-service/game-templates.md#resolved-launch-descriptor) owner contract. - `game_template_version_ref` is the canonical source for that base version; other normalized template references must agree with it. - Mixed-version template bundles are invalid for launch and must be rejected during template validation and launch-descriptor resolution rather than interpreted heuristically at runtime. - `scriptPatchVersion` is the only supported per-launch patch override and must reference the same `baseVersionId` as the resolved `versionId`. - Friendly channels such as `production` and `preview` may resolve only at a new launch or rollout. The resolved concrete tuple is recorded before instance identity/admission; later alias movement cannot change an existing descriptor, restart, recovery, or rollback target. Changing any tuple member creates a new tuple. -- `ResolveLaunchDescriptor` is idempotent per `controlPlaneRequestId`: a retry with the same `(tenantId, gameTemplateId, controlPlaneRequestId)` and the same input fields must return the same descriptor values, and it must not re-resolve to a newer attestation, patch, or runtime default. +- `ResolveLaunchDescriptor` claims the canonical namespace/tenant-qualified `controlPlaneRequestId` under the [source-bound descriptor contract](./microservices/game-design-service/api-contracts.md#authored-source-bound-launch-descriptor-and-exact-readback). Exact input retries return the stored descriptor without re-resolving a newer attestation, patch or runtime default; changing the template or source under that same request identity conflicts rather than allocating another descriptor. - A fresh launch attempt with a new `controlPlaneRequestId` may resolve against newer valid published state if the underlying template, attestation, or patch data has advanced. - A retry that already failed with a deterministic business outcome (for example invalid template wiring, missing attestation, stale version-state epoch, or patch override conflict) must return the same failure result for that `controlPlaneRequestId`; callers must not expect retries on the same launch-attempt identity to “pick up” newer control-plane state. - Caller-supplied runtime overrides are only honored when the template leaves the corresponding field unset. If the template already supplies a default, any caller-supplied value for that field is a deterministic launch-descriptor failure instead of being merged heuristically. diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index 88474104b0..6530d1ff66 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -62,7 +62,7 @@ These links add decision provenance only; they do not change existing implementa | `AR-2.1` Typed settings, defaults, scopes, and precedence | `partial` | `proven` for typed settings metadata/defaults, persisted overrides, effective resolution, and command-capability resolution seams; selected presets, operator bootstrap/runtime layers, safety caps, complete precedence proof, and all scoped consumers remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [generated settings reference](../../architecture/generated/platform-settings-reference.md); [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md) | [SettingsAuthorityServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImpl.java); [SharedEffectiveSettingsResolver.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolver.java); [FiremudCommandCapabilitiesProperties.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/config/FiremudCommandCapabilitiesProperties.java); [platform settings publication](../../../config/settings/platform-settings-publication.json); [V6 settings overrides](../../../services/game-design-service/src/main/resources/db/migration/V6__game_settings_overrides.sql) | [SettingsAuthorityServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImplTest.java); [SettingsAuthorityServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/SettingsAuthorityServiceIntegrationTest.java); [SharedEffectiveSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolverTest.java); [EffectiveCommandCapabilitiesSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolverTest.java) | [shared runtime](./shared-runtime-contracts-and-persistence.md); [platform operations](./platform-operations-and-delivery.md); [world runtime](./world-runtime-and-movement.md) | Partial: typed defaults, scopes, persisted overrides, and effective resolution exist, but selected presets, operator bootstrap/runtime layers, caps, and their precedence proof are not implemented. ADR 0012 is accepted and owns the target precedence and constraint contract. | | `AR-2.2` Feature, command, profile, and capability policy | `partial` | `proven` for command-capability resolution, feature-flag, published-command admission, and interpreter seams; complete profile/capability catalog, starter-profile behavior, and full policy-consumer coverage remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [player command model](../../architecture/system-architecture-player-command-model.md); [feature flags](../../architecture/microservices/game-design-service/feature-flags.md); [game templates](../../architecture/microservices/game-design-service/game-templates.md); [ADR 0124](../../architecture/decisions/adr-0124-materialized-starter-profiles-with-conservative-draft-upgrades.md) | [EffectiveCommandCapabilitiesSettingsResolver.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolver.java); [FeatureFlagServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/FeatureFlagServiceImpl.java); [AggregatingTextCommandRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistry.java); [AdmittedTextCommandRegistryResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolver.java); [V23 published commands](../../../services/game-design-service/src/main/resources/db/migration/V23__published_command_definitions.sql) | [EffectiveCommandCapabilitiesSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolverTest.java); [AggregatingTextCommandRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistryTest.java); [AdmittedTextCommandRegistryResolverTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolverTest.java); [TextCommandInterpreterCapabilityTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterCapabilityTest.java) | [player experience](./player-experience-commands-and-communication.md); [player access](./player-access-and-session.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [automation](./automation-and-scheduler-runtime.md); [platform operations](./platform-operations-and-delivery.md) | Partial: command capability resolution, feature flags, and published command admission exist, but the complete profile/capability catalog, starter-profile behavior, and full policy-consumer coverage are not implemented. ADR 0124 defines materialized starter-profile content and conservative Draft upgrades; implementation and focused proof remain incomplete. | | `AR-2.3` Tenant/game overrides, safety caps, validation, and effective configuration | `partial` | `proven` only for tenant/game settings persistence, validation, functional effective resolution/readback, and resolver seams; the current route authorization does not enforce tenant binding: the shared classifier accepts a tenant-scoped privileged role for any tenant and the controller accepts unbound tenant or session selectors, so cross-tenant effective-settings reads are currently possible. Cross-tenant denial proof is tracked separately and remains unproved. Safety caps, presets, complete hot-reload/invalidation, and all scoped consumers also remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [generated settings reference](../../architecture/generated/platform-settings-reference.md); [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md) | [SettingsAuthorityServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImpl.java); [SharedSettingsAuthorityReader.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/SharedSettingsAuthorityReader.java); [GameDesignSettingsAuthorityClient.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/GameDesignSettingsAuthorityClient.java); [EffectiveSettingsController.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/controller/EffectiveSettingsController.java); [V6 settings overrides](../../../services/game-design-service/src/main/resources/db/migration/V6__game_settings_overrides.sql) | [SettingsAuthorityServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImplTest.java); [SettingsAuthorityServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/SettingsAuthorityServiceIntegrationTest.java); [SharedEffectiveSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolverTest.java); [EffectiveSettingsControllerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/controller/EffectiveSettingsControllerIntegrationTest.java) | [shared runtime](./shared-runtime-contracts-and-persistence.md); [world runtime](./world-runtime-and-movement.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [platform operations](./platform-operations-and-delivery.md) | Partial: tenant/game persistence, validation, and functional effective readback/resolver seams exist, but route-aware authorization, scoped/global role binding, cross-tenant denial proof, safety caps, presets, complete hot-reload/invalidation, and all scoped consumers remain incomplete under accepted [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md); implementation and proof gaps remain. | -| `AR-3.1` Runtime instance launch, lifecycle, and termination | `partial` | `proven` for launch-descriptor, game-instance lifecycle, world-instance activation, failure, and termination seams; Automation `READY` join, initial world-event scheduling, generator-input completeness, and full multi-participant launch convergence remain unproved. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md); [game templates](../../architecture/microservices/game-design-service/game-templates.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md) | [LaunchDescriptorServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java); [GameInstanceServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java); [WorldInstanceActivationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImpl.java); [WorldLifecycleCommandServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java); [V11 launch descriptor](../../../services/game-design-service/src/main/resources/db/migration/V11__launch_descriptor_framework.sql); [V12 world activation](../../../services/world-management-service/src/main/resources/db/migration/V12__world_instance_activation.sql) | [LaunchDescriptorServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java); [LaunchDescriptorServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java); [GameInstanceServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java); [GameInstanceServiceLifecycleIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java); [WorldInstanceActivationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [automation](./automation-and-scheduler-runtime.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: launch descriptors and world/game instance prepare, activation, failure, and termination seams exist, but Automation `READY` is not joined, initial world events are not scheduled, generator inputs remain partly hardcoded, and full multi-participant launch convergence is absent. Accepted replacement namespace and database-authoritative lifecycle decisions now define the target boundary; namespace-aware cutover, owner cleanup acknowledgement, and complete launch convergence remain unproved. | +| `AR-3.1` Runtime instance launch, lifecycle, and termination | `partial` | `partial` component proof for retained lifecycle and earlier World seams. Numeric launch/cutover now deny before mutation; new source-bound descriptor component proof is being validated. Canonical launch, replacement, World preparation/activation, Automation `READY`, initial scheduling and generator-input convergence remain unproved. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md); [game templates](../../architecture/microservices/game-design-service/game-templates.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md) | [LaunchDescriptorServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java); [GameInstanceServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java); [WorldInstanceActivationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImpl.java); [WorldLifecycleCommandServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java); [V11 launch descriptor](../../../services/game-design-service/src/main/resources/db/migration/V11__launch_descriptor_framework.sql); [V12 world activation](../../../services/world-management-service/src/main/resources/db/migration/V12__world_instance_activation.sql) | [LaunchDescriptorServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java); [LaunchDescriptorServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java); [GameInstanceServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java); [GameInstanceServiceLifecycleIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java); [WorldInstanceActivationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [automation](./automation-and-scheduler-runtime.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: source-bound descriptor preparation and retained lifecycle behavior exist; unsupported numeric start/cutover are denied, so earlier positive numeric preflight tests are not proof of the canonical launch path. Automation `READY` is not joined, initial world events are not scheduled, generator inputs remain partly hardcoded, and full multi-participant launch convergence is absent. Accepted replacement namespace and database-authoritative lifecycle decisions now define the target boundary; namespace-aware cutover, owner cleanup acknowledgement, and complete launch convergence remain unproved. | | `AR-3.2` Release readiness, compatibility, and propagation | `partial` | `proven` for publish-gate, digest-read, release-bundle, launch-descriptor, and compatibility-check seams; target-commit convergence, coordinated digest-schema adoption, Automation readiness propagation, complete attestation tuples, and environment-promotion behavior remain unproved. | [Promotion attestation](../../architecture/system-architecture-promotion-attestation.md); [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [Game Design version control](../../architecture/microservices/game-design-service/version-control.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0094](../../architecture/decisions/adr-0094-explicit-cohesive-runtime-release-tuples.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md); [ADR 0096](../../architecture/decisions/adr-0096-attested-publication-gate-and-quarantined-failed-assets.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md) | [PublishGateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java); [PublishedReleaseBundleServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java); [LaunchDescriptorServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java); [WorldDraftDesignDigestServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImpl.java); [InstanceCutoverCompatibilityServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InstanceCutoverCompatibilityServiceImpl.java); [V14 recorded participant digests](../../../services/game-design-service/src/main/resources/db/migration/V14__recorded_participant_digest.sql) | [PublishGateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [LaunchDescriptorServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java); [WorldDraftDesignDigestServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java); [EntityDraftDesignDigestServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImplTest.java); [InstanceCutoverCompatibilityServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InstanceCutoverCompatibilityServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [automation](./automation-and-scheduler-runtime.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: publish gates, digest reads, release bundles, and compatibility checks exist, but actual target-commit convergence, coordinated digest schema adoption, Automation readiness propagation, and complete environment-promotion evidence are not established. Accepted publication, asset, and procedural-generation decisions now define the target readiness and convergence contracts; complete digest/attestation tuples, Automation readiness propagation, and promotion evidence remain incomplete. | | `AR-3.3` Cutover, rollback, hotfix, and script-patch activation | `partial` | `proven` for prepared cutover, pointer-CAS, patch pin/readiness, and plugin activation seams; complete live hotfix/rollback orchestration and downstream runtime-ready, alias, and binding convergence remain unproved. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [scripting control-plane API](../../architecture/system-architecture-scripting-control-plane-api.md); [scripting rollout and rollback](../../architecture/system-architecture-scripting-rollout-and-rollback.md); [ADR 0094](../../architecture/decisions/adr-0094-explicit-cohesive-runtime-release-tuples.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md) | [VersionUpgradePreparationServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/VersionUpgradePreparationServiceImpl.java); [GameSessionAdmissionPointerControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java); [GameSessionVersionUpgradeControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionVersionUpgradeControlPlaneService.java); [AutomationPatchControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneService.java); [AutomationPluginControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneService.java) | [VersionUpgradePreparationServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/VersionUpgradePreparationServiceImplTest.java); [InstanceCutoverCompatibilityServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InstanceCutoverCompatibilityServiceImplTest.java); [AutomationPatchControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneServiceTest.java); [ScriptPatchPinProjectionServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchPinProjectionServiceImplTest.java); [AutomationPluginControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneServiceTest.java) | [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [automation](./automation-and-scheduler-runtime.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: prepared cutover, pointer CAS, patch pin/readiness, and plugin activation seams exist, but complete live hotfix/rollback orchestration and all downstream runtime-ready, alias, and binding convergence remain incomplete. Accepted release-tuple and asset-lifecycle decisions now define immutable runtime selection and CAS-governed publication; complete cutover, rollback, hotfix, and downstream binding enforcement remain incomplete. | | `AR-3.4` Playtest forks, reset, expiry, and isolation | `not-implemented` | `unverified` | [Playtest fork boundary](../../architecture/system-architecture-versioning-runtime.md); [creator journeys](../../product/user-journeys/creators.md); [multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [ADR 0137](../../architecture/decisions/adr-0137-isolated-playtest-state-modes-and-reset.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md); [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md) | No production anchor: no playtest-fork implementation exists. Adjacent context only: [GameInstanceServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java) provides ordinary launch/termination; [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) has no fork/reset contract; [V1 baseline](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) has no playtest-fork state. | No focused executable proof: no fork/playtest production boundary exists to exercise. | [realm routing](./realm-routing-and-playable-state.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [player access](./player-access-and-session.md) | Not implemented: no fork creation/snapshot copy, reset, expiry automation, isolation, or admission contract was found in production code, schema, proto, config, or focused tests. ADR 0122 and ADR 0123 define adjacent namespace/lifecycle boundaries; they do not claim that playtest fork behavior is implemented or proved. | @@ -75,7 +75,7 @@ These links add decision provenance only; they do not change existing implementa - [Game Design ability and action tools](../../architecture/microservices/game-design-service/ability-action-tools.md) defines authored action data, targeting, admission, and effect policy. - [World Management Service](../../architecture/microservices/world-management-service/README.md) owns authoritative Draft/Published world templates, version-scoped mutation, and activation handoff. -Playtest and lifecycle ownership remains with [Versioning & Runtime Configuration](../../architecture/system-architecture-versioning-runtime.md#tenant-owned-runtime-lifecycle-authority) and its [playtest boundary](../../architecture/system-architecture-versioning-runtime.md#fork-snapshot-boundary-for-playtest-realms); [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#account-owned-playtest-grant-contract) owns grants. This tracker owns only publication/launch integration and remains `not-implemented`/`unverified`; fork/reset, grant-expiry, owner-manifest, isolation, and playtest-lifecycle proof are absent, while tenant-owned lifecycle gates and break-glass proof remain incomplete. The ordinary launch-descriptor, game-instance lifecycle, activation, failure, and termination seams already proved for `AR-3.1` are not playtest proof. +Playtest and lifecycle ownership remains with [Versioning & Runtime Configuration](../../architecture/system-architecture-versioning-runtime.md#tenant-owned-runtime-lifecycle-authority) and its [playtest boundary](../../architecture/system-architecture-versioning-runtime.md#fork-snapshot-boundary-for-playtest-realms); [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#account-owned-playtest-grant-contract) owns grants. This tracker owns only publication/launch integration and remains `not-implemented`/`unverified`; fork/reset, grant-expiry, owner-manifest, isolation, and playtest-lifecycle proof are absent, while tenant-owned lifecycle gates and break-glass proof remain incomplete. Earlier numeric launch/lifecycle fixture evidence is neither canonical source-bound launch nor playtest proof; retained lifecycle and World component coverage remain separately scoped under `AR-3.1`. The current owner consequences from [ADR 0112](../../architecture/decisions/adr-0112-typed-bounded-gameplay-effect-extension.md), [ADR 0113](../../architecture/decisions/adr-0113-bounded-pull-settings-distribution-with-freshness-classes.md), [ADR 0114](../../architecture/decisions/adr-0114-command-plan-preview-dry-run-isolation.md), [ADR 0115](../../architecture/decisions/adr-0115-manifest-complete-onload-readiness-without-durable-game-initialization.md), [ADR 0116](../../architecture/decisions/adr-0116-routine-component-migration-and-explicit-emergency-revocation.md), [ADR 0117](../../architecture/decisions/adr-0117-producer-owned-event-schemas-with-one-materialized-catalogue.md), and [ADR 0118](../../architecture/decisions/adr-0118-preselected-exclusive-handlers-and-durable-fanout-ordering.md) are target links only: authored effect policies remain release-pinned typed data; settings consumers need revision/freshness metadata; the isolated command-plan preview remains target-state and unimplemented; patch manifests must enumerate readiness handlers; routine component migration is distinct from emergency security action; producer event manifests feed the Automation catalogue; and handler exclusivity/order is resolved before fan-out. The existing `EA-3.2` creator-facing preview gap and capability/proof statuses, along with `AR-1.1`/`AR-1.3`/`AR-1.5` partial states, are unchanged. @@ -149,9 +149,9 @@ Lifecycle status/proof is also incomplete: artifact and Version epoch checks lac ### Launch, Activation, Cutover, and Termination -Game Design exposes deterministic `ResolveLaunchDescriptor` keyed by `(tenantId, gameTemplateId, controlPlaneRequestId)` and persists one descriptor per key. Same-request retries return the same descriptor or deterministic failure; conflicting request-ID reuse is rejected. The descriptor freezes `versionId`, `scriptPatchVersion`, `runtimeFlags`, `generationConfigRevision`, `versionStateEpoch`, `releaseBundleRef`, and approved replacement `remapSetId` where required. Runtime provisioning consumes that immutable descriptor and must not re-parse template JSON or resolve mutable "latest" control-plane state mid-flight. Game Design also exposes `GetVersionState` and `CompareAndSetVersionState`, and persists approved remap sets through `CreateTemplateRemapSet`, `ApproveTemplateRemapSet`, and `GetTemplateRemapSet`. +The prepared source-bound `ResolveLaunchDescriptor` producer claims `(targetNamespace, canonicalTenantId, controlPlaneRequestId)` before mutable template/version resolution and retains the exact authored-source request and successful result digests in its existing immutable descriptor family. Changed source, world, template or overrides cannot reuse that claim to select another release. `GetLaunchDescriptor` prepares exact readback for verified Game Session and World peers; the canonical request/result schema is owned by the [Game Design API contract](../../architecture/microservices/game-design-service/api-contracts.md#authored-source-bound-launch-descriptor-and-exact-readback). Shared codec/vector unit proof executes locally. The owner candidate also retains typed deterministic business denials in that same immutable request/outcome family, without fabricating descriptor or release IDs. Producer, failed-outcome and physical peer tests are being validated; PostgreSQL execution and exact CI remain required, and none of these components proves release publication or World materialization. The descriptor freezes `versionId`, `scriptPatchVersion`, `runtimeFlags`, `generationConfigRevision`, Game Design's `versionStateEpoch`, `releaseBundleRef`, and approved replacement `remapSetId` where required. Runtime provisioning must consume that immutable descriptor rather than resolve mutable "latest" control-plane state mid-flight. Game Design also exposes `GetVersionState` and `CompareAndSetVersionState`, and persists approved remap sets through `CreateTemplateRemapSet`, `ApproveTemplateRemapSet`, and `GetTemplateRemapSet`. -`StartSession` resolves the descriptor and, before creating `game_instances`, verifies release attestation, published asset artifact proof including manifest hash and required keys, and authoritative version state. Current Game Design launch resolution now denies any requested/template script patch, including replay of a previously persisted patched descriptor, because exact published-for-base and Automation `READY` evidence are unavailable. Unpatched launches can continue through the existing checks. Game Session does not yet independently re-check patch publication/base identity or join Automation's tenant runtime status; those remain required before patched launch is enabled. The typed descriptor and launch-preflight failures include `TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED`, `INVALID_TEMPLATE_CONFIGURATION`, `SCRIPT_PATCH_OVERRIDE_CONFLICT`, `SCRIPT_PATCH_NOT_READY`, `RELEASE_BUNDLE_NOT_FOUND`, `RELEASE_ATTESTATION_MISMATCH`, `VERSION_STATE_EPOCH_STALE`, and `LAUNCH_REMAP_REQUIRED`. This `SCRIPT_PATCH_NOT_READY` denial is containment, not proof of same-base publication or runtime readiness. World Management exposes `PrepareWorldInstance`, `ActivatePreparedWorldInstance`, and `FailPreparedWorldInstance`; its instance-backed `world_instance`, `region_instance`, `zone_instance`, `room_instance`, and `room_instance_exit` rows are keyed by `(tenantId, gameInstanceId)` and activation revalidates release, asset, and epoch proof. Start-up failure marks prepared world state `FAILED_PRE_ACTIVATION`. +The candidate denies legacy numeric `StartSession` preflight and cutover descriptor lookup with `AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED`, before descriptor lookup or lifecycle/pointer/World mutation. There is no canonical source evidence in those requests, and no proved numeric World association; they must not be described as successful unpatched launch. Canonical Game Session orchestration and World durable source-bound `PREPARING` readback remain required before launch can proceed. The former numeric post-preflight preparation/activation, replacement, compensation and ambiguity branches are not proof of that canonical workflow; retained-instance stop/restart and independent lifecycle coverage remain useful but separate. Game Design denies any requested/template script patch because exact published-for-base and Automation `READY` evidence are unavailable. Game Session must independently re-check patch publication/base identity and join Automation's tenant runtime status before patched launch is enabled. The typed descriptor and launch-preflight failures include `TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED`, `INVALID_TEMPLATE_CONFIGURATION`, `SCRIPT_PATCH_OVERRIDE_CONFLICT`, `SCRIPT_PATCH_NOT_READY`, `RELEASE_BUNDLE_NOT_FOUND`, `RELEASE_ATTESTATION_MISMATCH`, `VERSION_STATE_EPOCH_STALE`, and `LAUNCH_REMAP_REQUIRED`. `SCRIPT_PATCH_NOT_READY` is containment, not readiness proof. Existing numeric World `PrepareWorldInstance`, activation and failed-preparation seams do not yet retain the canonical authored-source binding; their presence and earlier fixture results are not proof of the required UUID-qualified owner handoff. Game Session exposes `ValidateInstanceCutoverCompatibility`, `PrepareVersionUpgrade`, and `ExecutePreparedVersionCutover`. Preparation freezes target descriptor identity, approved remap ID, participant results, and checked-at time. Logging & Admin exposes the bounded compatibility read without first creating a preparation row. Cutover requires a matching durable preparation, revalidates it against the current pointer and replacement instance, performs a CAS-guarded pointer move, records the preparation ID in audit history, and makes retries of the same executed request idempotent. Successful preparation records replacement instance, resulting pointer version, execution timestamp, and request ID. diff --git a/design/project-management/implementation-tracking/world-runtime-and-movement.md b/design/project-management/implementation-tracking/world-runtime-and-movement.md index 98407cd6f1..a82386a807 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -6,9 +6,11 @@ This is a non-normative implementation tracker for world runtime and movement. C ## Current Status +**Canonical launch prerequisite:** Current World design/materialization rows and `PrepareWorldInstance` still use World's private numeric tenant key. No World-owned authenticated intake/readback currently associates that key to the complete canonical UUID/content binding. Overseer approved automatic Game Design-authenticated fresh World intake and a separate owner-approved, audited association with exact retained-row evidence; the [World API contract](../../architecture/microservices/world-management-service/api-contracts.md#authenticated-authored-content-intake-and-tenant-association) owns this boundary. Producer, receiver, exact content/association readback, retry/rollback and retained-row proof remain required. Numeric similarity, selectors and Account's migration manifest are not substitutes, and no runtime activation is authorized. + The canonical launch correction must also supply genuinely fresh instance creation, not merely attach a UUID carrier to the legacy prepare call: Game Session's `game_instances.tenant_id` and World's lifecycle/topology tenant selectors remain required numeric fields on this tree. A fresh canonical catalog provides no numeric tenant alias. Widen the actual owner instance/lifecycle representation and source-qualified creation/readback together; adding a binding table while inventing a numeric tenant selector would not close this gate. Exact retained instance associations remain separately source-proved and cannot be inferred from the Game Session row number or an Account mapping. -The [Game Design authored-world source](../../architecture/microservices/game-design-service/api-contracts.md#authored-world-source-registration-and-game-session-readback) proves selector provenance, not a release or a World template lookup. Its private source game key cannot be reused as a World tenant association. The precise binding from that source operation/evidence and `worldSlug` to the launch template and resolved version/release remains an owner-contract decision sent to Overseer; the proposed extension belongs to Game Design's existing authenticated launch descriptor, not a guessed numeric bridge. No such binding, UUID-scoped World materialization or canonical launch is implemented or proved yet. +The [Game Design authored-world source](../../architecture/microservices/game-design-service/api-contracts.md#authored-world-source-registration-and-game-session-readback) proves selector provenance, not a release or a World template lookup. Its private source game key cannot be reused as a World tenant association. Overseer approved the [existing launch descriptor extension](../../architecture/microservices/game-design-service/api-contracts.md#authored-source-bound-launch-descriptor-and-exact-readback) binding source operation/evidence, canonical tenant/world and resolved template/version/bundle/Game Design epoch. Game Session remains orchestrator; World must verify and durably read back that binding before `PREPARING`, with its lifecycle epoch separate. Producer and receiver implementation is in preparation, not proved canonical materialization or activation. The canonical Unit 1B tree does not yet contain a persisted authenticated launch association from Game Session's canonical catalog/instance identities to World's lifecycle row. Existing start/prepare paths still carry numeric tenant/instance/template/version selectors and drop the persisted Game Session instance UUID; the fresh canonical catalog deliberately supplies no numeric tenant alias. The separately prepared #2939 numeric `NO_PRIOR_POINTER` hold is therefore not a compatible canonical first-OPEN handoff. Required work is an explicit persisted owner launch binding and authenticated exact readback, both tagged initial-hold modes, an ACTIVE epoch fence, termination blocking while unresolved, and atomic Game Session pointer/audit/outcome proof. Retained associations require authoritative source evidence rather than guessed mapping. See the [initial hold owner contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-hold-contract). No canonical World hold, OPEN runtime composition or activation is claimed by the current receipt/CLOSED checkpoint. diff --git a/protos/game-design/v1/game_design_service.proto b/protos/game-design/v1/game_design_service.proto index b7739f7145..67079e8d13 100644 --- a/protos/game-design/v1/game_design_service.proto +++ b/protos/game-design/v1/game_design_service.proto @@ -35,6 +35,7 @@ service GameDesignService { returns (CompareAndSetVersionStateResponse); rpc ResolveLaunchDescriptor(ResolveLaunchDescriptorRequest) returns (ResolveLaunchDescriptorResponse); + rpc GetLaunchDescriptor(GetLaunchDescriptorRequest) returns (GetLaunchDescriptorResponse); rpc CreateTemplateRemapSet(CreateTemplateRemapSetRequest) returns (CreateTemplateRemapSetResponse); rpc ApproveTemplateRemapSet(ApproveTemplateRemapSetRequest) @@ -337,13 +338,16 @@ message CompareAndSetVersionStateResponse { } message ResolveLaunchDescriptorRequest { - string tenant_id = 1; + string canonical_tenant_id = 1; int64 game_template_id = 2; string control_plane_request_id = 3; optional string requested_script_patch_version = 4; optional int64 source_version_id = 5; optional int64 target_version_id = 6; optional string requested_runtime_flags_json = 7; + string world_slug = 8; + string authored_world_source_operation_id = 9; + string expected_authored_world_source_evidence_digest = 10; } message ResolveLaunchDescriptorResponse { @@ -351,6 +355,21 @@ message ResolveLaunchDescriptorResponse { shared.v1.ErrorDetail error = 2; } +message GetLaunchDescriptorRequest { + string request_id = 1; + string canonical_tenant_id = 2; + string world_slug = 3; + string control_plane_request_id = 4; + string expected_request_digest = 5; + string expected_result_digest = 6; +} + +message GetLaunchDescriptorResponse { + string request_id = 1; + LaunchDescriptor launch_descriptor = 2; + shared.v1.ErrorDetail error = 3; +} + message CreateTemplateRemapSetRequest { string tenant_id = 1; int64 source_version_id = 2; @@ -495,7 +514,7 @@ message PublishedReleaseBundle { message LaunchDescriptor { string launch_descriptor_id = 1; - string tenant_id = 2; + string canonical_tenant_id = 2; int64 game_template_id = 3; string control_plane_request_id = 4; int64 version_id = 5; @@ -506,6 +525,33 @@ message LaunchDescriptor { int64 release_bundle_id = 10; string published_release_bundle_ref = 11; string remap_set_id = 12; + AuthoredWorldLaunchDescriptorEvidence authored_world_binding = 13; +} + +message AuthoredWorldLaunchDescriptorEvidence { + int32 schema_version = 1; + string target_namespace = 2; + string control_plane_request_id = 3; + string canonical_tenant_id = 4; + string world_slug = 5; + string authored_world_source_operation_id = 6; + string authored_world_source_evidence_digest = 7; + int64 game_template_id = 8; + optional string requested_script_patch_version = 9; + optional int64 source_version_id = 10; + optional int64 target_version_id = 11; + optional string requested_runtime_flags_json = 12; + string request_digest = 13; + string launch_descriptor_id = 14; + int64 version_id = 15; + optional string script_patch_version = 16; + string runtime_flags_json = 17; + string generation_config_revision = 18; + int64 version_state_epoch = 19; + int64 release_bundle_id = 20; + string published_release_bundle_ref = 21; + optional string remap_set_id = 22; + string result_digest = 23; } message TemplateRemapSet { diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClient.java new file mode 100644 index 0000000000..02808eedf5 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClient.java @@ -0,0 +1,178 @@ +package net.firedevops.firemud.common.gamedesign; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.gamedesign.v1.GameDesignServiceGrpc; + +/** + * Explicit mTLS client for exact authored-world launch descriptor resolution and owner readback. + */ +public final class AuthoredWorldLaunchDescriptorClient + extends AbstractReloadingBlockingGrpcClient< + GameDesignServiceGrpc.GameDesignServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public AuthoredWorldLaunchDescriptorClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + AuthoredWorldLaunchDescriptorClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes only when an owning service explicitly starts this client. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("Authored-world launch descriptor client is closed"); + } + if (initialized) { + return; + } + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException( + "Authored-world launch descriptor client did not initialize a gRPC stub"); + } + initialized = true; + } + + /** Resolves a descriptor for exactly the supplied authored-world request tuple. */ + public AuthoredWorldLaunchDescriptorEvidence resolve( + AuthoredWorldLaunchDescriptorEvidence.Request request) { + Objects.requireNonNull(request, "request"); + requireNamespace(request.targetNamespace()); + GameDesignServiceGrpc.GameDesignServiceBlockingStub currentStub = requireStub(); + var response = + currentStub + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .resolveLaunchDescriptor( + AuthoredWorldLaunchDescriptorGrpcCodec.toResolveRequest(request)); + try { + return AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse(request, response); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "Game Design returned invalid authored-world launch descriptor evidence", exception); + } + } + + /** Reads back the immutable result using a separate read request UUID and the complete tuple. */ + public AuthoredWorldLaunchDescriptorEvidence get( + AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest request) { + Objects.requireNonNull(request, "request"); + requireNamespace(request.expectedRequest().targetNamespace()); + GameDesignServiceGrpc.GameDesignServiceBlockingStub currentStub = requireStub(); + var response = + currentStub + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .getLaunchDescriptor(AuthoredWorldLaunchDescriptorGrpcCodec.toGetRequest(request)); + try { + return AuthoredWorldLaunchDescriptorGrpcCodec.fromGetResponse(request, response); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "Game Design returned invalid exact authored-world launch descriptor readback", + exception); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameDesignService(); + } + + @Override + protected String defaultTarget() { + return "game-design-service:6565"; + } + + @Override + protected GameDesignServiceGrpc.GameDesignServiceBlockingStub buildStub(ManagedChannel channel) { + return GameDesignServiceGrpc.newBlockingStub(channel) + .withInterceptors( + new GrpcServerPeerIdentityClientInterceptor( + "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service")) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private GameDesignServiceGrpc.GameDesignServiceBlockingStub requireStub() { + GameDesignServiceGrpc.GameDesignServiceBlockingStub currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Authored-world launch descriptor client is not initialized and available"); + } + return currentStub; + } + + private void requireNamespace(String targetNamespace) { + if (!workloadNamespace.equals(targetNamespace)) { + throw new IllegalArgumentException( + "Launch descriptor request must use the configured workload namespace"); + } + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null) { + throw new IllegalArgumentException("gRPC mTLS configuration is required"); + } + if (tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("Launch descriptor reads require workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "Launch descriptor reads require file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Launch descriptor reads require file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException exception) { + throw new IllegalArgumentException( + "Launch descriptor " + label + " must be a readable file-backed path", exception); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Launch descriptor " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorEvidence.java new file mode 100644 index 0000000000..5a6be36581 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorEvidence.java @@ -0,0 +1,568 @@ +package net.firedevops.firemud.common.gamedesign; + +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; + +/** Closed immutable launch binding evidence for an exact Game Design authored-world source. */ +public record AuthoredWorldLaunchDescriptorEvidence( + int schemaVersion, + String targetNamespace, + String controlPlaneRequestId, + UUID canonicalTenantId, + String worldSlug, + UUID authoredWorldSourceOperationId, + String authoredWorldSourceEvidenceDigest, + long gameTemplateId, + boolean requestedScriptPatchVersionPresent, + String requestedScriptPatchVersion, + boolean sourceVersionIdPresent, + Long sourceVersionId, + boolean targetVersionIdPresent, + Long targetVersionId, + boolean requestedRuntimeFlagsJsonPresent, + String requestedRuntimeFlagsJson, + String requestDigest, + String launchDescriptorId, + long versionId, + boolean scriptPatchVersionPresent, + String scriptPatchVersion, + String runtimeFlagsJson, + String generationConfigRevision, + long versionStateEpoch, + long releaseBundleId, + String publishedReleaseBundleRef, + boolean remapSetIdPresent, + String remapSetId, + String resultDigest) { + public static final int SCHEMA_VERSION = 1; + private static final String REQUEST_DOMAIN = + "game-design-authored-world-launch-descriptor-request/v1"; + private static final String RESULT_DOMAIN = + "game-design-authored-world-launch-descriptor-result/v1"; + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private record Field(String name, String value) {} + + /** The exact request values, including presence for every optional field. */ + public record Request( + String targetNamespace, + String controlPlaneRequestId, + UUID canonicalTenantId, + String worldSlug, + UUID authoredWorldSourceOperationId, + String authoredWorldSourceEvidenceDigest, + long gameTemplateId, + boolean requestedScriptPatchVersionPresent, + String requestedScriptPatchVersion, + boolean sourceVersionIdPresent, + Long sourceVersionId, + boolean targetVersionIdPresent, + Long targetVersionId, + boolean requestedRuntimeFlagsJsonPresent, + String requestedRuntimeFlagsJson) { + public Request { + validateRequest( + targetNamespace, + controlPlaneRequestId, + canonicalTenantId, + worldSlug, + authoredWorldSourceOperationId, + authoredWorldSourceEvidenceDigest, + gameTemplateId, + requestedScriptPatchVersionPresent, + requestedScriptPatchVersion, + sourceVersionIdPresent, + sourceVersionId, + targetVersionIdPresent, + targetVersionId, + requestedRuntimeFlagsJsonPresent, + requestedRuntimeFlagsJson); + } + + public String requestDigest() { + return AuthoredWorldLaunchDescriptorEvidence.requestDigest(this); + } + } + + public AuthoredWorldLaunchDescriptorEvidence { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported authored-world launch descriptor schema"); + } + Request request = + new Request( + targetNamespace, + controlPlaneRequestId, + canonicalTenantId, + worldSlug, + authoredWorldSourceOperationId, + authoredWorldSourceEvidenceDigest, + gameTemplateId, + requestedScriptPatchVersionPresent, + requestedScriptPatchVersion, + sourceVersionIdPresent, + sourceVersionId, + targetVersionIdPresent, + targetVersionId, + requestedRuntimeFlagsJsonPresent, + requestedRuntimeFlagsJson); + requireOptional(scriptPatchVersionPresent, scriptPatchVersion, "scriptPatchVersion"); + requireOptional(remapSetIdPresent, remapSetId, "remapSetId"); + requireText(launchDescriptorId, "launchDescriptorId"); + requirePositive(versionId, "versionId"); + requireText(runtimeFlagsJson, "runtimeFlagsJson"); + requireText(generationConfigRevision, "generationConfigRevision"); + if (versionStateEpoch <= 0) { + throw new IllegalArgumentException("versionStateEpoch must be positive"); + } + requirePositive(releaseBundleId, "releaseBundleId"); + requireText(publishedReleaseBundleRef, "publishedReleaseBundleRef"); + requireDigest(requestDigest, "requestDigest"); + if (!request.requestDigest().equals(requestDigest)) { + throw new IllegalArgumentException("Request digest does not match the exact request tuple"); + } + requireDigest(resultDigest, "resultDigest"); + } + + /** Recomputes both closed digests after construction or deserialization. */ + public void requireValid() { + if (!requestDigest(this.request()).equals(requestDigest) + || !resultDigest(this).equals(resultDigest)) { + throw new IllegalArgumentException("Result digest does not match the immutable descriptor"); + } + } + + public Request request() { + return new Request( + targetNamespace, + controlPlaneRequestId, + canonicalTenantId, + worldSlug, + authoredWorldSourceOperationId, + authoredWorldSourceEvidenceDigest, + gameTemplateId, + requestedScriptPatchVersionPresent, + requestedScriptPatchVersion, + sourceVersionIdPresent, + sourceVersionId, + targetVersionIdPresent, + targetVersionId, + requestedRuntimeFlagsJsonPresent, + requestedRuntimeFlagsJson); + } + + public static AuthoredWorldLaunchDescriptorEvidence create( + Request request, + String launchDescriptorId, + long versionId, + boolean scriptPatchVersionPresent, + String scriptPatchVersion, + String runtimeFlagsJson, + String generationConfigRevision, + long versionStateEpoch, + long releaseBundleId, + String publishedReleaseBundleRef, + boolean remapSetIdPresent, + String remapSetId) { + Objects.requireNonNull(request, "request"); + AuthoredWorldLaunchDescriptorEvidence provisional = + new AuthoredWorldLaunchDescriptorEvidence( + SCHEMA_VERSION, + request.targetNamespace(), + request.controlPlaneRequestId(), + request.canonicalTenantId(), + request.worldSlug(), + request.authoredWorldSourceOperationId(), + request.authoredWorldSourceEvidenceDigest(), + request.gameTemplateId(), + request.requestedScriptPatchVersionPresent(), + request.requestedScriptPatchVersion(), + request.sourceVersionIdPresent(), + request.sourceVersionId(), + request.targetVersionIdPresent(), + request.targetVersionId(), + request.requestedRuntimeFlagsJsonPresent(), + request.requestedRuntimeFlagsJson(), + request.requestDigest(), + launchDescriptorId, + versionId, + scriptPatchVersionPresent, + scriptPatchVersion, + runtimeFlagsJson, + generationConfigRevision, + versionStateEpoch, + releaseBundleId, + publishedReleaseBundleRef, + remapSetIdPresent, + remapSetId, + "sha256:" + "0".repeat(64)); + AuthoredWorldLaunchDescriptorEvidence evidence = + new AuthoredWorldLaunchDescriptorEvidence( + provisional.schemaVersion(), + provisional.targetNamespace(), + provisional.controlPlaneRequestId(), + provisional.canonicalTenantId(), + provisional.worldSlug(), + provisional.authoredWorldSourceOperationId(), + provisional.authoredWorldSourceEvidenceDigest(), + provisional.gameTemplateId(), + provisional.requestedScriptPatchVersionPresent(), + provisional.requestedScriptPatchVersion(), + provisional.sourceVersionIdPresent(), + provisional.sourceVersionId(), + provisional.targetVersionIdPresent(), + provisional.targetVersionId(), + provisional.requestedRuntimeFlagsJsonPresent(), + provisional.requestedRuntimeFlagsJson(), + provisional.requestDigest(), + provisional.launchDescriptorId(), + provisional.versionId(), + provisional.scriptPatchVersionPresent(), + provisional.scriptPatchVersion(), + provisional.runtimeFlagsJson(), + provisional.generationConfigRevision(), + provisional.versionStateEpoch(), + provisional.releaseBundleId(), + provisional.publishedReleaseBundleRef(), + provisional.remapSetIdPresent(), + provisional.remapSetId(), + resultDigest(provisional)); + evidence.requireValid(); + return evidence; + } + + public static String requestDigest(Request request) { + Objects.requireNonNull(request, "request"); + return digest( + REQUEST_DOMAIN, + field("schemaVersion", Integer.toString(SCHEMA_VERSION)), + field("targetNamespace", request.targetNamespace()), + field("controlPlaneRequestId", request.controlPlaneRequestId()), + field("canonicalTenantId", request.canonicalTenantId().toString()), + field("worldSlug", request.worldSlug()), + field( + "authoredWorldSourceOperationId", request.authoredWorldSourceOperationId().toString()), + field("authoredWorldSourceEvidenceDigest", request.authoredWorldSourceEvidenceDigest()), + field("gameTemplateId", Long.toString(request.gameTemplateId())), + optionalPresence( + "requestedScriptPatchVersion", request.requestedScriptPatchVersionPresent()), + optionalValue( + "requestedScriptPatchVersion", + request.requestedScriptPatchVersionPresent(), + request.requestedScriptPatchVersion()), + optionalPresence("sourceVersionId", request.sourceVersionIdPresent()), + optionalValue( + "sourceVersionId", + request.sourceVersionIdPresent(), + decimal(request.sourceVersionId())), + optionalPresence("targetVersionId", request.targetVersionIdPresent()), + optionalValue( + "targetVersionId", + request.targetVersionIdPresent(), + decimal(request.targetVersionId())), + optionalPresence("requestedRuntimeFlagsJson", request.requestedRuntimeFlagsJsonPresent()), + optionalValue( + "requestedRuntimeFlagsJson", + request.requestedRuntimeFlagsJsonPresent(), + request.requestedRuntimeFlagsJson())); + } + + /** Computes the result digest while deliberately excluding only {@code resultDigest}. */ + public static String resultDigest(AuthoredWorldLaunchDescriptorEvidence evidence) { + Objects.requireNonNull(evidence, "evidence"); + return digest( + RESULT_DOMAIN, + field("schemaVersion", Integer.toString(evidence.schemaVersion())), + field("targetNamespace", evidence.targetNamespace()), + field("controlPlaneRequestId", evidence.controlPlaneRequestId()), + field("canonicalTenantId", evidence.canonicalTenantId().toString()), + field("worldSlug", evidence.worldSlug()), + field( + "authoredWorldSourceOperationId", evidence.authoredWorldSourceOperationId().toString()), + field("authoredWorldSourceEvidenceDigest", evidence.authoredWorldSourceEvidenceDigest()), + field("gameTemplateId", Long.toString(evidence.gameTemplateId())), + optionalPresence( + "requestedScriptPatchVersion", evidence.requestedScriptPatchVersionPresent()), + optionalValue( + "requestedScriptPatchVersion", + evidence.requestedScriptPatchVersionPresent(), + evidence.requestedScriptPatchVersion()), + optionalPresence("sourceVersionId", evidence.sourceVersionIdPresent()), + optionalValue( + "sourceVersionId", + evidence.sourceVersionIdPresent(), + decimal(evidence.sourceVersionId())), + optionalPresence("targetVersionId", evidence.targetVersionIdPresent()), + optionalValue( + "targetVersionId", + evidence.targetVersionIdPresent(), + decimal(evidence.targetVersionId())), + optionalPresence("requestedRuntimeFlagsJson", evidence.requestedRuntimeFlagsJsonPresent()), + optionalValue( + "requestedRuntimeFlagsJson", + evidence.requestedRuntimeFlagsJsonPresent(), + evidence.requestedRuntimeFlagsJson()), + field("requestDigest", evidence.requestDigest()), + field("launchDescriptorId", evidence.launchDescriptorId()), + field("versionId", Long.toString(evidence.versionId())), + optionalPresence("scriptPatchVersion", evidence.scriptPatchVersionPresent()), + optionalValue( + "scriptPatchVersion", + evidence.scriptPatchVersionPresent(), + evidence.scriptPatchVersion()), + field("runtimeFlagsJson", evidence.runtimeFlagsJson()), + field("generationConfigRevision", evidence.generationConfigRevision()), + field("versionStateEpoch", Long.toString(evidence.versionStateEpoch())), + field("releaseBundleId", Long.toString(evidence.releaseBundleId())), + field("publishedReleaseBundleRef", evidence.publishedReleaseBundleRef()), + optionalPresence("remapSetId", evidence.remapSetIdPresent()), + optionalValue("remapSetId", evidence.remapSetIdPresent(), evidence.remapSetId())); + } + + /** Returns the exact UTF-8 request preimage for shared producer and consumer proof. */ + public static byte[] requestPreimage(Request request) { + return preimage( + REQUEST_DOMAIN, + field("schemaVersion", Integer.toString(SCHEMA_VERSION)), + field("targetNamespace", request.targetNamespace()), + field("controlPlaneRequestId", request.controlPlaneRequestId()), + field("canonicalTenantId", request.canonicalTenantId().toString()), + field("worldSlug", request.worldSlug()), + field( + "authoredWorldSourceOperationId", request.authoredWorldSourceOperationId().toString()), + field("authoredWorldSourceEvidenceDigest", request.authoredWorldSourceEvidenceDigest()), + field("gameTemplateId", Long.toString(request.gameTemplateId())), + optionalPresence( + "requestedScriptPatchVersion", request.requestedScriptPatchVersionPresent()), + optionalValue( + "requestedScriptPatchVersion", + request.requestedScriptPatchVersionPresent(), + request.requestedScriptPatchVersion()), + optionalPresence("sourceVersionId", request.sourceVersionIdPresent()), + optionalValue( + "sourceVersionId", + request.sourceVersionIdPresent(), + decimal(request.sourceVersionId())), + optionalPresence("targetVersionId", request.targetVersionIdPresent()), + optionalValue( + "targetVersionId", + request.targetVersionIdPresent(), + decimal(request.targetVersionId())), + optionalPresence("requestedRuntimeFlagsJson", request.requestedRuntimeFlagsJsonPresent()), + optionalValue( + "requestedRuntimeFlagsJson", + request.requestedRuntimeFlagsJsonPresent(), + request.requestedRuntimeFlagsJson())); + } + + /** Returns the exact UTF-8 result preimage, excluding only the result digest itself. */ + public static byte[] resultPreimage(AuthoredWorldLaunchDescriptorEvidence evidence) { + Objects.requireNonNull(evidence, "evidence"); + return preimage( + RESULT_DOMAIN, + field("schemaVersion", Integer.toString(evidence.schemaVersion())), + field("targetNamespace", evidence.targetNamespace()), + field("controlPlaneRequestId", evidence.controlPlaneRequestId()), + field("canonicalTenantId", evidence.canonicalTenantId().toString()), + field("worldSlug", evidence.worldSlug()), + field( + "authoredWorldSourceOperationId", evidence.authoredWorldSourceOperationId().toString()), + field("authoredWorldSourceEvidenceDigest", evidence.authoredWorldSourceEvidenceDigest()), + field("gameTemplateId", Long.toString(evidence.gameTemplateId())), + optionalPresence( + "requestedScriptPatchVersion", evidence.requestedScriptPatchVersionPresent()), + optionalValue( + "requestedScriptPatchVersion", + evidence.requestedScriptPatchVersionPresent(), + evidence.requestedScriptPatchVersion()), + optionalPresence("sourceVersionId", evidence.sourceVersionIdPresent()), + optionalValue( + "sourceVersionId", + evidence.sourceVersionIdPresent(), + decimal(evidence.sourceVersionId())), + optionalPresence("targetVersionId", evidence.targetVersionIdPresent()), + optionalValue( + "targetVersionId", + evidence.targetVersionIdPresent(), + decimal(evidence.targetVersionId())), + optionalPresence("requestedRuntimeFlagsJson", evidence.requestedRuntimeFlagsJsonPresent()), + optionalValue( + "requestedRuntimeFlagsJson", + evidence.requestedRuntimeFlagsJsonPresent(), + evidence.requestedRuntimeFlagsJson()), + field("requestDigest", evidence.requestDigest()), + field("launchDescriptorId", evidence.launchDescriptorId()), + field("versionId", Long.toString(evidence.versionId())), + optionalPresence("scriptPatchVersion", evidence.scriptPatchVersionPresent()), + optionalValue( + "scriptPatchVersion", + evidence.scriptPatchVersionPresent(), + evidence.scriptPatchVersion()), + field("runtimeFlagsJson", evidence.runtimeFlagsJson()), + field("generationConfigRevision", evidence.generationConfigRevision()), + field("versionStateEpoch", Long.toString(evidence.versionStateEpoch())), + field("releaseBundleId", Long.toString(evidence.releaseBundleId())), + field("publishedReleaseBundleRef", evidence.publishedReleaseBundleRef()), + optionalPresence("remapSetId", evidence.remapSetIdPresent()), + optionalValue("remapSetId", evidence.remapSetIdPresent(), evidence.remapSetId())); + } + + private static void validateRequest( + String targetNamespace, + String controlPlaneRequestId, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String sourceEvidenceDigest, + long gameTemplateId, + boolean requestedPatchPresent, + String requestedPatch, + boolean sourceVersionPresent, + Long sourceVersion, + boolean targetVersionPresent, + Long targetVersion, + boolean runtimeFlagsPresent, + String runtimeFlags) { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be a canonical DNS label"); + } + Objects.requireNonNull(controlPlaneRequestId, "controlPlaneRequestId"); + if (controlPlaneRequestId.isBlank()) { + throw new IllegalArgumentException("controlPlaneRequestId is required"); + } + if (strictUtf8(controlPlaneRequestId).length > 64) { + throw new IllegalArgumentException("controlPlaneRequestId exceeds its stored byte bound"); + } + requireNonNil(canonicalTenantId, "canonicalTenantId"); + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requireNonNil(sourceOperationId, "authoredWorldSourceOperationId"); + requireDigest(sourceEvidenceDigest, "authoredWorldSourceEvidenceDigest"); + requirePositive(gameTemplateId, "gameTemplateId"); + requireOptional(requestedPatchPresent, requestedPatch, "requestedScriptPatchVersion"); + requireOptional(sourceVersionPresent, sourceVersion, "sourceVersionId"); + if (sourceVersionPresent) { + requirePositive(sourceVersion, "sourceVersionId"); + } + requireOptional(targetVersionPresent, targetVersion, "targetVersionId"); + if (targetVersionPresent) { + requirePositive(targetVersion, "targetVersionId"); + } + requireOptional(runtimeFlagsPresent, runtimeFlags, "requestedRuntimeFlagsJson"); + } + + private static Field optionalPresence(String name, boolean present) { + return field(name + ".present", Boolean.toString(present)); + } + + private static Field optionalValue(String name, boolean present, String value) { + return field(name + ".value", present ? Objects.requireNonNull(value, name) : ""); + } + + private static Field field(String name, String value) { + return new Field(name, value); + } + + private static String digest(String domain, Field... fields) { + try { + return "sha256:" + + HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(preimage(domain, fields))); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static byte[] preimage(String domain, Field... fields) { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + writeSegment(bytes, domain); + for (Field field : fields) { + writeSegment(bytes, field.name()); + writeSegment(bytes, field.value()); + } + return bytes.toByteArray(); + } + + private static void writeSegment(ByteArrayOutputStream output, String value) { + byte[] bytes = strictUtf8(value); + output.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(bytes); + } + + private static byte[] strictUtf8(String value) { + Objects.requireNonNull(value, "value"); + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + byte[] bytes = new byte[encoded.remaining()]; + encoded.get(bytes); + return bytes; + } catch (CharacterCodingException exception) { + throw new IllegalArgumentException("Digest inputs must contain valid Unicode", exception); + } + } + + private static String decimal(Long value) { + return value == null ? "" : Long.toString(value); + } + + private static void requireOptional(boolean present, Object value, String name) { + if (present != (value != null)) { + throw new IllegalArgumentException(name + " presence does not match its value"); + } + if (value instanceof String text) { + strictUtf8(text); + } + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must not be nil"); + } + } + + private static void requirePositive(long value, String name) { + if (value <= 0) { + throw new IllegalArgumentException(name + " must be positive"); + } + } + + private static void requirePositive(Long value, String name) { + if (value == null || value <= 0) { + throw new IllegalArgumentException(name + " must be positive"); + } + } + + private static void requireText(String value, String name) { + Objects.requireNonNull(value, name); + if (value.isBlank()) { + throw new IllegalArgumentException(name + " is required"); + } + strictUtf8(value); + } + + private static void requireDigest(String value, String name) { + Objects.requireNonNull(value, name); + if (!SHA256.matcher(value).matches()) { + throw new IllegalArgumentException(name + " must be a lowercase SHA-256 digest"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodec.java new file mode 100644 index 0000000000..7a182cdb42 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodec.java @@ -0,0 +1,256 @@ +package net.firedevops.firemud.common.gamedesign; + +import com.google.protobuf.Message; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorResponse; +import net.firedevops.firemud.gamedesign.v1.LaunchDescriptor; +import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorResponse; + +/** Closed mapping and exact-readback validation for authored-world launch descriptor RPCs. */ +public final class AuthoredWorldLaunchDescriptorGrpcCodec { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + + /** Exact owner read identity and the immutable resolve tuple whose result is being recovered. */ + public record GetRequest( + UUID requestId, + AuthoredWorldLaunchDescriptorEvidence.Request expectedRequest, + String expectedResultDigest) { + public GetRequest { + if (requestId == null || NIL_UUID.equals(requestId)) { + throw new IllegalArgumentException( + "A nonnil launch descriptor read request ID is required"); + } + Objects.requireNonNull(expectedRequest, "expectedRequest"); + if (requestId.equals(expectedRequest.authoredWorldSourceOperationId()) + || requestId.toString().equals(expectedRequest.controlPlaneRequestId())) { + throw new IllegalArgumentException( + "Launch descriptor read request ID must be distinct from the original request"); + } + if (expectedResultDigest == null || !SHA256.matcher(expectedResultDigest).matches()) { + throw new IllegalArgumentException( + "Expected launch descriptor result digest must be canonical SHA-256 text"); + } + } + } + + private AuthoredWorldLaunchDescriptorGrpcCodec() {} + + /** Encodes only the exact request fields owned by the immutable shared request value. */ + public static ResolveLaunchDescriptorRequest toResolveRequest( + AuthoredWorldLaunchDescriptorEvidence.Request request) { + Objects.requireNonNull(request, "request"); + ResolveLaunchDescriptorRequest.Builder builder = + ResolveLaunchDescriptorRequest.newBuilder() + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setGameTemplateId(request.gameTemplateId()) + .setControlPlaneRequestId(request.controlPlaneRequestId()) + .setWorldSlug(request.worldSlug()) + .setAuthoredWorldSourceOperationId(request.authoredWorldSourceOperationId().toString()) + .setExpectedAuthoredWorldSourceEvidenceDigest( + request.authoredWorldSourceEvidenceDigest()); + if (request.requestedScriptPatchVersionPresent()) { + builder.setRequestedScriptPatchVersion(request.requestedScriptPatchVersion()); + } + if (request.sourceVersionIdPresent()) { + builder.setSourceVersionId(request.sourceVersionId()); + } + if (request.targetVersionIdPresent()) { + builder.setTargetVersionId(request.targetVersionId()); + } + if (request.requestedRuntimeFlagsJsonPresent()) { + builder.setRequestedRuntimeFlagsJson(request.requestedRuntimeFlagsJson()); + } + return builder.build(); + } + + /** Encodes an exact persisted owner read, kept distinct from the original resolve identity. */ + public static GetLaunchDescriptorRequest toGetRequest(GetRequest request) { + Objects.requireNonNull(request, "request"); + AuthoredWorldLaunchDescriptorEvidence.Request expected = request.expectedRequest(); + return GetLaunchDescriptorRequest.newBuilder() + .setRequestId(request.requestId().toString()) + .setCanonicalTenantId(expected.canonicalTenantId().toString()) + .setWorldSlug(expected.worldSlug()) + .setControlPlaneRequestId(expected.controlPlaneRequestId()) + .setExpectedRequestDigest(expected.requestDigest()) + .setExpectedResultDigest(request.expectedResultDigest()) + .build(); + } + + /** Validates the complete response and flat descriptor duplicates against the exact request. */ + public static AuthoredWorldLaunchDescriptorEvidence fromResolveResponse( + AuthoredWorldLaunchDescriptorEvidence.Request expectedRequest, + ResolveLaunchDescriptorResponse response) { + Objects.requireNonNull(expectedRequest, "expectedRequest"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "ResolveLaunchDescriptor response"); + if (response.hasError()) { + throw new IllegalArgumentException("Game Design rejected launch descriptor resolution"); + } + if (!response.hasLaunchDescriptor()) { + throw new IllegalArgumentException("Launch descriptor resolution returned no descriptor"); + } + return decodeDescriptor(expectedRequest, response.getLaunchDescriptor()); + } + + /** Validates an exact read echo, original request tuple, result digest, and duplicate fields. */ + public static AuthoredWorldLaunchDescriptorEvidence fromGetResponse( + GetRequest request, GetLaunchDescriptorResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "GetLaunchDescriptor response"); + if (response.hasError()) { + throw new IllegalArgumentException("Game Design rejected the exact launch descriptor read"); + } + UUID echoedRequestId = parseCanonicalNonNilUuid(response.getRequestId(), "read request ID"); + if (!request.requestId().equals(echoedRequestId)) { + throw new IllegalArgumentException("Launch descriptor read request ID echo changed"); + } + if (!response.hasLaunchDescriptor()) { + throw new IllegalArgumentException("Exact launch descriptor read returned no descriptor"); + } + AuthoredWorldLaunchDescriptorEvidence evidence = + decodeDescriptor(request.expectedRequest(), response.getLaunchDescriptor()); + if (!request.expectedResultDigest().equals(evidence.resultDigest())) { + throw new IllegalArgumentException( + "Launch descriptor result digest does not match the exact read request"); + } + return evidence; + } + + private static AuthoredWorldLaunchDescriptorEvidence decodeDescriptor( + AuthoredWorldLaunchDescriptorEvidence.Request expectedRequest, LaunchDescriptor descriptor) { + requireNoUnknownFields(descriptor, "LaunchDescriptor"); + if (!descriptor.hasAuthoredWorldBinding()) { + throw new IllegalArgumentException("Launch descriptor has no authored-world binding"); + } + var binding = descriptor.getAuthoredWorldBinding(); + requireNoUnknownFields(binding, "AuthoredWorldLaunchDescriptorEvidence"); + + AuthoredWorldLaunchDescriptorEvidence evidence; + try { + evidence = + new AuthoredWorldLaunchDescriptorEvidence( + binding.getSchemaVersion(), + binding.getTargetNamespace(), + binding.getControlPlaneRequestId(), + parseCanonicalNonNilUuid(binding.getCanonicalTenantId(), "canonical tenant ID"), + binding.getWorldSlug(), + parseCanonicalNonNilUuid( + binding.getAuthoredWorldSourceOperationId(), + "authored-world source operation ID"), + binding.getAuthoredWorldSourceEvidenceDigest(), + binding.getGameTemplateId(), + binding.hasRequestedScriptPatchVersion(), + binding.hasRequestedScriptPatchVersion() + ? binding.getRequestedScriptPatchVersion() + : null, + binding.hasSourceVersionId(), + binding.hasSourceVersionId() ? binding.getSourceVersionId() : null, + binding.hasTargetVersionId(), + binding.hasTargetVersionId() ? binding.getTargetVersionId() : null, + binding.hasRequestedRuntimeFlagsJson(), + binding.hasRequestedRuntimeFlagsJson() + ? binding.getRequestedRuntimeFlagsJson() + : null, + binding.getRequestDigest(), + binding.getLaunchDescriptorId(), + binding.getVersionId(), + binding.hasScriptPatchVersion(), + binding.hasScriptPatchVersion() ? binding.getScriptPatchVersion() : null, + binding.getRuntimeFlagsJson(), + binding.getGenerationConfigRevision(), + binding.getVersionStateEpoch(), + binding.getReleaseBundleId(), + binding.getPublishedReleaseBundleRef(), + binding.hasRemapSetId(), + binding.hasRemapSetId() ? binding.getRemapSetId() : null, + binding.getResultDigest()); + evidence.requireValid(); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Authored-world launch evidence is invalid", exception); + } + + if (!evidence.request().equals(expectedRequest)) { + throw new IllegalArgumentException( + "Launch descriptor does not match the exact authored-world resolve request"); + } + requireFlatDuplicate( + descriptor.getLaunchDescriptorId(), evidence.launchDescriptorId(), "launchDescriptorId"); + requireFlatDuplicate( + descriptor.getCanonicalTenantId(), + evidence.canonicalTenantId().toString(), + "canonicalTenantId"); + requireFlatDuplicate( + descriptor.getGameTemplateId(), evidence.gameTemplateId(), "gameTemplateId"); + requireFlatDuplicate( + descriptor.getControlPlaneRequestId(), + evidence.controlPlaneRequestId(), + "controlPlaneRequestId"); + requireFlatDuplicate(descriptor.getVersionId(), evidence.versionId(), "versionId"); + requireFlatDuplicate( + descriptor.getScriptPatchVersion(), + evidence.scriptPatchVersionPresent() ? evidence.scriptPatchVersion() : "", + "scriptPatchVersion"); + requireFlatDuplicate( + descriptor.getRuntimeFlagsJson(), evidence.runtimeFlagsJson(), "runtimeFlagsJson"); + requireFlatDuplicate( + descriptor.getGenerationConfigRevision(), + evidence.generationConfigRevision(), + "generationConfigRevision"); + requireFlatDuplicate( + descriptor.getVersionStateEpoch(), evidence.versionStateEpoch(), "versionStateEpoch"); + requireFlatDuplicate( + descriptor.getReleaseBundleId(), evidence.releaseBundleId(), "releaseBundleId"); + requireFlatDuplicate( + descriptor.getPublishedReleaseBundleRef(), + evidence.publishedReleaseBundleRef(), + "publishedReleaseBundleRef"); + requireFlatDuplicate( + descriptor.getRemapSetId(), + evidence.remapSetIdPresent() ? evidence.remapSetId() : "", + "remapSetId"); + return evidence; + } + + private static void requireNoUnknownFields(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(label + " contains unsupported fields"); + } + } + + private static UUID parseCanonicalNonNilUuid(String value, String label) { + if (value == null) { + throw new IllegalArgumentException("Canonical nonnil " + label + " is required"); + } + UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Canonical nonnil " + label + " is required", exception); + } + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException("Canonical nonnil " + label + " is required"); + } + return parsed; + } + + private static void requireFlatDuplicate(String actual, String expected, String field) { + if (!Objects.equals(actual, expected)) { + throw new IllegalArgumentException( + "Flat launch descriptor " + field + " does not match evidence"); + } + } + + private static void requireFlatDuplicate(long actual, long expected, String field) { + if (actual != expected) { + throw new IllegalArgumentException( + "Flat launch descriptor " + field + " does not match evidence"); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClientTest.java new file mode 100644 index 0000000000..42df73d19a --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClientTest.java @@ -0,0 +1,165 @@ +package net.firedevops.firemud.common.gamedesign; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.ManagedChannel; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.UUID; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class AuthoredWorldLaunchDescriptorClientTest { + private static final String NAMESPACE = "test"; + private static final UUID TENANT_ID = UUID.fromString("12345678-1234-4234-8234-123456789abc"); + private static final UUID SOURCE_OPERATION_ID = + UUID.fromString("22345678-1234-4234-8234-123456789abc"); + private static final UUID READ_REQUEST_ID = + UUID.fromString("32345678-1234-4234-8234-123456789abc"); + + @Test + void rejectsPlaintextMissingClasspathAndUnreadableTlsMaterialBeforeChannelCreation( + @TempDir Path directory) throws Exception { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + + CommonGrpcClientProperties plaintext = fileBackedMtls(directory); + plaintext.setPlaintext(true); + assertThatThrownBy(() -> newClient(plaintext, channelFactory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + + assertThatThrownBy(() -> newClient(new CommonGrpcClientProperties(), channelFactory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + + CommonGrpcClientProperties classpath = fileBackedMtls(directory); + classpath.setCaCert("classpath:certs/ca.crt"); + assertThatThrownBy(() -> newClient(classpath, channelFactory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + + CommonGrpcClientProperties missingFiles = new CommonGrpcClientProperties(); + missingFiles.setCertChain(directory.resolve("missing-client.crt").toString()); + missingFiles.setPrivateKey(directory.resolve("missing-client.key").toString()); + missingFiles.setCaCert(directory.resolve("missing-ca.crt").toString()); + assertThatThrownBy(() -> newClient(missingFiles, channelFactory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("existing readable file"); + + verifyNoInteractions(channelFactory); + } + + @Test + void deniesResolveAndReadUntilExplicitInitializationAndAfterClose(@TempDir Path directory) + throws Exception { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + AuthoredWorldLaunchDescriptorClient client = + newClient(fileBackedMtls(directory), channelFactory); + var request = request(NAMESPACE); + var getRequest = + new AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest( + READ_REQUEST_ID, request, "sha256:" + "b".repeat(64)); + + assertThatThrownBy(() -> client.resolve(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + assertThatThrownBy(() -> client.get(getRequest)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + verifyNoInteractions(channelFactory); + + client.close(); + assertThatThrownBy(() -> client.resolve(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + verifyNoInteractions(channelFactory); + } + + @Test + void initializesConfiguredTargetWhenFileBackedTlsFilesExist(@TempDir Path directory) + throws Exception { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("game-design.internal:6565"); + CommonGrpcClientProperties tls = fileBackedMtls(directory); + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + ManagedChannel channel = mock(ManagedChannel.class); + when(channelFactory.buildChannel( + eq("game-design.internal:6565"), + eq(6565), + any(CommonGrpcClientProperties.class), + eq(true))) + .thenReturn(channel); + AuthoredWorldLaunchDescriptorClient client = + new AuthoredWorldLaunchDescriptorClient(endpoints, tls, channelFactory, NAMESPACE); + + try { + // The mocked channel factory covers explicit target wiring only; socket peer proof is + // separate. + client.init(); + verify(channelFactory) + .buildChannel( + eq("game-design.internal:6565"), + eq(6565), + any(CommonGrpcClientProperties.class), + eq(true)); + } finally { + client.close(); + } + } + + @Test + void rejectsARequestOutsideTheConfiguredNamespace(@TempDir Path directory) throws Exception { + AuthoredWorldLaunchDescriptorClient client = + newClient(fileBackedMtls(directory), mock(GrpcChannelFactory.class)); + try { + assertThatThrownBy(() -> client.resolve(request("other"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured workload namespace"); + } finally { + client.close(); + } + } + + private static AuthoredWorldLaunchDescriptorClient newClient( + CommonGrpcClientProperties tls, GrpcChannelFactory channelFactory) { + return new AuthoredWorldLaunchDescriptorClient( + new ServiceEndpointsProperties(), tls, channelFactory, NAMESPACE); + } + + private static CommonGrpcClientProperties fileBackedMtls(Path directory) throws Exception { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(Files.writeString(directory.resolve("client.crt"), "certificate").toString()); + tls.setPrivateKey(Files.writeString(directory.resolve("client.key"), "private key").toString()); + tls.setCaCert( + Files.writeString(directory.resolve("server-ca.crt"), "CA certificate").toString()); + return tls; + } + + private static AuthoredWorldLaunchDescriptorEvidence.Request request(String namespace) { + return new AuthoredWorldLaunchDescriptorEvidence.Request( + namespace, + "launch-operation-7", + TENANT_ID, + "copper-coast", + SOURCE_OPERATION_ID, + "sha256:" + "a".repeat(64), + 19L, + false, + null, + false, + null, + false, + null, + false, + null); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorEvidenceTest.java new file mode 100644 index 0000000000..780f890997 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorEvidenceTest.java @@ -0,0 +1,109 @@ +package net.firedevops.firemud.common.gamedesign; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +import java.nio.charset.StandardCharsets; +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class AuthoredWorldLaunchDescriptorEvidenceTest { + private static final String REQUEST_ABSENT_PREIMAGE = + "55:game-design-authored-world-launch-descriptor-request/v113:schemaVersion1:115:targetNamespace4:test21:controlPlaneRequestId5:cp-α17:canonicalTenantId36:12345678-1234-4234-8234-123456789abc9:worldSlug12:copper-coast30:authoredWorldSourceOperationId36:22345678-1234-4234-8234-123456789abc33:authoredWorldSourceEvidenceDigest71:sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa14:gameTemplateId2:1935:requestedScriptPatchVersion.present4:true33:requestedScriptPatchVersion.value11:pätch-🦊23:sourceVersionId.present5:false21:sourceVersionId.value0:23:targetVersionId.present5:false21:targetVersionId.value0:33:requestedRuntimeFlagsJson.present5:false31:requestedRuntimeFlagsJson.value0:"; + private static final String REQUEST_EMPTY_PREIMAGE = + "55:game-design-authored-world-launch-descriptor-request/v113:schemaVersion1:115:targetNamespace4:test21:controlPlaneRequestId5:cp-α17:canonicalTenantId36:12345678-1234-4234-8234-123456789abc9:worldSlug12:copper-coast30:authoredWorldSourceOperationId36:22345678-1234-4234-8234-123456789abc33:authoredWorldSourceEvidenceDigest71:sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa14:gameTemplateId2:1935:requestedScriptPatchVersion.present4:true33:requestedScriptPatchVersion.value11:pätch-🦊23:sourceVersionId.present5:false21:sourceVersionId.value0:23:targetVersionId.present5:false21:targetVersionId.value0:33:requestedRuntimeFlagsJson.present4:true31:requestedRuntimeFlagsJson.value0:"; + private static final String REQUEST_CHANGED_WORLD_PREIMAGE = + "55:game-design-authored-world-launch-descriptor-request/v113:schemaVersion1:115:targetNamespace4:test21:controlPlaneRequestId5:cp-α17:canonicalTenantId36:12345678-1234-4234-8234-123456789abc9:worldSlug12:copper-shore30:authoredWorldSourceOperationId36:22345678-1234-4234-8234-123456789abc33:authoredWorldSourceEvidenceDigest71:sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa14:gameTemplateId2:1935:requestedScriptPatchVersion.present4:true33:requestedScriptPatchVersion.value11:pätch-🦊23:sourceVersionId.present5:false21:sourceVersionId.value0:23:targetVersionId.present5:false21:targetVersionId.value0:33:requestedRuntimeFlagsJson.present5:false31:requestedRuntimeFlagsJson.value0:"; + private static final String RESULT_MAX_PREIMAGE = + "54:game-design-authored-world-launch-descriptor-result/v113:schemaVersion1:115:targetNamespace4:test21:controlPlaneRequestId5:cp-α17:canonicalTenantId36:12345678-1234-4234-8234-123456789abc9:worldSlug12:copper-coast30:authoredWorldSourceOperationId36:22345678-1234-4234-8234-123456789abc33:authoredWorldSourceEvidenceDigest71:sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa14:gameTemplateId2:1935:requestedScriptPatchVersion.present4:true33:requestedScriptPatchVersion.value11:pätch-🦊23:sourceVersionId.present5:false21:sourceVersionId.value0:23:targetVersionId.present5:false21:targetVersionId.value0:33:requestedRuntimeFlagsJson.present5:false31:requestedRuntimeFlagsJson.value0:13:requestDigest71:sha256:ac6fc51a4b81185a33cfe9c84df69e05537a69415a6d8b8fb478a946221e711118:launchDescriptorId11:ld-vector-19:versionId19:922337203685477580726:scriptPatchVersion.present4:true24:scriptPatchVersion.value11:pätch-🦊16:runtimeFlagsJson17:{\"welcome\":\"雪\"}24:generationConfigRevision13:gen-rév-🧭17:versionStateEpoch19:922337203685477580715:releaseBundleId19:922337203685477580725:publishedReleaseBundleRef91:release-bundle:12345678-1234-4234-8234-123456789abc:9223372036854775807:922337203685477580718:remapSetId.present5:false16:remapSetId.value0:"; + private static final String RESULT_CHANGED_EPOCH_PREIMAGE = + "54:game-design-authored-world-launch-descriptor-result/v113:schemaVersion1:115:targetNamespace4:test21:controlPlaneRequestId5:cp-α17:canonicalTenantId36:12345678-1234-4234-8234-123456789abc9:worldSlug12:copper-coast30:authoredWorldSourceOperationId36:22345678-1234-4234-8234-123456789abc33:authoredWorldSourceEvidenceDigest71:sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa14:gameTemplateId2:1935:requestedScriptPatchVersion.present4:true33:requestedScriptPatchVersion.value11:pätch-🦊23:sourceVersionId.present5:false21:sourceVersionId.value0:23:targetVersionId.present5:false21:targetVersionId.value0:33:requestedRuntimeFlagsJson.present5:false31:requestedRuntimeFlagsJson.value0:13:requestDigest71:sha256:ac6fc51a4b81185a33cfe9c84df69e05537a69415a6d8b8fb478a946221e711118:launchDescriptorId11:ld-vector-19:versionId19:922337203685477580726:scriptPatchVersion.present4:true24:scriptPatchVersion.value11:pätch-🦊16:runtimeFlagsJson17:{\"welcome\":\"雪\"}24:generationConfigRevision13:gen-rév-🧭17:versionStateEpoch19:922337203685477580615:releaseBundleId19:922337203685477580725:publishedReleaseBundleRef91:release-bundle:12345678-1234-4234-8234-123456789abc:9223372036854775807:922337203685477580718:remapSetId.present5:false16:remapSetId.value0:"; + + @Test + void requestDigestMatchesIndependentUtf8FramingVectors() { + AuthoredWorldLaunchDescriptorEvidence.Request absentFlags = request("copper-coast", false); + AuthoredWorldLaunchDescriptorEvidence.Request emptyFlags = request("copper-coast", true); + AuthoredWorldLaunchDescriptorEvidence.Request changedWorld = request("copper-shore", false); + + assertEquals( + REQUEST_ABSENT_PREIMAGE, + text(AuthoredWorldLaunchDescriptorEvidence.requestPreimage(absentFlags))); + assertEquals( + "sha256:ac6fc51a4b81185a33cfe9c84df69e05537a69415a6d8b8fb478a946221e7111", + absentFlags.requestDigest()); + assertEquals( + REQUEST_EMPTY_PREIMAGE, + text(AuthoredWorldLaunchDescriptorEvidence.requestPreimage(emptyFlags))); + assertEquals( + "sha256:99207cb6a0d39108465c81fdd2519117237607c7e80b2ad1db07e74217d81f42", + emptyFlags.requestDigest()); + assertEquals( + REQUEST_CHANGED_WORLD_PREIMAGE, + text(AuthoredWorldLaunchDescriptorEvidence.requestPreimage(changedWorld))); + assertEquals( + "sha256:fec25a5c82d0b831feb7018d25b7f76123af23834b1d2ce653a1b9dc97aea4eb", + changedWorld.requestDigest()); + assertNotEquals(absentFlags.requestDigest(), emptyFlags.requestDigest()); + } + + @Test + void resultDigestMatchesIndependentUnicodeAndLongBoundaryVectors() { + AuthoredWorldLaunchDescriptorEvidence maximumCounter = evidence(Long.MAX_VALUE); + AuthoredWorldLaunchDescriptorEvidence changedCounter = evidence(Long.MAX_VALUE - 1); + + assertEquals( + RESULT_MAX_PREIMAGE, + text(AuthoredWorldLaunchDescriptorEvidence.resultPreimage(maximumCounter))); + assertEquals( + "sha256:701c68797b898b696cac24d48dcff4fe25c0856f15965ff7e8b219f7c57acd11", + maximumCounter.resultDigest()); + assertEquals( + RESULT_CHANGED_EPOCH_PREIMAGE, + text(AuthoredWorldLaunchDescriptorEvidence.resultPreimage(changedCounter))); + assertEquals( + "sha256:1b3f500a92a621c901c0f2200a244b3f4d1a120c4416d79469fb11ec77a5cf68", + changedCounter.resultDigest()); + assertNotEquals(maximumCounter.resultDigest(), changedCounter.resultDigest()); + } + + private static AuthoredWorldLaunchDescriptorEvidence evidence(long versionStateEpoch) { + AuthoredWorldLaunchDescriptorEvidence.Request request = request("copper-coast", false); + return AuthoredWorldLaunchDescriptorEvidence.create( + request, + "ld-vector-1", + Long.MAX_VALUE, + true, + "pätch-🦊", + "{\"welcome\":\"雪\"}", + "gen-rév-🧭", + versionStateEpoch, + Long.MAX_VALUE, + "release-bundle:12345678-1234-4234-8234-123456789abc:9223372036854775807:9223372036854775807", + false, + null); + } + + private static AuthoredWorldLaunchDescriptorEvidence.Request request( + String worldSlug, boolean runtimeFlagsPresent) { + return new AuthoredWorldLaunchDescriptorEvidence.Request( + "test", + "cp-α", + UUID.fromString("12345678-1234-4234-8234-123456789abc"), + worldSlug, + UUID.fromString("22345678-1234-4234-8234-123456789abc"), + "sha256:" + "a".repeat(64), + 19L, + true, + "pätch-🦊", + false, + null, + false, + null, + runtimeFlagsPresent, + runtimeFlagsPresent ? "" : null); + } + + private static String text(byte[] bytes) { + return new String(bytes, StandardCharsets.UTF_8); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodecTest.java new file mode 100644 index 0000000000..0282115626 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodecTest.java @@ -0,0 +1,391 @@ +package net.firedevops.firemud.common.gamedesign; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.UnknownFieldSet; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorResponse; +import net.firedevops.firemud.gamedesign.v1.LaunchDescriptor; +import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorResponse; +import org.junit.jupiter.api.Test; + +class AuthoredWorldLaunchDescriptorGrpcCodecTest { + private static final UUID TENANT_ID = UUID.fromString("12345678-1234-4234-8234-123456789abc"); + private static final UUID SOURCE_OPERATION_ID = + UUID.fromString("22345678-1234-4234-8234-123456789abc"); + private static final UUID READ_REQUEST_ID = + UUID.fromString("32345678-1234-4234-8234-123456789abc"); + private static final UUID WRONG_READ_REQUEST_ID = + UUID.fromString("42345678-1234-4234-8234-123456789abc"); + + @Test + void resolvesAndReadsBackSharedDigestVectorWithExactOptionalPresence() { + AuthoredWorldLaunchDescriptorEvidence.Request request = request("test", "copper-coast", false); + net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence evidence = + evidence(request); + + assertThat(request.requestDigest()) + .isEqualTo("sha256:ac6fc51a4b81185a33cfe9c84df69e05537a69415a6d8b8fb478a946221e7111"); + assertThat(evidence.resultDigest()) + .isEqualTo("sha256:701c68797b898b696cac24d48dcff4fe25c0856f15965ff7e8b219f7c57acd11"); + + var resolveWire = AuthoredWorldLaunchDescriptorGrpcCodec.toResolveRequest(request); + assertThat(resolveWire.hasRequestedScriptPatchVersion()).isTrue(); + assertThat(resolveWire.hasSourceVersionId()).isFalse(); + assertThat(resolveWire.hasTargetVersionId()).isFalse(); + assertThat(resolveWire.hasRequestedRuntimeFlagsJson()).isFalse(); + assertThat( + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + request, resolveResponse(evidence))) + .isEqualTo(evidence); + + var emptyFlagsRequest = request("test", "copper-coast", true); + var emptyFlagsWire = AuthoredWorldLaunchDescriptorGrpcCodec.toResolveRequest(emptyFlagsRequest); + assertThat(emptyFlagsWire.hasRequestedRuntimeFlagsJson()).isTrue(); + assertThat(emptyFlagsWire.getRequestedRuntimeFlagsJson()).isEmpty(); + var emptyFlagsEvidence = evidence(emptyFlagsRequest); + var emptyFlagsReadback = + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + emptyFlagsRequest, resolveResponse(emptyFlagsEvidence)); + assertThat(emptyFlagsReadback.requestedRuntimeFlagsJsonPresent()).isTrue(); + assertThat(emptyFlagsReadback.requestedRuntimeFlagsJson()).isEmpty(); + + var getRequest = + new AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest( + READ_REQUEST_ID, request, evidence.resultDigest()); + var getWire = AuthoredWorldLaunchDescriptorGrpcCodec.toGetRequest(getRequest); + assertThat(getWire.getRequestId()).isEqualTo(READ_REQUEST_ID.toString()); + assertThat(getWire.getExpectedRequestDigest()).isEqualTo(request.requestDigest()); + assertThat(getWire.getExpectedResultDigest()).isEqualTo(evidence.resultDigest()); + assertThat( + AuthoredWorldLaunchDescriptorGrpcCodec.fromGetResponse( + getRequest, getResponse(READ_REQUEST_ID.toString(), evidence))) + .isEqualTo(evidence); + } + + @Test + void rejectsAChangedRequestFieldAndWrongNamespace() { + var expected = request("test", "copper-coast", false); + var changedWorld = evidence(request("test", "copper-shore", false)); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + expected, resolveResponse(changedWorld))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact authored-world resolve request"); + + var otherNamespace = evidence(request("other", "copper-coast", false)); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + expected, resolveResponse(otherNamespace))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact authored-world resolve request"); + } + + @Test + void rejectsEveryChangedFlatDescriptorDuplicate() { + var evidence = evidence(request("test", "copper-coast", false)); + LaunchDescriptor descriptor = descriptor(evidence); + + assertFlatDuplicateRejected(descriptor.toBuilder().setLaunchDescriptorId("other").build()); + assertFlatDuplicateRejected(descriptor.toBuilder().setCanonicalTenantId("other").build()); + assertFlatDuplicateRejected(descriptor.toBuilder().setGameTemplateId(20L).build()); + assertFlatDuplicateRejected(descriptor.toBuilder().setControlPlaneRequestId("other").build()); + assertFlatDuplicateRejected(descriptor.toBuilder().setVersionId(20L).build()); + assertFlatDuplicateRejected(descriptor.toBuilder().setScriptPatchVersion("other").build()); + assertFlatDuplicateRejected(descriptor.toBuilder().setRuntimeFlagsJson("other").build()); + assertFlatDuplicateRejected( + descriptor.toBuilder().setGenerationConfigRevision("other").build()); + assertFlatDuplicateRejected(descriptor.toBuilder().setVersionStateEpoch(20L).build()); + assertFlatDuplicateRejected(descriptor.toBuilder().setReleaseBundleId(20L).build()); + assertFlatDuplicateRejected( + descriptor.toBuilder().setPublishedReleaseBundleRef("other").build()); + assertFlatDuplicateRejected(descriptor.toBuilder().setRemapSetId("other").build()); + } + + @Test + void rejectsMissingEvidenceUnknownFieldsAndUnsupportedSchema() { + var request = request("test", "copper-coast", false); + var evidence = evidence(request); + LaunchDescriptor withoutBinding = + descriptor(evidence).toBuilder().clearAuthoredWorldBinding().build(); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + request, + ResolveLaunchDescriptorResponse.newBuilder() + .setLaunchDescriptor(withoutBinding) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("no authored-world binding"); + + var unknown = unknownFields(); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + request, + ResolveLaunchDescriptorResponse.newBuilder() + .setLaunchDescriptor(descriptor(evidence)) + .setUnknownFields(unknown) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + request, + ResolveLaunchDescriptorResponse.newBuilder() + .setLaunchDescriptor( + descriptor(evidence).toBuilder().setUnknownFields(unknown)) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + + var getRequest = + new AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest( + READ_REQUEST_ID, request, evidence.resultDigest()); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromGetResponse( + getRequest, + GetLaunchDescriptorResponse.newBuilder() + .setRequestId(READ_REQUEST_ID.toString()) + .setLaunchDescriptor(descriptor(evidence)) + .setUnknownFields(unknown) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + request, + ResolveLaunchDescriptorResponse.newBuilder() + .setLaunchDescriptor( + descriptor(evidence).toBuilder() + .setAuthoredWorldBinding( + descriptor(evidence).getAuthoredWorldBinding().toBuilder() + .setUnknownFields(unknown))) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + + var unsupportedSchema = + descriptor(evidence).toBuilder() + .setAuthoredWorldBinding( + descriptor(evidence).getAuthoredWorldBinding().toBuilder().setSchemaVersion(2)) + .build(); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + request, + ResolveLaunchDescriptorResponse.newBuilder() + .setLaunchDescriptor(unsupportedSchema) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("invalid"); + } + + @Test + void rejectsConflictingDigestsAndNonmatchingReadEchoOrResult() { + var request = request("test", "copper-coast", false); + var evidence = evidence(request); + var invalidRequestDigest = + descriptor(evidence).toBuilder() + .setAuthoredWorldBinding( + descriptor(evidence).getAuthoredWorldBinding().toBuilder() + .setRequestDigest("sha256:" + "0".repeat(64))) + .build(); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + request, + ResolveLaunchDescriptorResponse.newBuilder() + .setLaunchDescriptor(invalidRequestDigest) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("invalid"); + + var invalidResultDigest = + descriptor(evidence).toBuilder() + .setAuthoredWorldBinding( + descriptor(evidence).getAuthoredWorldBinding().toBuilder() + .setResultDigest("sha256:" + "0".repeat(64))) + .build(); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + request, + ResolveLaunchDescriptorResponse.newBuilder() + .setLaunchDescriptor(invalidResultDigest) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("invalid"); + + var getRequest = + new AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest( + READ_REQUEST_ID, request, evidence.resultDigest()); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromGetResponse( + getRequest, getResponse(WRONG_READ_REQUEST_ID.toString(), evidence))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("echo changed"); + var wrongResult = + new AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest( + READ_REQUEST_ID, request, "sha256:" + "0".repeat(64)); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromGetResponse( + wrongResult, getResponse(READ_REQUEST_ID.toString(), evidence))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("result digest"); + } + + @Test + void requiresDistinctNonnilReadRequestUuid() { + var request = request("test", "copper-coast", false); + assertThatThrownBy( + () -> + new AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest( + new UUID(0L, 0L), request, evidence(request).resultDigest())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("nonnil"); + assertThatThrownBy( + () -> + new AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest( + SOURCE_OPERATION_ID, request, evidence(request).resultDigest())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("distinct"); + } + + private static void assertFlatDuplicateRejected(LaunchDescriptor descriptor) { + var expected = request("test", "copper-coast", false); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + expected, + ResolveLaunchDescriptorResponse.newBuilder() + .setLaunchDescriptor(descriptor) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("does not match evidence"); + } + + private static AuthoredWorldLaunchDescriptorEvidence.Request request( + String namespace, String worldSlug, boolean runtimeFlagsPresent) { + return new AuthoredWorldLaunchDescriptorEvidence.Request( + namespace, + "cp-α", + TENANT_ID, + worldSlug, + SOURCE_OPERATION_ID, + "sha256:" + "a".repeat(64), + 19L, + true, + "pätch-🦊", + false, + null, + false, + null, + runtimeFlagsPresent, + runtimeFlagsPresent ? "" : null); + } + + private static net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence + evidence(AuthoredWorldLaunchDescriptorEvidence.Request request) { + return net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence.create( + request, + "ld-vector-1", + Long.MAX_VALUE, + true, + "pätch-🦊", + "{\"welcome\":\"雪\"}", + "gen-rév-🧭", + Long.MAX_VALUE, + Long.MAX_VALUE, + "release-bundle:12345678-1234-4234-8234-123456789abc:9223372036854775807:9223372036854775807", + false, + null); + } + + private static ResolveLaunchDescriptorResponse resolveResponse( + net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence evidence) { + return ResolveLaunchDescriptorResponse.newBuilder() + .setLaunchDescriptor(descriptor(evidence)) + .build(); + } + + private static GetLaunchDescriptorResponse getResponse( + String requestId, + net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence evidence) { + return GetLaunchDescriptorResponse.newBuilder() + .setRequestId(requestId) + .setLaunchDescriptor(descriptor(evidence)) + .build(); + } + + private static LaunchDescriptor descriptor( + net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence evidence) { + net.firedevops.firemud.gamedesign.v1.AuthoredWorldLaunchDescriptorEvidence.Builder binding = + net.firedevops.firemud.gamedesign.v1.AuthoredWorldLaunchDescriptorEvidence.newBuilder() + .setSchemaVersion(evidence.schemaVersion()) + .setTargetNamespace(evidence.targetNamespace()) + .setControlPlaneRequestId(evidence.controlPlaneRequestId()) + .setCanonicalTenantId(evidence.canonicalTenantId().toString()) + .setWorldSlug(evidence.worldSlug()) + .setAuthoredWorldSourceOperationId(evidence.authoredWorldSourceOperationId().toString()) + .setAuthoredWorldSourceEvidenceDigest(evidence.authoredWorldSourceEvidenceDigest()) + .setGameTemplateId(evidence.gameTemplateId()) + .setRequestDigest(evidence.requestDigest()) + .setLaunchDescriptorId(evidence.launchDescriptorId()) + .setVersionId(evidence.versionId()) + .setRuntimeFlagsJson(evidence.runtimeFlagsJson()) + .setGenerationConfigRevision(evidence.generationConfigRevision()) + .setVersionStateEpoch(evidence.versionStateEpoch()) + .setReleaseBundleId(evidence.releaseBundleId()) + .setPublishedReleaseBundleRef(evidence.publishedReleaseBundleRef()) + .setResultDigest(evidence.resultDigest()); + if (evidence.requestedScriptPatchVersionPresent()) { + binding.setRequestedScriptPatchVersion(evidence.requestedScriptPatchVersion()); + } + if (evidence.sourceVersionIdPresent()) { + binding.setSourceVersionId(evidence.sourceVersionId()); + } + if (evidence.targetVersionIdPresent()) { + binding.setTargetVersionId(evidence.targetVersionId()); + } + if (evidence.requestedRuntimeFlagsJsonPresent()) { + binding.setRequestedRuntimeFlagsJson(evidence.requestedRuntimeFlagsJson()); + } + if (evidence.scriptPatchVersionPresent()) { + binding.setScriptPatchVersion(evidence.scriptPatchVersion()); + } + if (evidence.remapSetIdPresent()) { + binding.setRemapSetId(evidence.remapSetId()); + } + return LaunchDescriptor.newBuilder() + .setLaunchDescriptorId(evidence.launchDescriptorId()) + .setCanonicalTenantId(evidence.canonicalTenantId().toString()) + .setGameTemplateId(evidence.gameTemplateId()) + .setControlPlaneRequestId(evidence.controlPlaneRequestId()) + .setVersionId(evidence.versionId()) + .setScriptPatchVersion( + evidence.scriptPatchVersionPresent() ? evidence.scriptPatchVersion() : "") + .setRuntimeFlagsJson(evidence.runtimeFlagsJson()) + .setGenerationConfigRevision(evidence.generationConfigRevision()) + .setVersionStateEpoch(evidence.versionStateEpoch()) + .setReleaseBundleId(evidence.releaseBundleId()) + .setPublishedReleaseBundleRef(evidence.publishedReleaseBundleRef()) + .setRemapSetId(evidence.remapSetIdPresent() ? evidence.remapSetId() : "") + .setAuthoredWorldBinding(binding.build()) + .build(); + } + + private static UnknownFieldSet unknownFields() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + } +} diff --git a/services/game-design-service/build.gradle.kts b/services/game-design-service/build.gradle.kts index 264cc3ebfc..f5e0868592 100644 --- a/services/game-design-service/build.gradle.kts +++ b/services/game-design-service/build.gradle.kts @@ -14,4 +14,5 @@ firemudJooq { dependencies { compileOnly(libs.spotbugs.annotations) implementation(libs.aws.sdk.s3) + testImplementation(libs.bouncycastle.pkix) } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/ResolvedLaunchDescriptorDto.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/ResolvedLaunchDescriptorDto.java index 251dc5129e..363db4bd74 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/ResolvedLaunchDescriptorDto.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/ResolvedLaunchDescriptorDto.java @@ -1,8 +1,10 @@ package net.firedevops.firemud.gamedesign.dto; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; + public record ResolvedLaunchDescriptorDto( String launchDescriptorId, - String tenantId, + String canonicalTenantId, long gameTemplateId, String controlPlaneRequestId, long versionId, @@ -12,31 +14,5 @@ public record ResolvedLaunchDescriptorDto( long versionStateEpoch, long releaseBundleId, String publishedReleaseBundleRef, - String remapSetId) { - public ResolvedLaunchDescriptorDto( - String launchDescriptorId, - String tenantId, - long gameTemplateId, - String controlPlaneRequestId, - long versionId, - String scriptPatchVersion, - String runtimeFlagsJson, - String generationConfigRevision, - long versionStateEpoch, - long releaseBundleId, - String publishedReleaseBundleRef) { - this( - launchDescriptorId, - tenantId, - gameTemplateId, - controlPlaneRequestId, - versionId, - scriptPatchVersion, - runtimeFlagsJson, - generationConfigRevision, - versionStateEpoch, - releaseBundleId, - publishedReleaseBundleRef, - null); - } -} + String remapSetId, + AuthoredWorldLaunchDescriptorEvidence authoredWorldBinding) {} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/LaunchDescriptor.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/LaunchDescriptor.java index 357d46c8e8..2626699e67 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/LaunchDescriptor.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/LaunchDescriptor.java @@ -5,6 +5,9 @@ @Data public class LaunchDescriptor { + public static final String OUTCOME_SUCCESS = "SUCCESS"; + public static final String OUTCOME_FAILED = "FAILED"; + private Long id; private String launchDescriptorId; private String tenantId; @@ -19,5 +22,18 @@ public class LaunchDescriptor { private Long releaseBundleId; private String publishedReleaseBundleRef; private String remapSetId; + private Integer descriptorSchemaVersion; + private String targetNamespace; + private String canonicalTenantId; + private String worldSlug; + private String authoredWorldSourceOperationId; + private String authoredWorldSourceEvidenceDigest; + private String requestDigest; + private String resultDigest; + private String originalRequestJson; + private String sourceEvidenceJson; + private String outcomeStatus = OUTCOME_SUCCESS; + private String failureCode; + private String failureMessage; private LocalDateTime createdAt = LocalDateTime.now(); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepository.java index 4e18a44aea..c95c0704de 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepository.java @@ -4,6 +4,7 @@ import java.sql.Timestamp; import java.time.LocalDateTime; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.gamedesign.entity.LaunchDescriptor; import org.jooq.DSLContext; import org.jooq.Field; @@ -12,6 +13,7 @@ import org.jooq.impl.DSL; import org.springframework.stereotype.Repository; +/** Owner-local immutable launch descriptor history. */ @Repository @SuppressFBWarnings( value = "EI_EXPOSE_REP2", @@ -43,6 +45,31 @@ public class LaunchDescriptorRepository { DSL.field(DSL.name("published_release_bundle_ref"), String.class); private static final Field REMAP_SET_ID = DSL.field(DSL.name("remap_set_id"), String.class); + private static final Field DESCRIPTOR_SCHEMA_VERSION = + DSL.field(DSL.name("descriptor_schema_version"), Integer.class); + private static final Field TARGET_NAMESPACE = + DSL.field(DSL.name("target_namespace"), String.class); + private static final Field CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field WORLD_SLUG = DSL.field(DSL.name("world_slug"), String.class); + private static final Field SOURCE_OPERATION_ID = + DSL.field(DSL.name("authored_world_source_operation_id"), UUID.class); + private static final Field SOURCE_EVIDENCE_DIGEST = + DSL.field(DSL.name("authored_world_source_evidence_digest"), String.class); + private static final Field REQUEST_DIGEST = + DSL.field(DSL.name("request_digest"), String.class); + private static final Field RESULT_DIGEST = + DSL.field(DSL.name("result_digest"), String.class); + private static final Field ORIGINAL_REQUEST_JSON = + DSL.field(DSL.name("original_request_json"), String.class); + private static final Field SOURCE_EVIDENCE_JSON = + DSL.field(DSL.name("source_evidence_json"), String.class); + private static final Field OUTCOME_STATUS = + DSL.field(DSL.name("outcome_status"), String.class); + private static final Field FAILURE_CODE = + DSL.field(DSL.name("failure_code"), String.class); + private static final Field FAILURE_MESSAGE = + DSL.field(DSL.name("failure_message"), String.class); private static final Field CREATED_AT = DSL.field(DSL.name("created_at"), Timestamp.class); @@ -52,71 +79,98 @@ public LaunchDescriptorRepository(DSLContext dsl) { this.dsl = dsl; } - public Optional findByTenantIdAndGameTemplateIdAndControlPlaneRequestId( - String tenantId, Long gameTemplateId, String controlPlaneRequestId) { + /** Serializes one launch request identity before source, template, or version resolution. */ + public void lockBoundRequest(String targetNamespace, UUID canonicalTenantId, String requestId) { + String lockIdentity = canonicalTenantId + ":" + requestId; + dsl.fetch( + "select pg_advisory_xact_lock(hashtext(?), hashtext(?))", targetNamespace, lockIdentity); + } + + public Optional findBoundByRequest( + String targetNamespace, UUID canonicalTenantId, String controlPlaneRequestId) { return Optional.ofNullable( dsl.selectFrom(TABLE_REF) .where( - TENANT_ID - .eq(tenantId) - .and(GAME_TEMPLATE_ID.eq(gameTemplateId)) + TARGET_NAMESPACE + .eq(targetNamespace) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) .and(CONTROL_PLANE_REQUEST_ID.eq(controlPlaneRequestId))) .limit(1) .fetchOne(this::toEntity)); } + /** Reads the legacy private owner/request tuple only to deny unbound retained history. */ + public Optional findByPrivateRequest( + String tenantId, String controlPlaneRequestId) { + return Optional.ofNullable( + dsl.selectFrom(TABLE_REF) + .where(TENANT_ID.eq(tenantId).and(CONTROL_PLANE_REQUEST_ID.eq(controlPlaneRequestId))) + .limit(1) + .fetchOne(this::toEntity)); + } + public boolean existsByTenantIdAndVersionId(String tenantId, Long versionId) { return dsl.fetchExists(TABLE_REF, TENANT_ID.eq(tenantId).and(VERSION_ID.eq(versionId))); } - public LaunchDescriptor save(LaunchDescriptor descriptor) { + /** Inserts one immutable descriptor; conflicting identities can only return their stored row. */ + public LaunchDescriptor insertImmutable(LaunchDescriptor descriptor) { + if (descriptor.getId() != null || descriptor.getDescriptorSchemaVersion() == null) { + throw new IllegalArgumentException("Only a new bound launch descriptor can be inserted"); + } + if (descriptor.getOutcomeStatus() == null + || !(LaunchDescriptor.OUTCOME_SUCCESS.equals(descriptor.getOutcomeStatus()) + || LaunchDescriptor.OUTCOME_FAILED.equals(descriptor.getOutcomeStatus()))) { + throw new IllegalArgumentException("A known launch descriptor outcome is required"); + } LocalDateTime createdAt = descriptor.getCreatedAt() == null ? LocalDateTime.now() : descriptor.getCreatedAt(); - if (descriptor.getId() == null) { - dsl.insertInto(TABLE_REF) - .set(LAUNCH_DESCRIPTOR_ID, descriptor.getLaunchDescriptorId()) - .set(TENANT_ID, descriptor.getTenantId()) - .set(GAME_TEMPLATE_ID, descriptor.getGameTemplateId()) - .set(CONTROL_PLANE_REQUEST_ID, descriptor.getControlPlaneRequestId()) - .set(REQUEST_HASH, descriptor.getRequestHash()) - .set(VERSION_ID, descriptor.getVersionId()) - .set(SCRIPT_PATCH_VERSION, descriptor.getScriptPatchVersion()) - .set(RUNTIME_FLAGS_JSON, descriptor.getRuntimeFlagsJson()) - .set(GENERATION_CONFIG_REVISION, descriptor.getGenerationConfigRevision()) - .set(VERSION_STATE_EPOCH, descriptor.getVersionStateEpoch()) - .set(RELEASE_BUNDLE_ID, descriptor.getReleaseBundleId()) - .set(PUBLISHED_RELEASE_BUNDLE_REF, descriptor.getPublishedReleaseBundleRef()) - .set(REMAP_SET_ID, descriptor.getRemapSetId()) - .set(CREATED_AT, Timestamp.valueOf(createdAt)) - .execute(); - return findByTenantIdAndGameTemplateIdAndControlPlaneRequestId( - descriptor.getTenantId(), - descriptor.getGameTemplateId(), - descriptor.getControlPlaneRequestId()) - .orElseThrow(); + int inserted = + dsl.insertInto(TABLE_REF) + .set(LAUNCH_DESCRIPTOR_ID, descriptor.getLaunchDescriptorId()) + .set(TENANT_ID, descriptor.getTenantId()) + .set(GAME_TEMPLATE_ID, descriptor.getGameTemplateId()) + .set(CONTROL_PLANE_REQUEST_ID, descriptor.getControlPlaneRequestId()) + .set(REQUEST_HASH, descriptor.getRequestDigest()) + .set(VERSION_ID, descriptor.getVersionId()) + .set(SCRIPT_PATCH_VERSION, descriptor.getScriptPatchVersion()) + .set(RUNTIME_FLAGS_JSON, descriptor.getRuntimeFlagsJson()) + .set(GENERATION_CONFIG_REVISION, descriptor.getGenerationConfigRevision()) + .set(VERSION_STATE_EPOCH, descriptor.getVersionStateEpoch()) + .set(RELEASE_BUNDLE_ID, descriptor.getReleaseBundleId()) + .set(PUBLISHED_RELEASE_BUNDLE_REF, descriptor.getPublishedReleaseBundleRef()) + .set(REMAP_SET_ID, descriptor.getRemapSetId()) + .set(DESCRIPTOR_SCHEMA_VERSION, descriptor.getDescriptorSchemaVersion()) + .set(TARGET_NAMESPACE, descriptor.getTargetNamespace()) + .set(CANONICAL_TENANT_ID, UUID.fromString(descriptor.getCanonicalTenantId())) + .set(WORLD_SLUG, descriptor.getWorldSlug()) + .set( + SOURCE_OPERATION_ID, + UUID.fromString(descriptor.getAuthoredWorldSourceOperationId())) + .set(SOURCE_EVIDENCE_DIGEST, descriptor.getAuthoredWorldSourceEvidenceDigest()) + .set(REQUEST_DIGEST, descriptor.getRequestDigest()) + .set(RESULT_DIGEST, descriptor.getResultDigest()) + .set(ORIGINAL_REQUEST_JSON, descriptor.getOriginalRequestJson()) + .set(SOURCE_EVIDENCE_JSON, descriptor.getSourceEvidenceJson()) + .set(OUTCOME_STATUS, descriptor.getOutcomeStatus()) + .set(FAILURE_CODE, descriptor.getFailureCode()) + .set(FAILURE_MESSAGE, descriptor.getFailureMessage()) + .set(CREATED_AT, Timestamp.valueOf(createdAt)) + .onConflictDoNothing() + .execute(); + Optional stored = + findBoundByRequest( + descriptor.getTargetNamespace(), + UUID.fromString(descriptor.getCanonicalTenantId()), + descriptor.getControlPlaneRequestId()); + if (stored.isEmpty()) { + throw new IllegalStateException( + "Launch descriptor identity conflicts with existing immutable history"); + } + if (inserted == 0 && stored.orElseThrow().getDescriptorSchemaVersion() == null) { + throw new IllegalStateException("An unbound launch descriptor cannot be reused canonically"); } - dsl.update(TABLE_REF) - .set(LAUNCH_DESCRIPTOR_ID, descriptor.getLaunchDescriptorId()) - .set(TENANT_ID, descriptor.getTenantId()) - .set(GAME_TEMPLATE_ID, descriptor.getGameTemplateId()) - .set(CONTROL_PLANE_REQUEST_ID, descriptor.getControlPlaneRequestId()) - .set(REQUEST_HASH, descriptor.getRequestHash()) - .set(VERSION_ID, descriptor.getVersionId()) - .set(SCRIPT_PATCH_VERSION, descriptor.getScriptPatchVersion()) - .set(RUNTIME_FLAGS_JSON, descriptor.getRuntimeFlagsJson()) - .set(GENERATION_CONFIG_REVISION, descriptor.getGenerationConfigRevision()) - .set(VERSION_STATE_EPOCH, descriptor.getVersionStateEpoch()) - .set(RELEASE_BUNDLE_ID, descriptor.getReleaseBundleId()) - .set(PUBLISHED_RELEASE_BUNDLE_REF, descriptor.getPublishedReleaseBundleRef()) - .set(REMAP_SET_ID, descriptor.getRemapSetId()) - .set(CREATED_AT, Timestamp.valueOf(createdAt)) - .where(ID.eq(descriptor.getId())) - .execute(); - return findByTenantIdAndGameTemplateIdAndControlPlaneRequestId( - descriptor.getTenantId(), - descriptor.getGameTemplateId(), - descriptor.getControlPlaneRequestId()) - .orElseThrow(); + return stored.orElseThrow(); } private LaunchDescriptor toEntity(Record record) { @@ -138,6 +192,23 @@ private LaunchDescriptor toEntity(Record record) { descriptor.setReleaseBundleId(record.get(RELEASE_BUNDLE_ID)); descriptor.setPublishedReleaseBundleRef(record.get(PUBLISHED_RELEASE_BUNDLE_REF)); descriptor.setRemapSetId(record.get(REMAP_SET_ID)); + descriptor.setDescriptorSchemaVersion(record.get(DESCRIPTOR_SCHEMA_VERSION)); + descriptor.setTargetNamespace(record.get(TARGET_NAMESPACE)); + UUID canonicalTenantId = record.get(CANONICAL_TENANT_ID); + descriptor.setCanonicalTenantId( + canonicalTenantId == null ? null : canonicalTenantId.toString()); + descriptor.setWorldSlug(record.get(WORLD_SLUG)); + UUID sourceOperationId = record.get(SOURCE_OPERATION_ID); + descriptor.setAuthoredWorldSourceOperationId( + sourceOperationId == null ? null : sourceOperationId.toString()); + descriptor.setAuthoredWorldSourceEvidenceDigest(record.get(SOURCE_EVIDENCE_DIGEST)); + descriptor.setRequestDigest(record.get(REQUEST_DIGEST)); + descriptor.setResultDigest(record.get(RESULT_DIGEST)); + descriptor.setOriginalRequestJson(record.get(ORIGINAL_REQUEST_JSON)); + descriptor.setSourceEvidenceJson(record.get(SOURCE_EVIDENCE_JSON)); + descriptor.setOutcomeStatus(record.get(OUTCOME_STATUS)); + descriptor.setFailureCode(record.get(FAILURE_CODE)); + descriptor.setFailureMessage(record.get(FAILURE_MESSAGE)); Timestamp createdAt = record.get(CREATED_AT); descriptor.setCreatedAt(createdAt == null ? null : createdAt.toLocalDateTime()); return descriptor; diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/LaunchDescriptorService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/LaunchDescriptorService.java index 6403542e21..1ac7a5b74e 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/LaunchDescriptorService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/LaunchDescriptorService.java @@ -1,14 +1,18 @@ package net.firedevops.firemud.gamedesign.service; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; public interface LaunchDescriptorService { ResolvedLaunchDescriptorDto resolveLaunchDescriptor( - String tenantId, - long gameTemplateId, + AuthoredWorldLaunchDescriptorEvidence.Request request); + + ResolvedLaunchDescriptorDto getLaunchDescriptor( + UUID readRequestId, + UUID canonicalTenantId, + String worldSlug, String controlPlaneRequestId, - String requestedScriptPatchVersion, - Long sourceVersionId, - Long targetVersionId, - String requestedRuntimeFlagsJson); + String expectedRequestDigest, + String expectedResultDigest); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/FrozenLaunchDescriptorDenialException.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/FrozenLaunchDescriptorDenialException.java new file mode 100644 index 0000000000..5bc425144a --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/FrozenLaunchDescriptorDenialException.java @@ -0,0 +1,23 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +/** A deterministic launch business denial whose exact request outcome is stored by the owner. */ +final class FrozenLaunchDescriptorDenialException extends IllegalArgumentException { + private final String failureCode; + + static FrozenLaunchDescriptorDenialException create(String failureCode, String detail) { + return new FrozenLaunchDescriptorDenialException(failureCode, failureCode + ": " + detail); + } + + private FrozenLaunchDescriptorDenialException(String failureCode, String message) { + super(message); + this.failureCode = failureCode; + } + + static FrozenLaunchDescriptorDenialException fromStored(String failureCode, String message) { + return new FrozenLaunchDescriptorDenialException(failureCode, message); + } + + String failureCode() { + return failureCode; + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java index 8a4faf2be8..de39648b6b 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java @@ -8,8 +8,11 @@ import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.List; +import java.util.UUID; import lombok.RequiredArgsConstructor; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; import net.firedevops.firemud.common.grpc.GrpcAppErrors; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.AdminAuthorizationException; import net.firedevops.firemud.common.security.AdminRoleGuard; import net.firedevops.firemud.common.security.SessionContext; @@ -53,6 +56,8 @@ import net.firedevops.firemud.gamedesign.v1.GameDesignServiceGrpc; import net.firedevops.firemud.gamedesign.v1.GetDesignControlPlaneDigestRequest; import net.firedevops.firemud.gamedesign.v1.GetDesignControlPlaneDigestResponse; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorResponse; import net.firedevops.firemud.gamedesign.v1.GetPublishedPluginVersionRequest; import net.firedevops.firemud.gamedesign.v1.GetPublishedPluginVersionResponse; import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleRequest; @@ -116,6 +121,7 @@ import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; import org.springframework.grpc.server.service.GrpcService; @GrpcService @@ -132,6 +138,9 @@ public class GameDesignGrpcService extends GameDesignServiceGrpc.GameDesignServi private final GameAuthoredHelpTopicService gameAuthoredHelpTopicService; private final TemporalVersionPublishWorkflowMetadataResolver publishWorkflowMetadataResolver; + @Value("${firemud.grpc.workload-namespace:}") + private String workloadNamespace; + @SuppressFBWarnings( value = "EI_EXPOSE_REP2", justification = "MeterRegistry is injected and not exposed") @@ -841,36 +850,38 @@ public void resolveLaunchDescriptor( StreamObserver responseObserver) { ResolveLaunchDescriptorResponse.Builder builder = ResolveLaunchDescriptorResponse.newBuilder(); try { - requireLaunchAttestationReadAccess(); - var descriptor = - launchDescriptorService.resolveLaunchDescriptor( - request.getTenantId(), - request.getGameTemplateId(), + requireLaunchDescriptorResolveAccess(); + UUID canonicalTenantId = parseCanonicalNonNilUuid(request.getCanonicalTenantId()); + UUID sourceOperationId = + parseCanonicalNonNilUuid(request.getAuthoredWorldSourceOperationId()); + if (canonicalTenantId == null + || sourceOperationId == null + || !request.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Closed canonical authored-world request is required"); + } + AuthoredWorldLaunchDescriptorEvidence.Request bindingRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + workloadNamespace, request.getControlPlaneRequestId(), + canonicalTenantId, + request.getWorldSlug(), + sourceOperationId, + request.getExpectedAuthoredWorldSourceEvidenceDigest(), + request.getGameTemplateId(), + request.hasRequestedScriptPatchVersion(), request.hasRequestedScriptPatchVersion() ? request.getRequestedScriptPatchVersion() : null, + request.hasSourceVersionId(), request.hasSourceVersionId() ? request.getSourceVersionId() : null, + request.hasTargetVersionId(), request.hasTargetVersionId() ? request.getTargetVersionId() : null, + request.hasRequestedRuntimeFlagsJson(), request.hasRequestedRuntimeFlagsJson() ? request.getRequestedRuntimeFlagsJson() : null); - builder.setLaunchDescriptor( - net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.newBuilder() - .setLaunchDescriptorId(descriptor.launchDescriptorId()) - .setTenantId(descriptor.tenantId()) - .setGameTemplateId(descriptor.gameTemplateId()) - .setControlPlaneRequestId(descriptor.controlPlaneRequestId()) - .setVersionId(descriptor.versionId()) - .setScriptPatchVersion( - descriptor.scriptPatchVersion() == null ? "" : descriptor.scriptPatchVersion()) - .setRuntimeFlagsJson(descriptor.runtimeFlagsJson()) - .setGenerationConfigRevision(descriptor.generationConfigRevision()) - .setVersionStateEpoch(descriptor.versionStateEpoch()) - .setReleaseBundleId(descriptor.releaseBundleId()) - .setPublishedReleaseBundleRef(descriptor.publishedReleaseBundleRef()) - .setRemapSetId(descriptor.remapSetId() == null ? "" : descriptor.remapSetId()) - .build()); + var descriptor = launchDescriptorService.resolveLaunchDescriptor(bindingRequest); + builder.setLaunchDescriptor(toProtoLaunchDescriptor(descriptor)); } catch (AdminAuthorizationException ex) { builder.setError( GrpcAppErrors.error( @@ -879,7 +890,7 @@ public void resolveLaunchDescriptor( "ResolveLaunchDescriptor", "PERMISSION_DENIED", ex.getMessage())); - } catch (IllegalStateException ex) { + } catch (IllegalArgumentException ex) { builder.setError( GrpcAppErrors.error( meterRegistry, @@ -887,13 +898,13 @@ public void resolveLaunchDescriptor( "ResolveLaunchDescriptor", launchDescriptorErrorCode(ex.getMessage(), true), ex.getMessage())); - } catch (IllegalArgumentException ex) { + } catch (IllegalStateException ex) { builder.setError( GrpcAppErrors.error( meterRegistry, logger, "ResolveLaunchDescriptor", - launchDescriptorErrorCode(ex.getMessage(), false), + launchDescriptorErrorCode(ex.getMessage(), true), ex.getMessage())); } catch (Exception ex) { builder.setError( @@ -903,6 +914,51 @@ public void resolveLaunchDescriptor( responseObserver.onCompleted(); } + @Override + @Timed(value = "gamedesignGrpc.getLaunchDescriptor") + public void getLaunchDescriptor( + GetLaunchDescriptorRequest request, + StreamObserver responseObserver) { + GetLaunchDescriptorResponse.Builder builder = GetLaunchDescriptorResponse.newBuilder(); + try { + requireLaunchDescriptorReadAccess(); + UUID readRequestId = parseCanonicalNonNilUuid(request.getRequestId()); + UUID canonicalTenantId = parseCanonicalNonNilUuid(request.getCanonicalTenantId()); + if (readRequestId == null + || canonicalTenantId == null + || !request.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Canonical exact launch descriptor read is required"); + } + var descriptor = + launchDescriptorService.getLaunchDescriptor( + readRequestId, + canonicalTenantId, + request.getWorldSlug(), + request.getControlPlaneRequestId(), + request.getExpectedRequestDigest(), + request.getExpectedResultDigest()); + builder + .setRequestId(readRequestId.toString()) + .setLaunchDescriptor(toProtoLaunchDescriptor(descriptor)); + } catch (AdminAuthorizationException ex) { + builder.setError( + GrpcAppErrors.error( + meterRegistry, logger, "GetLaunchDescriptor", "PERMISSION_DENIED", ex.getMessage())); + } catch (IllegalArgumentException ex) { + builder.setError( + GrpcAppErrors.error( + meterRegistry, + logger, + "GetLaunchDescriptor", + launchDescriptorErrorCode(ex.getMessage(), true), + ex.getMessage())); + } catch (Exception ex) { + builder.setError(GrpcAppErrors.internal(meterRegistry, logger, "GetLaunchDescriptor", ex)); + } + responseObserver.onNext(builder.build()); + responseObserver.onCompleted(); + } + @Override @Timed(value = "gamedesignGrpc.createTemplateRemapSet") public void createTemplateRemapSet( @@ -1930,6 +1986,80 @@ private WorldDesignMutationResult toProtoWorldDesignMutationResult(String result return WorldDesignMutationResult.valueOf(result); } + private net.firedevops.firemud.gamedesign.v1.LaunchDescriptor toProtoLaunchDescriptor( + net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto descriptor) { + AuthoredWorldLaunchDescriptorEvidence evidence = descriptor.authoredWorldBinding(); + if (evidence == null) { + throw new IllegalStateException("Bound authored-world launch evidence is required"); + } + evidence.requireValid(); + var binding = + net.firedevops.firemud.gamedesign.v1.AuthoredWorldLaunchDescriptorEvidence.newBuilder() + .setSchemaVersion(evidence.schemaVersion()) + .setTargetNamespace(evidence.targetNamespace()) + .setControlPlaneRequestId(evidence.controlPlaneRequestId()) + .setCanonicalTenantId(evidence.canonicalTenantId().toString()) + .setWorldSlug(evidence.worldSlug()) + .setAuthoredWorldSourceOperationId(evidence.authoredWorldSourceOperationId().toString()) + .setAuthoredWorldSourceEvidenceDigest(evidence.authoredWorldSourceEvidenceDigest()) + .setGameTemplateId(evidence.gameTemplateId()) + .setRequestDigest(evidence.requestDigest()) + .setLaunchDescriptorId(evidence.launchDescriptorId()) + .setVersionId(evidence.versionId()) + .setRuntimeFlagsJson(evidence.runtimeFlagsJson()) + .setGenerationConfigRevision(evidence.generationConfigRevision()) + .setVersionStateEpoch(evidence.versionStateEpoch()) + .setReleaseBundleId(evidence.releaseBundleId()) + .setPublishedReleaseBundleRef(evidence.publishedReleaseBundleRef()) + .setResultDigest(evidence.resultDigest()); + if (evidence.requestedScriptPatchVersionPresent()) { + binding.setRequestedScriptPatchVersion(evidence.requestedScriptPatchVersion()); + } + if (evidence.sourceVersionIdPresent()) { + binding.setSourceVersionId(evidence.sourceVersionId()); + } + if (evidence.targetVersionIdPresent()) { + binding.setTargetVersionId(evidence.targetVersionId()); + } + if (evidence.requestedRuntimeFlagsJsonPresent()) { + binding.setRequestedRuntimeFlagsJson(evidence.requestedRuntimeFlagsJson()); + } + if (evidence.scriptPatchVersionPresent()) { + binding.setScriptPatchVersion(evidence.scriptPatchVersion()); + } + if (evidence.remapSetIdPresent()) { + binding.setRemapSetId(evidence.remapSetId()); + } + return net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.newBuilder() + .setLaunchDescriptorId(descriptor.launchDescriptorId()) + .setCanonicalTenantId(descriptor.canonicalTenantId()) + .setGameTemplateId(descriptor.gameTemplateId()) + .setControlPlaneRequestId(descriptor.controlPlaneRequestId()) + .setVersionId(descriptor.versionId()) + .setScriptPatchVersion( + descriptor.scriptPatchVersion() == null ? "" : descriptor.scriptPatchVersion()) + .setRuntimeFlagsJson(descriptor.runtimeFlagsJson()) + .setGenerationConfigRevision(descriptor.generationConfigRevision()) + .setVersionStateEpoch(descriptor.versionStateEpoch()) + .setReleaseBundleId(descriptor.releaseBundleId()) + .setPublishedReleaseBundleRef(descriptor.publishedReleaseBundleRef()) + .setRemapSetId(descriptor.remapSetId() == null ? "" : descriptor.remapSetId()) + .setAuthoredWorldBinding(binding.build()) + .build(); + } + + private UUID parseCanonicalNonNilUuid(String value) { + if (value == null) { + return null; + } + try { + UUID parsed = UUID.fromString(value); + return parsed.toString().equals(value) && !parsed.equals(new UUID(0L, 0L)) ? parsed : null; + } catch (IllegalArgumentException exception) { + return null; + } + } + private String launchDescriptorErrorCode(String message, boolean allowSchemaUnsupported) { if (message == null || message.isBlank()) { return "INVALID_ARGUMENT"; @@ -1952,6 +2082,15 @@ private String launchDescriptorErrorCode(String message, boolean allowSchemaUnsu return prefix; } } + if (message.startsWith("AUTHORED_WORLD_SOURCE_NOT_FOUND")) { + return "NOT_FOUND"; + } + if (message.startsWith("LAUNCH_DESCRIPTOR_NOT_FOUND")) { + return "NOT_FOUND"; + } + if (message.startsWith("AUTHORED_WORLD_SOURCE_") || message.startsWith("LAUNCH_DESCRIPTOR_")) { + return "FAILED_PRECONDITION"; + } return "INVALID_ARGUMENT"; } @@ -2039,6 +2178,33 @@ private void requireLaunchAttestationReadAccess() { AdminRoleGuard.requireAdminRole(); } + private void requireLaunchDescriptorResolveAccess() { + requireExactWorkloadPeer("game-session-service"); + } + + private void requireLaunchDescriptorReadAccess() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace) + || peer == null + || !workloadNamespace.equals(peer.namespace()) + || !(peer.isService("game-session-service") + || peer.isService("world-management-service"))) { + throw new AdminAuthorizationException( + "Exact same-namespace Game Session or World Management workload identity is required"); + } + } + + private void requireExactWorkloadPeer(String service) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace) + || peer == null + || !workloadNamespace.equals(peer.namespace()) + || !peer.isService(service)) { + throw new AdminAuthorizationException( + "Exact same-namespace workload identity is required for launch descriptor resolution"); + } + } + private void requireSettingsAuthorityReadAccess() { if (SessionContext.isInternalService()) { return; diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java index 7133e95364..4e69876f13 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java @@ -1,20 +1,23 @@ package net.firedevops.firemud.gamedesign.service.impl; import io.micrometer.core.annotation.Timed; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.LinkedHashMap; -import java.util.Map; +import java.util.Objects; +import java.util.Optional; import java.util.UUID; import lombok.RequiredArgsConstructor; -import net.firedevops.firemud.common.LoggingUtil; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; import net.firedevops.firemud.gamedesign.dto.TemplateRemapSetDto; import net.firedevops.firemud.gamedesign.dto.VersionDto; import net.firedevops.firemud.gamedesign.entity.LaunchDescriptor; import net.firedevops.firemud.gamedesign.model.TemplateReferencePhase; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; import net.firedevops.firemud.gamedesign.repository.GameTemplateLaunchConfigView; import net.firedevops.firemud.gamedesign.repository.GameTemplateRepository; import net.firedevops.firemud.gamedesign.repository.LaunchDescriptorRepository; @@ -22,261 +25,567 @@ import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; import net.firedevops.firemud.gamedesign.service.TemplateRemapSetService; -import org.slf4j.Logger; +import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import tools.jackson.core.exc.StreamReadException; import tools.jackson.databind.ObjectMapper; @Service @RequiredArgsConstructor public class LaunchDescriptorServiceImpl implements LaunchDescriptorService { - private static final Logger logger = LoggingUtil.getLogger(LaunchDescriptorServiceImpl.class); - + private static final UUID NIL_UUID = new UUID(0L, 0L); private final GameTemplateRepository gameTemplateRepository; private final LaunchDescriptorRepository launchDescriptorRepository; private final VersionRepository versionRepository; private final PublishedReleaseBundleService publishedReleaseBundleService; private final TemplateRemapSetService templateRemapSetService; + private final GameAuthoredWorldSourceRepository authoredWorldSourceRepository; private final ObjectMapper objectMapper; + @Value("${firemud.grpc.workload-namespace:}") + private String workloadNamespace; + @Override - @Transactional + @Transactional(noRollbackFor = FrozenLaunchDescriptorDenialException.class) @Timed(value = "gamedesign.launchDescriptor.resolve") public ResolvedLaunchDescriptorDto resolveLaunchDescriptor( - String tenantId, - long gameTemplateId, - String controlPlaneRequestId, - String requestedScriptPatchVersion, - Long sourceVersionId, - Long targetVersionId, - String requestedRuntimeFlagsJson) { - if (controlPlaneRequestId == null || controlPlaneRequestId.isBlank()) { + AuthoredWorldLaunchDescriptorEvidence.Request request) { + requireConfiguredNamespace(request.targetNamespace()); + launchDescriptorRepository.lockBoundRequest( + workloadNamespace, request.canonicalTenantId(), request.controlPlaneRequestId()); + String requestJson = writeJson(request); + + Optional stored = + launchDescriptorRepository.findBoundByRequest( + workloadNamespace, request.canonicalTenantId(), request.controlPlaneRequestId()); + if (stored.isPresent()) { + LaunchDescriptor descriptor = stored.orElseThrow(); + requireStoredRequestMatches(descriptor, request, requestJson); + AuthoredWorldSourceEvidence source = readExactSource(request); + String sourceJson = writeJson(source); + if (LaunchDescriptor.OUTCOME_FAILED.equals(descriptor.getOutcomeStatus())) { + throwStoredFailure( + descriptor, request, requestJson, sourceJson, source.sourceGameTenantKey()); + } + if (!LaunchDescriptor.OUTCOME_SUCCESS.equals(descriptor.getOutcomeStatus())) { + throw new IllegalArgumentException("LAUNCH_DESCRIPTOR_CONFLICT: stored outcome is unknown"); + } + return readStored(descriptor, request, requestJson, sourceJson); + } + AuthoredWorldSourceEvidence source = readExactSource(request); + String sourceJson = writeJson(source); + if (launchDescriptorRepository + .findByPrivateRequest(source.sourceGameTenantKey(), request.controlPlaneRequestId()) + .isPresent()) { throw new IllegalArgumentException( - "INVALID_TEMPLATE_CONFIGURATION: controlPlaneRequestId is required"); + "LAUNCH_DESCRIPTOR_CONFLICT: retained private-owner request history is unbound or bound to another canonical identity"); } + + try { + return resolveNewLaunchDescriptor(request, source, requestJson, sourceJson); + } catch (FrozenLaunchDescriptorDenialException denial) { + LaunchDescriptor failure = frozenFailure(request, source, requestJson, sourceJson, denial); + LaunchDescriptor persisted = launchDescriptorRepository.insertImmutable(failure); + throwStoredFailure(persisted, request, requestJson, sourceJson, source.sourceGameTenantKey()); + throw new IllegalStateException("Persisted deterministic launch denial was not returned"); + } + } + + private ResolvedLaunchDescriptorDto resolveNewLaunchDescriptor( + AuthoredWorldLaunchDescriptorEvidence.Request request, + AuthoredWorldSourceEvidence source, + String requestJson, + String sourceJson) { GameTemplateLaunchConfigView template = gameTemplateRepository - .findLaunchConfigByTenantIdAndId(tenantId, gameTemplateId) + .findLaunchConfigByTenantIdAndId(source.sourceGameTenantKey(), request.gameTemplateId()) + .filter(row -> row.getId() == request.gameTemplateId()) + .filter(row -> source.sourceGameTenantKey().equals(row.getTenantId())) .orElseThrow( () -> - new IllegalArgumentException( - "INVALID_TEMPLATE_CONFIGURATION: game template not found")); - String requestHash = - hashRequest( - tenantId, - gameTemplateId, - controlPlaneRequestId, - requestedScriptPatchVersion, - sourceVersionId, - targetVersionId, - requestedRuntimeFlagsJson); - var existing = - launchDescriptorRepository.findByTenantIdAndGameTemplateIdAndControlPlaneRequestId( - tenantId, gameTemplateId, controlPlaneRequestId); - if (existing.isPresent()) { - if (!existing.get().getRequestHash().equals(requestHash)) { - throw new IllegalArgumentException( - "INVALID_TEMPLATE_CONFIGURATION: controlPlaneRequestId already resolved with different inputs"); - } - requireReadyScriptPatch(requestedScriptPatchVersion); - requireReadyScriptPatch(template.getDefaultScriptPatchVersion()); - requireReadyScriptPatch(existing.get().getScriptPatchVersion()); - return toDto(existing.get()); - } + denial( + "INVALID_TEMPLATE_CONFIGURATION", + "template is not owned by the source game")); if (template.getTemplateReferencePhase() != TemplateReferencePhase.ENFORCED) { - throw new IllegalArgumentException( - "TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED: template reference phase is not enforced"); + throw denial( + "TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED", "template reference phase is not enforced"); } - Long resolvedVersionId = - targetVersionId != null ? targetVersionId : template.getDefaultVersionId(); - if (resolvedVersionId == null || resolvedVersionId <= 0L) { - throw new IllegalArgumentException( - "INVALID_TEMPLATE_CONFIGURATION: template defaultVersionId is required"); + Long versionId = + request.targetVersionIdPresent() + ? request.targetVersionId() + : template.getDefaultVersionId(); + if (versionId == null || versionId <= 0) { + throw denial("INVALID_TEMPLATE_CONFIGURATION", "template defaultVersionId is required"); } VersionDto version = versionRepository - .findById(resolvedVersionId) - .filter(found -> found.getTenantId().equals(tenantId)) + .findById(versionId) + .filter(row -> row.getId().equals(versionId)) + .filter(row -> source.sourceGameTenantKey().equals(row.getTenantId())) .map( - found -> + row -> new VersionDto( - found.getId(), - found.getTenantId(), - found.getVersionNumber(), - found.getVersionState(), - found.getVersionStateEpoch(), - found.getScriptPatchVersion(), - found.getBaseVersionId(), - found.isScriptOnly(), - found.getNotes(), - found.getCreatedAt(), - found.getUpdatedAt())) + row.getId(), + row.getTenantId(), + row.getVersionNumber(), + row.getVersionState(), + row.getVersionStateEpoch(), + row.getScriptPatchVersion(), + row.getBaseVersionId(), + row.isScriptOnly(), + row.getNotes(), + row.getCreatedAt(), + row.getUpdatedAt())) .orElseThrow( () -> - new IllegalArgumentException( - "INVALID_TEMPLATE_CONFIGURATION: target version not found")); + denial( + "INVALID_TEMPLATE_CONFIGURATION", + "target version is not owned by the source game")); if (version.versionState() != VersionLifecycleState.PUBLISHED && version.versionState() != VersionLifecycleState.ACTIVE) { - throw new IllegalArgumentException( - "VERSION_STATE_EPOCH_STALE: resolved version is not activation-eligible"); + throw denial("VERSION_STATE_EPOCH_STALE", "resolved version is not activation-eligible"); } + requireReadyScriptPatch( + request.requestedScriptPatchVersionPresent() + ? request.requestedScriptPatchVersion() + : null); + requireReadyScriptPatch(template.getDefaultScriptPatchVersion()); requireReadyScriptPatch(version.scriptPatchVersion()); - String resolvedScriptPatchVersion = - resolveScriptPatchVersion(template, requestedScriptPatchVersion, version); - requireReadyScriptPatch(resolvedScriptPatchVersion); - String resolvedRuntimeFlagsJson = resolveRuntimeFlagsJson(template, requestedRuntimeFlagsJson); + String scriptPatch = resolveScriptPatchVersion(template, request, version); + String runtimeFlags = resolveRuntimeFlagsJson(template, request); + String remapSetId = null; - if (sourceVersionId != null && !sourceVersionId.equals(resolvedVersionId)) { - TemplateRemapSetDto remapSet = + if (request.sourceVersionIdPresent() && !request.sourceVersionId().equals(versionId)) { + TemplateRemapSetDto remap = templateRemapSetService - .findApprovedTemplateRemapSet(tenantId, sourceVersionId, resolvedVersionId) + .findApprovedTemplateRemapSet( + source.sourceGameTenantKey(), request.sourceVersionId(), versionId) .orElseThrow( () -> - new IllegalArgumentException( - "LAUNCH_REMAP_REQUIRED: replacement-instance launch requires an approved remapSetId")); - remapSetId = remapSet.remapSetId(); + denial( + "LAUNCH_REMAP_REQUIRED", + "replacement-instance launch requires an approved remapSetId")); + remapSetId = remap.remapSetId(); } - var bundle = requirePublishedReleaseBundle(tenantId, resolvedVersionId); - PublishedReleaseBundleContract.requireSupportedSchemaForLaunch(bundle); + PublishedReleaseBundleDto bundle = + requirePublishedReleaseBundle(source.sourceGameTenantKey(), versionId); + if (!source.sourceGameTenantKey().equals(bundle.tenantId()) + || !Objects.equals(bundle.versionId(), versionId)) { + throw denial( + "RELEASE_BUNDLE_NOT_FOUND", "release bundle is not owned by the resolved source version"); + } + if (!PublishedReleaseBundleContract.SUPPORTED_ATTESTATION_SCHEMA_VERSION.equals( + bundle.attestationSchemaVersion())) { + throw denial( + PublishedReleaseBundleContract.SCHEMA_VERSION_UNSUPPORTED, + "unsupported published release bundle attestation schema " + + bundle.attestationSchemaVersion()); + } + + String descriptorId = "ld-" + UUID.randomUUID(); + AuthoredWorldLaunchDescriptorEvidence evidence = + AuthoredWorldLaunchDescriptorEvidence.create( + request, + descriptorId, + versionId, + scriptPatch != null, + scriptPatch, + runtimeFlags, + bundle.generationConfigRevision(), + version.versionStateEpoch(), + bundle.id(), + releaseBundleRef(request.canonicalTenantId().toString(), bundle.id(), versionId), + remapSetId != null, + remapSetId); LaunchDescriptor descriptor = new LaunchDescriptor(); - descriptor.setLaunchDescriptorId("ld-" + UUID.randomUUID()); - descriptor.setTenantId(tenantId); - descriptor.setGameTemplateId(gameTemplateId); - descriptor.setControlPlaneRequestId(controlPlaneRequestId); - descriptor.setRequestHash(requestHash); - descriptor.setVersionId(resolvedVersionId); - descriptor.setScriptPatchVersion(resolvedScriptPatchVersion); - descriptor.setRuntimeFlagsJson(resolvedRuntimeFlagsJson); + descriptor.setLaunchDescriptorId(descriptorId); + descriptor.setTenantId(source.sourceGameTenantKey()); + descriptor.setGameTemplateId(request.gameTemplateId()); + descriptor.setControlPlaneRequestId(request.controlPlaneRequestId()); + descriptor.setRequestHash(evidence.requestDigest()); + descriptor.setVersionId(versionId); + descriptor.setScriptPatchVersion(scriptPatch); + descriptor.setRuntimeFlagsJson(runtimeFlags); descriptor.setGenerationConfigRevision(bundle.generationConfigRevision()); descriptor.setVersionStateEpoch(version.versionStateEpoch()); descriptor.setReleaseBundleId(bundle.id()); - descriptor.setPublishedReleaseBundleRef( - releaseBundleRef(tenantId, bundle.id(), resolvedVersionId)); + descriptor.setPublishedReleaseBundleRef(evidence.publishedReleaseBundleRef()); descriptor.setRemapSetId(remapSetId); - logger.info( - "Resolved launch descriptor tenant={} template={} controlPlaneRequestId={} version={} remapSetId={}", - tenantId, - gameTemplateId, - controlPlaneRequestId, - resolvedVersionId, - remapSetId); - return toDto(launchDescriptorRepository.save(descriptor)); + descriptor.setDescriptorSchemaVersion(evidence.schemaVersion()); + descriptor.setTargetNamespace(workloadNamespace); + descriptor.setCanonicalTenantId(request.canonicalTenantId().toString()); + descriptor.setWorldSlug(request.worldSlug()); + descriptor.setAuthoredWorldSourceOperationId( + request.authoredWorldSourceOperationId().toString()); + descriptor.setAuthoredWorldSourceEvidenceDigest(request.authoredWorldSourceEvidenceDigest()); + descriptor.setRequestDigest(evidence.requestDigest()); + descriptor.setResultDigest(evidence.resultDigest()); + descriptor.setOriginalRequestJson(requestJson); + descriptor.setSourceEvidenceJson(sourceJson); + return readStored( + launchDescriptorRepository.insertImmutable(descriptor), request, requestJson, sourceJson); + } + + @Override + @Transactional(readOnly = true) + @Timed(value = "gamedesign.launchDescriptor.read") + public ResolvedLaunchDescriptorDto getLaunchDescriptor( + UUID readRequestId, + UUID canonicalTenantId, + String worldSlug, + String controlPlaneRequestId, + String expectedRequestDigest, + String expectedResultDigest) { + if (readRequestId == null || NIL_UUID.equals(readRequestId)) { + throw new IllegalArgumentException("Canonical nonnil read request ID is required"); + } + requireConfiguredNamespace(workloadNamespace); + AuthoredWorldSourceDigest.validateReadSelector(workloadNamespace, canonicalTenantId, worldSlug); + if (controlPlaneRequestId == null + || controlPlaneRequestId.isBlank() + || !GameTenantCreationDigest.isDigest(expectedRequestDigest) + || !GameTenantCreationDigest.isDigest(expectedResultDigest)) { + throw new IllegalArgumentException("Exact descriptor read selector and digests are required"); + } + LaunchDescriptor descriptor = + launchDescriptorRepository + .findBoundByRequest(workloadNamespace, canonicalTenantId, controlPlaneRequestId) + .orElseThrow( + () -> + new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_NOT_FOUND: no descriptor exists for the exact request")); + if (!LaunchDescriptor.OUTCOME_SUCCESS.equals(descriptor.getOutcomeStatus())) { + throw new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_CONFLICT: request outcome is not a successful descriptor"); + } + if (descriptor.getDescriptorSchemaVersion() == null) { + throw new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_UNBOUND: retained descriptor history has no authored-world binding"); + } + if (!worldSlug.equals(descriptor.getWorldSlug()) + || !canonicalTenantId.toString().equals(descriptor.getCanonicalTenantId()) + || !expectedRequestDigest.equals(descriptor.getRequestDigest()) + || !expectedResultDigest.equals(descriptor.getResultDigest())) { + throw new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_CONFLICT: exact readback selector or digest does not match"); + } + AuthoredWorldLaunchDescriptorEvidence.Request storedRequest = + readRequest(descriptor.getOriginalRequestJson()); + AuthoredWorldSourceEvidence source = readExactSource(storedRequest); + String sourceJson = writeJson(source); + if (!sourceJson.equals(descriptor.getSourceEvidenceJson())) { + throw new IllegalArgumentException( + "AUTHORED_WORLD_SOURCE_CHANGED: committed source differs from descriptor history"); + } + return readStored( + descriptor, + storedRequest, + descriptor.getOriginalRequestJson(), + descriptor.getSourceEvidenceJson()); + } + + private AuthoredWorldSourceEvidence readExactSource( + AuthoredWorldLaunchDescriptorEvidence.Request request) { + AuthoredWorldSourceEvidence source = + authoredWorldSourceRepository + .read( + request.authoredWorldSourceOperationId(), + request.canonicalTenantId(), + request.worldSlug(), + workloadNamespace) + .orElseThrow( + () -> + new IllegalArgumentException( + "AUTHORED_WORLD_SOURCE_NOT_FOUND: exact committed source evidence is missing")); + if (!workloadNamespace.equals(source.targetNamespace()) + || !request.canonicalTenantId().equals(source.canonicalTenantId()) + || !request.worldSlug().equals(source.worldSlug()) + || !request.authoredWorldSourceOperationId().equals(source.operationId()) + || !request.authoredWorldSourceEvidenceDigest().equals(source.evidenceDigest())) { + throw new IllegalArgumentException( + "AUTHORED_WORLD_SOURCE_CHANGED: source evidence does not match the exact request"); + } + return source; + } + + private ResolvedLaunchDescriptorDto readStored( + LaunchDescriptor descriptor, + AuthoredWorldLaunchDescriptorEvidence.Request request, + String requestJson, + String sourceJson) { + if (!LaunchDescriptor.OUTCOME_SUCCESS.equals(descriptor.getOutcomeStatus()) + || descriptor.getFailureCode() != null + || descriptor.getFailureMessage() != null + || descriptor.getDescriptorSchemaVersion() == null + || !Objects.equals( + descriptor.getDescriptorSchemaVersion(), + AuthoredWorldLaunchDescriptorEvidence.SCHEMA_VERSION) + || !workloadNamespace.equals(descriptor.getTargetNamespace()) + || !request.canonicalTenantId().toString().equals(descriptor.getCanonicalTenantId()) + || !request.worldSlug().equals(descriptor.getWorldSlug()) + || !request + .authoredWorldSourceOperationId() + .toString() + .equals(descriptor.getAuthoredWorldSourceOperationId()) + || !request + .authoredWorldSourceEvidenceDigest() + .equals(descriptor.getAuthoredWorldSourceEvidenceDigest()) + || !request.controlPlaneRequestId().equals(descriptor.getControlPlaneRequestId()) + || request.gameTemplateId() != descriptor.getGameTemplateId() + || !requestJson.equals(descriptor.getOriginalRequestJson()) + || !sourceJson.equals(descriptor.getSourceEvidenceJson()) + || !request.requestDigest().equals(descriptor.getRequestHash()) + || !request.requestDigest().equals(descriptor.getRequestDigest())) { + throw new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_CONFLICT: stored descriptor is not the exact immutable request"); + } + AuthoredWorldLaunchDescriptorEvidence evidence = + AuthoredWorldLaunchDescriptorEvidence.create( + request, + descriptor.getLaunchDescriptorId(), + descriptor.getVersionId(), + descriptor.getScriptPatchVersion() != null, + descriptor.getScriptPatchVersion(), + descriptor.getRuntimeFlagsJson(), + descriptor.getGenerationConfigRevision(), + descriptor.getVersionStateEpoch(), + descriptor.getReleaseBundleId(), + descriptor.getPublishedReleaseBundleRef(), + descriptor.getRemapSetId() != null, + descriptor.getRemapSetId()); + evidence.requireValid(); + if (!evidence.resultDigest().equals(descriptor.getResultDigest())) { + throw new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_CONFLICT: stored resolved result digest is inconsistent"); + } + return new ResolvedLaunchDescriptorDto( + evidence.launchDescriptorId(), + evidence.canonicalTenantId().toString(), + evidence.gameTemplateId(), + evidence.controlPlaneRequestId(), + evidence.versionId(), + evidence.scriptPatchVersion(), + evidence.runtimeFlagsJson(), + evidence.generationConfigRevision(), + evidence.versionStateEpoch(), + evidence.releaseBundleId(), + evidence.publishedReleaseBundleRef(), + evidence.remapSetId(), + evidence); + } + + private LaunchDescriptor frozenFailure( + AuthoredWorldLaunchDescriptorEvidence.Request request, + AuthoredWorldSourceEvidence source, + String requestJson, + String sourceJson, + FrozenLaunchDescriptorDenialException denial) { + LaunchDescriptor descriptor = new LaunchDescriptor(); + descriptor.setTenantId(source.sourceGameTenantKey()); + descriptor.setControlPlaneRequestId(request.controlPlaneRequestId()); + descriptor.setRequestHash(request.requestDigest()); + descriptor.setDescriptorSchemaVersion(AuthoredWorldLaunchDescriptorEvidence.SCHEMA_VERSION); + descriptor.setTargetNamespace(workloadNamespace); + descriptor.setCanonicalTenantId(request.canonicalTenantId().toString()); + descriptor.setWorldSlug(request.worldSlug()); + descriptor.setAuthoredWorldSourceOperationId( + request.authoredWorldSourceOperationId().toString()); + descriptor.setAuthoredWorldSourceEvidenceDigest(request.authoredWorldSourceEvidenceDigest()); + descriptor.setRequestDigest(request.requestDigest()); + descriptor.setOriginalRequestJson(requestJson); + descriptor.setSourceEvidenceJson(sourceJson); + descriptor.setOutcomeStatus(LaunchDescriptor.OUTCOME_FAILED); + descriptor.setFailureCode(denial.failureCode()); + descriptor.setFailureMessage(denial.getMessage()); + return descriptor; + } + + private void requireStoredRequestMatches( + LaunchDescriptor descriptor, + AuthoredWorldLaunchDescriptorEvidence.Request request, + String requestJson) { + if (!workloadNamespace.equals(descriptor.getTargetNamespace()) + || !request.canonicalTenantId().toString().equals(descriptor.getCanonicalTenantId()) + || !request.controlPlaneRequestId().equals(descriptor.getControlPlaneRequestId()) + || !request.requestDigest().equals(descriptor.getRequestDigest()) + || !request.requestDigest().equals(descriptor.getRequestHash()) + || !requestJson.equals(descriptor.getOriginalRequestJson())) { + throw new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_CONFLICT: control-plane request identity was reused with changed input"); + } + } + + private void throwStoredFailure( + LaunchDescriptor descriptor, + AuthoredWorldLaunchDescriptorEvidence.Request request, + String requestJson, + String sourceJson, + String sourceGameTenantKey) { + if (!LaunchDescriptor.OUTCOME_FAILED.equals(descriptor.getOutcomeStatus()) + || !Objects.equals( + descriptor.getDescriptorSchemaVersion(), + AuthoredWorldLaunchDescriptorEvidence.SCHEMA_VERSION) + || !workloadNamespace.equals(descriptor.getTargetNamespace()) + || !request.canonicalTenantId().toString().equals(descriptor.getCanonicalTenantId()) + || !request.worldSlug().equals(descriptor.getWorldSlug()) + || !request + .authoredWorldSourceOperationId() + .toString() + .equals(descriptor.getAuthoredWorldSourceOperationId()) + || !request + .authoredWorldSourceEvidenceDigest() + .equals(descriptor.getAuthoredWorldSourceEvidenceDigest()) + || !request.controlPlaneRequestId().equals(descriptor.getControlPlaneRequestId()) + || !request.requestDigest().equals(descriptor.getRequestDigest()) + || !request.requestDigest().equals(descriptor.getRequestHash()) + || !requestJson.equals(descriptor.getOriginalRequestJson()) + || !sourceJson.equals(descriptor.getSourceEvidenceJson()) + || !sourceGameTenantKey.equals(descriptor.getTenantId()) + || descriptor.getLaunchDescriptorId() != null + || descriptor.getGameTemplateId() != null + || descriptor.getVersionId() != null + || descriptor.getScriptPatchVersion() != null + || descriptor.getRuntimeFlagsJson() != null + || descriptor.getGenerationConfigRevision() != null + || descriptor.getVersionStateEpoch() != null + || descriptor.getReleaseBundleId() != null + || descriptor.getPublishedReleaseBundleRef() != null + || descriptor.getRemapSetId() != null + || descriptor.getResultDigest() != null + || !isPersistableFailureCode(descriptor.getFailureCode()) + || descriptor.getFailureMessage() == null + || descriptor.getFailureMessage().isBlank()) { + throw new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_CONFLICT: stored failure is not the exact immutable request outcome"); + } + throw FrozenLaunchDescriptorDenialException.fromStored( + descriptor.getFailureCode(), descriptor.getFailureMessage()); + } + + private boolean isPersistableFailureCode(String failureCode) { + return switch (failureCode == null ? "" : failureCode) { + case "TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED", + "INVALID_TEMPLATE_CONFIGURATION", + "SCRIPT_PATCH_OVERRIDE_CONFLICT", + "SCRIPT_PATCH_NOT_READY", + "RELEASE_BUNDLE_NOT_FOUND", + "RELEASE_ATTESTATION_MISMATCH", + "VERSION_STATE_EPOCH_STALE", + "LAUNCH_REMAP_REQUIRED", + PublishedReleaseBundleContract.SCHEMA_VERSION_UNSUPPORTED -> + true; + default -> false; + }; + } + + private static FrozenLaunchDescriptorDenialException denial(String code, String detail) { + return FrozenLaunchDescriptorDenialException.create(code, detail); + } + + private AuthoredWorldLaunchDescriptorEvidence.Request readRequest(String json) { + if (json == null) { + throw new IllegalArgumentException("LAUNCH_DESCRIPTOR_UNBOUND: original request is missing"); + } + try { + AuthoredWorldLaunchDescriptorEvidence.Request request = + objectMapper.readValue(json, AuthoredWorldLaunchDescriptorEvidence.Request.class); + if (!writeJson(request).equals(json)) { + throw new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_UNBOUND: original request is not the closed owner encoding"); + } + return request; + } catch (Exception exception) { + throw new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_UNBOUND: original request is unreadable", exception); + } + } + + private String writeJson(Object value) { + try { + return objectMapper.writeValueAsString(value); + } catch (Exception exception) { + throw new IllegalStateException( + "Launch descriptor evidence could not be serialized", exception); + } + } + + private void requireConfiguredNamespace(String requestNamespace) { + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace) + || !workloadNamespace.equals(requestNamespace)) { + throw new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_NAMESPACE_MISMATCH: configured workload namespace is required"); + } } private String resolveScriptPatchVersion( GameTemplateLaunchConfigView template, - String requestedScriptPatchVersion, + AuthoredWorldLaunchDescriptorEvidence.Request request, VersionDto version) { String templateDefault = normalizeBlank(template.getDefaultScriptPatchVersion()); - String requested = normalizeBlank(requestedScriptPatchVersion); + String requested = + request.requestedScriptPatchVersionPresent() + ? normalizeBlank(request.requestedScriptPatchVersion()) + : null; if (templateDefault != null && requested != null && !templateDefault.equals(requested)) { - throw new IllegalArgumentException( - "SCRIPT_PATCH_OVERRIDE_CONFLICT: requested script patch conflicts with template default"); + throw denial( + "SCRIPT_PATCH_OVERRIDE_CONFLICT", + "requested script patch conflicts with template default"); } String resolved = requested != null ? requested : templateDefault; if (resolved != null && version.scriptPatchVersion() != null && !version.scriptPatchVersion().isBlank() && !version.scriptPatchVersion().equals(resolved)) { - throw new IllegalArgumentException( - "SCRIPT_PATCH_NOT_READY: requested script patch is not published for the resolved version"); + throw denial( + "SCRIPT_PATCH_NOT_READY", + "requested script patch is not published for the resolved version"); } return resolved; } private String resolveRuntimeFlagsJson( - GameTemplateLaunchConfigView template, String requestedRuntimeFlagsJson) { + GameTemplateLaunchConfigView template, + AuthoredWorldLaunchDescriptorEvidence.Request request) { String templateFlags = normalizeBlank(template.getDefaultRuntimeFlagsJson()) == null ? "{}" : template.getDefaultRuntimeFlagsJson(); - String requested = normalizeBlank(requestedRuntimeFlagsJson); + String requested = + request.requestedRuntimeFlagsJsonPresent() + ? normalizeBlank(request.requestedRuntimeFlagsJson()) + : null; if (requested == null) { return templateFlags; } if (!"{}".equals(templateFlags)) { - throw new IllegalArgumentException( - "INVALID_TEMPLATE_CONFIGURATION: template-owned runtime flags cannot be overridden"); + throw denial( + "INVALID_TEMPLATE_CONFIGURATION", "template-owned runtime flags cannot be overridden"); } return requested; } private void requireReadyScriptPatch(String scriptPatchVersion) { if (scriptPatchVersion != null && !scriptPatchVersion.isBlank()) { - throw new IllegalArgumentException( - "SCRIPT_PATCH_NOT_READY: exact published-for-base and Automation READY evidence is unavailable"); - } - } - - private net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto - requirePublishedReleaseBundle(String tenantId, long resolvedVersionId) { - try { - return publishedReleaseBundleService.getPublishedReleaseBundle(tenantId, resolvedVersionId); - } catch (PublishedReleaseBundleNotFoundException ex) { - throw new IllegalArgumentException( - "RELEASE_BUNDLE_NOT_FOUND: no published release bundle for the resolved version"); + throw denial( + "SCRIPT_PATCH_NOT_READY", + "exact published-for-base and Automation READY evidence is unavailable"); } } - private ResolvedLaunchDescriptorDto toDto(LaunchDescriptor descriptor) { - return new ResolvedLaunchDescriptorDto( - descriptor.getLaunchDescriptorId(), - descriptor.getTenantId(), - descriptor.getGameTemplateId(), - descriptor.getControlPlaneRequestId(), - descriptor.getVersionId(), - descriptor.getScriptPatchVersion(), - descriptor.getRuntimeFlagsJson(), - descriptor.getGenerationConfigRevision(), - descriptor.getVersionStateEpoch(), - descriptor.getReleaseBundleId(), - descriptor.getPublishedReleaseBundleRef(), - descriptor.getRemapSetId()); - } - - private String hashRequest( - String tenantId, - long gameTemplateId, - String controlPlaneRequestId, - String requestedScriptPatchVersion, - Long sourceVersionId, - Long targetVersionId, - String requestedRuntimeFlagsJson) { - Map request = new LinkedHashMap<>(); - request.put("tenantId", tenantId); - request.put("gameTemplateId", gameTemplateId); - request.put("controlPlaneRequestId", controlPlaneRequestId); - request.put("requestedScriptPatchVersion", normalizeBlank(requestedScriptPatchVersion)); - request.put("sourceVersionId", sourceVersionId); - request.put("targetVersionId", targetVersionId); - request.put("requestedRuntimeFlagsJson", normalizeBlank(requestedRuntimeFlagsJson)); + private PublishedReleaseBundleDto requirePublishedReleaseBundle(String tenantId, long versionId) { try { - return sha256(objectMapper.writeValueAsString(request)); - } catch (StreamReadException | tools.jackson.databind.DatabindException ex) { - throw new IllegalStateException("failed to hash launch descriptor request", ex); + return publishedReleaseBundleService.getPublishedReleaseBundle(tenantId, versionId); + } catch (PublishedReleaseBundleNotFoundException exception) { + throw denial( + "RELEASE_BUNDLE_NOT_FOUND", "no published release bundle for the resolved version"); } } - private String releaseBundleRef(String tenantId, long bundleId, long versionId) { - return "prb:" + tenantId + ":" + versionId + ":" + bundleId; - } - - private String sha256(String value) { - try { - MessageDigest digest = MessageDigest.getInstance("SHA-256"); - byte[] bytes = digest.digest(value.getBytes(StandardCharsets.UTF_8)); - StringBuilder builder = new StringBuilder(bytes.length * 2); - for (byte current : bytes) { - builder.append(String.format("%02x", current)); - } - return builder.toString(); - } catch (NoSuchAlgorithmException ex) { - throw new IllegalStateException("sha-256 unavailable", ex); - } + private String releaseBundleRef(String canonicalTenantId, long bundleId, long versionId) { + return "release-bundle:" + canonicalTenantId + ":" + versionId + ":" + bundleId; } - private String normalizeBlank(String value) { + private static String normalizeBlank(String value) { return value == null || value.isBlank() ? null : value; } } diff --git a/services/game-design-service/src/main/resources/application-prod.yml b/services/game-design-service/src/main/resources/application-prod.yml index 53ba1be852..baa0577a12 100644 --- a/services/game-design-service/src/main/resources/application-prod.yml +++ b/services/game-design-service/src/main/resources/application-prod.yml @@ -55,6 +55,8 @@ firemud: - gamedesign.v1.TenantIdentityService/ResolveRuntimeTenantIdentity - gamedesign.v1.TenantIdentityService/ResolveAuthoredWorldSource - gamedesign.v1.TenantIdentityService/ResolveLegacyGameSessionTenantAssociation + - gamedesign.v1.GameDesignService/ResolveLaunchDescriptor + - gamedesign.v1.GameDesignService/GetLaunchDescriptor grpc: cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} diff --git a/services/game-design-service/src/main/resources/application.yml b/services/game-design-service/src/main/resources/application.yml index 8e5ef17edd..9072adfc00 100644 --- a/services/game-design-service/src/main/resources/application.yml +++ b/services/game-design-service/src/main/resources/application.yml @@ -78,6 +78,8 @@ firemud: - gamedesign.v1.TenantIdentityService/ResolveRuntimeTenantIdentity - gamedesign.v1.TenantIdentityService/ResolveAuthoredWorldSource - gamedesign.v1.TenantIdentityService/ResolveLegacyGameSessionTenantAssociation + - gamedesign.v1.GameDesignService/ResolveLaunchDescriptor + - gamedesign.v1.GameDesignService/GetLaunchDescriptor grpc: cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} diff --git a/services/game-design-service/src/main/resources/db/migration/V35__authored_source_launch_descriptor_binding.sql b/services/game-design-service/src/main/resources/db/migration/V35__authored_source_launch_descriptor_binding.sql new file mode 100644 index 0000000000..d539f6021d --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V35__authored_source_launch_descriptor_binding.sql @@ -0,0 +1,147 @@ +ALTER TABLE launch_descriptor ADD COLUMN descriptor_schema_version SMALLINT; +ALTER TABLE launch_descriptor ADD COLUMN target_namespace VARCHAR(63); +ALTER TABLE launch_descriptor ADD COLUMN canonical_tenant_id UUID; +ALTER TABLE launch_descriptor ADD COLUMN world_slug VARCHAR(120); +ALTER TABLE launch_descriptor ADD COLUMN authored_world_source_operation_id UUID; +ALTER TABLE launch_descriptor ADD COLUMN authored_world_source_evidence_digest VARCHAR(72); +ALTER TABLE launch_descriptor ADD COLUMN request_digest VARCHAR(72); +ALTER TABLE launch_descriptor ADD COLUMN result_digest VARCHAR(72); +ALTER TABLE launch_descriptor ADD COLUMN original_request_json TEXT; +ALTER TABLE launch_descriptor ADD COLUMN source_evidence_json TEXT; +ALTER TABLE launch_descriptor ADD COLUMN outcome_status VARCHAR(16) NOT NULL DEFAULT 'SUCCESS'; +ALTER TABLE launch_descriptor ADD COLUMN failure_code VARCHAR(64); +ALTER TABLE launch_descriptor ADD COLUMN failure_message TEXT; + +-- A deterministic denial is a request outcome, not a descriptor. Keep the successful tuple +-- nullable at the row level and require its complete shape below for SUCCESS outcomes. +ALTER TABLE launch_descriptor ALTER COLUMN launch_descriptor_id DROP NOT NULL; +ALTER TABLE launch_descriptor ALTER COLUMN game_template_id DROP NOT NULL; +ALTER TABLE launch_descriptor ALTER COLUMN version_id DROP NOT NULL; +ALTER TABLE launch_descriptor ALTER COLUMN runtime_flags_json DROP NOT NULL; +ALTER TABLE launch_descriptor ALTER COLUMN generation_config_revision DROP NOT NULL; +ALTER TABLE launch_descriptor ALTER COLUMN version_state_epoch DROP NOT NULL; +ALTER TABLE launch_descriptor ALTER COLUMN release_bundle_id DROP NOT NULL; +ALTER TABLE launch_descriptor ALTER COLUMN published_release_bundle_ref DROP NOT NULL; + +ALTER TABLE launch_descriptor + ADD CONSTRAINT ck_launch_descriptor_authored_binding_complete + CHECK ( + (outcome_status = 'SUCCESS' + AND descriptor_schema_version IS NULL + AND target_namespace IS NULL + AND canonical_tenant_id IS NULL + AND world_slug IS NULL + AND authored_world_source_operation_id IS NULL + AND authored_world_source_evidence_digest IS NULL + AND request_digest IS NULL + AND result_digest IS NULL + AND original_request_json IS NULL + AND source_evidence_json IS NULL + AND failure_code IS NULL + AND failure_message IS NULL + AND launch_descriptor_id IS NOT NULL + AND tenant_id IS NOT NULL + AND game_template_id IS NOT NULL + AND control_plane_request_id IS NOT NULL + AND request_hash IS NOT NULL + AND version_id IS NOT NULL + AND runtime_flags_json IS NOT NULL + AND generation_config_revision IS NOT NULL + AND version_state_epoch IS NOT NULL + AND release_bundle_id IS NOT NULL + AND published_release_bundle_ref IS NOT NULL) + OR + (outcome_status = 'SUCCESS' + AND descriptor_schema_version IS NOT NULL + AND descriptor_schema_version = 1 + AND target_namespace IS NOT NULL + AND canonical_tenant_id IS NOT NULL + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND world_slug IS NOT NULL + AND authored_world_source_operation_id IS NOT NULL + AND authored_world_source_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND authored_world_source_evidence_digest IS NOT NULL + AND request_digest IS NOT NULL + AND result_digest IS NOT NULL + AND original_request_json IS NOT NULL + AND source_evidence_json IS NOT NULL + AND failure_code IS NULL + AND failure_message IS NULL + AND launch_descriptor_id IS NOT NULL + AND tenant_id IS NOT NULL + AND game_template_id IS NOT NULL + AND control_plane_request_id IS NOT NULL + AND version_id IS NOT NULL + AND runtime_flags_json IS NOT NULL + AND generation_config_revision IS NOT NULL + AND version_state_epoch IS NOT NULL + AND release_bundle_id IS NOT NULL + AND published_release_bundle_ref IS NOT NULL + AND request_hash = request_digest) + OR + (outcome_status = 'FAILED' + AND descriptor_schema_version IS NOT NULL + AND descriptor_schema_version = 1 + AND target_namespace IS NOT NULL + AND canonical_tenant_id IS NOT NULL + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND world_slug IS NOT NULL + AND authored_world_source_operation_id IS NOT NULL + AND authored_world_source_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND authored_world_source_evidence_digest IS NOT NULL + AND request_digest IS NOT NULL + AND result_digest IS NULL + AND original_request_json IS NOT NULL + AND source_evidence_json IS NOT NULL + AND failure_code IS NOT NULL + AND failure_code IN ( + 'TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED', + 'INVALID_TEMPLATE_CONFIGURATION', + 'SCRIPT_PATCH_OVERRIDE_CONFLICT', + 'SCRIPT_PATCH_NOT_READY', + 'RELEASE_BUNDLE_NOT_FOUND', + 'RELEASE_ATTESTATION_MISMATCH', + 'VERSION_STATE_EPOCH_STALE', + 'LAUNCH_REMAP_REQUIRED', + 'SCHEMA_VERSION_UNSUPPORTED') + AND failure_message IS NOT NULL + AND CHAR_LENGTH(failure_message) > 0 + AND launch_descriptor_id IS NULL + AND tenant_id IS NOT NULL + AND game_template_id IS NULL + AND control_plane_request_id IS NOT NULL + AND request_hash = request_digest + AND version_id IS NULL + AND script_patch_version IS NULL + AND runtime_flags_json IS NULL + AND generation_config_revision IS NULL + AND version_state_epoch IS NULL + AND release_bundle_id IS NULL + AND published_release_bundle_ref IS NULL + AND remap_set_id IS NULL) + ); + +ALTER TABLE launch_descriptor + ADD CONSTRAINT ck_launch_descriptor_outcome_status + CHECK (outcome_status IN ('SUCCESS', 'FAILED')); + +CREATE UNIQUE INDEX uq_launch_descriptor_bound_request + ON launch_descriptor(target_namespace, canonical_tenant_id, control_plane_request_id) + WHERE descriptor_schema_version IS NOT NULL; + +-- PostgreSQL enforces the immutable history; the schema generator needs only the table shape. +-- [jooq ignore start] +CREATE FUNCTION reject_launch_descriptor_history_mutation() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'launch descriptors are immutable'; +END; +$$; + +CREATE TRIGGER trg_launch_descriptor_immutable + BEFORE UPDATE OR DELETE ON launch_descriptor + FOR EACH ROW + EXECUTE FUNCTION reject_launch_descriptor_history_mutation(); +-- [jooq ignore end] diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java index 202e3f3faf..4bcd23a5ae 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java @@ -1,29 +1,63 @@ package integration.net.firedevops.firemud.gamedesign.service; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.time.LocalDateTime; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.gamedesign.GameDesignServiceApplication; +import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; +import net.firedevops.firemud.gamedesign.entity.Game; import net.firedevops.firemud.gamedesign.entity.GameTemplate; +import net.firedevops.firemud.gamedesign.entity.LaunchDescriptor; import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.model.TemplateReferencePhase; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.GameTemplateLaunchConfigView; import net.firedevops.firemud.gamedesign.repository.GameTemplateRepository; +import net.firedevops.firemud.gamedesign.repository.LaunchDescriptorRepository; import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; +import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; +import net.firedevops.firemud.gamedesign.service.TemplateRemapSetService; +import net.firedevops.firemud.gamedesign.service.impl.LaunchDescriptorServiceImpl; import net.firedevops.firemud.test.NoGrpcServerTestConfiguration; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; +import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Import; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.ObjectMapper; @Testcontainers(disabledWithoutDocker = true) @SpringBootTest( @@ -32,6 +66,7 @@ "spring.profiles.active=test", "firemud.auth.jwt-secret=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "firemud.grpc.plaintext=true", + "firemud.grpc.workload-namespace=launch-descriptor-test", "spring.grpc.server.port=0", "asset.store.endpoint=http://localhost:9000", "asset.store.bucket=test-bucket", @@ -41,6 +76,18 @@ }) @Import(NoGrpcServerTestConfiguration.class) class LaunchDescriptorServiceIntegrationTest { + private static final String NAMESPACE = "launch-descriptor-test"; + private static final String FLYWAY_TABLE = "flyway_schema_history_game_design_service"; + private static final org.jooq.Table LAUNCH_DESCRIPTOR = + DSL.table(DSL.name("launch_descriptor")); + private static final org.jooq.Field LAUNCH_ROW_ID = DSL.field(DSL.name("id"), Long.class); + private static final org.jooq.Field LAUNCH_NAMESPACE = + DSL.field(DSL.name("target_namespace"), String.class); + private static final org.jooq.Field LAUNCH_CANONICAL_TENANT = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final org.jooq.Field LAUNCH_REQUEST_ID = + DSL.field(DSL.name("control_plane_request_id"), String.class); + @Container static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); @@ -51,51 +98,864 @@ static void configure(DynamicPropertyRegistry registry) { } @Autowired private LaunchDescriptorService launchDescriptorService; + @Autowired private GameRepository gameRepository; + @Autowired private GameAuthoredWorldSourceRepository authoredWorldSourceRepository; @Autowired private GameTemplateRepository gameTemplateRepository; @Autowired private VersionRepository versionRepository; @Autowired private PublishedReleaseBundleRepository publishedReleaseBundleRepository; + @Autowired private PublishedReleaseBundleService publishedReleaseBundleService; + @Autowired private LaunchDescriptorRepository launchDescriptorRepository; + @Autowired private PlatformTransactionManager transactionManager; + @Autowired private DSLContext dsl; + + @Test + void resolvesPersistedSourceAndReplaysOriginalDescriptorAfterDefaultsAndVersionChange() { + Fixture fixture = fixture("cp-persisted"); + + ResolvedLaunchDescriptorDto original = + launchDescriptorService.resolveLaunchDescriptor(fixture.request()); + assertThat(original.canonicalTenantId()).isEqualTo(fixture.canonicalTenantId().toString()); + assertThat(original.authoredWorldBinding()).isNotNull(); + assertThat(original.authoredWorldBinding().authoredWorldSourceOperationId()) + .isEqualTo(fixture.source().operationId()); + assertThat(original.authoredWorldBinding().authoredWorldSourceEvidenceDigest()) + .isEqualTo(fixture.source().evidenceDigest()); + assertThat(original.canonicalTenantId()).isNotEqualTo(fixture.privateSourceTenantKey()); + + Version newDraft = new Version(); + newDraft.setTenantId(fixture.privateSourceTenantKey()); + newDraft.setVersionNumber(2); + newDraft.setVersionState(VersionLifecycleState.DRAFT); + newDraft.setVersionStateEpoch(1L); + newDraft.setNotes("new mutable template default"); + newDraft.setUpdatedAt(LocalDateTime.now()); + newDraft = versionRepository.save(newDraft); + fixture.template().setDefaultVersionId(newDraft.getId()); + gameTemplateRepository.save(fixture.template()); + fixture.version().setVersionState(VersionLifecycleState.RETIRED); + fixture.version().setVersionStateEpoch(2L); + versionRepository.save(fixture.version()); + + ResolvedLaunchDescriptorDto retry = + launchDescriptorService.resolveLaunchDescriptor(fixture.request()); + + assertThat(retry).isEqualTo(original); + assertThat(retry.versionId()).isEqualTo(fixture.version().getId()); + LaunchDescriptor persisted = + launchDescriptorRepository + .findBoundByRequest( + NAMESPACE, fixture.canonicalTenantId(), fixture.controlPlaneRequestId()) + .orElseThrow(); + assertThat(persisted.getLaunchDescriptorId()).isEqualTo(original.launchDescriptorId()); + assertThat(persisted.getRequestDigest()) + .isEqualTo(original.authoredWorldBinding().requestDigest()); + assertThat(persisted.getResultDigest()) + .isEqualTo(original.authoredWorldBinding().resultDigest()); + assertThat( + dsl.fetchCount( + LAUNCH_DESCRIPTOR, + LAUNCH_NAMESPACE + .eq(NAMESPACE) + .and(LAUNCH_CANONICAL_TENANT.eq(fixture.canonicalTenantId())) + .and(LAUNCH_REQUEST_ID.eq(fixture.controlPlaneRequestId())))) + .isEqualTo(1); + + ResolvedLaunchDescriptorDto readback = + launchDescriptorService.getLaunchDescriptor( + UUID.randomUUID(), + fixture.canonicalTenantId(), + fixture.source().worldSlug(), + fixture.controlPlaneRequestId(), + original.authoredWorldBinding().requestDigest(), + original.authoredWorldBinding().resultDigest()); + assertThat(readback).isEqualTo(original); + } + + @Test + void concurrentExactRetriesPersistOneOriginalDescriptor() throws Exception { + Fixture fixture = fixture("cp-concurrent"); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit(() -> resolveAfterLatch(fixture, ready, start)); + Future second = + executor.submit(() -> resolveAfterLatch(fixture, ready, start)); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + + ResolvedLaunchDescriptorDto firstResult = first.get(20, TimeUnit.SECONDS); + ResolvedLaunchDescriptorDto secondResult = second.get(20, TimeUnit.SECONDS); + + assertThat(secondResult).isEqualTo(firstResult); + assertThat( + dsl.fetchCount( + LAUNCH_DESCRIPTOR, + LAUNCH_NAMESPACE + .eq(NAMESPACE) + .and(LAUNCH_CANONICAL_TENANT.eq(fixture.canonicalTenantId())) + .and(LAUNCH_REQUEST_ID.eq(fixture.controlPlaneRequestId())))) + .isEqualTo(1); + LaunchDescriptor persisted = + launchDescriptorRepository + .findBoundByRequest( + NAMESPACE, fixture.canonicalTenantId(), fixture.controlPlaneRequestId()) + .orElseThrow(); + assertThat(persisted.getLaunchDescriptorId()).isEqualTo(firstResult.launchDescriptorId()); + assertThat(persisted.getResultDigest()) + .isEqualTo(firstResult.authoredWorldBinding().resultDigest()); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } @Test - void resolvesLaunchDescriptorForJsonConfiguredTemplate() { + void deterministicFailureIsFrozenAcrossDependencyChangeAndConcurrentExactRetries() + throws Exception { + Fixture fixture = fixture("cp-frozen-phase"); + fixture.template().setTemplateReferencePhase(TemplateReferencePhase.LEGACY); + gameTemplateRepository.save(fixture.template()); + + assertThatThrownBy(() -> launchDescriptorService.resolveLaunchDescriptor(fixture.request())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage( + "TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED: template reference phase is not enforced"); + + LaunchDescriptor failed = + launchDescriptorRepository + .findBoundByRequest( + NAMESPACE, fixture.canonicalTenantId(), fixture.controlPlaneRequestId()) + .orElseThrow(); + assertThat(failed.getOutcomeStatus()).isEqualTo(LaunchDescriptor.OUTCOME_FAILED); + assertThat(failed.getFailureCode()).isEqualTo("TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED"); + assertThat(failed.getFailureMessage()) + .isEqualTo( + "TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED: template reference phase is not enforced"); + assertThat(failed.getRequestDigest()).isEqualTo(fixture.request().requestDigest()); + assertThat(failed.getOriginalRequestJson()).isNotBlank(); + assertThat(failed.getSourceEvidenceJson()).isNotBlank(); + assertThat(failed.getLaunchDescriptorId()).isNull(); + assertThat(failed.getGameTemplateId()).isNull(); + assertThat(failed.getVersionId()).isNull(); + assertThat(failed.getReleaseBundleId()).isNull(); + assertThat(failed.getResultDigest()).isNull(); + assertFailedShapeRejected(failed, "cp-frozen-null-schema", true); + assertFailedShapeRejected(failed, "cp-frozen-null-failure-code", false); + assertThat( + dsl.fetchCount( + LAUNCH_DESCRIPTOR, + LAUNCH_NAMESPACE + .eq(NAMESPACE) + .and(LAUNCH_CANONICAL_TENANT.eq(fixture.canonicalTenantId())) + .and(LAUNCH_REQUEST_ID.eq(fixture.controlPlaneRequestId())))) + .isEqualTo(1); + + fixture.template().setTemplateReferencePhase(TemplateReferencePhase.ENFORCED); + gameTemplateRepository.save(fixture.template()); + + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = executor.submit(() -> resolveFailureAfterLatch(fixture, ready, start)); + Future second = + executor.submit(() -> resolveFailureAfterLatch(fixture, ready, start)); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + assertThat(first.get(20, TimeUnit.SECONDS)).isEqualTo(failed.getFailureMessage()); + assertThat(second.get(20, TimeUnit.SECONDS)).isEqualTo(failed.getFailureMessage()); + } finally { + start.countDown(); + executor.shutdownNow(); + } + + assertThatThrownBy( + () -> + launchDescriptorService.resolveLaunchDescriptor( + fixture.requestWithPatch("different-patch"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("control-plane request identity was reused with changed input"); + + ResolvedLaunchDescriptorDto freshAttempt = + launchDescriptorService.resolveLaunchDescriptor(fixture.request("cp-frozen-phase-fresh")); + assertThat(freshAttempt.versionId()).isEqualTo(fixture.version().getId()); + assertThat( + launchDescriptorRepository + .findBoundByRequest(NAMESPACE, fixture.canonicalTenantId(), "cp-frozen-phase-fresh") + .orElseThrow() + .getOutcomeStatus()) + .isEqualTo(LaunchDescriptor.OUTCOME_SUCCESS); + } + + @Test + void corruptFailureReadbackRollsBackTheOutcomeInsert() { + Fixture fixture = fixture("cp-corrupt-failure-readback"); + fixture.template().setTemplateReferencePhase(TemplateReferencePhase.LEGACY); + gameTemplateRepository.save(fixture.template()); + LaunchDescriptorRepository corruptingRepository = + new LaunchDescriptorRepository(dsl) { + @Override + public LaunchDescriptor insertImmutable(LaunchDescriptor descriptor) { + LaunchDescriptor persisted = super.insertImmutable(descriptor); + persisted.setFailureCode("UNRECOGNIZED_FAILURE"); + return persisted; + } + }; + LaunchDescriptorServiceImpl corruptingService = + new LaunchDescriptorServiceImpl( + gameTemplateRepository, + corruptingRepository, + versionRepository, + Mockito.mock(PublishedReleaseBundleService.class), + Mockito.mock(TemplateRemapSetService.class), + authoredWorldSourceRepository, + new ObjectMapper()); + ReflectionTestUtils.setField(corruptingService, "workloadNamespace", NAMESPACE); + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + + assertThatThrownBy( + () -> + transaction.execute( + status -> corruptingService.resolveLaunchDescriptor(fixture.request()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("stored failure is not the exact immutable request outcome"); + + assertThat( + launchDescriptorRepository.findBoundByRequest( + NAMESPACE, fixture.canonicalTenantId(), fixture.controlPlaneRequestId())) + .isEmpty(); + } + + @Test + void concurrentSuccessAndFailureCandidatesPersistOnlyTheFirstOutcome() throws Exception { + Fixture fixture = fixture("cp-mixed-candidates"); + CountDownLatch lockArrivals = new CountDownLatch(2); + CountDownLatch viewReached = new CountDownLatch(1); + CountDownLatch continueResolution = new CountDownLatch(1); + LaunchDescriptorRepository serializedRepository = + new LaunchDescriptorRepository(dsl) { + @Override + public void lockBoundRequest(String targetNamespace, UUID tenantId, String requestId) { + lockArrivals.countDown(); + super.lockBoundRequest(targetNamespace, tenantId, requestId); + } + }; + LaunchDescriptorServiceImpl failureCandidate = + candidateForPhase( + fixture, + serializedRepository, + TemplateReferencePhase.LEGACY, + viewReached, + continueResolution); + LaunchDescriptorServiceImpl successCandidate = + candidateForPhase( + fixture, + serializedRepository, + TemplateReferencePhase.ENFORCED, + viewReached, + continueResolution); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit( + () -> resolveCandidateInOwnerTransaction(failureCandidate, fixture, ready, start)); + Future second = + executor.submit( + () -> resolveCandidateInOwnerTransaction(successCandidate, fixture, ready, start)); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + assertThat(viewReached.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(lockArrivals.await(10, TimeUnit.SECONDS)).isTrue(); + continueResolution.countDown(); + + String firstResult = first.get(20, TimeUnit.SECONDS); + String secondResult = second.get(20, TimeUnit.SECONDS); + assertThat(secondResult).isEqualTo(firstResult); + LaunchDescriptor stored = + launchDescriptorRepository + .findBoundByRequest( + NAMESPACE, fixture.canonicalTenantId(), fixture.controlPlaneRequestId()) + .orElseThrow(); + assertThat(stored.getOutcomeStatus()) + .isEqualTo( + firstResult.startsWith("FAILED:") + ? LaunchDescriptor.OUTCOME_FAILED + : LaunchDescriptor.OUTCOME_SUCCESS); + assertThat( + dsl.fetchCount( + LAUNCH_DESCRIPTOR, + LAUNCH_NAMESPACE + .eq(NAMESPACE) + .and(LAUNCH_CANONICAL_TENANT.eq(fixture.canonicalTenantId())) + .and(LAUNCH_REQUEST_ID.eq(fixture.controlPlaneRequestId())))) + .isEqualTo(1); + } finally { + continueResolution.countDown(); + start.countDown(); + executor.shutdownNow(); + } + } + + @Test + void rolledBackDescriptorInsertLeavesNoCanonicalOrPrivateRequestClaim() { + Fixture fixture = fixture("cp-rollback"); + AuthoredWorldLaunchDescriptorEvidence evidence = evidence(fixture, "ld-rollback-candidate"); + LaunchDescriptor candidate = entity(evidence, fixture); + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + + assertThatThrownBy( + () -> + transaction.execute( + status -> { + launchDescriptorRepository.insertImmutable(candidate); + throw new IllegalStateException("force owner transaction rollback"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("force owner transaction rollback"); + + assertThat( + launchDescriptorRepository.findBoundByRequest( + NAMESPACE, fixture.canonicalTenantId(), fixture.controlPlaneRequestId())) + .isEmpty(); + assertThat( + launchDescriptorRepository.findByPrivateRequest( + fixture.privateSourceTenantKey(), fixture.controlPlaneRequestId())) + .isEmpty(); + ResolvedLaunchDescriptorDto committed = + launchDescriptorService.resolveLaunchDescriptor(fixture.request()); + assertThat(committed.authoredWorldBinding().requestDigest()) + .isEqualTo(evidence.requestDigest()); + } + + @Test + void v35MigrationPreservesRetainedUnboundDescriptorAndCanonicalResolveDeniesIt() { + String schema = "game_design_launch_history_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = isolatedDataSource(schema); + migrate(dataSource, schema, MigrationVersion.fromVersion("34")); + DSLContext isolatedDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + DataSourceTransactionManager isolatedTransactionManager = + new DataSourceTransactionManager(dataSource); + TransactionTemplate isolatedTransaction = new TransactionTemplate(isolatedTransactionManager); + + String privateTenantKey = privateTenantKey(); + Game game = new Game(); + game.setTenantId(privateTenantKey); + game.setName("Retained launch source"); + game.setDescription("Persisted V34 source fixture"); + Game persistedGame = + isolatedTransaction.execute(status -> new GameRepository(isolatedDsl).save(game)); + assertThat(persistedGame).isNotNull(); + String suffix = UUID.randomUUID().toString().replace("-", "").substring(0, 12); + AuthoredWorldSourceEvidence source = + isolatedTransaction.execute( + status -> + new GameAuthoredWorldSourceRepository(isolatedDsl) + .register( + NAMESPACE, + UUID.randomUUID(), + persistedGame.getCanonicalTenantId(), + "tenant-" + suffix, + "world-" + suffix, + "Retained World 🐉")); + assertThat(source).isNotNull(); + + Long versionId = + isolatedDsl + .resultQuery( + "INSERT INTO version (tenant_id, version_number, version_state, version_state_epoch) " + + "VALUES (?, 1, 'PUBLISHED', 1) RETURNING id", + privateTenantKey) + .fetchOne(0, Long.class); + Long templateId = + isolatedDsl + .resultQuery( + "INSERT INTO game_templates (tenant_id, name, config) " + + "VALUES (?, ?, '{}'::jsonb) RETURNING id", + privateTenantKey, + "Retained Template " + suffix) + .fetchOne(0, Long.class); + // Synthetic retained-row seed for storage compatibility only; not live publication proof. + Long bundleId = + isolatedDsl + .resultQuery( + "INSERT INTO published_release_bundle " + + "(tenant_id, version_id, version_number, attestation_schema_version, " + + "publish_workflow_id, manifest_hash, required_manifest_asset_keys_json, " + + "participant_digests_json, generation_config_revision) " + + "VALUES (?, ?, 1, 'v1', ?, ?, '[]', '[]', ?) RETURNING id", + privateTenantKey, + versionId, + "synthetic-retained-fixture-" + suffix, + "sha256:" + "d".repeat(64), + "gen-rev:" + suffix) + .fetchOne(0, Long.class); + String requestId = "retained-cp-" + suffix; + String legacyDescriptorId = "ld-retained-" + suffix; + isolatedDsl.execute( + "INSERT INTO launch_descriptor " + + "(launch_descriptor_id, tenant_id, game_template_id, control_plane_request_id, " + + "request_hash, version_id, runtime_flags_json, generation_config_revision, " + + "version_state_epoch, release_bundle_id, published_release_bundle_ref) " + + "VALUES (?, ?, ?, ?, ?, ?, '{}', ?, 1, ?, ?)", + legacyDescriptorId, + privateTenantKey, + templateId, + requestId, + "legacy-request-hash-" + suffix, + versionId, + "gen-rev:" + suffix, + bundleId, + "legacy-release-ref-" + suffix); + Map retainedV34Snapshot = + legacyLaunchDescriptorSnapshot(isolatedDsl, privateTenantKey, requestId); + + migrate(dataSource, schema, null); + LaunchDescriptorRepository launchRepository = new LaunchDescriptorRepository(isolatedDsl); + assertThat(legacyLaunchDescriptorSnapshot(isolatedDsl, privateTenantKey, requestId)) + .isEqualTo(retainedV34Snapshot); + LaunchDescriptor before = + launchRepository.findByPrivateRequest(privateTenantKey, requestId).orElseThrow(); + assertThat(before.getDescriptorSchemaVersion()).isNull(); + assertThat(before.getCanonicalTenantId()).isNull(); + assertThat(before.getRequestHash()).isEqualTo("legacy-request-hash-" + suffix); + + AuthoredWorldLaunchDescriptorEvidence.Request request = + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + requestId, + persistedGame.getCanonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + templateId, + false, + null, + false, + null, + false, + null, + false, + null); + LaunchDescriptorServiceImpl isolatedService = + new LaunchDescriptorServiceImpl( + Mockito.mock(GameTemplateRepository.class), + launchRepository, + Mockito.mock(VersionRepository.class), + Mockito.mock(PublishedReleaseBundleService.class), + Mockito.mock(TemplateRemapSetService.class), + new GameAuthoredWorldSourceRepository(isolatedDsl), + new ObjectMapper()); + ReflectionTestUtils.setField(isolatedService, "workloadNamespace", NAMESPACE); + + assertThatThrownBy(() -> isolatedService.resolveLaunchDescriptor(request)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("LAUNCH_DESCRIPTOR_CONFLICT") + .hasMessageContaining("unbound"); + assertThat( + launchRepository.findBoundByRequest( + NAMESPACE, persistedGame.getCanonicalTenantId(), requestId)) + .isEmpty(); + assertRetainedRowUnchanged( + before, launchRepository.findByPrivateRequest(privateTenantKey, requestId).orElseThrow()); + + assertThatThrownBy( + () -> + isolatedDsl.execute( + "UPDATE launch_descriptor SET runtime_flags_json = ? WHERE id = ?", + "{\"changed\":true}", + before.getId())) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("launch descriptors are immutable"); + assertRetainedRowUnchanged( + before, launchRepository.findByPrivateRequest(privateTenantKey, requestId).orElseThrow()); + } + + private Fixture fixture(String controlPlaneRequestId) { + String privateTenantKey = privateTenantKey(); + Game sourceGame = new Game(); + sourceGame.setTenantId(privateTenantKey); + sourceGame.setName("Launch Source " + UUID.randomUUID()); + sourceGame.setDescription("Persisted fresh Game Design tenant source"); + Game persistedGame = + new TransactionTemplate(transactionManager) + .execute(status -> gameRepository.save(sourceGame)); + assertThat(persistedGame).isNotNull(); + + String suffix = UUID.randomUUID().toString().replace("-", "").substring(0, 12); + AuthoredWorldSourceEvidence source = + new TransactionTemplate(transactionManager) + .execute( + status -> + authoredWorldSourceRepository.register( + NAMESPACE, + UUID.randomUUID(), + persistedGame.getCanonicalTenantId(), + "tenant-" + suffix, + "world-" + suffix, + "Launch World 🐉")); + assertThat(source).isNotNull(); + Version version = new Version(); - version.setTenantId("1"); + version.setTenantId(privateTenantKey); version.setVersionNumber(1); version.setVersionState(VersionLifecycleState.PUBLISHED); version.setVersionStateEpoch(1L); - version.setNotes("integration test version"); + version.setNotes("synthetic release storage proof fixture"); version.setUpdatedAt(LocalDateTime.now()); version = versionRepository.save(version); GameTemplate template = new GameTemplate(); - template.setTenantId("1"); - template.setName("Integration Template"); - template.setDescription("launch descriptor integration template"); + template.setTenantId(privateTenantKey); + template.setName("Launch Template " + suffix); + template.setDescription("Persisted descriptor resolution fixture"); template.setConfig("{}"); template.setDefaultVersionId(version.getId()); template.setDefaultRuntimeFlagsJson("{}"); template.setTemplateReferencePhase(TemplateReferencePhase.ENFORCED); template = gameTemplateRepository.save(template); + // This row exercises descriptor storage and resolution only; it is not live publication proof. PublishedReleaseBundle bundle = new PublishedReleaseBundle(); - bundle.setTenantId("1"); + bundle.setTenantId(privateTenantKey); bundle.setVersionId(version.getId()); bundle.setVersionNumber(1); bundle.setAttestationSchemaVersion("v1"); - bundle.setPublishWorkflowId("integration-seed"); - bundle.setManifestHash("integration-manifest"); - bundle.setGenerationConfigRevision("genrev:integration"); + bundle.setPublishWorkflowId("synthetic-storage-proof-" + suffix); + bundle.setManifestHash("sha256:" + "e".repeat(64)); + bundle.setGenerationConfigRevision("gen-rev:" + suffix); bundle.setRequiredManifestAssetKeysJson("[]"); bundle.setParticipantDigestsJson("[]"); bundle.setScriptOnly(false); - publishedReleaseBundleRepository.save(bundle); + bundle = publishedReleaseBundleRepository.save(bundle); + + return new Fixture( + controlPlaneRequestId, + persistedGame.getCanonicalTenantId(), + privateTenantKey, + source, + version, + template, + bundle); + } + + private void assertFailedShapeRejected( + LaunchDescriptor failed, String controlPlaneRequestId, boolean nullSchemaVersion) { + assertThatThrownBy( + () -> + dsl.execute( + """ + INSERT INTO launch_descriptor ( + tenant_id, + control_plane_request_id, + request_hash, + descriptor_schema_version, + target_namespace, + canonical_tenant_id, + world_slug, + authored_world_source_operation_id, + authored_world_source_evidence_digest, + request_digest, + original_request_json, + source_evidence_json, + outcome_status, + failure_code, + failure_message) + VALUES (?, ?, ?, CAST(? AS SMALLINT), ?, CAST(? AS UUID), ?, + CAST(? AS UUID), ?, ?, ?, ?, 'FAILED', CAST(? AS VARCHAR(64)), ?) + """, + failed.getTenantId(), + controlPlaneRequestId, + failed.getRequestHash(), + nullSchemaVersion ? null : failed.getDescriptorSchemaVersion(), + failed.getTargetNamespace(), + failed.getCanonicalTenantId(), + failed.getWorldSlug(), + failed.getAuthoredWorldSourceOperationId(), + failed.getAuthoredWorldSourceEvidenceDigest(), + failed.getRequestDigest(), + failed.getOriginalRequestJson(), + failed.getSourceEvidenceJson(), + nullSchemaVersion ? failed.getFailureCode() : null, + failed.getFailureMessage())) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("ck_launch_descriptor_authored_binding_complete"); + } + + private ResolvedLaunchDescriptorDto resolveAfterLatch( + Fixture fixture, CountDownLatch ready, CountDownLatch start) { + ready.countDown(); + await(start); + return launchDescriptorService.resolveLaunchDescriptor(fixture.request()); + } + + private String resolveFailureAfterLatch( + Fixture fixture, CountDownLatch ready, CountDownLatch start) { + ready.countDown(); + await(start); + try { + launchDescriptorService.resolveLaunchDescriptor(fixture.request()); + return "unexpected success"; + } catch (IllegalArgumentException exception) { + return exception.getMessage(); + } + } + + private String resolveCandidateInOwnerTransaction( + LaunchDescriptorServiceImpl service, + Fixture fixture, + CountDownLatch ready, + CountDownLatch start) { + ready.countDown(); + await(start); + return new TransactionTemplate(transactionManager) + .execute( + status -> { + try { + return "SUCCESS:" + + service + .resolveLaunchDescriptor(fixture.request()) + .authoredWorldBinding() + .resultDigest(); + } catch (IllegalArgumentException exception) { + return "FAILED:" + exception.getMessage(); + } + }); + } + + private LaunchDescriptorServiceImpl candidateForPhase( + Fixture fixture, + LaunchDescriptorRepository repository, + TemplateReferencePhase phase, + CountDownLatch viewReached, + CountDownLatch continueResolution) { + GameTemplateRepository templateRepository = Mockito.mock(GameTemplateRepository.class); + GameTemplateLaunchConfigView view = Mockito.mock(GameTemplateLaunchConfigView.class); + Mockito.when(view.getId()).thenReturn(fixture.template().getId()); + Mockito.when(view.getTenantId()).thenReturn(fixture.privateSourceTenantKey()); + Mockito.when(view.getDefaultVersionId()).thenReturn(fixture.version().getId()); + Mockito.when(view.getDefaultRuntimeFlagsJson()).thenReturn("{}"); + Mockito.when(view.getTemplateReferencePhase()) + .thenAnswer( + invocation -> { + viewReached.countDown(); + await(continueResolution); + return phase; + }); + Mockito.when( + templateRepository.findLaunchConfigByTenantIdAndId( + fixture.privateSourceTenantKey(), fixture.template().getId())) + .thenReturn(java.util.Optional.of(view)); + LaunchDescriptorServiceImpl service = + new LaunchDescriptorServiceImpl( + templateRepository, + repository, + versionRepository, + publishedReleaseBundleService, + Mockito.mock(TemplateRemapSetService.class), + authoredWorldSourceRepository, + new ObjectMapper()); + ReflectionTestUtils.setField(service, "workloadNamespace", NAMESPACE); + return service; + } + + private void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting for descriptor retry race"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted while waiting for descriptor retry race", exception); + } + } + + private AuthoredWorldLaunchDescriptorEvidence evidence(Fixture fixture, String descriptorId) { + return AuthoredWorldLaunchDescriptorEvidence.create( + fixture.request(), + descriptorId, + fixture.version().getId(), + false, + null, + "{}", + fixture.bundle().getGenerationConfigRevision(), + fixture.version().getVersionStateEpoch(), + fixture.bundle().getId(), + "release-bundle:" + + fixture.canonicalTenantId() + + ":" + + fixture.version().getId() + + ":" + + fixture.bundle().getId(), + false, + null); + } + + private LaunchDescriptor entity(AuthoredWorldLaunchDescriptorEvidence evidence, Fixture fixture) { + LaunchDescriptor descriptor = new LaunchDescriptor(); + descriptor.setLaunchDescriptorId(evidence.launchDescriptorId()); + descriptor.setTenantId(fixture.privateSourceTenantKey()); + descriptor.setGameTemplateId(evidence.gameTemplateId()); + descriptor.setControlPlaneRequestId(evidence.controlPlaneRequestId()); + descriptor.setRequestHash(evidence.requestDigest()); + descriptor.setVersionId(evidence.versionId()); + descriptor.setScriptPatchVersion(evidence.scriptPatchVersion()); + descriptor.setRuntimeFlagsJson(evidence.runtimeFlagsJson()); + descriptor.setGenerationConfigRevision(evidence.generationConfigRevision()); + descriptor.setVersionStateEpoch(evidence.versionStateEpoch()); + descriptor.setReleaseBundleId(evidence.releaseBundleId()); + descriptor.setPublishedReleaseBundleRef(evidence.publishedReleaseBundleRef()); + descriptor.setRemapSetId(evidence.remapSetId()); + descriptor.setDescriptorSchemaVersion(evidence.schemaVersion()); + descriptor.setTargetNamespace(evidence.targetNamespace()); + descriptor.setCanonicalTenantId(evidence.canonicalTenantId().toString()); + descriptor.setWorldSlug(evidence.worldSlug()); + descriptor.setAuthoredWorldSourceOperationId( + evidence.authoredWorldSourceOperationId().toString()); + descriptor.setAuthoredWorldSourceEvidenceDigest(evidence.authoredWorldSourceEvidenceDigest()); + descriptor.setRequestDigest(evidence.requestDigest()); + descriptor.setResultDigest(evidence.resultDigest()); + descriptor.setOriginalRequestJson(json(evidence.request())); + descriptor.setSourceEvidenceJson(json(fixture.source())); + return descriptor; + } + + private String json(Object value) { + try { + return new ObjectMapper().writeValueAsString(value); + } catch (Exception exception) { + throw new IllegalStateException("Test evidence serialization failed", exception); + } + } + + private DriverManagerDataSource isolatedDataSource(String schema) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + return dataSource; + } + + private void migrate(DriverManagerDataSource dataSource, String schema, MigrationVersion target) { + var configuration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table(FLYWAY_TABLE) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration"); + if (target != null) { + configuration.target(target); + } + configuration.load().migrate(); + } + + private Map legacyLaunchDescriptorSnapshot( + DSLContext isolatedDsl, String privateTenantKey, String controlPlaneRequestId) { + var record = + isolatedDsl.fetchOne( + "SELECT id, launch_descriptor_id, tenant_id, game_template_id, " + + "control_plane_request_id, request_hash, version_id, script_patch_version, " + + "runtime_flags_json, generation_config_revision, version_state_epoch, " + + "release_bundle_id, published_release_bundle_ref, remap_set_id, created_at " + + "FROM launch_descriptor WHERE tenant_id = ? AND control_plane_request_id = ?", + privateTenantKey, + controlPlaneRequestId); + if (record == null) { + throw new IllegalStateException("Retained V34 launch descriptor fixture is missing"); + } + return record.intoMap(); + } + + private String privateTenantKey() { + return "src-" + UUID.randomUUID().toString().replace("-", ""); + } + + private void assertRetainedRowUnchanged(LaunchDescriptor expected, LaunchDescriptor actual) { + assertThat(actual.getId()).isEqualTo(expected.getId()); + assertThat(actual.getLaunchDescriptorId()).isEqualTo(expected.getLaunchDescriptorId()); + assertThat(actual.getTenantId()).isEqualTo(expected.getTenantId()); + assertThat(actual.getGameTemplateId()).isEqualTo(expected.getGameTemplateId()); + assertThat(actual.getControlPlaneRequestId()).isEqualTo(expected.getControlPlaneRequestId()); + assertThat(actual.getRequestHash()).isEqualTo(expected.getRequestHash()); + assertThat(actual.getVersionId()).isEqualTo(expected.getVersionId()); + assertThat(actual.getScriptPatchVersion()).isEqualTo(expected.getScriptPatchVersion()); + assertThat(actual.getRuntimeFlagsJson()).isEqualTo(expected.getRuntimeFlagsJson()); + assertThat(actual.getGenerationConfigRevision()) + .isEqualTo(expected.getGenerationConfigRevision()); + assertThat(actual.getVersionStateEpoch()).isEqualTo(expected.getVersionStateEpoch()); + assertThat(actual.getReleaseBundleId()).isEqualTo(expected.getReleaseBundleId()); + assertThat(actual.getPublishedReleaseBundleRef()) + .isEqualTo(expected.getPublishedReleaseBundleRef()); + assertThat(actual.getRemapSetId()).isEqualTo(expected.getRemapSetId()); + assertThat(actual.getCreatedAt()).isEqualTo(expected.getCreatedAt()); + assertThat(actual.getDescriptorSchemaVersion()).isNull(); + assertThat(actual.getTargetNamespace()).isNull(); + assertThat(actual.getCanonicalTenantId()).isNull(); + assertThat(actual.getWorldSlug()).isNull(); + assertThat(actual.getAuthoredWorldSourceOperationId()).isNull(); + assertThat(actual.getAuthoredWorldSourceEvidenceDigest()).isNull(); + assertThat(actual.getRequestDigest()).isNull(); + assertThat(actual.getResultDigest()).isNull(); + assertThat(actual.getOriginalRequestJson()).isNull(); + assertThat(actual.getSourceEvidenceJson()).isNull(); + } + + private record Fixture( + String controlPlaneRequestId, + UUID canonicalTenantId, + String privateSourceTenantKey, + AuthoredWorldSourceEvidence source, + Version version, + GameTemplate template, + PublishedReleaseBundle bundle) { + AuthoredWorldLaunchDescriptorEvidence.Request request() { + return request(controlPlaneRequestId); + } - var descriptor = - launchDescriptorService.resolveLaunchDescriptor( - "1", template.getId(), "integration-cp-1", null, null, null, null); + AuthoredWorldLaunchDescriptorEvidence.Request request(String requestId) { + return new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + requestId, + canonicalTenantId, + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + template.getId(), + false, + null, + false, + null, + false, + null, + false, + null); + } - assertThat(descriptor.gameTemplateId()).isEqualTo(template.getId()); - assertThat(descriptor.versionId()).isEqualTo(version.getId()); - assertThat(descriptor.generationConfigRevision()).isEqualTo("genrev:integration"); - assertThat(descriptor.versionStateEpoch()).isEqualTo(1L); + AuthoredWorldLaunchDescriptorEvidence.Request requestWithPatch(String patch) { + return new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + controlPlaneRequestId, + canonicalTenantId, + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + template.getId(), + true, + patch, + false, + null, + false, + null, + false, + null); + } } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldLaunchDescriptorMtlsTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldLaunchDescriptorMtlsTest.java new file mode 100644 index 0000000000..c0aa33c658 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldLaunchDescriptorMtlsTest.java @@ -0,0 +1,908 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.ForwardingServerCall.SimpleForwardingServerCall; +import io.grpc.ManagedChannel; +import io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.MetadataUtils; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.io.IOException; +import java.math.BigInteger; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.PrivateKey; +import java.security.Security; +import java.security.cert.X509Certificate; +import java.time.Instant; +import java.util.Base64; +import java.util.Date; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.security.AuthTokenInterceptor; +import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; +import net.firedevops.firemud.gamedesign.service.GameAuthoredHelpTopicService; +import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; +import net.firedevops.firemud.gamedesign.service.PingService; +import net.firedevops.firemud.gamedesign.service.RevisionService; +import net.firedevops.firemud.gamedesign.service.SettingsAuthorityService; +import net.firedevops.firemud.gamedesign.service.TemplateRemapSetService; +import net.firedevops.firemud.gamedesign.service.VersionAssetArtifactService; +import net.firedevops.firemud.gamedesign.service.VersionService; +import net.firedevops.firemud.gamedesign.v1.GameDesignServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorResponse; +import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorResponse; +import net.firedevops.firemud.test.TlsTestSupport; +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.asn1.x509.BasicConstraints; +import org.bouncycastle.asn1.x509.ExtendedKeyUsage; +import org.bouncycastle.asn1.x509.Extension; +import org.bouncycastle.asn1.x509.GeneralName; +import org.bouncycastle.asn1.x509.GeneralNames; +import org.bouncycastle.asn1.x509.KeyPurposeId; +import org.bouncycastle.asn1.x509.KeyUsage; +import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; +import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.ArgumentCaptor; +import org.mockito.Mockito; +import org.springframework.boot.context.properties.bind.Bindable; +import org.springframework.boot.context.properties.bind.Binder; +import org.springframework.boot.env.YamlPropertySourceLoader; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.core.env.StandardEnvironment; +import org.springframework.core.io.FileSystemResource; +import org.springframework.test.util.ReflectionTestUtils; + +/** + * Physical socket proof for authored-source-bound launch descriptor peer authorization. The + * descriptor producer is mocked; this does not exercise owner persistence or runtime activation. + */ +class AuthoredWorldLaunchDescriptorMtlsTest { + private static final String NAMESPACE = "test"; + private static final String GAME_SESSION_URI = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String WORLD_MANAGEMENT_URI = + "spiffe://firemud/ns/test/sa/world-management-service"; + private static final String RESOLVE_METHOD = + "gamedesign.v1.GameDesignService/ResolveLaunchDescriptor"; + private static final String READ_METHOD = "gamedesign.v1.GameDesignService/GetLaunchDescriptor"; + private static final Set DESCRIPTOR_METHODS = Set.of(RESOLVE_METHOD, READ_METHOD); + private static final Metadata.Key AUTHORIZATION = + Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER); + private static final UUID TENANT_ID = UUID.fromString("c7a1b80e-a5fa-4fc9-9fc4-cab3cbe44b21"); + private static final UUID SOURCE_OPERATION_ID = + UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID READ_REQUEST_ID = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final AtomicLong CERTIFICATE_SERIAL = new AtomicLong(1); + private static final AuthoredWorldLaunchDescriptorEvidence.Request BOUND_REQUEST = + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + "launch-request-17", + TENANT_ID, + "harbor-world", + SOURCE_OPERATION_ID, + "sha256:" + "a".repeat(64), + 17L, + true, + "requested-patch-2", + true, + 9L, + true, + 12L, + true, + "{\"requested\":true}"); + private static final AuthoredWorldLaunchDescriptorEvidence BOUND_EVIDENCE = + AuthoredWorldLaunchDescriptorEvidence.create( + BOUND_REQUEST, + "launch-descriptor-17", + 12L, + true, + "resolved-patch-2", + "{\"runtime\":true}", + "generation-revision-3", + 6L, + 29L, + "release-bundle:" + TENANT_ID + ":12:29", + true, + "remap-set-4"); + private static TestPki pki; + + private LaunchDescriptorService launchDescriptorService; + private Server server; + private AtomicReference responseMutation; + + @BeforeAll + static void generateEphemeralPki() throws Exception { + if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { + Security.addProvider(new BouncyCastleProvider()); + } + KeyPair caKeyPair = newRsaKeyPair(); + X500Name caName = new X500Name("CN=Authored Launch Test CA, O=FireMUD Test"); + X509Certificate caCertificate = + issueCertificate( + caName, caKeyPair.getPublic(), caName, caKeyPair.getPrivate(), true, null, false); + pki = + new TestPki( + caCertificate, + issueLeaf( + caName, + caKeyPair.getPrivate(), + "game-design-service", + "spiffe://firemud/ns/test/sa/game-design-service", + true), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "wrong-game-design-server-workload", + "spiffe://firemud/ns/test/sa/world-management-service", + true), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "wrong-game-design-server-namespace", + "spiffe://firemud/ns/other-test/sa/game-design-service", + true), + issueLeaf( + caName, caKeyPair.getPrivate(), "game-session-service", GAME_SESSION_URI, false), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "world-management-service", + WORLD_MANAGEMENT_URI, + false), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "account-service", + "spiffe://firemud/ns/test/sa/account-service", + false), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "cross-namespace-game-session-service", + "spiffe://firemud/ns/other-test/sa/game-session-service", + false), + issueLeaf(caName, caKeyPair.getPrivate(), "shared-workload-certificate", null, false)); + } + + @BeforeEach + void startPhysicalReceiver() throws Exception { + launchDescriptorService = Mockito.mock(LaunchDescriptorService.class); + responseMutation = new AtomicReference<>(ResponseMutation.NONE); + server = startReceiver(pki.serverCertificate()); + } + + private Server startReceiver(TestCertificate serverCertificate) throws Exception { + GameDesignGrpcService service = + new GameDesignGrpcService( + Mockito.mock(PingService.class), + Mockito.mock(RevisionService.class), + Mockito.mock(VersionService.class), + launchDescriptorService, + Mockito.mock(TemplateRemapSetService.class), + Mockito.mock(VersionAssetArtifactService.class), + Mockito.mock(SettingsAuthorityService.class), + Mockito.mock(GameAuthoredHelpTopicService.class), + new TemporalVersionPublishWorkflowMetadataResolver(Optional.empty(), Optional.empty()), + new SimpleMeterRegistry()); + ReflectionTestUtils.setField(service, "workloadNamespace", NAMESPACE); + + Set unauthenticatedMethods = publicMethods("application.yml"); + return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + serverCertificate.privateKey(), serverCertificate.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + service, + responseMutationInterceptor(responseMutation), + new AuthTokenInterceptor( + new JwtUtil("test-secret-key-test-secret-key-32-bytes", 60_000), + unauthenticatedMethods), + new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + @AfterEach + void stopPhysicalReceiver() throws Exception { + if (server != null) { + stopServer(server); + server = null; + } + } + + @Test + void exactGameSessionPeerResolvesAndEchoesTheFullCanonicalDescriptor() throws Exception { + when(launchDescriptorService.resolveLaunchDescriptor(any())).thenReturn(resolvedDescriptor()); + ManagedChannel channel = channel(pki.gameSessionCertificate(), false); + try { + ResolveLaunchDescriptorResponse response = + stub(channel).resolveLaunchDescriptor(resolveRequest()); + + assertThat(response.getError().getCode()).isEmpty(); + assertThat(response.getLaunchDescriptor()).isEqualTo(expectedProtoDescriptor()); + ArgumentCaptor requestCaptor = + ArgumentCaptor.forClass(AuthoredWorldLaunchDescriptorEvidence.Request.class); + verify(launchDescriptorService).resolveLaunchDescriptor(requestCaptor.capture()); + assertThat(requestCaptor.getValue()).isEqualTo(BOUND_REQUEST); + } finally { + stopChannel(channel); + } + } + + @Test + void gameSessionAndWorldPeersReadExactDescriptorAndEchoReadRequestIdentity() throws Exception { + when(launchDescriptorService.getLaunchDescriptor( + any(UUID.class), any(UUID.class), anyString(), anyString(), anyString(), anyString())) + .thenReturn(resolvedDescriptor()); + + for (TestCertificate certificate : + List.of(pki.gameSessionCertificate(), pki.worldManagementCertificate())) { + ManagedChannel channel = channel(certificate, false); + try { + GetLaunchDescriptorResponse response = stub(channel).getLaunchDescriptor(readRequest()); + + assertThat(response.getError().getCode()).isEmpty(); + assertThat(response.getRequestId()).isEqualTo(READ_REQUEST_ID.toString()); + assertThat(response.getLaunchDescriptor()).isEqualTo(expectedProtoDescriptor()); + } finally { + stopChannel(channel); + } + } + + verify(launchDescriptorService, Mockito.times(2)) + .getLaunchDescriptor( + READ_REQUEST_ID, + TENANT_ID, + BOUND_REQUEST.worldSlug(), + BOUND_REQUEST.controlPlaneRequestId(), + BOUND_EVIDENCE.requestDigest(), + BOUND_EVIDENCE.resultDigest()); + } + + @Test + void sharedClientResolvesAndReadsExactDescriptorOverPhysicalMtlsSocket(@TempDir Path directory) + throws Exception { + when(launchDescriptorService.resolveLaunchDescriptor(any())).thenReturn(resolvedDescriptor()); + when(launchDescriptorService.getLaunchDescriptor( + any(UUID.class), any(UUID.class), anyString(), anyString(), anyString(), anyString())) + .thenReturn(resolvedDescriptor()); + + AuthoredWorldLaunchDescriptorClient client = newSharedClient(directory, server); + try { + client.init(); + + AuthoredWorldLaunchDescriptorEvidence resolved = client.resolve(BOUND_REQUEST); + assertThat(resolved).isEqualTo(BOUND_EVIDENCE); + + AuthoredWorldLaunchDescriptorEvidence readBack = client.get(readClientRequest()); + assertThat(readBack).isEqualTo(BOUND_EVIDENCE); + + ArgumentCaptor requestCaptor = + ArgumentCaptor.forClass(AuthoredWorldLaunchDescriptorEvidence.Request.class); + verify(launchDescriptorService).resolveLaunchDescriptor(requestCaptor.capture()); + assertThat(requestCaptor.getValue()).isEqualTo(BOUND_REQUEST); + verify(launchDescriptorService) + .getLaunchDescriptor( + READ_REQUEST_ID, + TENANT_ID, + BOUND_REQUEST.worldSlug(), + BOUND_REQUEST.controlPlaneRequestId(), + BOUND_EVIDENCE.requestDigest(), + BOUND_EVIDENCE.resultDigest()); + } finally { + client.close(); + } + } + + @Test + void sharedClientRejectsWrongGameDesignServerWorkloadAndNamespaceBeforeReturningEvidence( + @TempDir Path directory) throws Exception { + when(launchDescriptorService.resolveLaunchDescriptor(any())).thenReturn(resolvedDescriptor()); + when(launchDescriptorService.getLaunchDescriptor( + any(UUID.class), any(UUID.class), anyString(), anyString(), anyString(), anyString())) + .thenReturn(resolvedDescriptor()); + + for (TestCertificate serverCertificate : + List.of(pki.wrongServerWorkloadCertificate(), pki.wrongServerNamespaceCertificate())) { + Server wrongIdentityServer = startReceiver(serverCertificate); + AuthoredWorldLaunchDescriptorClient client = + newSharedClient(directory.resolve(UUID.randomUUID().toString()), wrongIdentityServer); + try { + client.init(); + assertServerPeerRefused(() -> client.resolve(BOUND_REQUEST)); + assertServerPeerRefused(() -> client.get(readClientRequest())); + } finally { + client.close(); + stopServer(wrongIdentityServer); + } + } + } + + @Test + void sharedClientCodecRejectsChangedDescriptorReadEchoAndDigestOverPhysicalSocket( + @TempDir Path directory) throws Exception { + when(launchDescriptorService.resolveLaunchDescriptor(any())).thenReturn(resolvedDescriptor()); + when(launchDescriptorService.getLaunchDescriptor( + any(UUID.class), any(UUID.class), anyString(), anyString(), anyString(), anyString())) + .thenReturn(resolvedDescriptor()); + + AuthoredWorldLaunchDescriptorClient client = newSharedClient(directory, server); + try { + client.init(); + + responseMutation.set(ResponseMutation.CHANGE_DESCRIPTOR_DUPLICATE); + assertClientCodecRejected( + () -> client.resolve(BOUND_REQUEST), "Flat launch descriptor launchDescriptorId"); + + responseMutation.set(ResponseMutation.CHANGE_READ_REQUEST_ID); + assertClientCodecRejected( + () -> client.get(readClientRequest()), "read request ID echo changed"); + + responseMutation.set(ResponseMutation.CHANGE_RESULT_DIGEST); + assertClientCodecRejected( + () -> client.get(readClientRequest()), "Authored-world launch evidence is invalid"); + } finally { + client.close(); + } + } + + @Test + void worldPeerCannotResolveBeforeDescriptorProducerAccess() throws Exception { + ManagedChannel channel = channel(pki.worldManagementCertificate(), false); + try { + ResolveLaunchDescriptorResponse response = + stub(channel).resolveLaunchDescriptor(resolveRequest()); + assertThat(response.getError().getCode()).isEqualTo("PERMISSION_DENIED"); + } finally { + stopChannel(channel); + } + verifyNoInteractions(launchDescriptorService); + } + + @Test + void missingClientCertificateFailsWithTlsHandshakeEvidenceBeforeProducerAccess() + throws Exception { + ManagedChannel channel = channel(null, false); + try { + var stub = stub(channel); + assertTlsDenied(() -> stub.resolveLaunchDescriptor(resolveRequest()), RESOLVE_METHOD); + assertTlsDenied(() -> stub.getLaunchDescriptor(readRequest()), READ_METHOD); + } finally { + stopChannel(channel); + } + verifyNoInteractions(launchDescriptorService); + } + + @Test + void jwtOnlyCallerWithoutClientCertificateFailsWithTlsHandshakeEvidence() throws Exception { + ManagedChannel channel = channel(null, true); + try { + var stub = stub(channel); + assertTlsDenied(() -> stub.resolveLaunchDescriptor(resolveRequest()), RESOLVE_METHOD); + assertTlsDenied(() -> stub.getLaunchDescriptor(readRequest()), READ_METHOD); + } finally { + stopChannel(channel); + } + verifyNoInteractions(launchDescriptorService); + } + + @Test + void wrongServiceCertificateCannotResolveOrReadEvenWithBearerMetadata() throws Exception { + assertWrongPeerDenied(pki.wrongServiceCertificate()); + } + + @Test + void wrongNamespaceCertificateCannotResolveOrReadEvenWithBearerMetadata() throws Exception { + assertWrongPeerDenied(pki.wrongNamespaceCertificate()); + } + + @Test + void sharedCertificateWithoutWorkloadUriCannotResolveOrRead() throws Exception { + assertWrongPeerDenied(pki.noWorkloadUriCertificate()); + } + + @Test + void malformedAndUnknownClosedRequestsFailBeforeDescriptorProducerAccess() throws Exception { + ManagedChannel channel = channel(pki.gameSessionCertificate(), false); + ResolveLaunchDescriptorRequest malformed = + resolveRequest().toBuilder().setCanonicalTenantId("not-a-canonical-uuid").build(); + ResolveLaunchDescriptorRequest unknownField = + resolveRequest().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build(); + try { + assertThat(stub(channel).resolveLaunchDescriptor(malformed).getError().getCode()) + .isEqualTo("INVALID_ARGUMENT"); + assertThat(stub(channel).resolveLaunchDescriptor(unknownField).getError().getCode()) + .isEqualTo("INVALID_ARGUMENT"); + } finally { + stopChannel(channel); + } + verifyNoInteractions(launchDescriptorService); + } + + @Test + void bothProductionProfilesKeepOnlyExactLaunchDescriptorMethodsInGameDesignJwtBypass() + throws Exception { + for (String profile : List.of("application.yml", "application-prod.yml")) { + Set configuredMethods = publicMethods(profile); + Set gameDesignMethods = + configuredMethods.stream() + .filter(method -> method.startsWith("gamedesign.v1.GameDesignService/")) + .collect(java.util.stream.Collectors.toSet()); + assertThat(gameDesignMethods).containsExactlyInAnyOrderElementsOf(DESCRIPTOR_METHODS); + } + } + + private void assertWrongPeerDenied(TestCertificate certificate) throws Exception { + ManagedChannel channel = channel(certificate, true); + try { + GameDesignServiceGrpc.GameDesignServiceBlockingStub stub = stub(channel); + assertThat(stub.resolveLaunchDescriptor(resolveRequest()).getError().getCode()) + .isEqualTo("PERMISSION_DENIED"); + assertThat(stub.getLaunchDescriptor(readRequest()).getError().getCode()) + .isEqualTo("PERMISSION_DENIED"); + } finally { + stopChannel(channel); + } + verifyNoInteractions(launchDescriptorService); + } + + private static ServerInterceptor responseMutationInterceptor( + AtomicReference pendingMutation) { + return new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + ServerCall forwardingCall = + new SimpleForwardingServerCall<>(call) { + @Override + public void sendMessage(RespT message) { + super.sendMessage( + mutateResponse(message, pendingMutation.getAndSet(ResponseMutation.NONE))); + } + }; + return next.startCall(forwardingCall, headers); + } + }; + } + + @SuppressWarnings("unchecked") + private static Response mutateResponse(Response response, ResponseMutation mutation) { + if (mutation == ResponseMutation.NONE) { + return response; + } + if (mutation == ResponseMutation.CHANGE_DESCRIPTOR_DUPLICATE + && response instanceof ResolveLaunchDescriptorResponse resolve) { + var changedDescriptor = + resolve.getLaunchDescriptor().toBuilder() + .setLaunchDescriptorId("changed-flat-launch-descriptor-id") + .build(); + return (Response) resolve.toBuilder().setLaunchDescriptor(changedDescriptor).build(); + } + if (mutation == ResponseMutation.CHANGE_READ_REQUEST_ID + && response instanceof GetLaunchDescriptorResponse read) { + return (Response) + read.toBuilder().setRequestId("44444444-4444-4444-8444-444444444444").build(); + } + if (mutation == ResponseMutation.CHANGE_RESULT_DIGEST + && response instanceof GetLaunchDescriptorResponse read) { + var descriptor = read.getLaunchDescriptor(); + var changedBinding = + descriptor.getAuthoredWorldBinding().toBuilder() + .setResultDigest("sha256:" + "f".repeat(64)) + .build(); + var changedDescriptor = + descriptor.toBuilder().setAuthoredWorldBinding(changedBinding).build(); + return (Response) read.toBuilder().setLaunchDescriptor(changedDescriptor).build(); + } + throw new IllegalStateException("Response mutation does not match the physical RPC response"); + } + + private static void assertServerPeerRefused(Runnable call) { + Throwable failure = catchFailure(call); + assertThat(failure).isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); + } + + private static void assertClientCodecRejected(Runnable call, String expectedCauseMessage) { + Throwable failure = catchFailure(call); + assertThat(failure).isInstanceOf(IllegalStateException.class); + assertThat(failure.getCause()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(expectedCauseMessage); + } + + private static AuthoredWorldLaunchDescriptorClient newSharedClient( + Path directory, Server receiver) throws Exception { + Files.createDirectories(directory); + Path caCertificate = + writePem(directory.resolve("test-ca.crt"), "CERTIFICATE", pki.caCertificate().getEncoded()); + Path clientCertificate = + writePem( + directory.resolve("game-session-service.crt"), + "CERTIFICATE", + pki.gameSessionCertificate().certificate().getEncoded()); + Path clientPrivateKey = + writePem( + directory.resolve("game-session-service.key"), + "PRIVATE KEY", + pki.gameSessionCertificate().privateKey().getEncoded()); + + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(clientCertificate.toString()); + tls.setPrivateKey(clientPrivateKey.toString()); + tls.setCaCert(caCertificate.toString()); + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("localhost:" + receiver.getPort()); + return new AuthoredWorldLaunchDescriptorClient( + endpoints, tls, new GrpcChannelFactory(), NAMESPACE); + } + + private static Path writePem(Path path, String label, byte[] encoded) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(encoded); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + + private static void stopServer(Server server) throws InterruptedException { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + + private static void assertTlsDenied(Runnable call, String method) { + Throwable failure = catchFailure(call); + assertThat(failure) + .as( + "%s must fail with a client-certificate handshake rejection: %s", + method, diagnostics(failure)) + .isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(failure).getCode()) + .as("%s must be a TLS transport rejection, not a timeout: %s", method, diagnostics(failure)) + .isEqualTo(Status.Code.UNAVAILABLE); + assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)) + .as("%s cause chain must identify certificate rejection: %s", method, diagnostics(failure)) + .isTrue(); + } + + private static Set publicMethods(String resourceName) throws IOException { + ConfigurableEnvironment environment = new StandardEnvironment(); + environment + .getPropertySources() + .remove(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME); + environment + .getPropertySources() + .remove(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME); + for (var propertySource : + new YamlPropertySourceLoader() + .load(resourceName, new FileSystemResource("src/main/resources/" + resourceName))) { + environment.getPropertySources().addFirst(propertySource); + } + return Set.copyOf( + Binder.get(environment) + .bind("firemud.auth.grpc.public-methods", Bindable.listOf(String.class)) + .orElse(List.of())); + } + + private static ResolveLaunchDescriptorRequest resolveRequest() { + return ResolveLaunchDescriptorRequest.newBuilder() + .setCanonicalTenantId(BOUND_REQUEST.canonicalTenantId().toString()) + .setGameTemplateId(BOUND_REQUEST.gameTemplateId()) + .setControlPlaneRequestId(BOUND_REQUEST.controlPlaneRequestId()) + .setRequestedScriptPatchVersion(BOUND_REQUEST.requestedScriptPatchVersion()) + .setSourceVersionId(BOUND_REQUEST.sourceVersionId()) + .setTargetVersionId(BOUND_REQUEST.targetVersionId()) + .setRequestedRuntimeFlagsJson(BOUND_REQUEST.requestedRuntimeFlagsJson()) + .setWorldSlug(BOUND_REQUEST.worldSlug()) + .setAuthoredWorldSourceOperationId( + BOUND_REQUEST.authoredWorldSourceOperationId().toString()) + .setExpectedAuthoredWorldSourceEvidenceDigest( + BOUND_REQUEST.authoredWorldSourceEvidenceDigest()) + .build(); + } + + private static GetLaunchDescriptorRequest readRequest() { + return GetLaunchDescriptorRequest.newBuilder() + .setRequestId(READ_REQUEST_ID.toString()) + .setCanonicalTenantId(BOUND_REQUEST.canonicalTenantId().toString()) + .setWorldSlug(BOUND_REQUEST.worldSlug()) + .setControlPlaneRequestId(BOUND_REQUEST.controlPlaneRequestId()) + .setExpectedRequestDigest(BOUND_EVIDENCE.requestDigest()) + .setExpectedResultDigest(BOUND_EVIDENCE.resultDigest()) + .build(); + } + + private static AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest readClientRequest() { + return new AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest( + READ_REQUEST_ID, BOUND_REQUEST, BOUND_EVIDENCE.resultDigest()); + } + + private static ResolvedLaunchDescriptorDto resolvedDescriptor() { + return new ResolvedLaunchDescriptorDto( + BOUND_EVIDENCE.launchDescriptorId(), + BOUND_EVIDENCE.canonicalTenantId().toString(), + BOUND_EVIDENCE.gameTemplateId(), + BOUND_EVIDENCE.controlPlaneRequestId(), + BOUND_EVIDENCE.versionId(), + BOUND_EVIDENCE.scriptPatchVersion(), + BOUND_EVIDENCE.runtimeFlagsJson(), + BOUND_EVIDENCE.generationConfigRevision(), + BOUND_EVIDENCE.versionStateEpoch(), + BOUND_EVIDENCE.releaseBundleId(), + BOUND_EVIDENCE.publishedReleaseBundleRef(), + BOUND_EVIDENCE.remapSetId(), + BOUND_EVIDENCE); + } + + private static net.firedevops.firemud.gamedesign.v1.LaunchDescriptor expectedProtoDescriptor() { + return net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.newBuilder() + .setLaunchDescriptorId(BOUND_EVIDENCE.launchDescriptorId()) + .setCanonicalTenantId(BOUND_EVIDENCE.canonicalTenantId().toString()) + .setGameTemplateId(BOUND_EVIDENCE.gameTemplateId()) + .setControlPlaneRequestId(BOUND_EVIDENCE.controlPlaneRequestId()) + .setVersionId(BOUND_EVIDENCE.versionId()) + .setScriptPatchVersion(BOUND_EVIDENCE.scriptPatchVersion()) + .setRuntimeFlagsJson(BOUND_EVIDENCE.runtimeFlagsJson()) + .setGenerationConfigRevision(BOUND_EVIDENCE.generationConfigRevision()) + .setVersionStateEpoch(BOUND_EVIDENCE.versionStateEpoch()) + .setReleaseBundleId(BOUND_EVIDENCE.releaseBundleId()) + .setPublishedReleaseBundleRef(BOUND_EVIDENCE.publishedReleaseBundleRef()) + .setRemapSetId(BOUND_EVIDENCE.remapSetId()) + .setAuthoredWorldBinding(expectedProtoEvidence()) + .build(); + } + + private static net.firedevops.firemud.gamedesign.v1.AuthoredWorldLaunchDescriptorEvidence + expectedProtoEvidence() { + var builder = + net.firedevops.firemud.gamedesign.v1.AuthoredWorldLaunchDescriptorEvidence.newBuilder() + .setSchemaVersion(BOUND_EVIDENCE.schemaVersion()) + .setTargetNamespace(BOUND_EVIDENCE.targetNamespace()) + .setControlPlaneRequestId(BOUND_EVIDENCE.controlPlaneRequestId()) + .setCanonicalTenantId(BOUND_EVIDENCE.canonicalTenantId().toString()) + .setWorldSlug(BOUND_EVIDENCE.worldSlug()) + .setAuthoredWorldSourceOperationId( + BOUND_EVIDENCE.authoredWorldSourceOperationId().toString()) + .setAuthoredWorldSourceEvidenceDigest( + BOUND_EVIDENCE.authoredWorldSourceEvidenceDigest()) + .setGameTemplateId(BOUND_EVIDENCE.gameTemplateId()) + .setRequestDigest(BOUND_EVIDENCE.requestDigest()) + .setLaunchDescriptorId(BOUND_EVIDENCE.launchDescriptorId()) + .setVersionId(BOUND_EVIDENCE.versionId()) + .setRuntimeFlagsJson(BOUND_EVIDENCE.runtimeFlagsJson()) + .setGenerationConfigRevision(BOUND_EVIDENCE.generationConfigRevision()) + .setVersionStateEpoch(BOUND_EVIDENCE.versionStateEpoch()) + .setReleaseBundleId(BOUND_EVIDENCE.releaseBundleId()) + .setPublishedReleaseBundleRef(BOUND_EVIDENCE.publishedReleaseBundleRef()) + .setResultDigest(BOUND_EVIDENCE.resultDigest()); + if (BOUND_EVIDENCE.requestedScriptPatchVersionPresent()) { + builder.setRequestedScriptPatchVersion(BOUND_EVIDENCE.requestedScriptPatchVersion()); + } + if (BOUND_EVIDENCE.sourceVersionIdPresent()) { + builder.setSourceVersionId(BOUND_EVIDENCE.sourceVersionId()); + } + if (BOUND_EVIDENCE.targetVersionIdPresent()) { + builder.setTargetVersionId(BOUND_EVIDENCE.targetVersionId()); + } + if (BOUND_EVIDENCE.requestedRuntimeFlagsJsonPresent()) { + builder.setRequestedRuntimeFlagsJson(BOUND_EVIDENCE.requestedRuntimeFlagsJson()); + } + if (BOUND_EVIDENCE.scriptPatchVersionPresent()) { + builder.setScriptPatchVersion(BOUND_EVIDENCE.scriptPatchVersion()); + } + if (BOUND_EVIDENCE.remapSetIdPresent()) { + builder.setRemapSetId(BOUND_EVIDENCE.remapSetId()); + } + return builder.build(); + } + + private static GameDesignServiceGrpc.GameDesignServiceBlockingStub stub(ManagedChannel channel) { + return GameDesignServiceGrpc.newBlockingStub(channel).withDeadlineAfter(3, TimeUnit.SECONDS); + } + + private ManagedChannel channel(TestCertificate clientCertificate, boolean attachBearer) + throws Exception { + NettyChannelBuilder builder = + NettyChannelBuilder.forAddress(new InetSocketAddress("127.0.0.1", server.getPort())) + .sslContext(clientSslContext(clientCertificate)); + if (attachBearer) { + Metadata headers = new Metadata(); + headers.put(AUTHORIZATION, "Bearer header.payload.signature"); + builder.intercept(MetadataUtils.newAttachHeadersInterceptor(headers)); + } + return builder.build(); + } + + private static io.grpc.netty.shaded.io.netty.handler.ssl.SslContext clientSslContext( + TestCertificate clientCertificate) throws Exception { + var builder = GrpcSslContexts.forClient().trustManager(pki.caCertificate()); + if (clientCertificate != null) { + builder.keyManager(clientCertificate.privateKey(), clientCertificate.certificate()); + } + return builder.build(); + } + + private static void stopChannel(ManagedChannel channel) throws InterruptedException { + channel.shutdownNow(); + assertThat(channel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + + private static Throwable catchFailure(Runnable action) { + try { + action.run(); + return null; + } catch (Throwable throwable) { + return throwable; + } + } + + private static String diagnostics(Throwable throwable) { + if (throwable == null) { + return "RPC unexpectedly completed"; + } + StringBuilder result = new StringBuilder(); + for (Throwable current = throwable; current != null; current = current.getCause()) { + if (!result.isEmpty()) { + result.append(" <- "); + } + result.append(current.getClass().getName()).append(": ").append(current.getMessage()); + } + return result.toString(); + } + + private static TestCertificate issueLeaf( + X500Name caName, + PrivateKey caPrivateKey, + String commonName, + String workloadUri, + boolean serverCertificate) + throws Exception { + KeyPair keyPair = newRsaKeyPair(); + X500Name subject = new X500Name("CN=" + commonName + ", O=FireMUD Test"); + GeneralName[] subjectAltNames = + workloadUri == null + ? new GeneralName[] { + new GeneralName(GeneralName.dNSName, "localhost"), + new GeneralName(GeneralName.iPAddress, "127.0.0.1") + } + : new GeneralName[] { + new GeneralName(GeneralName.uniformResourceIdentifier, workloadUri), + new GeneralName(GeneralName.dNSName, "localhost"), + new GeneralName(GeneralName.iPAddress, "127.0.0.1") + }; + X509Certificate certificate = + issueCertificate( + subject, + keyPair.getPublic(), + caName, + caPrivateKey, + false, + new GeneralNames(subjectAltNames), + serverCertificate); + return new TestCertificate(keyPair.getPrivate(), certificate); + } + + private static X509Certificate issueCertificate( + X500Name subject, + java.security.PublicKey publicKey, + X500Name issuer, + PrivateKey issuerPrivateKey, + boolean ca, + GeneralNames subjectAltNames, + boolean serverCertificate) + throws Exception { + Instant now = Instant.now().minusSeconds(60); + JcaX509v3CertificateBuilder builder = + new JcaX509v3CertificateBuilder( + issuer, + BigInteger.valueOf(CERTIFICATE_SERIAL.getAndIncrement()), + Date.from(now), + Date.from(now.plusSeconds(60L * 60L * 24L * 14L)), + subject, + publicKey); + builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(ca)); + if (ca) { + builder.addExtension( + Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign)); + } else { + builder.addExtension( + Extension.keyUsage, + true, + new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); + builder.addExtension( + Extension.extendedKeyUsage, + false, + new ExtendedKeyUsage( + serverCertificate ? KeyPurposeId.id_kp_serverAuth : KeyPurposeId.id_kp_clientAuth)); + builder.addExtension(Extension.subjectAlternativeName, false, subjectAltNames); + } + return new JcaX509CertificateConverter() + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .getCertificate( + builder.build( + new JcaContentSignerBuilder("SHA256withRSA") + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .build(issuerPrivateKey))); + } + + private static KeyPair newRsaKeyPair() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + return generator.generateKeyPair(); + } + + private record TestCertificate(PrivateKey privateKey, X509Certificate certificate) {} + + private enum ResponseMutation { + NONE, + CHANGE_DESCRIPTOR_DUPLICATE, + CHANGE_READ_REQUEST_ID, + CHANGE_RESULT_DIGEST + } + + private record TestPki( + X509Certificate caCertificate, + TestCertificate serverCertificate, + TestCertificate wrongServerWorkloadCertificate, + TestCertificate wrongServerNamespaceCertificate, + TestCertificate gameSessionCertificate, + TestCertificate worldManagementCertificate, + TestCertificate wrongServiceCertificate, + TestCertificate wrongNamespaceCertificate, + TestCertificate noWorkloadUriCertificate) {} +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java index 6cdbaa103c..3319159b0e 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java @@ -3,15 +3,16 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import io.grpc.Context; import io.grpc.stub.StreamObserver; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; -import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; import net.firedevops.firemud.gamedesign.service.GameAuthoredHelpTopicService; import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; import net.firedevops.firemud.gamedesign.service.PingService; @@ -20,6 +21,8 @@ import net.firedevops.firemud.gamedesign.service.TemplateRemapSetService; import net.firedevops.firemud.gamedesign.service.VersionAssetArtifactService; import net.firedevops.firemud.gamedesign.service.VersionService; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorResponse; import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleRequest; import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleResponse; import net.firedevops.firemud.gamedesign.v1.ListVersionsRequest; @@ -29,6 +32,7 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; +import org.springframework.test.util.ReflectionTestUtils; class GameDesignGrpcServiceAuthTest { @AfterEach @@ -74,7 +78,7 @@ public void onCompleted() {} } @Test - void launchAttestationReadMethodsAllowInternalServiceIdentity() { + void launchDescriptorRejectsJwtOnlyInternalServiceIdentity() { VersionService versionService = Mockito.mock(VersionService.class); LaunchDescriptorService launchDescriptorService = Mockito.mock(LaunchDescriptorService.class); Mockito.when(versionService.getPublishedReleaseBundle("1", 7L)) @@ -93,13 +97,6 @@ void launchAttestationReadMethodsAllowInternalServiceIdentity() { false, null, java.time.LocalDateTime.parse("2026-04-14T12:00:00"))); - Mockito.when( - launchDescriptorService.resolveLaunchDescriptor( - "1", 9L, "cp-1", null, null, null, null)) - .thenReturn( - new ResolvedLaunchDescriptorDto( - "ld-1", "1", 9L, "cp-1", 7L, null, "{}", "genrev-1", 11L, 11L, "prb:1:7:11", null)); - GameDesignGrpcService service = new GameDesignGrpcService( Mockito.mock(PingService.class), @@ -112,6 +109,7 @@ void launchAttestationReadMethodsAllowInternalServiceIdentity() { Mockito.mock(GameAuthoredHelpTopicService.class), new TemporalVersionPublishWorkflowMetadataResolver(Optional.empty(), Optional.empty()), new SimpleMeterRegistry()); + ReflectionTestUtils.setField(service, "workloadNamespace", "test"); SessionContext.setContext(null, List.of(), Map.of(), true, "game-session-service", "gs-1"); @@ -134,9 +132,12 @@ public void onCompleted() {} AtomicReference descriptorRef = new AtomicReference<>(); service.resolveLaunchDescriptor( ResolveLaunchDescriptorRequest.newBuilder() - .setTenantId("1") + .setCanonicalTenantId("12345678-1234-4234-8234-123456789abc") .setGameTemplateId(9L) .setControlPlaneRequestId("cp-1") + .setWorldSlug("silver-march") + .setAuthoredWorldSourceOperationId("22345678-1234-4234-8234-123456789abc") + .setExpectedAuthoredWorldSourceEvidenceDigest("sha256:" + "a".repeat(64)) .build(), new StreamObserver<>() { @Override @@ -155,7 +156,132 @@ public void onCompleted() {} assertEquals("", bundleRef.get().getError().getCode()); assertEquals(11L, bundleRef.get().getBundle().getId()); assertNotNull(descriptorRef.get()); - assertEquals("", descriptorRef.get().getError().getCode()); - assertEquals("ld-1", descriptorRef.get().getLaunchDescriptor().getLaunchDescriptorId()); + assertEquals("PERMISSION_DENIED", descriptorRef.get().getError().getCode()); + Mockito.verifyNoInteractions(launchDescriptorService); + } + + @Test + void + launchDescriptorResolveRejectsMissingWrongWorkloadAndWrongNamespacePeersBeforeServiceAccess() { + LaunchDescriptorService launchDescriptorService = Mockito.mock(LaunchDescriptorService.class); + GameDesignGrpcService service = + new GameDesignGrpcService( + Mockito.mock(PingService.class), + Mockito.mock(RevisionService.class), + Mockito.mock(VersionService.class), + launchDescriptorService, + Mockito.mock(TemplateRemapSetService.class), + Mockito.mock(VersionAssetArtifactService.class), + Mockito.mock(SettingsAuthorityService.class), + Mockito.mock(GameAuthoredHelpTopicService.class), + new TemporalVersionPublishWorkflowMetadataResolver(Optional.empty(), Optional.empty()), + new SimpleMeterRegistry()); + ReflectionTestUtils.setField(service, "workloadNamespace", "test"); + SessionContext.setContext(null, List.of(), Map.of(), true, "game-session-service", "gs-1"); + + assertEquals("PERMISSION_DENIED", resolve(service, null).getError().getCode()); + assertEquals( + "PERMISSION_DENIED", + resolve(service, "spiffe://firemud/ns/test/sa/world-management-service") + .getError() + .getCode()); + assertEquals( + "PERMISSION_DENIED", + resolve(service, "spiffe://firemud/ns/other/sa/game-session-service").getError().getCode()); + Mockito.verifyNoInteractions(launchDescriptorService); + } + + @Test + void launchDescriptorReadRejectsWrongWorkloadAndNamespacePeersBeforeServiceAccess() { + LaunchDescriptorService launchDescriptorService = Mockito.mock(LaunchDescriptorService.class); + GameDesignGrpcService service = + new GameDesignGrpcService( + Mockito.mock(PingService.class), + Mockito.mock(RevisionService.class), + Mockito.mock(VersionService.class), + launchDescriptorService, + Mockito.mock(TemplateRemapSetService.class), + Mockito.mock(VersionAssetArtifactService.class), + Mockito.mock(SettingsAuthorityService.class), + Mockito.mock(GameAuthoredHelpTopicService.class), + new TemporalVersionPublishWorkflowMetadataResolver(Optional.empty(), Optional.empty()), + new SimpleMeterRegistry()); + ReflectionTestUtils.setField(service, "workloadNamespace", "test"); + SessionContext.setContext(null, List.of(), Map.of(), true, "world-management-service", "wms-1"); + + assertEquals( + "PERMISSION_DENIED", + readDescriptor(service, "spiffe://firemud/ns/test/sa/game-design-service") + .getError() + .getCode()); + assertEquals( + "PERMISSION_DENIED", + readDescriptor(service, "spiffe://firemud/ns/other/sa/world-management-service") + .getError() + .getCode()); + Mockito.verifyNoInteractions(launchDescriptorService); + } + + private ResolveLaunchDescriptorResponse resolve(GameDesignGrpcService service, String peerUri) { + AtomicReference response = new AtomicReference<>(); + Runnable call = + () -> + service.resolveLaunchDescriptor( + ResolveLaunchDescriptorRequest.newBuilder() + .setCanonicalTenantId("12345678-1234-4234-8234-123456789abc") + .setGameTemplateId(9L) + .setControlPlaneRequestId("cp-auth") + .setWorldSlug("silver-march") + .setAuthoredWorldSourceOperationId("22345678-1234-4234-8234-123456789abc") + .setExpectedAuthoredWorldSourceEvidenceDigest("sha256:" + "a".repeat(64)) + .build(), + observerFor(response)); + runAsPeer(peerUri, call); + return response.get(); + } + + private GetLaunchDescriptorResponse readDescriptor( + GameDesignGrpcService service, String peerUri) { + AtomicReference response = new AtomicReference<>(); + Runnable call = + () -> + service.getLaunchDescriptor( + GetLaunchDescriptorRequest.newBuilder() + .setRequestId("32345678-1234-4234-8234-123456789abc") + .setCanonicalTenantId("12345678-1234-4234-8234-123456789abc") + .setWorldSlug("silver-march") + .setControlPlaneRequestId("cp-auth") + .setExpectedRequestDigest("sha256:" + "a".repeat(64)) + .setExpectedResultDigest("sha256:" + "b".repeat(64)) + .build(), + observerFor(response)); + runAsPeer(peerUri, call); + return response.get(); + } + + private void runAsPeer(String peerUri, Runnable call) { + if (peerUri == null) { + call.run(); + return; + } + GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(peerUri).orElseThrow(); + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(call); + } + + private static StreamObserver observerFor(AtomicReference ref) { + return new StreamObserver<>() { + @Override + public void onNext(T value) { + ref.set(value); + } + + @Override + public void onError(Throwable t) { + throw new AssertionError(t); + } + + @Override + public void onCompleted() {} + }; } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java index 0721e9523c..26852a5543 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java @@ -2,12 +2,17 @@ import static org.junit.jupiter.api.Assertions.assertEquals; +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; import io.grpc.stub.StreamObserver; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.time.LocalDateTime; import java.util.List; import java.util.Optional; +import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.AdminRoleGuard; import net.firedevops.firemud.gamedesign.dto.AppliedWorldDesignMutationDto; import net.firedevops.firemud.gamedesign.dto.DesignControlPlaneDigestDto; @@ -40,6 +45,8 @@ import net.firedevops.firemud.gamedesign.v1.CreateTemplateRemapSetResponse; import net.firedevops.firemud.gamedesign.v1.GetDesignControlPlaneDigestRequest; import net.firedevops.firemud.gamedesign.v1.GetDesignControlPlaneDigestResponse; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorResponse; import net.firedevops.firemud.gamedesign.v1.GetPublishedPluginVersionRequest; import net.firedevops.firemud.gamedesign.v1.GetPublishedPluginVersionResponse; import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleRequest; @@ -81,6 +88,7 @@ import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; +import org.springframework.test.util.ReflectionTestUtils; class GameDesignGrpcServiceTest { private final PingService pingService = Mockito.mock(PingService.class); @@ -999,122 +1007,135 @@ void getPublishedReleaseBundleRejectsUnsupportedSchema() { @Test void resolveLaunchDescriptorReturnsDeterministicDescriptor() { - Mockito.when( - launchDescriptorService.resolveLaunchDescriptor( - "tenant-1", 9L, "cp-1", null, null, null, null)) - .thenReturn( - new ResolvedLaunchDescriptorDto( - "ld-1", - "tenant-1", - 9L, - "cp-1", - 7L, - "patch-1", - "{}", - "genrev-1", - 11L, - 11L, - "prb:tenant-1:7:11", - "")); + AuthoredWorldLaunchDescriptorEvidence.Request request = launchRequest("cp-1"); + AuthoredWorldLaunchDescriptorEvidence evidence = launchEvidence(request); + Mockito.when(launchDescriptorService.resolveLaunchDescriptor(Mockito.any())) + .thenReturn(launchDto(evidence)); AtomicReference ref = new AtomicReference<>(); - try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { - service.resolveLaunchDescriptor( - ResolveLaunchDescriptorRequest.newBuilder() - .setTenantId("tenant-1") - .setGameTemplateId(9L) - .setControlPlaneRequestId("cp-1") - .build(), - new StreamObserver<>() { - @Override - public void onNext(ResolveLaunchDescriptorResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) { - throw new AssertionError(t); - } - - @Override - public void onCompleted() {} - }); - } + underLaunchPeer( + "game-session-service", + () -> service.resolveLaunchDescriptor(resolveRequest("cp-1"), observerFor(ref))); assertEquals("ld-1", ref.get().getLaunchDescriptor().getLaunchDescriptorId()); assertEquals("genrev-1", ref.get().getLaunchDescriptor().getGenerationConfigRevision()); + assertEquals( + evidence.resultDigest(), + ref.get().getLaunchDescriptor().getAuthoredWorldBinding().getResultDigest()); + Mockito.verify(launchDescriptorService).resolveLaunchDescriptor(request); } @Test void resolveLaunchDescriptorSurfacesTypedReleaseBundleNotFoundError() { - Mockito.when( - launchDescriptorService.resolveLaunchDescriptor( - "tenant-1", 9L, "cp-2", null, null, null, null)) + Mockito.when(launchDescriptorService.resolveLaunchDescriptor(Mockito.any())) .thenThrow( new IllegalArgumentException( "RELEASE_BUNDLE_NOT_FOUND: no published release bundle for the resolved version")); AtomicReference ref = new AtomicReference<>(); - try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { - service.resolveLaunchDescriptor( - ResolveLaunchDescriptorRequest.newBuilder() - .setTenantId("tenant-1") - .setGameTemplateId(9L) - .setControlPlaneRequestId("cp-2") - .build(), - new StreamObserver<>() { - @Override - public void onNext(ResolveLaunchDescriptorResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) { - throw new AssertionError(t); - } - - @Override - public void onCompleted() {} - }); - } + underLaunchPeer( + "game-session-service", + () -> service.resolveLaunchDescriptor(resolveRequest("cp-2"), observerFor(ref))); assertEquals("RELEASE_BUNDLE_NOT_FOUND", ref.get().getError().getCode()); } @Test void resolveLaunchDescriptorSurfacesTypedRemapRequiredError() { - Mockito.when( - launchDescriptorService.resolveLaunchDescriptor( - "tenant-1", 9L, "cp-3", null, null, null, null)) + Mockito.when(launchDescriptorService.resolveLaunchDescriptor(Mockito.any())) .thenThrow( new IllegalArgumentException( "LAUNCH_REMAP_REQUIRED: replacement-instance launch requires an approved remapSetId")); AtomicReference ref = new AtomicReference<>(); - try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { - service.resolveLaunchDescriptor( - ResolveLaunchDescriptorRequest.newBuilder() - .setTenantId("tenant-1") - .setGameTemplateId(9L) - .setControlPlaneRequestId("cp-3") - .build(), - new StreamObserver<>() { - @Override - public void onNext(ResolveLaunchDescriptorResponse value) { - ref.set(value); - } + underLaunchPeer( + "game-session-service", + () -> service.resolveLaunchDescriptor(resolveRequest("cp-3"), observerFor(ref))); - @Override - public void onError(Throwable t) { - throw new AssertionError(t); - } + assertEquals("LAUNCH_REMAP_REQUIRED", ref.get().getError().getCode()); + } - @Override - public void onCompleted() {} - }); - } + @Test + void getLaunchDescriptorReturnsExactBoundReadback() { + AuthoredWorldLaunchDescriptorEvidence.Request request = launchRequest("cp-read"); + AuthoredWorldLaunchDescriptorEvidence evidence = launchEvidence(request); + Mockito.when( + launchDescriptorService.getLaunchDescriptor( + Mockito.eq(UUID.fromString("32345678-1234-4234-8234-123456789abc")), + Mockito.eq(UUID.fromString("12345678-1234-4234-8234-123456789abc")), + Mockito.eq("silver-march"), + Mockito.eq("cp-read"), + Mockito.eq(evidence.requestDigest()), + Mockito.eq(evidence.resultDigest()))) + .thenReturn(launchDto(evidence)); + + AtomicReference ref = new AtomicReference<>(); + var readRequest = + GetLaunchDescriptorRequest.newBuilder() + .setRequestId("32345678-1234-4234-8234-123456789abc") + .setCanonicalTenantId("12345678-1234-4234-8234-123456789abc") + .setWorldSlug("silver-march") + .setControlPlaneRequestId("cp-read") + .setExpectedRequestDigest(evidence.requestDigest()) + .setExpectedResultDigest(evidence.resultDigest()) + .build(); + underLaunchPeer( + "world-management-service", + () -> service.getLaunchDescriptor(readRequest, observerFor(ref))); + + assertEquals("32345678-1234-4234-8234-123456789abc", ref.get().getRequestId()); + assertEquals("ld-1", ref.get().getLaunchDescriptor().getLaunchDescriptorId()); + assertEquals( + evidence.resultDigest(), + ref.get().getLaunchDescriptor().getAuthoredWorldBinding().getResultDigest()); + Mockito.verify(launchDescriptorService) + .getLaunchDescriptor( + UUID.fromString("32345678-1234-4234-8234-123456789abc"), + UUID.fromString("12345678-1234-4234-8234-123456789abc"), + "silver-march", + "cp-read", + evidence.requestDigest(), + evidence.resultDigest()); + } - assertEquals("LAUNCH_REMAP_REQUIRED", ref.get().getError().getCode()); + @Test + void resolveLaunchDescriptorRejectsUnknownFieldsBeforeOwnerRead() { + AtomicReference ref = new AtomicReference<>(); + var request = + resolveRequest("cp-unknown").toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build(); + underLaunchPeer( + "game-session-service", () -> service.resolveLaunchDescriptor(request, observerFor(ref))); + + assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); + Mockito.verifyNoInteractions(launchDescriptorService); + } + + @Test + void getLaunchDescriptorRejectsUnknownFieldsBeforeOwnerRead() { + AtomicReference ref = new AtomicReference<>(); + var request = + GetLaunchDescriptorRequest.newBuilder() + .setRequestId("32345678-1234-4234-8234-123456789abc") + .setCanonicalTenantId("12345678-1234-4234-8234-123456789abc") + .setWorldSlug("silver-march") + .setControlPlaneRequestId("cp-read") + .setExpectedRequestDigest("sha256:" + "a".repeat(64)) + .setExpectedResultDigest("sha256:" + "b".repeat(64)) + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build(); + underLaunchPeer( + "game-session-service", () -> service.getLaunchDescriptor(request, observerFor(ref))); + + assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); + Mockito.verifyNoInteractions(launchDescriptorService); } @Test @@ -1381,6 +1402,78 @@ public void onCompleted() {} assertEquals("wf-1", ref.get().getArtifactState().getLastWorkflowId()); } + private void underLaunchPeer(String serviceName, Runnable operation) { + ReflectionTestUtils.setField(service, "workloadNamespace", "test"); + GrpcPeerIdentity peer = + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/" + serviceName).orElseThrow(); + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(operation); + } + + private AuthoredWorldLaunchDescriptorEvidence.Request launchRequest( + String controlPlaneRequestId) { + return new AuthoredWorldLaunchDescriptorEvidence.Request( + "test", + controlPlaneRequestId, + UUID.fromString("12345678-1234-4234-8234-123456789abc"), + "silver-march", + UUID.fromString("22345678-1234-4234-8234-123456789abc"), + "sha256:" + "a".repeat(64), + 9L, + false, + null, + false, + null, + false, + null, + false, + null); + } + + private AuthoredWorldLaunchDescriptorEvidence launchEvidence( + AuthoredWorldLaunchDescriptorEvidence.Request request) { + return AuthoredWorldLaunchDescriptorEvidence.create( + request, + "ld-1", + 7L, + false, + null, + "{}", + "genrev-1", + 11L, + 11L, + "release-bundle:" + request.canonicalTenantId() + ":7:11", + false, + null); + } + + private ResolvedLaunchDescriptorDto launchDto(AuthoredWorldLaunchDescriptorEvidence evidence) { + return new ResolvedLaunchDescriptorDto( + evidence.launchDescriptorId(), + evidence.canonicalTenantId().toString(), + evidence.gameTemplateId(), + evidence.controlPlaneRequestId(), + evidence.versionId(), + evidence.scriptPatchVersion(), + evidence.runtimeFlagsJson(), + evidence.generationConfigRevision(), + evidence.versionStateEpoch(), + evidence.releaseBundleId(), + evidence.publishedReleaseBundleRef(), + evidence.remapSetId(), + evidence); + } + + private ResolveLaunchDescriptorRequest resolveRequest(String controlPlaneRequestId) { + return ResolveLaunchDescriptorRequest.newBuilder() + .setCanonicalTenantId("12345678-1234-4234-8234-123456789abc") + .setGameTemplateId(9L) + .setControlPlaneRequestId(controlPlaneRequestId) + .setWorldSlug("silver-march") + .setAuthoredWorldSourceOperationId("22345678-1234-4234-8234-123456789abc") + .setExpectedAuthoredWorldSourceEvidenceDigest("sha256:" + "a".repeat(64)) + .build(); + } + private static StreamObserver observerFor(AtomicReference ref) { return new GenericObserver<>(ref); } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java index 6ebb3311b0..7fbcdd9f41 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java @@ -1,14 +1,23 @@ package net.firedevops.firemud.gamedesign.service.impl; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.time.LocalDateTime; import java.util.List; import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; import net.firedevops.firemud.gamedesign.dto.TemplateRemapSetDto; import net.firedevops.firemud.gamedesign.entity.LaunchDescriptor; @@ -16,6 +25,7 @@ import net.firedevops.firemud.gamedesign.model.TemplateReferencePhase; import net.firedevops.firemud.gamedesign.model.TemplateRemapSetStatus; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; import net.firedevops.firemud.gamedesign.repository.GameTemplateLaunchConfigView; import net.firedevops.firemud.gamedesign.repository.GameTemplateRepository; import net.firedevops.firemud.gamedesign.repository.LaunchDescriptorRepository; @@ -25,21 +35,37 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; +import org.mockito.Mockito; import org.mockito.MockitoAnnotations; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.test.util.ReflectionTestUtils; import tools.jackson.databind.ObjectMapper; class LaunchDescriptorServiceImplTest { + private static final String NAMESPACE = "test"; + private static final UUID CANONICAL_TENANT_ID = + UUID.fromString("12345678-1234-4234-8234-123456789abc"); + private static final UUID SOURCE_OPERATION_ID = + UUID.fromString("22345678-1234-4234-8234-123456789abc"); + private static final UUID SOURCE_REGISTRATION_ID = + UUID.fromString("32345678-1234-4234-8234-123456789abc"); + private static final String WORLD_SLUG = "silver-march"; + private static final String PRIVATE_SOURCE_TENANT_KEY = "game-owner-key-901"; + @Mock private GameTemplateRepository gameTemplateRepository; @Mock private LaunchDescriptorRepository launchDescriptorRepository; @Mock private VersionRepository versionRepository; @Mock private PublishedReleaseBundleService publishedReleaseBundleService; @Mock private TemplateRemapSetService templateRemapSetService; + @Mock private GameAuthoredWorldSourceRepository authoredWorldSourceRepository; private LaunchDescriptorServiceImpl service; @BeforeEach void setUp() { MockitoAnnotations.openMocks(this); + when(launchDescriptorRepository.insertImmutable(any(LaunchDescriptor.class))) + .thenAnswer(invocation -> invocation.getArgument(0)); service = new LaunchDescriptorServiceImpl( gameTemplateRepository, @@ -47,209 +73,386 @@ void setUp() { versionRepository, publishedReleaseBundleService, templateRemapSetService, + authoredWorldSourceRepository, new ObjectMapper()); + ReflectionTestUtils.setField(service, "workloadNamespace", NAMESPACE); } @Test - void resolveLaunchDescriptorPersistsDeterministicDescriptor() { - GameTemplateLaunchConfigView template = - org.mockito.Mockito.mock(GameTemplateLaunchConfigView.class); - when(template.getId()).thenReturn(9L); - when(template.getTenantId()).thenReturn("tenant-1"); - when(template.getDefaultVersionId()).thenReturn(7L); - when(template.getDefaultScriptPatchVersion()).thenReturn(null); - when(template.getDefaultRuntimeFlagsJson()).thenReturn("{}"); - when(template.getTemplateReferencePhase()).thenReturn(TemplateReferencePhase.ENFORCED); - when(gameTemplateRepository.findLaunchConfigByTenantIdAndId("tenant-1", 9L)) - .thenReturn(Optional.of(template)); - when(launchDescriptorRepository.findByTenantIdAndGameTemplateIdAndControlPlaneRequestId( - "tenant-1", 9L, "cp-1")) + void resolveLaunchDescriptorPersistsCanonicalBindingAndResolvedRelease() { + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-1", 9L); + stubSuccessfulLaunch(request, 7L, 11L); + AtomicReference inserted = new AtomicReference<>(); + when(launchDescriptorRepository.insertImmutable(any(LaunchDescriptor.class))) + .thenAnswer( + invocation -> { + LaunchDescriptor descriptor = invocation.getArgument(0); + inserted.set(descriptor); + return descriptor; + }); + + var resolved = service.resolveLaunchDescriptor(request); + + assertEquals(CANONICAL_TENANT_ID.toString(), resolved.canonicalTenantId()); + assertEquals(9L, resolved.gameTemplateId()); + assertEquals(7L, resolved.versionId()); + assertEquals("genrev-1", resolved.generationConfigRevision()); + assertEquals(17L, resolved.versionStateEpoch()); + assertEquals(11L, resolved.releaseBundleId()); + assertEquals( + "release-bundle:" + CANONICAL_TENANT_ID + ":7:11", resolved.publishedReleaseBundleRef()); + assertNotNull(resolved.authoredWorldBinding()); + assertEquals(request.requestDigest(), resolved.authoredWorldBinding().requestDigest()); + assertEquals( + PRIVATE_SOURCE_TENANT_KEY, + inserted.get().getTenantId(), + "The private source key remains owner-local and is not the canonical tenant UUID"); + assertEquals(CANONICAL_TENANT_ID.toString(), inserted.get().getCanonicalTenantId()); + verify(authoredWorldSourceRepository) + .read(SOURCE_OPERATION_ID, CANONICAL_TENANT_ID, WORLD_SLUG, NAMESPACE); + verify(gameTemplateRepository).findLaunchConfigByTenantIdAndId(PRIVATE_SOURCE_TENANT_KEY, 9L); + verify(gameTemplateRepository, never()) + .findLaunchConfigByTenantIdAndId(CANONICAL_TENANT_ID.toString(), 9L); + } + + @Test + void exactRetryReturnsStoredResultWithoutReadingChangedDefaultsVersionOrRelease() { + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-retry", 9L); + GameTemplateLaunchConfigView template = stubTemplate(request, 7L, null); + stubVersion(7L, VersionLifecycleState.PUBLISHED, 17L, null); + stubBundle(7L, 11L, "v1"); + AuthoredWorldSourceEvidence source = sourceEvidence(WORLD_SLUG); + stubSource(request, source); + AtomicReference stored = new AtomicReference<>(); + when(launchDescriptorRepository.findBoundByRequest(NAMESPACE, CANONICAL_TENANT_ID, "cp-retry")) + .thenAnswer(invocation -> Optional.ofNullable(stored.get())); + when(launchDescriptorRepository.findByPrivateRequest(PRIVATE_SOURCE_TENANT_KEY, "cp-retry")) .thenReturn(Optional.empty()); - Version version = new Version(); - version.setId(7L); - version.setTenantId("tenant-1"); - version.setVersionNumber(8); - version.setVersionState(VersionLifecycleState.PUBLISHED); - version.setVersionStateEpoch(17L); - version.setUpdatedAt(LocalDateTime.now()); - when(versionRepository.findById(7L)).thenReturn(Optional.of(version)); - when(publishedReleaseBundleService.getPublishedReleaseBundle("tenant-1", 7L)) - .thenReturn( - new PublishedReleaseBundleDto( - 11L, - "tenant-1", - 7L, - 8, - "v1", - "workflow-1", - "hash-1", - List.of("manifest.json"), - List.of(), - "genrev-1", - false, - null, - LocalDateTime.now())); - when(launchDescriptorRepository.save(any(LaunchDescriptor.class))) + when(launchDescriptorRepository.insertImmutable(any(LaunchDescriptor.class))) + .thenAnswer( + invocation -> { + LaunchDescriptor descriptor = invocation.getArgument(0); + stored.set(descriptor); + return descriptor; + }); + + var first = service.resolveLaunchDescriptor(request); + when(template.getDefaultVersionId()).thenReturn(8L); + when(versionRepository.findById(8L)).thenReturn(Optional.empty()); + when(publishedReleaseBundleService.getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 8L)) + .thenThrow(new PublishedReleaseBundleNotFoundException(PRIVATE_SOURCE_TENANT_KEY, 8L)); + + var retry = service.resolveLaunchDescriptor(request); + + assertEquals(first, retry); + assertEquals(7L, retry.versionId()); + verify(gameTemplateRepository, times(1)) + .findLaunchConfigByTenantIdAndId(PRIVATE_SOURCE_TENANT_KEY, 9L); + verify(template, times(1)).getDefaultVersionId(); + verify(versionRepository, times(1)).findById(7L); + verify(versionRepository, never()).findById(8L); + verify(publishedReleaseBundleService, times(1)) + .getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 7L); + verify(publishedReleaseBundleService, never()) + .getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 8L); + verify(launchDescriptorRepository, times(1)).insertImmutable(any(LaunchDescriptor.class)); + } + + @Test + void changedSourceScopeTemplateOrRequestCannotReplaceOriginalDescriptor() { + AuthoredWorldLaunchDescriptorEvidence.Request original = request("cp-conflict", 9L); + stubSuccessfulLaunch(original, 7L, 11L); + LaunchDescriptor stored = descriptorFor(original, 7L, 11L); + when(launchDescriptorRepository.findBoundByRequest( + NAMESPACE, CANONICAL_TENANT_ID, "cp-conflict")) + .thenReturn(Optional.of(stored)); + when(launchDescriptorRepository.insertImmutable(any(LaunchDescriptor.class))) .thenAnswer(invocation -> invocation.getArgument(0)); - var descriptor = - service.resolveLaunchDescriptor("tenant-1", 9L, "cp-1", null, null, null, null); + AuthoredWorldLaunchDescriptorEvidence.Request changedTemplate = request("cp-conflict", 10L); + IllegalArgumentException templateConflict = + assertThrows( + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(changedTemplate)); + assertEquals( + "LAUNCH_DESCRIPTOR_CONFLICT: control-plane request identity was reused with changed input", + templateConflict.getMessage()); + + AuthoredWorldLaunchDescriptorEvidence.Request changedRequest = + request("cp-conflict", 9L, true, "other-patch"); + IllegalArgumentException requestConflict = + assertThrows( + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(changedRequest)); + assertEquals( + "LAUNCH_DESCRIPTOR_CONFLICT: control-plane request identity was reused with changed input", + requestConflict.getMessage()); - assertEquals("tenant-1", descriptor.tenantId()); - assertEquals(7L, descriptor.versionId()); - assertEquals("genrev-1", descriptor.generationConfigRevision()); - assertEquals(17L, descriptor.versionStateEpoch()); - assertEquals(11L, descriptor.releaseBundleId()); + UUID otherOperation = UUID.fromString("42345678-1234-4234-8234-123456789abc"); + AuthoredWorldLaunchDescriptorEvidence.Request changedSource = + request("cp-conflict", 9L, otherOperation, WORLD_SLUG, CANONICAL_TENANT_ID); + when(authoredWorldSourceRepository.read( + otherOperation, CANONICAL_TENANT_ID, WORLD_SLUG, NAMESPACE)) + .thenReturn(Optional.empty()); + IllegalArgumentException sourceConflict = + assertThrows( + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(changedSource)); + assertEquals( + "LAUNCH_DESCRIPTOR_CONFLICT: control-plane request identity was reused with changed input", + sourceConflict.getMessage()); + + UUID otherCanonicalTenant = UUID.fromString("52345678-1234-4234-8234-123456789abc"); + AuthoredWorldLaunchDescriptorEvidence.Request changedTenantScope = + request("cp-conflict", 9L, SOURCE_OPERATION_ID, WORLD_SLUG, otherCanonicalTenant); + when(authoredWorldSourceRepository.read( + SOURCE_OPERATION_ID, otherCanonicalTenant, WORLD_SLUG, NAMESPACE)) + .thenReturn(Optional.empty()); + IllegalArgumentException scopeConflict = + assertThrows( + IllegalArgumentException.class, + () -> service.resolveLaunchDescriptor(changedTenantScope)); + assertEquals( + "AUTHORED_WORLD_SOURCE_NOT_FOUND: exact committed source evidence is missing", + scopeConflict.getMessage()); + + AuthoredWorldLaunchDescriptorEvidence.Request changedWorldScope = + request("cp-conflict", 9L, SOURCE_OPERATION_ID, "other-world", CANONICAL_TENANT_ID); + when(authoredWorldSourceRepository.read( + SOURCE_OPERATION_ID, CANONICAL_TENANT_ID, "other-world", NAMESPACE)) + .thenReturn(Optional.empty()); + IllegalArgumentException worldConflict = + assertThrows( + IllegalArgumentException.class, + () -> service.resolveLaunchDescriptor(changedWorldScope)); + assertEquals( + "LAUNCH_DESCRIPTOR_CONFLICT: control-plane request identity was reused with changed input", + worldConflict.getMessage()); + verify(launchDescriptorRepository, never()).insertImmutable(any(LaunchDescriptor.class)); } @Test - void selectedPatchWithoutExactPublicationAndReadinessEvidenceCannotResolve() { - GameTemplateLaunchConfigView template = - org.mockito.Mockito.mock(GameTemplateLaunchConfigView.class); - when(template.getDefaultVersionId()).thenReturn(7L); - when(template.getDefaultScriptPatchVersion()).thenReturn("patch-1"); - when(template.getTemplateReferencePhase()).thenReturn(TemplateReferencePhase.ENFORCED); - when(gameTemplateRepository.findLaunchConfigByTenantIdAndId("tenant-1", 9L)) - .thenReturn(Optional.of(template)); - Version version = new Version(); - version.setId(7L); - version.setTenantId("tenant-1"); - version.setVersionState(VersionLifecycleState.PUBLISHED); - when(versionRepository.findById(7L)).thenReturn(Optional.of(version)); + void exactReadbackReturnsOriginalEvidenceAndRejectsDigestOrScopeSubstitution() { + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-read", 9L); + stubSuccessfulLaunch(request, 7L, 11L); + LaunchDescriptor stored = descriptorFor(request, 7L, 11L); + when(launchDescriptorRepository.findBoundByRequest(NAMESPACE, CANONICAL_TENANT_ID, "cp-read")) + .thenReturn(Optional.of(stored)); + when(launchDescriptorRepository.insertImmutable(any(LaunchDescriptor.class))) + .thenAnswer(invocation -> invocation.getArgument(0)); + var original = service.resolveLaunchDescriptor(request); - IllegalArgumentException thrown = + var readback = + service.getLaunchDescriptor( + UUID.fromString("62345678-1234-4234-8234-123456789abc"), + CANONICAL_TENANT_ID, + WORLD_SLUG, + "cp-read", + original.authoredWorldBinding().requestDigest(), + original.authoredWorldBinding().resultDigest()); + + assertEquals(original, readback); + IllegalArgumentException changedRequestDigest = assertThrows( IllegalArgumentException.class, () -> - service.resolveLaunchDescriptor( - "tenant-1", 9L, "cp-patch", null, null, null, null)); + service.getLaunchDescriptor( + UUID.fromString("72345678-1234-4234-8234-123456789abc"), + CANONICAL_TENANT_ID, + WORLD_SLUG, + "cp-read", + "sha256:" + "b".repeat(64), + original.authoredWorldBinding().resultDigest())); + assertEquals( + "LAUNCH_DESCRIPTOR_CONFLICT: exact readback selector or digest does not match", + changedRequestDigest.getMessage()); + IllegalArgumentException changedResultDigest = + assertThrows( + IllegalArgumentException.class, + () -> + service.getLaunchDescriptor( + UUID.fromString("82345678-1234-4234-8234-123456789abc"), + CANONICAL_TENANT_ID, + WORLD_SLUG, + "cp-read", + original.authoredWorldBinding().requestDigest(), + "sha256:" + "c".repeat(64))); assertEquals( - "SCRIPT_PATCH_NOT_READY: exact published-for-base and Automation READY evidence is unavailable", - thrown.getMessage()); - verify(launchDescriptorRepository, org.mockito.Mockito.never()) - .save(any(LaunchDescriptor.class)); + "LAUNCH_DESCRIPTOR_CONFLICT: exact readback selector or digest does not match", + changedResultDigest.getMessage()); + + IllegalArgumentException changedWorld = + assertThrows( + IllegalArgumentException.class, + () -> + service.getLaunchDescriptor( + UUID.fromString("92345678-1234-4234-8234-123456789abc"), + CANONICAL_TENANT_ID, + "other-world", + "cp-read", + original.authoredWorldBinding().requestDigest(), + original.authoredWorldBinding().resultDigest())); + assertEquals( + "LAUNCH_DESCRIPTOR_CONFLICT: exact readback selector or digest does not match", + changedWorld.getMessage()); + verify(launchDescriptorRepository, never()).insertImmutable(any(LaunchDescriptor.class)); } @Test - void replayOfRetainedDescriptorCannotReturnUnverifiedPatch() { - GameTemplateLaunchConfigView template = - org.mockito.Mockito.mock(GameTemplateLaunchConfigView.class); - when(template.getDefaultVersionId()).thenReturn(7L); - when(template.getTemplateReferencePhase()).thenReturn(TemplateReferencePhase.ENFORCED); - when(gameTemplateRepository.findLaunchConfigByTenantIdAndId("tenant-1", 9L)) - .thenReturn(Optional.of(template)); - when(launchDescriptorRepository.findByTenantIdAndGameTemplateIdAndControlPlaneRequestId( - "tenant-1", 9L, "cp-replay")) - .thenReturn(Optional.empty()); - Version version = new Version(); - version.setId(7L); - version.setTenantId("tenant-1"); - version.setVersionState(VersionLifecycleState.PUBLISHED); - when(versionRepository.findById(7L)).thenReturn(Optional.of(version)); - when(publishedReleaseBundleService.getPublishedReleaseBundle("tenant-1", 7L)) - .thenReturn( - new PublishedReleaseBundleDto( - 11L, - "tenant-1", - 7L, - 8, - "v1", - "workflow-1", - "hash-1", - List.of("manifest.json"), - List.of(), - "genrev-1", - false, - null, - LocalDateTime.now())); - java.util.concurrent.atomic.AtomicReference saved = - new java.util.concurrent.atomic.AtomicReference<>(); - when(launchDescriptorRepository.save(any(LaunchDescriptor.class))) - .thenAnswer( - invocation -> { - LaunchDescriptor descriptor = invocation.getArgument(0); - saved.set(descriptor); - return descriptor; - }); - service.resolveLaunchDescriptor("tenant-1", 9L, "cp-replay", null, null, null, null); - saved.get().setScriptPatchVersion("patch-1"); - when(launchDescriptorRepository.findByTenantIdAndGameTemplateIdAndControlPlaneRequestId( - "tenant-1", 9L, "cp-replay")) - .thenReturn(Optional.of(saved.get())); + void selectedPatchWithoutExactPublicationAndReadinessEvidenceCannotResolve() { + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-patch", 9L); + GameTemplateLaunchConfigView template = stubTemplate(request, 7L, "patch-1"); + stubSource(request, sourceEvidence(WORLD_SLUG)); + stubVersion(7L, VersionLifecycleState.PUBLISHED, 17L, null); IllegalArgumentException thrown = assertThrows( - IllegalArgumentException.class, - () -> - service.resolveLaunchDescriptor( - "tenant-1", 9L, "cp-replay", null, null, null, null)); + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); + assertEquals( "SCRIPT_PATCH_NOT_READY: exact published-for-base and Automation READY evidence is unavailable", thrown.getMessage()); + verify(template).getDefaultScriptPatchVersion(); + org.mockito.ArgumentCaptor failure = + org.mockito.ArgumentCaptor.forClass(LaunchDescriptor.class); + verify(launchDescriptorRepository).insertImmutable(failure.capture()); + assertEquals(LaunchDescriptor.OUTCOME_FAILED, failure.getValue().getOutcomeStatus()); + assertEquals("SCRIPT_PATCH_NOT_READY", failure.getValue().getFailureCode()); + assertEquals(request.requestDigest(), failure.getValue().getRequestDigest()); + assertEquals(null, failure.getValue().getLaunchDescriptorId()); + assertEquals(null, failure.getValue().getVersionId()); } @Test - void resolveLaunchDescriptorRejectsConflictingRequestReuse() { - LaunchDescriptor existing = new LaunchDescriptor(); - existing.setRequestHash("other-hash"); - GameTemplateLaunchConfigView template = - org.mockito.Mockito.mock(GameTemplateLaunchConfigView.class); - when(gameTemplateRepository.findLaunchConfigByTenantIdAndId("tenant-1", 9L)) - .thenReturn(Optional.of(template)); - when(launchDescriptorRepository.findByTenantIdAndGameTemplateIdAndControlPlaneRequestId( - "tenant-1", 9L, "cp-1")) - .thenReturn(Optional.of(existing)); + void sourceAndTransientDependencyFailuresDoNotCreateFrozenOutcomes() { + AuthoredWorldLaunchDescriptorEvidence.Request missingSource = request("cp-no-source", 9L); + when(authoredWorldSourceRepository.read( + SOURCE_OPERATION_ID, CANONICAL_TENANT_ID, WORLD_SLUG, NAMESPACE)) + .thenReturn(Optional.empty()); + + IllegalArgumentException sourceFailure = + assertThrows( + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(missingSource)); + assertEquals( + "AUTHORED_WORLD_SOURCE_NOT_FOUND: exact committed source evidence is missing", + sourceFailure.getMessage()); + AuthoredWorldLaunchDescriptorEvidence.Request changedSourceEvidence = + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + "cp-changed-source", + CANONICAL_TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + "sha256:" + "f".repeat(64), + 9L, + false, + null, + false, + null, + false, + null, + false, + null); + stubSource(changedSourceEvidence, sourceEvidence(WORLD_SLUG)); assertThrows( IllegalArgumentException.class, - () -> service.resolveLaunchDescriptor("tenant-1", 9L, "cp-1", null, null, null, null)); + () -> service.resolveLaunchDescriptor(changedSourceEvidence)); + + AuthoredWorldLaunchDescriptorEvidence.Request unavailableDependency = + request("cp-unavailable", 9L); + stubSource(unavailableDependency, sourceEvidence(WORLD_SLUG)); + when(gameTemplateRepository.findLaunchConfigByTenantIdAndId(PRIVATE_SOURCE_TENANT_KEY, 9L)) + .thenThrow(new DataAccessResourceFailureException("temporary database outage")); + + assertThrows( + DataAccessResourceFailureException.class, + () -> service.resolveLaunchDescriptor(unavailableDependency)); + verify(launchDescriptorRepository, never()).insertImmutable(any(LaunchDescriptor.class)); + } + + @Test + void exactRetryOfStoredFailureReturnsItsOriginalCodeAndMessageBeforeMutableReads() { + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-frozen-failure", 9L); + AuthoredWorldSourceEvidence source = sourceEvidence(WORLD_SLUG); + LaunchDescriptor failure = new LaunchDescriptor(); + failure.setTenantId(PRIVATE_SOURCE_TENANT_KEY); + failure.setControlPlaneRequestId(request.controlPlaneRequestId()); + failure.setRequestHash(request.requestDigest()); + failure.setDescriptorSchemaVersion(AuthoredWorldLaunchDescriptorEvidence.SCHEMA_VERSION); + failure.setTargetNamespace(NAMESPACE); + failure.setCanonicalTenantId(CANONICAL_TENANT_ID.toString()); + failure.setWorldSlug(WORLD_SLUG); + failure.setAuthoredWorldSourceOperationId(SOURCE_OPERATION_ID.toString()); + failure.setAuthoredWorldSourceEvidenceDigest(request.authoredWorldSourceEvidenceDigest()); + failure.setRequestDigest(request.requestDigest()); + failure.setOriginalRequestJson(new ObjectMapper().writeValueAsString(request)); + failure.setSourceEvidenceJson(new ObjectMapper().writeValueAsString(source)); + failure.setOutcomeStatus(LaunchDescriptor.OUTCOME_FAILED); + failure.setFailureCode("TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED"); + failure.setFailureMessage("TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED: frozen phase denial"); + when(launchDescriptorRepository.findBoundByRequest( + NAMESPACE, CANONICAL_TENANT_ID, request.controlPlaneRequestId())) + .thenReturn(Optional.of(failure)); + stubSource(request, source); + + FrozenLaunchDescriptorDenialException thrown = + assertThrows( + FrozenLaunchDescriptorDenialException.class, + () -> service.resolveLaunchDescriptor(request)); + + assertEquals("TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED", thrown.failureCode()); + assertEquals("TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED: frozen phase denial", thrown.getMessage()); + verify(gameTemplateRepository, never()) + .findLaunchConfigByTenantIdAndId(PRIVATE_SOURCE_TENANT_KEY, 9L); + verify(launchDescriptorRepository, never()).insertImmutable(any(LaunchDescriptor.class)); + } + + @Test + void tamperedStoredPatchCannotReplayOutsideItsCommittedResultDigest() { + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-tampered", 9L); + stubSuccessfulLaunch(request, 7L, 11L); + LaunchDescriptor stored = descriptorFor(request, 7L, 11L); + stored.setScriptPatchVersion("patch-1"); + when(launchDescriptorRepository.findBoundByRequest( + NAMESPACE, CANONICAL_TENANT_ID, "cp-tampered")) + .thenReturn(Optional.of(stored)); + + IllegalArgumentException thrown = + assertThrows( + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); + + assertEquals( + "LAUNCH_DESCRIPTOR_CONFLICT: stored resolved result digest is inconsistent", + thrown.getMessage()); + } + + @Test + void resolveLaunchDescriptorPreservesTemplatePhaseGate() { + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-phase", 9L); + GameTemplateLaunchConfigView template = stubTemplate(request, 7L, null); + when(template.getTemplateReferencePhase()).thenReturn(TemplateReferencePhase.LEGACY); + stubSource(request, sourceEvidence(WORLD_SLUG)); + + IllegalArgumentException thrown = + assertThrows( + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); + + assertEquals( + "TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED: template reference phase is not enforced", + thrown.getMessage()); } @Test void resolveLaunchDescriptorFailsClosedOnUnsupportedAttestationSchema() { - GameTemplateLaunchConfigView template = - org.mockito.Mockito.mock(GameTemplateLaunchConfigView.class); - when(template.getId()).thenReturn(9L); - when(template.getTenantId()).thenReturn("tenant-1"); - when(template.getDefaultVersionId()).thenReturn(7L); - when(template.getDefaultScriptPatchVersion()).thenReturn(null); - when(template.getDefaultRuntimeFlagsJson()).thenReturn("{}"); - when(template.getTemplateReferencePhase()).thenReturn(TemplateReferencePhase.ENFORCED); - when(gameTemplateRepository.findLaunchConfigByTenantIdAndId("tenant-1", 9L)) - .thenReturn(Optional.of(template)); - when(launchDescriptorRepository.findByTenantIdAndGameTemplateIdAndControlPlaneRequestId( - "tenant-1", 9L, "cp-1")) - .thenReturn(Optional.empty()); - Version version = new Version(); - version.setId(7L); - version.setTenantId("tenant-1"); - version.setVersionNumber(8); - version.setVersionState(VersionLifecycleState.PUBLISHED); - version.setVersionStateEpoch(17L); - version.setUpdatedAt(LocalDateTime.now()); - when(versionRepository.findById(7L)).thenReturn(Optional.of(version)); - when(publishedReleaseBundleService.getPublishedReleaseBundle("tenant-1", 7L)) - .thenReturn( - new PublishedReleaseBundleDto( - 11L, - "tenant-1", - 7L, - 8, - "v2", - "workflow-1", - "hash-1", - List.of("manifest.json"), - List.of(), - "genrev-1", - false, - null, - LocalDateTime.now())); + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-schema", 9L); + stubTemplate(request, 7L, null); + stubSource(request, sourceEvidence(WORLD_SLUG)); + stubVersion(7L, VersionLifecycleState.PUBLISHED, 17L, null); + when(publishedReleaseBundleService.getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 7L)) + .thenReturn(releaseBundle(7L, 11L, "v2")); IllegalArgumentException thrown = assertThrows( - IllegalArgumentException.class, - () -> service.resolveLaunchDescriptor("tenant-1", 9L, "cp-1", null, null, null, null)); + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); assertEquals( true, @@ -261,33 +464,16 @@ void resolveLaunchDescriptorFailsClosedOnUnsupportedAttestationSchema() { @Test void resolveLaunchDescriptorReportsMissingReleaseBundleDeterministically() { - GameTemplateLaunchConfigView template = - org.mockito.Mockito.mock(GameTemplateLaunchConfigView.class); - when(template.getId()).thenReturn(9L); - when(template.getTenantId()).thenReturn("tenant-1"); - when(template.getDefaultVersionId()).thenReturn(7L); - when(template.getDefaultScriptPatchVersion()).thenReturn(null); - when(template.getDefaultRuntimeFlagsJson()).thenReturn("{}"); - when(template.getTemplateReferencePhase()).thenReturn(TemplateReferencePhase.ENFORCED); - when(gameTemplateRepository.findLaunchConfigByTenantIdAndId("tenant-1", 9L)) - .thenReturn(Optional.of(template)); - when(launchDescriptorRepository.findByTenantIdAndGameTemplateIdAndControlPlaneRequestId( - "tenant-1", 9L, "cp-2")) - .thenReturn(Optional.empty()); - Version version = new Version(); - version.setId(7L); - version.setTenantId("tenant-1"); - version.setVersionNumber(8); - version.setVersionState(VersionLifecycleState.PUBLISHED); - version.setVersionStateEpoch(17L); - when(versionRepository.findById(7L)).thenReturn(Optional.of(version)); - when(publishedReleaseBundleService.getPublishedReleaseBundle("tenant-1", 7L)) - .thenThrow(new PublishedReleaseBundleNotFoundException("tenant-1", 7L)); + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-missing-release", 9L); + stubTemplate(request, 7L, null); + stubSource(request, sourceEvidence(WORLD_SLUG)); + stubVersion(7L, VersionLifecycleState.PUBLISHED, 17L, null); + when(publishedReleaseBundleService.getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 7L)) + .thenThrow(new PublishedReleaseBundleNotFoundException(PRIVATE_SOURCE_TENANT_KEY, 7L)); IllegalArgumentException thrown = assertThrows( - IllegalArgumentException.class, - () -> service.resolveLaunchDescriptor("tenant-1", 9L, "cp-2", null, null, null, null)); + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); assertEquals( "RELEASE_BUNDLE_NOT_FOUND: no published release bundle for the resolved version", @@ -295,34 +481,66 @@ void resolveLaunchDescriptorReportsMissingReleaseBundleDeterministically() { } @Test - void resolveLaunchDescriptorRequiresRemapForCrossVersionReplacementLaunch() { - GameTemplateLaunchConfigView template = - org.mockito.Mockito.mock(GameTemplateLaunchConfigView.class); - when(template.getId()).thenReturn(9L); - when(template.getTenantId()).thenReturn("tenant-1"); - when(template.getDefaultVersionId()).thenReturn(7L); - when(template.getDefaultScriptPatchVersion()).thenReturn(null); - when(template.getDefaultRuntimeFlagsJson()).thenReturn("{}"); - when(template.getTemplateReferencePhase()).thenReturn(TemplateReferencePhase.ENFORCED); - when(gameTemplateRepository.findLaunchConfigByTenantIdAndId("tenant-1", 9L)) - .thenReturn(Optional.of(template)); - when(launchDescriptorRepository.findByTenantIdAndGameTemplateIdAndControlPlaneRequestId( - "tenant-1", 9L, "cp-3")) + void resolveLaunchDescriptorAcceptsEqualLargeReleaseVersionIdsByValue() { + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-large-version", 9L); + Long resolvedVersionId = boxedLargeVersionId(); + Long bundleVersionId = boxedLargeVersionId(); + assertNotSame(resolvedVersionId, bundleVersionId); + stubTemplate(request, resolvedVersionId, null); + stubSource(request, sourceEvidence(WORLD_SLUG)); + stubVersion(1_000L, VersionLifecycleState.PUBLISHED, 17L, null); + when(publishedReleaseBundleService.getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 1_000L)) + .thenReturn(releaseBundle(bundleVersionId, 11L, "v1")); + when(launchDescriptorRepository.findBoundByRequest( + NAMESPACE, CANONICAL_TENANT_ID, request.controlPlaneRequestId())) .thenReturn(Optional.empty()); - Version version = new Version(); - version.setId(8L); - version.setTenantId("tenant-1"); - version.setVersionNumber(9); - version.setVersionState(VersionLifecycleState.PUBLISHED); - version.setVersionStateEpoch(18L); - when(versionRepository.findById(8L)).thenReturn(Optional.of(version)); - when(templateRemapSetService.findApprovedTemplateRemapSet("tenant-1", 7L, 8L)) + when(launchDescriptorRepository.findByPrivateRequest( + PRIVATE_SOURCE_TENANT_KEY, request.controlPlaneRequestId())) .thenReturn(Optional.empty()); + var resolved = service.resolveLaunchDescriptor(request); + + assertEquals(CANONICAL_TENANT_ID.toString(), resolved.canonicalTenantId()); + assertEquals(9L, resolved.gameTemplateId()); + assertEquals(1_000L, resolved.versionId()); + assertEquals(11L, resolved.releaseBundleId()); + assertNotNull(resolved.authoredWorldBinding()); + assertEquals(request.requestDigest(), resolved.authoredWorldBinding().requestDigest()); + assertEquals( + "release-bundle:" + CANONICAL_TENANT_ID + ":1000:11", resolved.publishedReleaseBundleRef()); + } + + @Test + void resolveLaunchDescriptorRejectsReleaseBundleForDifferentVersionDeterministically() { + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-mismatched-release", 9L); + stubTemplate(request, 1_000L, null); + stubSource(request, sourceEvidence(WORLD_SLUG)); + stubVersion(1_000L, VersionLifecycleState.PUBLISHED, 17L, null); + when(publishedReleaseBundleService.getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 1_000L)) + .thenReturn(releaseBundle(1_001L, 11L, "v1")); + IllegalArgumentException thrown = assertThrows( - IllegalArgumentException.class, - () -> service.resolveLaunchDescriptor("tenant-1", 9L, "cp-3", null, 7L, 8L, null)); + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); + + assertEquals( + "RELEASE_BUNDLE_NOT_FOUND: release bundle is not owned by the resolved source version", + thrown.getMessage()); + } + + @Test + void resolveLaunchDescriptorRequiresRemapForCrossVersionReplacementLaunch() { + AuthoredWorldLaunchDescriptorEvidence.Request request = + request("cp-remap-required", 9L, 7L, 8L); + stubTemplate(request, 8L, null); + stubSource(request, sourceEvidence(WORLD_SLUG)); + stubVersion(8L, VersionLifecycleState.PUBLISHED, 18L, null); + when(templateRemapSetService.findApprovedTemplateRemapSet(PRIVATE_SOURCE_TENANT_KEY, 7L, 8L)) + .thenReturn(Optional.empty()); + + IllegalArgumentException thrown = + assertThrows( + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); assertEquals( "LAUNCH_REMAP_REQUIRED: replacement-instance launch requires an approved remapSetId", @@ -331,61 +549,282 @@ void resolveLaunchDescriptorRequiresRemapForCrossVersionReplacementLaunch() { @Test void resolveLaunchDescriptorUsesApprovedRemapSetForCrossVersionReplacementLaunch() { - GameTemplateLaunchConfigView template = - org.mockito.Mockito.mock(GameTemplateLaunchConfigView.class); - when(template.getId()).thenReturn(9L); - when(template.getTenantId()).thenReturn("tenant-1"); - when(template.getDefaultVersionId()).thenReturn(8L); - when(template.getDefaultScriptPatchVersion()).thenReturn(null); - when(template.getDefaultRuntimeFlagsJson()).thenReturn("{}"); - when(template.getTemplateReferencePhase()).thenReturn(TemplateReferencePhase.ENFORCED); - when(gameTemplateRepository.findLaunchConfigByTenantIdAndId("tenant-1", 9L)) - .thenReturn(Optional.of(template)); - when(launchDescriptorRepository.findByTenantIdAndGameTemplateIdAndControlPlaneRequestId( - "tenant-1", 9L, "cp-4")) - .thenReturn(Optional.empty()); - Version version = new Version(); - version.setId(8L); - version.setTenantId("tenant-1"); - version.setVersionNumber(9); - version.setVersionState(VersionLifecycleState.PUBLISHED); - version.setVersionStateEpoch(18L); - when(versionRepository.findById(8L)).thenReturn(Optional.of(version)); - when(templateRemapSetService.findApprovedTemplateRemapSet("tenant-1", 7L, 8L)) + AuthoredWorldLaunchDescriptorEvidence.Request request = + request("cp-remap-approved", 9L, 7L, 8L); + stubTemplate(request, 8L, null); + stubSource(request, sourceEvidence(WORLD_SLUG)); + stubVersion(8L, VersionLifecycleState.PUBLISHED, 18L, null); + when(templateRemapSetService.findApprovedTemplateRemapSet(PRIVATE_SOURCE_TENANT_KEY, 7L, 8L)) .thenReturn( Optional.of( new TemplateRemapSetDto( "remap-1", - "tenant-1", + PRIVATE_SOURCE_TENANT_KEY, 7L, 8L, TemplateRemapSetStatus.APPROVED, - "prep", + "preparation", "approved", LocalDateTime.now(), LocalDateTime.now(), List.of()))); - when(publishedReleaseBundleService.getPublishedReleaseBundle("tenant-1", 8L)) - .thenReturn( - new PublishedReleaseBundleDto( - 11L, - "tenant-1", - 8L, - 9, - "v1", - "workflow-1", - "hash-1", - List.of("manifest.json"), - List.of(), - "genrev-1", - false, - null, - LocalDateTime.now())); - when(launchDescriptorRepository.save(any(LaunchDescriptor.class))) + stubBundle(8L, 11L, "v1"); + when(launchDescriptorRepository.insertImmutable(any(LaunchDescriptor.class))) .thenAnswer(invocation -> invocation.getArgument(0)); - var descriptor = service.resolveLaunchDescriptor("tenant-1", 9L, "cp-4", null, 7L, 8L, null); + var resolved = service.resolveLaunchDescriptor(request); + + assertEquals("remap-1", resolved.remapSetId()); + assertEquals("remap-1", resolved.authoredWorldBinding().remapSetId()); + } + + private void stubSuccessfulLaunch( + AuthoredWorldLaunchDescriptorEvidence.Request request, long versionId, long bundleId) { + stubTemplate(request, versionId, null); + stubSource(request, sourceEvidence(request.worldSlug())); + stubVersion(versionId, VersionLifecycleState.PUBLISHED, 17L, null); + stubBundle(versionId, bundleId, "v1"); + when(launchDescriptorRepository.findBoundByRequest( + NAMESPACE, CANONICAL_TENANT_ID, request.controlPlaneRequestId())) + .thenReturn(Optional.empty()); + when(launchDescriptorRepository.findByPrivateRequest( + PRIVATE_SOURCE_TENANT_KEY, request.controlPlaneRequestId())) + .thenReturn(Optional.empty()); + } + + private GameTemplateLaunchConfigView stubTemplate( + AuthoredWorldLaunchDescriptorEvidence.Request request, + Long defaultVersionId, + String defaultPatch) { + GameTemplateLaunchConfigView template = Mockito.mock(GameTemplateLaunchConfigView.class); + when(template.getId()).thenReturn(request.gameTemplateId()); + when(template.getTenantId()).thenReturn(PRIVATE_SOURCE_TENANT_KEY); + when(template.getDefaultVersionId()).thenReturn(defaultVersionId); + when(template.getDefaultScriptPatchVersion()).thenReturn(defaultPatch); + when(template.getDefaultRuntimeFlagsJson()).thenReturn("{}"); + when(template.getTemplateReferencePhase()).thenReturn(TemplateReferencePhase.ENFORCED); + when(gameTemplateRepository.findLaunchConfigByTenantIdAndId( + PRIVATE_SOURCE_TENANT_KEY, request.gameTemplateId())) + .thenReturn(Optional.of(template)); + return template; + } + + private void stubSource( + AuthoredWorldLaunchDescriptorEvidence.Request request, AuthoredWorldSourceEvidence source) { + when(authoredWorldSourceRepository.read( + request.authoredWorldSourceOperationId(), + request.canonicalTenantId(), + request.worldSlug(), + NAMESPACE)) + .thenReturn(Optional.of(source)); + } + + private void stubVersion( + long versionId, VersionLifecycleState state, long epoch, String scriptPatchVersion) { + Version version = new Version(); + version.setId(versionId); + version.setTenantId(PRIVATE_SOURCE_TENANT_KEY); + version.setVersionNumber(8); + version.setVersionState(state); + version.setVersionStateEpoch(epoch); + version.setScriptPatchVersion(scriptPatchVersion); + version.setUpdatedAt(LocalDateTime.now()); + when(versionRepository.findById(versionId)).thenReturn(Optional.of(version)); + } + + private void stubBundle(long versionId, long bundleId, String schemaVersion) { + when(publishedReleaseBundleService.getPublishedReleaseBundle( + PRIVATE_SOURCE_TENANT_KEY, versionId)) + .thenReturn(releaseBundle(versionId, bundleId, schemaVersion)); + } + + private PublishedReleaseBundleDto releaseBundle( + Long versionId, long bundleId, String schemaVersion) { + return new PublishedReleaseBundleDto( + bundleId, + PRIVATE_SOURCE_TENANT_KEY, + versionId, + 8, + schemaVersion, + "workflow-1", + "hash-1", + List.of("manifest.json"), + List.of(), + "genrev-1", + false, + null, + LocalDateTime.now()); + } + + @SuppressWarnings("removal") + private Long boxedLargeVersionId() { + return new Long(1_000L); + } + + private LaunchDescriptor descriptorFor( + AuthoredWorldLaunchDescriptorEvidence.Request request, long versionId, long bundleId) { + var evidence = + AuthoredWorldLaunchDescriptorEvidence.create( + request, + "ld-stored-" + request.controlPlaneRequestId(), + versionId, + false, + null, + "{}", + "genrev-1", + 17L, + bundleId, + "release-bundle:" + CANONICAL_TENANT_ID + ":" + versionId + ":" + bundleId, + false, + null); + AuthoredWorldSourceEvidence source = sourceEvidence(request.worldSlug()); + LaunchDescriptor descriptor = new LaunchDescriptor(); + descriptor.setLaunchDescriptorId(evidence.launchDescriptorId()); + descriptor.setTenantId(PRIVATE_SOURCE_TENANT_KEY); + descriptor.setGameTemplateId(request.gameTemplateId()); + descriptor.setControlPlaneRequestId(request.controlPlaneRequestId()); + descriptor.setRequestHash(evidence.requestDigest()); + descriptor.setVersionId(evidence.versionId()); + descriptor.setRuntimeFlagsJson(evidence.runtimeFlagsJson()); + descriptor.setGenerationConfigRevision(evidence.generationConfigRevision()); + descriptor.setVersionStateEpoch(evidence.versionStateEpoch()); + descriptor.setReleaseBundleId(evidence.releaseBundleId()); + descriptor.setPublishedReleaseBundleRef(evidence.publishedReleaseBundleRef()); + descriptor.setDescriptorSchemaVersion(evidence.schemaVersion()); + descriptor.setTargetNamespace(evidence.targetNamespace()); + descriptor.setCanonicalTenantId(evidence.canonicalTenantId().toString()); + descriptor.setWorldSlug(evidence.worldSlug()); + descriptor.setAuthoredWorldSourceOperationId( + evidence.authoredWorldSourceOperationId().toString()); + descriptor.setAuthoredWorldSourceEvidenceDigest(evidence.authoredWorldSourceEvidenceDigest()); + descriptor.setRequestDigest(evidence.requestDigest()); + descriptor.setResultDigest(evidence.resultDigest()); + descriptor.setOriginalRequestJson(new ObjectMapper().writeValueAsString(request)); + descriptor.setSourceEvidenceJson(new ObjectMapper().writeValueAsString(source)); + return descriptor; + } + + private AuthoredWorldSourceEvidence sourceEvidence(String worldSlug) { + String tenantSlug = "silver-company"; + String displayName = "Silver March 🐉"; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, + SOURCE_REGISTRATION_ID, + CANONICAL_TENANT_ID, + tenantSlug, + worldSlug, + displayName); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + SOURCE_REGISTRATION_ID, + SOURCE_OPERATION_ID, + requestDigest, + CANONICAL_TENANT_ID, + tenantSlug, + worldSlug, + displayName, + 901L, + PRIVATE_SOURCE_TENANT_KEY, + "NEW_GAME_ROW", + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + SOURCE_REGISTRATION_ID, + SOURCE_OPERATION_ID, + requestDigest, + CANONICAL_TENANT_ID, + tenantSlug, + worldSlug, + displayName, + 901L, + PRIVATE_SOURCE_TENANT_KEY, + "NEW_GAME_ROW")); + } + + private AuthoredWorldLaunchDescriptorEvidence.Request request( + String controlPlaneRequestId, long gameTemplateId) { + return request( + controlPlaneRequestId, + gameTemplateId, + SOURCE_OPERATION_ID, + WORLD_SLUG, + CANONICAL_TENANT_ID); + } + + private AuthoredWorldLaunchDescriptorEvidence.Request request( + String controlPlaneRequestId, + long gameTemplateId, + long sourceVersionId, + long targetVersionId) { + return new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + controlPlaneRequestId, + CANONICAL_TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + sourceEvidence(WORLD_SLUG).evidenceDigest(), + gameTemplateId, + false, + null, + true, + sourceVersionId, + true, + targetVersionId, + false, + null); + } + + private AuthoredWorldLaunchDescriptorEvidence.Request request( + String controlPlaneRequestId, + long gameTemplateId, + boolean requestedPatchPresent, + String requestedPatch) { + return new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + controlPlaneRequestId, + CANONICAL_TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + sourceEvidence(WORLD_SLUG).evidenceDigest(), + gameTemplateId, + requestedPatchPresent, + requestedPatch, + false, + null, + false, + null, + false, + null); + } - assertEquals("remap-1", descriptor.remapSetId()); + private AuthoredWorldLaunchDescriptorEvidence.Request request( + String controlPlaneRequestId, + long gameTemplateId, + UUID operationId, + String worldSlug, + UUID canonicalTenantId) { + String evidenceDigest = + SOURCE_OPERATION_ID.equals(operationId) + && WORLD_SLUG.equals(worldSlug) + && CANONICAL_TENANT_ID.equals(canonicalTenantId) + ? sourceEvidence(WORLD_SLUG).evidenceDigest() + : "sha256:" + "a".repeat(64); + return new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + controlPlaneRequestId, + canonicalTenantId, + worldSlug, + operationId, + evidenceDigest, + gameTemplateId, + false, + null, + false, + null, + false, + null, + false, + null); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java index ca97ef1158..201fbfcf0d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java @@ -21,8 +21,6 @@ import net.firedevops.firemud.gamedesign.v1.HelpTopicScope; import net.firedevops.firemud.gamedesign.v1.ResolveHelpTopicRequest; import net.firedevops.firemud.gamedesign.v1.ResolveHelpTopicResponse; -import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorRequest; -import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorResponse; import net.firedevops.firemud.gamesession.service.GameAuthoredHelpReader; import net.firedevops.firemud.shared.v1.ErrorDetail; import org.springframework.stereotype.Component; @@ -62,31 +60,6 @@ protected GameDesignServiceGrpc.GameDesignServiceBlockingStub buildStub( GameDesignServiceGrpc.newBlockingStub(channel).withCompression("gzip")); } - public ResolveLaunchDescriptorResponse resolveLaunchDescriptor( - long tenantId, long gameTemplateId, String controlPlaneRequestId) { - return resolveLaunchDescriptor(tenantId, gameTemplateId, controlPlaneRequestId, null, null); - } - - public ResolveLaunchDescriptorResponse resolveLaunchDescriptor( - long tenantId, - long gameTemplateId, - String controlPlaneRequestId, - Long sourceVersionId, - Long targetVersionId) { - ResolveLaunchDescriptorRequest.Builder request = - ResolveLaunchDescriptorRequest.newBuilder() - .setTenantId(Long.toString(tenantId)) - .setGameTemplateId(gameTemplateId) - .setControlPlaneRequestId(controlPlaneRequestId); - if (sourceVersionId != null) { - request.setSourceVersionId(sourceVersionId); - } - if (targetVersionId != null) { - request.setTargetVersionId(targetVersionId); - } - return callStub().resolveLaunchDescriptor(request.build()); - } - public GetPublishedReleaseBundleResponse getPublishedReleaseBundle( long tenantId, long versionId) { return callStub() 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 97cfd671b7..3c9d1cd108 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 @@ -9,7 +9,6 @@ import net.firedevops.firemud.common.saga.SagaException; import net.firedevops.firemud.common.saga.SagaRunner; import net.firedevops.firemud.common.security.RequestIdValidation; -import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; import net.firedevops.firemud.gamesession.client.EntityManagementClient; import net.firedevops.firemud.gamesession.client.GameDesignClient; import net.firedevops.firemud.gamesession.client.GameLogicClient; @@ -633,69 +632,9 @@ private GameInstanceDto withStatus(GameInstanceDto snapshot, String status) { } private ResolvedLaunchDescriptor preflightLaunch(StartSessionRequest request) { - if (gameDesignClient == null) { - throw new IllegalStateException("launch descriptor authority unavailable"); - } - var descriptorResponse = - gameDesignClient.resolveLaunchDescriptor( - request.tenantId(), request.gameTemplateId(), request.controlPlaneRequestId()); - if (descriptorResponse.hasError()) { - throw new IllegalArgumentException( - descriptorResponse.getError().getCode() - + ": " - + descriptorResponse.getError().getMessage()); - } - var descriptor = descriptorResponse.getLaunchDescriptor(); - var bundleResponse = - gameDesignClient.getPublishedReleaseBundle(request.tenantId(), descriptor.getVersionId()); - if (bundleResponse.hasError()) { - throw new IllegalArgumentException( - bundleResponse.getError().getCode() + ": " + bundleResponse.getError().getMessage()); - } - var bundle = bundleResponse.getBundle(); - requireSupportedReleaseAttestationSchema(bundle.getAttestationSchemaVersion()); - if (bundle.getId() != descriptor.getReleaseBundleId() - || bundle.getVersionId() != descriptor.getVersionId() - || !bundle.getGenerationConfigRevision().equals(descriptor.getGenerationConfigRevision()) - || !releaseBundleRef(request.tenantId(), descriptor.getVersionId(), bundle.getId()) - .equals(descriptor.getPublishedReleaseBundleRef())) { - throw new IllegalArgumentException( - "RELEASE_ATTESTATION_MISMATCH: resolved launch descriptor does not match the published" - + " release bundle"); - } - validatePublishedAssetProof(request.tenantId(), descriptor.getVersionId(), bundle); - var versionStateResponse = - gameDesignClient.getVersionState(request.tenantId(), descriptor.getVersionId()); - if (versionStateResponse.hasError()) { - throw new IllegalArgumentException( - versionStateResponse.getError().getCode() - + ": " - + versionStateResponse.getError().getMessage()); - } - var versionState = versionStateResponse.getVersionState(); - if (versionState.getVersionState() != VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED - && versionState.getVersionState() != VersionLifecycleState.VERSION_LIFECYCLE_STATE_ACTIVE) { - throw new IllegalArgumentException( - "VERSION_STATE_EPOCH_STALE: resolved version is not activation-eligible"); - } - if (versionState.getVersionStateEpoch() != descriptor.getVersionStateEpoch()) { - throw new IllegalArgumentException( - "VERSION_STATE_EPOCH_STALE: resolved launch descriptor epoch does not match current" - + " version state"); - } - return new ResolvedLaunchDescriptor( - descriptor.getLaunchDescriptorId(), - requirePositiveExternalId(descriptor.getTenantId(), "tenantId"), - descriptor.getGameTemplateId(), - descriptor.getControlPlaneRequestId(), - descriptor.getVersionId(), - descriptor.getScriptPatchVersion().isBlank() ? null : descriptor.getScriptPatchVersion(), - descriptor.getRuntimeFlagsJson(), - descriptor.getGenerationConfigRevision(), - descriptor.getVersionStateEpoch(), - descriptor.getReleaseBundleId(), - descriptor.getPublishedReleaseBundleRef(), - descriptor.getRemapSetId().isBlank() ? null : descriptor.getRemapSetId()); + throw new IllegalArgumentException( + "AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED: canonical authored-world launch binding is" + + " required"); } private void validatePublishedAssetProof( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InstanceCutoverCompatibilityServiceImpl.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InstanceCutoverCompatibilityServiceImpl.java index 0f87b388ad..a45d906ac9 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InstanceCutoverCompatibilityServiceImpl.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InstanceCutoverCompatibilityServiceImpl.java @@ -2,15 +2,12 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.grpc.StatusRuntimeException; -import java.time.Instant; import java.util.ArrayList; import java.util.List; -import java.util.UUID; import net.firedevops.firemud.common.security.RequestIdValidation; import net.firedevops.firemud.entitymanagement.v1.ValidateEntityUpgradeMappingsResponse; import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleResponse; import net.firedevops.firemud.gamedesign.v1.GetVersionStateResponse; -import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorResponse; import net.firedevops.firemud.gamesession.client.EntityManagementClient; import net.firedevops.firemud.gamesession.client.GameDesignClient; import net.firedevops.firemud.gamesession.client.WorldManagementClient; @@ -50,78 +47,9 @@ public InstanceCutoverCompatibilityServiceImpl( @Transactional(readOnly = true) public InstanceCutoverCompatibilityDto validateInstanceCutoverCompatibility( long tenantId, long sourceGameInstanceId, long targetVersionId) { - GameInstance sourceInstance = requireSourceInstance(tenantId, sourceGameInstanceId); - long sourceVersionId = requireSourceVersionId(sourceInstance); - long gameTemplateId = requireGameTemplateId(sourceInstance); - List reasons = new ArrayList<>(); - List checkedParticipants = new ArrayList<>(); - List participantResults = new ArrayList<>(); - - ResolveLaunchDescriptorResponse descriptor = - resolveLaunchDescriptor(tenantId, gameTemplateId, sourceVersionId, targetVersionId); - if (descriptor.hasError()) { - String reason = errorSummary(descriptor.getError()); - return new InstanceCutoverCompatibilityDto( - sourceVersionId, - targetVersionId, - null, - "INCOMPATIBLE", - List.of(reason), - List.of("GAME_DESIGN"), - Instant.now(), - null, - List.of( - new CutoverParticipantCompatibilityDto( - "GAME_DESIGN", - List.of(), - List.of("launch_descriptor"), - false, - "INCOMPATIBLE", - List.of(reason)))); - } - - String remapSetId = normalizeBlank(descriptor.getLaunchDescriptor().getRemapSetId()); - checkedParticipants.add("GAME_DESIGN"); - participantResults.add(validateGameDesignParticipant(tenantId, targetVersionId, reasons)); - - ValidateWorldUpgradeMappingsResponse worldValidation = - worldManagementClient.validateWorldUpgradeMappings( - tenantId, sourceGameInstanceId, targetVersionId, remapSetId); - checkedParticipants.add("WORLD"); - participantResults.add( - new CutoverParticipantCompatibilityDto( - "WORLD", - worldValidation.getStateClassesCheckedList(), - worldValidation.getCheckedFamiliesList(), - worldValidation.getHasS2Rows(), - translateWorldResult(worldValidation), - collectReasons(worldValidation.getReasonsList(), worldValidation.getError()))); - reasons.addAll(collectReasons(worldValidation.getReasonsList(), worldValidation.getError())); - - ValidateEntityUpgradeMappingsResponse entityValidation = - entityManagementClient.validateEntityUpgradeMappings( - tenantId, sourceGameInstanceId, targetVersionId, remapSetId); - checkedParticipants.add("ENTITY"); - participantResults.add( - new CutoverParticipantCompatibilityDto( - "ENTITY", - entityValidation.getStateClassesCheckedList(), - entityValidation.getCheckedFamiliesList(), - entityValidation.getHasS2Rows(), - translateEntityResult(entityValidation), - collectReasons(entityValidation.getReasonsList(), entityValidation.getError()))); - reasons.addAll(collectReasons(entityValidation.getReasonsList(), entityValidation.getError())); - - return new InstanceCutoverCompatibilityDto( - sourceVersionId, - targetVersionId, - descriptor.getLaunchDescriptor().getLaunchDescriptorId(), - summarizeOverallResult(participantResults), - reasons, - checkedParticipants, - Instant.now(), - remapSetId, - participantResults); + throw new IllegalArgumentException( + "AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED: canonical authored-world launch binding is" + + " required"); } private GameInstance requireSourceInstance(long tenantId, long sourceGameInstanceId) { @@ -147,31 +75,10 @@ private long requireSourceVersionId(GameInstance sourceInstance) { throw new IllegalArgumentException("Source game instance version metadata missing"); } - private long requireGameTemplateId(GameInstance sourceInstance) { - if (sourceInstance.getGameTemplateId() == null) { - throw new IllegalArgumentException("Source game instance gameTemplateId missing"); - } - return requirePositiveSourceMetadata(sourceInstance.getGameTemplateId(), "gameTemplateId"); - } - private long requirePositiveSourceMetadata(Long value, String fieldName) { return RequestIdValidation.requirePositiveLong(value.toString(), fieldName); } - private ResolveLaunchDescriptorResponse resolveLaunchDescriptor( - long tenantId, long gameTemplateId, long sourceVersionId, long targetVersionId) { - try { - return gameDesignClient.resolveLaunchDescriptor( - tenantId, - gameTemplateId, - "cutover-compatibility-" + UUID.randomUUID(), - sourceVersionId, - targetVersionId); - } catch (StatusRuntimeException ex) { - throw new IllegalStateException("GAME_DESIGN_UNAVAILABLE: launch descriptor unavailable", ex); - } - } - private CutoverParticipantCompatibilityDto validateGameDesignParticipant( long tenantId, long targetVersionId, List reasons) { List participantReasons = new ArrayList<>(); 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 20b2ba97a2..a6b01fbfc3 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 @@ -1,11 +1,7 @@ package net.firedevops.firemud.gamesession; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.ArgumentMatchers.nullable; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import java.util.List; @@ -20,8 +16,8 @@ import net.firedevops.firemud.gamesession.client.GameDesignClient; import net.firedevops.firemud.gamesession.client.GameLogicClient; import net.firedevops.firemud.gamesession.client.WorldManagementClient; -import net.firedevops.firemud.gamesession.dto.GameInstanceDto; import net.firedevops.firemud.gamesession.dto.StartSessionRequest; +import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.gamesession.service.SessionContextService; import net.firedevops.firemud.test.FiremudAuthTestProperties; @@ -89,123 +85,11 @@ static void configure(DynamicPropertyRegistry registry) { @org.springframework.beans.factory.annotation.Autowired private SessionContextService sessionContextService; + @org.springframework.beans.factory.annotation.Autowired + private GameInstanceRepository gameInstanceRepository; + @Test - void startSessionUsesRealHttpAndPersistencePath() throws Exception { - when(gameDesignClient.resolveLaunchDescriptor(42L, 7L, "cp-1")) - .thenReturn( - net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorResponse.newBuilder() - .setLaunchDescriptor( - net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.newBuilder() - .setLaunchDescriptorId("ld-1") - .setTenantId("42") - .setGameTemplateId(7L) - .setControlPlaneRequestId("cp-1") - .setVersionId(11L) - .setScriptPatchVersion("patch-1") - .setRuntimeFlagsJson("{}") - .setGenerationConfigRevision("genrev-11") - .setVersionStateEpoch(77L) - .setReleaseBundleId(77L) - .setPublishedReleaseBundleRef("prb:42:11:77") - .build()) - .build()); - when(gameDesignClient.getPublishedReleaseBundle(42L, 11L)) - .thenReturn( - net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleResponse.newBuilder() - .setBundle( - net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle.newBuilder() - .setId(77L) - .setVersionId(11L) - .setAttestationSchemaVersion("v1") - .setManifestHash("manifest-11") - .addRequiredManifestAssetKeys("manifest.json") - .setGenerationConfigRevision("genrev-11") - .build()) - .build()); - when(gameDesignClient.getVersionAssetArtifactState(42L, 11L)) - .thenReturn( - net.firedevops.firemud.gamedesign.v1.GetVersionAssetArtifactStateResponse.newBuilder() - .setArtifactState( - net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState.newBuilder() - .setTenantId("42") - .setVersionId(11L) - .setArtifactState( - net.firedevops.firemud.gamedesign.v1.ArtifactState - .ARTIFACT_STATE_PUBLISHED) - .setStateEpoch(2L) - .setManifestHash("manifest-11") - .addExportedManifestAssetKeys("manifest.json") - .build()) - .build()); - when(gameDesignClient.getVersionState(42L, 11L)) - .thenReturn( - net.firedevops.firemud.gamedesign.v1.GetVersionStateResponse.newBuilder() - .setVersionState( - net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot.newBuilder() - .setTenantId("42") - .setVersionId(11L) - .setVersionState( - net.firedevops.firemud.gamedesign.v1.VersionLifecycleState - .VERSION_LIFECYCLE_STATE_PUBLISHED) - .setVersionStateEpoch(77L) - .setUpdatedAt("2026-04-15T10:00:00") - .build()) - .build()); - when(worldManagementClient.prepareWorldInstance( - anyLong(), - anyLong(), - anyLong(), - anyString(), - anyString(), - anyLong(), - nullable(String.class), - anyString(), - anyString(), - anyLong(), - anyString(), - anyLong(), - any())) - .thenAnswer( - invocation -> - net.firedevops.firemud.worldmanagement.v1.PrepareWorldInstanceResponse.newBuilder() - .setWorldInstance( - net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot - .newBuilder() - .setTenantId(Long.toString(invocation.getArgument(0, Long.class))) - .setGameInstanceId(Long.toString(invocation.getArgument(1, Long.class))) - .setGameTemplateId(Long.toString(invocation.getArgument(2, Long.class))) - .setControlPlaneRequestId(invocation.getArgument(3, String.class)) - .setLaunchDescriptorId(invocation.getArgument(4, String.class)) - .setVersionId(Long.toString(invocation.getArgument(5, Long.class))) - .setReleaseBundleId( - Long.toString(invocation.getArgument(9, Long.class))) - .setGenerationConfigRevision(invocation.getArgument(8, String.class)) - .setPublishedReleaseBundleRef(invocation.getArgument(10, String.class)) - .setVersionStateEpoch(invocation.getArgument(11, Long.class)) - .setLifecycleEpoch(1L) - .setStatus( - net.firedevops.firemud.worldmanagement.v1 - .WorldInstanceLifecycleStatus - .WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING) - .build()) - .build()); - when(worldManagementClient.activatePreparedWorldInstance(anyLong(), anyLong(), anyLong())) - .thenAnswer( - invocation -> - net.firedevops.firemud.worldmanagement.v1.ActivatePreparedWorldInstanceResponse - .newBuilder() - .setWorldInstance( - net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot - .newBuilder() - .setTenantId(Long.toString(invocation.getArgument(0, Long.class))) - .setGameInstanceId(Long.toString(invocation.getArgument(1, Long.class))) - .setLifecycleEpoch(invocation.getArgument(2, Long.class) + 1L) - .setStatus( - net.firedevops.firemud.worldmanagement.v1 - .WorldInstanceLifecycleStatus - .WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE) - .build()) - .build()); + void legacyNumericStartFailsBeforeDependenciesOrPersistence() throws Exception { StartSessionRequest request = new StartSessionRequest(42L, 7L, "cp-1", "123e4567-e89b-12d3-a456-426614174000"); @@ -214,41 +98,17 @@ void startSessionUsesRealHttpAndPersistencePath() throws Exception { "http://localhost:" + port + "/sessions", OBJECT_MAPPER.writeValueAsString(request), privilegedHeaders()); - ApiResponse body = - OBJECT_MAPPER.readValue(responseBody, new TypeReference>() {}); - - org.mockito.Mockito.verify(worldManagementClient) - .prepareWorldInstance( - eq(42L), - anyLong(), - eq(7L), - eq("cp-1"), - eq("ld-1"), - eq(11L), - org.mockito.ArgumentMatchers.isNull(), - eq("{}"), - eq("genrev-11"), - eq(77L), - eq("prb:42:11:77"), - eq(77L), - any()); + ApiResponse body = + OBJECT_MAPPER.readValue( + responseBody, + new TypeReference>() {}); assertThat(body).isNotNull(); - assertThat(body.status()).isEqualTo(ResultStatus.SUCCESS); - assertThat(body.data()).isNotNull(); - assertThat(body.data().tenantId()).isEqualTo(42L); - assertThat(body.data().runtimeVersion()).isEqualTo("11"); - assertThat(body.data().scriptPatchVersion()).isNull(); - assertThat(body.data().scriptPinEpoch()).isNull(); - assertThat(body.data().gameTemplateId()).isEqualTo(7L); - assertThat(body.data().launchDescriptorId()).isEqualTo("ld-1"); - assertThat(body.data().versionId()).isEqualTo(11L); - assertThat(body.data().releaseBundleId()).isEqualTo(77L); - assertThat(body.data().versionStateEpoch()).isEqualTo(77L); - assertThat(body.data().generationConfigRevision()).isEqualTo("genrev-11"); - assertThat(body.data().ownerAccountId()).isEqualTo("123e4567-e89b-12d3-a456-426614174000"); - assertThat(body.data().status()).isEqualTo("RUNNING"); - assertThat(body.data().id()).isPositive(); + assertThat(body.status()).isEqualTo(ResultStatus.ERROR); + assertThat(body.error().code()).isEqualTo("INVALID_ARGUMENT"); + assertThat(body.error().message()).contains("AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED"); + assertThat(gameInstanceRepository.findAll()).isEmpty(); + verifyNoInteractions(gameDesignClient, worldManagementClient); } @Test 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 511eb52e71..d243bc9e93 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 @@ -5,10 +5,10 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; @@ -132,42 +132,6 @@ void setUp() throws Exception { entity.getOwnerAccountId(), entity.getStatus()); }); - when(gameDesignClient.resolveLaunchDescriptor(42L, 7L, "cp-1")) - .thenReturn( - net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorResponse.newBuilder() - .setLaunchDescriptor( - net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.newBuilder() - .setLaunchDescriptorId("ld-1") - .setTenantId("42") - .setGameTemplateId(7L) - .setControlPlaneRequestId("cp-1") - .setVersionId(11L) - .setScriptPatchVersion("patch-1") - .setRuntimeFlagsJson("{}") - .setGenerationConfigRevision("genrev-11") - .setVersionStateEpoch(77L) - .setReleaseBundleId(77L) - .setPublishedReleaseBundleRef("prb:42:11:77") - .build()) - .build()); - when(gameDesignClient.resolveLaunchDescriptor(42L, 7L, "cp-2")) - .thenReturn( - net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorResponse.newBuilder() - .setLaunchDescriptor( - net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.newBuilder() - .setLaunchDescriptorId("ld-2") - .setTenantId("42") - .setGameTemplateId(7L) - .setControlPlaneRequestId("cp-2") - .setVersionId(12L) - .setScriptPatchVersion("patch-2") - .setRuntimeFlagsJson("{}") - .setGenerationConfigRevision("genrev-12") - .setVersionStateEpoch(78L) - .setReleaseBundleId(78L) - .setPublishedReleaseBundleRef("prb:42:12:78") - .build()) - .build()); when(gameDesignClient.getPublishedReleaseBundle(42L, 11L)) .thenReturn( net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleResponse.newBuilder() @@ -362,23 +326,20 @@ void setUp() throws Exception { } @Test - void startSessionRollsBackWhenStatePropagationFails() { - doThrow(new IllegalStateException("state propagation failed")) - .when(sessionStateService) - .saveState(any()); - + void legacyNumericStartIsDeniedBeforeStateOrWorldMutation() { assertThatThrownBy( () -> service.startSession(new StartSessionRequest(42L, 7L, "cp-1", OWNER_ACCOUNT_UUID))) - .isInstanceOf(IllegalStateException.class) - .hasMessage("state propagation failed"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED"); assertThat(repository.findAll()).isEmpty(); - verify(sessionStateService).saveState(any()); + verifyNoInteractions(sessionStateService, gameDesignClient, worldManagementClient); } @Test void stopSessionRollsBackWhenStatePropagationFails() { + // This direct retained-row fixture exercises stop independently of the denied numeric start. GameInstance instance = new GameInstance(); instance.setTenantId(42L); instance.setRuntimeVersion("1.0.0"); @@ -405,6 +366,7 @@ void stopSessionRollsBackWhenStatePropagationFails() { @Test void restartSessionRollsBackWhenStatePropagationFails() { + // This direct retained-row fixture exercises restart independently of the denied numeric start. GameInstance instance = new GameInstance(); instance.setTenantId(42L); instance.setRuntimeVersion("1.0.0"); @@ -435,7 +397,8 @@ void restartSessionRollsBackWhenStatePropagationFails() { } @Test - void replacingExistingSessionRestoresPriorRunningSessionWhenNewStartFails() { + void legacyNumericReplacementLeavesRetainedSessionUntouched() { + // The row is seeded as retained state; this test proves only that legacy replacement is denied. GameInstance existing = new GameInstance(); existing.setTenantId(42L); existing.setRuntimeVersion("1.0.0"); @@ -447,16 +410,12 @@ void replacingExistingSessionRestoresPriorRunningSessionWhenNewStartFails() { existing = repository.saveAndFlush(existing); long existingId = existing.getId(); - doThrow(new IllegalStateException("state propagation failed")) - .when(sessionStateService) - .saveState(any()); - assertThatThrownBy( () -> service.startSession( new StartSessionRequest(42L, 7L, "cp-2", OWNER_ACCOUNT_UUID), true)) - .isInstanceOf(IllegalStateException.class) - .hasMessage("state propagation failed"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED"); assertThat(repository.findAll()).hasSize(1); GameInstance restored = repository.findById(existingId).orElseThrow(); @@ -466,10 +425,12 @@ void replacingExistingSessionRestoresPriorRunningSessionWhenNewStartFails() { assertThat(restored.getScriptPinEpoch()).isEqualTo(1L); assertThat(restored.getScriptPatchPinnedControlPlaneRequestId()).isEqualTo("pin-request-1"); assertThat(restored.getOwnerAccountId()).isEqualTo(OWNER_ACCOUNT_UUID); + verifyNoInteractions(sessionStateService, gameDesignClient, worldManagementClient); } @Test - void replacingExistingSessionTerminatesPriorWorldBeforeFinalizingReplacement() { + void legacyNumericReplacementDoesNotTerminateRetainedWorld() { + // No World lifecycle call is expected until a canonical bound replacement path exists. GameInstance existing = new GameInstance(); existing.setTenantId(42L); existing.setRuntimeVersion("1.0.0"); @@ -481,15 +442,16 @@ void replacingExistingSessionTerminatesPriorWorldBeforeFinalizingReplacement() { existing = repository.saveAndFlush(existing); long existingId = existing.getId(); - GameInstanceDto started = - service.startSession(new StartSessionRequest(42L, 7L, "cp-2", OWNER_ACCOUNT_UUID), true); + assertThatThrownBy( + () -> + service.startSession( + new StartSessionRequest(42L, 7L, "cp-2", OWNER_ACCOUNT_UUID), true)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED"); - assertThat(started.status()).isEqualTo("RUNNING"); assertThat(repository.findById(existingId)).isPresent(); - assertThat(repository.findById(existingId).orElseThrow().getStatus()).isEqualTo("STOPPED"); - verify(worldManagementClient).getWorldInstanceLifecycle(42L, existingId); - verify(worldManagementClient) - .terminateWorldInstance(anyLong(), eq(existingId), anyLong(), any(), any()); + assertThat(repository.findById(existingId).orElseThrow().getStatus()).isEqualTo("RUNNING"); + verifyNoInteractions(sessionStateService, gameDesignClient, worldManagementClient); } @TestConfiguration 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 9f6e32aa16..b24181aded 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 @@ -6,18 +6,16 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; -import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.util.HashMap; import java.util.List; @@ -25,9 +23,6 @@ import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; -import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleResponse; -import net.firedevops.firemud.gamedesign.v1.GetVersionAssetArtifactStateResponse; -import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorResponse; import net.firedevops.firemud.gamesession.client.GameDesignClient; import net.firedevops.firemud.gamesession.client.WorldManagementClient; import net.firedevops.firemud.gamesession.dto.GameInstanceDto; @@ -47,13 +42,14 @@ class GameInstanceServiceImplTest { private static final String OWNER_ACCOUNT_UUID = "123e4567-e89b-12d3-a456-426614174000"; + private static final String LEGACY_LAUNCH_DENIAL = + "AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED: canonical authored-world launch binding is required"; private GameInstanceRepository repository; private GameInstanceMapper mapper; private SessionStateService stateService; private GameDesignClient gameDesignClient; private WorldManagementClient worldManagementClient; - private SimpleMeterRegistry meterRegistry; private GameInstanceServiceImpl service; private Map store; private AtomicLong nextId; @@ -91,7 +87,6 @@ void setup() { stateService = mock(SessionStateService.class); gameDesignClient = mock(GameDesignClient.class); worldManagementClient = mock(WorldManagementClient.class); - meterRegistry = new SimpleMeterRegistry(); store = new HashMap<>(); nextId = new AtomicLong(10L); service = @@ -104,526 +99,61 @@ void setup() { worldManagementClient, null, null, - meterRegistry, + new SimpleMeterRegistry(), immediateTransactionOperations()); configureRepositoryPersistence(); configureMapper(); - configureLaunchPreflight(); - configureWorldActivation(); + configureWorldLifecycle(); } @Test - void startSessionSavesState() { - StartSessionRequest request = new StartSessionRequest(1L, 3L, "cp-1", OWNER_ACCOUNT_UUID); - - GameInstanceDto dto = service.startSession(request); + void legacyNumericStartIsDeniedBeforeDescriptorLookupOrMutation() { + IllegalArgumentException error = + assertThrows( + IllegalArgumentException.class, + () -> + service.startSession( + new StartSessionRequest(1L, 3L, "cp-legacy", OWNER_ACCOUNT_UUID))); - assertEquals("RUNNING", dto.status()); - 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()); - assertEquals("RUNNING", states.getAllValues().get(1).status()); - assertNull(store.get(10L).getScriptPinEpoch()); + assertEquals(LEGACY_LAUNCH_DENIAL, error.getMessage()); + assertEquals(0, store.size()); + verifyNoInteractions(repository, gameDesignClient, worldManagementClient, stateService); } @Test - void startSessionRejectsNonCanonicalOwnerBeforeDependenciesOrMutation() { + void startSessionStillRejectsNonCanonicalOwnerBeforeLaunchPreflight() { + IllegalArgumentException error = null; 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)); + error = + 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( - ResolveLaunchDescriptorResponse.newBuilder() - .setLaunchDescriptor( - net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.newBuilder() - .setLaunchDescriptorId("ld-pinned") - .setTenantId("1") - .setGameTemplateId(3L) - .setControlPlaneRequestId("cp-pinned") - .setVersionId(11L) - .setScriptPatchVersion("patch-1") - .setRuntimeFlagsJson("{}") - .setGenerationConfigRevision("genrev-11") - .setVersionStateEpoch(77L) - .setReleaseBundleId(77L) - .setPublishedReleaseBundleRef("prb:1:11:77") - .build()) - .build()) - .when(gameDesignClient) - .resolveLaunchDescriptor(any(Long.class), any(Long.class), any()); - - GameInstanceDto dto = - service.startSession(new StartSessionRequest(1L, 3L, "cp-pinned", OWNER_ACCOUNT_UUID)); - - assertNull(dto.scriptPatchVersion()); - assertNull(dto.scriptPinEpoch()); - assertNull(store.get(dto.id()).getScriptPinEpoch()); - ArgumentCaptor scriptPatchVersion = ArgumentCaptor.forClass(String.class); - verify(worldManagementClient) - .prepareWorldInstance( - eq(1L), - eq(dto.id()), - eq(3L), - eq("cp-pinned"), - eq("ld-pinned"), - eq(11L), - scriptPatchVersion.capture(), - eq("{}"), - eq("genrev-11"), - eq(77L), - eq("prb:1:11:77"), - eq(77L), - org.mockito.ArgumentMatchers.isNull()); - assertNull(scriptPatchVersion.getValue()); - } - - @Test - void startSessionDoesNotCompensateWhenStartedMetricFails() { - MeterRegistry failingMeterRegistry = mock(MeterRegistry.class); - when(failingMeterRegistry.counter("game_sessions_started_total")) - .thenThrow(new IllegalStateException("metrics unavailable")); - service = - new GameInstanceServiceImpl( - repository, - mapper, - stateService, - gameDesignClient, - null, - worldManagementClient, - null, - null, - failingMeterRegistry, - immediateTransactionOperations()); - - StartSessionRequest request = - new StartSessionRequest(1L, 3L, "cp-metric-failure", OWNER_ACCOUNT_UUID); - - GameInstanceDto dto = service.startSession(request); - - assertEquals("RUNNING", dto.status()); - assertEquals("RUNNING", store.get(10L).getStatus()); - verify(stateService, never()).deleteState(1L, 10L); - } - - @Test - void startSessionQuarantinesOwnerWhenWorldActivationFails() { - 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 - .newBuilder() - .setError( - net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() - .setCode("WORLD_ACTIVATION_FAILED") - .setMessage("activation failed") - .build()) - .build()); - - assertThrows(IllegalStateException.class, () -> service.startSession(request)); - - ArgumentCaptor states = ArgumentCaptor.forClass(GameInstanceDto.class); - verify(stateService).saveState(states.capture()); - assertEquals("STARTING", states.getValue().status()); - verify(stateService, never()).deleteState(1L, 10L); - verify(worldManagementClient, never()) - .failPreparedWorldInstance(anyLong(), anyLong(), anyLong(), any()); - verify(repository, never()).deleteById(10L); - assertEquals("STARTING", store.get(10L).getStatus()); - } - - @Test - void startSessionQuarantinesOwnerAfterAmbiguousWorldActivationResponse() { - 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")); - - assertThrows(IllegalStateException.class, () -> service.startSession(request)); - - verify(stateService).saveState(any(GameInstanceDto.class)); - verify(stateService, never()).deleteState(1L, 10L); - verify(worldManagementClient, never()) - .failPreparedWorldInstance(anyLong(), anyLong(), anyLong(), any()); - verify(repository, never()).deleteById(10L); - assertEquals("STARTING", store.get(10L).getStatus()); - } - - @Test - void startSessionQuarantinesOwnerWhenRuntimeStateSaveFailsAfterActivation() { - StartSessionRequest request = - new StartSessionRequest(1L, 3L, "cp-runtime-save-failure", OWNER_ACCOUNT_UUID); - AtomicInteger saveCount = new AtomicInteger(); - doAnswer( - invocation -> { - if (saveCount.incrementAndGet() == 2) { - throw new IllegalStateException("redis down"); - } - return null; - }) - .when(stateService) - .saveState(any(GameInstanceDto.class)); - - assertThrows(IllegalStateException.class, () -> service.startSession(request)); - - verify(worldManagementClient).activatePreparedWorldInstance(anyLong(), anyLong(), anyLong()); - ArgumentCaptor states = ArgumentCaptor.forClass(GameInstanceDto.class); - verify(stateService, times(3)).saveState(states.capture()); - assertEquals( - List.of("STARTING", "RUNNING", "STARTING"), - states.getAllValues().stream().map(GameInstanceDto::status).toList()); - verify(stateService, never()).deleteState(1L, 10L); - verify(worldManagementClient, never()) - .failPreparedWorldInstance(anyLong(), anyLong(), anyLong(), any()); - verify(repository, never()).deleteById(10L); - assertEquals("STARTING", store.get(10L).getStatus()); - } - - @Test - void startSessionQuarantinesOwnerWhenLocalFinalizationFailsAfterActivation() { - StartSessionRequest request = - new StartSessionRequest(1L, 3L, "cp-finalization-failure", OWNER_ACCOUNT_UUID); - doThrow(new IllegalStateException("local finalization failed")) - .when(mapper) - .toDto(any(GameInstance.class)); - - assertThrows(IllegalStateException.class, () -> service.startSession(request)); - - verify(worldManagementClient).activatePreparedWorldInstance(anyLong(), anyLong(), anyLong()); - ArgumentCaptor states = ArgumentCaptor.forClass(GameInstanceDto.class); - verify(stateService, times(3)).saveState(states.capture()); - assertEquals( - List.of("STARTING", "RUNNING", "STARTING"), - states.getAllValues().stream().map(GameInstanceDto::status).toList()); - verify(stateService, never()).deleteState(1L, 10L); - verify(worldManagementClient, never()) - .failPreparedWorldInstance(anyLong(), anyLong(), anyLong(), any()); - verify(repository, never()).deleteById(10L); - assertEquals("STARTING", store.get(10L).getStatus()); - } - - @Test - void startSessionFailsWhenWorldPreparationFails() { - StartSessionRequest request = new StartSessionRequest(1L, 3L, "cp-6", OWNER_ACCOUNT_UUID); - when(worldManagementClient.prepareWorldInstance( - anyLong(), - anyLong(), - anyLong(), - anyString(), - anyString(), - anyLong(), - any(), - any(), - anyString(), - anyLong(), - anyString(), - anyLong(), - any())) - .thenReturn( - net.firedevops.firemud.worldmanagement.v1.PrepareWorldInstanceResponse.newBuilder() - .setError( - net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() - .setCode("WORLD_UNAVAILABLE") - .setMessage("world unavailable") - .build()) - .build()); - - assertThrows(IllegalStateException.class, () -> service.startSession(request)); - - verify(stateService, never()).saveState(any()); + assertEquals("ownerAccountId must be a canonical non-nil UUID", error.getMessage()); assertEquals(0, store.size()); - verify(worldManagementClient, never()) - .failPreparedWorldInstance(anyLong(), anyLong(), anyLong(), any()); - } - - @Test - void startSessionUsesPreparationAuthorityErrorWhenPreparationTransportFails() { - StartSessionRequest request = - new StartSessionRequest(1L, 3L, "cp-preparation-timeout", OWNER_ACCOUNT_UUID); - when(worldManagementClient.prepareWorldInstance( - anyLong(), - anyLong(), - anyLong(), - anyString(), - anyString(), - anyLong(), - any(), - any(), - anyString(), - anyLong(), - anyString(), - anyLong(), - any())) - .thenThrow(new IllegalStateException("preparation response timed out")); - - IllegalStateException error = - assertThrows(IllegalStateException.class, () -> service.startSession(request)); - - assertEquals("world preparation authority unavailable", error.getMessage()); - assertEquals("preparation response timed out", error.getCause().getMessage()); - verify(stateService, never()).saveState(any()); - verify(worldManagementClient, never()) - .failPreparedWorldInstance(anyLong(), anyLong(), anyLong(), any()); + verifyNoInteractions(repository, gameDesignClient, worldManagementClient, stateService); } @Test - void startSessionPreservesStartFailureWhenPreparedWorldCleanupTransportFails() { - 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")); - - IllegalStateException error = - assertThrows(IllegalStateException.class, () -> service.startSession(request)); - - assertEquals("state save failed", error.getMessage()); - verify(worldManagementClient) - .failPreparedWorldInstance( - eq(1L), eq(10L), eq(1L), eq("session start failed before admission opened")); - } - - @Test - void startSessionFailsClosedWhenWorldPreparationResponseIsNull() { - StartSessionRequest request = - new StartSessionRequest(1L, 3L, "cp-null-world", OWNER_ACCOUNT_UUID); - when(worldManagementClient.prepareWorldInstance( - anyLong(), - anyLong(), - anyLong(), - anyString(), - anyString(), - anyLong(), - any(), - any(), - anyString(), - anyLong(), - anyString(), - anyLong(), - any())) - .thenReturn(null); - - IllegalStateException error = - assertThrows(IllegalStateException.class, () -> service.startSession(request)); - - assertEquals("WORLD_AUTHORITY_MALFORMED: response was null", error.getMessage()); - } - - @Test - void startSessionFailsClosedWhenWorldPreparationOmitsSnapshotAndError() { - StartSessionRequest request = - new StartSessionRequest(1L, 3L, "cp-empty-world", OWNER_ACCOUNT_UUID); - when(worldManagementClient.prepareWorldInstance( - anyLong(), - anyLong(), - anyLong(), - anyString(), - anyString(), - anyLong(), - any(), - any(), - anyString(), - anyLong(), - anyString(), - anyLong(), - any())) - .thenReturn( - net.firedevops.firemud.worldmanagement.v1.PrepareWorldInstanceResponse - .getDefaultInstance()); + void legacyNumericReplacementIsDeniedWithoutChangingRetainedSession() { + persistExisting(7L, 1L, "v1", null, OWNER_ACCOUNT_UUID, "RUNNING"); - IllegalStateException error = - assertThrows(IllegalStateException.class, () -> service.startSession(request)); - - assertEquals( - "WORLD_AUTHORITY_MALFORMED: response omitted lifecycle snapshot", error.getMessage()); - } - - @Test - void startSessionFailsClosedWhenWorldPreparationScopeDoesNotMatch() { - StartSessionRequest request = - new StartSessionRequest(1L, 3L, "cp-mismatched-world", OWNER_ACCOUNT_UUID); - when(worldManagementClient.prepareWorldInstance( - anyLong(), - anyLong(), - anyLong(), - anyString(), - anyString(), - anyLong(), - any(), - any(), - anyString(), - anyLong(), - anyString(), - anyLong(), - any())) - .thenReturn(worldPreparationSnapshot("2", "10", 1L)); - - IllegalStateException error = - assertThrows(IllegalStateException.class, () -> service.startSession(request)); - - assertEquals( - "WORLD_AUTHORITY_SCOPE_MISMATCH: lifecycle response does not match the requested instance", - error.getMessage()); - } - - @Test - void startSessionFailsClosedWhenWorldPreparationEpochIsNotPositive() { - StartSessionRequest request = - new StartSessionRequest(1L, 3L, "cp-zero-world-epoch", OWNER_ACCOUNT_UUID); - when(worldManagementClient.prepareWorldInstance( - anyLong(), - anyLong(), - anyLong(), - anyString(), - anyString(), - anyLong(), - any(), - any(), - anyString(), - anyLong(), - anyString(), - anyLong(), - any())) - .thenReturn(worldPreparationSnapshot("1", "10", 0L)); - - IllegalStateException error = - assertThrows(IllegalStateException.class, () -> service.startSession(request)); - - assertEquals("WORLD_AUTHORITY_MALFORMED: lifecycle epoch must be positive", error.getMessage()); - } - - @ParameterizedTest - @org.junit.jupiter.params.provider.CsvSource({ - "not-a-number,10,tenantId", - "1,not-a-number,gameInstanceId" - }) - void startSessionPrefixesMalformedWorldIdentifiersAndRetainsCause( - String tenantId, String gameInstanceId, String fieldName) { - StartSessionRequest request = - new StartSessionRequest(1L, 3L, "cp-malformed-world-id", OWNER_ACCOUNT_UUID); - when(worldManagementClient.prepareWorldInstance( - anyLong(), - anyLong(), - anyLong(), - anyString(), - anyString(), - anyLong(), - any(), - any(), - anyString(), - anyLong(), - anyString(), - anyLong(), - any())) - .thenReturn(worldPreparationSnapshot(tenantId, gameInstanceId, 1L)); - - IllegalStateException error = - assertThrows(IllegalStateException.class, () -> service.startSession(request)); - - assertEquals( - "WORLD_AUTHORITY_MALFORMED: " + fieldName + " must be numeric", error.getMessage()); - assertEquals(fieldName + " must be numeric", error.getCause().getMessage()); - } - - @Test - void startSessionFailsClosedWhenWorldPreparationStatusIsAlreadyActive() { - StartSessionRequest request = - new StartSessionRequest(1L, 3L, "cp-active-world", OWNER_ACCOUNT_UUID); - doReturn( - net.firedevops.firemud.worldmanagement.v1.PrepareWorldInstanceResponse.newBuilder() - .setWorldInstance( - net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot - .newBuilder() - .setTenantId("1") - .setGameInstanceId("10") - .setLifecycleEpoch(1L) - .setStatus( - net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleStatus - .WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE) - .build()) - .build()) - .when(worldManagementClient) - .prepareWorldInstance( - anyLong(), - anyLong(), - anyLong(), - anyString(), - anyString(), - anyLong(), - any(), - any(), - anyString(), - anyLong(), - anyString(), - anyLong(), - any()); - - IllegalStateException error = - assertThrows(IllegalStateException.class, () -> service.startSession(request)); - - assertEquals( - "WORLD_AUTHORITY_MALFORMED: lifecycle response has unexpected status", error.getMessage()); - verify(worldManagementClient, never()) - .activatePreparedWorldInstance(anyLong(), anyLong(), anyLong()); - verify(stateService, never()).saveState(any()); - } - - @ParameterizedTest - @EnumSource( - value = WorldInstanceLifecycleStatus.class, - names = { - "WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING", - "WORLD_INSTANCE_LIFECYCLE_STATUS_FAILED_PRE_ACTIVATION" - }) - void startSessionWithReplacementRejectsKnownNonActiveWorldLifecycle( - WorldInstanceLifecycleStatus status) { - StartSessionRequest request = - 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)); - - IllegalStateException error = - assertThrows(IllegalStateException.class, () -> service.startSession(request, true)); + IllegalArgumentException error = + assertThrows( + IllegalArgumentException.class, + () -> + service.startSession( + new StartSessionRequest(1L, 3L, "cp-replace", OWNER_ACCOUNT_UUID), true)); - assertEquals("WORLD_INSTANCE_LIFECYCLE_NOT_ACTIVE: instance is not ACTIVE", error.getMessage()); + assertEquals(LEGACY_LAUNCH_DENIAL, error.getMessage()); assertEquals("RUNNING", store.get(7L).getStatus()); - verify(worldManagementClient, never()) - .terminateWorldInstance(anyLong(), anyLong(), anyLong(), anyString(), anyString()); - } - - @Test - void startSessionFailsClosedWhenWorldActivationOmitsSnapshotAndError() { - 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 - .getDefaultInstance()); - - IllegalStateException error = - assertThrows(IllegalStateException.class, () -> service.startSession(request)); - - assertEquals( - "WORLD_AUTHORITY_MALFORMED: response omitted lifecycle snapshot", error.getMessage()); + assertEquals(1, store.size()); + verifyNoInteractions(repository, gameDesignClient, worldManagementClient, stateService); } @Test @@ -642,47 +172,6 @@ void stopSessionFailsClosedWhenWorldTerminationOmitsSnapshotAndError() { "WORLD_AUTHORITY_MALFORMED: response omitted lifecycle snapshot", error.getMessage()); } - @Test - void startSessionStopsExistingRunningSessionOnlyWithinTenantAndOwner() { - 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, OWNER_ACCOUNT_UUID, "RUNNING"); - verify(stateService, times(2)).saveState(any(GameInstanceDto.class)); - verify(stateService).deleteState(2L, 7L); - verify(worldManagementClient).getWorldInstanceLifecycle(2L, 7L); - verify(worldManagementClient) - .terminateWorldInstance( - anyLong(), anyLong(), anyLong(), anyString(), eq("session replacement requested")); - ArgumentCaptor savedInstances = ArgumentCaptor.forClass(GameInstance.class); - verify(repository, times(4)).save(savedInstances.capture()); - assertEquals( - 1, - savedInstances.getAllValues().stream() - .filter(instance -> Long.valueOf(7L).equals(instance.getId())) - .filter(instance -> "STOPPED".equals(instance.getStatus())) - .count()); - assertEquals("STOPPED", store.get(7L).getStatus()); - assertEquals("RUNNING", store.get(dto.id()).getStatus()); - } - - @Test - void startSessionWithoutReplacementLeavesExistingSessionRunning() { - StartSessionRequest request = new StartSessionRequest(2L, 3L, "cp-3", OWNER_ACCOUNT_UUID); - - service.startSession(request, false); - - 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, OWNER_ACCOUNT_UUID, "RUNNING"); @@ -766,236 +255,6 @@ void stopSessionKeepsSessionStoppedWhenFinalizationFailsAfterWorldTermination() assertEquals("STOPPED", store.get(10L).getStatus()); } - @Test - void startSessionFailsFastWhenStateSaveFails() { - 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)); - - verify(stateService).saveState(any()); - verify(stateService, never()).deleteState(1L, 10L); - assertEquals(0, store.size()); - } - - @Test - void startSessionWithReplacementRestoresExistingRunningStateWhenNewStateSaveFails() { - StartSessionRequest request = new StartSessionRequest(2L, 3L, "cp-5", OWNER_ACCOUNT_UUID); - GameInstance existing = - 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( - invocation -> { - if (saveCount.incrementAndGet() == 1) { - throw new IllegalStateException("redis down"); - } - return null; - }) - .when(stateService) - .saveState(any()); - - assertThrows(IllegalStateException.class, () -> service.startSession(request, true)); - - assertEquals(1, store.size()); - assertEquals("RUNNING", store.get(7L).getStatus()); - assertEquals("patch-1", store.get(7L).getScriptPatchVersion()); - assertEquals(100L, store.get(7L).getScriptPatchBaseVersionId()); - assertEquals(3L, store.get(7L).getScriptPinEpoch()); - assertEquals("pin-request-1", store.get(7L).getScriptPatchPinnedControlPlaneRequestId()); - verify(stateService, never()).deleteState(2L, 7L); - ArgumentCaptor states = ArgumentCaptor.forClass(GameInstanceDto.class); - verify(stateService, times(2)).saveState(states.capture()); - assertEquals(10L, states.getAllValues().get(0).id()); - assertEquals(7L, states.getAllValues().get(1).id()); - assertEquals("RUNNING", states.getAllValues().get(1).status()); - assertEquals(100L, states.getAllValues().get(1).scriptPatchBaseVersionId()); - verify(worldManagementClient, never()).getWorldInstanceLifecycle(anyLong(), anyLong()); - } - - @Test - void startSessionWithReplacementLeavesExistingSessionStoppingWhenTerminationFails() { - 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())) - .thenReturn( - net.firedevops.firemud.worldmanagement.v1.TerminateWorldInstanceResponse.newBuilder() - .setError( - net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() - .setCode("ENTITY_CLEANUP_FAILED") - .setMessage("cleanup failed") - .build()) - .build()); - - assertThrows(IllegalStateException.class, () -> service.startSession(request, true)); - - assertEquals(1, store.size()); - assertEquals("STOPPING", store.get(7L).getStatus()); - verify(stateService).deleteState(2L, 7L); - verify(stateService).deleteState(2L, 10L); - ArgumentCaptor states = ArgumentCaptor.forClass(GameInstanceDto.class); - verify(stateService, times(1)).saveState(states.capture()); - assertEquals(10L, states.getValue().id()); - } - - @Test - void startSessionWithReplacementFinalizesAlreadyTerminatedExistingSession() { - 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( - worldLifecycleSnapshot( - "2", - "7", - 3L, - WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_TERMINATED)); - - GameInstanceDto dto = service.startSession(request, true); - - assertEquals("STOPPED", store.get(7L).getStatus()); - assertEquals("RUNNING", dto.status()); - verify(worldManagementClient, never()) - .terminateWorldInstance(anyLong(), anyLong(), anyLong(), anyString(), anyString()); - } - - @Test - void startSessionWithReplacementDoesNotRestoreAlreadyTerminatedExistingSessionOnFailure() { - StartSessionRequest request = - 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( - worldLifecycleSnapshot( - "2", - "7", - 3L, - WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_TERMINATED)); - when(worldManagementClient.activatePreparedWorldInstance(anyLong(), anyLong(), anyLong())) - .thenReturn( - net.firedevops.firemud.worldmanagement.v1.ActivatePreparedWorldInstanceResponse - .newBuilder() - .setError( - net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() - .setCode("WORLD_ACTIVATION_FAILED") - .setMessage("activation failed") - .build()) - .build()); - - assertThrows(IllegalStateException.class, () -> service.startSession(request, true)); - - assertEquals("STOPPED", store.get(7L).getStatus()); - verify(stateService).deleteState(2L, 7L); - verify(stateService, never()).saveState(argThat(state -> state.id() == 7L)); - } - - @Test - void startSessionWithReplacementLeavesExistingSessionStoppingWhenTerminationIsInProgress() { - StartSessionRequest request = - 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( - worldLifecycleSnapshot( - "2", - "7", - 3L, - WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_TERMINATING)); - - IllegalStateException error = - assertThrows(IllegalStateException.class, () -> service.startSession(request, true)); - - assertEquals( - "WORLD_TERMINATION_IN_PROGRESS: replaced session is already terminating", - error.getMessage()); - assertEquals("STOPPING", store.get(7L).getStatus()); - assertEquals(1, store.size()); - verify(stateService).deleteState(2L, 10L); - verify(stateService, never()).saveState(argThat(state -> state.id() == 7L)); - verify(worldManagementClient, never()) - .terminateWorldInstance(anyLong(), anyLong(), anyLong(), anyString(), anyString()); - } - - @Test - void startSessionWithReplacementRestoresExistingStateWhenWorldLifecyclePreflightFails() { - StartSessionRequest request = - 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( - net.firedevops.firemud.worldmanagement.v1.GetWorldInstanceLifecycleResponse.newBuilder() - .setError( - net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() - .setCode("WORLD_LIFECYCLE_UNAVAILABLE") - .setMessage("lifecycle read failed") - .build()) - .build()); - - assertThrows(IllegalStateException.class, () -> service.startSession(request, true)); - - assertEquals(1, store.size()); - assertEquals("RUNNING", store.get(7L).getStatus()); - verify(stateService).deleteState(2L, 7L); - verify(stateService).deleteState(2L, 10L); - ArgumentCaptor states = ArgumentCaptor.forClass(GameInstanceDto.class); - verify(stateService, times(2)).saveState(states.capture()); - assertEquals(10L, states.getAllValues().get(0).id()); - assertEquals(7L, states.getAllValues().get(1).id()); - assertEquals("RUNNING", states.getAllValues().get(1).status()); - verify(worldManagementClient).getWorldInstanceLifecycle(2L, 7L); - verify(worldManagementClient, never()) - .terminateWorldInstance(anyLong(), anyLong(), anyLong(), anyString(), anyString()); - verify(worldManagementClient) - .failPreparedWorldInstance(anyLong(), anyLong(), anyLong(), anyString()); - verify(repository).deleteById(10L); - } - - @Test - void startSessionDoesNotResurrectReplacedSessionWhenActivationFails() { - 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 - .newBuilder() - .setError( - net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() - .setCode("WORLD_ACTIVATION_FAILED") - .setMessage("activation failed") - .build()) - .build()); - - assertThrows(IllegalStateException.class, () -> service.startSession(request, true)); - - assertEquals("STOPPED", store.get(7L).getStatus()); - assertEquals("STARTING", store.get(10L).getStatus()); - verify(stateService).deleteState(2L, 7L); - verify(stateService, times(1)).saveState(any(GameInstanceDto.class)); - verify(worldManagementClient, never()) - .failPreparedWorldInstance(anyLong(), anyLong(), anyLong(), any()); - verify(repository, never()).deleteById(10L); - } - @Test void stopSessionFailsFastWhenStateDeleteFails() { GameInstance retained = persistExisting(10L, 1L, "v1", null, OWNER_ACCOUNT_UUID, "RUNNING"); @@ -1084,13 +343,12 @@ void stopSessionLeavesStoppingStateWhenWorldTerminationIsInProgress() { .thenReturn( net.firedevops.firemud.worldmanagement.v1.GetWorldInstanceLifecycleResponse.newBuilder() .setWorldInstance( - net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot - .newBuilder() + WorldInstanceLifecycleSnapshot.newBuilder() .setTenantId("1") .setGameInstanceId("10") .setLifecycleEpoch(2L) .setStatus( - net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleStatus + WorldInstanceLifecycleStatus .WORLD_INSTANCE_LIFECYCLE_STATUS_TERMINATING) .build()) .build()); @@ -1129,6 +387,19 @@ void stopSessionRejectsKnownNonActiveWorldLifecycle(WorldInstanceLifecycleStatus .terminateWorldInstance(anyLong(), anyLong(), anyLong(), anyString(), anyString()); } + @Test + void persistExistingPreservesScriptPinOwnerRequestIdInCopiedTuple() { + GameInstance existing = + persistExisting( + 7L, 2L, "v1", "patch-1", OWNER_ACCOUNT_UUID, "RUNNING", 100L, 3L, "pin-request-1"); + + assertEquals(100L, existing.getScriptPatchBaseVersionId()); + assertEquals(3L, existing.getScriptPinEpoch()); + assertEquals("pin-request-1", existing.getScriptPatchPinnedControlPlaneRequestId()); + assertEquals(100L, store.get(7L).getScriptPatchBaseVersionId()); + assertEquals("pin-request-1", store.get(7L).getScriptPatchPinnedControlPlaneRequestId()); + } + private void configureRepositoryPersistence() { when(repository.save(any(GameInstance.class))) .thenAnswer( @@ -1147,20 +418,6 @@ private void configureRepositoryPersistence() { GameInstance stored = store.get(id); return stored == null ? Optional.empty() : Optional.of(copyOf(stored)); }); - when(repository.findFirstByTenantIdAndOwnerAccountIdAndStatus( - any(Long.class), anyString(), any())) - .thenAnswer( - invocation -> { - Long tenantId = invocation.getArgument(0); - String ownerAccountId = invocation.getArgument(1); - String status = invocation.getArgument(2); - return store.values().stream() - .filter(instance -> tenantId.equals(instance.getTenantId())) - .filter(instance -> ownerAccountId.equals(instance.getOwnerAccountId())) - .filter(instance -> status.equals(instance.getStatus())) - .findFirst() - .map(GameInstanceServiceImplTest::copyOf); - }); org.mockito.Mockito.doAnswer( invocation -> { Long id = invocation.getArgument(0); @@ -1196,238 +453,6 @@ private GameInstanceDto configureMappedDto(GameInstance entity) { entity.getStatus()); } - private void configureLaunchPreflight() { - when(gameDesignClient.resolveLaunchDescriptor(any(Long.class), any(Long.class), any())) - .thenAnswer( - invocation -> - ResolveLaunchDescriptorResponse.newBuilder() - .setLaunchDescriptor( - net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.newBuilder() - .setLaunchDescriptorId("ld-" + invocation.getArgument(2, String.class)) - .setTenantId(Long.toString(invocation.getArgument(0, Long.class))) - .setGameTemplateId(invocation.getArgument(1, Long.class)) - .setControlPlaneRequestId(invocation.getArgument(2, String.class)) - .setVersionId(11L) - .setRuntimeFlagsJson("{}") - .setGenerationConfigRevision("genrev-11") - .setVersionStateEpoch(77L) - .setReleaseBundleId(77L) - .setPublishedReleaseBundleRef( - "prb:" + invocation.getArgument(0, Long.class) + ":11:77") - .build()) - .build()); - when(gameDesignClient.getPublishedReleaseBundle(any(Long.class), any(Long.class))) - .thenReturn( - GetPublishedReleaseBundleResponse.newBuilder() - .setBundle( - net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle.newBuilder() - .setId(77L) - .setVersionId(11L) - .setAttestationSchemaVersion("v1") - .setManifestHash("manifest-11") - .addRequiredManifestAssetKeys("manifest.json") - .setGenerationConfigRevision("genrev-11") - .build()) - .build()); - when(gameDesignClient.getVersionAssetArtifactState(any(Long.class), any(Long.class))) - .thenReturn( - GetVersionAssetArtifactStateResponse.newBuilder() - .setArtifactState( - net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState.newBuilder() - .setTenantId("1") - .setVersionId(11L) - .setArtifactState( - net.firedevops.firemud.gamedesign.v1.ArtifactState - .ARTIFACT_STATE_PUBLISHED) - .setStateEpoch(2L) - .setManifestHash("manifest-11") - .addExportedManifestAssetKeys("manifest.json") - .build()) - .build()); - when(gameDesignClient.getVersionState(any(Long.class), any(Long.class))) - .thenReturn( - net.firedevops.firemud.gamedesign.v1.GetVersionStateResponse.newBuilder() - .setVersionState( - net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot.newBuilder() - .setTenantId("1") - .setVersionId(11L) - .setVersionState( - net.firedevops.firemud.gamedesign.v1.VersionLifecycleState - .VERSION_LIFECYCLE_STATE_PUBLISHED) - .setVersionStateEpoch(77L) - .setUpdatedAt("2026-04-15T10:00:00") - .build()) - .build()); - } - - @Test - void startSessionFailsWhenPublishedAssetProofDoesNotMatchReleaseBundle() { - StartSessionRequest request = new StartSessionRequest(1L, 3L, "cp-proof", OWNER_ACCOUNT_UUID); - when(gameDesignClient.getVersionAssetArtifactState(any(Long.class), any(Long.class))) - .thenReturn( - GetVersionAssetArtifactStateResponse.newBuilder() - .setArtifactState( - net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState.newBuilder() - .setTenantId("1") - .setVersionId(11L) - .setArtifactState( - net.firedevops.firemud.gamedesign.v1.ArtifactState - .ARTIFACT_STATE_PUBLISHED) - .setStateEpoch(2L) - .setManifestHash("different-manifest") - .addExportedManifestAssetKeys("manifest.json") - .build()) - .build()); - - IllegalArgumentException error = - assertThrows(IllegalArgumentException.class, () -> service.startSession(request)); - - assertEquals( - "RELEASE_ATTESTATION_MISMATCH: published asset artifact state does not match the release" - + " bundle", - error.getMessage()); - } - - @Test - void startSessionRejectsNonPositiveLaunchDescriptorTenantIdBeforeWorldPreparation() { - StartSessionRequest request = - new StartSessionRequest(1L, 3L, "cp-launch-tenant", OWNER_ACCOUNT_UUID); - doReturn( - ResolveLaunchDescriptorResponse.newBuilder() - .setLaunchDescriptor( - net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.newBuilder() - .setLaunchDescriptorId("ld-cp-launch-tenant") - .setTenantId("0") - .setGameTemplateId(3L) - .setControlPlaneRequestId("cp-launch-tenant") - .setVersionId(11L) - .setRuntimeFlagsJson("{}") - .setGenerationConfigRevision("genrev-11") - .setVersionStateEpoch(77L) - .setReleaseBundleId(77L) - .setPublishedReleaseBundleRef("prb:1:11:77") - .build()) - .build()) - .when(gameDesignClient) - .resolveLaunchDescriptor(anyLong(), anyLong(), anyString()); - - IllegalArgumentException error = - assertThrows(IllegalArgumentException.class, () -> service.startSession(request)); - - assertEquals("tenantId must be positive", error.getMessage()); - verify(worldManagementClient, never()) - .prepareWorldInstance( - anyLong(), - anyLong(), - anyLong(), - anyString(), - anyString(), - anyLong(), - any(), - any(), - anyString(), - anyLong(), - anyString(), - anyLong(), - any()); - verify(stateService, never()).saveState(any()); - } - - @Test - void startSessionFailsWhenReleaseBundleSchemaIsUnsupported() { - StartSessionRequest request = new StartSessionRequest(1L, 3L, "cp-schema", OWNER_ACCOUNT_UUID); - when(gameDesignClient.getPublishedReleaseBundle(any(Long.class), any(Long.class))) - .thenReturn( - GetPublishedReleaseBundleResponse.newBuilder() - .setBundle( - net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle.newBuilder() - .setId(77L) - .setVersionId(11L) - .setAttestationSchemaVersion("v999") - .setManifestHash("manifest-11") - .addRequiredManifestAssetKeys("manifest.json") - .setGenerationConfigRevision("genrev-11") - .build()) - .build()); - - IllegalArgumentException error = - assertThrows(IllegalArgumentException.class, () -> service.startSession(request)); - - assertEquals( - "SCHEMA_VERSION_UNSUPPORTED: unsupported published release bundle attestation schema v999", - error.getMessage()); - } - - @Test - void startSessionRejectsMalformedPreparedWorldInstanceGameInstanceIdBeforeActivation() { - StartSessionRequest request = new StartSessionRequest(1L, 3L, "cp-prep-id", OWNER_ACCOUNT_UUID); - doReturn( - net.firedevops.firemud.worldmanagement.v1.PrepareWorldInstanceResponse.newBuilder() - .setWorldInstance( - net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot - .newBuilder() - .setTenantId("1") - .setGameInstanceId("bad") - .setLifecycleEpoch(1L) - .setStatus( - net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleStatus - .WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING) - .build()) - .build()) - .when(worldManagementClient) - .prepareWorldInstance( - anyLong(), - anyLong(), - anyLong(), - anyString(), - anyString(), - anyLong(), - any(), - any(), - anyString(), - anyLong(), - anyString(), - anyLong(), - any()); - - IllegalStateException error = - assertThrows(IllegalStateException.class, () -> service.startSession(request)); - - assertEquals("WORLD_AUTHORITY_MALFORMED: gameInstanceId must be numeric", error.getMessage()); - assertEquals("gameInstanceId must be numeric", error.getCause().getMessage()); - verify(worldManagementClient, never()) - .activatePreparedWorldInstance(anyLong(), anyLong(), anyLong()); - verify(stateService, never()).saveState(any()); - } - - @Test - void persistExistingPreservesScriptPinOwnerRequestIdInCopiedTuple() { - GameInstance existing = - persistExisting( - 7L, 2L, "v1", "patch-1", OWNER_ACCOUNT_UUID, "RUNNING", 100L, 3L, "pin-request-1"); - - assertEquals(100L, existing.getScriptPatchBaseVersionId()); - assertEquals(3L, existing.getScriptPinEpoch()); - assertEquals("pin-request-1", existing.getScriptPatchPinnedControlPlaneRequestId()); - assertEquals(100L, store.get(7L).getScriptPatchBaseVersionId()); - assertEquals("pin-request-1", store.get(7L).getScriptPatchPinnedControlPlaneRequestId()); - } - - private static net.firedevops.firemud.worldmanagement.v1.PrepareWorldInstanceResponse - worldPreparationSnapshot(String tenantId, String gameInstanceId, long lifecycleEpoch) { - return net.firedevops.firemud.worldmanagement.v1.PrepareWorldInstanceResponse.newBuilder() - .setWorldInstance( - net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot.newBuilder() - .setTenantId(tenantId) - .setGameInstanceId(gameInstanceId) - .setLifecycleEpoch(lifecycleEpoch) - .setStatus( - net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleStatus - .WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING) - .build()) - .build(); - } - private static GetWorldInstanceLifecycleResponse worldLifecycleSnapshot( String tenantId, String gameInstanceId, @@ -1444,103 +469,15 @@ private static GetWorldInstanceLifecycleResponse worldLifecycleSnapshot( .build(); } - private void configureWorldActivation() { - when(worldManagementClient.prepareWorldInstance( - anyLong(), - anyLong(), - anyLong(), - anyString(), - anyString(), - anyLong(), - any(), - any(), - anyString(), - anyLong(), - anyString(), - anyLong(), - any())) - .thenAnswer( - invocation -> - net.firedevops.firemud.worldmanagement.v1.PrepareWorldInstanceResponse.newBuilder() - .setWorldInstance( - net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot - .newBuilder() - .setTenantId(Long.toString(invocation.getArgument(0, Long.class))) - .setGameInstanceId(Long.toString(invocation.getArgument(1, Long.class))) - .setGameTemplateId("3") - .setControlPlaneRequestId("cp") - .setLaunchDescriptorId("ld-cp") - .setVersionId("11") - .setReleaseBundleId("77") - .setGenerationConfigRevision("genrev-11") - .setPublishedReleaseBundleRef("prb:1:11:77") - .setVersionStateEpoch(77L) - .setLifecycleEpoch(1L) - .setStatus( - net.firedevops.firemud.worldmanagement.v1 - .WorldInstanceLifecycleStatus - .WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING) - .build()) - .build()); - when(worldManagementClient.activatePreparedWorldInstance(anyLong(), anyLong(), anyLong())) - .thenAnswer( - invocation -> - net.firedevops.firemud.worldmanagement.v1.ActivatePreparedWorldInstanceResponse - .newBuilder() - .setWorldInstance( - net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot - .newBuilder() - .setTenantId(Long.toString(invocation.getArgument(0, Long.class))) - .setGameInstanceId(Long.toString(invocation.getArgument(1, Long.class))) - .setGameTemplateId("3") - .setControlPlaneRequestId("cp") - .setLaunchDescriptorId("ld-cp") - .setVersionId("11") - .setReleaseBundleId("77") - .setGenerationConfigRevision("genrev-11") - .setPublishedReleaseBundleRef("prb:1:11:77") - .setVersionStateEpoch(77L) - .setLifecycleEpoch(2L) - .setStatus( - net.firedevops.firemud.worldmanagement.v1 - .WorldInstanceLifecycleStatus - .WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE) - .build()) - .build()); - when(worldManagementClient.failPreparedWorldInstance(anyLong(), anyLong(), anyLong(), any())) - .thenAnswer( - invocation -> - net.firedevops.firemud.worldmanagement.v1.FailPreparedWorldInstanceResponse - .newBuilder() - .setWorldInstance( - net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot - .newBuilder() - .setTenantId(Long.toString(invocation.getArgument(0, Long.class))) - .setGameInstanceId(Long.toString(invocation.getArgument(1, Long.class))) - .setLifecycleEpoch(2L) - .setStatus( - net.firedevops.firemud.worldmanagement.v1 - .WorldInstanceLifecycleStatus - .WORLD_INSTANCE_LIFECYCLE_STATUS_FAILED_PRE_ACTIVATION) - .build()) - .build()); + private void configureWorldLifecycle() { when(worldManagementClient.getWorldInstanceLifecycle(anyLong(), anyLong())) .thenAnswer( invocation -> - net.firedevops.firemud.worldmanagement.v1.GetWorldInstanceLifecycleResponse - .newBuilder() - .setWorldInstance( - net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot - .newBuilder() - .setTenantId(Long.toString(invocation.getArgument(0, Long.class))) - .setGameInstanceId(Long.toString(invocation.getArgument(1, Long.class))) - .setLifecycleEpoch(2L) - .setStatus( - net.firedevops.firemud.worldmanagement.v1 - .WorldInstanceLifecycleStatus - .WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE) - .build()) - .build()); + worldLifecycleSnapshot( + Long.toString(invocation.getArgument(0, Long.class)), + Long.toString(invocation.getArgument(1, Long.class)), + 2L, + WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE)); when(worldManagementClient.terminateWorldInstance( anyLong(), anyLong(), anyLong(), anyString(), anyString())) .thenAnswer( @@ -1548,14 +485,12 @@ private void configureWorldActivation() { net.firedevops.firemud.worldmanagement.v1.TerminateWorldInstanceResponse .newBuilder() .setWorldInstance( - net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot - .newBuilder() + WorldInstanceLifecycleSnapshot.newBuilder() .setTenantId(Long.toString(invocation.getArgument(0, Long.class))) .setGameInstanceId(Long.toString(invocation.getArgument(1, Long.class))) - .setLifecycleEpoch(4L) + .setLifecycleEpoch(3L) .setStatus( - net.firedevops.firemud.worldmanagement.v1 - .WorldInstanceLifecycleStatus + WorldInstanceLifecycleStatus .WORLD_INSTANCE_LIFECYCLE_STATUS_TERMINATED) .build()) .build()); @@ -1603,6 +538,8 @@ private GameInstance persistExisting( Long scriptPatchBaseVersionId, Long scriptPinEpoch, String scriptPatchPinnedControlPlaneRequestId) { + // Test-only retained-row fixture; this bypasses StartSession and proves retained-state APIs + // only. 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/service/impl/InstanceCutoverCompatibilityServiceImplTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InstanceCutoverCompatibilityServiceImplTest.java index 7613e3caba..4ead82aa41 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InstanceCutoverCompatibilityServiceImplTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InstanceCutoverCompatibilityServiceImplTest.java @@ -3,23 +3,20 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; -import java.util.Optional; import net.firedevops.firemud.gamesession.client.EntityManagementClient; import net.firedevops.firemud.gamesession.client.GameDesignClient; import net.firedevops.firemud.gamesession.client.WorldManagementClient; -import net.firedevops.firemud.gamesession.entity.GameInstance; import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; import org.junit.jupiter.api.Test; import org.mockito.Mockito; class InstanceCutoverCompatibilityServiceImplTest { @Test - void validateInstanceCutoverCompatibilityRejectsZeroSourceVersionIdBeforeDownstreamChecks() { + void validateInstanceCutoverCompatibilityDeniesLegacyNumericLaunchBeforeAnyLookup() { GameInstanceRepository repository = Mockito.mock(GameInstanceRepository.class); GameDesignClient gameDesignClient = Mockito.mock(GameDesignClient.class); WorldManagementClient worldManagementClient = Mockito.mock(WorldManagementClient.class); EntityManagementClient entityManagementClient = Mockito.mock(EntityManagementClient.class); - Mockito.when(repository.findById(7L)).thenReturn(Optional.of(sourceInstance(1L, null, 0L, 3L))); InstanceCutoverCompatibilityServiceImpl service = new InstanceCutoverCompatibilityServiceImpl( repository, gameDesignClient, worldManagementClient, entityManagementClient); @@ -29,60 +26,10 @@ void validateInstanceCutoverCompatibilityRejectsZeroSourceVersionIdBeforeDownstr IllegalArgumentException.class, () -> service.validateInstanceCutoverCompatibility(1L, 7L, 9L)); - assertEquals("versionId must be positive", error.getMessage()); - Mockito.verifyNoInteractions(gameDesignClient, worldManagementClient, entityManagementClient); - } - - @Test - void validateInstanceCutoverCompatibilityRejectsMalformedRuntimeVersionBeforeDownstreamChecks() { - GameInstanceRepository repository = Mockito.mock(GameInstanceRepository.class); - GameDesignClient gameDesignClient = Mockito.mock(GameDesignClient.class); - WorldManagementClient worldManagementClient = Mockito.mock(WorldManagementClient.class); - EntityManagementClient entityManagementClient = Mockito.mock(EntityManagementClient.class); - Mockito.when(repository.findById(7L)) - .thenReturn(Optional.of(sourceInstance(1L, "bad", null, 3L))); - InstanceCutoverCompatibilityServiceImpl service = - new InstanceCutoverCompatibilityServiceImpl( - repository, gameDesignClient, worldManagementClient, entityManagementClient); - - IllegalArgumentException error = - assertThrows( - IllegalArgumentException.class, - () -> service.validateInstanceCutoverCompatibility(1L, 7L, 9L)); - - assertEquals("runtimeVersion must be numeric", error.getMessage()); - Mockito.verifyNoInteractions(gameDesignClient, worldManagementClient, entityManagementClient); - } - - @Test - void validateInstanceCutoverCompatibilityRejectsZeroGameTemplateIdBeforeDownstreamChecks() { - GameInstanceRepository repository = Mockito.mock(GameInstanceRepository.class); - GameDesignClient gameDesignClient = Mockito.mock(GameDesignClient.class); - WorldManagementClient worldManagementClient = Mockito.mock(WorldManagementClient.class); - EntityManagementClient entityManagementClient = Mockito.mock(EntityManagementClient.class); - Mockito.when(repository.findById(7L)) - .thenReturn(Optional.of(sourceInstance(1L, null, 11L, 0L))); - InstanceCutoverCompatibilityServiceImpl service = - new InstanceCutoverCompatibilityServiceImpl( - repository, gameDesignClient, worldManagementClient, entityManagementClient); - - IllegalArgumentException error = - assertThrows( - IllegalArgumentException.class, - () -> service.validateInstanceCutoverCompatibility(1L, 7L, 9L)); - - assertEquals("gameTemplateId must be positive", error.getMessage()); - Mockito.verifyNoInteractions(gameDesignClient, worldManagementClient, entityManagementClient); - } - - private static GameInstance sourceInstance( - long tenantId, String runtimeVersion, Long versionId, Long gameTemplateId) { - GameInstance instance = new GameInstance(); - instance.setId(7L); - instance.setTenantId(tenantId); - instance.setRuntimeVersion(runtimeVersion); - instance.setVersionId(versionId); - instance.setGameTemplateId(gameTemplateId); - return instance; + assertEquals( + "AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED: canonical authored-world launch binding is required", + error.getMessage()); + Mockito.verifyNoInteractions( + repository, gameDesignClient, worldManagementClient, entityManagementClient); } } From 057f92f4e9d0c61b4ebbe1911aaa7dd2873c7664 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 20:54:39 +1300 Subject: [PATCH 02/13] fix(game-design): convert immutable launch descriptor readback types --- .github/workflows/ci.yml | 5 +- .../LaunchDescriptorRepository.java | 8 +-- .../LaunchDescriptorRepositoryTest.java | 68 +++++++++++++++++++ 3 files changed, 74 insertions(+), 7 deletions(-) create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 77da657a77..6541b7ec2b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -960,10 +960,9 @@ jobs: run: | ./gradlew :game-design-service:integrationTest \ --tests integration.net.firedevops.firemud.gamedesign.service.LaunchDescriptorServiceIntegrationTest \ - -PfullCheck --no-build-cache --no-configuration-cache - ./gradlew :game-design-service:test \ + :game-design-service:test \ --tests net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldLaunchDescriptorMtlsTest \ - -PfullCheck --no-build-cache --no-configuration-cache + -PfullCheck --continue --no-build-cache --no-configuration-cache bash dev-tools/validation/inspect-test-results.sh \ --strict \ --require-suite integration.net.firedevops.firemud.gamedesign.service.LaunchDescriptorServiceIntegrationTest \ diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepository.java index c95c0704de..3f09f54f70 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepository.java @@ -192,13 +192,13 @@ private LaunchDescriptor toEntity(Record record) { descriptor.setReleaseBundleId(record.get(RELEASE_BUNDLE_ID)); descriptor.setPublishedReleaseBundleRef(record.get(PUBLISHED_RELEASE_BUNDLE_REF)); descriptor.setRemapSetId(record.get(REMAP_SET_ID)); - descriptor.setDescriptorSchemaVersion(record.get(DESCRIPTOR_SCHEMA_VERSION)); + descriptor.setDescriptorSchemaVersion(record.get(DESCRIPTOR_SCHEMA_VERSION, Integer.class)); descriptor.setTargetNamespace(record.get(TARGET_NAMESPACE)); - UUID canonicalTenantId = record.get(CANONICAL_TENANT_ID); + UUID canonicalTenantId = record.get(CANONICAL_TENANT_ID, UUID.class); descriptor.setCanonicalTenantId( canonicalTenantId == null ? null : canonicalTenantId.toString()); descriptor.setWorldSlug(record.get(WORLD_SLUG)); - UUID sourceOperationId = record.get(SOURCE_OPERATION_ID); + UUID sourceOperationId = record.get(SOURCE_OPERATION_ID, UUID.class); descriptor.setAuthoredWorldSourceOperationId( sourceOperationId == null ? null : sourceOperationId.toString()); descriptor.setAuthoredWorldSourceEvidenceDigest(record.get(SOURCE_EVIDENCE_DIGEST)); @@ -209,7 +209,7 @@ private LaunchDescriptor toEntity(Record record) { descriptor.setOutcomeStatus(record.get(OUTCOME_STATUS)); descriptor.setFailureCode(record.get(FAILURE_CODE)); descriptor.setFailureMessage(record.get(FAILURE_MESSAGE)); - Timestamp createdAt = record.get(CREATED_AT); + Timestamp createdAt = record.get(CREATED_AT, Timestamp.class); descriptor.setCreatedAt(createdAt == null ? null : createdAt.toLocalDateTime()); return descriptor; } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java new file mode 100644 index 0000000000..b8e6c0a130 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java @@ -0,0 +1,68 @@ +package net.firedevops.firemud.gamedesign.repository; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.sql.DriverManager; +import java.time.LocalDateTime; +import java.util.UUID; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; + +class LaunchDescriptorRepositoryTest { + @Test + void findBoundByRequestConvertsMetadataBackedSmallintUuidAndTimestamp() throws Exception { + UUID canonicalTenantId = UUID.fromString("09cb7579-69b0-492b-82eb-7bb2231c0211"); + UUID sourceOperationId = UUID.fromString("c4651f34-8cb8-4ef8-b6f5-4aa19f8c1c42"); + LocalDateTime createdAt = LocalDateTime.of(2026, 10, 3, 10, 15, 30, 123_000_000); + + try (var connection = + DriverManager.getConnection( + "jdbc:h2:mem:launch-descriptor-readback;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE")) { + DSLContext dsl = DSL.using(connection, SQLDialect.H2); + dsl.execute( + "CREATE TABLE launch_descriptor (" + + "id BIGINT, launch_descriptor_id VARCHAR(64), tenant_id VARCHAR(36), " + + "game_template_id BIGINT, control_plane_request_id VARCHAR(64), " + + "request_hash VARCHAR(128), version_id BIGINT, script_patch_version VARCHAR(100), " + + "runtime_flags_json VARCHAR(4000), generation_config_revision VARCHAR(128), " + + "version_state_epoch BIGINT, release_bundle_id BIGINT, " + + "published_release_bundle_ref VARCHAR(128), remap_set_id VARCHAR(64), " + + "descriptor_schema_version SMALLINT, target_namespace VARCHAR(63), " + + "canonical_tenant_id UUID, world_slug VARCHAR(120), " + + "authored_world_source_operation_id UUID, " + + "authored_world_source_evidence_digest VARCHAR(72), request_digest VARCHAR(72), " + + "result_digest VARCHAR(72), original_request_json VARCHAR(4000), " + + "source_evidence_json VARCHAR(4000), outcome_status VARCHAR(16), " + + "failure_code VARCHAR(64), failure_message VARCHAR(1000), created_at TIMESTAMP)"); + dsl.execute( + "INSERT INTO launch_descriptor (id, launch_descriptor_id, tenant_id, game_template_id, " + + "control_plane_request_id, request_hash, version_id, script_patch_version, " + + "runtime_flags_json, generation_config_revision, version_state_epoch, " + + "release_bundle_id, published_release_bundle_ref, remap_set_id, " + + "descriptor_schema_version, target_namespace, canonical_tenant_id, world_slug, " + + "authored_world_source_operation_id, authored_world_source_evidence_digest, " + + "request_digest, result_digest, original_request_json, source_evidence_json, " + + "outcome_status, failure_code, failure_message, created_at) VALUES " + + "(17, 'launch-17', 'private-tenant', 23, 'request-17', 'sha256:request', 29, " + + "'patch-4', '{}', 'generation-6', 8, 31, 'release-31', NULL, 1, 'preview', '" + + canonicalTenantId + + "', 'verdant-harbor', '" + + sourceOperationId + + "', 'sha256:source', 'sha256:request', 'sha256:result', '{}', '{}', 'SUCCESS', " + + "NULL, NULL, TIMESTAMP '2026-10-03 10:15:30.123')"); + + var descriptor = + new LaunchDescriptorRepository(dsl) + .findBoundByRequest("preview", canonicalTenantId, "request-17") + .orElseThrow(); + + assertThat(descriptor.getDescriptorSchemaVersion()).isEqualTo(1); + assertThat(descriptor.getCanonicalTenantId()).isEqualTo(canonicalTenantId.toString()); + assertThat(descriptor.getAuthoredWorldSourceOperationId()) + .isEqualTo(sourceOperationId.toString()); + assertThat(descriptor.getCreatedAt()).isEqualTo(createdAt); + } + } +} From 9447e0ef59f1e624308c56e694ba7b340a31a493 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 21:29:35 +1300 Subject: [PATCH 03/13] feat(world): retain authenticated authored-source intake evidence --- .github/workflows/ci.yml | 57 ++ .../game-design-service/api-contracts.md | 2 +- .../world-management-service/api-contracts.md | 6 + ...ame-authoring-publishing-and-activation.md | 2 +- .../world-runtime-and-movement.md | 2 +- .../tenant/AuthoredWorldSourceClient.java | 156 ++++ .../tenant/AuthoredWorldSourceGrpcCodec.java | 115 +++ .../tenant/AuthoredWorldSourceClientTest.java | 134 +++ .../AuthoredWorldSourceGrpcCodecTest.java | 154 ++++ .../impl/TenantIdentityGrpcService.java | 14 +- .../impl/AuthoredWorldSourceMtlsTest.java | 825 ++++++++++++++++++ .../impl/TenantIdentityGrpcServiceTest.java | 37 +- ...GameDesignRuntimeTenantIdentityClient.java | 53 +- ...DesignRuntimeTenantIdentityClientTest.java | 3 +- .../WorldAuthoredSourceIntakeDigest.java | 112 +++ .../WorldAuthoredSourceIntakeReceipt.java | 61 ++ .../WorldAuthoredSourceIntakeRepository.java | 576 ++++++++++++ .../WorldAuthoredSourceIntakeService.java | 262 ++++++ .../V23__world_authored_source_intake.sql | 250 ++++++ ...ldAuthoredSourceIntakeIntegrationTest.java | 733 ++++++++++++++++ .../WorldAuthoredSourceIntakeDigestTest.java | 131 +++ .../WorldAuthoredSourceIntakeServiceTest.java | 503 +++++++++++ 22 files changed, 4135 insertions(+), 53 deletions(-) create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceGrpcCodec.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceClientTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceGrpcCodecTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceMtlsTest.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeDigest.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeReceipt.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeRepository.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeService.java create mode 100644 services/world-management-service/src/main/resources/db/migration/V23__world_authored_source_intake.sql create mode 100644 services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeDigestTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeServiceTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6541b7ec2b..c3fc05faf0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1000,6 +1000,63 @@ jobs: if-no-files-found: warn retention-days: 7 + - name: Run Game Design authored-source read socket mTLS proof + if: ${{ matrix.module == 'game-design-service' }} + run: | + ./gradlew :game-design-service:test \ + --tests net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldSourceMtlsTest \ + -PfullCheck --no-build-cache --no-configuration-cache + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldSourceMtlsTest \ + --require-case 'net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldSourceMtlsTest#exactWorldAndGameSessionReadersResolveCompleteSourceReceiptThroughSharedClient(Path)' \ + --require-case 'net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldSourceMtlsTest#wrongServiceNamespaceAndSharedCertificatesAreDeniedBeforeOwnerRead()' \ + --require-case 'net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldSourceMtlsTest#missingClientCertificateFailsWithTlsHandshakeEvidenceBeforeOwnerRead()' \ + --require-case 'net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldSourceMtlsTest#jwtOnlyCallerWithoutClientCertificateFailsWithTlsHandshakeEvidence()' \ + --require-case 'net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldSourceMtlsTest#validJwtWithTrustedCertificateButNoWorkloadUriIsDeniedByPeerGuard()' \ + --require-case 'net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldSourceMtlsTest#sharedClientRefusesWrongGameDesignServerWorkloadAndNamespace(Path)' \ + --require-case 'net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldSourceMtlsTest#sharedClientRejectsChangedRequestEchoSourceDigestAndUnknownFieldsOverSocket(Path)' \ + --require-case 'net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldSourceMtlsTest#unknownReadRequestFieldsAreRejectedByProductionServiceBeforeOwnerRead()' \ + --require-case 'net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldSourceMtlsTest#productionYamlAndSocketGuardsKeepWorldAccessLimitedToExactSourceMethod()' \ + game-design-service + + - name: Upload Game Design authored-source read socket proof results + if: ${{ always() && matrix.module == 'game-design-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: game-design-authored-source-read-proof-${{ github.sha }} + path: services/game-design-service/build/test-results/test/TEST-*AuthoredWorldSourceMtlsTest.xml + if-no-files-found: warn + retention-days: 7 + + - name: Run World authored-source intake PostgreSQL component proof + if: ${{ matrix.module == 'world-management-service' }} + run: | + ./gradlew :world-management-service:integrationTest \ + --tests net.firedevops.firemud.worldmanagement.WorldAuthoredSourceIntakeIntegrationTest \ + -PfullCheck --no-build-cache --no-configuration-cache + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite net.firedevops.firemud.worldmanagement.WorldAuthoredSourceIntakeIntegrationTest \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredSourceIntakeIntegrationTest#persistsCompleteFreshReceiptAndReusesExactTenantAssociationAcrossWorlds()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredSourceIntakeIntegrationTest#deniesRetainedEvidenceAndChangedRequestOrTenantScopeBeforeAddingClaims()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredSourceIntakeIntegrationTest#ownerTransactionRollbackLeavesNeitherAssociationNorReceipt()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredSourceIntakeIntegrationTest#rejectsImmutableHistoryMutationAndTruncation()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredSourceIntakeIntegrationTest#rejectsReadOnlyAndNonReadCommittedOwnerTransactionsWithoutClaims()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredSourceIntakeIntegrationTest#concurrentExactRetriesReturnTheSingleCommittedReceipt()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredSourceIntakeIntegrationTest#concurrentLegacyNumericClaimSerializesBeforeFreshSelectorAllocation()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredSourceIntakeIntegrationTest#concurrentLegacyClaimAfterAllocationCannotTakeTheReservedSelector()' \ + world-management-service + + - name: Upload World authored-source intake proof results + if: ${{ always() && matrix.module == 'world-management-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: world-authored-source-intake-proof-${{ github.sha }} + path: services/world-management-service/build/test-results/integrationTest/TEST-*WorldAuthoredSourceIntakeIntegrationTest.xml + if-no-files-found: warn + retention-days: 7 + - name: Run Game Session authored-world intake PostgreSQL component proof if: ${{ matrix.module == 'game-session-service' }} run: | diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 937cd62a4b..3b54615910 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -28,7 +28,7 @@ Only the verified peer `spiffe://firemud/ns/{configured_namespace}/sa/game-sessi ### Authored-world source registration and Game Session readback -Game Design owns a persisted authored-world selector source; Game Session consumes its authenticated readback and remains the sole runtime catalog writer. A Game Design owner transaction binds the existing canonical tenant identity and exact source-game provenance to separately supplied stable `tenantSlug` and tenant-scoped `worldSlug` values. Neither selector is inferred from a display name, template, numeric key, realm slug or runtime instance. A template or launch descriptor is not itself an authored-world identity. This source is selector provenance, not a content-version release, realm policy, membership grant, selected runtime or admission permission. +Game Design owns a persisted authored-world selector source; Game Session consumes its authenticated readback and remains the sole runtime catalog writer. World consumes the same source authority for its separate [automatic authored-content intake and local association](../world-management-service/api-contracts.md#authenticated-authored-content-intake-and-tenant-association); only the exact same-namespace Game Session and World workloads may read this source, while the other tenant-identity methods retain their own caller restrictions. A Game Design owner transaction binds the existing canonical tenant identity and exact source-game provenance to separately supplied stable `tenantSlug` and tenant-scoped `worldSlug` values. Neither selector is inferred from a display name, template, numeric key, realm slug or runtime instance. A template or launch descriptor is not itself an authored-world identity. This source is selector provenance, not a content-version release, realm policy, membership grant, selected runtime or admission permission. The closed `game-design-authored-world-source/v1` evidence contains `schemaVersion=1`, `targetNamespace`, canonical non-nil `registrationRequestId`, canonical non-nil owner `operationId`, `requestDigest`, canonical non-nil `canonicalTenantId`, `tenantSlug`, `worldSlug`, `worldDisplayName`, positive private `sourceGameRowId`, exact private `sourceGameTenantKey`, `provenanceKind` (`NEW_GAME_ROW` or `RETAINED_GAME_V30`) and `evidenceDigest`. Slugs use the existing canonical lower-case routing-selector grammar `[a-z0-9]+(?:-[a-z0-9]+)*`, bounded to 120 UTF-8 bytes; no case folding, trimming or inference changes a signed or stored selector. The display name is explicitly supplied, nonblank valid Unicode and at most 100 code points. Source-key bounds and actual game-row provenance retain the tenant-identity rules above. Private source row/key fields are provenance only, not public logical identifiers or a Game Session numeric tenant association. diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 4f345bad48..e4a4d6c3aa 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -251,8 +251,14 @@ Fresh World content enters automatically through authenticated Game Design sourc World owns allocation and retention of its private local storage selectors. It atomically persists the association to the canonical tenant UUID and exact accepted content binding with its intake outcome, then reads back the complete original association and result before acknowledging success. Exact retries preserve the original source, descriptor, content and local association; a changed binding conflicts rather than silently selecting another tenant or release. This association does not itself prove current ACTIVE state or permit gameplay admission. +The source-intake prerequisite is separate from released-content acceptance: `world-authored-source-intake/v1` retains the complete closed Game Design source receipt, positive schema version, target namespace, stable `intakeRequestId`, owner-allocated operation UUID, canonical tenant UUID, world slug, source operation/evidence digest, request digest and receipt digest. World also retains its own private local tenant association internally; it does not transmit that numeric selector as a canonical identifier. Fresh allocation requires Game Design's proved `NEW_GAME_ROW` provenance and an owner-allocated selector that cannot claim existing World rows. A retained Game Design source is not proof that World has no retained content and cannot take this fresh-allocation shortcut. + +The request digest is SHA-256 over fixed-order UTF-8 segments with decimal byte-length `:` framing: `world-authored-source-intake-request/v1`, target namespace, intake request UUID, canonical tenant UUID, world slug, source operation UUID and source evidence digest. The owner-internal receipt digest uses the same framing over `world-authored-source-intake-receipt/v1`, target namespace, owner operation UUID, request digest, canonical tenant UUID, world slug, source operation UUID, source evidence digest and canonical decimal private local tenant key. UUIDs use canonical non-nil text, the private key is positive, and digests render as `sha256:` plus 64 lower-case hexadecimal characters. The source digest is verified against the complete original owner receipt, never accepted alone as authentication. A writable World owner transaction stores and exactly reads back the association and immutable receipt together; changed request/source/local association, absent or corrupt readback, and allocation over existing World state fail closed. This receipt is not released-content, descriptor, ACTIVE-state or admission proof. + Retained World rows use a separate owner-approved, audited association operation, following the existing provenance-backed association pattern but binding World's exact retained-row evidence. World verifies and durably reads back that evidence and the one-to-one canonical association. Account's migration manifest, matching numeric keys, selector similarity and absent history are not World ownership proof. Unmapped, ambiguous or contradictory retained rows remain denied. This exceptional retained-data migration is not part of routine fresh intake, and no association is inferred or repaired during a launch retry. +World reserves a fresh private selector durably with its canonical association. Every legacy numeric writer must fail closed rather than take that selector, including a concurrent writer with an older transaction snapshot; existing legacy selectors remain usable but cannot acquire a canonical association through numeric equality. Reservation and intake rollback together, and committed associations, reservations and receipts cannot be rewritten or deleted to make another binding appear valid. This reservation is not permission for a legacy content writer to populate canonical content: the canonical-source-qualified writer and its owner evidence remain separate prerequisites. + The producer, authenticated receiver, exact local content readback, rollback/concurrent retry and fresh/retained isolation proof must pass before this boundary is used by canonical preparation. Private numeric selectors remain internal. Implementation and proof status is recorded in [World Runtime and Movement](../../../project-management/implementation-tracking/world-runtime-and-movement.md#current-status). ## Initial Admission Hold Contract diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index 6530d1ff66..fb0ae64b34 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -149,7 +149,7 @@ Lifecycle status/proof is also incomplete: artifact and Version epoch checks lac ### Launch, Activation, Cutover, and Termination -The prepared source-bound `ResolveLaunchDescriptor` producer claims `(targetNamespace, canonicalTenantId, controlPlaneRequestId)` before mutable template/version resolution and retains the exact authored-source request and successful result digests in its existing immutable descriptor family. Changed source, world, template or overrides cannot reuse that claim to select another release. `GetLaunchDescriptor` prepares exact readback for verified Game Session and World peers; the canonical request/result schema is owned by the [Game Design API contract](../../architecture/microservices/game-design-service/api-contracts.md#authored-source-bound-launch-descriptor-and-exact-readback). Shared codec/vector unit proof executes locally. The owner candidate also retains typed deterministic business denials in that same immutable request/outcome family, without fabricating descriptor or release IDs. Producer, failed-outcome and physical peer tests are being validated; PostgreSQL execution and exact CI remain required, and none of these components proves release publication or World materialization. The descriptor freezes `versionId`, `scriptPatchVersion`, `runtimeFlags`, `generationConfigRevision`, Game Design's `versionStateEpoch`, `releaseBundleRef`, and approved replacement `remapSetId` where required. Runtime provisioning must consume that immutable descriptor rather than resolve mutable "latest" control-plane state mid-flight. Game Design also exposes `GetVersionState` and `CompareAndSetVersionState`, and persists approved remap sets through `CreateTemplateRemapSet`, `ApproveTemplateRemapSet`, and `GetTemplateRemapSet`. +The prepared source-bound `ResolveLaunchDescriptor` producer claims `(targetNamespace, canonicalTenantId, controlPlaneRequestId)` before mutable template/version resolution and retains the exact authored-source request and successful result digests in its existing immutable descriptor family. Changed source, world, template or overrides cannot reuse that claim to select another release. `GetLaunchDescriptor` prepares exact readback for verified Game Session and World peers; the canonical request/result schema is owned by the [Game Design API contract](../../architecture/microservices/game-design-service/api-contracts.md#authored-source-bound-launch-descriptor-and-exact-readback). Shared codec/vector unit proof executes locally. The owner candidate also retains typed deterministic business denials in that same immutable request/outcome family, without fabricating descriptor or release IDs. Thirteen descriptor and nine source-read physical mTLS methods execute cleanly locally with production guards/handlers and mocked source producers; this is not database-to-socket or live creation proof. The preceding exact runner executed all seven descriptor PostgreSQL cases, with one pass and six actual SMALLINT readback-conversion failures. The explicit metadata conversion correction and its unit regression pass locally; corrected PostgreSQL execution and exact CI remain required. World owner-local fresh intake/reservation/readback is a separate prepared prerequisite recorded in [World Runtime and Movement](./world-runtime-and-movement.md#current-status), not release publication or canonical content materialization. The descriptor freezes `versionId`, `scriptPatchVersion`, `runtimeFlags`, `generationConfigRevision`, Game Design's `versionStateEpoch`, `releaseBundleRef`, and approved replacement `remapSetId` where required. Runtime provisioning must consume that immutable descriptor rather than resolve mutable "latest" control-plane state mid-flight. Game Design also exposes `GetVersionState` and `CompareAndSetVersionState`, and persists approved remap sets through `CreateTemplateRemapSet`, `ApproveTemplateRemapSet`, and `GetTemplateRemapSet`. The candidate denies legacy numeric `StartSession` preflight and cutover descriptor lookup with `AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED`, before descriptor lookup or lifecycle/pointer/World mutation. There is no canonical source evidence in those requests, and no proved numeric World association; they must not be described as successful unpatched launch. Canonical Game Session orchestration and World durable source-bound `PREPARING` readback remain required before launch can proceed. The former numeric post-preflight preparation/activation, replacement, compensation and ambiguity branches are not proof of that canonical workflow; retained-instance stop/restart and independent lifecycle coverage remain useful but separate. Game Design denies any requested/template script patch because exact published-for-base and Automation `READY` evidence are unavailable. Game Session must independently re-check patch publication/base identity and join Automation's tenant runtime status before patched launch is enabled. The typed descriptor and launch-preflight failures include `TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED`, `INVALID_TEMPLATE_CONFIGURATION`, `SCRIPT_PATCH_OVERRIDE_CONFLICT`, `SCRIPT_PATCH_NOT_READY`, `RELEASE_BUNDLE_NOT_FOUND`, `RELEASE_ATTESTATION_MISMATCH`, `VERSION_STATE_EPOCH_STALE`, and `LAUNCH_REMAP_REQUIRED`. `SCRIPT_PATCH_NOT_READY` is containment, not readiness proof. Existing numeric World `PrepareWorldInstance`, activation and failed-preparation seams do not yet retain the canonical authored-source binding; their presence and earlier fixture results are not proof of the required UUID-qualified owner handoff. diff --git a/design/project-management/implementation-tracking/world-runtime-and-movement.md b/design/project-management/implementation-tracking/world-runtime-and-movement.md index a82386a807..e09d527d12 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for world runtime and movement. C ## Current Status -**Canonical launch prerequisite:** Current World design/materialization rows and `PrepareWorldInstance` still use World's private numeric tenant key. No World-owned authenticated intake/readback currently associates that key to the complete canonical UUID/content binding. Overseer approved automatic Game Design-authenticated fresh World intake and a separate owner-approved, audited association with exact retained-row evidence; the [World API contract](../../architecture/microservices/world-management-service/api-contracts.md#authenticated-authored-content-intake-and-tenant-association) owns this boundary. Producer, receiver, exact content/association readback, retry/rollback and retained-row proof remain required. Numeric similarity, selectors and Account's migration manifest are not substitutes, and no runtime activation is authorized. +**Canonical launch prerequisite:** Current World design/materialization rows and `PrepareWorldInstance` still use World's private numeric tenant key. The candidate adds V23 and an explicitly unwired owner-local fresh-source intake service/repository: a complete authenticated Game Design `NEW_GAME_ROW` receipt, private World tenant association, numeric-key reservation and immutable intake receipt commit together, with exact independent readback. Legacy numeric writes cannot take a reserved canonical selector; existing legacy keys are reserved without inventing UUID associations. Shared source-client/codec and nine exact Game Design source-method socket tests pass locally using production transport and a mocked source repository, not the complete normal producer or database-to-socket path. Fifteen World digest/service unit cases execute cleanly; the eight PostgreSQL intake cases compile but skip locally without Docker, so transactional, migration and concurrency execution remains unproved locally. Focused World/Game Session checks, static analysis and packaged JAR construction pass. The automatic normal Game Design registration/delivery producer, World RPC receiver, canonical-source-qualified content writer, actual content/descriptor/release readback and separate audited retained-World association remain required. The [World API contract](../../architecture/microservices/world-management-service/api-contracts.md#authenticated-authored-content-intake-and-tenant-association) owns this boundary. Numeric similarity, selectors and Account's migration manifest are not substitutes, and no runtime activation is authorized. The canonical launch correction must also supply genuinely fresh instance creation, not merely attach a UUID carrier to the legacy prepare call: Game Session's `game_instances.tenant_id` and World's lifecycle/topology tenant selectors remain required numeric fields on this tree. A fresh canonical catalog provides no numeric tenant alias. Widen the actual owner instance/lifecycle representation and source-qualified creation/readback together; adding a binding table while inventing a numeric tenant selector would not close this gate. Exact retained instance associations remain separately source-proved and cannot be inferred from the Game Session row number or an Account mapping. diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceClient.java new file mode 100644 index 0000000000..fff22828fd --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceClient.java @@ -0,0 +1,156 @@ +package net.firedevops.firemud.common.tenant; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.gamedesign.v1.TenantIdentityServiceGrpc; + +/** Explicit mTLS client for exact, non-mutating Game Design authored-world source reads. */ +public final class AuthoredWorldSourceClient + extends AbstractReloadingBlockingGrpcClient< + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public AuthoredWorldSourceClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + AuthoredWorldSourceClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes only when an owning service explicitly starts this client. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("Authored-world source client is closed"); + } + if (initialized) { + return; + } + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException( + "Authored-world source client did not initialize a gRPC stub"); + } + initialized = true; + } + + /** Reads the exact persisted source receipt without registering a World association. */ + public AuthoredWorldSourceEvidence read(AuthoredWorldSourceGrpcCodec.ReadRequest request) { + Objects.requireNonNull(request, "request"); + requireNamespace(request.targetNamespace()); + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub currentStub = requireStub(); + var response = + currentStub + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .resolveAuthoredWorldSource(AuthoredWorldSourceGrpcCodec.toReadRequest(request)); + try { + return AuthoredWorldSourceGrpcCodec.fromReadResponse(request, response); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "Game Design returned invalid authored-world source evidence", exception); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameDesignService(); + } + + @Override + protected String defaultTarget() { + return "game-design-service:6565"; + } + + @Override + protected TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub buildStub( + ManagedChannel channel) { + return TenantIdentityServiceGrpc.newBlockingStub(channel) + .withInterceptors( + new GrpcServerPeerIdentityClientInterceptor( + "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service")) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub requireStub() { + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Authored-world source client is not initialized and available"); + } + return currentStub; + } + + private void requireNamespace(String targetNamespace) { + if (!workloadNamespace.equals(targetNamespace)) { + throw new IllegalArgumentException( + "Authored-world source request must use the configured workload namespace"); + } + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null) { + throw new IllegalArgumentException("gRPC mTLS configuration is required"); + } + if (tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("Authored-world source reads require workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "Authored-world source reads require file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Authored-world source reads require file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException exception) { + throw new IllegalArgumentException( + "Authored-world source " + label + " must be a readable file-backed path", exception); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Authored-world source " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceGrpcCodec.java new file mode 100644 index 0000000000..a995782343 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceGrpcCodec.java @@ -0,0 +1,115 @@ +package net.firedevops.firemud.common.tenant; + +import com.google.protobuf.Message; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceResponse; + +/** Closed request mapping and exact readback validation for authored-world source RPCs. */ +public final class AuthoredWorldSourceGrpcCodec { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + /** Exact, non-mutating source read selector and caller-owned read identity. */ + public record ReadRequest( + String targetNamespace, + UUID requestId, + UUID operationId, + UUID canonicalTenantId, + String worldSlug) { + public ReadRequest { + Objects.requireNonNull(requestId, "requestId"); + Objects.requireNonNull(operationId, "operationId"); + Objects.requireNonNull(canonicalTenantId, "canonicalTenantId"); + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requireNonNil(requestId, "requestId"); + requireNonNil(operationId, "operationId"); + } + } + + private AuthoredWorldSourceGrpcCodec() {} + + /** Encodes exactly the owner read identity and source selector. */ + public static ResolveAuthoredWorldSourceRequest toReadRequest(ReadRequest request) { + Objects.requireNonNull(request, "request"); + return ResolveAuthoredWorldSourceRequest.newBuilder() + .setRequestId(request.requestId().toString()) + .setOperationId(request.operationId().toString()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setWorldSlug(request.worldSlug()) + .build(); + } + + /** Decodes the complete closed receipt and binds all echoed fields to the exact read request. */ + public static AuthoredWorldSourceEvidence fromReadResponse( + ReadRequest request, ResolveAuthoredWorldSourceResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response); + + AuthoredWorldSourceEvidence evidence; + try { + UUID echoedRequestId = parseCanonicalNonNilUuid(response.getRequestId(), "requestId"); + if (!request.requestId().equals(echoedRequestId)) { + throw new IllegalArgumentException("Authored-world source read request echo changed"); + } + evidence = + new AuthoredWorldSourceEvidence( + response.getSchemaVersion(), + response.getTargetNamespace(), + parseCanonicalNonNilUuid( + response.getRegistrationRequestId(), "registrationRequestId"), + parseCanonicalNonNilUuid(response.getOperationId(), "operationId"), + response.getRequestDigest(), + parseCanonicalNonNilUuid(response.getCanonicalTenantId(), "canonicalTenantId"), + response.getTenantSlug(), + response.getWorldSlug(), + response.getWorldDisplayName(), + response.getSourceGameRowId(), + response.getSourceGameTenantKey(), + response.getProvenanceKind(), + response.getEvidenceDigest()); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Authored-world source response is invalid", exception); + } + + if (!request.targetNamespace().equals(evidence.targetNamespace()) + || !request.operationId().equals(evidence.operationId()) + || !request.canonicalTenantId().equals(evidence.canonicalTenantId()) + || !request.worldSlug().equals(evidence.worldSlug())) { + throw new IllegalArgumentException( + "Authored-world source response does not match the exact request"); + } + return evidence; + } + + private static void requireNoUnknownFields(Message message) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException( + "Authored-world source response contains unsupported fields"); + } + } + + private static UUID parseCanonicalNonNilUuid(String value, String label) { + if (value == null) { + throw new IllegalArgumentException("Canonical nonnil " + label + " is required"); + } + UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Canonical nonnil " + label + " is required", exception); + } + requireNonNil(parsed, label); + if (!parsed.toString().equals(value)) { + throw new IllegalArgumentException("Canonical nonnil " + label + " is required"); + } + return parsed; + } + + private static void requireNonNil(UUID value, String label) { + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceClientTest.java new file mode 100644 index 0000000000..7328955cbd --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceClientTest.java @@ -0,0 +1,134 @@ +package net.firedevops.firemud.common.tenant; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.ManagedChannel; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.UUID; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class AuthoredWorldSourceClientTest { + private static final String NAMESPACE = "test"; + private static final AuthoredWorldSourceGrpcCodec.ReadRequest REQUEST = + new AuthoredWorldSourceGrpcCodec.ReadRequest( + NAMESPACE, + UUID.fromString("12345678-1234-4234-8234-123456789abc"), + UUID.fromString("22345678-1234-4234-8234-123456789abc"), + UUID.fromString("32345678-1234-4234-8234-123456789abc"), + "world-one"); + + @Test + void rejectsPlaintextMissingClasspathAndUnreadableTlsMaterialBeforeChannelCreation( + @TempDir Path directory) throws Exception { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + + CommonGrpcClientProperties plaintext = fileBackedMtls(directory); + plaintext.setPlaintext(true); + assertThatThrownBy(() -> newClient(plaintext, channelFactory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + + assertThatThrownBy(() -> newClient(new CommonGrpcClientProperties(), channelFactory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + + CommonGrpcClientProperties classpath = fileBackedMtls(directory); + classpath.setCaCert("classpath:certs/ca.crt"); + assertThatThrownBy(() -> newClient(classpath, channelFactory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + + CommonGrpcClientProperties missingFiles = new CommonGrpcClientProperties(); + missingFiles.setCertChain(directory.resolve("missing-client.crt").toString()); + missingFiles.setPrivateKey(directory.resolve("missing-client.key").toString()); + missingFiles.setCaCert(directory.resolve("missing-ca.crt").toString()); + assertThatThrownBy(() -> newClient(missingFiles, channelFactory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("existing readable file"); + + verifyNoInteractions(channelFactory); + } + + @Test + void requiresExplicitInitializationAndRejectsNamespaceMismatch(@TempDir Path directory) + throws Exception { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + AuthoredWorldSourceClient client = newClient(fileBackedMtls(directory), channelFactory); + try { + assertThatThrownBy(() -> client.read(REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + assertThatThrownBy( + () -> + client.read( + new AuthoredWorldSourceGrpcCodec.ReadRequest( + "other", + REQUEST.requestId(), + REQUEST.operationId(), + REQUEST.canonicalTenantId(), + REQUEST.worldSlug()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured workload namespace"); + verifyNoInteractions(channelFactory); + } finally { + client.close(); + } + } + + @Test + void initializesTheConfiguredGameDesignTargetOnlyOnExplicitInit(@TempDir Path directory) + throws Exception { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("game-design.internal:6565"); + CommonGrpcClientProperties tls = fileBackedMtls(directory); + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + ManagedChannel channel = mock(ManagedChannel.class); + when(channelFactory.buildChannel( + eq("game-design.internal:6565"), + eq(6565), + any(CommonGrpcClientProperties.class), + eq(true))) + .thenReturn(channel); + AuthoredWorldSourceClient client = + new AuthoredWorldSourceClient(endpoints, tls, channelFactory, NAMESPACE); + + try { + client.init(); + client.init(); + verify(channelFactory) + .buildChannel( + eq("game-design.internal:6565"), + eq(6565), + any(CommonGrpcClientProperties.class), + eq(true)); + } finally { + client.close(); + } + } + + private static AuthoredWorldSourceClient newClient( + CommonGrpcClientProperties tls, GrpcChannelFactory channelFactory) { + return new AuthoredWorldSourceClient( + new ServiceEndpointsProperties(), tls, channelFactory, NAMESPACE); + } + + private static CommonGrpcClientProperties fileBackedMtls(Path directory) throws Exception { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(Files.writeString(directory.resolve("client.crt"), "certificate").toString()); + tls.setPrivateKey(Files.writeString(directory.resolve("client.key"), "private key").toString()); + tls.setCaCert( + Files.writeString(directory.resolve("server-ca.crt"), "CA certificate").toString()); + return tls; + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceGrpcCodecTest.java new file mode 100644 index 0000000000..07075347b5 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceGrpcCodecTest.java @@ -0,0 +1,154 @@ +package net.firedevops.firemud.common.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.UnknownFieldSet; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceResponse; +import org.junit.jupiter.api.Test; + +class AuthoredWorldSourceGrpcCodecTest { + private static final String NAMESPACE = "test"; + private static final UUID REQUEST_ID = UUID.fromString("12345678-1234-4234-8234-123456789abc"); + private static final UUID OPERATION_ID = UUID.fromString("22345678-1234-4234-8234-123456789abc"); + private static final UUID TENANT_ID = UUID.fromString("32345678-1234-4234-8234-123456789abc"); + private static final UUID REGISTRATION_REQUEST_ID = + UUID.fromString("42345678-1234-4234-8234-123456789abc"); + private static final AuthoredWorldSourceGrpcCodec.ReadRequest REQUEST = + new AuthoredWorldSourceGrpcCodec.ReadRequest( + NAMESPACE, REQUEST_ID, OPERATION_ID, TENANT_ID, "world-one"); + + @Test + void encodesTheExactReadTupleAndDecodesTheCompleteReceipt() { + var encoded = AuthoredWorldSourceGrpcCodec.toReadRequest(REQUEST); + assertThat(encoded.getRequestId()).isEqualTo(REQUEST_ID.toString()); + assertThat(encoded.getOperationId()).isEqualTo(OPERATION_ID.toString()); + assertThat(encoded.getCanonicalTenantId()).isEqualTo(TENANT_ID.toString()); + assertThat(encoded.getWorldSlug()).isEqualTo("world-one"); + assertThat(encoded.getUnknownFields().asMap()).isEmpty(); + + AuthoredWorldSourceEvidence evidence = + AuthoredWorldSourceGrpcCodec.fromReadResponse(REQUEST, response()); + assertThat(evidence.registrationRequestId()).isEqualTo(REGISTRATION_REQUEST_ID); + assertThat(evidence.operationId()).isEqualTo(OPERATION_ID); + assertThat(evidence.canonicalTenantId()).isEqualTo(TENANT_ID); + assertThat(evidence.tenantSlug()).isEqualTo("tenant-one"); + assertThat(evidence.worldSlug()).isEqualTo("world-one"); + assertThat(evidence.worldDisplayName()).isEqualTo("Wörld"); + assertThat(evidence.sourceGameRowId()).isEqualTo(19L); + assertThat(evidence.sourceGameTenantKey()).isEqualTo("source-key"); + assertThat(evidence.provenanceKind()).isEqualTo("NEW_GAME_ROW"); + } + + @Test + void rejectsMalformedReadSelectorsBeforeEncoding() { + for (Runnable invalid : + List.of( + () -> + new AuthoredWorldSourceGrpcCodec.ReadRequest( + "Other", REQUEST_ID, OPERATION_ID, TENANT_ID, "world-one"), + () -> + new AuthoredWorldSourceGrpcCodec.ReadRequest( + NAMESPACE, new UUID(0L, 0L), OPERATION_ID, TENANT_ID, "world-one"), + () -> + new AuthoredWorldSourceGrpcCodec.ReadRequest( + NAMESPACE, REQUEST_ID, new UUID(0L, 0L), TENANT_ID, "world-one"), + () -> + new AuthoredWorldSourceGrpcCodec.ReadRequest( + NAMESPACE, REQUEST_ID, OPERATION_ID, new UUID(0L, 0L), "world-one"), + () -> + new AuthoredWorldSourceGrpcCodec.ReadRequest( + NAMESPACE, REQUEST_ID, OPERATION_ID, TENANT_ID, "World"), + () -> + new AuthoredWorldSourceGrpcCodec.ReadRequest( + NAMESPACE, REQUEST_ID, OPERATION_ID, TENANT_ID, "w".repeat(121)))) { + assertThatThrownBy(invalid::run).isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void rejectsUnknownFieldsAndEveryChangedReceiptField() { + ResolveAuthoredWorldSourceResponse valid = response(); + for (ResolveAuthoredWorldSourceResponse changed : + List.of( + valid.toBuilder().setSchemaVersion(2).build(), + valid.toBuilder().setTargetNamespace("other").build(), + valid.toBuilder().setRequestId(REGISTRATION_REQUEST_ID.toString()).build(), + valid.toBuilder().setRegistrationRequestId(REQUEST_ID.toString()).build(), + valid.toBuilder().setOperationId(REQUEST_ID.toString()).build(), + valid.toBuilder().setRequestDigest("sha256:" + "0".repeat(64)).build(), + valid.toBuilder().setCanonicalTenantId(REQUEST_ID.toString()).build(), + valid.toBuilder().setTenantSlug("tenant-other").build(), + valid.toBuilder().setWorldSlug("world-other").build(), + valid.toBuilder().setWorldDisplayName("World").build(), + valid.toBuilder().setSourceGameRowId(20L).build(), + valid.toBuilder().setSourceGameTenantKey("changed-key").build(), + valid.toBuilder().setProvenanceKind("RETAINED_GAME_V30").build(), + valid.toBuilder().setEvidenceDigest("sha256:" + "0".repeat(64)).build(), + valid.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) { + assertThatThrownBy(() -> AuthoredWorldSourceGrpcCodec.fromReadResponse(REQUEST, changed)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void rejectsCoherentRepliesForAnotherNamespaceOperationTenantOrWorld() { + for (ResolveAuthoredWorldSourceResponse changed : + List.of( + response("other", TENANT_ID, OPERATION_ID, "world-one"), + response(NAMESPACE, TENANT_ID, REQUEST_ID, "world-one"), + response(NAMESPACE, REQUEST_ID, OPERATION_ID, "world-one"), + response(NAMESPACE, TENANT_ID, OPERATION_ID, "other-world"))) { + assertThatThrownBy(() -> AuthoredWorldSourceGrpcCodec.fromReadResponse(REQUEST, changed)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact request"); + } + } + + private static ResolveAuthoredWorldSourceResponse response() { + return response(NAMESPACE, TENANT_ID, OPERATION_ID, "world-one"); + } + + private static ResolveAuthoredWorldSourceResponse response( + String namespace, UUID tenantId, UUID operationId, String worldSlug) { + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + namespace, REGISTRATION_REQUEST_ID, tenantId, "tenant-one", worldSlug, "Wörld"); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + namespace, + REGISTRATION_REQUEST_ID, + operationId, + requestDigest, + tenantId, + "tenant-one", + worldSlug, + "Wörld", + 19L, + "source-key", + "NEW_GAME_ROW"); + return ResolveAuthoredWorldSourceResponse.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(namespace) + .setRequestId(REQUEST_ID.toString()) + .setRegistrationRequestId(REGISTRATION_REQUEST_ID.toString()) + .setOperationId(operationId.toString()) + .setRequestDigest(requestDigest) + .setCanonicalTenantId(tenantId.toString()) + .setTenantSlug("tenant-one") + .setWorldSlug(worldSlug) + .setWorldDisplayName("Wörld") + .setSourceGameRowId(19L) + .setSourceGameTenantKey("source-key") + .setProvenanceKind("NEW_GAME_ROW") + .setEvidenceDigest(evidenceDigest) + .build(); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java index b1e425c5fa..40c556f682 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java @@ -437,10 +437,11 @@ public void resolveRuntimeTenantIdentity( public void resolveAuthoredWorldSource( ResolveAuthoredWorldSourceRequest request, StreamObserver responseObserver) { - if (!isGameSessionPeer()) { + if (!isAuthoredWorldSourceReaderPeer()) { responseObserver.onError( Status.PERMISSION_DENIED - .withDescription("Verified Game Session workload identity is required") + .withDescription( + "Verified same-namespace Game Session or World Management identity is required") .asRuntimeException()); return; } @@ -647,6 +648,15 @@ private boolean isGameSessionPeer() { .equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service"); } + private boolean isAuthoredWorldSourceReaderPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + String expectedPrefix = "spiffe://firemud/ns/" + workloadNamespace + "/sa/"; + return peer != null + && GrpcPeerIdentity.isValidNamespace(workloadNamespace) + && (peer.uri().equals(expectedPrefix + "game-session-service") + || peer.uri().equals(expectedPrefix + "world-management-service")); + } + private static UUID parseCanonicalNonNilUuid(String value) { if (value == null) { return null; diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceMtlsTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceMtlsTest.java new file mode 100644 index 0000000000..0d27b8182f --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceMtlsTest.java @@ -0,0 +1,825 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.ForwardingServerCall.SimpleForwardingServerCall; +import io.grpc.ManagedChannel; +import io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.MetadataUtils; +import java.io.IOException; +import java.math.BigInteger; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.PrivateKey; +import java.security.Security; +import java.security.cert.X509Certificate; +import java.time.Instant; +import java.util.Base64; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.security.AuthTokenInterceptor; +import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceClient; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceGrpcCodec; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepository; +import net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepository; +import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceResponse; +import net.firedevops.firemud.gamedesign.v1.ResolveFreshTenantCreationRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyAccountTenantAssociationRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameSessionTenantAssociationRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameTenantIdentityRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityRequest; +import net.firedevops.firemud.gamedesign.v1.TenantIdentityServiceGrpc; +import net.firedevops.firemud.test.TlsTestSupport; +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.asn1.x509.BasicConstraints; +import org.bouncycastle.asn1.x509.ExtendedKeyUsage; +import org.bouncycastle.asn1.x509.Extension; +import org.bouncycastle.asn1.x509.GeneralName; +import org.bouncycastle.asn1.x509.GeneralNames; +import org.bouncycastle.asn1.x509.KeyPurposeId; +import org.bouncycastle.asn1.x509.KeyUsage; +import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; +import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.boot.context.properties.bind.Bindable; +import org.springframework.boot.context.properties.bind.Binder; +import org.springframework.boot.env.YamlPropertySourceLoader; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.core.env.StandardEnvironment; +import org.springframework.core.io.FileSystemResource; + +/** + * Physical socket proof for Game Design's authored-world source read boundary. + * + *

The production gRPC service, peer-identity interceptor, JWT interceptor, and shared source + * client run over ephemeral mTLS sockets. The owner repository is mocked and returns a complete, + * digest-valid schema-v1 receipt; this suite does not prove source registration persistence, normal + * source creation, World intake, local association, publication, or runtime activation. + */ +class AuthoredWorldSourceMtlsTest { + private static final String NAMESPACE = "test"; + private static final String SOURCE_METHOD = + "gamedesign.v1.TenantIdentityService/ResolveAuthoredWorldSource"; + private static final String AUTHORIZATION = "authorization"; + private static final String JWT_SECRET = "test-secret-key-test-secret-key-32-bytes"; + private static final UUID REGISTRATION_REQUEST_ID = + UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID SOURCE_OPERATION_ID = + UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID TENANT_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID READ_REQUEST_ID = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final AtomicLong CERTIFICATE_SERIAL = new AtomicLong(1L); + private static final Set TENANT_IDENTITY_JWT_BYPASS_METHODS = + Set.of( + "gamedesign.v1.TenantIdentityService/ResolveLegacyAccountTenantAssociation", + "gamedesign.v1.TenantIdentityService/ResolveFreshTenantCreation", + "gamedesign.v1.TenantIdentityService/ResolveRuntimeTenantIdentity", + SOURCE_METHOD, + "gamedesign.v1.TenantIdentityService/ResolveLegacyGameSessionTenantAssociation"); + private static final AuthoredWorldSourceEvidence SOURCE_EVIDENCE = sourceEvidence(); + private static final AuthoredWorldSourceGrpcCodec.ReadRequest READ_REQUEST = + new AuthoredWorldSourceGrpcCodec.ReadRequest( + NAMESPACE, READ_REQUEST_ID, SOURCE_OPERATION_ID, TENANT_ID, "harbor-world"); + private static TestPki pki; + + private GameRepository gameRepository; + private TenantAssociationMigrationService associationService; + private GameTenantCreationRepository creationRepository; + private GameAuthoredWorldSourceRepository authoredWorldRepository; + private GameSessionTenantAssociationRepository gameSessionAssociationRepository; + private Server server; + private AtomicReference responseMutation; + + @BeforeAll + static void generateEphemeralPki() throws Exception { + if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { + Security.addProvider(new BouncyCastleProvider()); + } + KeyPair caKeyPair = newRsaKeyPair(); + X500Name caName = new X500Name("CN=Authored Source Test CA, O=FireMUD Test"); + X509Certificate caCertificate = + issueCertificate( + caName, caKeyPair.getPublic(), caName, caKeyPair.getPrivate(), true, null, false); + pki = + new TestPki( + caCertificate, + issueLeaf( + caName, + caKeyPair.getPrivate(), + "game-design-service", + "spiffe://firemud/ns/test/sa/game-design-service", + true), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "wrong-game-design-server-workload", + "spiffe://firemud/ns/test/sa/world-management-service", + true), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "wrong-game-design-server-namespace", + "spiffe://firemud/ns/other-test/sa/game-design-service", + true), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "world-management-service", + "spiffe://firemud/ns/test/sa/world-management-service", + false), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "game-session-service", + "spiffe://firemud/ns/test/sa/game-session-service", + false), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "account-service", + "spiffe://firemud/ns/test/sa/account-service", + false), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "cross-namespace-game-session-service", + "spiffe://firemud/ns/other-test/sa/game-session-service", + false), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "trusted-certificate-without-workload-uri", + null, + false)); + } + + @BeforeEach + void startPhysicalReceiver() throws Exception { + gameRepository = mock(GameRepository.class); + associationService = mock(TenantAssociationMigrationService.class); + creationRepository = mock(GameTenantCreationRepository.class); + authoredWorldRepository = mock(GameAuthoredWorldSourceRepository.class); + gameSessionAssociationRepository = mock(GameSessionTenantAssociationRepository.class); + when(authoredWorldRepository.read(SOURCE_OPERATION_ID, TENANT_ID, "harbor-world", NAMESPACE)) + .thenReturn(Optional.of(SOURCE_EVIDENCE)); + responseMutation = new AtomicReference<>(ResponseMutation.NONE); + server = startReceiver(pki.gameDesignServerCertificate()); + } + + @AfterEach + void stopPhysicalReceiver() throws Exception { + if (server != null) { + stopServer(server); + server = null; + } + } + + @Test + void exactWorldAndGameSessionReadersResolveCompleteSourceReceiptThroughSharedClient( + @TempDir Path directory) throws Exception { + for (TestCertificate clientCertificate : + List.of(pki.worldManagementCertificate(), pki.gameSessionCertificate())) { + Path clientDirectory = directory.resolve(UUID.randomUUID().toString()); + AuthoredWorldSourceClient client = + newSharedClient(clientDirectory, server, clientCertificate); + try { + client.init(); + + assertThat(client.read(READ_REQUEST)).isEqualTo(SOURCE_EVIDENCE); + } finally { + client.close(); + } + } + + verify(authoredWorldRepository, times(2)) + .read(SOURCE_OPERATION_ID, TENANT_ID, "harbor-world", NAMESPACE); + } + + @Test + void wrongServiceNamespaceAndSharedCertificatesAreDeniedBeforeOwnerRead() throws Exception { + for (TestCertificate clientCertificate : + List.of( + pki.wrongServiceCertificate(), + pki.wrongNamespaceCertificate(), + pki.noWorkloadUriCertificate())) { + ManagedChannel channel = channel(server, clientCertificate, jwtToken()); + try { + assertStatus( + () -> sourceStub(channel).resolveAuthoredWorldSource(wireReadRequest()), + Status.Code.PERMISSION_DENIED); + } finally { + stopChannel(channel); + } + } + + verifyNoInteractions(authoredWorldRepository); + } + + @Test + void missingClientCertificateFailsWithTlsHandshakeEvidenceBeforeOwnerRead() throws Exception { + ManagedChannel channel = channel(server, null, null); + try { + assertTlsDenied( + () -> sourceStub(channel).resolveAuthoredWorldSource(wireReadRequest()), SOURCE_METHOD); + } finally { + stopChannel(channel); + } + + verifyNoInteractions(authoredWorldRepository); + } + + @Test + void jwtOnlyCallerWithoutClientCertificateFailsWithTlsHandshakeEvidence() throws Exception { + ManagedChannel channel = channel(server, null, jwtToken()); + try { + assertTlsDenied( + () -> sourceStub(channel).resolveAuthoredWorldSource(wireReadRequest()), SOURCE_METHOD); + } finally { + stopChannel(channel); + } + + verifyNoInteractions(authoredWorldRepository); + } + + @Test + void validJwtWithTrustedCertificateButNoWorkloadUriIsDeniedByPeerGuard() throws Exception { + ManagedChannel channel = channel(server, pki.noWorkloadUriCertificate(), jwtToken()); + try { + assertStatus( + () -> sourceStub(channel).resolveAuthoredWorldSource(wireReadRequest()), + Status.Code.PERMISSION_DENIED); + } finally { + stopChannel(channel); + } + + verifyNoInteractions(authoredWorldRepository); + } + + @Test + void sharedClientRefusesWrongGameDesignServerWorkloadAndNamespace(@TempDir Path directory) + throws Exception { + for (TestCertificate serverCertificate : + List.of(pki.wrongServerWorkloadCertificate(), pki.wrongServerNamespaceCertificate())) { + Server wrongIdentityServer = startReceiver(serverCertificate); + AuthoredWorldSourceClient client = + newSharedClient( + directory.resolve(UUID.randomUUID().toString()), + wrongIdentityServer, + pki.worldManagementCertificate()); + try { + client.init(); + assertServerPeerRefused(() -> client.read(READ_REQUEST)); + } finally { + client.close(); + stopServer(wrongIdentityServer); + } + } + + verify(authoredWorldRepository, times(2)) + .read(SOURCE_OPERATION_ID, TENANT_ID, "harbor-world", NAMESPACE); + } + + @Test + void sharedClientRejectsChangedRequestEchoSourceDigestAndUnknownFieldsOverSocket( + @TempDir Path directory) throws Exception { + AuthoredWorldSourceClient client = + newSharedClient(directory, server, pki.worldManagementCertificate()); + try { + client.init(); + + responseMutation.set(ResponseMutation.CHANGE_READ_REQUEST_ID); + assertClientCodecRejected(() -> client.read(READ_REQUEST), "read request echo changed"); + + responseMutation.set(ResponseMutation.CHANGE_SOURCE_DISPLAY_NAME); + assertClientCodecRejected( + () -> client.read(READ_REQUEST), "Request digest does not match the registration tuple"); + + responseMutation.set(ResponseMutation.CHANGE_EVIDENCE_DIGEST); + assertClientCodecRejected( + () -> client.read(READ_REQUEST), "Evidence digest does not match the immutable tuple"); + + responseMutation.set(ResponseMutation.ADD_UNKNOWN_FIELD); + assertClientCodecRejected( + () -> client.read(READ_REQUEST), "Authored-world source response contains unsupported"); + } finally { + client.close(); + } + + verify(authoredWorldRepository, times(4)) + .read(SOURCE_OPERATION_ID, TENANT_ID, "harbor-world", NAMESPACE); + } + + @Test + void unknownReadRequestFieldsAreRejectedByProductionServiceBeforeOwnerRead() throws Exception { + ManagedChannel channel = channel(server, pki.worldManagementCertificate(), jwtToken()); + ResolveAuthoredWorldSourceRequest unknownFieldRequest = + wireReadRequest().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build(); + try { + assertStatus( + () -> sourceStub(channel).resolveAuthoredWorldSource(unknownFieldRequest), + Status.Code.INVALID_ARGUMENT); + } finally { + stopChannel(channel); + } + + verifyNoInteractions(authoredWorldRepository); + } + + @Test + void productionYamlAndSocketGuardsKeepWorldAccessLimitedToExactSourceMethod() throws Exception { + for (String profile : List.of("application.yml", "application-prod.yml")) { + Set tenantIdentityBypassMethods = + publicMethods(profile).stream() + .filter(method -> method.startsWith("gamedesign.v1.TenantIdentityService/")) + .collect(java.util.stream.Collectors.toSet()); + assertThat(tenantIdentityBypassMethods) + .containsExactlyInAnyOrderElementsOf(TENANT_IDENTITY_JWT_BYPASS_METHODS); + } + + ManagedChannel channel = channel(server, pki.worldManagementCertificate(), jwtToken()); + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub = sourceStub(channel); + try { + assertStatus( + () -> + stub.resolveLegacyGameTenantIdentity( + ResolveLegacyGameTenantIdentityRequest.newBuilder() + .setLegacyGameTenantId("legacy-game-17") + .build()), + Status.Code.PERMISSION_DENIED); + assertStatus( + () -> + stub.resolveLegacyAccountTenantAssociation( + ResolveLegacyAccountTenantAssociationRequest.newBuilder() + .setLegacyAccountTenantId(17L) + .build()), + Status.Code.PERMISSION_DENIED); + assertStatus( + () -> + stub.resolveFreshTenantCreation( + ResolveFreshTenantCreationRequest.getDefaultInstance()), + Status.Code.PERMISSION_DENIED); + assertStatus( + () -> + stub.resolveRuntimeTenantIdentity( + ResolveRuntimeTenantIdentityRequest.getDefaultInstance()), + Status.Code.PERMISSION_DENIED); + assertStatus( + () -> + stub.resolveLegacyGameSessionTenantAssociation( + ResolveLegacyGameSessionTenantAssociationRequest.getDefaultInstance()), + Status.Code.PERMISSION_DENIED); + } finally { + stopChannel(channel); + } + + verifyNoInteractions( + gameRepository, + associationService, + creationRepository, + authoredWorldRepository, + gameSessionAssociationRepository); + } + + private Server startReceiver(TestCertificate serverCertificate) throws Exception { + TenantIdentityGrpcService service = + new TenantIdentityGrpcService( + gameRepository, + associationService, + creationRepository, + authoredWorldRepository, + gameSessionAssociationRepository, + NAMESPACE); + Set unauthenticatedMethods = publicMethods("application.yml"); + return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + serverCertificate.privateKey(), serverCertificate.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + service, + responseMutationInterceptor(responseMutation), + new AuthTokenInterceptor(new JwtUtil(JWT_SECRET, 60_000L), unauthenticatedMethods), + new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private AuthoredWorldSourceClient newSharedClient( + Path directory, Server receiver, TestCertificate clientCertificate) throws Exception { + Files.createDirectories(directory); + Path caCertificate = + writePem(directory.resolve("test-ca.crt"), "CERTIFICATE", pki.caCertificate().getEncoded()); + Path certificate = + writePem( + directory.resolve("client.crt"), + "CERTIFICATE", + clientCertificate.certificate().getEncoded()); + Path privateKey = + writePem( + directory.resolve("client.key"), + "PRIVATE KEY", + clientCertificate.privateKey().getEncoded()); + + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(certificate.toString()); + tls.setPrivateKey(privateKey.toString()); + tls.setCaCert(caCertificate.toString()); + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("localhost:" + receiver.getPort()); + return new AuthoredWorldSourceClient(endpoints, tls, new GrpcChannelFactory(), NAMESPACE); + } + + private ManagedChannel channel(Server receiver, TestCertificate clientCertificate, String jwt) + throws Exception { + NettyChannelBuilder builder = + NettyChannelBuilder.forAddress(new InetSocketAddress("127.0.0.1", receiver.getPort())) + .sslContext(clientSslContext(clientCertificate)); + if (jwt != null) { + Metadata headers = new Metadata(); + headers.put( + Metadata.Key.of(AUTHORIZATION, Metadata.ASCII_STRING_MARSHALLER), "Bearer " + jwt); + builder.intercept(MetadataUtils.newAttachHeadersInterceptor(headers)); + } + return builder.build(); + } + + private static io.grpc.netty.shaded.io.netty.handler.ssl.SslContext clientSslContext( + TestCertificate clientCertificate) throws Exception { + var builder = GrpcSslContexts.forClient().trustManager(pki.caCertificate()); + if (clientCertificate != null) { + builder.keyManager(clientCertificate.privateKey(), clientCertificate.certificate()); + } + return builder.build(); + } + + private static TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub sourceStub( + ManagedChannel channel) { + return TenantIdentityServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(3, TimeUnit.SECONDS); + } + + private static ResolveAuthoredWorldSourceRequest wireReadRequest() { + return AuthoredWorldSourceGrpcCodec.toReadRequest(READ_REQUEST); + } + + private String jwtToken() { + JwtUtil jwtUtil = new JwtUtil(JWT_SECRET, 60_000L); + return jwtUtil.generateToken( + "service:world-management-service", + Map.of( + "accountId", + "", + "globalRoles", + List.of(), + "scopedRoles", + Map.of(), + "internalService", + true, + "serviceName", + "world-management-service")); + } + + private static ServerInterceptor responseMutationInterceptor( + AtomicReference pendingMutation) { + return new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + ServerCall forwardingCall = + new SimpleForwardingServerCall<>(call) { + @Override + public void sendMessage(RespT message) { + super.sendMessage( + mutateResponse(message, pendingMutation.getAndSet(ResponseMutation.NONE))); + } + }; + return next.startCall(forwardingCall, headers); + } + }; + } + + @SuppressWarnings("unchecked") + private static Response mutateResponse(Response response, ResponseMutation mutation) { + if (mutation == ResponseMutation.NONE) { + return response; + } + if (!(response instanceof ResolveAuthoredWorldSourceResponse source)) { + throw new IllegalStateException("Response mutation does not match the source read RPC"); + } + return (Response) + switch (mutation) { + case CHANGE_READ_REQUEST_ID -> + source.toBuilder().setRequestId("55555555-5555-4555-8555-555555555555").build(); + case CHANGE_SOURCE_DISPLAY_NAME -> + source.toBuilder().setWorldDisplayName("Changed display name").build(); + case CHANGE_EVIDENCE_DIGEST -> + source.toBuilder().setEvidenceDigest("sha256:" + "f".repeat(64)).build(); + case ADD_UNKNOWN_FIELD -> + source.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build(); + case NONE -> source; + }; + } + + private static void assertStatus(Runnable call, Status.Code expectedCode) { + Throwable failure = catchFailure(call); + assertThat(failure) + .as("RPC should fail with %s: %s", expectedCode, diagnostics(failure)) + .isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(failure).getCode()) + .as("RPC denial evidence: %s", diagnostics(failure)) + .isEqualTo(expectedCode); + } + + private static void assertServerPeerRefused(Runnable call) { + Throwable failure = catchFailure(call); + assertThat(failure).isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(Status.fromThrowable(failure).getDescription()) + .contains("exact authenticated server workload identity"); + } + + private static void assertClientCodecRejected(Runnable call, String expectedEvidence) { + Throwable failure = catchFailure(call); + assertThat(failure).isInstanceOf(IllegalStateException.class); + assertThat(diagnostics(failure)).contains(expectedEvidence); + } + + private static void assertTlsDenied(Runnable call, String method) { + Throwable failure = catchFailure(call); + assertThat(failure) + .as( + "%s must fail with client-certificate handshake evidence: %s", + method, diagnostics(failure)) + .isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(failure).getCode()) + .as( + "%s must fail at TLS rather than by application timeout: %s", + method, diagnostics(failure)) + .isEqualTo(Status.Code.UNAVAILABLE); + assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)) + .as( + "%s cause chain must identify client-certificate rejection: %s", + method, diagnostics(failure)) + .isTrue(); + } + + private static Set publicMethods(String resourceName) throws IOException { + ConfigurableEnvironment environment = new StandardEnvironment(); + environment + .getPropertySources() + .remove(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME); + environment + .getPropertySources() + .remove(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME); + for (var propertySource : + new YamlPropertySourceLoader() + .load(resourceName, new FileSystemResource("src/main/resources/" + resourceName))) { + environment.getPropertySources().addFirst(propertySource); + } + return Set.copyOf( + Binder.get(environment) + .bind("firemud.auth.grpc.public-methods", Bindable.listOf(String.class)) + .orElse(List.of())); + } + + private static AuthoredWorldSourceEvidence sourceEvidence() { + String tenantSlug = "firemud"; + String worldSlug = "harbor-world"; + String worldDisplayName = "Harbor World"; + String sourceGameTenantKey = "legacy-game-17"; + String provenanceKind = "NEW_GAME_ROW"; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, REGISTRATION_REQUEST_ID, TENANT_ID, tenantSlug, worldSlug, worldDisplayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + REGISTRATION_REQUEST_ID, + SOURCE_OPERATION_ID, + requestDigest, + TENANT_ID, + tenantSlug, + worldSlug, + worldDisplayName, + 17L, + sourceGameTenantKey, + provenanceKind); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + REGISTRATION_REQUEST_ID, + SOURCE_OPERATION_ID, + requestDigest, + TENANT_ID, + tenantSlug, + worldSlug, + worldDisplayName, + 17L, + sourceGameTenantKey, + provenanceKind, + evidenceDigest); + } + + private static Path writePem(Path path, String label, byte[] encoded) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(encoded); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + + private static void stopServer(Server server) throws InterruptedException { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + + private static void stopChannel(ManagedChannel channel) throws InterruptedException { + channel.shutdownNow(); + assertThat(channel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + + private static Throwable catchFailure(Runnable action) { + try { + action.run(); + return null; + } catch (Throwable throwable) { + return throwable; + } + } + + private static String diagnostics(Throwable throwable) { + if (throwable == null) { + return "RPC unexpectedly completed"; + } + StringBuilder result = new StringBuilder(); + for (Throwable current = throwable; current != null; current = current.getCause()) { + if (!result.isEmpty()) { + result.append(" <- "); + } + result.append(current.getClass().getName()).append(": ").append(current.getMessage()); + } + return result.toString(); + } + + private static TestCertificate issueLeaf( + X500Name caName, + PrivateKey caPrivateKey, + String commonName, + String workloadUri, + boolean serverCertificate) + throws Exception { + KeyPair keyPair = newRsaKeyPair(); + X500Name subject = new X500Name("CN=" + commonName + ", O=FireMUD Test"); + GeneralName[] subjectAltNames = + workloadUri == null + ? new GeneralName[] { + new GeneralName(GeneralName.dNSName, "localhost"), + new GeneralName(GeneralName.iPAddress, "127.0.0.1") + } + : new GeneralName[] { + new GeneralName(GeneralName.uniformResourceIdentifier, workloadUri), + new GeneralName(GeneralName.dNSName, "localhost"), + new GeneralName(GeneralName.iPAddress, "127.0.0.1") + }; + X509Certificate certificate = + issueCertificate( + subject, + keyPair.getPublic(), + caName, + caPrivateKey, + false, + new GeneralNames(subjectAltNames), + serverCertificate); + return new TestCertificate(keyPair.getPrivate(), certificate); + } + + private static X509Certificate issueCertificate( + X500Name subject, + java.security.PublicKey publicKey, + X500Name issuer, + PrivateKey issuerPrivateKey, + boolean ca, + GeneralNames subjectAltNames, + boolean serverCertificate) + throws Exception { + Instant now = Instant.now().minusSeconds(60L); + JcaX509v3CertificateBuilder builder = + new JcaX509v3CertificateBuilder( + issuer, + BigInteger.valueOf(CERTIFICATE_SERIAL.getAndIncrement()), + Date.from(now), + Date.from(now.plusSeconds(60L * 60L * 24L * 14L)), + subject, + publicKey); + builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(ca)); + if (ca) { + builder.addExtension( + Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign)); + } else { + builder.addExtension( + Extension.keyUsage, + true, + new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); + builder.addExtension( + Extension.extendedKeyUsage, + false, + new ExtendedKeyUsage( + serverCertificate ? KeyPurposeId.id_kp_serverAuth : KeyPurposeId.id_kp_clientAuth)); + builder.addExtension(Extension.subjectAlternativeName, false, subjectAltNames); + } + return new JcaX509CertificateConverter() + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .getCertificate( + builder.build( + new JcaContentSignerBuilder("SHA256withRSA") + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .build(issuerPrivateKey))); + } + + private static KeyPair newRsaKeyPair() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + return generator.generateKeyPair(); + } + + private record TestCertificate(PrivateKey privateKey, X509Certificate certificate) {} + + private enum ResponseMutation { + NONE, + CHANGE_READ_REQUEST_ID, + CHANGE_SOURCE_DISPLAY_NAME, + CHANGE_EVIDENCE_DIGEST, + ADD_UNKNOWN_FIELD + } + + private record TestPki( + X509Certificate caCertificate, + TestCertificate gameDesignServerCertificate, + TestCertificate wrongServerWorkloadCertificate, + TestCertificate wrongServerNamespaceCertificate, + TestCertificate worldManagementCertificate, + TestCertificate gameSessionCertificate, + TestCertificate wrongServiceCertificate, + TestCertificate wrongNamespaceCertificate, + TestCertificate noWorkloadUriCertificate) {} +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java index 3c21b864b8..ae3d687b19 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java @@ -57,6 +57,11 @@ class TenantIdentityGrpcServiceTest { "spiffe://firemud/ns/test/sa/game-session-service"; private static final String WRONG_NAMESPACE_GAME_SESSION_PEER = "spiffe://firemud/ns/other/sa/game-session-service"; + private static final String WORLD_MANAGEMENT_PEER = + "spiffe://firemud/ns/test/sa/world-management-service"; + private static final String WRONG_NAMESPACE_WORLD_MANAGEMENT_PEER = + "spiffe://firemud/ns/other/sa/world-management-service"; + private static final String GAME_DESIGN_PEER = "spiffe://firemud/ns/test/sa/game-design-service"; private static final UUID CANONICAL_TENANT_ID = UUID.fromString("87426bb3-a733-43f0-9c8e-2e379cbdf7ec"); private static final UUID FRESH_CREATION_REQUEST_ID = @@ -93,19 +98,47 @@ class TenantIdentityGrpcServiceTest { "test"); @Test - void authoredSourceReadRequiresExactGameSessionPeerBeforeOwnerAccess() { + void authoredSourceReadRejectsUnrelatedOrWrongNamespacePeersBeforeOwnerAccess() { for (String peer : new String[] { - null, ACCOUNT_PEER, ACCOUNT_MIGRATOR_PEER, WRONG_NAMESPACE_GAME_SESSION_PEER + null, + ACCOUNT_PEER, + ACCOUNT_MIGRATOR_PEER, + WRONG_NAMESPACE_GAME_SESSION_PEER, + WRONG_NAMESPACE_WORLD_MANAGEMENT_PEER, + GAME_DESIGN_PEER }) { AuthoredSourceObserver observer = authoredSourceCall(authoredSourceRequest(), peer); assertEquals(Status.Code.PERMISSION_DENIED, observer.errorCode); assertNull(observer.value); assertFalse(observer.completed); } + AuthoredSourceObserver malformedRequestWithWrongPeer = + authoredSourceCall( + authoredSourceRequest().toBuilder().setRequestId("malformed").build(), + GAME_DESIGN_PEER); + assertEquals(Status.Code.PERMISSION_DENIED, malformedRequestWithWrongPeer.errorCode); verifyNoInteractions(authoredWorldRepository); } + @Test + void authoredSourceReadAllowsExactSameNamespaceWorldManagementPeer() { + AuthoredWorldSourceEvidence evidence = authoredSourceEvidence("test"); + when(authoredWorldRepository.read(FRESH_OPERATION_ID, RUNTIME_TENANT_ID, "world-one", "test")) + .thenReturn(Optional.of(evidence)); + + AuthoredSourceObserver observer = + authoredSourceCall(authoredSourceRequest(), WORLD_MANAGEMENT_PEER); + + assertNull(observer.errorCode); + assertTrue(observer.completed); + assertNotNull(observer.value); + assertEquals(RUNTIME_REQUEST_ID.toString(), observer.value.getRequestId()); + assertEquals(evidence.evidenceDigest(), observer.value.getEvidenceDigest()); + verify(authoredWorldRepository) + .read(FRESH_OPERATION_ID, RUNTIME_TENANT_ID, "world-one", "test"); + } + @Test void authoredSourceRejectsMalformedTupleAndUnknownFieldsBeforeRead() { ResolveAuthoredWorldSourceRequest exact = authoredSourceRequest(); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClient.java index 5a73e5ea7f..f932e7164d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClient.java @@ -12,12 +12,10 @@ import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; -import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceGrpcCodec; import net.firedevops.firemud.common.tenant.GameSessionTenantAssociationEvidence; import net.firedevops.firemud.common.tenant.RuntimeTenantIdentityEvidence; -import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceRequest; -import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceResponse; import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameSessionTenantAssociationRequest; import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameSessionTenantAssociationResponse; import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityRequest; @@ -136,59 +134,24 @@ public AuthoredWorldSourceEvidence resolveAuthoredWorldSource( UUID tenantUuid = parseCanonicalNonNilUuid(canonicalTenantId, "canonical tenant ID"); UUID operationUuid = parseCanonicalNonNilUuid(operationId, "operation ID"); UUID requestUuid = parseCanonicalNonNilUuid(requestId, "request ID"); - AuthoredWorldSourceDigest.validateReadSelector(workloadNamespace, tenantUuid, worldSlug); + AuthoredWorldSourceGrpcCodec.ReadRequest readRequest = + new AuthoredWorldSourceGrpcCodec.ReadRequest( + workloadNamespace, requestUuid, operationUuid, tenantUuid, worldSlug); TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub currentStub = stub(); if (currentStub == null) { throw new IllegalStateException( "Game Design authored-world source client is not initialized"); } - ResolveAuthoredWorldSourceResponse response = + var response = currentStub .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) - .resolveAuthoredWorldSource( - ResolveAuthoredWorldSourceRequest.newBuilder() - .setRequestId(requestUuid.toString()) - .setOperationId(operationUuid.toString()) - .setCanonicalTenantId(tenantUuid.toString()) - .setWorldSlug(worldSlug) - .build()); - if (!response.getUnknownFields().asMap().isEmpty()) { - throw new IllegalStateException("Authored-world source response contains unsupported fields"); - } - AuthoredWorldSourceEvidence evidence; + .resolveAuthoredWorldSource(AuthoredWorldSourceGrpcCodec.toReadRequest(readRequest)); try { - UUID echoedRequest = parseCanonicalNonNilUuid(response.getRequestId(), "response request ID"); - if (!requestUuid.equals(echoedRequest)) { - throw new IllegalArgumentException("Authored-world source read request identity changed"); - } - evidence = - new AuthoredWorldSourceEvidence( - response.getSchemaVersion(), - response.getTargetNamespace(), - parseCanonicalNonNilUuid( - response.getRegistrationRequestId(), "registration request ID"), - parseCanonicalNonNilUuid(response.getOperationId(), "response operation ID"), - response.getRequestDigest(), - parseCanonicalNonNilUuid( - response.getCanonicalTenantId(), "response canonical tenant ID"), - response.getTenantSlug(), - response.getWorldSlug(), - response.getWorldDisplayName(), - response.getSourceGameRowId(), - response.getSourceGameTenantKey(), - response.getProvenanceKind(), - response.getEvidenceDigest()); + return AuthoredWorldSourceGrpcCodec.fromReadResponse(readRequest, response); } catch (IllegalArgumentException exception) { - throw new IllegalStateException("Authored-world source response is invalid", exception); - } - if (!workloadNamespace.equals(evidence.targetNamespace()) - || !tenantUuid.equals(evidence.canonicalTenantId()) - || !operationUuid.equals(evidence.operationId()) - || !worldSlug.equals(evidence.worldSlug())) { throw new IllegalStateException( - "Authored-world source response does not match the exact request"); + "Game Design authored-world source response is invalid", exception); } - return evidence; } /** diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClientTest.java index 72c0d28e51..d558f7ab7b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClientTest.java @@ -154,7 +154,8 @@ void authoredSourceRejectsCoherentReceiptsForAnotherNamespaceTenantOperationOrWo "world-one", REQUEST_ID.toString())) .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("does not match the exact request"); + .hasCauseInstanceOf(IllegalArgumentException.class) + .hasRootCauseMessage("Authored-world source response does not match the exact request"); } } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeDigest.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeDigest.java new file mode 100644 index 0000000000..6b40dbf5ed --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeDigest.java @@ -0,0 +1,112 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; + +/** Versioned World-owned request and receipt digests for fresh authored-source intake. */ +public final class WorldAuthoredSourceIntakeDigest { + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private WorldAuthoredSourceIntakeDigest() {} + + public static String requestDigest( + String targetNamespace, UUID intakeRequestId, AuthoredWorldSourceEvidence source) { + requireNonNil(intakeRequestId, "intakeRequestId"); + requireFreshSource(targetNamespace, source); + return digest( + "world-authored-source-intake-request/v1", + targetNamespace, + intakeRequestId.toString(), + source.canonicalTenantId().toString(), + source.worldSlug(), + source.operationId().toString(), + source.evidenceDigest()); + } + + public static String receiptDigest( + String targetNamespace, + UUID operationId, + String requestDigest, + AuthoredWorldSourceEvidence source, + long localTenantKey) { + requireNonNil(operationId, "operationId"); + requireDigest(requestDigest, "requestDigest"); + requireFreshSource(targetNamespace, source); + if (localTenantKey <= 0) { + throw new IllegalArgumentException("localTenantKey must be positive"); + } + return digest( + "world-authored-source-intake-receipt/v1", + targetNamespace, + operationId.toString(), + requestDigest, + source.canonicalTenantId().toString(), + source.worldSlug(), + source.operationId().toString(), + source.evidenceDigest(), + Long.toString(localTenantKey)); + } + + static void requireFreshSource(String targetNamespace, AuthoredWorldSourceEvidence source) { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + Objects.requireNonNull(source, "source"); + if (!"NEW_GAME_ROW".equals(source.provenanceKind())) { + throw new IllegalArgumentException( + "Fresh World authored-source intake requires NEW_GAME_ROW provenance"); + } + if (!targetNamespace.equals(source.targetNamespace())) { + throw new IllegalArgumentException("Source namespace differs from the intake namespace"); + } + AuthoredWorldSourceDigest.validateReadSelector( + targetNamespace, source.canonicalTenantId(), source.worldSlug()); + new AuthoredWorldSourceEvidence( + source.schemaVersion(), + source.targetNamespace(), + source.registrationRequestId(), + source.operationId(), + source.requestDigest(), + source.canonicalTenantId(), + source.tenantSlug(), + source.worldSlug(), + source.worldDisplayName(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.evidenceDigest()); + } + + private static String digest(String... segments) { + try { + MessageDigest hash = MessageDigest.getInstance("SHA-256"); + for (String segment : segments) { + byte[] bytes = segment.getBytes(StandardCharsets.UTF_8); + hash.update(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + hash.update((byte) ':'); + hash.update(bytes); + } + return "sha256:" + HexFormat.of().formatHex(hash.digest()); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + } + + private static void requireDigest(String value, String label) { + if (value == null || !SHA256.matcher(value).matches()) { + throw new IllegalArgumentException(label + " must be a canonical SHA-256 digest"); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeReceipt.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeReceipt.java new file mode 100644 index 0000000000..b25bbf5c34 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeReceipt.java @@ -0,0 +1,61 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; + +/** Complete immutable World-owned receipt for one fresh Game Design source intake. */ +public record WorldAuthoredSourceIntakeReceipt( + int schemaVersion, + String targetNamespace, + UUID intakeRequestId, + UUID operationId, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String sourceEvidenceDigest, + String requestDigest, + String receiptDigest, + long localTenantKey, + AuthoredWorldSourceEvidence source) { + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public WorldAuthoredSourceIntakeReceipt { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported World authored-source receipt version"); + } + Objects.requireNonNull(targetNamespace, "targetNamespace"); + requireNonNil(intakeRequestId, "intakeRequestId"); + requireNonNil(operationId, "operationId"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + Objects.requireNonNull(worldSlug, "worldSlug"); + requireNonNil(sourceOperationId, "sourceOperationId"); + Objects.requireNonNull(sourceEvidenceDigest, "sourceEvidenceDigest"); + Objects.requireNonNull(requestDigest, "requestDigest"); + Objects.requireNonNull(receiptDigest, "receiptDigest"); + Objects.requireNonNull(source, "source"); + if (localTenantKey <= 0) { + throw new IllegalArgumentException("localTenantKey must be positive"); + } + WorldAuthoredSourceIntakeDigest.requireFreshSource(targetNamespace, source); + if (!targetNamespace.equals(source.targetNamespace()) + || !canonicalTenantId.equals(source.canonicalTenantId()) + || !worldSlug.equals(source.worldSlug()) + || !sourceOperationId.equals(source.operationId()) + || !sourceEvidenceDigest.equals(source.evidenceDigest()) + || !requestDigest.equals( + WorldAuthoredSourceIntakeDigest.requestDigest(targetNamespace, intakeRequestId, source)) + || !receiptDigest.equals( + WorldAuthoredSourceIntakeDigest.receiptDigest( + targetNamespace, operationId, requestDigest, source, localTenantKey))) { + throw new IllegalArgumentException("World authored-source receipt fields or digests differ"); + } + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeRepository.java new file mode 100644 index 0000000000..38100db605 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeRepository.java @@ -0,0 +1,576 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.Connection; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.Table; +import org.jooq.impl.DSL; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * World-owned immutable copy of authenticated, fresh Game Design authored-world source evidence. + */ +@Repository +public class WorldAuthoredSourceIntakeRepository { + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Table TENANT_ASSOCIATION = + DSL.table(DSL.name("world_authored_source_tenant_association")); + private static final Table TENANT_KEY_RESERVATION = + DSL.table(DSL.name("world_authored_source_tenant_key_reservation")); + private static final Table INTAKE = DSL.table(DSL.name("world_authored_source_intake")); + + private static final Field TARGET_NAMESPACE = + DSL.field(DSL.name("target_namespace"), String.class); + private static final Field CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field TENANT_SLUG = DSL.field(DSL.name("tenant_slug"), String.class); + private static final Field SOURCE_GAME_ROW_ID = + DSL.field(DSL.name("source_game_row_id"), Long.class); + private static final Field SOURCE_GAME_TENANT_KEY = + DSL.field(DSL.name("source_game_tenant_key"), String.class); + private static final Field SOURCE_PROVENANCE_KIND = + DSL.field(DSL.name("source_provenance_kind"), String.class); + private static final Field LOCAL_TENANT_KEY = + DSL.field(DSL.name("local_tenant_key"), Long.class); + private static final Field RESERVED_TENANT_KEY = + DSL.field(DSL.name("tenant_key"), Long.class); + private static final Field RESERVATION_CLAIM_KIND = + DSL.field(DSL.name("claim_kind"), String.class); + private static final Field RESERVATION_NAMESPACE = + DSL.field(DSL.name("target_namespace"), String.class); + private static final Field RESERVATION_CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + + private static final Field OPERATION_ID = DSL.field(DSL.name("operation_id"), UUID.class); + private static final Field STORED_SCHEMA_VERSION = + DSL.field(DSL.name("schema_version"), Short.class); + private static final Field INTAKE_REQUEST_ID = + DSL.field(DSL.name("intake_request_id"), UUID.class); + private static final Field REQUEST_DIGEST = + DSL.field(DSL.name("request_digest"), String.class); + private static final Field SOURCE_SCHEMA_VERSION = + DSL.field(DSL.name("source_schema_version"), Short.class); + private static final Field SOURCE_REGISTRATION_REQUEST_ID = + DSL.field(DSL.name("source_registration_request_id"), UUID.class); + private static final Field SOURCE_OPERATION_ID = + DSL.field(DSL.name("source_operation_id"), UUID.class); + private static final Field SOURCE_REQUEST_DIGEST = + DSL.field(DSL.name("source_request_digest"), String.class); + private static final Field WORLD_SLUG = DSL.field(DSL.name("world_slug"), String.class); + private static final Field WORLD_DISPLAY_NAME = + DSL.field(DSL.name("world_display_name"), String.class); + private static final Field SOURCE_EVIDENCE_DIGEST = + DSL.field(DSL.name("source_evidence_digest"), String.class); + private static final Field RECEIPT_DIGEST = + DSL.field(DSL.name("receipt_digest"), String.class); + + private static final String LOCK_LEGACY_TENANT_TABLES = + "LOCK TABLE generation_rule, instance, region, region_instance, room, room_exit, " + + "room_instance, room_instance_exit, world_design_aggregate_epoch, " + + "world_design_revision_ledger, world_design_scope_epoch, " + + "world_entity_spawn_binding, world_event, world_instance, zone, zone_instance " + + "IN SHARE MODE"; + private static final String MAX_OCCUPIED_TENANT_KEY = + "SELECT COALESCE(MAX(occupied_key), 0) FROM (" + + "SELECT tenant_id AS occupied_key FROM generation_rule UNION ALL " + + "SELECT tenant_id FROM instance UNION ALL " + + "SELECT tenant_id FROM region UNION ALL " + + "SELECT tenant_id FROM region_instance UNION ALL " + + "SELECT tenant_id FROM room UNION ALL " + + "SELECT tenant_id FROM room_exit UNION ALL " + + "SELECT tenant_id FROM room_instance UNION ALL " + + "SELECT tenant_id FROM room_instance_exit UNION ALL " + + "SELECT tenant_id FROM world_design_aggregate_epoch UNION ALL " + + "SELECT tenant_id FROM world_design_revision_ledger UNION ALL " + + "SELECT tenant_id FROM world_design_scope_epoch UNION ALL " + + "SELECT tenant_id FROM world_entity_spawn_binding UNION ALL " + + "SELECT tenant_id FROM world_event UNION ALL " + + "SELECT tenant_id FROM world_instance UNION ALL " + + "SELECT tenant_id FROM zone UNION ALL " + + "SELECT tenant_id FROM zone_instance UNION ALL " + + "SELECT tenant_key FROM world_authored_source_tenant_key_reservation UNION ALL " + + "SELECT local_tenant_key FROM world_authored_source_tenant_association" + + ") AS occupied_tenant_keys"; + + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "The injected DSLContext is an internal Spring collaborator; construction acquires no resources and this repository has no finalizer.") + public WorldAuthoredSourceIntakeRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl must not be null"); + } + + /** + * Retains the complete fresh Game Design receipt and its World-local tenant association. + * + *

The caller must already have authenticated Game Design and opened the World owner + * transaction. This method does not accept a forwarded digest in place of source evidence. + */ + @Transactional(propagation = Propagation.MANDATORY) + public WorldAuthoredSourceIntakeReceipt acceptFresh( + String namespace, UUID intakeRequestId, AuthoredWorldSourceEvidence source) { + requireActiveOwnerTransaction(); + requireWritableReadCommittedOwnerTransaction(); + AuthoredWorldSourceEvidence validatedSource = validateFreshSource(namespace, source); + String requestDigest = + WorldAuthoredSourceIntakeDigest.requestDigest(namespace, intakeRequestId, validatedSource); + + Record priorRequest = findByRequest(namespace, intakeRequestId); + if (priorRequest != null) { + return requireExactReplay(priorRequest, intakeRequestId, requestDigest, validatedSource); + } + + lockFreshIntakeAndExistingTenantRows(); + + priorRequest = findByRequest(namespace, intakeRequestId); + if (priorRequest != null) { + return requireExactReplay(priorRequest, intakeRequestId, requestDigest, validatedSource); + } + requireUnclaimedSourceAndWorld(namespace, validatedSource); + + long localTenantKey = ensureTenantAssociation(validatedSource); + UUID operationId = UUID.randomUUID(); + String receiptDigest = + WorldAuthoredSourceIntakeDigest.receiptDigest( + namespace, operationId, requestDigest, validatedSource, localTenantKey); + + int inserted = + dsl.insertInto(INTAKE) + .set(OPERATION_ID, operationId) + .set(STORED_SCHEMA_VERSION, (short) SCHEMA_VERSION) + .set(TARGET_NAMESPACE, namespace) + .set(INTAKE_REQUEST_ID, intakeRequestId) + .set(REQUEST_DIGEST, requestDigest) + .set(LOCAL_TENANT_KEY, localTenantKey) + .set(SOURCE_SCHEMA_VERSION, (short) validatedSource.schemaVersion()) + .set(SOURCE_REGISTRATION_REQUEST_ID, validatedSource.registrationRequestId()) + .set(SOURCE_OPERATION_ID, validatedSource.operationId()) + .set(SOURCE_REQUEST_DIGEST, validatedSource.requestDigest()) + .set(CANONICAL_TENANT_ID, validatedSource.canonicalTenantId()) + .set(TENANT_SLUG, validatedSource.tenantSlug()) + .set(WORLD_SLUG, validatedSource.worldSlug()) + .set(WORLD_DISPLAY_NAME, validatedSource.worldDisplayName()) + .set(SOURCE_GAME_ROW_ID, validatedSource.sourceGameRowId()) + .set(SOURCE_GAME_TENANT_KEY, validatedSource.sourceGameTenantKey()) + .set(SOURCE_PROVENANCE_KIND, validatedSource.provenanceKind()) + .set(SOURCE_EVIDENCE_DIGEST, validatedSource.evidenceDigest()) + .set(RECEIPT_DIGEST, receiptDigest) + .execute(); + if (inserted != 1) { + throw new RegistrationConflictException("World authored-source intake was not inserted"); + } + + Record persisted = findByRequest(namespace, intakeRequestId); + if (persisted == null) { + throw new InvalidIntakeEvidenceException( + "World authored-source intake disappeared before owner readback"); + } + WorldAuthoredSourceIntakeReceipt receipt = toReceipt(persisted); + requireExactReceipt(receipt, intakeRequestId, requestDigest, validatedSource); + requireTenantAssociation(receipt); + return receipt; + } + + /** Reads a committed World intake by its exact namespace and stable request identity. */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional read(String namespace, UUID intakeRequestId) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "World authored-source intake read requires a committed-outcome owner read"); + } + validateReadKey(namespace, intakeRequestId); + Record record = findByRequest(namespace, intakeRequestId); + if (record == null) { + return Optional.empty(); + } + WorldAuthoredSourceIntakeReceipt receipt = toReceipt(record); + requireTenantAssociation(receipt); + return Optional.of(receipt); + } + + private void lockFreshIntakeAndExistingTenantRows() { + // Serialize allocator owners, then keep every current tenant-bearing table stable while the + // candidate is checked. Legacy writers do not take this association lock; their database + // reservation trigger rejects selectors already claimed by a canonical source. + dsl.execute("LOCK TABLE world_authored_source_tenant_association IN SHARE ROW EXCLUSIVE MODE"); + dsl.execute(LOCK_LEGACY_TENANT_TABLES); + } + + private void requireUnclaimedSourceAndWorld( + String namespace, AuthoredWorldSourceEvidence source) { + if (findBySourceOperation(namespace, source.operationId()) != null) { + throw new RegistrationConflictException( + "Game Design source operation is already claimed by another World intake"); + } + if (findBySourceRegistrationRequest(namespace, source.registrationRequestId()) != null) { + throw new RegistrationConflictException( + "Game Design source registration request is already claimed by another World intake"); + } + if (findByWorldSelector(namespace, source.canonicalTenantId(), source.worldSlug()) != null) { + throw new RegistrationConflictException( + "World selector is already associated with different source evidence"); + } + } + + private long ensureTenantAssociation(AuthoredWorldSourceEvidence source) { + Record existing = findTenantAssociation(source.targetNamespace(), source.canonicalTenantId()); + if (existing != null) { + requireMatchingTenantAssociation(existing, source); + long existingKey = Objects.requireNonNull(existing.get(LOCAL_TENANT_KEY, Long.class)); + requireCanonicalTenantKeyReservation(source, existingKey); + return existingKey; + } + + if (findTenantSlugAssociation(source.targetNamespace(), source.tenantSlug()) != null) { + throw new RegistrationConflictException( + "Tenant selector is already associated with another canonical tenant"); + } + if (findSourceRowAssociation(source.targetNamespace(), source.sourceGameRowId()) != null) { + throw new RegistrationConflictException( + "Game Design source row is already associated with another canonical tenant"); + } + + long localTenantKey = nextUnclaimedTenantKey(); + int inserted = + dsl.insertInto(TENANT_ASSOCIATION) + .set(TARGET_NAMESPACE, source.targetNamespace()) + .set(CANONICAL_TENANT_ID, source.canonicalTenantId()) + .set(TENANT_SLUG, source.tenantSlug()) + .set(SOURCE_GAME_ROW_ID, source.sourceGameRowId()) + .set(SOURCE_GAME_TENANT_KEY, source.sourceGameTenantKey()) + .set(SOURCE_PROVENANCE_KIND, source.provenanceKind()) + .set(LOCAL_TENANT_KEY, localTenantKey) + .onConflictDoNothing() + .execute(); + if (inserted == 1) { + requireCanonicalTenantKeyReservation(source, localTenantKey); + return localTenantKey; + } + + existing = findTenantAssociation(source.targetNamespace(), source.canonicalTenantId()); + if (existing != null) { + requireMatchingTenantAssociation(existing, source); + long existingKey = Objects.requireNonNull(existing.get(LOCAL_TENANT_KEY, Long.class)); + requireCanonicalTenantKeyReservation(source, existingKey); + return existingKey; + } + if (findTenantSlugAssociation(source.targetNamespace(), source.tenantSlug()) != null) { + throw new RegistrationConflictException( + "Tenant selector is already associated with another canonical tenant"); + } + if (findSourceRowAssociation(source.targetNamespace(), source.sourceGameRowId()) != null) { + throw new RegistrationConflictException( + "Game Design source row is already associated with another canonical tenant"); + } + throw new RegistrationConflictException( + "World authored-source tenant association conflicts with an owner claim"); + } + + private long nextUnclaimedTenantKey() { + Record allocation = dsl.fetchOne(MAX_OCCUPIED_TENANT_KEY); + if (allocation == null) { + throw new IllegalStateException("World tenant-selector allocation aggregate returned no row"); + } + Long maxKey = allocation.get(0, Long.class); + if (maxKey == null) { + throw new IllegalStateException("World tenant-selector allocation aggregate returned null"); + } + long currentMax = maxKey; + if (currentMax == Long.MAX_VALUE) { + throw new IllegalStateException("World has no remaining positive local tenant selectors"); + } + return Math.max(currentMax, 0L) + 1L; + } + + private void requireCanonicalTenantKeyReservation( + AuthoredWorldSourceEvidence source, long localTenantKey) { + dsl.insertInto(TENANT_KEY_RESERVATION) + .set(RESERVED_TENANT_KEY, localTenantKey) + .set(RESERVATION_CLAIM_KIND, "CANONICAL_AUTHORED_SOURCE") + .set(RESERVATION_NAMESPACE, source.targetNamespace()) + .set(RESERVATION_CANONICAL_TENANT_ID, source.canonicalTenantId()) + .onConflictDoNothing() + .execute(); + Record reservation = findTenantKeyReservation(localTenantKey); + if (reservation == null + || !Objects.equals( + reservation.get(RESERVATION_CLAIM_KIND, String.class), "CANONICAL_AUTHORED_SOURCE") + || !Objects.equals( + reservation.get(RESERVATION_NAMESPACE, String.class), source.targetNamespace()) + || !Objects.equals( + reservation.get(RESERVATION_CANONICAL_TENANT_ID, UUID.class), + source.canonicalTenantId())) { + throw new RegistrationConflictException( + "World local tenant selector is already reserved by another claim"); + } + } + + private void requireTenantAssociation(WorldAuthoredSourceIntakeReceipt receipt) { + Record association = + findTenantAssociation(receipt.targetNamespace(), receipt.canonicalTenantId()); + if (association == null) { + throw new InvalidIntakeEvidenceException( + "World authored-source tenant association is missing"); + } + requireMatchingTenantAssociation(association, receipt.source()); + if (!Objects.equals(association.get(LOCAL_TENANT_KEY, Long.class), receipt.localTenantKey())) { + throw new InvalidIntakeEvidenceException( + "World authored-source private tenant selector differs from its association"); + } + Record reservation = findTenantKeyReservation(receipt.localTenantKey()); + if (reservation == null + || !Objects.equals( + reservation.get(RESERVATION_CLAIM_KIND, String.class), "CANONICAL_AUTHORED_SOURCE") + || !Objects.equals( + reservation.get(RESERVATION_NAMESPACE, String.class), receipt.targetNamespace()) + || !Objects.equals( + reservation.get(RESERVATION_CANONICAL_TENANT_ID, UUID.class), + receipt.canonicalTenantId())) { + throw new InvalidIntakeEvidenceException( + "World authored-source private tenant selector reservation is missing or changed"); + } + } + + private Record findTenantKeyReservation(long tenantKey) { + return dsl.selectFrom(TENANT_KEY_RESERVATION) + .where(RESERVED_TENANT_KEY.eq(tenantKey)) + .fetchOne(); + } + + private void requireMatchingTenantAssociation( + Record association, AuthoredWorldSourceEvidence source) { + if (!Objects.equals(association.get(TARGET_NAMESPACE, String.class), source.targetNamespace()) + || !Objects.equals( + association.get(CANONICAL_TENANT_ID, UUID.class), source.canonicalTenantId()) + || !Objects.equals(association.get(TENANT_SLUG, String.class), source.tenantSlug()) + || !Objects.equals( + association.get(SOURCE_GAME_ROW_ID, Long.class), source.sourceGameRowId()) + || !Objects.equals( + association.get(SOURCE_GAME_TENANT_KEY, String.class), source.sourceGameTenantKey()) + || !Objects.equals( + association.get(SOURCE_PROVENANCE_KIND, String.class), source.provenanceKind())) { + throw new RegistrationConflictException( + "Canonical tenant source or stable tenant selector conflicts with its World association"); + } + } + + private WorldAuthoredSourceIntakeReceipt requireExactReplay( + Record record, + UUID intakeRequestId, + String requestDigest, + AuthoredWorldSourceEvidence source) { + WorldAuthoredSourceIntakeReceipt receipt = toReceipt(record); + requireExactReceipt(receipt, intakeRequestId, requestDigest, source); + requireTenantAssociation(receipt); + return receipt; + } + + private void requireExactReceipt( + WorldAuthoredSourceIntakeReceipt receipt, + UUID intakeRequestId, + String requestDigest, + AuthoredWorldSourceEvidence source) { + if (!receipt.intakeRequestId().equals(intakeRequestId) + || !receipt.requestDigest().equals(requestDigest) + || !receipt.source().equals(source)) { + throw new RegistrationConflictException( + "World intake request identity was reused with changed scope or source evidence"); + } + } + + private AuthoredWorldSourceEvidence validateFreshSource( + String namespace, AuthoredWorldSourceEvidence source) { + Objects.requireNonNull(namespace, "namespace"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new InvalidIntakeEvidenceException( + "World authored-source target namespace must be one canonical DNS label"); + } + Objects.requireNonNull(source, "source"); + try { + AuthoredWorldSourceEvidence validated = + new AuthoredWorldSourceEvidence( + source.schemaVersion(), + source.targetNamespace(), + source.registrationRequestId(), + source.operationId(), + source.requestDigest(), + source.canonicalTenantId(), + source.tenantSlug(), + source.worldSlug(), + source.worldDisplayName(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.evidenceDigest()); + WorldAuthoredSourceIntakeDigest.requireFreshSource(namespace, validated); + return validated; + } catch (IllegalArgumentException exception) { + throw new InvalidIntakeEvidenceException( + "Game Design authored-world source evidence is invalid or not fresh", exception); + } + } + + private void validateReadKey(String namespace, UUID intakeRequestId) { + if (namespace == null || !GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("namespace must be one canonical DNS label"); + } + requireNonNil(intakeRequestId, "intakeRequestId"); + } + + private void requireActiveOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "World authored-source intake requires an active World owner transaction"); + } + } + + private void requireWritableReadCommittedOwnerTransaction() { + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "World authored-source intake requires a writable owner transaction"); + } + Integer declaredIsolation = + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + if (declaredIsolation != null && declaredIsolation != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "World authored-source intake requires READ COMMITTED isolation"); + } + Record settings = + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS transaction_isolation, " + + "current_setting('transaction_read_only') AS transaction_read_only"); + if (settings == null + || !"read committed".equalsIgnoreCase(settings.get("transaction_isolation", String.class)) + || !"off".equalsIgnoreCase(settings.get("transaction_read_only", String.class))) { + throw new IllegalStateException( + "World authored-source intake requires a writable READ COMMITTED owner transaction"); + } + } + + private Record findByRequest(String namespace, UUID intakeRequestId) { + return dsl.selectFrom(INTAKE) + .where(TARGET_NAMESPACE.eq(namespace).and(INTAKE_REQUEST_ID.eq(intakeRequestId))) + .fetchOne(); + } + + private Record findBySourceOperation(String namespace, UUID sourceOperationId) { + return dsl.selectFrom(INTAKE) + .where(TARGET_NAMESPACE.eq(namespace).and(SOURCE_OPERATION_ID.eq(sourceOperationId))) + .fetchOne(); + } + + private Record findBySourceRegistrationRequest(String namespace, UUID sourceRequestId) { + return dsl.selectFrom(INTAKE) + .where( + TARGET_NAMESPACE.eq(namespace).and(SOURCE_REGISTRATION_REQUEST_ID.eq(sourceRequestId))) + .fetchOne(); + } + + private Record findByWorldSelector(String namespace, UUID tenantId, String worldSlug) { + return dsl.selectFrom(INTAKE) + .where( + TARGET_NAMESPACE + .eq(namespace) + .and(CANONICAL_TENANT_ID.eq(tenantId)) + .and(WORLD_SLUG.eq(worldSlug))) + .fetchOne(); + } + + private Record findTenantAssociation(String namespace, UUID canonicalTenantId) { + return dsl.selectFrom(TENANT_ASSOCIATION) + .where(TARGET_NAMESPACE.eq(namespace).and(CANONICAL_TENANT_ID.eq(canonicalTenantId))) + .fetchOne(); + } + + private Record findTenantSlugAssociation(String namespace, String tenantSlug) { + return dsl.selectFrom(TENANT_ASSOCIATION) + .where(TARGET_NAMESPACE.eq(namespace).and(TENANT_SLUG.eq(tenantSlug))) + .fetchOne(); + } + + private Record findSourceRowAssociation(String namespace, long sourceGameRowId) { + return dsl.selectFrom(TENANT_ASSOCIATION) + .where(TARGET_NAMESPACE.eq(namespace).and(SOURCE_GAME_ROW_ID.eq(sourceGameRowId))) + .fetchOne(); + } + + private WorldAuthoredSourceIntakeReceipt toReceipt(Record record) { + try { + Short schemaVersion = Objects.requireNonNull(record.get(STORED_SCHEMA_VERSION, Short.class)); + Short sourceSchemaVersion = + Objects.requireNonNull(record.get(SOURCE_SCHEMA_VERSION, Short.class)); + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + sourceSchemaVersion.intValue(), + Objects.requireNonNull(record.get(TARGET_NAMESPACE, String.class)), + Objects.requireNonNull(record.get(SOURCE_REGISTRATION_REQUEST_ID, UUID.class)), + Objects.requireNonNull(record.get(SOURCE_OPERATION_ID, UUID.class)), + Objects.requireNonNull(record.get(SOURCE_REQUEST_DIGEST, String.class)), + Objects.requireNonNull(record.get(CANONICAL_TENANT_ID, UUID.class)), + Objects.requireNonNull(record.get(TENANT_SLUG, String.class)), + Objects.requireNonNull(record.get(WORLD_SLUG, String.class)), + Objects.requireNonNull(record.get(WORLD_DISPLAY_NAME, String.class)), + Objects.requireNonNull(record.get(SOURCE_GAME_ROW_ID, Long.class)), + Objects.requireNonNull(record.get(SOURCE_GAME_TENANT_KEY, String.class)), + Objects.requireNonNull(record.get(SOURCE_PROVENANCE_KIND, String.class)), + Objects.requireNonNull(record.get(SOURCE_EVIDENCE_DIGEST, String.class))); + if (schemaVersion.intValue() != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported local intake schema version"); + } + return new WorldAuthoredSourceIntakeReceipt( + schemaVersion.intValue(), + Objects.requireNonNull(record.get(TARGET_NAMESPACE, String.class)), + Objects.requireNonNull(record.get(INTAKE_REQUEST_ID, UUID.class)), + Objects.requireNonNull(record.get(OPERATION_ID, UUID.class)), + Objects.requireNonNull(record.get(CANONICAL_TENANT_ID, UUID.class)), + Objects.requireNonNull(record.get(WORLD_SLUG, String.class)), + source.operationId(), + source.evidenceDigest(), + Objects.requireNonNull(record.get(REQUEST_DIGEST, String.class)), + Objects.requireNonNull(record.get(RECEIPT_DIGEST, String.class)), + Objects.requireNonNull(record.get(LOCAL_TENANT_KEY, Long.class)), + source); + } catch (RuntimeException exception) { + if (exception instanceof InvalidIntakeEvidenceException) { + throw exception; + } + throw new InvalidIntakeEvidenceException( + "Persisted World authored-source intake evidence is invalid", exception); + } + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + } + + public static final class RegistrationConflictException extends IllegalStateException { + public RegistrationConflictException(String message) { + super(message); + } + } + + public static final class InvalidIntakeEvidenceException extends IllegalStateException { + public InvalidIntakeEvidenceException(String message) { + super(message); + } + + public InvalidIntakeEvidenceException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeService.java new file mode 100644 index 0000000000..fae4a474c8 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeService.java @@ -0,0 +1,262 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceClient; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceGrpcCodec.ReadRequest; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unwired World owner intake. A fresh, authenticated Game Design source read precedes the local + * transaction that retains its complete evidence and private tenant association. + */ +public class WorldAuthoredSourceIntakeService { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final AuthoredWorldSourceClient sourceClient; + private final WorldAuthoredSourceIntakeRepository repository; + private final TransactionTemplate ownerTransaction; + private final String workloadNamespace; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Trusted owner configuration is validated before use; no resources or finalizer are " + + "acquired.") + public WorldAuthoredSourceIntakeService( + AuthoredWorldSourceClient sourceClient, + WorldAuthoredSourceIntakeRepository repository, + PlatformTransactionManager transactionManager, + String workloadNamespace) { + this.sourceClient = Objects.requireNonNull(sourceClient, "sourceClient"); + this.repository = Objects.requireNonNull(repository, "repository"); + Objects.requireNonNull(transactionManager, "transactionManager"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("World workload namespace is invalid"); + } + this.workloadNamespace = workloadNamespace; + this.ownerTransaction = new TransactionTemplate(transactionManager); + this.ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + this.ownerTransaction.setReadOnly(false); + } + + /** + * Retains one fresh source binding. The intake request identity is stable across exact retries; + * each first attempt gets a separate Game Design read identity. + */ + public WorldAuthoredSourceIntakeReceipt intake( + UUID intakeRequestId, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String expectedSourceEvidenceDigest) { + requireAuthenticatedGameDesignCaller(); + requireNoAmbientTransaction(); + validateRequest( + intakeRequestId, + canonicalTenantId, + worldSlug, + sourceOperationId, + expectedSourceEvidenceDigest); + + Optional prior = + repository.read(workloadNamespace, intakeRequestId); + if (prior.isPresent()) { + return requireReceiptForRequest( + prior.get(), + intakeRequestId, + canonicalTenantId, + worldSlug, + sourceOperationId, + expectedSourceEvidenceDigest); + } + + AuthoredWorldSourceEvidence source = + sourceClient.read( + new ReadRequest( + workloadNamespace, + newReadRequestId(intakeRequestId), + sourceOperationId, + canonicalTenantId, + worldSlug)); + requireFreshSourceForRequest( + source, canonicalTenantId, worldSlug, sourceOperationId, expectedSourceEvidenceDigest); + + WorldAuthoredSourceIntakeReceipt accepted = + ownerTransaction.execute( + status -> repository.acceptFresh(workloadNamespace, intakeRequestId, source)); + if (accepted == null) { + throw new WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException( + "World owner transaction returned no authored-source receipt"); + } + requireReceiptForRequest( + accepted, + intakeRequestId, + canonicalTenantId, + worldSlug, + sourceOperationId, + expectedSourceEvidenceDigest, + source); + + Optional committed = + repository.read(workloadNamespace, intakeRequestId); + if (committed.isEmpty()) { + throw new WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException( + "World authored-source intake is missing after commit readback"); + } + WorldAuthoredSourceIntakeReceipt readback = committed.get(); + requireReceiptForRequest( + readback, + intakeRequestId, + canonicalTenantId, + worldSlug, + sourceOperationId, + expectedSourceEvidenceDigest, + source); + if (!accepted.equals(readback)) { + throw new WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException( + "World authored-source intake changed during commit readback"); + } + return readback; + } + + private void requireAuthenticatedGameDesignCaller() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null + || !peer.isService("game-design-service") + || !peer.isInNamespace(workloadNamespace)) { + throw new SecurityException( + "World authored-source intake requires the authenticated Game Design workload"); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "World authored-source intake cannot enter from an ambient transaction"); + } + } + + private void validateRequest( + UUID intakeRequestId, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String expectedSourceEvidenceDigest) { + requireNonNil(intakeRequestId, "intakeRequestId"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(sourceOperationId, "sourceOperationId"); + AuthoredWorldSourceDigest.validateReadSelector(workloadNamespace, canonicalTenantId, worldSlug); + if (!GameTenantCreationDigest.isDigest(expectedSourceEvidenceDigest)) { + throw new IllegalArgumentException( + "expectedSourceEvidenceDigest must be a canonical SHA-256 digest"); + } + } + + private void requireFreshSourceForRequest( + AuthoredWorldSourceEvidence source, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String expectedSourceEvidenceDigest) { + if (source == null + || !workloadNamespace.equals(source.targetNamespace()) + || !canonicalTenantId.equals(source.canonicalTenantId()) + || !worldSlug.equals(source.worldSlug()) + || !sourceOperationId.equals(source.operationId()) + || !expectedSourceEvidenceDigest.equals(source.evidenceDigest())) { + throw new WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException( + "Authenticated Game Design source does not match the requested World intake"); + } + try { + WorldAuthoredSourceIntakeDigest.requireFreshSource(workloadNamespace, source); + } catch (IllegalArgumentException exception) { + throw new WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException( + "Authenticated Game Design source is invalid or not fresh", exception); + } + } + + private WorldAuthoredSourceIntakeReceipt requireReceiptForRequest( + WorldAuthoredSourceIntakeReceipt receipt, + UUID intakeRequestId, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String expectedSourceEvidenceDigest) { + return requireReceiptForRequest( + receipt, + intakeRequestId, + canonicalTenantId, + worldSlug, + sourceOperationId, + expectedSourceEvidenceDigest, + null); + } + + private WorldAuthoredSourceIntakeReceipt requireReceiptForRequest( + WorldAuthoredSourceIntakeReceipt receipt, + UUID intakeRequestId, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String expectedSourceEvidenceDigest, + AuthoredWorldSourceEvidence expectedSource) { + if (receipt == null + || !workloadNamespace.equals(receipt.targetNamespace()) + || !intakeRequestId.equals(receipt.intakeRequestId()) + || !canonicalTenantId.equals(receipt.canonicalTenantId()) + || !worldSlug.equals(receipt.worldSlug()) + || !sourceOperationId.equals(receipt.sourceOperationId()) + || !expectedSourceEvidenceDigest.equals(receipt.sourceEvidenceDigest())) { + throw new WorldAuthoredSourceIntakeRepository.RegistrationConflictException( + "World intake request identity was reused with changed scope or source evidence"); + } + + AuthoredWorldSourceEvidence source = receipt.source(); + if (expectedSource != null && !expectedSource.equals(source)) { + throw new WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException( + "World authored-source receipt does not retain the complete source evidence"); + } + requireFreshSourceForRequest( + source, canonicalTenantId, worldSlug, sourceOperationId, expectedSourceEvidenceDigest); + String requestDigest = + WorldAuthoredSourceIntakeDigest.requestDigest(workloadNamespace, intakeRequestId, source); + String receiptDigest = + WorldAuthoredSourceIntakeDigest.receiptDigest( + workloadNamespace, + receipt.operationId(), + requestDigest, + source, + receipt.localTenantKey()); + if (!requestDigest.equals(receipt.requestDigest()) + || !receiptDigest.equals(receipt.receiptDigest())) { + throw new WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException( + "World authored-source receipt digest readback is invalid"); + } + return receipt; + } + + private static UUID newReadRequestId(UUID intakeRequestId) { + UUID readRequestId; + do { + readRequestId = UUID.randomUUID(); + } while (NIL_UUID.equals(readRequestId) || intakeRequestId.equals(readRequestId)); + return readRequestId; + } + + private static void requireNonNil(UUID value, String name) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + } +} diff --git a/services/world-management-service/src/main/resources/db/migration/V23__world_authored_source_intake.sql b/services/world-management-service/src/main/resources/db/migration/V23__world_authored_source_intake.sql new file mode 100644 index 0000000000..8e586e23ea --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V23__world_authored_source_intake.sql @@ -0,0 +1,250 @@ +CREATE TABLE world_authored_source_tenant_association ( + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + tenant_slug VARCHAR(120) NOT NULL, + source_game_row_id BIGINT NOT NULL, + source_game_tenant_key VARCHAR(72) NOT NULL, + source_provenance_kind VARCHAR(32) NOT NULL, + local_tenant_key BIGINT NOT NULL, + CONSTRAINT pk_world_authored_source_tenant_association + PRIMARY KEY (target_namespace, canonical_tenant_id), + CONSTRAINT uq_world_authored_source_tenant_local_key UNIQUE (local_tenant_key), + CONSTRAINT uq_world_authored_source_tenant_selector UNIQUE (target_namespace, tenant_slug), + CONSTRAINT uq_world_authored_source_game_row UNIQUE (target_namespace, source_game_row_id), + CONSTRAINT uq_world_authored_source_tenant_binding + UNIQUE (target_namespace, canonical_tenant_id, local_tenant_key), + CONSTRAINT ck_world_authored_source_tenant_canonical_id + CHECK (canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT ck_world_authored_source_tenant_game_row CHECK (source_game_row_id > 0), + CONSTRAINT ck_world_authored_source_tenant_local_key CHECK (local_tenant_key > 0), + CONSTRAINT ck_world_authored_source_tenant_provenance + CHECK (source_provenance_kind = 'NEW_GAME_ROW') +); + +CREATE TABLE world_authored_source_tenant_key_reservation ( + tenant_key BIGINT NOT NULL, + claim_kind VARCHAR(32) NOT NULL, + target_namespace VARCHAR(63), + canonical_tenant_id UUID, + CONSTRAINT pk_world_authored_source_tenant_key_reservation PRIMARY KEY (tenant_key), + CONSTRAINT fk_world_authored_source_tenant_key_canonical_binding + FOREIGN KEY (target_namespace, canonical_tenant_id, tenant_key) + REFERENCES world_authored_source_tenant_association + (target_namespace, canonical_tenant_id, local_tenant_key), + CONSTRAINT ck_world_authored_source_tenant_key_claim_kind CHECK ( + (claim_kind = 'LEGACY_NUMERIC' + AND target_namespace IS NULL + AND canonical_tenant_id IS NULL) + OR + (claim_kind = 'CANONICAL_AUTHORED_SOURCE' + AND target_namespace IS NOT NULL + AND canonical_tenant_id IS NOT NULL + AND tenant_key > 0) + ) +); + +INSERT INTO world_authored_source_tenant_key_reservation (tenant_key, claim_kind) +SELECT DISTINCT tenant_id, 'LEGACY_NUMERIC' +FROM ( + SELECT tenant_id FROM generation_rule + UNION ALL SELECT tenant_id FROM instance + UNION ALL SELECT tenant_id FROM region + UNION ALL SELECT tenant_id FROM region_instance + UNION ALL SELECT tenant_id FROM room + UNION ALL SELECT tenant_id FROM room_exit + UNION ALL SELECT tenant_id FROM room_instance + UNION ALL SELECT tenant_id FROM room_instance_exit + UNION ALL SELECT tenant_id FROM world_design_aggregate_epoch + UNION ALL SELECT tenant_id FROM world_design_revision_ledger + UNION ALL SELECT tenant_id FROM world_design_scope_epoch + UNION ALL SELECT tenant_id FROM world_entity_spawn_binding + UNION ALL SELECT tenant_id FROM world_event + UNION ALL SELECT tenant_id FROM world_instance + UNION ALL SELECT tenant_id FROM zone + UNION ALL SELECT tenant_id FROM zone_instance +) AS existing_world_tenant_keys; + +-- [jooq ignore start] +CREATE FUNCTION world_claim_legacy_numeric_tenant_key() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + claimed_key BIGINT; +BEGIN + INSERT INTO world_authored_source_tenant_key_reservation AS reservation + (tenant_key, claim_kind) + VALUES (NEW.tenant_id, 'LEGACY_NUMERIC') + ON CONFLICT (tenant_key) DO UPDATE + SET tenant_key = EXCLUDED.tenant_key + WHERE reservation.claim_kind = 'LEGACY_NUMERIC' + RETURNING reservation.tenant_key INTO claimed_key; + + IF claimed_key IS NULL THEN + RAISE EXCEPTION 'World tenant key % is reserved for a canonical authored source', NEW.tenant_id + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION world_reject_authored_source_history_mutation() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'World authored-source association and receipt history is immutable' + USING ERRCODE = '55000'; +END; +$$; + +CREATE FUNCTION world_protect_tenant_key_reservation_history() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF TG_OP = 'UPDATE' THEN + IF OLD.tenant_key IS NOT DISTINCT FROM NEW.tenant_key + AND OLD.claim_kind IS NOT DISTINCT FROM NEW.claim_kind + AND OLD.target_namespace IS NOT DISTINCT FROM NEW.target_namespace + AND OLD.canonical_tenant_id IS NOT DISTINCT FROM NEW.canonical_tenant_id + THEN + RETURN NEW; + END IF; + END IF; + RAISE EXCEPTION 'World tenant-key reservation history cannot be changed or deleted' + USING ERRCODE = '55000'; +END; +$$; + +CREATE TRIGGER trg_world_tenant_key_reservation_immutable + BEFORE UPDATE OR DELETE ON world_authored_source_tenant_key_reservation + FOR EACH ROW EXECUTE FUNCTION world_protect_tenant_key_reservation_history(); + +CREATE TRIGGER trg_world_tenant_key_reservation_no_truncate + BEFORE TRUNCATE ON world_authored_source_tenant_key_reservation + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_authored_source_history_mutation(); + +CREATE TRIGGER trg_world_authored_source_association_immutable + BEFORE UPDATE OR DELETE ON world_authored_source_tenant_association + FOR EACH ROW EXECUTE FUNCTION world_reject_authored_source_history_mutation(); + +CREATE TRIGGER trg_world_authored_source_association_no_truncate + BEFORE TRUNCATE ON world_authored_source_tenant_association + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_authored_source_history_mutation(); + +CREATE TRIGGER trg_reserve_generation_rule_tenant_key + BEFORE INSERT OR UPDATE OF tenant_id ON generation_rule + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); +CREATE TRIGGER trg_reserve_instance_tenant_key + BEFORE INSERT OR UPDATE OF tenant_id ON instance + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); +CREATE TRIGGER trg_reserve_region_tenant_key + BEFORE INSERT OR UPDATE OF tenant_id ON region + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); +CREATE TRIGGER trg_reserve_region_instance_tenant_key + BEFORE INSERT OR UPDATE OF tenant_id ON region_instance + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); +CREATE TRIGGER trg_reserve_room_tenant_key + BEFORE INSERT OR UPDATE OF tenant_id ON room + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); +CREATE TRIGGER trg_reserve_room_exit_tenant_key + BEFORE INSERT OR UPDATE OF tenant_id ON room_exit + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); +CREATE TRIGGER trg_reserve_room_instance_tenant_key + BEFORE INSERT OR UPDATE OF tenant_id ON room_instance + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); +CREATE TRIGGER trg_reserve_room_instance_exit_tenant_key + BEFORE INSERT OR UPDATE OF tenant_id ON room_instance_exit + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); +CREATE TRIGGER trg_reserve_world_design_aggregate_epoch_tenant_key + BEFORE INSERT OR UPDATE OF tenant_id ON world_design_aggregate_epoch + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); +CREATE TRIGGER trg_reserve_world_design_revision_ledger_tenant_key + BEFORE INSERT OR UPDATE OF tenant_id ON world_design_revision_ledger + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); +CREATE TRIGGER trg_reserve_world_design_scope_epoch_tenant_key + BEFORE INSERT OR UPDATE OF tenant_id ON world_design_scope_epoch + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); +CREATE TRIGGER trg_reserve_world_entity_spawn_binding_tenant_key + BEFORE INSERT OR UPDATE OF tenant_id ON world_entity_spawn_binding + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); +CREATE TRIGGER trg_reserve_world_event_tenant_key + BEFORE INSERT OR UPDATE OF tenant_id ON world_event + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); +CREATE TRIGGER trg_reserve_world_instance_tenant_key + BEFORE INSERT OR UPDATE OF tenant_id ON world_instance + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); +CREATE TRIGGER trg_reserve_zone_tenant_key + BEFORE INSERT OR UPDATE OF tenant_id ON zone + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); +CREATE TRIGGER trg_reserve_zone_instance_tenant_key + BEFORE INSERT OR UPDATE OF tenant_id ON zone_instance + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); +-- [jooq ignore stop] + +CREATE TABLE world_authored_source_intake ( + operation_id UUID NOT NULL, + schema_version SMALLINT NOT NULL, + target_namespace VARCHAR(63) NOT NULL, + intake_request_id UUID NOT NULL, + request_digest VARCHAR(71) NOT NULL, + local_tenant_key BIGINT NOT NULL, + source_schema_version SMALLINT NOT NULL, + source_registration_request_id UUID NOT NULL, + source_operation_id UUID NOT NULL, + source_request_digest VARCHAR(71) NOT NULL, + canonical_tenant_id UUID NOT NULL, + tenant_slug VARCHAR(120) NOT NULL, + world_slug VARCHAR(120) NOT NULL, + world_display_name VARCHAR(200) NOT NULL, + source_game_row_id BIGINT NOT NULL, + source_game_tenant_key VARCHAR(72) NOT NULL, + source_provenance_kind VARCHAR(32) NOT NULL, + source_evidence_digest VARCHAR(71) NOT NULL, + receipt_digest VARCHAR(71) NOT NULL, + CONSTRAINT pk_world_authored_source_intake PRIMARY KEY (operation_id), + CONSTRAINT uq_world_authored_source_intake_request + UNIQUE (target_namespace, intake_request_id), + CONSTRAINT uq_world_authored_source_intake_source_operation + UNIQUE (target_namespace, source_operation_id), + CONSTRAINT uq_world_authored_source_intake_source_request + UNIQUE (target_namespace, source_registration_request_id), + CONSTRAINT uq_world_authored_source_intake_world + UNIQUE (target_namespace, canonical_tenant_id, world_slug), + CONSTRAINT fk_world_authored_source_intake_tenant_binding + FOREIGN KEY (target_namespace, canonical_tenant_id, local_tenant_key) + REFERENCES world_authored_source_tenant_association + (target_namespace, canonical_tenant_id, local_tenant_key), + CONSTRAINT ck_world_authored_source_intake_schema CHECK (schema_version = 1), + CONSTRAINT ck_world_authored_source_intake_source_schema CHECK (source_schema_version = 1), + CONSTRAINT ck_world_authored_source_intake_local_key CHECK (local_tenant_key > 0), + CONSTRAINT ck_world_authored_source_intake_source_game_row CHECK (source_game_row_id > 0), + CONSTRAINT ck_world_authored_source_intake_provenance + CHECK (source_provenance_kind = 'NEW_GAME_ROW'), + CONSTRAINT ck_world_authored_source_intake_request_digest + CHECK (request_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT ck_world_authored_source_intake_source_request_digest + CHECK (source_request_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT ck_world_authored_source_intake_source_evidence_digest + CHECK (source_evidence_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT ck_world_authored_source_intake_receipt_digest + CHECK (receipt_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT ck_world_authored_source_intake_non_nil_ids CHECK ( + operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND intake_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND source_registration_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND source_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + ) +); + +-- [jooq ignore start] +CREATE TRIGGER trg_world_authored_source_intake_immutable + BEFORE UPDATE OR DELETE ON world_authored_source_intake + FOR EACH ROW EXECUTE FUNCTION world_reject_authored_source_history_mutation(); + +CREATE TRIGGER trg_world_authored_source_intake_no_truncate + BEFORE TRUNCATE ON world_authored_source_intake + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_authored_source_history_mutation(); +-- [jooq ignore stop] diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java new file mode 100644 index 0000000000..25c3136364 --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java @@ -0,0 +1,733 @@ +package net.firedevops.firemud.worldmanagement; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.worldmanagement.client.EntityManagementClient; +import net.firedevops.firemud.worldmanagement.client.GameDesignClient; +import net.firedevops.firemud.worldmanagement.client.GameSessionClient; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeReceipt; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeRepository; +import org.jooq.DSLContext; +import org.jooq.exception.DataAccessException; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.transaction.IllegalTransactionStateException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + classes = WorldManagementServiceApplication.class, + properties = "spring.grpc.server.port=0") +class WorldAuthoredSourceIntakeIntegrationTest { + private static final String NAMESPACE = "firemud"; + private static final String OCCUPIED_LEGACY_KEYS = + "SELECT COUNT(*) FROM (" + + "SELECT tenant_id AS occupied_key FROM generation_rule UNION ALL " + + "SELECT tenant_id FROM instance UNION ALL " + + "SELECT tenant_id FROM region UNION ALL " + + "SELECT tenant_id FROM region_instance UNION ALL " + + "SELECT tenant_id FROM room UNION ALL " + + "SELECT tenant_id FROM room_exit UNION ALL " + + "SELECT tenant_id FROM room_instance UNION ALL " + + "SELECT tenant_id FROM room_instance_exit UNION ALL " + + "SELECT tenant_id FROM world_design_aggregate_epoch UNION ALL " + + "SELECT tenant_id FROM world_design_revision_ledger UNION ALL " + + "SELECT tenant_id FROM world_design_scope_epoch UNION ALL " + + "SELECT tenant_id FROM world_entity_spawn_binding UNION ALL " + + "SELECT tenant_id FROM world_event UNION ALL " + + "SELECT tenant_id FROM world_instance UNION ALL " + + "SELECT tenant_id FROM zone UNION ALL " + + "SELECT tenant_id FROM zone_instance" + + ") AS occupied_world_keys WHERE occupied_key = ?"; + private static final String MAX_OCCUPIED_TENANT_KEY = + "SELECT COALESCE(MAX(occupied_key), 0) FROM (" + + "SELECT tenant_id AS occupied_key FROM generation_rule UNION ALL " + + "SELECT tenant_id FROM instance UNION ALL " + + "SELECT tenant_id FROM region UNION ALL " + + "SELECT tenant_id FROM region_instance UNION ALL " + + "SELECT tenant_id FROM room UNION ALL " + + "SELECT tenant_id FROM room_exit UNION ALL " + + "SELECT tenant_id FROM room_instance UNION ALL " + + "SELECT tenant_id FROM room_instance_exit UNION ALL " + + "SELECT tenant_id FROM world_design_aggregate_epoch UNION ALL " + + "SELECT tenant_id FROM world_design_revision_ledger UNION ALL " + + "SELECT tenant_id FROM world_design_scope_epoch UNION ALL " + + "SELECT tenant_id FROM world_entity_spawn_binding UNION ALL " + + "SELECT tenant_id FROM world_event UNION ALL " + + "SELECT tenant_id FROM world_instance UNION ALL " + + "SELECT tenant_id FROM zone UNION ALL " + + "SELECT tenant_id FROM zone_instance UNION ALL " + + "SELECT tenant_key FROM world_authored_source_tenant_key_reservation UNION ALL " + + "SELECT local_tenant_key FROM world_authored_source_tenant_association" + + ") AS occupied_tenant_keys"; + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Container + static GenericContainer redis = + new GenericContainer<>("redis:7.2-alpine").withExposedPorts(6379); + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.registerPostgresService( + registry, postgres, "world_management_service"); + PostgresBackedServiceTestSupport.registerRedisService(registry, redis); + } + + @Autowired private WorldAuthoredSourceIntakeRepository repository; + @Autowired private DSLContext dsl; + @Autowired private PlatformTransactionManager transactionManager; + + @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + @MockitoBean private GameDesignClient gameDesignClient; + @MockitoBean private GameSessionClient gameSessionClient; + @MockitoBean private EntityManagementClient entityManagementClient; + + @Test + void persistsCompleteFreshReceiptAndReusesExactTenantAssociationAcrossWorlds() { + long existingLegacyTenantKey = + 8_000_000_000L + ThreadLocalRandom.current().nextLong(1_000_000L); + Long legacyRegionId = + Objects.requireNonNull( + dsl.fetchOne( + "INSERT INTO region (tenant_id, name) VALUES (?, ?) RETURNING id", + existingLegacyTenantKey, + "retained-world-allocation-guard"), + "retained region insert did not return its row") + .get(0, Long.class); + dsl.execute( + "INSERT INTO region (tenant_id, name) VALUES (?, ?)", + existingLegacyTenantKey, + "same-legacy-selector-remains-valid"); + dsl.execute( + "UPDATE region SET tenant_id = ? WHERE id = ?", existingLegacyTenantKey, legacyRegionId); + + UUID canonicalTenantId = UUID.randomUUID(); + String tenantSlug = tenantSlug(canonicalTenantId); + long sourceRowId = sourceRowId(canonicalTenantId); + AuthoredWorldSourceEvidence firstSource = + source(canonicalTenantId, tenantSlug, "violet-wilds", sourceRowId, "Café 🐉"); + UUID firstRequestId = UUID.randomUUID(); + WorldAuthoredSourceIntakeReceipt first = accept(firstRequestId, firstSource); + + assertThat(first.source()).isEqualTo(firstSource); + assertThat(first.localTenantKey()).isGreaterThan(existingLegacyTenantKey); + assertThat( + Objects.requireNonNull( + dsl.fetchOne(OCCUPIED_LEGACY_KEYS, first.localTenantKey()), + "legacy key occupancy query returned no row") + .get(0, Long.class)) + .isZero(); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT COUNT(*) FROM world_authored_source_tenant_key_reservation " + + "WHERE tenant_key = ? AND claim_kind = 'CANONICAL_AUTHORED_SOURCE' " + + "AND target_namespace = ? AND canonical_tenant_id = ?", + first.localTenantKey(), + NAMESPACE, + canonicalTenantId), + "canonical tenant-key reservation count query returned no row") + .get(0, Long.class)) + .isEqualTo(1L); + assertThat(read(firstRequestId)).contains(first); + + assertThatThrownBy( + () -> + dsl.execute( + "INSERT INTO region (tenant_id, name) VALUES (?, ?)", + first.localTenantKey(), + "cannot-claim-canonical-selector")) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE region SET tenant_id = ? WHERE id = ?", + first.localTenantKey(), + legacyRegionId)) + .isInstanceOf(DataAccessException.class); + assertThat( + Objects.requireNonNull( + dsl.fetchOne("SELECT tenant_id FROM region WHERE id = ?", legacyRegionId), + "retained region tenant readback returned no row") + .get(0, Long.class)) + .isEqualTo(existingLegacyTenantKey); + + AuthoredWorldSourceEvidence secondSource = + source(canonicalTenantId, tenantSlug, "amber-coast", sourceRowId, "Amber Coast"); + WorldAuthoredSourceIntakeReceipt second = accept(UUID.randomUUID(), secondSource); + + assertThat(second.localTenantKey()).isEqualTo(first.localTenantKey()); + assertThat(second.source().tenantSlug()).isEqualTo(first.source().tenantSlug()); + assertThat(second.source().sourceGameRowId()).isEqualTo(first.source().sourceGameRowId()); + assertThat(second.source().sourceGameTenantKey()) + .isEqualTo(first.source().sourceGameTenantKey()); + assertThat(second.source().provenanceKind()).isEqualTo("NEW_GAME_ROW"); + } + + @Test + void deniesRetainedEvidenceAndChangedRequestOrTenantScopeBeforeAddingClaims() { + UUID tenant = UUID.randomUUID(); + String tenantSlug = tenantSlug(tenant); + long sourceRowId = sourceRowId(tenant); + AuthoredWorldSourceEvidence firstSource = + source(tenant, tenantSlug, "violet-wilds", sourceRowId, "Violet Wilds"); + UUID requestId = UUID.randomUUID(); + WorldAuthoredSourceIntakeReceipt first = accept(requestId, firstSource); + + AuthoredWorldSourceEvidence changedRequestSource = + source(tenant, tenantSlug, "amber-coast", sourceRowId, "Amber Coast"); + assertThatThrownBy(() -> accept(requestId, changedRequestSource)) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.RegistrationConflictException.class); + assertThatThrownBy( + () -> + accept( + requestId, + source( + UUID.randomUUID(), + "unrelated-tenant-selector", + "violet-wilds", + 7_456_321_987L, + "Violet Wilds"))) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.RegistrationConflictException.class); + + AuthoredWorldSourceEvidence changedWorldSource = + source(tenant, tenantSlug, "violet-wilds", sourceRowId, "Changed Display"); + assertThatThrownBy(() -> accept(UUID.randomUUID(), changedWorldSource)) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.RegistrationConflictException.class); + assertThatThrownBy(() -> accept(UUID.randomUUID(), firstSource)) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.RegistrationConflictException.class); + + AuthoredWorldSourceEvidence changedTenantSource = + source( + tenant, + "renamed-" + tenant.toString().replace("-", ""), + "new-world", + sourceRowId, + "New World"); + assertThatThrownBy(() -> accept(UUID.randomUUID(), changedTenantSource)) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.RegistrationConflictException.class); + + UUID retainedTenantId = UUID.randomUUID(); + AuthoredWorldSourceEvidence retainedSource = + source( + retainedTenantId, + tenantSlug(retainedTenantId), + "retained-world", + sourceRowId(retainedTenantId), + "Retained", + "RETAINED_GAME_V30"); + assertThatThrownBy(() -> accept(UUID.randomUUID(), retainedSource)) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException.class); + assertThat(read(requestId)).contains(first); + assertThat(countForCanonicalTenant(tenant)).isEqualTo(1L); + } + + @Test + void ownerTransactionRollbackLeavesNeitherAssociationNorReceipt() { + UUID tenant = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + AuthoredWorldSourceEvidence source = + source( + tenant, + tenantSlug(tenant), + "rolled-back-world", + sourceRowId(tenant), + "Rolled Back World"); + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + + assertThatThrownBy( + () -> + transactionTemplate.execute( + status -> { + repository.acceptFresh(NAMESPACE, requestId, source); + throw new ForcedOwnerRollbackException(); + })) + .isInstanceOf(ForcedOwnerRollbackException.class); + + assertThat(read(requestId)).isEmpty(); + assertThat(countForCanonicalTenant(tenant)).isZero(); + assertThat(countReservationsForCanonicalTenant(tenant)).isZero(); + } + + @Test + void rejectsImmutableHistoryMutationAndTruncation() { + UUID tenant = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + AuthoredWorldSourceEvidence source = + source( + tenant, tenantSlug(tenant), "immutable-world", sourceRowId(tenant), "Immutable World"); + WorldAuthoredSourceIntakeReceipt receipt = accept(requestId, source); + + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE world_authored_source_intake SET world_display_name = ? " + + "WHERE operation_id = ?", + "substituted", + receipt.operationId())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + dsl.execute( + "DELETE FROM world_authored_source_intake WHERE operation_id = ?", + receipt.operationId())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy(() -> dsl.execute("TRUNCATE world_authored_source_intake CASCADE")) + .isInstanceOf(DataAccessException.class); + + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE world_authored_source_tenant_association SET tenant_slug = ? " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + "changed-selector", + NAMESPACE, + tenant)) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + dsl.execute( + "DELETE FROM world_authored_source_tenant_association " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + NAMESPACE, + tenant)) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> dsl.execute("TRUNCATE world_authored_source_tenant_association CASCADE")) + .isInstanceOf(DataAccessException.class); + + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE world_authored_source_tenant_key_reservation " + + "SET claim_kind = 'LEGACY_NUMERIC' WHERE tenant_key = ?", + receipt.localTenantKey())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + dsl.execute( + "DELETE FROM world_authored_source_tenant_key_reservation " + + "WHERE tenant_key = ?", + receipt.localTenantKey())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> dsl.execute("TRUNCATE world_authored_source_tenant_key_reservation CASCADE")) + .isInstanceOf(DataAccessException.class); + + assertThat(read(requestId)).contains(receipt); + assertThat(countForCanonicalTenant(tenant)).isEqualTo(1L); + assertThat(countReservationsForCanonicalTenant(tenant)).isEqualTo(1L); + } + + @Test + void rejectsReadOnlyAndNonReadCommittedOwnerTransactionsWithoutClaims() { + UUID tenant = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + AuthoredWorldSourceEvidence source = + source( + tenant, + tenantSlug(tenant), + "unsupported-transaction-world", + sourceRowId(tenant), + "Unsupported Transaction World"); + + TransactionTemplate readOnly = new TransactionTemplate(transactionManager); + readOnly.setReadOnly(true); + assertThatThrownBy( + () -> readOnly.execute(status -> repository.acceptFresh(NAMESPACE, requestId, source))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable owner transaction"); + assertThat(countForCanonicalTenant(tenant)).isZero(); + assertThat(countReservationsForCanonicalTenant(tenant)).isZero(); + assertThat(read(requestId)).isEmpty(); + + TransactionTemplate repeatableRead = new TransactionTemplate(transactionManager); + repeatableRead.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + assertThatThrownBy( + () -> + repeatableRead.execute( + status -> repository.acceptFresh(NAMESPACE, requestId, source))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("READ COMMITTED"); + assertThat(countForCanonicalTenant(tenant)).isZero(); + assertThat(countReservationsForCanonicalTenant(tenant)).isZero(); + assertThat(read(requestId)).isEmpty(); + + assertThatThrownBy(() -> repository.acceptFresh(NAMESPACE, requestId, source)) + .isInstanceOf(IllegalTransactionStateException.class); + assertThat(countForCanonicalTenant(tenant)).isZero(); + assertThat(countReservationsForCanonicalTenant(tenant)).isZero(); + assertThat(read(requestId)).isEmpty(); + } + + @Test + void concurrentExactRetriesReturnTheSingleCommittedReceipt() throws Exception { + UUID tenant = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + AuthoredWorldSourceEvidence source = + source( + tenant, + tenantSlug(tenant), + "concurrent-world", + sourceRowId(tenant), + "Concurrent World"); + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + Future first = + executor.submit( + () -> acceptWhenReleased(transactionTemplate, ready, start, requestId, source)); + Future second = + executor.submit( + () -> acceptWhenReleased(transactionTemplate, ready, start, requestId, source)); + + assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + WorldAuthoredSourceIntakeReceipt firstReceipt = first.get(20, TimeUnit.SECONDS); + WorldAuthoredSourceIntakeReceipt secondReceipt = second.get(20, TimeUnit.SECONDS); + assertThat(firstReceipt).isEqualTo(secondReceipt); + assertThat(read(requestId)).contains(firstReceipt); + } + } + + @Test + void concurrentLegacyNumericClaimSerializesBeforeFreshSelectorAllocation() throws Exception { + long legacyTenantKey = 6_000_000_000L + ThreadLocalRandom.current().nextLong(1_000_000L); + UUID tenant = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + AuthoredWorldSourceEvidence source = + source( + tenant, + tenantSlug(tenant), + "concurrent-numeric-allocation-world", + sourceRowId(tenant), + "Concurrent Numeric Allocation World"); + TransactionTemplate legacyTransaction = new TransactionTemplate(transactionManager); + TransactionTemplate intakeTransaction = new TransactionTemplate(transactionManager); + CountDownLatch legacyInserted = new CountDownLatch(1); + CountDownLatch allowLegacyCommit = new CountDownLatch(1); + CountDownLatch intakeStarted = new CountDownLatch(1); + + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + Future legacyWrite = + executor.submit( + () -> + legacyTransaction.execute( + status -> { + dsl.execute( + "INSERT INTO region (tenant_id, name) VALUES (?, ?)", + legacyTenantKey, + "concurrent-legacy-selector"); + legacyInserted.countDown(); + await(allowLegacyCommit, 20); + return null; + })); + assertThat(legacyInserted.await(5, TimeUnit.SECONDS)).isTrue(); + + Future intake = + executor.submit( + () -> { + intakeStarted.countDown(); + return intakeTransaction.execute( + status -> repository.acceptFresh(NAMESPACE, requestId, source)); + }); + assertThat(intakeStarted.await(5, TimeUnit.SECONDS)).isTrue(); + awaitAllocatorLockWait(); + allowLegacyCommit.countDown(); + + legacyWrite.get(20, TimeUnit.SECONDS); + WorldAuthoredSourceIntakeReceipt receipt = intake.get(20, TimeUnit.SECONDS); + assertThat(receipt.localTenantKey()).isGreaterThan(legacyTenantKey); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT COUNT(*) FROM region WHERE tenant_id = ?", legacyTenantKey), + "legacy region count query returned no row") + .get(0, Long.class)) + .isEqualTo(1L); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT COUNT(*) FROM world_authored_source_tenant_key_reservation " + + "WHERE tenant_key = ? AND claim_kind = 'LEGACY_NUMERIC'", + legacyTenantKey), + "legacy tenant-key reservation count query returned no row") + .get(0, Long.class)) + .isEqualTo(1L); + assertThat(countForCanonicalTenant(tenant)).isEqualTo(1L); + assertThat(read(requestId)).contains(receipt); + } + } + + @Test + void concurrentLegacyClaimAfterAllocationCannotTakeTheReservedSelector() throws Exception { + UUID tenant = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + AuthoredWorldSourceEvidence source = + source( + tenant, + tenantSlug(tenant), + "concurrent-reserved-selector-world", + sourceRowId(tenant), + "Concurrent Reserved Selector World"); + TransactionTemplate ownerTransaction = new TransactionTemplate(transactionManager); + TransactionTemplate legacyTransaction = new TransactionTemplate(transactionManager); + CountDownLatch intakePrepared = new CountDownLatch(1); + CountDownLatch allowIntakeCommit = new CountDownLatch(1); + AtomicReference preparedReceipt = new AtomicReference<>(); + + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + Future intake = + executor.submit( + () -> + ownerTransaction.execute( + status -> { + WorldAuthoredSourceIntakeReceipt receipt = + repository.acceptFresh(NAMESPACE, requestId, source); + preparedReceipt.set(receipt); + intakePrepared.countDown(); + await(allowIntakeCommit, 20); + return receipt; + })); + assertThat(intakePrepared.await(5, TimeUnit.SECONDS)).isTrue(); + WorldAuthoredSourceIntakeReceipt receipt = preparedReceipt.get(); + assertThat(receipt).isNotNull(); + + Future legacyWrite = + executor.submit( + () -> { + try { + legacyTransaction.execute( + status -> { + dsl.execute( + "INSERT INTO region (tenant_id, name) VALUES (?, ?)", + receipt.localTenantKey(), + "cannot-race-private-selector"); + return null; + }); + return true; + } catch (DataAccessException expectedReservedKeyRejection) { + return false; + } + }); + + awaitLegacyWriterLockWait(); + allowIntakeCommit.countDown(); + assertThat(intake.get(20, TimeUnit.SECONDS)).isEqualTo(receipt); + assertThat(legacyWrite.get(20, TimeUnit.SECONDS)).isFalse(); + assertThat(read(requestId)).contains(receipt); + assertThat(countForCanonicalTenant(tenant)).isEqualTo(1L); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT COUNT(*) FROM region WHERE tenant_id = ?", + receipt.localTenantKey()), + "canonical-selector region count query returned no row") + .get(0, Long.class)) + .isZero(); + } + } + + private WorldAuthoredSourceIntakeReceipt accept( + UUID requestId, AuthoredWorldSourceEvidence source) { + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + return transactionTemplate.execute( + status -> repository.acceptFresh(NAMESPACE, requestId, source)); + } + + private WorldAuthoredSourceIntakeReceipt acceptWhenReleased( + TransactionTemplate transactionTemplate, + CountDownLatch ready, + CountDownLatch start, + UUID requestId, + AuthoredWorldSourceEvidence source) { + ready.countDown(); + await(start); + return transactionTemplate.execute( + status -> repository.acceptFresh(NAMESPACE, requestId, source)); + } + + private java.util.Optional read(UUID requestId) { + return repository.read(NAMESPACE, requestId); + } + + private long countForCanonicalTenant(UUID tenantId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT COUNT(*) FROM world_authored_source_tenant_association WHERE " + + "target_namespace = ? AND canonical_tenant_id = ?", + NAMESPACE, + tenantId), + "canonical tenant association count query returned no row") + .get(0, Long.class); + } + + private long countReservationsForCanonicalTenant(UUID tenantId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT COUNT(*) FROM world_authored_source_tenant_key_reservation " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + NAMESPACE, + tenantId), + "canonical tenant-key reservation count query returned no row") + .get(0, Long.class); + } + + private void awaitAllocatorLockWait() { + long deadlineNanos = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (System.nanoTime() < deadlineNanos) { + Long waiting = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT COUNT(*) FROM pg_stat_activity WHERE datname = current_database() " + + "AND wait_event_type = 'Lock' " + + "AND lower(query) LIKE 'lock table generation_rule%'"), + "allocator lock-wait query returned no row") + .get(0, Long.class); + if (waiting != null && waiting > 0L) { + return; + } + try { + TimeUnit.MILLISECONDS.sleep(25); + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted while observing PostgreSQL lock wait", exception); + } + } + throw new IllegalStateException( + "Fresh intake did not wait for the retained tenant-table writer"); + } + + private void awaitLegacyWriterLockWait() { + long deadlineNanos = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (System.nanoTime() < deadlineNanos) { + Long waiting = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT COUNT(*) FROM pg_stat_activity WHERE datname = current_database() " + + "AND wait_event_type = 'Lock' " + + "AND lower(query) LIKE 'insert into region%'"), + "legacy writer lock-wait query returned no row") + .get(0, Long.class); + if (waiting != null && waiting > 0L) { + return; + } + try { + TimeUnit.MILLISECONDS.sleep(25); + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted while observing PostgreSQL legacy-writer lock wait", exception); + } + } + throw new IllegalStateException( + "Legacy numeric writer did not wait for the fresh intake owner transaction"); + } + + private static final class ForcedOwnerRollbackException extends RuntimeException { + private ForcedOwnerRollbackException() { + super("Force the test owner transaction to roll back"); + } + } + + private static AuthoredWorldSourceEvidence source( + UUID tenantId, String tenantSlug, String worldSlug, long sourceRowId, String displayName) { + return source(tenantId, tenantSlug, worldSlug, sourceRowId, displayName, "NEW_GAME_ROW"); + } + + private static String tenantSlug(UUID tenantId) { + return "tenant-" + tenantId.toString().replace("-", ""); + } + + private static long sourceRowId(UUID tenantId) { + long positive = tenantId.getLeastSignificantBits() & Long.MAX_VALUE; + return positive == 0L ? 1L : positive; + } + + private static AuthoredWorldSourceEvidence source( + UUID tenantId, + String tenantSlug, + String worldSlug, + long sourceRowId, + String displayName, + String provenance) { + UUID registrationId = UUID.randomUUID(); + UUID sourceOperationId = UUID.randomUUID(); + String sourceGameTenantKey = "gd-row-" + sourceRowId; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registrationId, tenantId, tenantSlug, worldSlug, displayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationId, + sourceOperationId, + requestDigest, + tenantId, + tenantSlug, + worldSlug, + displayName, + sourceRowId, + sourceGameTenantKey, + provenance); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationId, + sourceOperationId, + requestDigest, + tenantId, + tenantSlug, + worldSlug, + displayName, + sourceRowId, + sourceGameTenantKey, + provenance, + evidenceDigest); + } + + private static void await(CountDownLatch latch) { + await(latch, 5); + } + + private static void await(CountDownLatch latch, long timeoutSeconds) { + try { + if (!latch.await(timeoutSeconds, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting for concurrent intake test gate"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Concurrent intake test was interrupted", exception); + } + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeDigestTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeDigestTest.java new file mode 100644 index 0000000000..50033c01ae --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeDigestTest.java @@ -0,0 +1,131 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.UUID; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import org.junit.jupiter.api.Test; + +class WorldAuthoredSourceIntakeDigestTest { + private static final String NAMESPACE = "firemud"; + private static final UUID TENANT = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID REGISTRATION = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID SOURCE_OPERATION = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID INTAKE_REQUEST = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID WORLD_OPERATION = + UUID.fromString("55555555-5555-4555-8555-555555555555"); + + @Test + void emitsSharedUnicodeAndFramingVectorsForCompleteSourceAndPrivateAssociation() { + AuthoredWorldSourceEvidence source = source("violet-wilds", "Café 🐉", "NEW_GAME_ROW"); + + assertThat(source.requestDigest()) + .isEqualTo("sha256:2f2e50fd98aede5418d7b52b8c837e12b092edd4044624b4047d21123cb35ba3"); + assertThat(source.evidenceDigest()) + .isEqualTo("sha256:0084bd312cf3c13540d453c6a1e173b6b8ef5436a57a55db3363e2cd6879cbda"); + String requestDigest = + WorldAuthoredSourceIntakeDigest.requestDigest(NAMESPACE, INTAKE_REQUEST, source); + assertThat(requestDigest) + .isEqualTo("sha256:1946ce9cb46af17732c4ec06445d7d9e297ac9bc22e30e7dde2858f9e1626c1f"); + assertThat( + WorldAuthoredSourceIntakeDigest.receiptDigest( + NAMESPACE, WORLD_OPERATION, requestDigest, source, 9001L)) + .isEqualTo("sha256:7d0ab0104385d80e5a2bc1f72386ca09b50473d262a0389840a90136a4778fb7"); + } + + @Test + void requestAndReceiptDigestsBindEveryLocalScopeAndAllocationInput() { + AuthoredWorldSourceEvidence source = source("violet-wilds", "Café 🐉", "NEW_GAME_ROW"); + AuthoredWorldSourceEvidence changedWorld = source("amber-coast", "Café 🐉", "NEW_GAME_ROW"); + String request = + WorldAuthoredSourceIntakeDigest.requestDigest(NAMESPACE, INTAKE_REQUEST, source); + String receipt = + WorldAuthoredSourceIntakeDigest.receiptDigest( + NAMESPACE, WORLD_OPERATION, request, source, 9001L); + + assertThat(WorldAuthoredSourceIntakeDigest.requestDigest(NAMESPACE, WORLD_OPERATION, source)) + .isNotEqualTo(request); + assertThat( + WorldAuthoredSourceIntakeDigest.requestDigest(NAMESPACE, INTAKE_REQUEST, changedWorld)) + .isNotEqualTo(request); + assertThat( + WorldAuthoredSourceIntakeDigest.receiptDigest( + NAMESPACE, UUID.randomUUID(), request, source, 9001L)) + .isNotEqualTo(receipt); + assertThat( + WorldAuthoredSourceIntakeDigest.receiptDigest( + NAMESPACE, WORLD_OPERATION, request, source, 9002L)) + .isNotEqualTo(receipt); + } + + @Test + void rejectsNilMalformedMismatchedAndRetainedInputs() { + AuthoredWorldSourceEvidence fresh = source("violet-wilds", "A world", "NEW_GAME_ROW"); + AuthoredWorldSourceEvidence retained = source("violet-wilds", "A world", "RETAINED_GAME_V30"); + + assertThatThrownBy( + () -> WorldAuthoredSourceIntakeDigest.requestDigest(NAMESPACE, new UUID(0L, 0L), fresh)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + WorldAuthoredSourceIntakeDigest.requestDigest( + "other-namespace", INTAKE_REQUEST, fresh)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + WorldAuthoredSourceIntakeDigest.requestDigest(NAMESPACE, INTAKE_REQUEST, retained)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + WorldAuthoredSourceIntakeDigest.receiptDigest( + NAMESPACE, WORLD_OPERATION, "sha256:bad", fresh, 9001L)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + WorldAuthoredSourceIntakeDigest.receiptDigest( + NAMESPACE, + WORLD_OPERATION, + WorldAuthoredSourceIntakeDigest.requestDigest(NAMESPACE, INTAKE_REQUEST, fresh), + fresh, + 0L)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static AuthoredWorldSourceEvidence source( + String worldSlug, String displayName, String provenanceKind) { + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, REGISTRATION, TENANT, "north-star", worldSlug, displayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + REGISTRATION, + SOURCE_OPERATION, + requestDigest, + TENANT, + "north-star", + worldSlug, + displayName, + 42L, + "legacy-game-tenant-42", + provenanceKind); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + REGISTRATION, + SOURCE_OPERATION, + requestDigest, + TENANT, + "north-star", + worldSlug, + displayName, + 42L, + "legacy-game-tenant-42", + provenanceKind, + evidenceDigest); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeServiceTest.java new file mode 100644 index 0000000000..b3ea8870ac --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeServiceTest.java @@ -0,0 +1,503 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceClient; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceGrpcCodec.ReadRequest; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class WorldAuthoredSourceIntakeServiceTest { + private static final String NAMESPACE = "firemud"; + private static final UUID INTAKE_REQUEST = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID TENANT = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID SOURCE_OPERATION = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final String WORLD = "violet-wilds"; + + private final AuthoredWorldSourceClient client = mock(AuthoredWorldSourceClient.class); + private final WorldAuthoredSourceIntakeRepository repository = + mock(WorldAuthoredSourceIntakeRepository.class); + private final RecordingTransactionManager transactionManager = new RecordingTransactionManager(); + private final WorldAuthoredSourceIntakeService service = + new WorldAuthoredSourceIntakeService(client, repository, transactionManager, NAMESPACE); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void requiresExactAuthenticatedGameDesignPeerBeforeOwnerAccess() { + assertThatThrownBy( + () -> + withoutPeer( + () -> + service.intake( + INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, digest('a')))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withPeer( + peer("firemud", "game-session-service"), + () -> + service.intake( + INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, digest('a')))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withPeer( + peer("other", "game-design-service"), + () -> + service.intake( + INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, digest('a')))) + .isInstanceOf(SecurityException.class); + + verifyNoInteractions(client, repository); + } + + @Test + void validatesAllRequestSelectorsAndDigestBeforeOwnerAccess() { + withGameDesign( + () -> { + assertThatThrownBy( + () -> service.intake(null, TENANT, WORLD, SOURCE_OPERATION, digest('a'))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + service.intake( + new UUID(0L, 0L), TENANT, WORLD, SOURCE_OPERATION, digest('a'))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> service.intake(INTAKE_REQUEST, null, WORLD, SOURCE_OPERATION, digest('a'))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + service.intake( + INTAKE_REQUEST, new UUID(0L, 0L), WORLD, SOURCE_OPERATION, digest('a'))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + service.intake( + INTAKE_REQUEST, TENANT, "Bad-Slug", SOURCE_OPERATION, digest('a'))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + service.intake(INTAKE_REQUEST, TENANT, WORLD, new UUID(0L, 0L), digest('a'))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + service.intake(INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, "sha256:bad")) + .isInstanceOf(IllegalArgumentException.class); + return null; + }); + + verifyNoInteractions(client, repository); + } + + @Test + void deniesWritableAmbientTransactionBeforeReadingOrWriting() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.intake( + INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, digest('a')))) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(client, repository); + } + + @Test + void deniesReadOnlyAmbientTransactionBeforeReadingOrWriting() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.intake( + INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, digest('a')))) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(client, repository); + } + + @Test + void exactStoredRetryReturnsOriginalReceiptWithoutCallingGameDesign() { + AuthoredWorldSourceEvidence source = source(NAMESPACE, TENANT, SOURCE_OPERATION, WORLD); + WorldAuthoredSourceIntakeReceipt receipt = receipt(source, 9001L); + when(repository.read(NAMESPACE, INTAKE_REQUEST)).thenReturn(Optional.of(receipt)); + + WorldAuthoredSourceIntakeReceipt result = + withGameDesign( + () -> + service.intake( + INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest())); + + assertThat(result).isSameAs(receipt); + verify(client, never()).read(any(ReadRequest.class)); + verify(repository, never()).acceptFresh(any(), any(), any()); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void changedRequestScopeOrExpectedDigestConflictsBeforeRemoteReadOrMutation() { + AuthoredWorldSourceEvidence source = source(NAMESPACE, TENANT, SOURCE_OPERATION, WORLD); + when(repository.read(NAMESPACE, INTAKE_REQUEST)) + .thenReturn(Optional.of(receipt(source, 9001L))); + + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.intake( + INTAKE_REQUEST, + UUID.fromString("66666666-6666-4666-8666-666666666666"), + WORLD, + SOURCE_OPERATION, + source.evidenceDigest()))) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.RegistrationConflictException.class); + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.intake( + INTAKE_REQUEST, + TENANT, + "amber-coast", + SOURCE_OPERATION, + source.evidenceDigest()))) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.RegistrationConflictException.class); + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.intake( + INTAKE_REQUEST, + TENANT, + WORLD, + UUID.fromString("77777777-7777-4777-8777-777777777777"), + source.evidenceDigest()))) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.RegistrationConflictException.class); + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.intake( + INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, digest('b')))) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.RegistrationConflictException.class); + + verify(client, never()).read(any(ReadRequest.class)); + verify(repository, never()).acceptFresh(any(), any(), any()); + } + + @Test + void sourceUnavailableCannotEnterTheOwnerWriteTransaction() { + when(repository.read(NAMESPACE, INTAKE_REQUEST)).thenReturn(Optional.empty()); + when(client.read(any(ReadRequest.class))) + .thenThrow(new IllegalStateException("source unavailable")); + + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.intake( + INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, digest('a')))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("source unavailable"); + + verify(repository).read(NAMESPACE, INTAKE_REQUEST); + verify(repository, never()).acceptFresh(any(), any(), any()); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void changedAuthenticatedSourceCannotEnterTheOwnerWriteTransaction() { + when(repository.read(NAMESPACE, INTAKE_REQUEST)).thenReturn(Optional.empty()); + AuthoredWorldSourceEvidence[] substitutedSources = { + source("other", TENANT, SOURCE_OPERATION, WORLD), + source( + NAMESPACE, + UUID.fromString("66666666-6666-4666-8666-666666666666"), + SOURCE_OPERATION, + WORLD), + source(NAMESPACE, TENANT, UUID.fromString("77777777-7777-4777-8777-777777777777"), WORLD), + source(NAMESPACE, TENANT, SOURCE_OPERATION, "amber-coast") + }; + for (AuthoredWorldSourceEvidence substituted : substitutedSources) { + when(client.read(any(ReadRequest.class))).thenReturn(substituted); + + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.intake( + INTAKE_REQUEST, + TENANT, + WORLD, + SOURCE_OPERATION, + substituted.evidenceDigest()))) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException.class); + } + + verify(repository, never()).acceptFresh(any(), any(), any()); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void callerDigestMustMatchFreshAuthenticatedEvidenceBeforeOpeningTransaction() { + AuthoredWorldSourceEvidence source = source(NAMESPACE, TENANT, SOURCE_OPERATION, WORLD); + when(repository.read(NAMESPACE, INTAKE_REQUEST)).thenReturn(Optional.empty()); + when(client.read(any(ReadRequest.class))).thenReturn(source); + + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.intake( + INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, digest('b')))) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException.class); + + verify(repository, never()).acceptFresh(any(), any(), any()); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void readsFreshSourceBeforeWritableReadCommittedTransactionAndVerifiesFullCommitReadback() { + AuthoredWorldSourceEvidence source = source(NAMESPACE, TENANT, SOURCE_OPERATION, WORLD); + WorldAuthoredSourceIntakeReceipt receipt = receipt(source, 9001L); + AtomicInteger readCount = new AtomicInteger(); + when(repository.read(NAMESPACE, INTAKE_REQUEST)) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return readCount.incrementAndGet() == 1 ? Optional.empty() : Optional.of(receipt); + }); + when(client.read(any(ReadRequest.class))) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return source; + }); + when(repository.acceptFresh(NAMESPACE, INTAKE_REQUEST, source)) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) + .isFalse(); + return receipt; + }); + + WorldAuthoredSourceIntakeReceipt result = + withGameDesign( + () -> + service.intake( + INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest())); + + assertThat(result).isEqualTo(receipt); + assertThat(readCount.get()).isEqualTo(2); + assertThat(transactionManager.startedWith.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(transactionManager.startedWith.isReadOnly()).isFalse(); + assertThat(transactionManager.startedWith.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ArgumentCaptor readRequest = ArgumentCaptor.forClass(ReadRequest.class); + verify(client).read(readRequest.capture()); + assertThat(readRequest.getValue().targetNamespace()).isEqualTo(NAMESPACE); + assertThat(readRequest.getValue().requestId()) + .isNotEqualTo(INTAKE_REQUEST) + .isNotEqualTo(new UUID(0L, 0L)); + assertThat(readRequest.getValue().operationId()).isEqualTo(SOURCE_OPERATION); + assertThat(readRequest.getValue().canonicalTenantId()).isEqualTo(TENANT); + assertThat(readRequest.getValue().worldSlug()).isEqualTo(WORLD); + verify(repository).acceptFresh(NAMESPACE, INTAKE_REQUEST, source); + } + + @Test + void deniesMissingPostCommitReadback() { + AuthoredWorldSourceEvidence source = source(NAMESPACE, TENANT, SOURCE_OPERATION, WORLD); + when(repository.read(NAMESPACE, INTAKE_REQUEST)).thenReturn(Optional.empty(), Optional.empty()); + when(client.read(any(ReadRequest.class))).thenReturn(source); + when(repository.acceptFresh(NAMESPACE, INTAKE_REQUEST, source)) + .thenReturn(receipt(source, 9001L)); + + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.intake( + INTAKE_REQUEST, + TENANT, + WORLD, + SOURCE_OPERATION, + source.evidenceDigest()))) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException.class) + .hasMessageContaining("missing after commit readback"); + + verify(repository).acceptFresh(NAMESPACE, INTAKE_REQUEST, source); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + } + + @Test + void deniesChangedPostCommitLocalSelectorReadback() { + AuthoredWorldSourceEvidence source = source(NAMESPACE, TENANT, SOURCE_OPERATION, WORLD); + WorldAuthoredSourceIntakeReceipt accepted = receipt(source, 9001L); + WorldAuthoredSourceIntakeReceipt changed = receipt(source, 9002L); + when(repository.read(NAMESPACE, INTAKE_REQUEST)) + .thenReturn(Optional.empty(), Optional.of(changed)); + when(client.read(any(ReadRequest.class))).thenReturn(source); + when(repository.acceptFresh(NAMESPACE, INTAKE_REQUEST, source)).thenReturn(accepted); + + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.intake( + INTAKE_REQUEST, + TENANT, + WORLD, + SOURCE_OPERATION, + source.evidenceDigest()))) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException.class) + .hasMessageContaining("changed during commit readback"); + + verify(repository).acceptFresh(NAMESPACE, INTAKE_REQUEST, source); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + } + + private static AuthoredWorldSourceEvidence source( + String namespace, UUID tenant, UUID operation, String world) { + UUID registration = UUID.fromString("11111111-1111-4111-8111-111111111111"); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + namespace, registration, tenant, "north-star", world, "Café 🐉"); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + namespace, + registration, + operation, + requestDigest, + tenant, + "north-star", + world, + "Café 🐉", + 42L, + "legacy-game-tenant-42", + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + namespace, + registration, + operation, + requestDigest, + tenant, + "north-star", + world, + "Café 🐉", + 42L, + "legacy-game-tenant-42", + "NEW_GAME_ROW", + evidenceDigest); + } + + private static WorldAuthoredSourceIntakeReceipt receipt( + AuthoredWorldSourceEvidence source, long localTenantKey) { + String requestDigest = + WorldAuthoredSourceIntakeDigest.requestDigest(NAMESPACE, INTAKE_REQUEST, source); + UUID operationId = UUID.fromString("55555555-5555-4555-8555-555555555555"); + return new WorldAuthoredSourceIntakeReceipt( + 1, + NAMESPACE, + INTAKE_REQUEST, + operationId, + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + requestDigest, + WorldAuthoredSourceIntakeDigest.receiptDigest( + NAMESPACE, operationId, requestDigest, source, localTenantKey), + localTenantKey, + source); + } + + private static String digest(char value) { + return "sha256:" + String.valueOf(value).repeat(64); + } + + private static GrpcPeerIdentity peer(String namespace, String service) { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + } + + private static T withGameDesign(Supplier action) { + return withPeer(peer(NAMESPACE, "game-design-service"), action); + } + + private static T withPeer(GrpcPeerIdentity peer, Supplier action) { + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + return action.get(); + } finally { + context.detach(previous); + } + } + + private static T withoutPeer(Supplier action) { + Context previous = Context.ROOT.attach(); + try { + return action.get(); + } finally { + Context.ROOT.detach(previous); + } + } + + private static final class RecordingTransactionManager + implements org.springframework.transaction.PlatformTransactionManager { + private TransactionDefinition startedWith; + + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + startedWith = definition; + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(definition.isReadOnly()); + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) { + TransactionSynchronizationManager.clear(); + } + + @Override + public void rollback(TransactionStatus status) { + TransactionSynchronizationManager.clear(); + } + } +} From 31e7faa1958b6b3814b42ef39021a9e2eb5018c3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 21:50:44 +1300 Subject: [PATCH 04/13] test: verify translated authored-owner PostgreSQL rejections --- design/project-management/ai-observations.md | 5 +++++ ...aunchDescriptorServiceIntegrationTest.java | 3 ++- ...ldAuthoredSourceIntakeIntegrationTest.java | 22 ++++++++++++++++--- 3 files changed, 26 insertions(+), 4 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index cd6dedfac7..1705ed8719 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -272,3 +272,8 @@ Entry format: - Context: an older stacked worktree's repo-local controller refused status with `SQLite cutover marker does not match database metadata`. This was a reader/version mismatch, not evidence about the PR's review or CI state. - Outcome: the human-designated `/home/ben/.local/bin/firemud-pr-review` reports writer build 8 and is used for the readback instead. No private database, marker or review evidence was edited to bypass the refusal. - Expected pattern: select the installed shared entrypoint named by the active brief, verify its version and preserve fail-closed cutover records; do not repair private metadata from an outdated checkout. + +- `2026-10-03`: Match PostgreSQL rejection proof to the actual exception-translation boundary + - Context: exact CI37109999851 executed seven descriptor and eight World intake PostgreSQL cases. Three failed assertions expected jOOQ `DataAccessException`, while the Spring-managed DSL translated correctly rejected writes into `DataIntegrityViolationException`; the concurrent World failure arrived through its future. Raw-connection fixtures retained their different jOOQ boundary. + - Outcome: the focused fixture correction preserves the descriptor's exact constraint and World's reservation message, SQL state and no-mutation assertions. Corrected runner execution remains required; local compilation or skipped PostgreSQL cases cannot prove the repaired assertions. + - Expected pattern: inspect the actual cause chain and preserve the exact constraint or SQL-state rejection rather than accepting any database error, catching every runtime exception or weakening a production guard. Do not blindly replace exception types in raw-connection fixtures merely because the service-managed DSL translates them. diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java index 4bcd23a5ae..5ce645d2ae 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java @@ -46,6 +46,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Import; +import org.springframework.dao.DataIntegrityViolationException; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; @@ -682,7 +683,7 @@ INSERT INTO launch_descriptor ( failed.getSourceEvidenceJson(), nullSchemaVersion ? failed.getFailureCode() : null, failed.getFailureMessage())) - .isInstanceOf(DataAccessException.class) + .isInstanceOf(DataIntegrityViolationException.class) .hasStackTraceContaining("ck_launch_descriptor_authored_binding_complete"); } diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java index 25c3136364..5155b4d214 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java @@ -3,6 +3,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.sql.SQLException; import java.util.Objects; import java.util.UUID; import java.util.concurrent.CountDownLatch; @@ -25,6 +26,7 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.dao.DataIntegrityViolationException; import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; @@ -164,14 +166,16 @@ void persistsCompleteFreshReceiptAndReusesExactTenantAssociationAcrossWorlds() { "INSERT INTO region (tenant_id, name) VALUES (?, ?)", first.localTenantKey(), "cannot-claim-canonical-selector")) - .isInstanceOf(DataAccessException.class); + .isInstanceOf(DataIntegrityViolationException.class) + .satisfies(this::assertReservedCanonicalSelectorRejected); assertThatThrownBy( () -> dsl.execute( "UPDATE region SET tenant_id = ? WHERE id = ?", first.localTenantKey(), legacyRegionId)) - .isInstanceOf(DataAccessException.class); + .isInstanceOf(DataIntegrityViolationException.class) + .satisfies(this::assertReservedCanonicalSelectorRejected); assertThat( Objects.requireNonNull( dsl.fetchOne("SELECT tenant_id FROM region WHERE id = ?", legacyRegionId), @@ -535,7 +539,8 @@ void concurrentLegacyClaimAfterAllocationCannotTakeTheReservedSelector() throws return null; }); return true; - } catch (DataAccessException expectedReservedKeyRejection) { + } catch (DataIntegrityViolationException expectedReservedKeyRejection) { + assertReservedCanonicalSelectorRejected(expectedReservedKeyRejection); return false; } }); @@ -591,6 +596,17 @@ private long countForCanonicalTenant(UUID tenantId) { .get(0, Long.class); } + private void assertReservedCanonicalSelectorRejected(Throwable throwable) { + assertThat(throwable).hasStackTraceContaining("is reserved for a canonical authored source"); + + Throwable cause = throwable; + while (cause != null && !(cause instanceof SQLException)) { + cause = cause.getCause(); + } + assertThat(cause).isInstanceOf(SQLException.class); + assertThat(((SQLException) cause).getSQLState()).isEqualTo("23514"); + } + private long countReservationsForCanonicalTenant(UUID tenantId) { return Objects.requireNonNull( dsl.fetchOne( From 73ab357d694618a56c65129394fd324b38ad652e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 21:56:36 +1300 Subject: [PATCH 05/13] ci: preserve independent authored-source proof and exact failure evidence --- .github/workflows/ci.yml | 2 +- .../game-authoring-publishing-and-activation.md | 2 +- .../implementation-tracking/world-runtime-and-movement.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c3fc05faf0..7ea82abf65 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1001,7 +1001,7 @@ jobs: retention-days: 7 - name: Run Game Design authored-source read socket mTLS proof - if: ${{ matrix.module == 'game-design-service' }} + if: ${{ !cancelled() && matrix.module == 'game-design-service' }} run: | ./gradlew :game-design-service:test \ --tests net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldSourceMtlsTest \ diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index fb0ae64b34..26588df83b 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -149,7 +149,7 @@ Lifecycle status/proof is also incomplete: artifact and Version epoch checks lac ### Launch, Activation, Cutover, and Termination -The prepared source-bound `ResolveLaunchDescriptor` producer claims `(targetNamespace, canonicalTenantId, controlPlaneRequestId)` before mutable template/version resolution and retains the exact authored-source request and successful result digests in its existing immutable descriptor family. Changed source, world, template or overrides cannot reuse that claim to select another release. `GetLaunchDescriptor` prepares exact readback for verified Game Session and World peers; the canonical request/result schema is owned by the [Game Design API contract](../../architecture/microservices/game-design-service/api-contracts.md#authored-source-bound-launch-descriptor-and-exact-readback). Shared codec/vector unit proof executes locally. The owner candidate also retains typed deterministic business denials in that same immutable request/outcome family, without fabricating descriptor or release IDs. Thirteen descriptor and nine source-read physical mTLS methods execute cleanly locally with production guards/handlers and mocked source producers; this is not database-to-socket or live creation proof. The preceding exact runner executed all seven descriptor PostgreSQL cases, with one pass and six actual SMALLINT readback-conversion failures. The explicit metadata conversion correction and its unit regression pass locally; corrected PostgreSQL execution and exact CI remain required. World owner-local fresh intake/reservation/readback is a separate prepared prerequisite recorded in [World Runtime and Movement](./world-runtime-and-movement.md#current-status), not release publication or canonical content materialization. The descriptor freezes `versionId`, `scriptPatchVersion`, `runtimeFlags`, `generationConfigRevision`, Game Design's `versionStateEpoch`, `releaseBundleRef`, and approved replacement `remapSetId` where required. Runtime provisioning must consume that immutable descriptor rather than resolve mutable "latest" control-plane state mid-flight. Game Design also exposes `GetVersionState` and `CompareAndSetVersionState`, and persists approved remap sets through `CreateTemplateRemapSet`, `ApproveTemplateRemapSet`, and `GetTemplateRemapSet`. +The prepared source-bound `ResolveLaunchDescriptor` producer claims `(targetNamespace, canonicalTenantId, controlPlaneRequestId)` before mutable template/version resolution and retains the exact authored-source request and successful result digests in its existing immutable descriptor family. Changed source, world, template or overrides cannot reuse that claim to select another release. `GetLaunchDescriptor` prepares exact readback for verified Game Session and World peers; the canonical request/result schema is owned by the [Game Design API contract](../../architecture/microservices/game-design-service/api-contracts.md#authored-source-bound-launch-descriptor-and-exact-readback). Shared codec/vector unit proof executes locally. The owner candidate also retains typed deterministic business denials in that same immutable request/outcome family, without fabricating descriptor or release IDs. Thirteen descriptor and nine source-read physical mTLS methods execute cleanly locally with production guards/handlers and mocked source producers; this is not database-to-socket or live creation proof. Exact CI37109999851 at `9447e0ef5` executed all seven descriptor PostgreSQL cases: six passed after the published metadata conversion correction, while one fixture expected jOOQ's exception instead of Spring's translated integrity exception from the correct database constraint. All thirteen descriptor socket cases passed in that runner; the separate nine source-read cases did not run after the preceding failed step. The bounded fixture correction passes local checks, but PostgreSQL skips do not prove its repaired assertions. Corrected complete runner execution remains required; the source-read step now runs independently of earlier test failures while retaining a failing job for any failed proof. World owner-local fresh intake/reservation/readback is a separate prepared prerequisite recorded in [World Runtime and Movement](./world-runtime-and-movement.md#current-status), not release publication or canonical content materialization. The descriptor freezes `versionId`, `scriptPatchVersion`, `runtimeFlags`, `generationConfigRevision`, Game Design's `versionStateEpoch`, `releaseBundleRef`, and approved replacement `remapSetId` where required. Runtime provisioning must consume that immutable descriptor rather than resolve mutable "latest" control-plane state mid-flight. Game Design also exposes `GetVersionState` and `CompareAndSetVersionState`, and persists approved remap sets through `CreateTemplateRemapSet`, `ApproveTemplateRemapSet`, and `GetTemplateRemapSet`. The candidate denies legacy numeric `StartSession` preflight and cutover descriptor lookup with `AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED`, before descriptor lookup or lifecycle/pointer/World mutation. There is no canonical source evidence in those requests, and no proved numeric World association; they must not be described as successful unpatched launch. Canonical Game Session orchestration and World durable source-bound `PREPARING` readback remain required before launch can proceed. The former numeric post-preflight preparation/activation, replacement, compensation and ambiguity branches are not proof of that canonical workflow; retained-instance stop/restart and independent lifecycle coverage remain useful but separate. Game Design denies any requested/template script patch because exact published-for-base and Automation `READY` evidence are unavailable. Game Session must independently re-check patch publication/base identity and join Automation's tenant runtime status before patched launch is enabled. The typed descriptor and launch-preflight failures include `TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED`, `INVALID_TEMPLATE_CONFIGURATION`, `SCRIPT_PATCH_OVERRIDE_CONFLICT`, `SCRIPT_PATCH_NOT_READY`, `RELEASE_BUNDLE_NOT_FOUND`, `RELEASE_ATTESTATION_MISMATCH`, `VERSION_STATE_EPOCH_STALE`, and `LAUNCH_REMAP_REQUIRED`. `SCRIPT_PATCH_NOT_READY` is containment, not readiness proof. Existing numeric World `PrepareWorldInstance`, activation and failed-preparation seams do not yet retain the canonical authored-source binding; their presence and earlier fixture results are not proof of the required UUID-qualified owner handoff. diff --git a/design/project-management/implementation-tracking/world-runtime-and-movement.md b/design/project-management/implementation-tracking/world-runtime-and-movement.md index e09d527d12..cd7929c36e 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for world runtime and movement. C ## Current Status -**Canonical launch prerequisite:** Current World design/materialization rows and `PrepareWorldInstance` still use World's private numeric tenant key. The candidate adds V23 and an explicitly unwired owner-local fresh-source intake service/repository: a complete authenticated Game Design `NEW_GAME_ROW` receipt, private World tenant association, numeric-key reservation and immutable intake receipt commit together, with exact independent readback. Legacy numeric writes cannot take a reserved canonical selector; existing legacy keys are reserved without inventing UUID associations. Shared source-client/codec and nine exact Game Design source-method socket tests pass locally using production transport and a mocked source repository, not the complete normal producer or database-to-socket path. Fifteen World digest/service unit cases execute cleanly; the eight PostgreSQL intake cases compile but skip locally without Docker, so transactional, migration and concurrency execution remains unproved locally. Focused World/Game Session checks, static analysis and packaged JAR construction pass. The automatic normal Game Design registration/delivery producer, World RPC receiver, canonical-source-qualified content writer, actual content/descriptor/release readback and separate audited retained-World association remain required. The [World API contract](../../architecture/microservices/world-management-service/api-contracts.md#authenticated-authored-content-intake-and-tenant-association) owns this boundary. Numeric similarity, selectors and Account's migration manifest are not substitutes, and no runtime activation is authorized. +**Canonical launch prerequisite:** Current World design/materialization rows and `PrepareWorldInstance` still use World's private numeric tenant key. The candidate adds V23 and an explicitly unwired owner-local fresh-source intake service/repository: a complete authenticated Game Design `NEW_GAME_ROW` receipt, private World tenant association, numeric-key reservation and immutable intake receipt commit together, with exact independent readback. Legacy numeric writes cannot take a reserved canonical selector; existing legacy keys are reserved without inventing UUID associations. Shared source-client/codec and nine exact Game Design source-method socket tests pass locally using production transport and a mocked source repository, not the complete normal producer or database-to-socket path. Fifteen World digest/service unit cases execute cleanly; the eight PostgreSQL intake cases compile but skip locally without Docker, so transactional, migration and concurrency execution remains unproved locally. Exact CI37109999851 at `9447e0ef5` executed all eight intake PostgreSQL cases: six passed; two reached the correct reserved-selector rejection but failed on the fixture's jOOQ-versus-Spring exception assumption. The corrected insert/update/concurrent assertions retain the exact reservation message, SQL state `23514`, unchanged legacy row and no-region checks. Local affected checks pass; corrected runner execution remains required. Focused World/Game Session checks, static analysis and packaged JAR construction pass. The automatic normal Game Design registration/delivery producer, World RPC receiver, canonical-source-qualified content writer, actual content/descriptor/release readback and separate audited retained-World association remain required. The [World API contract](../../architecture/microservices/world-management-service/api-contracts.md#authenticated-authored-content-intake-and-tenant-association) owns this boundary. Numeric similarity, selectors and Account's migration manifest are not substitutes, and no runtime activation is authorized. The canonical launch correction must also supply genuinely fresh instance creation, not merely attach a UUID carrier to the legacy prepare call: Game Session's `game_instances.tenant_id` and World's lifecycle/topology tenant selectors remain required numeric fields on this tree. A fresh canonical catalog provides no numeric tenant alias. Widen the actual owner instance/lifecycle representation and source-qualified creation/readback together; adding a binding table while inventing a numeric tenant selector would not close this gate. Exact retained instance associations remain separately source-proved and cannot be inferred from the Game Session row number or an Account mapping. From 9e9e8d69d4fe656164355053d0f6a9a2d6e8c45e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 22:38:55 +1300 Subject: [PATCH 06/13] Add canonical JOIN terminal storage and exact recovery proof --- .github/workflows/ci.yml | 11 +- .../account-service/api-contracts.md | 4 + .../account-service/runtime-and-data.md | 2 +- .../AccountAuditOutboxRepository.java | 107 +++ .../AccountJoinOperationRepository.java | 526 ++++++++++++- ...untCanonicalJoinReconciliationService.java | 459 ++++++++++++ ...countMembershipAuthorityEventProducer.java | 118 +++ ..._canonical_uuid_join_terminal_outcomes.sql | 318 ++++++++ ...icalJoinReconciliationIntegrationTest.java | 639 ++++++++++++++++ ...ScopeCanonicalIdentityIntegrationTest.java | 705 +++++++++++++++++- ...tJoinOperationRepositoryCanonicalTest.java | 45 ++ ...anonicalJoinReconciliationServiceTest.java | 530 +++++++++++++ 12 files changed, 3433 insertions(+), 31 deletions(-) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalJoinReconciliationService.java create mode 100644 services/account-service/src/main/resources/db/migration/V50__canonical_uuid_join_terminal_outcomes.sql create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCanonicalJoinReconciliationIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalJoinReconciliationServiceTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c3fc05faf0..d05d7ac006 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1375,13 +1375,20 @@ jobs: run: | ./gradlew :account-service:integrationTest \ --tests integration.net.firedevops.firemud.accountservice.repository.AccountConnectScopeCanonicalIdentityIntegrationTest \ + --tests integration.net.firedevops.firemud.accountservice.AccountCanonicalJoinReconciliationIntegrationTest \ -PfullCheck --no-build-cache --no-configuration-cache bash dev-tools/validation/inspect-test-results.sh \ --strict \ --require-suite integration.net.firedevops.firemud.accountservice.repository.AccountConnectScopeCanonicalIdentityIntegrationTest \ + --require-suite integration.net.firedevops.firemud.accountservice.AccountCanonicalJoinReconciliationIntegrationTest \ --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountConnectScopeCanonicalIdentityIntegrationTest#v2ScopesPreserveV1AndRequireExactUuidSourcesWithoutBearerOrNumericAliases()' \ --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountConnectScopeCanonicalIdentityIntegrationTest#canonicalJoinJournalSharesRequestIdsAndRetainsPendingHashOnlyIntentEvidence()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountConnectScopeCanonicalIdentityIntegrationTest#canonicalTerminalJournalPreservesHistoryAndOnlyStoresContractShapedOutcomes()' \ --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountConnectScopeCanonicalIdentityIntegrationTest#concurrentCanonicalIntentAndPolicyRetriesRecoverOneImmutableRequestRow()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountCanonicalJoinReconciliationIntegrationTest#completeHistoricalReadbackCommitsAfterExpiryAndLaterUnavailablePolicyAttempt()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountCanonicalJoinReconciliationIntegrationTest#eventReadbackRejectsStalePendingDtoAfterJournalHasTerminalized()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountCanonicalJoinReconciliationIntegrationTest#absentOrContradictoryOwnerEvidenceRemainsPendingWithoutReconciliationSideEffects()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountCanonicalJoinReconciliationIntegrationTest#concurrentExactTerminalRetryAndReconcilerRetainOneHistoricalWriteSet()' \ account-service - name: Upload Account canonical JOIN scope and intent PostgreSQL proof results @@ -1389,7 +1396,9 @@ jobs: uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 with: name: account-canonical-join-scope-intent-postgresql-proof-${{ github.sha }} - path: services/account-service/build/test-results/integrationTest/TEST-*AccountConnectScopeCanonicalIdentityIntegrationTest.xml + path: | + services/account-service/build/test-results/integrationTest/TEST-*AccountConnectScopeCanonicalIdentityIntegrationTest.xml + services/account-service/build/test-results/integrationTest/TEST-*AccountCanonicalJoinReconciliationIntegrationTest.xml if-no-files-found: warn retention-days: 7 diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 478c53921b..908e5e1576 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -96,6 +96,10 @@ Appending a canonical receipt requires an actual read-write Account owner transa Account's canonical tenant audit uses the version-qualified UUID envelope of [Logging & Admin's ingress and receipt owner](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt) through the existing outbox and RPCs. Account preserves exact retained numeric/platform envelope history and never invents a numeric alias for a fresh canonical tenant. The producer must compare the exact typed identity in delivery/readback before persisting terminal delivery evidence. A successful canonical JOIN must append that immutable outbox envelope in the same owner transaction as its membership, role snapshot, authority event, provisional receipt and operation outcome; implementing the audit carrier alone is not positive JOIN or admission proof. +The canonical `ACCOUNT_JOINED_PUBLIC_PRODUCTION` payload retains the closed JOIN field set in this serialization order: `accountId`, `tenantId`, `worldSlug`, `realmSlug`, `membershipVersion`, `requestId`. Account and tenant values are their exact canonical UUID strings; `membershipVersion` is the exact one-tenant map whose sole key is that tenant UUID and whose value is the canonical decimal-string version from the committed membership. The stable audit identity remains `UUID.nameUUIDFromBytes` over UTF-8 `account-join-audit/v1:` followed by the exact JOIN request ID; the identity prefix does not select the envelope's tenant representation. Producer and recovery compare the original payload bytes and digest, not a reserialized equivalent or a scalar membership-version substitute. Retained version-1 payload bytes are not rewritten. + +Canonical abandoned-intent reconciliation is readback-only. Under the Account and operation fences it must prove the exact immutable scope/source and policy-bound intent, committed membership and role snapshot, provisional transition receipt, tenant audit bytes, and matching authority event/checkpoint before recording a terminal outcome. An expired retained scope blocks new JOIN work but does not invalidate exact prior-commit evidence; a later unavailable policy-attempt diagnostic is retained and cannot erase the earlier bound policy or substitute for current authorization. Missing or contradictory evidence remains `PENDING`, with bounded attempt diagnostics. A bad source in one candidate must not prevent independent candidates from being checked. Reaching the automatic-attempt cap does not prove failure and does not remove the existing exact readback recovery obligation. This component supplies no caller authorization, membership creation, policy reevaluation, admission or runtime activation. + ### Current vs Target Export Lifecycle The current `GET /accounts/{accountId}/export` route is a synchronous Account/profile-local read. Direct account-ID `ExportAccount` gRPC and the legacy account-targeted tenant-export REST/service and gRPC entries deny before data access. The local Account read has no cross-service required-owner fan-in and does not satisfy ADR 0050; none of these current surfaces may be described as a complete portable-data or tenant-admin export. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index e3704b4471..46a384e678 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -8,7 +8,7 @@ Account owns platform identity, hosted Creator Party/operator and terms currentn ## Implementation Status -The local V45 candidate widens the existing membership and role storage, rather than creating a second authority family. Retained numeric rows remain unbridged history with unchanged state, counters and receipt/event bytes. Canonical writes require the exact persisted Account UUID and existing immutable fresh or approved-retained tenant source; fresh membership has a canonical tenant UUID and no numeric alias. Typed source/provenance facts alone are not authentication. This foundation does not yet implement canonical scope persistence, positive fresh JOIN, event/audit/reconciliation or an enabled runtime RPC. The [canonical JOIN encoding](./api-contracts.md#canonical-uuid-join-evidence) belongs to the API owner; component status and required producer/consumer proof remain in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). +Canonical UUID membership, scope, journal, receipt, audit and event components widen the existing Account-owned families without rewriting retained history or inventing numeric aliases. Their readback-only reconciliation is not a public JOIN producer or fresh caller authorization. Complete authenticated current-target/entitlement composition and positive JOIN proof remain required; runtime paths stay denied. The [canonical JOIN contract](./api-contracts.md#canonical-uuid-join-evidence) belongs to the API owner, and component capability, executed proof and remaining gaps belong to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). 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). diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java index 85b3f8ef19..b4ded0dad8 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java @@ -7,17 +7,21 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.time.Instant; import java.util.List; +import java.util.Map; import java.util.Optional; import java.util.UUID; +import java.util.regex.Pattern; import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; import net.firedevops.firemud.accountservice.dto.AccountAuditTenantIdentity; +import net.firedevops.firemud.accountservice.dto.MembershipTransitionReceiptDigest; import net.firedevops.firemud.accountservice.jooq.tables.records.AccountAuditOutboxRecord; import org.jooq.DSLContext; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; /** Owner-local audit identity, immutable envelope, and durable delivery state. */ @Repository @@ -25,6 +29,8 @@ value = "EI_EXPOSE_REP2", justification = "Injected DSLContext is an internal Spring collaborator.") public class AccountAuditOutboxRepository { + private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]*"); + private static final JsonMapper CANONICAL_JOIN_AUDIT_JSON = JsonMapper.builder().build(); private final DSLContext dsl; public AccountAuditOutboxRepository(DSLContext dsl) { @@ -83,6 +89,93 @@ public Optional findExactCanonicalTenantEnvelopeForUpdate( return found; } + /** + * Locks the existing JOIN audit identity and returns it only for its exact canonical UUID scope. + * A present event with another scope, tenant representation, producer, or event type is + * contradictory evidence rather than an absent canonical audit. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional findCanonicalJoinEnvelopeForUpdate( + UUID auditEventId, UUID canonicalTenantUuid) { + requireReadWriteOwnerTransaction(); + if (auditEventId == null + || canonicalTenantUuid == null + || new UUID(0L, 0L).equals(canonicalTenantUuid)) { + throw new IllegalArgumentException("Canonical JOIN audit identity and tenant are required"); + } + Optional found = + dsl.selectFrom(ACCOUNT_AUDIT_OUTBOX) + .where(ACCOUNT_AUDIT_OUTBOX.AUDIT_EVENT_ID.eq(auditEventId)) + .forUpdate() + .fetchOptional(this::toEnvelope); + found.ifPresent( + actual -> { + if (!"tenant".equals(actual.scope()) + || actual.tenantIdentityVersion() != AccountAuditTenantIdentity.VERSION_2 + || actual.tenantId() != null + || !canonicalTenantUuid.equals(actual.tenantUuid()) + || !"account-service".equals(actual.producerService()) + || !"ACCOUNT_JOINED_PUBLIC_PRODUCTION".equals(actual.eventType())) { + throw new IllegalStateException( + "Canonical JOIN audit identity differs from its immutable UUID envelope"); + } + }); + return found; + } + + /** + * Serializes the existing six-field JOIN audit payload for canonical UUID identity. The field + * order and names remain those of the retained JOIN payload; only the UUID identities and the + * canonical one-tenant membership-version map are represented in their owning forms. + */ + public static String canonicalJoinPayload( + UUID accountUuid, + UUID tenantUuid, + String worldSlug, + String realmSlug, + Map membershipVersion, + String requestId) { + requireCanonicalUuid(accountUuid, "Account UUID"); + requireCanonicalUuid(tenantUuid, "tenant UUID"); + if (worldSlug == null || worldSlug.isEmpty() || realmSlug == null || realmSlug.isEmpty()) { + throw new IllegalArgumentException("Canonical JOIN audit target slugs are required"); + } + String canonicalRequestId = MembershipTransitionReceiptDigest.requireRequestIdV2(requestId); + if (membershipVersion == null + || membershipVersion.size() != 1 + || !membershipVersion.containsKey(tenantUuid.toString())) { + throw new IllegalArgumentException( + "Canonical JOIN audit membership version must contain exactly its tenant UUID"); + } + String version = membershipVersion.get(tenantUuid.toString()); + if (version == null || !POSITIVE_DECIMAL.matcher(version).matches()) { + throw new IllegalArgumentException( + "Canonical JOIN audit membership version must be a positive canonical decimal"); + } + try { + if (Long.parseLong(version) <= 0L) { + throw new IllegalArgumentException( + "Canonical JOIN audit membership version must be a positive BIGINT"); + } + } catch (NumberFormatException exception) { + throw new IllegalArgumentException( + "Canonical JOIN audit membership version must be a positive BIGINT", exception); + } + try { + return CANONICAL_JOIN_AUDIT_JSON.writeValueAsString( + new CanonicalJoinAuditPayload( + accountUuid.toString(), + tenantUuid.toString(), + worldSlug, + realmSlug, + Map.of(tenantUuid.toString(), version), + canonicalRequestId)); + } catch (RuntimeException exception) { + throw new IllegalStateException( + "Canonical JOIN audit payload serialization failed", exception); + } + } + private AccountAuditEnvelope append( UUID auditEventId, String scope, @@ -229,6 +322,20 @@ private static void requireReadWriteOwnerTransaction() { } } + private static void requireCanonicalUuid(UUID value, String field) { + if (value == null || new UUID(0L, 0L).equals(value)) { + throw new IllegalArgumentException(field + " must be a non-nil canonical UUID"); + } + } + + private record CanonicalJoinAuditPayload( + String accountId, + String tenantId, + String worldSlug, + String realmSlug, + Map membershipVersion, + String requestId) {} + private static AccountAuditTenantIdentity retainedIdentity(String scope, Long tenantId) { if ("platform".equals(scope) && tenantId == null) { return AccountAuditTenantIdentity.platformV1(); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java index e8eb8235aa..85a44fcc23 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java @@ -7,6 +7,8 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneOffset; import java.util.List; import java.util.Objects; import java.util.Optional; @@ -29,12 +31,18 @@ public class AccountJoinOperationRepository { private static final int MAX_RECONCILIATION_PAGE_SIZE = 100; private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Pattern UTC_RFC3339 = + Pattern.compile("^([0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2})(?:\\.([0-9]+))?Z$"); private static final String CANONICAL_SELECT_COLUMNS = "SELECT request_id, account_id, tenant_id, verified_caller_binding, scope_token_hash, " + "connect_scope_digest, intent_digest_version, intent_digest, " + "entitlement_authority_availability, allow_public_join, entitlement_version, " + "request_digest_version, request_digest, last_attempt_failure_code, " + "last_attempt_authority_availability, caller_bound_authority_invalidated, status, " + + "outcome, membership_id, outcome_membership_version, " + + "outcome_membership_authority_generation, reconciliation_attempt_count, " + + "last_reconciliation_attempt_at, last_reconciliation_attempt_reason, " + + "next_reconciliation_attempt_at, " + "operation_representation_version, scope_digest_version, target_class, account_uuid, " + "tenant_uuid, tenant_slug, realm_id, world_slug, realm_slug, " + "playable_state_namespace_id, playable_state_namespace_uuid, playable_state_scope, " @@ -211,6 +219,7 @@ public boolean insertCanonicalIntent( requireCanonicalOperationInput(requestId, callerBinding); Objects.requireNonNull(scope, "Canonical JOIN scope is required"); CanonicalConnectScopeEvidence scopeEvidence = requireIncomingScope(scope); + lockAccount(scopeEvidence.privateAccountId()); String intentDigest = AccountJoinDigest.intentV2(requestId, scope, callerBinding); int inserted = @@ -269,6 +278,247 @@ public Optional findCanonicalEvidenceByRequestId return readCanonicalEvidenceByRequestId(requestId, false); } + /** + * Lists bounded, nonauthorizing metadata for due canonical PENDING rows below the caller's + * attempt cap. These candidates deliberately do not resolve scope/source evidence and cannot + * establish that an operation may be terminalized. + */ + @Transactional(propagation = Propagation.MANDATORY) + public List findDueCanonicalPendingReconciliation( + Instant now, int limit, int maxAttempts) { + requireOwnerTransaction(); + if (now == null) { + throw new IllegalArgumentException("JOIN reconciliation time is required"); + } + if (limit < 1 || limit > MAX_RECONCILIATION_PAGE_SIZE) { + throw new IllegalArgumentException("JOIN reconciliation page size must be between 1 and 100"); + } + if (maxAttempts < 1) { + throw new IllegalArgumentException("JOIN reconciliation attempt limit must be positive"); + } + + List candidates = + dsl + .fetch( + "SELECT request_id, account_id, reconciliation_attempt_count, " + + "next_reconciliation_attempt_at FROM account_join_operations " + + "WHERE operation_representation_version = 2 AND status = 'PENDING' " + + "AND reconciliation_attempt_count < ? " + + "AND next_reconciliation_attempt_at <= ? " + + "ORDER BY next_reconciliation_attempt_at, created_at, request_id LIMIT ?", + maxAttempts, + toLocalDateTime(now), + limit) + .stream() + .map( + row -> + new CanonicalJoinReconciliationCandidate( + required(row, "request_id", String.class), + required(row, "account_id", Long.class), + required(row, "reconciliation_attempt_count", Integer.class), + toInstant( + required(row, "next_reconciliation_attempt_at", LocalDateTime.class)))) + .toList(); + return candidates; + } + + /** + * Advances one canonical pending operation's bounded retry schedule under its Account and row + * fences. A false result means the candidate changed, is no longer due, or reached its cap. + */ + @Transactional(propagation = Propagation.MANDATORY) + public boolean recordCanonicalReconciliationAttempt( + String requestId, + int expectedAttemptCount, + int maxAttempts, + Instant attemptedAt, + String reason, + Instant nextAttemptAt) { + requireOwnerTransaction(); + requireRequestId(requestId); + if (expectedAttemptCount < 0 || maxAttempts < 1 || expectedAttemptCount >= maxAttempts) { + throw new IllegalArgumentException("JOIN reconciliation attempt count is outside its limit"); + } + if (attemptedAt == null || nextAttemptAt == null || nextAttemptAt.isBefore(attemptedAt)) { + throw new IllegalArgumentException("JOIN reconciliation attempt times are invalid"); + } + if (reason == null || reason.isBlank() || reason.trim().length() > 128) { + throw new IllegalArgumentException( + "JOIN reconciliation reason must contain 1 to 128 characters"); + } + String exactReason = reason.trim(); + + Record observed = + dsl.fetchOne( + "SELECT account_id FROM account_join_operations WHERE request_id = ? " + + "AND operation_representation_version = 2", + requestId); + if (observed == null) { + return false; + } + long accountId = required(observed, "account_id", Long.class); + lockAccount(accountId); + Record locked = + dsl.fetchOne( + "SELECT account_id, status, reconciliation_attempt_count, " + + "next_reconciliation_attempt_at FROM account_join_operations " + + "WHERE request_id = ? AND operation_representation_version = 2 FOR UPDATE", + requestId); + if (locked == null || required(locked, "account_id", Long.class) != accountId) { + return false; + } + LocalDateTime nextAttemptTime = + required(locked, "next_reconciliation_attempt_at", LocalDateTime.class); + if (!"PENDING".equals(required(locked, "status", String.class)) + || required(locked, "reconciliation_attempt_count", Integer.class) != expectedAttemptCount + || expectedAttemptCount >= maxAttempts + || toInstant(nextAttemptTime).isAfter(attemptedAt)) { + return false; + } + + int updated = + dsl.execute( + "UPDATE account_join_operations SET reconciliation_attempt_count = " + + "reconciliation_attempt_count + 1, last_reconciliation_attempt_at = ?, " + + "last_reconciliation_attempt_reason = ?, next_reconciliation_attempt_at = ?, " + + "updated_at = ? WHERE request_id = ? AND operation_representation_version = 2 " + + "AND status = 'PENDING' AND reconciliation_attempt_count = ? " + + "AND reconciliation_attempt_count < ? AND reconciliation_attempt_count < 2147483647 " + + "AND next_reconciliation_attempt_at <= ?", + toLocalDateTime(attemptedAt), + exactReason, + toLocalDateTime(nextAttemptAt), + toLocalDateTime(attemptedAt), + requestId, + expectedAttemptCount, + maxAttempts, + toLocalDateTime(attemptedAt)); + return updated == 1; + } + + /** + * Persists a terminal V2 JOIN journal result after the caller has proved the complete dependent + * Account operation, membership, role snapshot, authority event/checkpoint, provisional receipt, + * and audit envelope in this same owner transaction. These supplied values are storage fields, + * not authentication or dependent-evidence proof. COMMITTED is for exact durable-commit readback, + * including recovery after scope expiry; expiry does not authorize new JOIN work. FAILED remains + * gated on an unexpired scope and the latest available-policy attempt. The method checks the row + * and policy fences plus the exact current canonical membership row; its successful readback + * alone is not JOIN proof. + */ + @Transactional(propagation = Propagation.MANDATORY) + public CanonicalJoinOperationEvidence finishCanonicalOperation( + String requestId, + String status, + String outcome, + Long membershipId, + Long membershipVersion, + Long membershipAuthorityGeneration) { + requireOwnerTransaction(); + requireRequestId(requestId); + requireCanonicalTerminalShape( + status, outcome, membershipId, membershipVersion, membershipAuthorityGeneration); + + CanonicalJoinOperationEvidence observed = + readCanonicalEvidenceByRequestId(requestId, false) + .orElseThrow( + () -> + new CanonicalJoinOperationConflictException("Canonical JOIN intent is absent")); + lockAccount(observed.privateAccountId()); + CanonicalJoinOperationEvidence operation = + lockCanonicalEvidenceByRequestId(requestId) + .orElseThrow( + () -> + new CanonicalJoinOperationConflictException("Canonical JOIN intent is absent")); + + if (!"PENDING".equals(operation.status())) { + if (canonicalTerminalMatches( + operation, + status, + outcome, + membershipId, + membershipVersion, + membershipAuthorityGeneration)) { + return operation; + } + throw new CanonicalJoinOperationConflictException( + "Canonical JOIN request already has a different terminal result"); + } + if (!"AVAILABLE".equals(operation.entitlementAuthorityAvailability()) + || operation.requestDigestVersion() == null + || operation.requestDigest() == null + || operation.entitlementVersion() == null) { + throw new CanonicalJoinOperationConflictException( + "Canonical JOIN cannot terminalize without available bound policy evidence"); + } + + if ("COMMITTED".equals(status)) { + if (!Boolean.TRUE.equals(operation.allowPublicJoin()) + || !canonicalMembershipMatches( + operation, membershipId, membershipVersion, membershipAuthorityGeneration)) { + throw new CanonicalJoinOperationConflictException( + "Canonical JOIN committed fields lack matching current membership readback"); + } + } else { + if (!isScopeUnexpired(operation.scopeEvidence().connectScopeExpiresAt(), Instant.now())) { + throw new CanonicalJoinOperationConflictException( + "Expired canonical JOIN scope must remain pending for caller retry"); + } + if (!"AVAILABLE".equals(operation.lastAttemptAuthorityAvailability()) + || operation.lastAttemptFailureCode() != null) { + throw new CanonicalJoinOperationConflictException( + "Canonical JOIN failure requires a successful available-policy attempt"); + } + if ("PUBLIC_PRODUCTION_ADMISSION_DENIED".equals(outcome) + && !Boolean.FALSE.equals(operation.allowPublicJoin())) { + throw new CanonicalJoinOperationConflictException( + "Canonical JOIN denial outcome contradicts its available policy evidence"); + } + if ("MEMBERSHIP_RECONCILIATION_REQUIRED".equals(outcome) + && !Boolean.TRUE.equals(operation.allowPublicJoin())) { + throw new CanonicalJoinOperationConflictException( + "Canonical JOIN reconciliation outcome contradicts its available policy evidence"); + } + } + + int updated = + dsl.execute( + "UPDATE account_join_operations SET status = ?, outcome = ?, membership_id = ?, " + + "outcome_membership_version = ?, outcome_membership_authority_generation = ?, " + + "updated_at = CURRENT_TIMESTAMP " + + "WHERE request_id = ? AND operation_representation_version = 2 " + + "AND status = 'PENDING' AND request_digest_version = 2 AND request_digest = ? " + + "AND entitlement_version = ? AND allow_public_join = ?", + status, + outcome, + membershipId, + membershipVersion, + membershipAuthorityGeneration, + requestId, + operation.requestDigest(), + operation.entitlementVersion(), + operation.allowPublicJoin()); + if (updated != 1) { + throw new CanonicalJoinOperationConflictException( + "Canonical JOIN operation changed before terminal write"); + } + + CanonicalJoinOperationEvidence committed = + readCanonicalEvidenceByRequestId(requestId, false) + .orElseThrow( + () -> new IllegalStateException("Canonical JOIN terminal readback is absent")); + if (!canonicalTerminalMatches( + committed, + status, + outcome, + membershipId, + membershipVersion, + membershipAuthorityGeneration)) { + throw new IllegalStateException("Canonical JOIN terminal readback differs from its write"); + } + return committed; + } + /** Binds or exactly replays available V2 policy evidence under the Account and journal fences. */ @Transactional(propagation = Propagation.MANDATORY) public CanonicalJoinOperationEvidence bindCanonicalPolicyEvidence( @@ -281,6 +531,7 @@ public CanonicalJoinOperationEvidence bindCanonicalPolicyEvidence( requireCanonicalOperationInput(requestId, callerBinding); Objects.requireNonNull(scope, "Canonical JOIN scope is required"); CanonicalConnectScopeEvidence scopeEvidence = requireIncomingScope(scope); + lockAccount(scopeEvidence.privateAccountId()); String intentDigest = AccountJoinDigest.intentV2(requestId, scope, callerBinding); String requestDigest = AccountJoinDigest.requestV2( @@ -298,7 +549,27 @@ public CanonicalJoinOperationEvidence bindCanonicalPolicyEvidence( if (operation.requestDigest() != null) { requireCanonicalPolicyMatch(operation, requestDigest, allowPublicJoin, entitlementVersion); - return operation; + if ("AVAILABLE".equals(operation.lastAttemptAuthorityAvailability()) + && operation.lastAttemptFailureCode() == null) { + return operation; + } + int diagnosticsUpdated = + dsl.execute( + "UPDATE account_join_operations SET last_attempt_authority_availability = 'AVAILABLE', " + + "last_attempt_failure_code = NULL, updated_at = CURRENT_TIMESTAMP " + + "WHERE request_id = ? AND operation_representation_version = 2 " + + "AND status = 'PENDING' AND request_digest_version = 2 " + + "AND request_digest = ?", + requestId, + requestDigest); + if (diagnosticsUpdated != 1) { + throw new CanonicalJoinOperationConflictException( + "Canonical JOIN policy diagnostics changed before available retry readback"); + } + return readCanonicalEvidenceByRequestId(requestId, false) + .orElseThrow( + () -> + new IllegalStateException("Canonical JOIN available-attempt readback is absent")); } int updated = @@ -339,7 +610,9 @@ public CanonicalJoinOperationEvidence recordCanonicalPolicyUnavailable( throw new IllegalArgumentException( "JOIN attempt failure code must contain 1 to 64 characters"); } + failureCode = failureCode.trim(); CanonicalConnectScopeEvidence scopeEvidence = requireIncomingScope(scope); + lockAccount(scopeEvidence.privateAccountId()); String intentDigest = AccountJoinDigest.intentV2(requestId, scope, callerBinding); CanonicalJoinOperationEvidence operation = lockCanonicalEvidenceByRequestId(requestId) @@ -347,20 +620,31 @@ public CanonicalJoinOperationEvidence recordCanonicalPolicyUnavailable( () -> new CanonicalJoinOperationConflictException("Canonical JOIN intent is absent")); requireCanonicalIntentMatch(operation, requestId, callerBinding, intentDigest, scopeEvidence); - if (operation.requestDigest() != null) { - throw new CanonicalJoinOperationConflictException( - "Available canonical JOIN policy evidence cannot be downgraded"); - } - + String previousRequestDigest = operation.requestDigest(); + String expectedAuthorityAvailability = + previousRequestDigest == null ? "UNAVAILABLE" : "AVAILABLE"; + Boolean previousAllowPublicJoin = operation.allowPublicJoin(); + Long previousEntitlementVersion = operation.entitlementVersion(); + Integer previousRequestDigestVersion = operation.requestDigestVersion(); int updated = - dsl.execute( - "UPDATE account_join_operations SET entitlement_authority_availability = 'UNAVAILABLE', " - + "last_attempt_authority_availability = 'UNAVAILABLE', " - + "last_attempt_failure_code = ?, updated_at = CURRENT_TIMESTAMP " - + "WHERE request_id = ? AND operation_representation_version = 2 " - + "AND status = 'PENDING' AND request_digest IS NULL", - failureCode, - requestId); + previousRequestDigest == null + ? dsl.execute( + "UPDATE account_join_operations SET entitlement_authority_availability = 'UNAVAILABLE', " + + "last_attempt_authority_availability = 'UNAVAILABLE', " + + "last_attempt_failure_code = ?, updated_at = CURRENT_TIMESTAMP " + + "WHERE request_id = ? AND operation_representation_version = 2 " + + "AND status = 'PENDING' AND request_digest IS NULL", + failureCode, + requestId) + : dsl.execute( + "UPDATE account_join_operations SET last_attempt_authority_availability = 'UNAVAILABLE', " + + "last_attempt_failure_code = ?, updated_at = CURRENT_TIMESTAMP " + + "WHERE request_id = ? AND operation_representation_version = 2 " + + "AND status = 'PENDING' AND request_digest_version = 2 " + + "AND request_digest = ?", + failureCode, + requestId, + previousRequestDigest); if (updated != 1) { throw new CanonicalJoinOperationConflictException( "Canonical JOIN operation changed while recording policy unavailability"); @@ -373,14 +657,17 @@ public CanonicalJoinOperationEvidence recordCanonicalPolicyUnavailable( new IllegalStateException( "Canonical JOIN unavailable-attempt readback is absent")); requireCanonicalIntentMatch(committed, requestId, callerBinding, intentDigest, scopeEvidence); - if (!"UNAVAILABLE".equals(committed.entitlementAuthorityAvailability()) - || committed.entitlementVersion() != null - || committed.allowPublicJoin() != null - || committed.requestDigestVersion() != null - || committed.requestDigest() != null + if (!expectedAuthorityAvailability.equals(committed.entitlementAuthorityAvailability())) { + throw new IllegalStateException( + "Canonical JOIN unavailable attempt readback changed authority availability"); + } + if (!Objects.equals(committed.requestDigest(), previousRequestDigest) + || !Objects.equals(committed.requestDigestVersion(), previousRequestDigestVersion) + || !Objects.equals(committed.entitlementVersion(), previousEntitlementVersion) + || !Objects.equals(committed.allowPublicJoin(), previousAllowPublicJoin) || !failureCode.equals(committed.lastAttemptFailureCode())) { throw new IllegalStateException( - "Canonical JOIN unavailable attempt readback contains policy evidence"); + "Canonical JOIN unavailable attempt readback changed immutable policy evidence"); } return committed; } @@ -535,8 +822,8 @@ private Optional readCanonicalEvidenceByRequestI private Optional lockCanonicalEvidenceByRequestId( String requestId) { - // The source read locks the owning Account row before this operation-row lock, preserving the - // Account -> operation ordering used by JOIN and preventing an inversion during retries. + // Callers lock the owning Account before this operation-row lock, preserving the Account -> + // operation ordering used by JOIN and preventing an inversion during retries. if (readCanonicalEvidenceByRequestId(requestId, false).isEmpty()) { return Optional.empty(); } @@ -594,9 +881,10 @@ private static CanonicalJoinOperationEvidence toCanonicalOperationEvidence( } String status = required(row, "status", String.class); - if (!"PENDING".equals(status)) { - throw new IllegalStateException("Canonical JOIN operation has unsupported terminal evidence"); - } + LocalDateTime lastReconciliationAttemptAt = + row.get("last_reconciliation_attempt_at", LocalDateTime.class); + LocalDateTime nextReconciliationAttemptAt = + required(row, "next_reconciliation_attempt_at", LocalDateTime.class); return new CanonicalJoinOperationEvidence( required(row, "request_id", String.class), accountId, @@ -616,6 +904,14 @@ private static CanonicalJoinOperationEvidence toCanonicalOperationEvidence( row.get("last_attempt_failure_code", String.class), required(row, "caller_bound_authority_invalidated", Boolean.class), status, + row.get("outcome", String.class), + row.get("membership_id", Long.class), + row.get("outcome_membership_version", Long.class), + row.get("outcome_membership_authority_generation", Long.class), + required(row, "reconciliation_attempt_count", Integer.class), + lastReconciliationAttemptAt == null ? null : toInstant(lastReconciliationAttemptAt), + row.get("last_reconciliation_attempt_reason", String.class), + toInstant(nextReconciliationAttemptAt), scopeEvidence); } @@ -692,6 +988,129 @@ private static org.jooq.Condition retainedV1Representation() { return org.jooq.impl.DSL.field("operation_representation_version", Integer.class).eq(1); } + private boolean canonicalMembershipMatches( + CanonicalJoinOperationEvidence operation, + Long membershipId, + Long membershipVersion, + Long membershipAuthorityGeneration) { + var provenance = operation.scopeEvidence().tenantProvenance(); + return Boolean.TRUE.equals( + dsl.fetchValue( + "SELECT EXISTS (SELECT 1 FROM account_tenant_membership membership " + + "WHERE membership.id = ? AND membership.account_id = ? " + + "AND membership.tenant_id IS NOT DISTINCT FROM ? " + + "AND membership.tenant_uuid = ? " + + "AND membership.tenant_provenance_kind = ? " + + "AND membership.tenant_source_operation_id = ? " + + "AND membership.tenant_provenance_digest = ? " + + "AND membership.lifecycle_state = 'ACTIVE' " + + "AND membership.gameplay_admission_allowed IS TRUE " + + "AND membership.membership_version = ? " + + "AND membership.membership_authority_generation = ? " + + "AND membership.authority_provenance = 'EXPLICIT_JOIN')", + Boolean.class, + membershipId, + operation.privateAccountId(), + provenance.legacyTenantId(), + operation.scopeEvidence().tenantUuid(), + provenance.kind().name(), + provenance.sourceOperationId(), + provenance.digest(), + membershipVersion, + membershipAuthorityGeneration)); + } + + private static void requireCanonicalTerminalShape( + String status, + String outcome, + Long membershipId, + Long membershipVersion, + Long membershipAuthorityGeneration) { + if ("COMMITTED".equals(status)) { + if (!("JOINED".equals(outcome) || "ALREADY_ACTIVE".equals(outcome)) + || membershipId == null + || membershipId <= 0L + || membershipVersion == null + || membershipVersion <= 0L + || membershipAuthorityGeneration == null + || membershipAuthorityGeneration <= 0L) { + throw new IllegalArgumentException("Canonical JOIN committed fields are invalid"); + } + return; + } + if ("FAILED".equals(status)) { + if (!("TENANT_BILLING_BLOCKED".equals(outcome) + || "PUBLIC_PRODUCTION_ADMISSION_DENIED".equals(outcome) + || "MEMBERSHIP_RECONCILIATION_REQUIRED".equals(outcome)) + || membershipId != null + || membershipVersion != null + || membershipAuthorityGeneration != null) { + throw new IllegalArgumentException("Canonical JOIN failed fields are invalid"); + } + return; + } + throw new IllegalArgumentException("Canonical JOIN terminal status is invalid"); + } + + private static boolean canonicalTerminalMatches( + CanonicalJoinOperationEvidence operation, + String status, + String outcome, + Long membershipId, + Long membershipVersion, + Long membershipAuthorityGeneration) { + return status.equals(operation.status()) + && outcome.equals(operation.outcome()) + && Objects.equals(membershipId, operation.membershipId()) + && Objects.equals(membershipVersion, operation.membershipVersion()) + && Objects.equals(membershipAuthorityGeneration, operation.membershipAuthorityGeneration()); + } + + private static boolean isScopeUnexpired(String timestamp, Instant now) { + var matcher = UTC_RFC3339.matcher(timestamp); + if (!matcher.matches()) { + return false; + } + final long scopeEpochSecond; + try { + scopeEpochSecond = LocalDateTime.parse(matcher.group(1)).toEpochSecond(ZoneOffset.UTC); + } catch (RuntimeException invalidTimestamp) { + return false; + } + if (scopeEpochSecond != now.getEpochSecond()) { + return scopeEpochSecond > now.getEpochSecond(); + } + + String exactFraction = matcher.group(2) == null ? "" : matcher.group(2); + String scopeNanos = (exactFraction + "000000000").substring(0, 9); + String nowNanos = ("000000000" + now.getNano()); + nowNanos = nowNanos.substring(nowNanos.length() - 9); + int nanosComparison = scopeNanos.compareTo(nowNanos); + if (nanosComparison != 0) { + return nanosComparison > 0; + } + return exactFraction.length() > 9 + && exactFraction.substring(9).chars().anyMatch(character -> character != '0'); + } + + /** Bounded, nonauthorizing reconciliation metadata that deliberately omits scope evidence. */ + public record CanonicalJoinReconciliationCandidate( + String requestId, + long privateAccountId, + int reconciliationAttemptCount, + Instant nextReconciliationAttemptAt) { + public CanonicalJoinReconciliationCandidate { + if (requestId == null + || requestId.isBlank() + || requestId.codePointCount(0, requestId.length()) > 128 + || privateAccountId <= 0L + || reconciliationAttemptCount < 0 + || nextReconciliationAttemptAt == null) { + throw new IllegalArgumentException("Canonical JOIN reconciliation candidate is incomplete"); + } + } + } + /** Hash-only V2 operation plus exact owner scope evidence; it exposes no bearer. */ public record CanonicalJoinOperationEvidence( String requestId, @@ -712,6 +1131,14 @@ public record CanonicalJoinOperationEvidence( String lastAttemptFailureCode, boolean callerBoundAuthorityInvalidated, String status, + String outcome, + Long membershipId, + Long membershipVersion, + Long membershipAuthorityGeneration, + int reconciliationAttemptCount, + Instant lastReconciliationAttemptAt, + String lastReconciliationAttemptReason, + Instant nextReconciliationAttemptAt, CanonicalConnectScopeEvidence scopeEvidence) { public CanonicalJoinOperationEvidence { if (requestId == null @@ -727,7 +1154,9 @@ public record CanonicalJoinOperationEvidence( || intentDigest == null || entitlementAuthorityAvailability == null || lastAttemptAuthorityAvailability == null - || !"PENDING".equals(status) + || status == null + || reconciliationAttemptCount < 0 + || nextReconciliationAttemptAt == null || callerBoundAuthorityInvalidated || scopeEvidence == null || scopeEvidence.privateAccountId() != privateAccountId @@ -738,14 +1167,25 @@ public record CanonicalJoinOperationEvidence( requireSha256(scopeTokenHash, "Canonical JOIN scope token hash"); requireSha256(connectScopeDigest, "Canonical JOIN scope digest"); requireSha256(intentDigest, "Canonical JOIN intent digest"); + if (reconciliationAttemptCount == 0 + ? lastReconciliationAttemptAt != null || lastReconciliationAttemptReason != null + : lastReconciliationAttemptAt == null + || lastReconciliationAttemptReason == null + || lastReconciliationAttemptReason.isBlank()) { + throw new IllegalArgumentException( + "Canonical JOIN reconciliation diagnostics are incomplete"); + } if ("AVAILABLE".equals(entitlementAuthorityAvailability)) { if (allowPublicJoin == null || entitlementVersion == null || entitlementVersion <= 0L || !Integer.valueOf(2).equals(requestDigestVersion) || requestDigest == null - || lastAttemptFailureCode != null - || !"AVAILABLE".equals(lastAttemptAuthorityAvailability)) { + || !("AVAILABLE".equals(lastAttemptAuthorityAvailability) + && lastAttemptFailureCode == null + || "UNAVAILABLE".equals(lastAttemptAuthorityAvailability) + && lastAttemptFailureCode != null + && !lastAttemptFailureCode.isBlank())) { throw new IllegalArgumentException( "Canonical JOIN available policy evidence is incomplete"); } @@ -767,6 +1207,36 @@ public record CanonicalJoinOperationEvidence( } else { throw new IllegalArgumentException("Canonical JOIN policy evidence is contradictory"); } + if ("PENDING".equals(status)) { + if (outcome != null + || membershipId != null + || membershipVersion != null + || membershipAuthorityGeneration != null) { + throw new IllegalArgumentException("Canonical JOIN pending evidence has terminal fields"); + } + } else { + try { + requireCanonicalTerminalShape( + status, outcome, membershipId, membershipVersion, membershipAuthorityGeneration); + } catch (IllegalArgumentException invalidTerminal) { + throw new IllegalArgumentException( + "Canonical JOIN terminal evidence is incomplete", invalidTerminal); + } + if (!"AVAILABLE".equals(entitlementAuthorityAvailability) + || ("COMMITTED".equals(status) && !Boolean.TRUE.equals(allowPublicJoin)) + || ("FAILED".equals(status) + && (!"AVAILABLE".equals(lastAttemptAuthorityAvailability) + || lastAttemptFailureCode != null)) + || ("FAILED".equals(status) + && "PUBLIC_PRODUCTION_ADMISSION_DENIED".equals(outcome) + && !Boolean.FALSE.equals(allowPublicJoin)) + || ("FAILED".equals(status) + && "MEMBERSHIP_RECONCILIATION_REQUIRED".equals(outcome) + && !Boolean.TRUE.equals(allowPublicJoin))) { + throw new IllegalArgumentException( + "Canonical JOIN terminal result contradicts its policy evidence"); + } + } } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalJoinReconciliationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalJoinReconciliationService.java new file mode 100644 index 0000000000..f9b487e5cf --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalJoinReconciliationService.java @@ -0,0 +1,459 @@ +package net.firedevops.firemud.accountservice.service; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.charset.StandardCharsets; +import java.time.DateTimeException; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; +import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; +import net.firedevops.firemud.accountservice.dto.CanonicalMembershipTransitionReceipt; +import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Checkpoint; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinOperationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinReconciliationCandidate; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; +import net.firedevops.firemud.accountservice.repository.AccountMembershipTransitionReceiptRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Readback-only recovery candidate for canonical UUID JOIN operations; no runtime path invokes it. + */ +@Service +@SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = "Invalid bounded retry settings must fail startup.") +public class AccountCanonicalJoinReconciliationService { + private static final Logger logger = + LoggerFactory.getLogger(AccountCanonicalJoinReconciliationService.class); + private static final int MAX_BATCH_SIZE = 100; + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + + private final AccountJoinOperationRepository joinOperationRepository; + private final AccountTenantMembershipRepository membershipRepository; + private final AccountTenantMembershipRoleSnapshotRepository roleSnapshotRepository; + private final AccountMembershipTransitionReceiptRepository transitionReceiptRepository; + private final AccountAuditOutboxRepository auditOutboxRepository; + private final AccountMembershipAuthorityEventProducer membershipAuthorityEventProducer; + private final TransactionTemplate pageTransactionTemplate; + private final TransactionTemplate reconciliationTransactionTemplate; + private final int batchSize; + private final int maxAttempts; + private final long backoffMillis; + + public AccountCanonicalJoinReconciliationService( + AccountJoinOperationRepository joinOperationRepository, + AccountTenantMembershipRepository membershipRepository, + AccountTenantMembershipRoleSnapshotRepository roleSnapshotRepository, + AccountMembershipTransitionReceiptRepository transitionReceiptRepository, + AccountAuditOutboxRepository auditOutboxRepository, + AccountMembershipAuthorityEventProducer membershipAuthorityEventProducer, + PlatformTransactionManager transactionManager, + @Value("${firemud.account.join-reconciliation.batch-size:50}") int batchSize, + @Value("${firemud.account.join-reconciliation.max-attempts:12}") int maxAttempts, + @Value("${firemud.account.join-reconciliation.backoff-ms:30000}") long backoffMillis) { + if (batchSize < 1 || batchSize > MAX_BATCH_SIZE) { + throw new IllegalArgumentException( + "firemud.account.join-reconciliation.batch-size must be between 1 and 100"); + } + if (maxAttempts < 1) { + throw new IllegalArgumentException( + "firemud.account.join-reconciliation.max-attempts must be positive"); + } + if (backoffMillis < 1) { + throw new IllegalArgumentException( + "firemud.account.join-reconciliation.backoff-ms must be positive"); + } + this.joinOperationRepository = + Objects.requireNonNull(joinOperationRepository, "JOIN operation repository is required"); + this.membershipRepository = + Objects.requireNonNull(membershipRepository, "Membership repository is required"); + this.roleSnapshotRepository = + Objects.requireNonNull(roleSnapshotRepository, "Role snapshot repository is required"); + this.transitionReceiptRepository = + Objects.requireNonNull( + transitionReceiptRepository, "Transition receipt repository is required"); + this.auditOutboxRepository = + Objects.requireNonNull(auditOutboxRepository, "Audit outbox repository is required"); + this.membershipAuthorityEventProducer = + Objects.requireNonNull( + membershipAuthorityEventProducer, "Membership authority event producer is required"); + this.batchSize = batchSize; + this.maxAttempts = maxAttempts; + this.backoffMillis = backoffMillis; + this.pageTransactionTemplate = new TransactionTemplate(transactionManager); + this.pageTransactionTemplate.setPropagationBehavior( + TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.pageTransactionTemplate.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + this.reconciliationTransactionTemplate = new TransactionTemplate(transactionManager); + this.reconciliationTransactionTemplate.setPropagationBehavior( + TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.reconciliationTransactionTemplate.setIsolationLevel( + TransactionDefinition.ISOLATION_READ_COMMITTED); + } + + /** Processes one bounded due page; scope expiry and missing evidence never create an outcome. */ + public void reconcileDueOperations(Instant now) { + Objects.requireNonNull(now, "Canonical JOIN reconciliation time is required"); + final List dueOperations; + try { + dueOperations = + pageTransactionTemplate.execute( + status -> + joinOperationRepository.findDueCanonicalPendingReconciliation( + now, batchSize, maxAttempts)); + } catch (RuntimeException exception) { + logger.warn( + "Canonical JOIN reconciliation could not list due operations ({})", + exception.getClass().getSimpleName()); + return; + } + if (dueOperations == null) { + return; + } + for (CanonicalJoinReconciliationCandidate candidate : dueOperations) { + reconcileOne(candidate, now); + } + } + + private void reconcileOne(CanonicalJoinReconciliationCandidate candidate, Instant now) { + try { + reconciliationTransactionTemplate.execute(status -> reconcileLocked(candidate, now)); + } catch (RuntimeException exception) { + logger.warn( + "Canonical JOIN reconciliation readback failed for request {} ({})", + candidate.requestId(), + exception.getClass().getSimpleName()); + recordUnavailableAttempt(candidate, now); + } + } + + private ReconciliationResult reconcileLocked( + CanonicalJoinReconciliationCandidate candidate, Instant now) { + // All dependent evidence and any operation outcome are read or written after this Account + // fence. + joinOperationRepository.lockAccount(candidate.privateAccountId()); + CanonicalJoinOperationEvidence operation = + joinOperationRepository + .findCanonicalEvidenceByRequestId(candidate.requestId()) + .orElse(null); + if (!isDueCandidate(operation, candidate, now)) { + return ReconciliationResult.SKIPPED; + } + + String unresolvedReason = validatePendingOperation(operation); + var scope = operation.scopeEvidence(); + if (unresolvedReason == null) { + try { + var membership = + membershipRepository + .findCanonicalMembershipForUpdate(scope.accountUuid(), scope.tenantUuid()) + .orElse(null); + if (membership == null) { + unresolvedReason = "CANONICAL_MEMBERSHIP_ABSENT"; + } else if (!membershipMatches(operation, membership)) { + unresolvedReason = "CANONICAL_MEMBERSHIP_MISMATCH"; + } else { + RoleSnapshot roles = + roleSnapshotRepository + .findForCanonicalUpdate( + scope.accountUuid(), + scope.tenantUuid(), + scope.tenantProvenance(), + membership.getId(), + membership.getMembershipVersion()) + .orElse(null); + if (roles == null) { + unresolvedReason = "CANONICAL_ROLE_SNAPSHOT_ABSENT"; + } else if (!roleSnapshotMatches(operation, membership.getId(), roles)) { + unresolvedReason = "CANONICAL_ROLE_SNAPSHOT_MISMATCH"; + } else { + unresolvedReason = + validateReceipt(operation, membership.getId(), roles, scope.tenantProvenance()); + if (unresolvedReason == null) { + unresolvedReason = validateAuditEnvelope(operation); + } + if (unresolvedReason == null) { + try { + Checkpoint checkpoint = + membershipAuthorityEventProducer.requireCanonicalFirstJoinEvent(operation); + if (checkpoint == null + || checkpoint.outboxSequence() != 1L + || checkpoint.sourceEventId() == null + || checkpoint.sourceEventDigest() == null) { + unresolvedReason = "CANONICAL_AUTHORITY_EVENT_MISMATCH"; + } + } catch (RuntimeException exception) { + unresolvedReason = "CANONICAL_AUTHORITY_EVENT_UNAVAILABLE"; + } + } + if (unresolvedReason == null) { + joinOperationRepository.finishCanonicalOperation( + operation.requestId(), + "COMMITTED", + "JOINED", + membership.getId(), + membership.getMembershipVersion(), + membership.getMembershipAuthorityGeneration()); + return ReconciliationResult.COMMITTED; + } + } + } + } catch (RuntimeException exception) { + unresolvedReason = "CANONICAL_MEMBERSHIP_READBACK_UNAVAILABLE"; + } + } + + return recordUnresolvedAttempt(operation, now, unresolvedReason); + } + + private boolean isDueCandidate( + CanonicalJoinOperationEvidence operation, + CanonicalJoinReconciliationCandidate candidate, + Instant now) { + return operation != null + && candidate != null + && operation.privateAccountId() == candidate.privateAccountId() + && operation.requestId().equals(candidate.requestId()) + && "PENDING".equals(operation.status()) + && operation.reconciliationAttemptCount() == candidate.reconciliationAttemptCount() + && operation.nextReconciliationAttemptAt().equals(candidate.nextReconciliationAttemptAt()) + && operation.reconciliationAttemptCount() < maxAttempts + && operation.nextReconciliationAttemptAt() != null + && !operation.nextReconciliationAttemptAt().isAfter(now); + } + + private String validatePendingOperation(CanonicalJoinOperationEvidence operation) { + var scope = operation.scopeEvidence(); + if (operation.operationRepresentationVersion() != 2 + || operation.scopeDigestVersion() != 2 + || operation.intentDigestVersion() != 2 + || operation.requestDigestVersion() == null + || operation.requestDigestVersion() != 2 + || !isSha256(operation.intentDigest()) + || !isSha256(operation.requestDigest()) + || !isSha256(operation.scopeTokenHash()) + || !isSha256(operation.connectScopeDigest()) + || !"AVAILABLE".equals(operation.entitlementAuthorityAvailability()) + || !Boolean.TRUE.equals(operation.allowPublicJoin()) + || operation.entitlementVersion() == null + || operation.entitlementVersion() <= 0L + || !("AVAILABLE".equals(operation.lastAttemptAuthorityAvailability()) + && operation.lastAttemptFailureCode() == null + || "UNAVAILABLE".equals(operation.lastAttemptAuthorityAvailability()) + && operation.lastAttemptFailureCode() != null + && !operation.lastAttemptFailureCode().isBlank()) + || operation.callerBoundAuthorityInvalidated() + || !"PENDING".equals(operation.status()) + || operation.outcome() != null + || operation.membershipId() != null + || operation.membershipVersion() != null + || operation.membershipAuthorityGeneration() != null + || !"PUBLIC_PRODUCTION".equals(scope.targetClass()) + || scope.privateAccountId() != operation.privateAccountId() + || !operation.scopeTokenHash().equals(scope.scopeTokenHash()) + || !operation.connectScopeDigest().equals(scope.scopeDigest())) { + return "CANONICAL_JOIN_OPERATION_POLICY_UNPROVEN"; + } + return null; + } + + private static boolean membershipMatches( + CanonicalJoinOperationEvidence operation, + net.firedevops.firemud.accountservice.entity.AccountTenantMembership membership) { + var scope = operation.scopeEvidence(); + VerifiedTenantProvenance provenance = scope.tenantProvenance(); + return membership.getId() != null + && membership.getId() > 0L + && membership.getAccount() != null + && membership.getAccount().getId() != null + && membership.getAccount().getId() == operation.privateAccountId() + && scope.accountUuid().equals(membership.getAccount().getAccountUuid()) + && scope.tenantUuid().equals(membership.getTenantUuid()) + && Objects.equals(provenance.legacyTenantId(), membership.getTenantId()) + && provenance.kind().name().equals(membership.getTenantProvenanceKind()) + && provenance.sourceOperationId().equals(membership.getTenantSourceOperationId()) + && provenance.digest().equals(membership.getTenantProvenanceDigest()) + && membership.isGameplayAdmissionAllowed() + && "ACTIVE".equals(membership.getLifecycleState()) + && "EXPLICIT_JOIN".equals(membership.getAuthorityProvenance()) + && membership.getMembershipVersion() == 2L + && membership.getMembershipAuthorityGeneration() == 1L; + } + + private static boolean roleSnapshotMatches( + CanonicalJoinOperationEvidence operation, long membershipId, RoleSnapshot roles) { + var scope = operation.scopeEvidence(); + return roles.accountId() == operation.privateAccountId() + && Objects.equals(roles.tenantId(), scope.tenantProvenance().legacyTenantId()) + && roles.membershipId() == membershipId + && roles.snapshotVersion() == 2L + && scope.accountUuid().equals(roles.accountUuid()) + && scope.tenantUuid().equals(roles.tenantUuid()) + && scope.tenantProvenance().equals(roles.tenantProvenance()) + && List.of("player").equals(roles.roles()); + } + + private String validateReceipt( + CanonicalJoinOperationEvidence operation, + long membershipId, + RoleSnapshot roles, + VerifiedTenantProvenance provenance) { + final CanonicalMembershipTransitionReceipt receipt; + try { + receipt = + transitionReceiptRepository.findCanonicalByRequestId(operation.requestId()).orElse(null); + } catch (RuntimeException exception) { + return "CANONICAL_TRANSITION_RECEIPT_UNAVAILABLE"; + } + if (receipt == null) { + return "CANONICAL_TRANSITION_RECEIPT_ABSENT"; + } + var scope = operation.scopeEvidence(); + boolean exact = + receipt.receiptSequence() == 1L + && receipt.accountId().equals(scope.accountUuid()) + && receipt.tenantId().equals(scope.tenantUuid()) + && receipt.requestId().equals(operation.requestId()) + && "MEMBERSHIP_JOINED".equals(receipt.transitionType()) + && "ACTIVE".equals(receipt.membershipLifecycleState()) + && receipt.gameplayAdmissionAllowed() + && Map.of(scope.tenantUuid().toString(), "2").equals(receipt.membershipVersion()) + && receipt.membershipAuthorityGeneration() == 1L + && "EXPLICIT_JOIN".equals(receipt.authorityProvenance()) + && provenance.kind().name().equals(receipt.tenantProvenanceKind()) + && provenance.sourceOperationId().equals(receipt.tenantSourceOperationId()) + && provenance.digest().equals(receipt.tenantProvenanceDigest()) + && receipt + .receiptId() + .equals( + net.firedevops.firemud.accountservice.dto.MembershipTransitionReceiptDigest + .receiptIdForRequestV2(operation.requestId())) + && roles.membershipId() == membershipId; + return exact ? null : "CANONICAL_TRANSITION_RECEIPT_MISMATCH"; + } + + private String validateAuditEnvelope(CanonicalJoinOperationEvidence operation) { + var scope = operation.scopeEvidence(); + final AccountAuditEnvelope envelope; + try { + envelope = + auditOutboxRepository + .findCanonicalJoinEnvelopeForUpdate( + joinAuditEventId(operation.requestId()), scope.tenantUuid()) + .orElse(null); + } catch (RuntimeException exception) { + return "CANONICAL_JOIN_AUDIT_ENVELOPE_MISMATCH"; + } + if (envelope == null) { + return "CANONICAL_JOIN_AUDIT_ENVELOPE_ABSENT"; + } + if (envelope.payload() == null + || envelope.schemaVersion() != 1 + || envelope.payloadDigestVersion() != 1 + || !isSha256(envelope.payloadDigest()) + || !envelope.payloadDigest().equals(AccountAuditDigest.ofPayload(envelope.payload()))) { + return "CANONICAL_JOIN_AUDIT_ENVELOPE_UNCLEAR"; + } + String expectedPayload = + AccountAuditOutboxRepository.canonicalJoinPayload( + scope.accountUuid(), + scope.tenantUuid(), + scope.worldSlug(), + scope.realmSlug(), + Map.of(scope.tenantUuid().toString(), "2"), + operation.requestId()); + return expectedPayload.equals(envelope.payload()) + && joinAuditEventId(operation.requestId()).equals(envelope.auditEventId()) + ? null + : "CANONICAL_JOIN_AUDIT_ENVELOPE_MISMATCH"; + } + + private static UUID joinAuditEventId(String requestId) { + return UUID.nameUUIDFromBytes( + ("account-join-audit/v1:" + requestId).getBytes(StandardCharsets.UTF_8)); + } + + private ReconciliationResult recordUnresolvedAttempt( + CanonicalJoinOperationEvidence operation, Instant attemptedAt, String reason) { + boolean recorded = + joinOperationRepository.recordCanonicalReconciliationAttempt( + operation.requestId(), + operation.reconciliationAttemptCount(), + maxAttempts, + attemptedAt, + reason, + nextAttemptAt(attemptedAt)); + return !recorded + ? ReconciliationResult.SKIPPED + : operation.reconciliationAttemptCount() + 1 >= maxAttempts + ? ReconciliationResult.MAX_ATTEMPTS_REACHED + : ReconciliationResult.ATTEMPT_RECORDED; + } + + private void recordUnavailableAttempt( + CanonicalJoinReconciliationCandidate candidate, Instant attemptedAt) { + try { + reconciliationTransactionTemplate.execute( + status -> { + joinOperationRepository.lockAccount(candidate.privateAccountId()); + if (candidate.reconciliationAttemptCount() >= maxAttempts + || candidate.nextReconciliationAttemptAt().isAfter(attemptedAt)) { + return ReconciliationResult.SKIPPED; + } + boolean recorded = + joinOperationRepository.recordCanonicalReconciliationAttempt( + candidate.requestId(), + candidate.reconciliationAttemptCount(), + maxAttempts, + attemptedAt, + "CANONICAL_JOIN_READBACK_UNAVAILABLE", + nextAttemptAt(attemptedAt)); + return !recorded + ? ReconciliationResult.SKIPPED + : candidate.reconciliationAttemptCount() + 1 >= maxAttempts + ? ReconciliationResult.MAX_ATTEMPTS_REACHED + : ReconciliationResult.ATTEMPT_RECORDED; + }); + } catch (RuntimeException exception) { + logger.warn( + "Canonical JOIN reconciliation could not persist a retry diagnostic for request {} ({})", + candidate.requestId(), + exception.getClass().getSimpleName()); + } + } + + private Instant nextAttemptAt(Instant attemptedAt) { + try { + return attemptedAt.plusMillis(backoffMillis); + } catch (DateTimeException | ArithmeticException exception) { + throw new IllegalStateException( + "Canonical JOIN reconciliation backoff is outside timestamp range", exception); + } + } + + private static boolean isSha256(String value) { + return value != null && SHA256.matcher(value).matches(); + } + + private enum ReconciliationResult { + SKIPPED, + COMMITTED, + ATTEMPT_RECORDED, + MAX_ATTEMPTS_REACHED + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java index 4fecd2d474..167224fca9 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java @@ -30,6 +30,7 @@ import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.EventEvidence; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinOperationEvidence; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.JoinOperation; import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; @@ -1618,6 +1619,88 @@ public Checkpoint requireCommittedJoinEvent(JoinOperation operation) { return head; } + /** + * Reads the exact event, checkpoint, and pair tuple for a pending canonical first JOIN. + * + *

The operation and UUID scope are immutable Account readback evidence. This method does not + * reconstruct the original bearer-bound digest, publish an event, or infer current authority from + * a constructed DTO. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Checkpoint requireCanonicalFirstJoinEvent(CanonicalJoinOperationEvidence operation) { + requireWritableOwnerTransaction(); + if (operation == null || operation.requestId() == null || operation.requestId().isBlank()) { + throw new IllegalStateException("Canonical JOIN operation readback is required"); + } + UUID accountUuid = operation.scopeEvidence().accountUuid(); + UUID tenantUuid = operation.scopeEvidence().tenantUuid(); + requireCanonicalUuidInput(accountUuid, "Account UUID"); + requireCanonicalUuidInput(tenantUuid, "tenant UUID"); + + Identity identity = resolveCanonicalIdentity(accountUuid, tenantUuid); + CanonicalJoinOperationEvidence persistedOperation = + joinOperationRepository + .findCanonicalEvidenceByRequestId(operation.requestId()) + .orElseThrow( + () -> + new IllegalStateException( + "Canonical JOIN operation journal evidence is absent")); + if (!persistedOperation.equals(operation)) { + throw new IllegalStateException( + "Canonical JOIN operation differs from its exact persisted journal readback"); + } + requireCanonicalFirstJoinOperationReadback(identity, persistedOperation); + + String streamKey = membershipStreamKey(identity); + Event event = + authorityOutboxRepository + .findEvent(streamKey, operation.requestId()) + .orElseThrow( + () -> new IllegalStateException("Canonical JOIN has no matching V33 event")); + MembershipEvent verified = verifyStoredEvent(event, identity, operation.requestId()); + if (event.outboxSequence() != 1L + || !Map.of(tenantUuid.toString(), "2").equals(verified.membershipVersion()) + || !"1".equals(verified.membershipAuthorityGeneration()) + || !verified.gameplayAdmissionAllowed() + || !"ACTIVE".equals(verified.membershipLifecycleState()) + || !List.of("player").equals(verified.roles()) + || verified.callerBoundAuthorityInvalidated()) { + throw new IllegalStateException( + "Canonical JOIN operation differs from its exact first-membership V33 event"); + } + + Checkpoint checkpoint = + authorityOutboxRepository + .readCheckpoint(streamKey) + .orElseThrow( + () -> new IllegalStateException("Canonical JOIN authority checkpoint is absent")); + if (checkpoint.outboxSequence() != 1L + || checkpoint.outboxSequence() != event.outboxSequence() + || !Objects.equals(checkpoint.sourceEventId(), event.eventId()) + || !Objects.equals(checkpoint.sourceEventDigest(), event.eventDigest())) { + throw new IllegalStateException( + "Canonical JOIN checkpoint differs from its exact first-membership event"); + } + + PairAuthority pair = + pairAuthorityRepository + .readForUpdate(accountUuid, tenantUuid) + .orElseThrow( + () -> new IllegalStateException("Canonical JOIN pair authority is absent")); + if (!identity.provenance().equals(pair.provenance()) + || !pair.membershipExists() + || pair.membershipVersion() != 2L + || pair.membershipAuthorityGeneration() != 1L + || pair.lastEventSequence() != 1L + || !Objects.equals(pair.lastEventId(), event.eventId()) + || !Objects.equals(pair.lastEventDigest(), event.eventDigest()) + || pair.lastTransitionInvalidated()) { + throw new IllegalStateException( + "Canonical JOIN pair authority differs from its exact first-membership event"); + } + return checkpoint; + } + private Checkpoint appendAndReadBack( Identity identity, String requestId, @@ -2508,6 +2591,41 @@ private void requireCanonicalFirstJoinOperation( } } + private void requireCanonicalFirstJoinOperationReadback( + Identity identity, CanonicalJoinOperationEvidence operation) { + var scope = operation.scopeEvidence(); + if (operation.operationRepresentationVersion() != 2 + || operation.scopeDigestVersion() != 2 + || operation.intentDigestVersion() != 2 + || !"PENDING".equals(operation.status()) + || operation.outcome() != null + || operation.membershipId() != null + || operation.membershipVersion() != null + || operation.membershipAuthorityGeneration() != null + || !"AVAILABLE".equals(operation.entitlementAuthorityAvailability()) + || !Boolean.TRUE.equals(operation.allowPublicJoin()) + || operation.entitlementVersion() == null + || operation.entitlementVersion() <= 0L + || !Integer.valueOf(2).equals(operation.requestDigestVersion()) + || operation.requestDigest() == null + || !("AVAILABLE".equals(operation.lastAttemptAuthorityAvailability()) + && operation.lastAttemptFailureCode() == null + || "UNAVAILABLE".equals(operation.lastAttemptAuthorityAvailability()) + && operation.lastAttemptFailureCode() != null + && !operation.lastAttemptFailureCode().isBlank()) + || operation.callerBoundAuthorityInvalidated() + || operation.privateAccountId() != identity.accountId() + || !"PUBLIC_PRODUCTION".equals(scope.targetClass()) + || !identity.accountUuid().equals(scope.accountUuid()) + || !identity.tenantUuid().equals(scope.tenantUuid()) + || !identity.provenance().equals(scope.tenantProvenance()) + || !operation.scopeTokenHash().equals(scope.scopeTokenHash()) + || !operation.connectScopeDigest().equals(scope.scopeDigest())) { + throw new IllegalStateException( + "Canonical JOIN operation or immutable source policy is not exact positive evidence"); + } + } + private void requireCanonicalFirstJoinRoles( Identity identity, AccountTenantMembership membership, RoleSnapshot roles) { List exactRoles; diff --git a/services/account-service/src/main/resources/db/migration/V50__canonical_uuid_join_terminal_outcomes.sql b/services/account-service/src/main/resources/db/migration/V50__canonical_uuid_join_terminal_outcomes.sql new file mode 100644 index 0000000000..73b53c832c --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V50__canonical_uuid_join_terminal_outcomes.sql @@ -0,0 +1,318 @@ +-- V2 canonical JOIN rows may become terminal only after the owner proves a deterministic outcome. +-- Retained V1 rows and their historical transition behavior remain untouched. +ALTER TABLE account_join_operations + DROP CONSTRAINT account_join_operation_representation_check; + +ALTER TABLE account_join_operations + ADD CONSTRAINT account_join_operation_representation_check + CHECK ( + (operation_representation_version = 1 + AND scope_digest_version = 1 + AND target_class IS NULL + AND account_uuid IS NULL + AND tenant_uuid IS NULL + AND tenant_slug IS NULL + AND playable_state_namespace_uuid IS NULL + AND game_instance_uuid IS NULL) + OR + (operation_representation_version = 2 + AND scope_digest_version = 2 + AND request_id IS NOT NULL + AND account_id IS NOT NULL + AND verified_caller_binding IS NOT NULL + AND scope_token_hash IS NOT NULL + AND connect_scope_digest IS NOT NULL + AND realm_id IS NOT NULL + AND world_slug IS NOT NULL + AND realm_slug IS NOT NULL + AND playable_state_scope IS NOT NULL + AND catalog_revision IS NOT NULL + AND pointer_version IS NOT NULL + AND intent_digest_version = 2 + AND intent_digest IS NOT NULL + AND status IS NOT NULL + AND entitlement_authority_availability IS NOT NULL + AND last_attempt_authority_availability IS NOT NULL + AND caller_bound_authority_invalidated IS FALSE + AND btrim(request_id) <> '' + AND verified_caller_binding <> '' + AND scope_token_hash ~ '^sha256:[0-9a-f]{64}$' + AND target_class IS NOT NULL + AND target_class = 'PUBLIC_PRODUCTION' + AND tenant_id IS NULL + AND game_instance_id IS NULL + AND playable_state_namespace_id IS NULL + AND account_uuid IS NOT NULL + AND account_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND tenant_uuid IS NOT NULL + AND tenant_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND tenant_slug IS NOT NULL AND tenant_slug <> '' + AND realm_id IS NOT NULL + AND realm_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND world_slug IS NOT NULL AND world_slug <> '' + AND realm_slug IS NOT NULL AND realm_slug <> '' + AND playable_state_namespace_uuid IS NOT NULL + AND playable_state_namespace_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND playable_state_scope IS NOT NULL + AND playable_state_scope IN ('SHARED', 'ISOLATED') + AND game_instance_uuid IS NOT NULL + AND game_instance_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND connect_scope_digest ~ '^sha256:[0-9a-f]{64}$' + AND intent_digest IS NOT NULL + AND intent_digest ~ '^sha256:[0-9a-f]{64}$' + AND ( + (status = 'PENDING' + AND outcome IS NULL + AND membership_id IS NULL + AND outcome_membership_version IS NULL + AND outcome_membership_authority_generation IS NULL) + OR + (status = 'COMMITTED' + AND outcome IS NOT NULL + AND outcome IN ('JOINED', 'ALREADY_ACTIVE') + AND membership_id IS NOT NULL + AND outcome_membership_version IS NOT NULL + AND outcome_membership_version > 0 + AND outcome_membership_authority_generation IS NOT NULL + AND outcome_membership_authority_generation > 0 + AND entitlement_authority_availability = 'AVAILABLE' + AND ((last_attempt_authority_availability = 'AVAILABLE' + AND last_attempt_failure_code IS NULL) + OR (last_attempt_authority_availability = 'UNAVAILABLE' + AND last_attempt_failure_code IS NOT NULL + AND btrim(last_attempt_failure_code) <> '')) + AND allow_public_join IS TRUE + AND request_digest_version = 2 + AND request_digest IS NOT NULL + AND request_digest ~ '^sha256:[0-9a-f]{64}$') + OR + (status = 'FAILED' + AND outcome IS NOT NULL + AND outcome IN ( + 'TENANT_BILLING_BLOCKED', + 'PUBLIC_PRODUCTION_ADMISSION_DENIED', + 'MEMBERSHIP_RECONCILIATION_REQUIRED' + ) + AND membership_id IS NULL + AND outcome_membership_version IS NULL + AND outcome_membership_authority_generation IS NULL + AND entitlement_authority_availability = 'AVAILABLE' + AND last_attempt_authority_availability = 'AVAILABLE' + AND last_attempt_failure_code IS NULL + AND request_digest_version = 2 + AND request_digest IS NOT NULL + AND request_digest ~ '^sha256:[0-9a-f]{64}$' + AND (outcome <> 'PUBLIC_PRODUCTION_ADMISSION_DENIED' + OR allow_public_join IS FALSE) + AND (outcome <> 'MEMBERSHIP_RECONCILIATION_REQUIRED' + OR allow_public_join IS TRUE)) + )) + ); + +-- Preserve V47's shared request fence and source identity checks while permitting bounded +-- diagnostics and a single contract-shaped transition from PENDING to a terminal V2 result. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION guard_account_join_operation_identity() RETURNS trigger AS $$ +DECLARE + scope_source_matches BOOLEAN := FALSE; + reconciliation_changed BOOLEAN := FALSE; +BEGIN + IF TG_OP = 'DELETE' THEN + IF OLD.operation_representation_version = 2 THEN + RAISE EXCEPTION 'Canonical JOIN operation evidence cannot be deleted' + USING ERRCODE = 'check_violation'; + END IF; + RETURN OLD; + END IF; + + IF TG_OP = 'INSERT' THEN + IF NEW.operation_representation_version = 1 THEN + RETURN NEW; + END IF; + + IF NEW.operation_representation_version IS DISTINCT FROM 2 + OR NEW.scope_digest_version IS DISTINCT FROM 2 + OR NEW.intent_digest_version IS DISTINCT FROM 2 + OR NEW.status IS DISTINCT FROM 'PENDING' + OR NEW.outcome IS NOT NULL + OR NEW.membership_id IS NOT NULL + OR NEW.outcome_membership_version IS NOT NULL + OR NEW.outcome_membership_authority_generation IS NOT NULL + OR NEW.caller_bound_authority_invalidated IS DISTINCT FROM FALSE + OR NEW.entitlement_authority_availability IS DISTINCT FROM 'NOT_EVALUATED' + OR NEW.entitlement_version IS NOT NULL + OR NEW.allow_public_join IS NOT NULL + OR NEW.request_digest_version IS NOT NULL + OR NEW.request_digest IS NOT NULL + OR NEW.last_attempt_authority_availability IS DISTINCT FROM 'NOT_EVALUATED' + OR NEW.last_attempt_failure_code IS NOT NULL + OR NEW.reconciliation_attempt_count IS DISTINCT FROM 0 + OR NEW.last_reconciliation_attempt_at IS NOT NULL + OR NEW.last_reconciliation_attempt_reason IS NOT NULL THEN + RAISE EXCEPTION 'Canonical JOIN operation must start as an exact pending intent' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT EXISTS ( + SELECT 1 + FROM account_connect_scope_records scope_row + WHERE scope_row.scope_token_hash = NEW.scope_token_hash + AND scope_row.scope_digest_version = 2 + AND scope_row.snapshot_digest = NEW.connect_scope_digest + AND scope_row.account_id = NEW.account_id + AND scope_row.account_uuid = NEW.account_uuid + AND scope_row.target_class = NEW.target_class + AND scope_row.tenant_id IS NULL + AND scope_row.tenant_uuid = NEW.tenant_uuid + AND scope_row.tenant_slug = NEW.tenant_slug + AND scope_row.realm_id = NEW.realm_id + AND scope_row.world_slug = NEW.world_slug + AND scope_row.realm_slug = NEW.realm_slug + AND scope_row.playable_state_namespace_id IS NULL + AND scope_row.playable_state_namespace_uuid = NEW.playable_state_namespace_uuid + AND scope_row.playable_state_scope = NEW.playable_state_scope + AND scope_row.game_instance_id IS NULL + AND scope_row.game_instance_uuid = NEW.game_instance_uuid + AND scope_row.catalog_revision = NEW.catalog_revision + AND scope_row.pointer_version = NEW.pointer_version + ) INTO scope_source_matches; + IF NOT scope_source_matches THEN + RAISE EXCEPTION 'Canonical JOIN operation has no exact persisted scope source' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF OLD.operation_representation_version = 1 THEN + IF NEW.operation_representation_version <> 1 THEN + RAISE EXCEPTION 'Retained JOIN operation evidence cannot change representation' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF OLD.operation_representation_version <> 2 + OR NEW.operation_representation_version <> 2 + OR NEW.request_id IS DISTINCT FROM OLD.request_id + OR NEW.account_id IS DISTINCT FROM OLD.account_id + OR NEW.tenant_id IS DISTINCT FROM OLD.tenant_id + OR NEW.verified_caller_binding IS DISTINCT FROM OLD.verified_caller_binding + OR NEW.scope_token_hash IS DISTINCT FROM OLD.scope_token_hash + OR NEW.connect_scope_digest IS DISTINCT FROM OLD.connect_scope_digest + OR NEW.world_slug IS DISTINCT FROM OLD.world_slug + OR NEW.realm_slug IS DISTINCT FROM OLD.realm_slug + OR NEW.realm_id IS DISTINCT FROM OLD.realm_id + OR NEW.playable_state_namespace_id IS DISTINCT FROM OLD.playable_state_namespace_id + OR NEW.playable_state_scope IS DISTINCT FROM OLD.playable_state_scope + OR NEW.game_instance_id IS DISTINCT FROM OLD.game_instance_id + OR NEW.catalog_revision IS DISTINCT FROM OLD.catalog_revision + OR NEW.pointer_version IS DISTINCT FROM OLD.pointer_version + OR NEW.intent_digest_version IS DISTINCT FROM OLD.intent_digest_version + OR NEW.intent_digest IS DISTINCT FROM OLD.intent_digest + OR NEW.scope_digest_version IS DISTINCT FROM OLD.scope_digest_version + OR NEW.target_class IS DISTINCT FROM OLD.target_class + OR NEW.account_uuid IS DISTINCT FROM OLD.account_uuid + OR NEW.tenant_uuid IS DISTINCT FROM OLD.tenant_uuid + OR NEW.tenant_slug IS DISTINCT FROM OLD.tenant_slug + OR NEW.playable_state_namespace_uuid IS DISTINCT FROM OLD.playable_state_namespace_uuid + OR NEW.game_instance_uuid IS DISTINCT FROM OLD.game_instance_uuid + OR NEW.caller_bound_authority_invalidated IS DISTINCT FROM OLD.caller_bound_authority_invalidated + OR NEW.created_at IS DISTINCT FROM OLD.created_at THEN + RAISE EXCEPTION 'Canonical JOIN operation intent evidence is immutable' + USING ERRCODE = 'check_violation'; + END IF; + + IF OLD.status <> 'PENDING' THEN + RAISE EXCEPTION 'Canonical JOIN terminal operation evidence is immutable' + USING ERRCODE = 'check_violation'; + END IF; + + reconciliation_changed := + NEW.reconciliation_attempt_count IS DISTINCT FROM OLD.reconciliation_attempt_count + OR NEW.last_reconciliation_attempt_at IS DISTINCT FROM OLD.last_reconciliation_attempt_at + OR NEW.last_reconciliation_attempt_reason IS DISTINCT FROM OLD.last_reconciliation_attempt_reason + OR NEW.next_reconciliation_attempt_at IS DISTINCT FROM OLD.next_reconciliation_attempt_at; + IF reconciliation_changed AND NOT ( + OLD.reconciliation_attempt_count < 2147483647 + AND NEW.reconciliation_attempt_count::BIGINT = OLD.reconciliation_attempt_count::BIGINT + 1 + AND NEW.last_reconciliation_attempt_at IS NOT NULL + AND NEW.last_reconciliation_attempt_reason IS NOT NULL + AND btrim(NEW.last_reconciliation_attempt_reason) <> '' + AND length(NEW.last_reconciliation_attempt_reason) <= 128 + AND NEW.next_reconciliation_attempt_at >= NEW.last_reconciliation_attempt_at + ) THEN + RAISE EXCEPTION 'Canonical JOIN reconciliation attempts must advance once without overflow' + USING ERRCODE = 'check_violation'; + END IF; + + IF OLD.request_digest IS NOT NULL THEN + IF NEW.request_digest_version IS DISTINCT FROM OLD.request_digest_version + OR NEW.request_digest IS DISTINCT FROM OLD.request_digest + OR NEW.entitlement_authority_availability IS DISTINCT FROM 'AVAILABLE' + OR NEW.entitlement_version IS DISTINCT FROM OLD.entitlement_version + OR NEW.allow_public_join IS DISTINCT FROM OLD.allow_public_join THEN + RAISE EXCEPTION 'Canonical JOIN available policy evidence is immutable' + USING ERRCODE = 'check_violation'; + END IF; + IF NOT ((NEW.last_attempt_authority_availability = 'AVAILABLE' + AND NEW.last_attempt_failure_code IS NULL) + OR (NEW.last_attempt_authority_availability = 'UNAVAILABLE' + AND NEW.last_attempt_failure_code IS NOT NULL + AND btrim(NEW.last_attempt_failure_code) <> '')) THEN + RAISE EXCEPTION 'Canonical JOIN attempt diagnostics are contradictory' + USING ERRCODE = 'check_violation'; + END IF; + ELSIF NEW.request_digest IS NOT NULL THEN + IF NEW.request_digest_version IS DISTINCT FROM 2 + OR NEW.entitlement_authority_availability IS DISTINCT FROM 'AVAILABLE' + OR NEW.entitlement_version IS NULL + OR NEW.allow_public_join IS NULL + OR NEW.last_attempt_authority_availability IS DISTINCT FROM 'AVAILABLE' + OR NEW.last_attempt_failure_code IS NOT NULL THEN + RAISE EXCEPTION 'Canonical JOIN policy binding is incomplete' + USING ERRCODE = 'check_violation'; + END IF; + ELSE + IF NEW.request_digest_version IS NOT NULL + OR NEW.entitlement_version IS NOT NULL + OR NEW.allow_public_join IS NOT NULL THEN + RAISE EXCEPTION 'Canonical JOIN unavailable attempt cannot invent policy evidence' + USING ERRCODE = 'check_violation'; + END IF; + IF NOT ( + (NEW.entitlement_authority_availability IS NOT DISTINCT FROM OLD.entitlement_authority_availability + AND NEW.last_attempt_authority_availability IS NOT DISTINCT FROM OLD.last_attempt_authority_availability + AND NEW.last_attempt_failure_code IS NOT DISTINCT FROM OLD.last_attempt_failure_code) + OR (NEW.entitlement_authority_availability = 'UNAVAILABLE' + AND NEW.last_attempt_authority_availability = 'UNAVAILABLE' + AND NEW.last_attempt_failure_code IS NOT NULL + AND btrim(NEW.last_attempt_failure_code) <> '') + ) THEN + RAISE EXCEPTION 'Canonical JOIN unavailable attempt cannot invent policy evidence' + USING ERRCODE = 'check_violation'; + END IF; + END IF; + + IF NEW.status = 'FAILED' + AND (OLD.last_attempt_authority_availability IS DISTINCT FROM 'AVAILABLE' + OR OLD.last_attempt_failure_code IS NOT NULL) THEN + RAISE EXCEPTION 'Canonical JOIN failure requires a successful available-policy attempt' + USING ERRCODE = 'check_violation'; + END IF; + + IF NEW.status <> 'PENDING' AND reconciliation_changed THEN + RAISE EXCEPTION 'Canonical JOIN terminalization cannot rewrite reconciliation history' + USING ERRCODE = 'check_violation'; + END IF; + IF NEW.status = 'PENDING' + AND (NEW.outcome IS NOT NULL + OR NEW.membership_id IS NOT NULL + OR NEW.outcome_membership_version IS NOT NULL + OR NEW.outcome_membership_authority_generation IS NOT NULL) THEN + RAISE EXCEPTION 'Canonical JOIN pending operation has terminal fields' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCanonicalJoinReconciliationIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCanonicalJoinReconciliationIntegrationTest.java new file mode 100644 index 0000000000..6b6bd21548 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCanonicalJoinReconciliationIntegrationTest.java @@ -0,0 +1,639 @@ +package integration.net.firedevops.firemud.accountservice; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.accountservice.AccountServiceApplication; +import net.firedevops.firemud.accountservice.client.EntityManagementClient; +import net.firedevops.firemud.accountservice.client.GameSessionClient; +import net.firedevops.firemud.accountservice.client.LoggingAdminClient; +import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; +import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinOperationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; +import net.firedevops.firemud.accountservice.repository.AccountMembershipTransitionReceiptRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.service.AccountCanonicalJoinReconciliationService; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.test.GatewayTestProperties; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * PostgreSQL composition proof for the explicitly unwired canonical JOIN readback component. + * + *

These fixtures call Account owner repositories directly and establish storage/recovery proof + * only. In particular, historical event/receipt/audit rows seeded beside already-expired scopes do + * not exercise or claim authenticated entitlement, caller, or public JOIN authorization. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + webEnvironment = SpringBootTest.WebEnvironment.NONE, + classes = AccountServiceApplication.class, + properties = { + GatewayTestProperties.SPRING_GRPC_SERVER_SSL_DISABLED, + GatewayTestProperties.FIREMUD_GRPC_CERT_CHAIN_PATH, + GatewayTestProperties.FIREMUD_GRPC_PRIVATE_KEY_PATH, + GatewayTestProperties.FIREMUD_GRPC_CA_CERT_PATH, + "firemud.grpc.workload-namespace=firemud-unit1b" + }) +class AccountCanonicalJoinReconciliationIntegrationTest { + private static final String TEST_NAMESPACE = "firemud-unit1b"; + private static final int MAX_ATTEMPTS = 12; + private static final DateTimeFormatter RFC3339 = DateTimeFormatter.ISO_INSTANT; + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Container + static GenericContainer redis = + new GenericContainer<>("redis:7.2-alpine").withExposedPorts(6379); + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.registerPostgresService(registry, postgres, "account_service"); + PostgresBackedServiceTestSupport.registerRedisService(registry, redis); + } + + @Autowired private DSLContext dsl; + @Autowired private PlatformTransactionManager transactionManager; + @Autowired private AccountCanonicalJoinReconciliationService reconciliationService; + @Autowired private AccountMembershipAuthorityEventProducer membershipEventProducer; + @Autowired private AccountAuthorityGenerationRepository generations; + @Autowired private AccountConnectScopeRepository connectScopes; + @Autowired private AccountJoinOperationRepository joinOperations; + @Autowired private AccountRepository accounts; + @Autowired private AccountTenantMembershipRepository memberships; + @Autowired private AccountTenantMembershipRoleSnapshotRepository roleSnapshots; + @Autowired private AccountMembershipTransitionReceiptRepository receipts; + @Autowired private AccountAuditOutboxRepository auditOutbox; + @Autowired private FreshTenantIdentityAssociationRepository freshAssociations; + + @MockitoBean private EntityManagementClient entityManagementClient; + @MockitoBean private GameSessionClient gameSessionClient; + @MockitoBean private LoggingAdminClient loggingAdminClient; + @MockitoBean private JavaMailSender mailSender; + + @Test + void completeHistoricalReadbackCommitsAfterExpiryAndLaterUnavailablePolicyAttempt() { + JoinFixture fixture = fixture(true); + persistEvidence(fixture, EvidenceShape.COMPLETE); + recordLaterUnavailableAttempt(fixture); + EvidenceCounts before = evidenceCounts(fixture); + long fenceBefore = issuanceFence(fixture.account().accountUuid()); + Instant reconciliationAt = reconciliationTime(fixture); + assertThat(expiresAt(fixture)).isBefore(reconciliationAt); + + reconciliationService.reconcileDueOperations(reconciliationAt); + + CanonicalJoinOperationEvidence committed = readOperation(fixture); + assertThat(committed.status()).isEqualTo("COMMITTED"); + assertThat(committed.outcome()).isEqualTo("JOINED"); + assertThat(committed.membershipId()).isEqualTo(membershipId(fixture)); + assertThat(committed.membershipVersion()).isEqualTo(2L); + assertThat(committed.membershipAuthorityGeneration()).isEqualTo(1L); + assertThat(committed.lastAttemptAuthorityAvailability()).isEqualTo("UNAVAILABLE"); + assertThat(committed.lastAttemptFailureCode()).isEqualTo("ENTITLEMENT_TIMEOUT"); + assertThat(committed.reconciliationAttemptCount()).isEqualTo(1); + assertThat(evidenceCounts(fixture)).isEqualTo(before); + assertThat(issuanceFence(fixture.account().accountUuid())).isEqualTo(fenceBefore); + } + + @Test + void eventReadbackRejectsStalePendingDtoAfterJournalHasTerminalized() { + JoinFixture fixture = fixture(true); + persistEvidence(fixture, EvidenceShape.COMPLETE); + recordLaterUnavailableAttempt(fixture); + CanonicalJoinOperationEvidence stalePending = readOperation(fixture); + + reconciliationService.reconcileDueOperations(reconciliationTime(fixture)); + + assertThat(readOperation(fixture).status()).isEqualTo("COMMITTED"); + assertThatThrownBy( + () -> + inTransaction( + () -> membershipEventProducer.requireCanonicalFirstJoinEvent(stalePending))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("exact persisted journal readback"); + } + + @Test + void absentOrContradictoryOwnerEvidenceRemainsPendingWithoutReconciliationSideEffects() { + List cases = + List.of( + new Case("policy not evaluated", null, EvidenceShape.NONE), + new Case("policy denied", false, EvidenceShape.NONE), + new Case("membership absent", true, EvidenceShape.NONE), + new Case("roles absent", true, EvidenceShape.MEMBERSHIP_ONLY), + new Case("role snapshot mismatch", true, EvidenceShape.MISMATCHED_ROLES), + new Case("event and receipt absent", true, EvidenceShape.ROLES_ONLY), + new Case("receipt absent", true, EvidenceShape.EVENT_ONLY), + new Case("audit absent", true, EvidenceShape.RECEIPT_ONLY), + new Case("audit payload mismatch", true, EvidenceShape.MISMATCHED_AUDIT)); + List fixtures = + cases.stream() + .map( + candidate -> { + JoinFixture fixture = fixture(candidate.allowPublicJoin()); + persistEvidence(fixture, candidate.evidenceShape()); + recordLaterUnavailableAttempt(fixture); + return fixture; + }) + .toList(); + Map before = + fixtures.stream() + .collect( + java.util.stream.Collectors.toMap(JoinFixture::requestId, this::evidenceCounts)); + + reconciliationService.reconcileDueOperations(Instant.now().plus(Duration.ofDays(2))); + + for (int index = 0; index < fixtures.size(); index++) { + JoinFixture fixture = fixtures.get(index); + String caseDescription = cases.get(index).description(); + CanonicalJoinOperationEvidence unresolved = readOperation(fixture); + assertThat(unresolved.status()).as(caseDescription).isEqualTo("PENDING"); + assertThat(unresolved.outcome()).as(caseDescription).isNull(); + assertThat(unresolved.membershipId()).as(caseDescription).isNull(); + assertThat(unresolved.reconciliationAttemptCount()).as(caseDescription).isEqualTo(2); + assertThat(unresolved.lastAttemptAuthorityAvailability()) + .as(caseDescription) + .isEqualTo("UNAVAILABLE"); + assertThat(unresolved.lastAttemptFailureCode()) + .as(caseDescription) + .isEqualTo("ENTITLEMENT_TIMEOUT"); + assertThat(evidenceCounts(fixture)) + .as(caseDescription) + .isEqualTo(before.get(fixture.requestId())); + if ("event and receipt absent".equals(caseDescription)) { + assertThatThrownBy( + () -> + inTransaction( + () -> + membershipEventProducer.requireCanonicalFirstJoinEvent( + joinOperations + .findCanonicalEvidenceByRequestId(fixture.requestId()) + .orElseThrow()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no matching V33 event"); + } + } + } + + @Test + void concurrentExactTerminalRetryAndReconcilerRetainOneHistoricalWriteSet() throws Exception { + JoinFixture fixture = fixture(true); + persistEvidence(fixture, EvidenceShape.COMPLETE); + recordLaterUnavailableAttempt(fixture); + EvidenceCounts before = evidenceCounts(fixture); + Instant dueAt = reconciliationTime(fixture); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future reconcile = + executor.submit( + () -> { + ready.countDown(); + await(start); + reconciliationService.reconcileDueOperations(dueAt); + }); + Future retry = + executor.submit( + () -> { + ready.countDown(); + await(start); + return exactTerminalRetry(fixture); + }); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + reconcile.get(30, TimeUnit.SECONDS); + CanonicalJoinOperationEvidence retried = retry.get(30, TimeUnit.SECONDS); + assertThat(retried.status()).isEqualTo("COMMITTED"); + assertThat(retried.outcome()).isEqualTo("JOINED"); + assertThat(exactTerminalRetry(fixture)).isEqualTo(retried); + } finally { + start.countDown(); + executor.shutdownNow(); + } + + CanonicalJoinOperationEvidence committed = readOperation(fixture); + assertThat(committed.status()).isEqualTo("COMMITTED"); + assertThat(committed.outcome()).isEqualTo("JOINED"); + assertThat(evidenceCounts(fixture)).isEqualTo(before); + } + + private JoinFixture fixture(Boolean allowPublicJoin) { + AccountFixture account = accountFixture(); + UUID tenantUuid = UUID.randomUUID(); + FreshTenantCreationEvidence source = freshTenantEvidence(tenantUuid); + inTransaction( + () -> { + freshAssociations.importVerified(source); + generations.initializeTenantIfAbsent(tenantUuid); + generations.initializeIssuerIfAbsent(AccountServiceImpl.ACCOUNT_JWT_ISSUER); + membershipEventProducer.readFreshNeverJoinedMembershipSnapshot( + account.accountUuid(), tenantUuid); + return null; + }); + VerifiedTenantProvenance provenance = + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + source.operationId(), + source.evidenceDigest()); + Instant evaluatedAt = Instant.now().minus(Duration.ofHours(1)); + Instant expiresAt = Instant.now().minus(Duration.ofMinutes(30)); + CanonicalJoinScopeV2 scope = + new CanonicalJoinScopeV2( + "canonical-recovery-" + UUID.randomUUID(), + account.accountUuid(), + tenantUuid, + UUID.randomUUID(), + "recovery-tenant-" + shortUuid(), + "recovery-world-" + shortUuid(), + "production", + UUID.randomUUID(), + "SHARED", + UUID.randomUUID(), + 3L, + 2L, + RFC3339.format(evaluatedAt.atOffset(ZoneOffset.UTC)), + RFC3339.format(expiresAt.atOffset(ZoneOffset.UTC))); + String requestId = UUID.randomUUID().toString(); + String callerBinding = "synthetic-caller-" + UUID.randomUUID(); + inTransaction( + () -> { + connectScopes.insertCanonical(account.accountId(), scope, provenance); + joinOperations.insertCanonicalIntent(requestId, scope, callerBinding); + if (allowPublicJoin != null) { + joinOperations.bindCanonicalPolicyEvidence( + requestId, scope, callerBinding, allowPublicJoin, 11L); + } + return null; + }); + return new JoinFixture(account, tenantUuid, provenance, scope, requestId, callerBinding); + } + + private void persistEvidence(JoinFixture fixture, EvidenceShape shape) { + inTransactionWithoutResult( + () -> { + if (shape.membership()) { + Account account = + accounts.findByAccountUuid(fixture.account().accountUuid()).orElseThrow(); + AccountTenantMembership membership = new AccountTenantMembership(); + membership.setAccount(account); + membership.setTenantId(fixture.provenance().legacyTenantId()); + membership.setTenantUuid(fixture.tenantUuid()); + membership.setTenantProvenanceKind(fixture.provenance().kind().name()); + membership.setTenantSourceOperationId(fixture.provenance().sourceOperationId()); + membership.setTenantProvenanceDigest(fixture.provenance().digest()); + membership.setGameplayAdmissionAllowed(true); + membership.setLifecycleState("ACTIVE"); + membership.setMembershipVersion(2L); + membership.setMembershipAuthorityGeneration(1L); + membership.setAuthorityProvenance("EXPLICIT_JOIN"); + memberships.saveCanonical( + membership, + fixture.account().accountUuid(), + fixture.tenantUuid(), + fixture.provenance()); + if (shape.roles()) { + roleSnapshots.replaceCanonical( + membership, + fixture.account().accountUuid(), + fixture.tenantUuid(), + fixture.provenance(), + 2L, + shape.mismatchedRoles() ? List.of("player", "moderator") : List.of("player")); + } + } + if (shape.event()) { + membershipEventProducer.publishCanonicalFirstJoinMembershipChange( + fixture.scope(), fixture.requestId(), fixture.callerBinding()); + } + if (shape.receipt()) { + receipts.appendCanonicalTransition( + fixture.account().accountUuid(), + fixture.tenantUuid(), + "MEMBERSHIP_JOINED", + fixture.requestId()); + } + if (shape.audit()) { + UUID payloadAccountUuid = + shape.mismatchedAudit() ? UUID.randomUUID() : fixture.account().accountUuid(); + String payload = + AccountAuditOutboxRepository.canonicalJoinPayload( + payloadAccountUuid, + fixture.tenantUuid(), + fixture.scope().worldSlug(), + fixture.scope().realmSlug(), + Map.of(fixture.tenantUuid().toString(), "2"), + fixture.requestId()); + auditOutbox.appendCanonicalTenant( + auditEventId(fixture.requestId()), + fixture.tenantUuid().toString(), + "ACCOUNT_JOINED_PUBLIC_PRODUCTION", + payload); + } + }); + } + + private void recordLaterUnavailableAttempt(JoinFixture fixture) { + Instant diagnosticAt = Instant.now(); + inTransactionWithoutResult( + () -> { + joinOperations.recordCanonicalPolicyUnavailable( + fixture.requestId(), fixture.scope(), fixture.callerBinding(), "ENTITLEMENT_TIMEOUT"); + joinOperations.recordCanonicalReconciliationAttempt( + fixture.requestId(), + 0, + MAX_ATTEMPTS, + diagnosticAt, + "CANONICAL_JOIN_READBACK_UNAVAILABLE", + diagnosticAt); + }); + } + + private CanonicalJoinOperationEvidence exactTerminalRetry(JoinFixture fixture) { + return inTransaction( + () -> + joinOperations.finishCanonicalOperation( + fixture.requestId(), "COMMITTED", "JOINED", membershipId(fixture), 2L, 1L)); + } + + private AccountFixture accountFixture() { + String suffix = shortUuid(); + long accountId = + Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) RETURNING id", + "canonical-reconcile-" + suffix, + "canonical-reconcile-" + suffix + "@example.test", + "synthetic-fixture-hash") + .fetchOne(0, Long.class)); + UUID accountUuid = + Objects.requireNonNull( + dsl.resultQuery("SELECT account_uuid FROM accounts WHERE id = ?", accountId) + .fetchOne(0, UUID.class)); + dsl.execute( + "INSERT INTO account_authority_generations " + + "(scope_kind, account_uuid, generation, source_version) VALUES ('ACCOUNT', ?, 1, 1)", + accountUuid); + dsl.execute( + "INSERT INTO account_authority_issuance_fences " + + "(account_uuid, issuance_fence, source_version) VALUES (?, 1, 1)", + accountUuid); + inTransactionWithoutResult( + () -> generations.initializeIssuerIfAbsent(AccountServiceImpl.ACCOUNT_JWT_ISSUER)); + return new AccountFixture(accountId, accountUuid); + } + + private FreshTenantCreationEvidence freshTenantEvidence(UUID tenantUuid) { + UUID creationRequestId = UUID.randomUUID(); + UUID operationId = UUID.randomUUID(); + String sourceTenantKey = "f-" + shortUuid(); + String requestDigest = + GameTenantCreationDigest.requestDigest( + TEST_NAMESPACE, creationRequestId, sourceTenantKey, "Canonical recovery fixture", null); + long sourceGameRowId = positiveRandomLong(); + String provenanceKind = "NEW_GAME_ROW"; + return new FreshTenantCreationEvidence( + 1, + TEST_NAMESPACE, + creationRequestId, + operationId, + requestDigest, + tenantUuid, + sourceGameRowId, + sourceTenantKey, + provenanceKind, + GameTenantCreationDigest.evidenceDigest( + TEST_NAMESPACE, + creationRequestId, + operationId, + requestDigest, + tenantUuid, + sourceGameRowId, + sourceTenantKey, + provenanceKind)); + } + + private CanonicalJoinOperationEvidence readOperation(JoinFixture fixture) { + return inTransaction( + () -> joinOperations.findCanonicalEvidenceByRequestId(fixture.requestId()).orElseThrow()); + } + + private long membershipId(JoinFixture fixture) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT id FROM account_tenant_membership " + + "WHERE account_id = ? AND tenant_uuid = ?", + fixture.account().accountId(), + fixture.tenantUuid()) + .fetchOne(0, Long.class)); + } + + private EvidenceCounts evidenceCounts(JoinFixture fixture) { + return new EvidenceCounts( + count( + "SELECT COUNT(*) FROM account_tenant_membership WHERE account_id = ? AND tenant_uuid = ?", + fixture.account().accountId(), + fixture.tenantUuid()), + count( + "SELECT COUNT(*) FROM account_authority_outbox_events WHERE outbox_stream_key = ?", + eventStreamKey(fixture)), + count( + "SELECT COUNT(*) FROM account_membership_transition_receipts " + + "WHERE account_uuid = ? AND tenant_uuid = ? AND receipt_version = 2", + fixture.account().accountUuid(), + fixture.tenantUuid()), + count( + "SELECT COUNT(*) FROM account_audit_outbox WHERE audit_event_id = ?", + auditEventId(fixture.requestId()))); + } + + private long count(String sql, Object... bindings) { + return Objects.requireNonNull(dsl.resultQuery(sql, bindings).fetchOne(0, Long.class)); + } + + private long issuanceFence(UUID accountUuid) { + return count( + "SELECT issuance_fence FROM account_authority_issuance_fences WHERE account_uuid = ?", + accountUuid); + } + + private Instant expiresAt(JoinFixture fixture) { + return Instant.parse(fixture.scope().connectScopeExpiresAt()); + } + + private Instant reconciliationTime(JoinFixture fixture) { + return expiresAt(fixture).plus(Duration.ofDays(1)); + } + + private String eventStreamKey(JoinFixture fixture) { + return "account:auth-authority:v1:membership/" + + fixture.account().accountUuid() + + "/" + + fixture.tenantUuid(); + } + + private static UUID auditEventId(String requestId) { + return UUID.nameUUIDFromBytes( + ("account-join-audit/v1:" + requestId).getBytes(java.nio.charset.StandardCharsets.UTF_8)); + } + + private T inTransaction(java.util.function.Supplier callback) { + return new TransactionTemplate(transactionManager).execute(status -> callback.get()); + } + + private void inTransactionWithoutResult(Runnable callback) { + new TransactionTemplate(transactionManager).executeWithoutResult(status -> callback.run()); + } + + private static String shortUuid() { + return UUID.randomUUID().toString().replace("-", ""); + } + + private static long positiveRandomLong() { + long candidate = UUID.randomUUID().getMostSignificantBits() & Long.MAX_VALUE; + return candidate == 0L ? 1L : candidate; + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Concurrent reconciliation barrier timed out"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Concurrent reconciliation was interrupted", exception); + } + } + + private record AccountFixture(long accountId, UUID accountUuid) {} + + private record JoinFixture( + AccountFixture account, + UUID tenantUuid, + VerifiedTenantProvenance provenance, + CanonicalJoinScopeV2 scope, + String requestId, + String callerBinding) {} + + private record EvidenceCounts(long memberships, long events, long receipts, long audits) {} + + private record Case(String description, Boolean allowPublicJoin, EvidenceShape evidenceShape) {} + + private enum EvidenceShape { + NONE(false, false, false, false, false, false), + MEMBERSHIP_ONLY(true, false, false, false, false, false), + ROLES_ONLY(true, true, false, false, false, false), + MISMATCHED_ROLES(true, true, false, false, false, false, true), + EVENT_ONLY(true, true, true, false, false, false), + RECEIPT_ONLY(true, true, true, true, false, false), + MISMATCHED_AUDIT(true, true, true, true, true, true), + COMPLETE(true, true, true, true, true, false); + + private final boolean membership; + private final boolean roles; + private final boolean event; + private final boolean receipt; + private final boolean audit; + private final boolean mismatchedAudit; + private final boolean mismatchedRoles; + + EvidenceShape( + boolean membership, + boolean roles, + boolean event, + boolean receipt, + boolean audit, + boolean mismatchedAudit) { + this(membership, roles, event, receipt, audit, mismatchedAudit, false); + } + + EvidenceShape( + boolean membership, + boolean roles, + boolean event, + boolean receipt, + boolean audit, + boolean mismatchedAudit, + boolean mismatchedRoles) { + this.membership = membership; + this.roles = roles; + this.event = event; + this.receipt = receipt; + this.audit = audit; + this.mismatchedAudit = mismatchedAudit; + this.mismatchedRoles = mismatchedRoles; + } + + boolean membership() { + return membership; + } + + boolean roles() { + return roles; + } + + boolean event() { + return event; + } + + boolean receipt() { + return receipt; + } + + boolean audit() { + return audit; + } + + boolean mismatchedAudit() { + return mismatchedAudit; + } + + boolean mismatchedRoles() { + return mismatchedRoles; + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountConnectScopeCanonicalIdentityIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountConnectScopeCanonicalIdentityIntegrationTest.java index 84470a9a72..87503db94d 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountConnectScopeCanonicalIdentityIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountConnectScopeCanonicalIdentityIntegrationTest.java @@ -5,6 +5,7 @@ import java.time.Instant; import java.util.Base64; +import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; @@ -23,6 +24,7 @@ import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository.CanonicalConnectScopeEvidence; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinOperationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinReconciliationCandidate; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; import net.firedevops.firemud.accountservice.repository.AccountRepository; @@ -49,7 +51,7 @@ import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; -/** PostgreSQL proof of the shared V1/V2 scope evidence storage boundary. */ +/** PostgreSQL storage proof for retained V1 and canonical V2 JOIN scope/journal evidence. */ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") class AccountConnectScopeCanonicalIdentityIntegrationTest { @@ -865,6 +867,612 @@ public void afterCommit() { .noneMatch(operation -> operation.requestId().equals(requestId)); } + /** + * Storage-only proof: the synthetic membership row exercises journal fences, not authenticated + * entitlement, role, authority-event/checkpoint, receipt, audit, or public JOIN capability. + */ + @Test + void canonicalTerminalJournalPreservesHistoryAndOnlyStoresContractShapedOutcomes() { + Fixture fixture = fixture(); + SeededRetainedIdentity account = seedRetainedIdentity(fixture.setupDsl()); + CanonicalConnectScopeRepositoryFixture beforeV46 = scopeRepository(fixture); + VerifiedJoinScope retainedScope = retainedV1Scope(account.accountId()); + beforeV46.scopes().insert(retainedScope); + AccountJoinOperationRepository retainedOperations = + new AccountJoinOperationRepository(fixture.transactionDsl(), beforeV46.scopes()); + String retainedRequestId = "terminal-journal-retained-v1"; + String retainedCaller = "retained-v1-caller"; + fixture + .transaction() + .executeWithoutResult( + status -> + retainedOperations.insertIntent( + retainedRequestId, + retainedScope, + retainedCaller, + AccountJoinDigest.intent(retainedRequestId, retainedScope, retainedCaller))); + Map retainedOperationBefore = + v1OperationProjection(fixture.setupDsl(), retainedRequestId); + + UUID tenantUuid = UUID.randomUUID(); + FreshTenantCreationEvidence tenantEvidence = freshTenantEvidence(tenantUuid); + fixture + .transaction() + .executeWithoutResult( + status -> beforeV46.freshTenantIdentities().importVerified(tenantEvidence)); + flyway(fixture.dataSource(), fixture.schema(), "46").migrate(); + + CanonicalConnectScopeRepositoryFixture canonicalFixture = scopeRepository(fixture); + VerifiedTenantProvenance provenance = + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + tenantEvidence.operationId(), + tenantEvidence.evidenceDigest()); + CanonicalJoinScopeV2 unexpiredScope = + timedV2Scope( + "terminal-join-scope-token", + account.accountUuid(), + tenantUuid, + "terminal-tenant", + "2098-01-01T00:00:00Z", + "2099-01-01T00:00:00Z"); + fixture + .transaction() + .executeWithoutResult( + status -> + canonicalFixture + .scopes() + .insertCanonical(account.accountId(), unexpiredScope, provenance)); + flyway(fixture.dataSource(), fixture.schema(), "49").migrate(); + Record retainedOperationBeforeV50 = + Objects.requireNonNull( + fixture + .setupDsl() + .fetchOne( + "SELECT * FROM account_join_operations WHERE request_id = ?", + retainedRequestId), + "Retained V1 JOIN operation must exist before V50"); + flyway(fixture.dataSource(), fixture.schema(), "50").migrate(); + + AccountConnectScopeRepository scopes = scopeRepository(fixture).scopes(); + AccountJoinOperationRepository operations = + new AccountJoinOperationRepository(fixture.transactionDsl(), scopes); + String callerBinding = "verified-terminal-fixture-caller"; + String committedRequestId = "canonical-join-terminal-committed"; + fixture + .transaction() + .executeWithoutResult( + status -> + operations.insertCanonicalIntent( + committedRequestId, unexpiredScope, callerBinding)); + fixture + .transaction() + .execute( + status -> + operations.bindCanonicalPolicyEvidence( + committedRequestId, unexpiredScope, callerBinding, true, 19L)); + + CanonicalJoinOperationEvidence unavailableAfterPolicy = + fixture + .transaction() + .execute( + status -> + operations.recordCanonicalPolicyUnavailable( + committedRequestId, + unexpiredScope, + callerBinding, + "ENTITLEMENT_UNAVAILABLE")); + assertThat(unavailableAfterPolicy.status()).isEqualTo("PENDING"); + assertThat(unavailableAfterPolicy.entitlementAuthorityAvailability()).isEqualTo("AVAILABLE"); + assertThat(unavailableAfterPolicy.requestDigest()) + .isEqualTo( + AccountJoinDigest.requestV2( + unexpiredScope, + callerBinding, + AccountJoinDigest.EntitlementAvailabilityV2.AVAILABLE, + true, + 19L)); + assertThat(unavailableAfterPolicy.entitlementVersion()).isEqualTo(19L); + assertThat(unavailableAfterPolicy.allowPublicJoin()).isTrue(); + assertThat(unavailableAfterPolicy.lastAttemptAuthorityAvailability()).isEqualTo("UNAVAILABLE"); + assertThat(unavailableAfterPolicy.lastAttemptFailureCode()) + .isEqualTo("ENTITLEMENT_UNAVAILABLE"); + assertThatThrownBy( + () -> + fixture + .transaction() + .execute( + status -> + operations.finishCanonicalOperation( + committedRequestId, + "FAILED", + "TENANT_BILLING_BLOCKED", + null, + null, + null))) + .isInstanceOf(AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class) + .hasMessageContaining("successful available-policy attempt"); + + CanonicalJoinOperationEvidence availableAgain = + fixture + .transaction() + .execute( + status -> + operations.bindCanonicalPolicyEvidence( + committedRequestId, unexpiredScope, callerBinding, true, 19L)); + assertThat(availableAgain.entitlementAuthorityAvailability()).isEqualTo("AVAILABLE"); + assertThat(availableAgain.lastAttemptAuthorityAvailability()).isEqualTo("AVAILABLE"); + assertThat(availableAgain.lastAttemptFailureCode()).isNull(); + + Long membershipId = + fixture + .transaction() + .execute( + status -> + insertSyntheticCanonicalActiveMembership( + fixture, + account.accountId(), + tenantUuid, + tenantEvidence.operationId(), + tenantEvidence.evidenceDigest())); + CanonicalJoinOperationEvidence committed = + fixture + .transaction() + .execute( + status -> + operations.finishCanonicalOperation( + committedRequestId, "COMMITTED", "JOINED", membershipId, 2L, 1L)); + assertThat(committed.status()).isEqualTo("COMMITTED"); + assertThat(committed.outcome()).isEqualTo("JOINED"); + assertThat(committed.membershipId()).isEqualTo(membershipId); + assertThat(committed.membershipVersion()).isEqualTo(2L); + assertThat(committed.membershipAuthorityGeneration()).isEqualTo(1L); + assertThat(committed.scopeEvidence()).isEqualTo(availableAgain.scopeEvidence()); + CanonicalJoinOperationEvidence committedRetry = + fixture + .transaction() + .execute( + status -> + operations.finishCanonicalOperation( + committedRequestId, "COMMITTED", "JOINED", membershipId, 2L, 1L)); + assertThat(committedRetry).isEqualTo(committed); + assertThatThrownBy( + () -> + fixture + .transaction() + .execute( + status -> + operations.finishCanonicalOperation( + committedRequestId, + "COMMITTED", + "ALREADY_ACTIVE", + membershipId, + 2L, + 1L))) + .isInstanceOf(AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class); + assertThatThrownBy( + () -> + fixture + .setupDsl() + .execute( + "UPDATE account_join_operations SET outcome = 'ALREADY_ACTIVE' " + + "WHERE request_id = ?", + committedRequestId)) + .isInstanceOf(DataAccessException.class); + assertTerminalJournalCheckRejectsNullField(fixture, "outcome = NULL", committedRequestId); + assertTerminalJournalCheckRejectsNullField( + fixture, "outcome_membership_version = NULL", committedRequestId); + assertTerminalJournalCheckRejectsNullField( + fixture, "outcome_membership_authority_generation = NULL", committedRequestId); + + String deniedRequestId = "canonical-join-terminal-denied"; + fixture + .transaction() + .executeWithoutResult( + status -> + operations.insertCanonicalIntent(deniedRequestId, unexpiredScope, callerBinding)); + fixture + .transaction() + .execute( + status -> + operations.bindCanonicalPolicyEvidence( + deniedRequestId, unexpiredScope, callerBinding, false, 20L)); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> { + operations.finishCanonicalOperation( + deniedRequestId, + "FAILED", + "PUBLIC_PRODUCTION_ADMISSION_DENIED", + null, + null, + null); + throw new IllegalStateException("simulated terminal write rollback"); + })) + .hasMessage("simulated terminal write rollback"); + CanonicalJoinOperationEvidence afterTerminalRollback = + fixture + .transaction() + .execute(status -> operations.findCanonicalEvidenceByRequestId(deniedRequestId)) + .orElseThrow(); + assertThat(afterTerminalRollback.status()).isEqualTo("PENDING"); + assertThat(afterTerminalRollback.outcome()).isNull(); + assertThat(afterTerminalRollback.membershipId()).isNull(); + CanonicalJoinOperationEvidence failed = + fixture + .transaction() + .execute( + status -> + operations.finishCanonicalOperation( + deniedRequestId, + "FAILED", + "PUBLIC_PRODUCTION_ADMISSION_DENIED", + null, + null, + null)); + assertThat(failed.status()).isEqualTo("FAILED"); + assertThat(failed.outcome()).isEqualTo("PUBLIC_PRODUCTION_ADMISSION_DENIED"); + assertThat(failed.membershipId()).isNull(); + CanonicalJoinOperationEvidence failedRetry = + fixture + .transaction() + .execute( + status -> + operations.finishCanonicalOperation( + deniedRequestId, + "FAILED", + "PUBLIC_PRODUCTION_ADMISSION_DENIED", + null, + null, + null)); + assertThat(failedRetry).isEqualTo(failed); + assertTerminalJournalCheckRejectsNullField(fixture, "outcome = NULL", deniedRequestId); + + String unavailableRequestId = "canonical-join-terminal-unavailable"; + fixture + .transaction() + .executeWithoutResult( + status -> + operations.insertCanonicalIntent( + unavailableRequestId, unexpiredScope, callerBinding)); + CanonicalJoinOperationEvidence unavailable = + fixture + .transaction() + .execute( + status -> + operations.recordCanonicalPolicyUnavailable( + unavailableRequestId, + unexpiredScope, + callerBinding, + "ENTITLEMENT_UNAVAILABLE")); + assertThat(unavailable.status()).isEqualTo("PENDING"); + assertThat(unavailable.entitlementAuthorityAvailability()).isEqualTo("UNAVAILABLE"); + assertThat(unavailable.allowPublicJoin()).isNull(); + assertThat(unavailable.entitlementVersion()).isNull(); + assertThat(unavailable.requestDigestVersion()).isNull(); + assertThat(unavailable.requestDigest()).isNull(); + assertThatThrownBy( + () -> + fixture + .transaction() + .execute( + status -> + operations.finishCanonicalOperation( + unavailableRequestId, + "FAILED", + "TENANT_BILLING_BLOCKED", + null, + null, + null))) + .isInstanceOf(AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class); + assertThat( + fixture + .transaction() + .execute( + status -> operations.findCanonicalEvidenceByRequestId(unavailableRequestId)) + .orElseThrow() + .status()) + .isEqualTo("PENDING"); + + String absentMembershipRequestId = "canonical-join-terminal-absent-membership"; + fixture + .transaction() + .executeWithoutResult( + status -> + operations.insertCanonicalIntent( + absentMembershipRequestId, unexpiredScope, callerBinding)); + fixture + .transaction() + .execute( + status -> + operations.bindCanonicalPolicyEvidence( + absentMembershipRequestId, unexpiredScope, callerBinding, true, 21L)); + assertThatThrownBy( + () -> + fixture + .transaction() + .execute( + status -> + operations.finishCanonicalOperation( + absentMembershipRequestId, + "COMMITTED", + "JOINED", + Long.MAX_VALUE, + 2L, + 1L))) + .isInstanceOf(AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class); + assertThat( + fixture + .transaction() + .execute( + status -> + operations.findCanonicalEvidenceByRequestId(absentMembershipRequestId)) + .orElseThrow() + .status()) + .isEqualTo("PENDING"); + + CanonicalJoinScopeV2 expiredScope = + timedV2Scope( + "expired-terminal-join-scope-token", + account.accountUuid(), + tenantUuid, + "terminal-tenant", + "2020-01-01T00:00:00Z", + "2021-01-01T00:00:00Z"); + fixture + .transaction() + .executeWithoutResult( + status -> + canonicalFixture + .scopes() + .insertCanonical(account.accountId(), expiredScope, provenance)); + String expiredRequestId = "canonical-join-terminal-expired-scope"; + fixture + .transaction() + .executeWithoutResult( + status -> + operations.insertCanonicalIntent(expiredRequestId, expiredScope, callerBinding)); + fixture + .transaction() + .execute( + status -> + operations.bindCanonicalPolicyEvidence( + expiredRequestId, expiredScope, callerBinding, true, 22L)); + assertThatThrownBy( + () -> + fixture + .transaction() + .execute( + status -> + operations.finishCanonicalOperation( + expiredRequestId, + "FAILED", + "TENANT_BILLING_BLOCKED", + null, + null, + null))) + .isInstanceOf(AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class) + .hasMessageContaining("Expired canonical JOIN scope"); + assertThat( + fixture + .transaction() + .execute(status -> operations.findCanonicalEvidenceByRequestId(expiredRequestId)) + .orElseThrow() + .status()) + .isEqualTo("PENDING"); + + String expiredPriorCommitRequestId = "canonical-join-terminal-expired-prior-commit"; + fixture + .transaction() + .executeWithoutResult( + status -> + operations.insertCanonicalIntent( + expiredPriorCommitRequestId, expiredScope, callerBinding)); + fixture + .transaction() + .execute( + status -> + operations.bindCanonicalPolicyEvidence( + expiredPriorCommitRequestId, expiredScope, callerBinding, true, 23L)); + CanonicalJoinOperationEvidence unavailableAfterExpiredCommit = + fixture + .transaction() + .execute( + status -> + operations.recordCanonicalPolicyUnavailable( + expiredPriorCommitRequestId, + expiredScope, + callerBinding, + "ENTITLEMENT_UNAVAILABLE")); + CanonicalJoinOperationEvidence expiredPriorCommit = + fixture + .transaction() + .execute( + status -> + operations.finishCanonicalOperation( + expiredPriorCommitRequestId, "COMMITTED", "JOINED", membershipId, 2L, 1L)); + assertThat(unavailableAfterExpiredCommit.status()).isEqualTo("PENDING"); + assertThat(unavailableAfterExpiredCommit.entitlementAuthorityAvailability()) + .isEqualTo("AVAILABLE"); + assertThat(expiredPriorCommit.status()).isEqualTo("COMMITTED"); + assertThat(expiredPriorCommit.outcome()).isEqualTo("JOINED"); + assertThat(expiredPriorCommit.lastAttemptAuthorityAvailability()).isEqualTo("UNAVAILABLE"); + assertThat(expiredPriorCommit.lastAttemptFailureCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); + + String invalidSourceRequestId = "canonical-join-terminal-invalid-source"; + fixture + .transaction() + .executeWithoutResult( + status -> + operations.insertCanonicalIntent( + invalidSourceRequestId, unexpiredScope, callerBinding)); + fixture + .transaction() + .execute( + status -> + operations.bindCanonicalPolicyEvidence( + invalidSourceRequestId, unexpiredScope, callerBinding, true, 24L)); + String missingSourceHash = AccountJoinDigest.tokenHash("missing-canonical-scope-source"); + fixture + .transaction() + .executeWithoutResult( + status -> { + DSLContext transactionDsl = fixture.transactionDsl(); + transactionDsl.execute( + "ALTER TABLE account_join_operations " + + "DISABLE TRIGGER account_join_operation_identity_guard"); + try { + transactionDsl.execute( + "UPDATE account_join_operations SET scope_token_hash = ? WHERE request_id = ?", + missingSourceHash, + invalidSourceRequestId); + } finally { + transactionDsl.execute( + "ALTER TABLE account_join_operations " + + "ENABLE TRIGGER account_join_operation_identity_guard"); + } + }); + assertThatThrownBy( + () -> + fixture + .transaction() + .execute( + status -> + operations.findCanonicalEvidenceByRequestId(invalidSourceRequestId))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Canonical JOIN operation scope evidence is absent"); + + Instant attemptedAt = Instant.now().plusSeconds(5); + List due = + fixture + .transaction() + .execute( + status -> operations.findDueCanonicalPendingReconciliation(attemptedAt, 100, 3)); + assertThat(due) + .extracting(CanonicalJoinReconciliationCandidate::requestId) + .contains( + unavailableRequestId, + absentMembershipRequestId, + expiredRequestId, + invalidSourceRequestId); + Boolean unavailableAttemptRecorded = + fixture + .transaction() + .execute( + status -> + operations.recordCanonicalReconciliationAttempt( + unavailableRequestId, + 0, + 3, + attemptedAt, + "evidence remains unresolved", + attemptedAt.plusSeconds(30))); + assertThat(unavailableAttemptRecorded).isTrue(); + CanonicalJoinReconciliationCandidate invalidSourceCandidate = + due.stream() + .filter(candidate -> candidate.requestId().equals(invalidSourceRequestId)) + .findFirst() + .orElseThrow(); + Boolean invalidSourceAttemptRecorded = + fixture + .transaction() + .execute( + status -> + operations.recordCanonicalReconciliationAttempt( + invalidSourceCandidate.requestId(), + invalidSourceCandidate.reconciliationAttemptCount(), + 3, + attemptedAt, + "canonical scope source unresolved", + attemptedAt.plusSeconds(30))); + assertThat(invalidSourceAttemptRecorded).isTrue(); + Record invalidSourceAfterAttempt = + Objects.requireNonNull( + fixture + .setupDsl() + .fetchOne( + "SELECT status, reconciliation_attempt_count, " + + "last_reconciliation_attempt_reason FROM account_join_operations " + + "WHERE request_id = ?", + invalidSourceRequestId), + "Invalid-source operation must remain in the journal"); + assertThat(invalidSourceAfterAttempt.get("status", String.class)).isEqualTo("PENDING"); + assertThat(invalidSourceAfterAttempt.get("reconciliation_attempt_count", Integer.class)) + .isEqualTo(1); + assertThat(invalidSourceAfterAttempt.get("last_reconciliation_attempt_reason", String.class)) + .isEqualTo("canonical scope source unresolved"); + assertThatThrownBy( + () -> + fixture + .transaction() + .execute( + status -> + operations.finishCanonicalOperation( + invalidSourceRequestId, + "COMMITTED", + "JOINED", + membershipId, + 2L, + 1L))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Canonical JOIN operation scope evidence is absent"); + CanonicalJoinOperationEvidence attempted = + fixture + .transaction() + .execute(status -> operations.findCanonicalEvidenceByRequestId(unavailableRequestId)) + .orElseThrow(); + assertThat(attempted.status()).isEqualTo("PENDING"); + assertThat(attempted.reconciliationAttemptCount()).isEqualTo(1); + assertThat(attempted.lastReconciliationAttemptReason()) + .isEqualTo("evidence remains unresolved"); + List dueAfterBackoff = + fixture + .transaction() + .execute( + status -> + operations.findDueCanonicalPendingReconciliation( + attemptedAt.plusSeconds(10), 100, 3)); + assertThat(dueAfterBackoff) + .noneMatch(candidate -> candidate.requestId().equals(unavailableRequestId)); + assertThat(dueAfterBackoff) + .noneMatch(candidate -> candidate.requestId().equals(invalidSourceRequestId)); + + Boolean retainedV1InsertRejected = + fixture + .transaction() + .execute( + status -> + operations.insertIntent( + committedRequestId, + retainedScope, + retainedCaller, + AccountJoinDigest.intent( + committedRequestId, retainedScope, retainedCaller))); + assertThat(retainedV1InsertRejected).isFalse(); + assertThat(retainedOperations.find(committedRequestId)).isEmpty(); + Optional canonicalTerminalReadback = + fixture + .transaction() + .execute(status -> operations.findCanonicalEvidenceByRequestId(committedRequestId)); + assertThat(canonicalTerminalReadback).contains(committed); + assertThat(v1OperationProjection(fixture.setupDsl(), retainedRequestId)) + .containsExactlyEntriesOf(retainedOperationBefore); + Record retainedOperationAfterV50 = + Objects.requireNonNull( + fixture + .setupDsl() + .fetchOne( + "SELECT * FROM account_join_operations WHERE request_id = ?", + retainedRequestId), + "Retained V1 JOIN operation must exist after V50"); + assertThat(retainedOperationAfterV50.intoMap()) + .containsExactlyEntriesOf(retainedOperationBeforeV50.intoMap()); + } + @Test void concurrentCanonicalIntentAndPolicyRetriesRecoverOneImmutableRequestRow() throws Exception { Fixture fixture = fixture(); @@ -1292,6 +1900,101 @@ private static CanonicalJoinScopeV2 v2Scope( "2026-10-03T00:00:00.1234567891Z"); } + private static CanonicalJoinScopeV2 timedV2Scope( + String token, + UUID accountUuid, + UUID tenantUuid, + String tenantSlug, + String evaluatedAt, + String expiresAt) { + return new CanonicalJoinScopeV2( + token, + accountUuid, + tenantUuid, + UUID.fromString("e2b33891-a9a6-4b6f-9c2a-a71f078570dc"), + tenantSlug, + "world-" + tenantSlug, + "production", + UUID.fromString("156fc510-d536-4974-a350-79fbd4d6a1bc"), + "SHARED", + UUID.fromString("7701a6e2-d178-4a3f-97c8-72130c685f4b"), + 8L, + 5L, + evaluatedAt, + expiresAt); + } + + private static Long insertSyntheticCanonicalActiveMembership( + Fixture fixture, + long accountId, + UUID tenantUuid, + UUID tenantSourceOperationId, + String tenantSourceDigest) { + return Objects.requireNonNull( + fixture + .transactionDsl() + .resultQuery( + "INSERT INTO account_tenant_membership " + + "(account_id, tenant_id, tenant_uuid, tenant_provenance_kind, " + + "tenant_source_operation_id, tenant_provenance_digest, " + + "gameplay_admission_allowed, lifecycle_state, membership_version, " + + "membership_authority_generation, authority_provenance) " + + "VALUES (?, NULL, ?, 'FRESH_GAME_DESIGN', ?, ?, TRUE, 'ACTIVE', 2, 1, " + + "'EXPLICIT_JOIN') RETURNING id", + accountId, + tenantUuid, + tenantSourceOperationId, + tenantSourceDigest) + .fetchOne(0, Long.class), + "Synthetic canonical membership insert must return its storage ID"); + } + + private static Map v1OperationProjection(DSLContext dsl, String requestId) { + Record row = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT request_id, account_id, tenant_id, verified_caller_binding, " + + "scope_token_hash, connect_scope_digest, world_slug, realm_slug, realm_id, " + + "playable_state_namespace_id, playable_state_scope, game_instance_id, " + + "catalog_revision, pointer_version, intent_digest_version, intent_digest, " + + "entitlement_version, allow_public_join, entitlement_authority_availability, " + + "caller_bound_authority_invalidated, request_digest_version, request_digest, " + + "last_attempt_failure_code, last_attempt_authority_availability, status, " + + "outcome, membership_id, outcome_membership_version, " + + "outcome_membership_authority_generation, created_at, updated_at " + + "FROM account_join_operations WHERE request_id = ?", + requestId), + "Expected retained V1 JOIN operation"); + return row.intoMap(); + } + + private static void assertTerminalJournalCheckRejectsNullField( + Fixture fixture, String assignment, String requestId) { + fixture + .setupDsl() + .execute( + "ALTER TABLE account_join_operations " + + "DISABLE TRIGGER account_join_operation_identity_guard"); + try { + assertThatThrownBy( + () -> + fixture + .setupDsl() + .execute( + "UPDATE account_join_operations SET " + + assignment + + " WHERE request_id = ?", + requestId)) + .isInstanceOf(DataAccessException.class); + } finally { + fixture + .setupDsl() + .execute( + "ALTER TABLE account_join_operations " + + "ENABLE TRIGGER account_join_operation_identity_guard"); + } + } + private static FreshTenantCreationEvidence freshTenantEvidence(UUID tenantUuid) { UUID requestId = UUID.randomUUID(); UUID operationId = UUID.randomUUID(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepositoryCanonicalTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepositoryCanonicalTest.java index 13fe40fe1a..fff4eb4495 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepositoryCanonicalTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepositoryCanonicalTest.java @@ -4,6 +4,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyNoInteractions; +import java.time.Instant; import java.util.UUID; import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; @@ -13,6 +14,31 @@ import org.springframework.transaction.support.TransactionSynchronizationManager; class AccountJoinOperationRepositoryCanonicalTest { + @Test + void reconciliationAttemptAtIntegerMaximumIsRejectedBeforeJournalAccess() { + DSLContext dsl = mock(DSLContext.class); + AccountJoinOperationRepository repository = + new AccountJoinOperationRepository(dsl, mock(AccountConnectScopeRepository.class)); + boolean wasTransactionActive = TransactionSynchronizationManager.isActualTransactionActive(); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy( + () -> + repository.recordCanonicalReconciliationAttempt( + "request-v2", + Integer.MAX_VALUE, + Integer.MAX_VALUE, + Instant.EPOCH, + "counter is capped", + Instant.EPOCH)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("JOIN reconciliation attempt count is outside its limit"); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(wasTransactionActive); + } + verifyNoInteractions(dsl); + } + @Test void canonicalIntentAndPolicyMethodsRequireOwnerTransactionBeforeReadingScopeOrJournal() { DSLContext dsl = mock(DSLContext.class); @@ -46,6 +72,25 @@ void canonicalIntentAndPolicyMethodsRequireOwnerTransactionBeforeReadingScopeOrJ .isInstanceOf(IllegalStateException.class) .hasMessage( "Canonical Account JOIN operation access requires an active owner transaction"); + assertThatThrownBy( + () -> repository.findDueCanonicalPendingReconciliation(Instant.now(), 10, 3)) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + "Canonical Account JOIN operation access requires an active owner transaction"); + assertThatThrownBy( + () -> + repository.recordCanonicalReconciliationAttempt( + "request-v2", 0, 3, Instant.now(), "scope unavailable", Instant.now())) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + "Canonical Account JOIN operation access requires an active owner transaction"); + assertThatThrownBy( + () -> + repository.finishCanonicalOperation( + "request-v2", "COMMITTED", "JOINED", 1L, 2L, 1L)) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + "Canonical Account JOIN operation access requires an active owner transaction"); assertThatThrownBy( () -> repository.bindCanonicalPolicyEvidence("request-v2", scope, "caller", true, 1L)) .isInstanceOf(IllegalStateException.class) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalJoinReconciliationServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalJoinReconciliationServiceTest.java new file mode 100644 index 0000000000..190a688aa6 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalJoinReconciliationServiceTest.java @@ -0,0 +1,530 @@ +package net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; +import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; +import net.firedevops.firemud.accountservice.dto.AccountAuditTenantIdentity; +import net.firedevops.firemud.accountservice.dto.CanonicalMembershipTransitionReceipt; +import net.firedevops.firemud.accountservice.dto.MembershipTransitionReceiptDigest; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; +import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Checkpoint; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository.CanonicalConnectScopeEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinOperationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinReconciliationCandidate; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; +import net.firedevops.firemud.accountservice.repository.AccountMembershipTransitionReceiptRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.SimpleTransactionStatus; + +class AccountCanonicalJoinReconciliationServiceTest { + private static final Instant NOW = Instant.parse("2026-10-03T03:00:00Z"); + private static final long ACCOUNT_ROW_ID = 101L; + private static final long MEMBERSHIP_ROW_ID = 501L; + private static final UUID ACCOUNT_UUID = UUID.fromString("f951c9e1-5854-45b6-955f-262df49b3d10"); + private static final UUID TENANT_UUID = UUID.fromString("8b5949df-8245-4cea-b740-910450fd37e5"); + private static final UUID REQUEST_UUID = UUID.fromString("f14f9e1e-f6d0-4473-9e14-529c08744dc2"); + private static final String REQUEST_ID = REQUEST_UUID.toString(); + private static final String WORLD_SLUG = "first-world"; + private static final String REALM_SLUG = "production"; + private static final String SHA = "sha256:" + "a".repeat(64); + private static final UUID TENANT_SOURCE_OPERATION = + UUID.fromString("47849617-e9da-4dcb-a638-754b26605bb7"); + private static final VerifiedTenantProvenance TENANT_PROVENANCE = + new VerifiedTenantProvenance( + null, TenantProvenanceKind.FRESH_GAME_DESIGN, TENANT_SOURCE_OPERATION, SHA); + + @Test + void canonicalAuditPayloadUsesExistingFieldsAndRequiresExactOneTenantVersionMap() { + String payload = + AccountAuditOutboxRepository.canonicalJoinPayload( + ACCOUNT_UUID, + TENANT_UUID, + WORLD_SLUG, + REALM_SLUG, + Map.of(TENANT_UUID.toString(), "2"), + REQUEST_ID); + + assertThat(payload) + .isEqualTo( + "{\"accountId\":\"" + + ACCOUNT_UUID + + "\",\"tenantId\":\"" + + TENANT_UUID + + "\",\"worldSlug\":\"first-world\",\"realmSlug\":\"production\"," + + "\"membershipVersion\":{\"" + + TENANT_UUID + + "\":\"2\"},\"requestId\":\"" + + REQUEST_ID + + "\"}"); + assertThatThrownBy( + () -> + AccountAuditOutboxRepository.canonicalJoinPayload( + ACCOUNT_UUID, TENANT_UUID, WORLD_SLUG, REALM_SLUG, Map.of(), REQUEST_ID)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountAuditOutboxRepository.canonicalJoinPayload( + ACCOUNT_UUID, + TENANT_UUID, + WORLD_SLUG, + REALM_SLUG, + Map.of(TENANT_UUID.toString(), "2", UUID.randomUUID().toString(), "3"), + REQUEST_ID)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void fullyProvedExpiredJoinSurvivesLaterUnavailableDiagnosticWithoutRewritingEvidence() { + Fixture fixture = new Fixture(); + CanonicalJoinOperationEvidence pending = pendingOperation(true, "UNAVAILABLE", "TIMEOUT"); + stubDue(fixture, pending); + stubPositiveEvidence(fixture, pending); + when(fixture.operations.finishCanonicalOperation( + REQUEST_ID, "COMMITTED", "JOINED", MEMBERSHIP_ROW_ID, 2L, 1L)) + .thenReturn(terminalOperation(pending)); + + fixture.service.reconcileDueOperations(NOW); + + verify(fixture.operations).lockAccount(ACCOUNT_ROW_ID); + verify(fixture.operations).findCanonicalEvidenceByRequestId(REQUEST_ID); + verify(fixture.operations) + .finishCanonicalOperation(REQUEST_ID, "COMMITTED", "JOINED", MEMBERSHIP_ROW_ID, 2L, 1L); + verify(fixture.operations, never()) + .recordCanonicalReconciliationAttempt( + anyString(), anyInt(), anyInt(), any(), anyString(), any()); + verify(fixture.memberships).findCanonicalMembershipForUpdate(ACCOUNT_UUID, TENANT_UUID); + verify(fixture.roleSnapshots) + .findForCanonicalUpdate( + ACCOUNT_UUID, TENANT_UUID, TENANT_PROVENANCE, MEMBERSHIP_ROW_ID, 2L); + verify(fixture.receipts).findCanonicalByRequestId(REQUEST_ID); + verify(fixture.audit).findCanonicalJoinEnvelopeForUpdate(fixture.auditEventId(), TENANT_UUID); + verify(fixture.eventProducer).requireCanonicalFirstJoinEvent(pending); + verify(fixture.memberships, never()).saveCanonical(any(), any(), any(), any()); + verify(fixture.roleSnapshots, never()) + .replaceCanonical(any(), any(), any(), any(), anyLong(), any()); + verify(fixture.receipts, never()) + .appendCanonicalTransition(any(), any(), anyString(), anyString()); + verify(fixture.audit, never()) + .appendCanonicalTenant(any(), anyString(), anyString(), anyString()); + } + + @Test + void absentMembershipRemainsPendingEvenWhenScopeExpired() { + Fixture fixture = new Fixture(); + CanonicalJoinOperationEvidence pending = pendingOperation(true, "AVAILABLE", null); + stubDue(fixture, pending); + when(fixture.operations.findCanonicalEvidenceByRequestId(REQUEST_ID)) + .thenReturn(Optional.of(pending)); + when(fixture.memberships.findCanonicalMembershipForUpdate(ACCOUNT_UUID, TENANT_UUID)) + .thenReturn(Optional.empty()); + when(fixture.operations.recordCanonicalReconciliationAttempt( + REQUEST_ID, 1, 3, NOW, "CANONICAL_MEMBERSHIP_ABSENT", NOW.plusMillis(5_000))) + .thenReturn(true); + + fixture.service.reconcileDueOperations(NOW); + + verify(fixture.operations) + .recordCanonicalReconciliationAttempt( + REQUEST_ID, 1, 3, NOW, "CANONICAL_MEMBERSHIP_ABSENT", NOW.plusMillis(5_000)); + verify(fixture.operations, never()) + .finishCanonicalOperation(anyString(), anyString(), anyString(), any(), any(), any()); + verifyNoInteractions( + fixture.roleSnapshots, fixture.receipts, fixture.audit, fixture.eventProducer); + } + + @Test + void absentReceiptOrAuditRemainsPendingWithoutCreatingDependentEvidence() { + Fixture receiptFixture = new Fixture(); + CanonicalJoinOperationEvidence pending = pendingOperation(true, "AVAILABLE", null); + stubDue(receiptFixture, pending); + AccountTenantMembership membership = activeMembership(); + when(receiptFixture.operations.findCanonicalEvidenceByRequestId(REQUEST_ID)) + .thenReturn(Optional.of(pending)); + when(receiptFixture.memberships.findCanonicalMembershipForUpdate(ACCOUNT_UUID, TENANT_UUID)) + .thenReturn(Optional.of(membership)); + when(receiptFixture.roleSnapshots.findForCanonicalUpdate( + ACCOUNT_UUID, TENANT_UUID, TENANT_PROVENANCE, MEMBERSHIP_ROW_ID, 2L)) + .thenReturn(Optional.of(roleSnapshot())); + when(receiptFixture.receipts.findCanonicalByRequestId(REQUEST_ID)).thenReturn(Optional.empty()); + when(receiptFixture.operations.recordCanonicalReconciliationAttempt( + REQUEST_ID, 1, 3, NOW, "CANONICAL_TRANSITION_RECEIPT_ABSENT", NOW.plusMillis(5_000))) + .thenReturn(true); + + receiptFixture.service.reconcileDueOperations(NOW); + + verify(receiptFixture.operations) + .recordCanonicalReconciliationAttempt( + REQUEST_ID, 1, 3, NOW, "CANONICAL_TRANSITION_RECEIPT_ABSENT", NOW.plusMillis(5_000)); + verify(receiptFixture.audit, never()).findCanonicalJoinEnvelopeForUpdate(any(), any()); + verify(receiptFixture.eventProducer, never()).requireCanonicalFirstJoinEvent(any()); + verify(receiptFixture.operations, never()) + .finishCanonicalOperation(anyString(), anyString(), anyString(), any(), any(), any()); + + Fixture auditFixture = new Fixture(); + stubDue(auditFixture, pending); + when(auditFixture.operations.findCanonicalEvidenceByRequestId(REQUEST_ID)) + .thenReturn(Optional.of(pending)); + AccountTenantMembership auditMembership = activeMembership(); + when(auditFixture.memberships.findCanonicalMembershipForUpdate(ACCOUNT_UUID, TENANT_UUID)) + .thenReturn(Optional.of(auditMembership)); + when(auditFixture.roleSnapshots.findForCanonicalUpdate( + ACCOUNT_UUID, TENANT_UUID, TENANT_PROVENANCE, MEMBERSHIP_ROW_ID, 2L)) + .thenReturn(Optional.of(roleSnapshot())); + when(auditFixture.receipts.findCanonicalByRequestId(REQUEST_ID)) + .thenReturn(Optional.of(transitionReceipt())); + when(auditFixture.audit.findCanonicalJoinEnvelopeForUpdate( + auditFixture.auditEventId(), TENANT_UUID)) + .thenReturn(Optional.empty()); + when(auditFixture.operations.recordCanonicalReconciliationAttempt( + REQUEST_ID, 1, 3, NOW, "CANONICAL_JOIN_AUDIT_ENVELOPE_ABSENT", NOW.plusMillis(5_000))) + .thenReturn(true); + + auditFixture.service.reconcileDueOperations(NOW); + + verify(auditFixture.eventProducer, never()).requireCanonicalFirstJoinEvent(any()); + verify(auditFixture.operations, never()) + .finishCanonicalOperation(anyString(), anyString(), anyString(), any(), any(), any()); + verify(auditFixture.receipts, never()) + .appendCanonicalTransition(any(), any(), anyString(), anyString()); + } + + @Test + void unavailablePolicyCannotBeReplacedByPositiveMembershipHistory() { + Fixture fixture = new Fixture(); + CanonicalJoinOperationEvidence pending = pendingOperation(false, "UNAVAILABLE", "TIMEOUT"); + stubDue(fixture, pending); + when(fixture.operations.findCanonicalEvidenceByRequestId(REQUEST_ID)) + .thenReturn(Optional.of(pending)); + when(fixture.operations.recordCanonicalReconciliationAttempt( + REQUEST_ID, + 1, + 3, + NOW, + "CANONICAL_JOIN_OPERATION_POLICY_UNPROVEN", + NOW.plusMillis(5_000))) + .thenReturn(true); + + fixture.service.reconcileDueOperations(NOW); + + verify(fixture.operations) + .recordCanonicalReconciliationAttempt( + REQUEST_ID, + 1, + 3, + NOW, + "CANONICAL_JOIN_OPERATION_POLICY_UNPROVEN", + NOW.plusMillis(5_000)); + verifyNoInteractions( + fixture.memberships, fixture.roleSnapshots, fixture.receipts, fixture.audit); + verify(fixture.eventProducer, never()).requireCanonicalFirstJoinEvent(any()); + verify(fixture.operations, never()) + .finishCanonicalOperation(anyString(), anyString(), anyString(), any(), any(), any()); + } + + @Test + void malformedScopeSourceCandidateRecordsDiagnosticAndDoesNotStarveLaterValidCandidate() { + Fixture fixture = new Fixture(); + CanonicalJoinOperationEvidence pending = pendingOperation(true, "AVAILABLE", null); + CanonicalJoinReconciliationCandidate malformedSource = + new CanonicalJoinReconciliationCandidate( + "missing-scope-source", ACCOUNT_ROW_ID, 1, NOW.minusSeconds(1)); + when(fixture.operations.findDueCanonicalPendingReconciliation(NOW, 10, 3)) + .thenReturn(List.of(malformedSource, candidate(pending))); + when(fixture.operations.findCanonicalEvidenceByRequestId("missing-scope-source")) + .thenThrow(new IllegalStateException("canonical scope source is absent")); + when(fixture.operations.recordCanonicalReconciliationAttempt( + "missing-scope-source", + 1, + 3, + NOW, + "CANONICAL_JOIN_READBACK_UNAVAILABLE", + NOW.plusMillis(5_000))) + .thenReturn(true); + stubPositiveEvidence(fixture, pending); + when(fixture.operations.finishCanonicalOperation( + REQUEST_ID, "COMMITTED", "JOINED", MEMBERSHIP_ROW_ID, 2L, 1L)) + .thenReturn(terminalOperation(pending)); + + fixture.service.reconcileDueOperations(NOW); + + verify(fixture.operations) + .recordCanonicalReconciliationAttempt( + "missing-scope-source", + 1, + 3, + NOW, + "CANONICAL_JOIN_READBACK_UNAVAILABLE", + NOW.plusMillis(5_000)); + verify(fixture.operations) + .finishCanonicalOperation(REQUEST_ID, "COMMITTED", "JOINED", MEMBERSHIP_ROW_ID, 2L, 1L); + } + + private static void stubDue(Fixture fixture, CanonicalJoinOperationEvidence operation) { + when(fixture.operations.findDueCanonicalPendingReconciliation(NOW, 10, 3)) + .thenReturn(List.of(candidate(operation))); + } + + private static CanonicalJoinReconciliationCandidate candidate( + CanonicalJoinOperationEvidence operation) { + return new CanonicalJoinReconciliationCandidate( + operation.requestId(), + operation.privateAccountId(), + operation.reconciliationAttemptCount(), + operation.nextReconciliationAttemptAt()); + } + + private static void stubPositiveEvidence( + Fixture fixture, CanonicalJoinOperationEvidence operation) { + when(fixture.operations.findCanonicalEvidenceByRequestId(REQUEST_ID)) + .thenReturn(Optional.of(operation)); + AccountTenantMembership membership = activeMembership(); + when(fixture.memberships.findCanonicalMembershipForUpdate(ACCOUNT_UUID, TENANT_UUID)) + .thenReturn(Optional.of(membership)); + when(fixture.roleSnapshots.findForCanonicalUpdate( + ACCOUNT_UUID, TENANT_UUID, TENANT_PROVENANCE, MEMBERSHIP_ROW_ID, 2L)) + .thenReturn(Optional.of(roleSnapshot())); + when(fixture.receipts.findCanonicalByRequestId(REQUEST_ID)) + .thenReturn(Optional.of(transitionReceipt())); + when(fixture.audit.findCanonicalJoinEnvelopeForUpdate(fixture.auditEventId(), TENANT_UUID)) + .thenReturn(Optional.of(auditEnvelope(operation))); + when(fixture.eventProducer.requireCanonicalFirstJoinEvent(operation)) + .thenReturn( + new Checkpoint( + "account:auth-authority:v1:membership/" + ACCOUNT_UUID + "/" + TENANT_UUID, + 1L, + "event-1", + SHA)); + } + + private static CanonicalJoinOperationEvidence pendingOperation( + boolean allowPublicJoin, String lastAvailability, String lastFailure) { + CanonicalConnectScopeEvidence scope = scopeEvidence(); + return new CanonicalJoinOperationEvidence( + REQUEST_ID, + ACCOUNT_ROW_ID, + "game-session:fixture", + scope.scopeTokenHash(), + scope.scopeDigest(), + 2, + 2, + 2, + SHA, + "AVAILABLE", + allowPublicJoin, + 19L, + 2, + SHA, + lastAvailability, + lastFailure, + false, + "PENDING", + null, + null, + null, + null, + 1, + NOW.minusSeconds(10), + "PREVIOUS_RECONCILIATION_ATTEMPT", + NOW.minusSeconds(1), + scope); + } + + private static CanonicalJoinOperationEvidence terminalOperation( + CanonicalJoinOperationEvidence pending) { + return new CanonicalJoinOperationEvidence( + pending.requestId(), + pending.privateAccountId(), + pending.callerBinding(), + pending.scopeTokenHash(), + pending.connectScopeDigest(), + pending.operationRepresentationVersion(), + pending.scopeDigestVersion(), + pending.intentDigestVersion(), + pending.intentDigest(), + pending.entitlementAuthorityAvailability(), + pending.allowPublicJoin(), + pending.entitlementVersion(), + pending.requestDigestVersion(), + pending.requestDigest(), + pending.lastAttemptAuthorityAvailability(), + pending.lastAttemptFailureCode(), + pending.callerBoundAuthorityInvalidated(), + "COMMITTED", + "JOINED", + MEMBERSHIP_ROW_ID, + 2L, + 1L, + pending.reconciliationAttemptCount(), + pending.lastReconciliationAttemptAt(), + pending.lastReconciliationAttemptReason(), + pending.nextReconciliationAttemptAt(), + pending.scopeEvidence()); + } + + private static CanonicalConnectScopeEvidence scopeEvidence() { + return new CanonicalConnectScopeEvidence( + SHA, + ACCOUNT_ROW_ID, + "PUBLIC_PRODUCTION", + ACCOUNT_UUID, + TENANT_UUID, + UUID.fromString("998a33ef-23d6-4dc6-8d5d-6fd53de34d67"), + "tenant-fixture", + WORLD_SLUG, + REALM_SLUG, + UUID.fromString("ba2c9d44-dfc0-4437-a13a-5f263f131f42"), + "SHARED", + UUID.fromString("88a13821-1569-43a6-9eba-dbecf93833c1"), + 7L, + 4L, + "2026-10-03T00:00:00Z", + "2026-10-03T01:00:00Z", + 2, + SHA, + TENANT_PROVENANCE); + } + + private static AccountTenantMembership activeMembership() { + Account account = mock(Account.class); + when(account.getId()).thenReturn(ACCOUNT_ROW_ID); + when(account.getAccountUuid()).thenReturn(ACCOUNT_UUID); + AccountTenantMembership membership = mock(AccountTenantMembership.class); + when(membership.getId()).thenReturn(MEMBERSHIP_ROW_ID); + when(membership.getAccount()).thenReturn(account); + when(membership.getTenantId()).thenReturn(null); + when(membership.getTenantUuid()).thenReturn(TENANT_UUID); + when(membership.getTenantProvenanceKind()) + .thenReturn(TenantProvenanceKind.FRESH_GAME_DESIGN.name()); + when(membership.getTenantSourceOperationId()).thenReturn(TENANT_SOURCE_OPERATION); + when(membership.getTenantProvenanceDigest()).thenReturn(SHA); + when(membership.isGameplayAdmissionAllowed()).thenReturn(true); + when(membership.getLifecycleState()).thenReturn("ACTIVE"); + when(membership.getMembershipVersion()).thenReturn(2L); + when(membership.getMembershipAuthorityGeneration()).thenReturn(1L); + when(membership.getAuthorityProvenance()).thenReturn("EXPLICIT_JOIN"); + return membership; + } + + private static RoleSnapshot roleSnapshot() { + return new RoleSnapshot( + ACCOUNT_ROW_ID, + null, + MEMBERSHIP_ROW_ID, + 2L, + List.of("player"), + ACCOUNT_UUID, + TENANT_UUID, + TENANT_PROVENANCE); + } + + private static CanonicalMembershipTransitionReceipt transitionReceipt() { + String streamKey = + MembershipTransitionReceiptDigest.receiptStreamKeyV2(ACCOUNT_UUID, TENANT_UUID); + return new CanonicalMembershipTransitionReceipt( + streamKey, + 1L, + MembershipTransitionReceiptDigest.receiptIdForRequestV2(REQUEST_ID), + SHA, + MembershipTransitionReceiptDigest.EVIDENCE_STATUS, + "MEMBERSHIP_JOINED", + REQUEST_ID, + ACCOUNT_UUID, + TENANT_UUID, + "ACTIVE", + true, + Map.of(TENANT_UUID.toString(), "2"), + 1L, + "EXPLICIT_JOIN", + TenantProvenanceKind.FRESH_GAME_DESIGN.name(), + TENANT_SOURCE_OPERATION, + SHA); + } + + private static AccountAuditEnvelope auditEnvelope(CanonicalJoinOperationEvidence operation) { + var scope = operation.scopeEvidence(); + String payload = + AccountAuditOutboxRepository.canonicalJoinPayload( + scope.accountUuid(), + scope.tenantUuid(), + scope.worldSlug(), + scope.realmSlug(), + Map.of(scope.tenantUuid().toString(), "2"), + operation.requestId()); + return new AccountAuditEnvelope( + UUID.nameUUIDFromBytes( + ("account-join-audit/v1:" + operation.requestId()).getBytes(StandardCharsets.UTF_8)), + "tenant", + AccountAuditTenantIdentity.canonicalTenantV2(scope.tenantUuid().toString()), + "account-service", + "ACCOUNT_JOINED_PUBLIC_PRODUCTION", + NOW.minusSeconds(60), + 1, + 1, + AccountAuditDigest.ofPayload(payload), + payload); + } + + private static final class Fixture { + private final AccountJoinOperationRepository operations = + mock(AccountJoinOperationRepository.class); + private final AccountTenantMembershipRepository memberships = + mock(AccountTenantMembershipRepository.class); + private final AccountTenantMembershipRoleSnapshotRepository roleSnapshots = + mock(AccountTenantMembershipRoleSnapshotRepository.class); + private final AccountMembershipTransitionReceiptRepository receipts = + mock(AccountMembershipTransitionReceiptRepository.class); + private final AccountAuditOutboxRepository audit = mock(AccountAuditOutboxRepository.class); + private final AccountMembershipAuthorityEventProducer eventProducer = + mock(AccountMembershipAuthorityEventProducer.class); + private final AccountCanonicalJoinReconciliationService service; + + private Fixture() { + PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class); + when(transactionManager.getTransaction(any(TransactionDefinition.class))) + .thenAnswer(invocation -> new SimpleTransactionStatus()); + service = + new AccountCanonicalJoinReconciliationService( + operations, + memberships, + roleSnapshots, + receipts, + audit, + eventProducer, + transactionManager, + 10, + 3, + 5_000); + } + + private UUID auditEventId() { + return UUID.nameUUIDFromBytes( + ("account-join-audit/v1:" + REQUEST_ID).getBytes(StandardCharsets.UTF_8)); + } + } +} From a0f4ee82dbb740ea741c83615bc13036ca9968e9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 22:45:35 +1300 Subject: [PATCH 07/13] Record canonical JOIN recovery boundary and executed launch proof --- design/project-management/ai-observations.md | 1 + .../game-authoring-publishing-and-activation.md | 2 +- .../implementation-tracking/player-access-and-session.md | 4 +++- .../implementation-tracking/world-runtime-and-movement.md | 2 +- 4 files changed, 6 insertions(+), 3 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 1705ed8719..2db846c00c 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -277,3 +277,4 @@ Entry format: - Context: exact CI37109999851 executed seven descriptor and eight World intake PostgreSQL cases. Three failed assertions expected jOOQ `DataAccessException`, while the Spring-managed DSL translated correctly rejected writes into `DataIntegrityViolationException`; the concurrent World failure arrived through its future. Raw-connection fixtures retained their different jOOQ boundary. - Outcome: the focused fixture correction preserves the descriptor's exact constraint and World's reservation message, SQL state and no-mutation assertions. Corrected runner execution remains required; local compilation or skipped PostgreSQL cases cannot prove the repaired assertions. - Expected pattern: inspect the actual cause chain and preserve the exact constraint or SQL-state rejection rather than accepting any database error, catching every runtime exception or weakening a production guard. Do not blindly replace exception types in raw-connection fixtures merely because the service-managed DSL translates them. + - `2026-10-03` verified follow-up: exact CI37111727823 at `73ab357d694618a56c65129394fd324b38ad652e` executed all seven descriptor and eight World intake PostgreSQL cases cleanly, plus thirteen descriptor and nine source-read physical mTLS cases. Independently parsed and rehashed raw XML confirms all 37 focused cases have zero skips, failures or errors. The aggregate run still failed on identified checks outside these four suites; focused success is not live deployment or enabled runtime proof. diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index 26588df83b..2aae6293dd 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -149,7 +149,7 @@ Lifecycle status/proof is also incomplete: artifact and Version epoch checks lac ### Launch, Activation, Cutover, and Termination -The prepared source-bound `ResolveLaunchDescriptor` producer claims `(targetNamespace, canonicalTenantId, controlPlaneRequestId)` before mutable template/version resolution and retains the exact authored-source request and successful result digests in its existing immutable descriptor family. Changed source, world, template or overrides cannot reuse that claim to select another release. `GetLaunchDescriptor` prepares exact readback for verified Game Session and World peers; the canonical request/result schema is owned by the [Game Design API contract](../../architecture/microservices/game-design-service/api-contracts.md#authored-source-bound-launch-descriptor-and-exact-readback). Shared codec/vector unit proof executes locally. The owner candidate also retains typed deterministic business denials in that same immutable request/outcome family, without fabricating descriptor or release IDs. Thirteen descriptor and nine source-read physical mTLS methods execute cleanly locally with production guards/handlers and mocked source producers; this is not database-to-socket or live creation proof. Exact CI37109999851 at `9447e0ef5` executed all seven descriptor PostgreSQL cases: six passed after the published metadata conversion correction, while one fixture expected jOOQ's exception instead of Spring's translated integrity exception from the correct database constraint. All thirteen descriptor socket cases passed in that runner; the separate nine source-read cases did not run after the preceding failed step. The bounded fixture correction passes local checks, but PostgreSQL skips do not prove its repaired assertions. Corrected complete runner execution remains required; the source-read step now runs independently of earlier test failures while retaining a failing job for any failed proof. World owner-local fresh intake/reservation/readback is a separate prepared prerequisite recorded in [World Runtime and Movement](./world-runtime-and-movement.md#current-status), not release publication or canonical content materialization. The descriptor freezes `versionId`, `scriptPatchVersion`, `runtimeFlags`, `generationConfigRevision`, Game Design's `versionStateEpoch`, `releaseBundleRef`, and approved replacement `remapSetId` where required. Runtime provisioning must consume that immutable descriptor rather than resolve mutable "latest" control-plane state mid-flight. Game Design also exposes `GetVersionState` and `CompareAndSetVersionState`, and persists approved remap sets through `CreateTemplateRemapSet`, `ApproveTemplateRemapSet`, and `GetTemplateRemapSet`. +The prepared source-bound `ResolveLaunchDescriptor` producer claims `(targetNamespace, canonicalTenantId, controlPlaneRequestId)` before mutable template/version resolution and retains the exact authored-source request and successful result digests in its existing immutable descriptor family. Changed source, world, template or overrides cannot reuse that claim to select another release. `GetLaunchDescriptor` prepares exact readback for verified Game Session and World peers; the canonical request/result schema is owned by the [Game Design API contract](../../architecture/microservices/game-design-service/api-contracts.md#authored-source-bound-launch-descriptor-and-exact-readback). Shared codec/vector unit proof executes locally. The owner candidate also retains typed deterministic business denials in that same immutable request/outcome family, without fabricating descriptor or release IDs. Thirteen descriptor and nine source-read physical mTLS methods execute cleanly locally with production guards/handlers and mocked source producers; this is not database-to-socket or live creation proof. Exact [CI37111727823](https://github.com/benhook1013/FireMUD/actions/runs/37111727823) at `73ab357d694618a56c65129394fd324b38ad652e` proves all seven descriptor PostgreSQL, thirteen descriptor physical mTLS and nine source-read physical mTLS cases executed cleanly with zero skips, failures or errors. Independently parsed raw XML confirms the repaired exact-constraint assertions; local PostgreSQL skips remain a separate limitation. The broader Game Design job failed at the already-routed duplicate tenant fixture in `EntityDigestBaselineMigrationIntegrationTest`, not these suites; aggregate success is not claimed. The source-read step runs independently of earlier ordinary test failures while retaining a failing job for any failed proof. World owner-local fresh intake/reservation/readback is a separate implemented but unwired prerequisite recorded in [World Runtime and Movement](./world-runtime-and-movement.md#current-status), not release publication or canonical content materialization. The descriptor freezes `versionId`, `scriptPatchVersion`, `runtimeFlags`, `generationConfigRevision`, Game Design's `versionStateEpoch`, `releaseBundleRef`, and approved replacement `remapSetId` where required. Runtime provisioning must consume that immutable descriptor rather than resolve mutable "latest" control-plane state mid-flight. Game Design also exposes `GetVersionState` and `CompareAndSetVersionState`, and persists approved remap sets through `CreateTemplateRemapSet`, `ApproveTemplateRemapSet`, and `GetTemplateRemapSet`. The candidate denies legacy numeric `StartSession` preflight and cutover descriptor lookup with `AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED`, before descriptor lookup or lifecycle/pointer/World mutation. There is no canonical source evidence in those requests, and no proved numeric World association; they must not be described as successful unpatched launch. Canonical Game Session orchestration and World durable source-bound `PREPARING` readback remain required before launch can proceed. The former numeric post-preflight preparation/activation, replacement, compensation and ambiguity branches are not proof of that canonical workflow; retained-instance stop/restart and independent lifecycle coverage remain useful but separate. Game Design denies any requested/template script patch because exact published-for-base and Automation `READY` evidence are unavailable. Game Session must independently re-check patch publication/base identity and join Automation's tenant runtime status before patched launch is enabled. The typed descriptor and launch-preflight failures include `TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED`, `INVALID_TEMPLATE_CONFIGURATION`, `SCRIPT_PATCH_OVERRIDE_CONFLICT`, `SCRIPT_PATCH_NOT_READY`, `RELEASE_BUNDLE_NOT_FOUND`, `RELEASE_ATTESTATION_MISMATCH`, `VERSION_STATE_EPOCH_STALE`, and `LAUNCH_REMAP_REQUIRED`. `SCRIPT_PATCH_NOT_READY` is containment, not readiness proof. Existing numeric World `PrepareWorldInstance`, activation and failed-preparation seams do not yet retain the canonical authored-source binding; their presence and earlier fixture results are not proof of the required UUID-qualified owner handoff. 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 fd1a77f8cd..1fd5a44662 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,7 +8,9 @@ This is a non-normative implementation tracker for player access and session. Ca Exact #2949 `996d99ca11c99c685fdef0dd35a859a25ce3fc8b` [CI37097862965](https://github.com/benhook1013/FireMUD/actions/runs/37097862965) completed with aggregate failure; its sole observer finished. Independently parsed and rehashed raw XML proves all 56 captured methods executed cleanly without skips: three Account audit, one retained-row migration, fifteen Logging receiver, one Logging migration, nine physical mTLS, and the prior 27 scope/receipt/catalog/CLOSED methods. The corrected malformed-row case rejects every invalid write at the exact constraint and proves no projection growth. Physical mTLS uses production peer extraction and handler code with ephemeral fixture PKI and a mocked receiver service; it does not prove an Account-to-Logging database workflow or deployment. Concrete tooling, Automation formatting and Game Design duplicate-tenant fixture failures remain separately owned; no aggregate success, activation or ring mount is claimed. -Canonical first-JOIN event publication is a separate owner-local prerequisite in preparation. It reads persisted UUID membership/roles, exact V2 pending intent and stored AVAILABLE policy after the Account fence, then commits the closed event/checkpoint and positive pair transition together without advancing caller authority or issuance fence. Its fixtures deliberately seed policy and source evidence; they do not prove authenticated entitlement, public JOIN, terminal outcome or recovery. Runtime paths remain denied until that complete composition is implemented and proved. +Canonical first-JOIN event publication and historical reconciliation are implemented as explicitly unwired Account-owned prerequisites. The event producer reads persisted UUID membership/roles, the exact V2 pending intent and stored AVAILABLE policy after the Account fence, then commits the closed event/checkpoint and positive pair transition together without advancing caller authority or issuance fence. V50 widens the existing immutable operation journal without rewriting retained V1 history. The bounded reconciler terminalizes only after exact operation, membership/roles, receipt, canonical one-tenant audit map and event/checkpoint readback prove the original committed first JOIN. An expired scope or later unavailable entitlement diagnostic does not erase that prior commit; missing, contradictory or unsupported evidence remains PENDING with bounded diagnostics, never a synthesized outcome or fresh authorization. Malformed source evidence cannot prevent independent candidates from being examined. The [Account API contract](../../architecture/microservices/account-service/api-contracts.md#canonical-uuid-join-evidence) owns the exact readback and audit boundary. + +The Account recovery batch passes the full local check, boot JAR, formatting, Checkstyle, SpotBugs, coverage, links and Markdown: 715 unit cases execute cleanly, including six new reconciler cases. All 276 Account integration nodes compile but skip locally without Docker, including four new reconciliation cases and the expanded four-case canonical journal suite. The workflow now requires the new terminal-journal case and all four reconciliation cases and captures both raw XML suites. These fixtures deliberately seed policy and source evidence; they do not prove authenticated entitlement, a public positive JOIN, database-to-transport composition or activation. Corrected-head PostgreSQL execution, complete authenticated current-target/entitlement evidence and the actual positive JOIN producer remain required. Runtime paths and the Account ring mount stay denied/unpublished. Exact #2949 `51bfdafda78ff1448ac753de867a5b3c73afd2e2` [CI37092681148](https://github.com/benhook1013/FireMUD/actions/runs/37092681148) finished with aggregate failure. All four required raw XML suites prove three canonical Account scope/intent, seven receipt, five catalog and twelve CLOSED-pointer methods actually executed cleanly, with zero skips, failures or errors. Independently parsed method lists and hashes prove the corrected receipt setup and all four new locked-origin cases on this composed tree. Account's broader integration check executed 265 cases with one failure: the retained-row migration fixture compared pre-V48 receipt metadata with a widened row. The correction compares every original field separately from the new unbridged metadata and still needs corrected-head PostgreSQL execution. Game Session's component proof and Gradle checks passed before coverage upload was cancelled; separately owned Python lint, Automation formatting, Game Design duplicate-tenant and dev-demo summary failures remain explicit. No watcher remains for this terminal run. This is not aggregate success, complete canonical JOIN, authenticated World handoff, live readiness or activation; local Docker skips below remain accurate local limits. diff --git a/design/project-management/implementation-tracking/world-runtime-and-movement.md b/design/project-management/implementation-tracking/world-runtime-and-movement.md index cd7929c36e..f9c33bd644 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for world runtime and movement. C ## Current Status -**Canonical launch prerequisite:** Current World design/materialization rows and `PrepareWorldInstance` still use World's private numeric tenant key. The candidate adds V23 and an explicitly unwired owner-local fresh-source intake service/repository: a complete authenticated Game Design `NEW_GAME_ROW` receipt, private World tenant association, numeric-key reservation and immutable intake receipt commit together, with exact independent readback. Legacy numeric writes cannot take a reserved canonical selector; existing legacy keys are reserved without inventing UUID associations. Shared source-client/codec and nine exact Game Design source-method socket tests pass locally using production transport and a mocked source repository, not the complete normal producer or database-to-socket path. Fifteen World digest/service unit cases execute cleanly; the eight PostgreSQL intake cases compile but skip locally without Docker, so transactional, migration and concurrency execution remains unproved locally. Exact CI37109999851 at `9447e0ef5` executed all eight intake PostgreSQL cases: six passed; two reached the correct reserved-selector rejection but failed on the fixture's jOOQ-versus-Spring exception assumption. The corrected insert/update/concurrent assertions retain the exact reservation message, SQL state `23514`, unchanged legacy row and no-region checks. Local affected checks pass; corrected runner execution remains required. Focused World/Game Session checks, static analysis and packaged JAR construction pass. The automatic normal Game Design registration/delivery producer, World RPC receiver, canonical-source-qualified content writer, actual content/descriptor/release readback and separate audited retained-World association remain required. The [World API contract](../../architecture/microservices/world-management-service/api-contracts.md#authenticated-authored-content-intake-and-tenant-association) owns this boundary. Numeric similarity, selectors and Account's migration manifest are not substitutes, and no runtime activation is authorized. +**Canonical launch prerequisite:** Current World design/materialization rows and `PrepareWorldInstance` still use World's private numeric tenant key. The candidate adds V23 and an explicitly unwired owner-local fresh-source intake service/repository: a complete authenticated Game Design `NEW_GAME_ROW` receipt, private World tenant association, numeric-key reservation and immutable intake receipt commit together, with exact independent readback. Legacy numeric writes cannot take a reserved canonical selector; existing legacy keys are reserved without inventing UUID associations. Shared source-client/codec and nine exact Game Design source-method socket tests pass locally using production transport and a mocked source repository, not the complete normal producer or database-to-socket path. Fifteen World digest/service unit cases execute cleanly; the eight PostgreSQL intake cases compile but skip locally without Docker. Exact [CI37111727823](https://github.com/benhook1013/FireMUD/actions/runs/37111727823) at `73ab357d694618a56c65129394fd324b38ad652e` proves all eight intake PostgreSQL cases and all nine source-read socket cases executed cleanly with zero skips, failures or errors. Independent raw-XML verification confirms the corrected insert/update/concurrent assertions retain the exact reservation message, SQL state `23514`, unchanged legacy row and no-region checks. World's full job passed; aggregate CI failed on separately identified Game Design fixture, Automation formatting and shared-tooling checks. Focused World/Game Session checks, static analysis and packaged JAR construction pass. The automatic normal Game Design registration/delivery producer, World RPC receiver, canonical-source-qualified content writer, actual content/descriptor/release readback and separate audited retained-World association remain required. The [World API contract](../../architecture/microservices/world-management-service/api-contracts.md#authenticated-authored-content-intake-and-tenant-association) owns this boundary. Numeric similarity, selectors and Account's migration manifest are not substitutes, and no runtime activation is authorized. The canonical launch correction must also supply genuinely fresh instance creation, not merely attach a UUID carrier to the legacy prepare call: Game Session's `game_instances.tenant_id` and World's lifecycle/topology tenant selectors remain required numeric fields on this tree. A fresh canonical catalog provides no numeric tenant alias. Widen the actual owner instance/lifecycle representation and source-qualified creation/readback together; adding a binding table while inventing a numeric tenant selector would not close this gate. Exact retained instance associations remain separately source-proved and cannot be inferred from the Game Session row number or an Account mapping. From 00285d5a9474a01970293d5a225ad0c63ce1a611 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 00:07:12 +1300 Subject: [PATCH 08/13] Add authenticated World intake transport and repair canonical JOIN proof --- .github/workflows/ci.yml | 50 ++ .../game-design-service/api-contracts.md | 2 +- .../world-management-service/api-contracts.md | 6 +- design/project-management/ai-observations.md | 5 + .../player-access-and-session.md | 4 +- .../world-runtime-and-movement.md | 6 +- .../v1/world_management_service.proto | 62 ++ .../AccountJoinOperationRepository.java | 46 +- ...icalJoinReconciliationIntegrationTest.java | 2 +- ...ScopeCanonicalIdentityIntegrationTest.java | 28 +- .../WorldAuthoredSourceIntakeClient.java | 213 ++++++ .../WorldAuthoredSourceIntakeGrpcCodec.java | 307 ++++++++ .../WorldAuthoredSourceIntakeClientTest.java | 296 ++++++++ ...orldAuthoredSourceIntakeGrpcCodecTest.java | 242 ++++++ .../world-management-service/build.gradle.kts | 2 + .../WorldAuthoredSourceIntakeGrpcService.java | 255 +++++++ .../WorldAuthoredSourceIntakeService.java | 76 +- ...thoredSourceIntakeMtlsIntegrationTest.java | 621 ++++++++++++++++ ...ldAuthoredSourceIntakeGrpcServiceTest.java | 438 +++++++++++ .../WorldAuthoredSourceIntakeMtlsTest.java | 695 ++++++++++++++++++ .../WorldAuthoredSourceIntakeServiceTest.java | 135 ++++ 21 files changed, 3453 insertions(+), 38 deletions(-) create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeGrpcCodec.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeClientTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeGrpcCodecTest.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeGrpcService.java create mode 100644 services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeMtlsIntegrationTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeGrpcServiceTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeMtlsTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7c6cadb649..e77f768ff2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1057,6 +1057,56 @@ jobs: if-no-files-found: warn retention-days: 7 + - name: Run World authored-source intake socket mTLS proof + if: ${{ !cancelled() && matrix.module == 'world-management-service' }} + run: | + ./gradlew :world-management-service:test \ + --tests net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeMtlsTest \ + -PfullCheck --no-build-cache --no-configuration-cache + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeMtlsTest \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeMtlsTest#sameNamespaceGameDesignIntakesThenReadsExactReceiptOverSocketMtls()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeMtlsTest#wrongWorkloadsAndWrongNamespaceAreDeniedBeforeDecodeOrOwnerAccess()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeMtlsTest#sharedCertificateWithoutWorkloadUriCannotReachOwner()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeMtlsTest#jwtOnlyAndPlaintextCallersFailAtThePhysicalTransportBoundary()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeMtlsTest#clientRejectsAResponseFromTheWrongAuthenticatedWorldServerIdentity()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeMtlsTest#changedEchoDigestAndUnknownFieldsAreRejectedAfterSocketResponse()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeMtlsTest#publicWireMessagesNeverContainWorldPrivateNumericTenantKey()' \ + world-management-service + + - name: Upload World authored-source intake socket proof results + if: ${{ always() && matrix.module == 'world-management-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: world-authored-source-intake-socket-proof-${{ github.sha }} + path: services/world-management-service/build/test-results/test/TEST-*WorldAuthoredSourceIntakeMtlsTest.xml + if-no-files-found: warn + retention-days: 7 + + - name: Run World authored-source intake PostgreSQL socket composition proof + if: ${{ !cancelled() && matrix.module == 'world-management-service' }} + run: | + ./gradlew :world-management-service:integrationTest \ + --tests net.firedevops.firemud.worldmanagement.WorldAuthoredSourceIntakeMtlsIntegrationTest \ + -PfullCheck --no-build-cache --no-configuration-cache + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite net.firedevops.firemud.worldmanagement.WorldAuthoredSourceIntakeMtlsIntegrationTest \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredSourceIntakeMtlsIntegrationTest#commitsFreshWorldOwnerReceiptThenReturnsExactReceiptOverAuthenticatedSocket()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredSourceIntakeMtlsIntegrationTest#reconcilesLostSuccessAcknowledgementWithExactRetryAndCommittedReadback()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredSourceIntakeMtlsIntegrationTest#deniesWrongWorkloadAndChangedBindingWithoutOwnerMutation()' \ + world-management-service + + - name: Upload World authored-source intake PostgreSQL socket composition results + if: ${{ always() && matrix.module == 'world-management-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: world-authored-source-intake-postgres-socket-proof-${{ github.sha }} + path: services/world-management-service/build/test-results/integrationTest/TEST-*WorldAuthoredSourceIntakeMtlsIntegrationTest.xml + if-no-files-found: warn + retention-days: 7 + - name: Run Game Session authored-world intake PostgreSQL component proof if: ${{ matrix.module == 'game-session-service' }} run: | diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 3b54615910..fe9b420f58 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -36,7 +36,7 @@ The owner claims `(targetNamespace, registrationRequestId)` and commits the tena Both digests are SHA-256 rendered as `sha256:` plus 64 lowercase hexadecimal digits over fixed-order UTF-8 segments with decimal byte-length `:` framing, as in the fresh-creation contract. The request preimage is `game-design-authored-world-source-request/v1`, namespace, registration request UUID, canonical tenant UUID, tenant slug, world slug and world display name. The evidence preimage is `game-design-authored-world-source-receipt/v1`, namespace, registration request UUID, operation UUID, request digest, canonical tenant UUID, tenant slug, world slug, world display name, canonical decimal source row ID, exact source game tenant key and provenance kind. No field, implicit normalization or unframed concatenation is omitted. Producer and consumer recompute both digests and share positive/changed-field vectors. -The readback request binds a distinct canonical non-nil read `requestId` to the exact source `operationId`, canonical tenant UUID and world slug; the closed response echoes that read identity separately from the original registration identity and carries the complete source evidence. Only the verified same-namespace Game Session workload may read it. The guard precedes owner data access, and the receiver authenticates Game Design rather than accepting a JWT service claim or digest alone. Missing or changed source, digest/echo/scope mismatch, wrong workload or namespace, and unknown wire fields fail closed. Exact committed readback returns the same source receipt without mutation; it is not a catalog enrollment result. +The readback request binds a distinct canonical non-nil read `requestId` to the exact source `operationId`, canonical tenant UUID and world slug; the closed response echoes that read identity separately from the original registration identity and carries the complete source evidence. Only the verified same-namespace Game Session and World workloads may read it for their respective catalog and [World intake](../world-management-service/api-contracts.md#authenticated-authored-content-intake-and-tenant-association) consequences. The guard precedes owner data access, and the receiver authenticates Game Design rather than accepting a JWT service claim or digest alone. Missing or changed source, digest/echo/scope mismatch, wrong workload or namespace, and unknown wire fields fail closed. Exact committed readback returns the same source receipt without mutation; it is not a catalog enrollment, released-content or admission result. **Implementation and activation boundary:** The source repository/codec/readback is a prerequisite candidate, not a protected product creator or a live catalog handoff. Normal official-hosted authoring remains subject to the Account-owned commit-bound creator/terms gate below, which cannot be replaced by the source transaction or a caller-supplied authorization flag. No new public creation route or catalog admission is enabled before its producer, receiver, owner authorization and negative proof pass. Retained Game Session tenant keys need a separate audited, Game Design-authenticated association and Game Session's own exact retained-row readback; Account's manifest and numeric/slug similarity cannot establish it. The [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md) owns the remaining implementation and proof. diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index e4a4d6c3aa..c4881a1ffe 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -255,6 +255,10 @@ The source-intake prerequisite is separate from released-content acceptance: `wo The request digest is SHA-256 over fixed-order UTF-8 segments with decimal byte-length `:` framing: `world-authored-source-intake-request/v1`, target namespace, intake request UUID, canonical tenant UUID, world slug, source operation UUID and source evidence digest. The owner-internal receipt digest uses the same framing over `world-authored-source-intake-receipt/v1`, target namespace, owner operation UUID, request digest, canonical tenant UUID, world slug, source operation UUID, source evidence digest and canonical decimal private local tenant key. UUIDs use canonical non-nil text, the private key is positive, and digests render as `sha256:` plus 64 lower-case hexadecimal characters. The source digest is verified against the complete original owner receipt, never accepted alone as authentication. A writable World owner transaction stores and exactly reads back the association and immutable receipt together; changed request/source/local association, absent or corrupt readback, and allocation over existing World state fail closed. This receipt is not released-content, descriptor, ACTIVE-state or admission proof. +The closed owner transport separates `IntakeAuthoredWorldSource` from non-mutating `ReadAuthoredWorldSourceIntake`. Both require the exact authenticated same-namespace Game Design workload before parsing or owner access, `schemaVersion=1`, the exact target namespace, canonical non-nil `intakeRequestId`, canonical tenant UUID, world slug, source operation UUID and expected source evidence digest. The read also supplies a distinct canonical non-nil `requestId`; it does not create an intake, re-read mutable source state, allocate a local selector or repair an association. An exact read succeeds only from the complete committed World receipt and association, matching every original binding. Missing, conflicting or corrupt evidence fails closed. + +The success response echoes the complete original intake binding and adds World's canonical non-nil `operationId`, original request digest and original owner-internal receipt digest; a read separately echoes its read request ID. Unknown fields, unsupported versions and changed echoes are rejected. The receiving Game Design client must authenticate World's exact same-namespace workload before transmitting the request, then recompute the original request digest and compare all request/source bindings before accepting the response. A response-only identity check cannot protect an intake mutation sent to the wrong workload. World's private local tenant key is never transmitted. Its receipt digest therefore remains an opaque World-authenticated attestation to the internally verified association, not a client-recomputable digest, released-content evidence or independent admission authority. A forwarded response or digest without authenticated World readback is insufficient. Transport proof alone does not enable normal creation, intake or canonical preparation; implementation and activation limits remain in the [World tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#current-status). + Retained World rows use a separate owner-approved, audited association operation, following the existing provenance-backed association pattern but binding World's exact retained-row evidence. World verifies and durably reads back that evidence and the one-to-one canonical association. Account's migration manifest, matching numeric keys, selector similarity and absent history are not World ownership proof. Unmapped, ambiguous or contradictory retained rows remain denied. This exceptional retained-data migration is not part of routine fresh intake, and no association is inferred or repaired during a launch retry. World reserves a fresh private selector durably with its canonical association. Every legacy numeric writer must fail closed rather than take that selector, including a concurrent writer with an older transaction snapshot; existing legacy selectors remain usable but cannot acquire a canonical association through numeric equality. Reservation and intake rollback together, and committed associations, reservations and receipts cannot be rewritten or deleted to make another binding appear valid. This reservation is not permission for a legacy content writer to populate canonical content: the canonical-source-qualified writer and its owner evidence remain separate prerequisites. @@ -299,7 +303,7 @@ Termination owner-set and registry-revision snapshot semantics are defined by [I Current implementation notes: -- The first canonical activation seam is now live for the `StartSession` path. +- Legacy numeric lifecycle commands remain separate owner-local seams. Game Session's current `StartSession` preflight rejects launches without the canonical authored-world binding before mutation; those commands are not proof of an enabled canonical launch or first-OPEN path. The [World tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#current-status) records the remaining handoff and activation gates. - World Management persists `world_instance`, `region_instance`, `zone_instance`, `room_instance`, and `room_instance_exit` rows keyed by `(tenantId, gameInstanceId)` and uses `lifecycle_epoch` as the current fence token for prepare/activate/fail/terminate transitions. - `world_event` is now runtime-owned and keyed by `(tenantId, gameInstanceId)` via `region_instance`, rather than hanging off template `region` rows. - `stopSession` now consumes `GetWorldInstanceLifecycle` + `TerminateWorldInstance` rather than the old ping-only shutdown path; Entity Management cleanup runs through `CleanupRuntimeInstance`, and World hard-deletes its own runtime rows (`world_event`, room exits, rooms, zones, regions) before reporting `TERMINATED`. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 2db846c00c..c6f16cf1c6 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -278,3 +278,8 @@ Entry format: - Outcome: the focused fixture correction preserves the descriptor's exact constraint and World's reservation message, SQL state and no-mutation assertions. Corrected runner execution remains required; local compilation or skipped PostgreSQL cases cannot prove the repaired assertions. - Expected pattern: inspect the actual cause chain and preserve the exact constraint or SQL-state rejection rather than accepting any database error, catching every runtime exception or weakening a production guard. Do not blindly replace exception types in raw-connection fixtures merely because the service-managed DSL translates them. - `2026-10-03` verified follow-up: exact CI37111727823 at `73ab357d694618a56c65129394fd324b38ad652e` executed all seven descriptor and eight World intake PostgreSQL cases cleanly, plus thirteen descriptor and nine source-read physical mTLS cases. Independently parsed and rehashed raw XML confirms all 37 focused cases have zero skips, failures or errors. The aggregate run still failed on identified checks outside these four suites; focused success is not live deployment or enabled runtime proof. + +- `2026-10-03`: Authenticate a mutation's receiver before releasing request bytes + - Context: the existing gRPC server-peer response interceptor validates the certificate only when response headers or content arrive. Integration inspection of the World intake client and its initial socket fixture found that the wrong authenticated server could receive the mutation before its response was rejected; that initial fixture was not executed. This response guard is not pre-send receiver authorization. + - Outcome: the unregistered World intake client now also checks the negotiated TLS peer through call credentials before releasing request metadata/body, retaining the response guard. All seven focused socket cases execute cleanly locally, including both wrong-server intake/read rejection with no owner interaction. The receiver service is mocked in that suite; it does not prove database composition, delivery or runtime activation. + - Expected pattern: for owner mutations, prove both denial of wrong-peer responses and that the wrong receiver never sees the owner request. Do not treat response rejection as evidence that no mutation was attempted. 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 1fd5a44662..d6fa32131e 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,11 +6,13 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +Published `a0f4ee82dbb740ea741c83615bc13036ca9968e9` [CI37114161961](https://github.com/benhook1013/FireMUD/actions/runs/37114161961) ended in terminal failure. Independently parsed raw XML shows the four canonical reconciliation methods all failed during fixture setup because the fixture username was 51 characters against the unchanged 50-character column. The four canonical journal methods had two passes and two failures: one bound `Boolean.class` as a SQL parameter in `fetchValue`, and one retained a V47 fixture expectation although V50 preserves an earlier AVAILABLE policy when a later UNAVAILABLE attempt records diagnostics. The follow-up shortens only the username, reads `resultQuery.fetchOne(0, Boolean.class)` without changing the query or guards, and migrates the fixture to V50 while asserting the original AVAILABLE policy remains intact and the operation stays PENDING. Corrected PostgreSQL execution remains required; the failed run proves neither correction. Positive JOIN production, authenticated current-target/entitlement evidence and complete runtime reconciliation remain open, and runtime paths and the Account ring mount remain denied/unpublished. + Exact #2949 `996d99ca11c99c685fdef0dd35a859a25ce3fc8b` [CI37097862965](https://github.com/benhook1013/FireMUD/actions/runs/37097862965) completed with aggregate failure; its sole observer finished. Independently parsed and rehashed raw XML proves all 56 captured methods executed cleanly without skips: three Account audit, one retained-row migration, fifteen Logging receiver, one Logging migration, nine physical mTLS, and the prior 27 scope/receipt/catalog/CLOSED methods. The corrected malformed-row case rejects every invalid write at the exact constraint and proves no projection growth. Physical mTLS uses production peer extraction and handler code with ephemeral fixture PKI and a mocked receiver service; it does not prove an Account-to-Logging database workflow or deployment. Concrete tooling, Automation formatting and Game Design duplicate-tenant fixture failures remain separately owned; no aggregate success, activation or ring mount is claimed. Canonical first-JOIN event publication and historical reconciliation are implemented as explicitly unwired Account-owned prerequisites. The event producer reads persisted UUID membership/roles, the exact V2 pending intent and stored AVAILABLE policy after the Account fence, then commits the closed event/checkpoint and positive pair transition together without advancing caller authority or issuance fence. V50 widens the existing immutable operation journal without rewriting retained V1 history. The bounded reconciler terminalizes only after exact operation, membership/roles, receipt, canonical one-tenant audit map and event/checkpoint readback prove the original committed first JOIN. An expired scope or later unavailable entitlement diagnostic does not erase that prior commit; missing, contradictory or unsupported evidence remains PENDING with bounded diagnostics, never a synthesized outcome or fresh authorization. Malformed source evidence cannot prevent independent candidates from being examined. The [Account API contract](../../architecture/microservices/account-service/api-contracts.md#canonical-uuid-join-evidence) owns the exact readback and audit boundary. -The Account recovery batch passes the full local check, boot JAR, formatting, Checkstyle, SpotBugs, coverage, links and Markdown: 715 unit cases execute cleanly, including six new reconciler cases. All 276 Account integration nodes compile but skip locally without Docker, including four new reconciliation cases and the expanded four-case canonical journal suite. The workflow now requires the new terminal-journal case and all four reconciliation cases and captures both raw XML suites. These fixtures deliberately seed policy and source evidence; they do not prove authenticated entitlement, a public positive JOIN, database-to-transport composition or activation. Corrected-head PostgreSQL execution, complete authenticated current-target/entitlement evidence and the actual positive JOIN producer remain required. Runtime paths and the Account ring mount stay denied/unpublished. +The corrected Account recovery-batch full local check, boot JAR, formatting, Checkstyle, SpotBugs, coverage, links and Markdown pass: 715 unit cases execute cleanly, including six reconciler cases. All 276 Account integration nodes compile but skip locally without Docker, including the four reconciliation cases and expanded four-case canonical journal suite. The final composed Core/Account/World gate also passes; matching Account results are reused rather than counted as new executions. The workflow requires the terminal-journal case and all four reconciliation cases and captures both raw XML suites. These fixtures deliberately seed policy and source evidence; they do not prove authenticated entitlement, a public positive JOIN, database-to-transport composition or activation. Corrected-head PostgreSQL execution, complete authenticated current-target/entitlement evidence and the actual positive JOIN producer remain required. Runtime paths and the Account ring mount stay denied/unpublished. Exact #2949 `51bfdafda78ff1448ac753de867a5b3c73afd2e2` [CI37092681148](https://github.com/benhook1013/FireMUD/actions/runs/37092681148) finished with aggregate failure. All four required raw XML suites prove three canonical Account scope/intent, seven receipt, five catalog and twelve CLOSED-pointer methods actually executed cleanly, with zero skips, failures or errors. Independently parsed method lists and hashes prove the corrected receipt setup and all four new locked-origin cases on this composed tree. Account's broader integration check executed 265 cases with one failure: the retained-row migration fixture compared pre-V48 receipt metadata with a widened row. The correction compares every original field separately from the new unbridged metadata and still needs corrected-head PostgreSQL execution. Game Session's component proof and Gradle checks passed before coverage upload was cancelled; separately owned Python lint, Automation formatting, Game Design duplicate-tenant and dev-demo summary failures remain explicit. No watcher remains for this terminal run. This is not aggregate success, complete canonical JOIN, authenticated World handoff, live readiness or activation; local Docker skips below remain accurate local limits. diff --git a/design/project-management/implementation-tracking/world-runtime-and-movement.md b/design/project-management/implementation-tracking/world-runtime-and-movement.md index f9c33bd644..ef0a6b4ff6 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -6,7 +6,11 @@ This is a non-normative implementation tracker for world runtime and movement. C ## Current Status -**Canonical launch prerequisite:** Current World design/materialization rows and `PrepareWorldInstance` still use World's private numeric tenant key. The candidate adds V23 and an explicitly unwired owner-local fresh-source intake service/repository: a complete authenticated Game Design `NEW_GAME_ROW` receipt, private World tenant association, numeric-key reservation and immutable intake receipt commit together, with exact independent readback. Legacy numeric writes cannot take a reserved canonical selector; existing legacy keys are reserved without inventing UUID associations. Shared source-client/codec and nine exact Game Design source-method socket tests pass locally using production transport and a mocked source repository, not the complete normal producer or database-to-socket path. Fifteen World digest/service unit cases execute cleanly; the eight PostgreSQL intake cases compile but skip locally without Docker. Exact [CI37111727823](https://github.com/benhook1013/FireMUD/actions/runs/37111727823) at `73ab357d694618a56c65129394fd324b38ad652e` proves all eight intake PostgreSQL cases and all nine source-read socket cases executed cleanly with zero skips, failures or errors. Independent raw-XML verification confirms the corrected insert/update/concurrent assertions retain the exact reservation message, SQL state `23514`, unchanged legacy row and no-region checks. World's full job passed; aggregate CI failed on separately identified Game Design fixture, Automation formatting and shared-tooling checks. Focused World/Game Session checks, static analysis and packaged JAR construction pass. The automatic normal Game Design registration/delivery producer, World RPC receiver, canonical-source-qualified content writer, actual content/descriptor/release readback and separate audited retained-World association remain required. The [World API contract](../../architecture/microservices/world-management-service/api-contracts.md#authenticated-authored-content-intake-and-tenant-association) owns this boundary. Numeric similarity, selectors and Account's migration manifest are not substitutes, and no runtime activation is authorized. +**Canonical launch prerequisite:** Current World design/materialization rows and `PrepareWorldInstance` still use World's private numeric tenant key. V23 and the explicitly unwired owner-local fresh-source intake service/repository persist complete authenticated Game Design `NEW_GAME_ROW` evidence, a private World tenant association, numeric-key reservation and immutable intake receipt together, with exact independent readback. Legacy numeric writes cannot take a reserved canonical selector; existing legacy keys are reserved without inventing UUID associations. Exact [CI37111727823](https://github.com/benhook1013/FireMUD/actions/runs/37111727823) at `73ab357d694618a56c65129394fd324b38ad652e` proves all eight intake PostgreSQL cases and nine Game Design source-read socket cases executed cleanly without skips. Independent raw-XML verification confirms the reservation rejection, SQL state `23514`, unchanged legacy row and no-region assertions. That prior checkpoint does not prove the newer World receiver. + +The newer transport is explicitly unregistered: closed shared codec/client, exact Game Design peer guard before decoding or owner access, exact namespace enforcement, and non-mutating committed-receipt readback. The client verifies World's exact workload before releasing requests, not merely before accepting replies. Seven physical socket cases execute cleanly locally with a mocked owner, including wrong-server intake/read rejection with no owner interaction. The full Core/Account/World gate, both affected boot JARs, formatting, static analysis, coverage and documentation checks pass; Core208 and World146 unit cases are clean. All eighteen World integration nodes compile but skip locally without Docker, including three new real World PostgreSQL-through-socket composition cases for committed readback, lost acknowledgement/exact retry and denial without mutation. Their upstream Game Design source answer is synthetic; even successful execution would not prove its producer or automatic delivery. CI strictly requires and captures both new socket suites. Corrected-head database composition execution and live deployment remain unproved. + +The automatic normal Game Design registration/delivery producer, canonical-source-qualified content writer, exact content/descriptor/release readback, separate audited retained-World association and canonical lifecycle composition remain required. The [World API contract](../../architecture/microservices/world-management-service/api-contracts.md#authenticated-authored-content-intake-and-tenant-association) owns this boundary. Numeric similarity, selectors and Account's migration manifest are not substitutes, and no runtime activation is authorized. The prior World full CI job passed while aggregate CI failed on identified Game Design fixture, Automation formatting and shared-tooling checks; no aggregate-green claim follows from focused proof. The canonical launch correction must also supply genuinely fresh instance creation, not merely attach a UUID carrier to the legacy prepare call: Game Session's `game_instances.tenant_id` and World's lifecycle/topology tenant selectors remain required numeric fields on this tree. A fresh canonical catalog provides no numeric tenant alias. Widen the actual owner instance/lifecycle representation and source-qualified creation/readback together; adding a binding table while inventing a numeric tenant selector would not close this gate. Exact retained instance associations remain separately source-proved and cannot be inferred from the Game Session row number or an Account mapping. diff --git a/protos/world-management/v1/world_management_service.proto b/protos/world-management/v1/world_management_service.proto index 8c182551ba..bdcd3ffff5 100644 --- a/protos/world-management/v1/world_management_service.proto +++ b/protos/world-management/v1/world_management_service.proto @@ -31,6 +31,68 @@ service WorldManagementService { rpc ApplyRoomAmbientStatePatch(ApplyRoomAmbientStatePatchRequest) returns (ApplyRoomAmbientStatePatchResponse); } +// Explicitly unwired authenticated authored-source intake boundary. This service remains separate +// from the runtime WorldManagementService until its caller and deployment path are authorized. +service WorldAuthoredSourceIntakeService { + rpc IntakeAuthoredWorldSource(IntakeAuthoredWorldSourceRequest) + returns (IntakeAuthoredWorldSourceResponse); + rpc ReadAuthoredWorldSourceIntake(ReadAuthoredWorldSourceIntakeRequest) + returns (ReadAuthoredWorldSourceIntakeResponse); +} + +message IntakeAuthoredWorldSourceRequest { + int32 schema_version = 1; + string target_namespace = 2; + string intake_request_id = 3; + string canonical_tenant_id = 4; + string world_slug = 5; + string source_operation_id = 6; + string expected_source_evidence_digest = 7; +} + +message IntakeAuthoredWorldSourceResponse { + int32 schema_version = 1; + string target_namespace = 2; + string intake_request_id = 3; + string canonical_tenant_id = 4; + string world_slug = 5; + string source_operation_id = 6; + string expected_source_evidence_digest = 7; + string operation_id = 8; + // Recomputable from the echoed intake binding using the World request digest contract. + string request_digest = 9; + // Opaque authenticated World attestation; it binds private World state and is not client-recomputable. + string receipt_digest = 10; +} + +message ReadAuthoredWorldSourceIntakeRequest { + int32 schema_version = 1; + string target_namespace = 2; + // A distinct nonnil identity for this read; intake_request_id remains the stored receipt key. + string request_id = 3; + string intake_request_id = 4; + string canonical_tenant_id = 5; + string world_slug = 6; + string source_operation_id = 7; + string expected_source_evidence_digest = 8; +} + +message ReadAuthoredWorldSourceIntakeResponse { + int32 schema_version = 1; + string target_namespace = 2; + string request_id = 3; + string intake_request_id = 4; + string canonical_tenant_id = 5; + string world_slug = 6; + string source_operation_id = 7; + string expected_source_evidence_digest = 8; + string operation_id = 9; + // Recomputable from the echoed intake binding using the World request digest contract. + string request_digest = 10; + // Opaque authenticated World attestation; it binds private World state and is not client-recomputable. + string receipt_digest = 11; +} + enum WorldInstanceLifecycleStatus { WORLD_INSTANCE_LIFECYCLE_STATUS_UNSPECIFIED = 0; WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING = 1; diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java index 85a44fcc23..49621a4e23 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java @@ -995,29 +995,29 @@ private boolean canonicalMembershipMatches( Long membershipAuthorityGeneration) { var provenance = operation.scopeEvidence().tenantProvenance(); return Boolean.TRUE.equals( - dsl.fetchValue( - "SELECT EXISTS (SELECT 1 FROM account_tenant_membership membership " - + "WHERE membership.id = ? AND membership.account_id = ? " - + "AND membership.tenant_id IS NOT DISTINCT FROM ? " - + "AND membership.tenant_uuid = ? " - + "AND membership.tenant_provenance_kind = ? " - + "AND membership.tenant_source_operation_id = ? " - + "AND membership.tenant_provenance_digest = ? " - + "AND membership.lifecycle_state = 'ACTIVE' " - + "AND membership.gameplay_admission_allowed IS TRUE " - + "AND membership.membership_version = ? " - + "AND membership.membership_authority_generation = ? " - + "AND membership.authority_provenance = 'EXPLICIT_JOIN')", - Boolean.class, - membershipId, - operation.privateAccountId(), - provenance.legacyTenantId(), - operation.scopeEvidence().tenantUuid(), - provenance.kind().name(), - provenance.sourceOperationId(), - provenance.digest(), - membershipVersion, - membershipAuthorityGeneration)); + dsl.resultQuery( + "SELECT EXISTS (SELECT 1 FROM account_tenant_membership membership " + + "WHERE membership.id = ? AND membership.account_id = ? " + + "AND membership.tenant_id IS NOT DISTINCT FROM ? " + + "AND membership.tenant_uuid = ? " + + "AND membership.tenant_provenance_kind = ? " + + "AND membership.tenant_source_operation_id = ? " + + "AND membership.tenant_provenance_digest = ? " + + "AND membership.lifecycle_state = 'ACTIVE' " + + "AND membership.gameplay_admission_allowed IS TRUE " + + "AND membership.membership_version = ? " + + "AND membership.membership_authority_generation = ? " + + "AND membership.authority_provenance = 'EXPLICIT_JOIN')", + membershipId, + operation.privateAccountId(), + provenance.legacyTenantId(), + operation.scopeEvidence().tenantUuid(), + provenance.kind().name(), + provenance.sourceOperationId(), + provenance.digest(), + membershipVersion, + membershipAuthorityGeneration) + .fetchOne(0, Boolean.class)); } private static void requireCanonicalTerminalShape( diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCanonicalJoinReconciliationIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCanonicalJoinReconciliationIntegrationTest.java index 6b6bd21548..df9b14fd0c 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCanonicalJoinReconciliationIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCanonicalJoinReconciliationIntegrationTest.java @@ -406,7 +406,7 @@ private AccountFixture accountFixture() { Objects.requireNonNull( dsl.resultQuery( "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) RETURNING id", - "canonical-reconcile-" + suffix, + "canon-rec-" + suffix, "canonical-reconcile-" + suffix + "@example.test", "synthetic-fixture-hash") .fetchOne(0, Long.class)); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountConnectScopeCanonicalIdentityIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountConnectScopeCanonicalIdentityIntegrationTest.java index 87503db94d..a84176d538 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountConnectScopeCanonicalIdentityIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountConnectScopeCanonicalIdentityIntegrationTest.java @@ -449,6 +449,7 @@ void canonicalJoinJournalSharesRequestIdsAndRetainsPendingHashOnlyIntentEvidence scopeRepository(fixture).freshTenantIdentities().importVerified(tenantEvidence)); flyway(fixture.dataSource(), fixture.schema(), "46").migrate(); flyway(fixture.dataSource(), fixture.schema(), "47").migrate(); + flyway(fixture.dataSource(), fixture.schema(), "50").migrate(); AccountConnectScopeRepository scopes = scopeRepository(fixture).scopes(); VerifiedTenantProvenance tenantProvenance = @@ -629,15 +630,24 @@ public void afterCommit() { operations.bindCanonicalPolicyEvidence( requestId, scope, callerBinding, true, 10L))) .isInstanceOf(AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class); - assertThatThrownBy( - () -> - fixture - .transaction() - .execute( - status -> - operations.recordCanonicalPolicyUnavailable( - requestId, scope, callerBinding, "ENTITLEMENT_UNAVAILABLE"))) - .isInstanceOf(AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class); + CanonicalJoinOperationEvidence laterUnavailableAttempt = + fixture + .transaction() + .execute( + status -> + operations.recordCanonicalPolicyUnavailable( + requestId, scope, callerBinding, "ENTITLEMENT_UNAVAILABLE")); + assertThat(laterUnavailableAttempt.status()).isEqualTo("PENDING"); + assertThat(laterUnavailableAttempt.outcome()).isNull(); + assertThat(laterUnavailableAttempt.membershipId()).isNull(); + assertThat(laterUnavailableAttempt.entitlementAuthorityAvailability()).isEqualTo("AVAILABLE"); + assertThat(laterUnavailableAttempt.allowPublicJoin()).isTrue(); + assertThat(laterUnavailableAttempt.entitlementVersion()).isEqualTo(9L); + assertThat(laterUnavailableAttempt.requestDigestVersion()).isEqualTo(2); + assertThat(laterUnavailableAttempt.requestDigest()).isEqualTo(expectedPolicyDigest); + assertThat(laterUnavailableAttempt.lastAttemptAuthorityAvailability()).isEqualTo("UNAVAILABLE"); + assertThat(laterUnavailableAttempt.lastAttemptFailureCode()) + .isEqualTo("ENTITLEMENT_UNAVAILABLE"); String unavailableRequestId = "canonical-join-policy-unavailable"; fixture diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeClient.java new file mode 100644 index 0000000000..05190c81df --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeClient.java @@ -0,0 +1,213 @@ +package net.firedevops.firemud.common.tenant; + +import io.grpc.CallCredentials; +import io.grpc.Grpc; +import io.grpc.ManagedChannel; +import io.grpc.Metadata; +import io.grpc.Status; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.Executor; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.worldmanagement.v1.WorldAuthoredSourceIntakeServiceGrpc; + +/** Explicit mTLS client for World's authenticated authored-source intake and exact readback. */ +public final class WorldAuthoredSourceIntakeClient + extends AbstractReloadingBlockingGrpcClient< + WorldAuthoredSourceIntakeServiceGrpc.WorldAuthoredSourceIntakeServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public WorldAuthoredSourceIntakeClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + WorldAuthoredSourceIntakeClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes only when an owning service explicitly starts this client. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("World authored-source intake client is closed"); + } + if (initialized) { + return; + } + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException( + "World authored-source intake client did not initialize a gRPC stub"); + } + initialized = true; + } + + /** Sends one bounded intake request; transport failures are never retried blindly. */ + public WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt intake( + WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest request) { + Objects.requireNonNull(request, "request"); + requireNamespace(request.targetNamespace()); + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .intakeAuthoredWorldSource(WorldAuthoredSourceIntakeGrpcCodec.toIntakeRequest(request)); + try { + return WorldAuthoredSourceIntakeGrpcCodec.fromIntakeResponse(request, response); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "World returned an invalid authored-source intake receipt", exception); + } + } + + /** Reads one exact committed World receipt with its separate caller-owned read identity. */ + public WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt read( + WorldAuthoredSourceIntakeGrpcCodec.ReadRequest request) { + Objects.requireNonNull(request, "request"); + requireNamespace(request.binding().targetNamespace()); + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readAuthoredWorldSourceIntake( + WorldAuthoredSourceIntakeGrpcCodec.toReadRequest(request)); + try { + return WorldAuthoredSourceIntakeGrpcCodec.fromReadResponse(request, response); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "World returned an invalid authored-source intake readback", exception); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getWorldManagementService(); + } + + @Override + protected String defaultTarget() { + return "world-management-service:6565"; + } + + @Override + protected WorldAuthoredSourceIntakeServiceGrpc.WorldAuthoredSourceIntakeServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedWorldPeerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service"; + return WorldAuthoredSourceIntakeServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new ExactWorldServerCallCredentials(expectedWorldPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedWorldPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private WorldAuthoredSourceIntakeServiceGrpc.WorldAuthoredSourceIntakeServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "World authored-source intake client is not initialized and available"); + } + return currentStub; + } + + private void requireNamespace(String targetNamespace) { + if (!workloadNamespace.equals(targetNamespace)) { + throw new IllegalArgumentException( + "World authored-source intake request must use the configured workload namespace"); + } + } + + /** Authenticates the negotiated server before gRPC releases request headers or body. */ + private static final class ExactWorldServerCallCredentials extends CallCredentials { + private final String expectedPeerUri; + + private ExactWorldServerCallCredentials(String expectedPeerUri) { + this.expectedPeerUri = expectedPeerUri; + } + + @Override + public void applyRequestMetadata( + CallCredentials.RequestInfo requestInfo, + Executor appExecutor, + CallCredentials.MetadataApplier applier) { + var sslSession = + requestInfo == null || requestInfo.getTransportAttrs() == null + ? null + : requestInfo.getTransportAttrs().get(Grpc.TRANSPORT_ATTR_SSL_SESSION); + boolean exactPeer = + GrpcPeerIdentity.fromSslSession(sslSession) + .map(peer -> expectedPeerUri.equals(peer.uri())) + .orElse(false); + if (!exactPeer) { + applier.fail( + Status.UNAUTHENTICATED.withDescription( + "World intake requires the exact authenticated World workload identity")); + return; + } + applier.apply(new Metadata()); + } + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null) { + throw new IllegalArgumentException("gRPC mTLS configuration is required"); + } + if (tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("World authored-source intake requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "World authored-source intake requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "World authored-source intake requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException exception) { + throw new IllegalArgumentException( + "World authored-source intake " + label + " must be a readable file-backed path", + exception); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "World authored-source intake " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeGrpcCodec.java new file mode 100644 index 0000000000..577ccff3c1 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeGrpcCodec.java @@ -0,0 +1,307 @@ +package net.firedevops.firemud.common.tenant; + +import com.google.protobuf.Message; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceRequest; +import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeResponse; + +/** Closed request mapping and exact echo validation for the World authored-source intake RPCs. */ +public final class WorldAuthoredSourceIntakeGrpcCodec { + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String REQUEST_DIGEST_DOMAIN = "world-authored-source-intake-request/v1"; + + /** Complete canonical binding accepted by intake and echoed by both World RPCs. */ + public record IntakeRequest( + int schemaVersion, + String targetNamespace, + UUID intakeRequestId, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String expectedSourceEvidenceDigest) { + public IntakeRequest { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported World authored-source intake version"); + } + requireNonNil(intakeRequestId, "intakeRequestId"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(sourceOperationId, "sourceOperationId"); + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requireDigest(expectedSourceEvidenceDigest, "expectedSourceEvidenceDigest"); + } + } + + /** A committed World receipt read using a distinct request identity and the full intake tuple. */ + public record ReadRequest(IntakeRequest binding, UUID requestId) { + public ReadRequest { + Objects.requireNonNull(binding, "binding"); + requireNonNil(requestId, "requestId"); + if (requestId.equals(binding.intakeRequestId())) { + throw new IllegalArgumentException("Read requestId must differ from intakeRequestId"); + } + } + } + + /** Public receipt fields. receiptDigest is opaque because it also binds World's private key. */ + public record CommittedReceipt( + int schemaVersion, + String targetNamespace, + UUID intakeRequestId, + UUID operationId, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String sourceEvidenceDigest, + String requestDigest, + String receiptDigest) { + public CommittedReceipt { + IntakeRequest binding = + new IntakeRequest( + schemaVersion, + targetNamespace, + intakeRequestId, + canonicalTenantId, + worldSlug, + sourceOperationId, + sourceEvidenceDigest); + requireNonNil(operationId, "operationId"); + requireDigest(requestDigest, "requestDigest"); + requireDigest(receiptDigest, "receiptDigest"); + if (!WorldAuthoredSourceIntakeGrpcCodec.requestDigest(binding).equals(requestDigest)) { + throw new IllegalArgumentException("World intake requestDigest does not match its binding"); + } + } + } + + private WorldAuthoredSourceIntakeGrpcCodec() {} + + /** Encodes exactly the validated original intake binding. */ + public static IntakeAuthoredWorldSourceRequest toIntakeRequest(IntakeRequest request) { + Objects.requireNonNull(request, "request"); + return IntakeAuthoredWorldSourceRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setIntakeRequestId(request.intakeRequestId().toString()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setWorldSlug(request.worldSlug()) + .setSourceOperationId(request.sourceOperationId().toString()) + .setExpectedSourceEvidenceDigest(request.expectedSourceEvidenceDigest()) + .build(); + } + + /** Encodes the full intake binding and the caller-owned read request identity. */ + public static ReadAuthoredWorldSourceIntakeRequest toReadRequest(ReadRequest request) { + Objects.requireNonNull(request, "request"); + IntakeRequest binding = request.binding(); + return ReadAuthoredWorldSourceIntakeRequest.newBuilder() + .setSchemaVersion(binding.schemaVersion()) + .setTargetNamespace(binding.targetNamespace()) + .setRequestId(request.requestId().toString()) + .setIntakeRequestId(binding.intakeRequestId().toString()) + .setCanonicalTenantId(binding.canonicalTenantId().toString()) + .setWorldSlug(binding.worldSlug()) + .setSourceOperationId(binding.sourceOperationId().toString()) + .setExpectedSourceEvidenceDigest(binding.expectedSourceEvidenceDigest()) + .build(); + } + + /** Decodes the complete closed intake request before any owner access. */ + public static IntakeRequest fromIntakeRequest(IntakeAuthoredWorldSourceRequest request) { + Objects.requireNonNull(request, "request"); + requireNoUnknownFields(request, "IntakeAuthoredWorldSource request"); + return new IntakeRequest( + request.getSchemaVersion(), + request.getTargetNamespace(), + parseCanonicalNonNilUuid(request.getIntakeRequestId(), "intakeRequestId"), + parseCanonicalNonNilUuid(request.getCanonicalTenantId(), "canonicalTenantId"), + request.getWorldSlug(), + parseCanonicalNonNilUuid(request.getSourceOperationId(), "sourceOperationId"), + request.getExpectedSourceEvidenceDigest()); + } + + /** Decodes a closed exact-read request; requestId belongs only to the read itself. */ + public static ReadRequest fromReadRequest(ReadAuthoredWorldSourceIntakeRequest request) { + Objects.requireNonNull(request, "request"); + requireNoUnknownFields(request, "ReadAuthoredWorldSourceIntake request"); + IntakeRequest binding = + new IntakeRequest( + request.getSchemaVersion(), + request.getTargetNamespace(), + parseCanonicalNonNilUuid(request.getIntakeRequestId(), "intakeRequestId"), + parseCanonicalNonNilUuid(request.getCanonicalTenantId(), "canonicalTenantId"), + request.getWorldSlug(), + parseCanonicalNonNilUuid(request.getSourceOperationId(), "sourceOperationId"), + request.getExpectedSourceEvidenceDigest()); + return new ReadRequest(binding, parseCanonicalNonNilUuid(request.getRequestId(), "requestId")); + } + + /** Encodes only a fully validated committed receipt and its exact original request binding. */ + public static IntakeAuthoredWorldSourceResponse toIntakeResponse( + IntakeRequest request, CommittedReceipt receipt) { + requireExactBinding(request, receipt); + return IntakeAuthoredWorldSourceResponse.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setIntakeRequestId(request.intakeRequestId().toString()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setWorldSlug(request.worldSlug()) + .setSourceOperationId(request.sourceOperationId().toString()) + .setExpectedSourceEvidenceDigest(request.expectedSourceEvidenceDigest()) + .setOperationId(receipt.operationId().toString()) + .setRequestDigest(receipt.requestDigest()) + .setReceiptDigest(receipt.receiptDigest()) + .build(); + } + + /** Encodes a fully validated committed receipt and echoes the distinct read identity. */ + public static ReadAuthoredWorldSourceIntakeResponse toReadResponse( + ReadRequest request, CommittedReceipt receipt) { + Objects.requireNonNull(request, "request"); + requireExactBinding(request.binding(), receipt); + return ReadAuthoredWorldSourceIntakeResponse.newBuilder() + .setSchemaVersion(request.binding().schemaVersion()) + .setTargetNamespace(request.binding().targetNamespace()) + .setRequestId(request.requestId().toString()) + .setIntakeRequestId(request.binding().intakeRequestId().toString()) + .setCanonicalTenantId(request.binding().canonicalTenantId().toString()) + .setWorldSlug(request.binding().worldSlug()) + .setSourceOperationId(request.binding().sourceOperationId().toString()) + .setExpectedSourceEvidenceDigest(request.binding().expectedSourceEvidenceDigest()) + .setOperationId(receipt.operationId().toString()) + .setRequestDigest(receipt.requestDigest()) + .setReceiptDigest(receipt.receiptDigest()) + .build(); + } + + /** Validates all echoed request fields and the public, owner-authenticated receipt fields. */ + public static CommittedReceipt fromIntakeResponse( + IntakeRequest request, IntakeAuthoredWorldSourceResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "IntakeAuthoredWorldSource response"); + IntakeRequest echoed = + new IntakeRequest( + response.getSchemaVersion(), + response.getTargetNamespace(), + parseCanonicalNonNilUuid(response.getIntakeRequestId(), "intakeRequestId"), + parseCanonicalNonNilUuid(response.getCanonicalTenantId(), "canonicalTenantId"), + response.getWorldSlug(), + parseCanonicalNonNilUuid(response.getSourceOperationId(), "sourceOperationId"), + response.getExpectedSourceEvidenceDigest()); + if (!request.equals(echoed)) { + throw new IllegalArgumentException("World intake response does not echo the exact request"); + } + return new CommittedReceipt( + echoed.schemaVersion(), + echoed.targetNamespace(), + echoed.intakeRequestId(), + parseCanonicalNonNilUuid(response.getOperationId(), "operationId"), + echoed.canonicalTenantId(), + echoed.worldSlug(), + echoed.sourceOperationId(), + echoed.expectedSourceEvidenceDigest(), + response.getRequestDigest(), + response.getReceiptDigest()); + } + + /** Validates the separate read identity, full original binding, and committed receipt. */ + public static CommittedReceipt fromReadResponse( + ReadRequest request, ReadAuthoredWorldSourceIntakeResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "ReadAuthoredWorldSourceIntake response"); + IntakeRequest echoed = + new IntakeRequest( + response.getSchemaVersion(), + response.getTargetNamespace(), + parseCanonicalNonNilUuid(response.getIntakeRequestId(), "intakeRequestId"), + parseCanonicalNonNilUuid(response.getCanonicalTenantId(), "canonicalTenantId"), + response.getWorldSlug(), + parseCanonicalNonNilUuid(response.getSourceOperationId(), "sourceOperationId"), + response.getExpectedSourceEvidenceDigest()); + UUID echoedRequestId = parseCanonicalNonNilUuid(response.getRequestId(), "requestId"); + if (!request.binding().equals(echoed) || !request.requestId().equals(echoedRequestId)) { + throw new IllegalArgumentException( + "World intake read response does not echo the exact request"); + } + return new CommittedReceipt( + echoed.schemaVersion(), + echoed.targetNamespace(), + echoed.intakeRequestId(), + parseCanonicalNonNilUuid(response.getOperationId(), "operationId"), + echoed.canonicalTenantId(), + echoed.worldSlug(), + echoed.sourceOperationId(), + echoed.expectedSourceEvidenceDigest(), + response.getRequestDigest(), + response.getReceiptDigest()); + } + + /** Recomputable request digest defined by the World intake contract. */ + public static String requestDigest(IntakeRequest request) { + Objects.requireNonNull(request, "request"); + return GameTenantCreationDigest.digest( + REQUEST_DIGEST_DOMAIN, + request.targetNamespace(), + request.intakeRequestId().toString(), + request.canonicalTenantId().toString(), + request.worldSlug(), + request.sourceOperationId().toString(), + request.expectedSourceEvidenceDigest()); + } + + private static void requireExactBinding(IntakeRequest request, CommittedReceipt receipt) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(receipt, "receipt"); + if (receipt.schemaVersion() != request.schemaVersion() + || !receipt.targetNamespace().equals(request.targetNamespace()) + || !receipt.intakeRequestId().equals(request.intakeRequestId()) + || !receipt.canonicalTenantId().equals(request.canonicalTenantId()) + || !receipt.worldSlug().equals(request.worldSlug()) + || !receipt.sourceOperationId().equals(request.sourceOperationId()) + || !receipt.sourceEvidenceDigest().equals(request.expectedSourceEvidenceDigest()) + || !receipt.requestDigest().equals(requestDigest(request))) { + throw new IllegalArgumentException( + "World committed receipt does not match the exact request"); + } + } + + private static void requireNoUnknownFields(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(label + " contains unsupported fields"); + } + } + + private static UUID parseCanonicalNonNilUuid(String value, String label) { + if (value == null) { + throw new IllegalArgumentException("Canonical nonnil " + label + " is required"); + } + UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Canonical nonnil " + label + " is required", exception); + } + requireNonNil(parsed, label); + if (!parsed.toString().equals(value)) { + throw new IllegalArgumentException("Canonical nonnil " + label + " is required"); + } + return parsed; + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + } + + private static void requireDigest(String value, String label) { + if (!GameTenantCreationDigest.isDigest(value)) { + throw new IllegalArgumentException(label + " must be canonical SHA-256 text"); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeClientTest.java new file mode 100644 index 0000000000..a30c142c85 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeClientTest.java @@ -0,0 +1,296 @@ +package net.firedevops.firemud.common.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.ManagedChannel; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.lang.reflect.Field; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceRequest; +import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldAuthoredSourceIntakeServiceGrpc; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class WorldAuthoredSourceIntakeClientTest { + private static final String NAMESPACE = "test"; + private static final String SOURCE_DIGEST = "sha256:" + "a".repeat(64); + private static final String RECEIPT_DIGEST = "sha256:" + "b".repeat(64); + private static final WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest INTAKE_REQUEST = + new WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest( + 1, + NAMESPACE, + UUID.fromString("12345678-1234-4234-8234-123456789abc"), + UUID.fromString("22345678-1234-4234-8234-123456789abc"), + "world-one", + UUID.fromString("32345678-1234-4234-8234-123456789abc"), + SOURCE_DIGEST); + private static final WorldAuthoredSourceIntakeGrpcCodec.ReadRequest READ_REQUEST = + new WorldAuthoredSourceIntakeGrpcCodec.ReadRequest( + INTAKE_REQUEST, UUID.fromString("42345678-1234-4234-8234-123456789abc")); + + @Test + void rejectsPlaintextClasspathAndUnreadableTlsMaterialBeforeChannelCreation(@TempDir Path dir) + throws Exception { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + + CommonGrpcClientProperties plaintext = fileBackedMtls(dir); + plaintext.setPlaintext(true); + assertThatThrownBy(() -> newClient(plaintext, channelFactory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + + assertThatThrownBy(() -> newClient(new CommonGrpcClientProperties(), channelFactory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + + CommonGrpcClientProperties classpath = fileBackedMtls(dir); + classpath.setCaCert("classpath:certs/ca.crt"); + assertThatThrownBy(() -> newClient(classpath, channelFactory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + + CommonGrpcClientProperties missingFiles = new CommonGrpcClientProperties(); + missingFiles.setCertChain(dir.resolve("missing-client.crt").toString()); + missingFiles.setPrivateKey(dir.resolve("missing-client.key").toString()); + missingFiles.setCaCert(dir.resolve("missing-ca.crt").toString()); + assertThatThrownBy(() -> newClient(missingFiles, channelFactory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("existing readable file"); + + verifyNoInteractions(channelFactory); + } + + @Test + void requiresExplicitLifecycleAndExactConfiguredNamespace(@TempDir Path dir) throws Exception { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + WorldAuthoredSourceIntakeClient client = newClient(fileBackedMtls(dir), channelFactory); + try { + assertThatThrownBy(() -> client.intake(INTAKE_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + assertThatThrownBy( + () -> + client.intake( + new WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest( + 1, + "other", + INTAKE_REQUEST.intakeRequestId(), + INTAKE_REQUEST.canonicalTenantId(), + INTAKE_REQUEST.worldSlug(), + INTAKE_REQUEST.sourceOperationId(), + INTAKE_REQUEST.expectedSourceEvidenceDigest()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured workload namespace"); + assertThatThrownBy(() -> client.read(READ_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + verifyNoInteractions(channelFactory); + } finally { + client.close(); + } + } + + @Test + void initializesConfiguredWorldTargetOnceAndCannotRestartAfterClose(@TempDir Path dir) + throws Exception { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setWorldManagementService("world.internal:7676"); + CommonGrpcClientProperties tls = fileBackedMtls(dir); + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + ManagedChannel channel = mock(ManagedChannel.class); + when(channelFactory.buildChannel( + eq("world.internal:7676"), eq(6565), any(CommonGrpcClientProperties.class), eq(true))) + .thenReturn(channel); + WorldAuthoredSourceIntakeClient client = + new WorldAuthoredSourceIntakeClient(endpoints, tls, channelFactory, NAMESPACE); + + client.init(); + client.init(); + client.close(); + + verify(channelFactory) + .buildChannel( + eq("world.internal:7676"), eq(6565), any(CommonGrpcClientProperties.class), eq(true)); + assertThatThrownBy(() -> client.intake(INTAKE_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + assertThatThrownBy(client::init) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("is closed"); + } + + @Test + void sendsOneIntakeAndReturnsOnlyAValidatedExactWorldReceipt(@TempDir Path dir) throws Exception { + WorldAuthoredSourceIntakeServiceGrpc.WorldAuthoredSourceIntakeServiceBlockingStub stub = + mock( + WorldAuthoredSourceIntakeServiceGrpc.WorldAuthoredSourceIntakeServiceBlockingStub + .class); + WorldAuthoredSourceIntakeClient client = clientWithStub(dir, stub); + IntakeAuthoredWorldSourceResponse response = intakeResponse(INTAKE_REQUEST); + when(stub.intakeAuthoredWorldSource(any(IntakeAuthoredWorldSourceRequest.class))) + .thenReturn(response); + when(stub.withDeadlineAfter(anyLong(), eq(TimeUnit.SECONDS))).thenReturn(stub); + + WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt receipt = client.intake(INTAKE_REQUEST); + + assertThat(receipt.intakeRequestId()).isEqualTo(INTAKE_REQUEST.intakeRequestId()); + assertThat(receipt.operationId()) + .isEqualTo(UUID.fromString("52345678-1234-4234-8234-123456789abc")); + assertThat(receipt.receiptDigest()).isEqualTo(RECEIPT_DIGEST); + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + verify(stub) + .intakeAuthoredWorldSource( + WorldAuthoredSourceIntakeGrpcCodec.toIntakeRequest(INTAKE_REQUEST)); + assertThat( + WorldAuthoredSourceIntakeGrpcCodec.toIntakeRequest(INTAKE_REQUEST) + .getDescriptorForType() + .getFields()) + .extracting(field -> field.getName()) + .doesNotContain("world_tenant_key", "local_tenant_key", "tenant_id"); + } + + @Test + void rejectsChangedEchoesAndUnknownResponseFields(@TempDir Path dir) throws Exception { + WorldAuthoredSourceIntakeServiceGrpc.WorldAuthoredSourceIntakeServiceBlockingStub stub = + mock( + WorldAuthoredSourceIntakeServiceGrpc.WorldAuthoredSourceIntakeServiceBlockingStub + .class); + WorldAuthoredSourceIntakeClient client = clientWithStub(dir, stub); + when(stub.withDeadlineAfter(anyLong(), eq(TimeUnit.SECONDS))).thenReturn(stub); + + when(stub.intakeAuthoredWorldSource(any(IntakeAuthoredWorldSourceRequest.class))) + .thenReturn(intakeResponse(INTAKE_REQUEST).toBuilder().setWorldSlug("other-world").build()); + assertThatThrownBy(() -> client.intake(INTAKE_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid authored-source intake receipt"); + + when(stub.intakeAuthoredWorldSource(any(IntakeAuthoredWorldSourceRequest.class))) + .thenReturn( + intakeResponse(INTAKE_REQUEST).toBuilder().setUnknownFields(unknownField()).build()); + assertThatThrownBy(() -> client.intake(INTAKE_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid authored-source intake receipt"); + + ReadAuthoredWorldSourceIntakeResponse alteredRead = + readResponse(READ_REQUEST).toBuilder() + .setRequestId(INTAKE_REQUEST.intakeRequestId().toString()) + .build(); + when(stub.readAuthoredWorldSourceIntake(any(ReadAuthoredWorldSourceIntakeRequest.class))) + .thenReturn(alteredRead); + assertThatThrownBy(() -> client.read(READ_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid authored-source intake readback"); + + when(stub.intakeAuthoredWorldSource(any(IntakeAuthoredWorldSourceRequest.class))) + .thenThrow(new StatusRuntimeException(Status.UNAVAILABLE)); + assertThatThrownBy(() -> client.intake(INTAKE_REQUEST)) + .isInstanceOf(StatusRuntimeException.class); + verify(stub, org.mockito.Mockito.times(3)) + .intakeAuthoredWorldSource(any(IntakeAuthoredWorldSourceRequest.class)); + } + + @Test + void readRequiresAndReturnsTheSeparateExactReadIdentity(@TempDir Path dir) throws Exception { + WorldAuthoredSourceIntakeServiceGrpc.WorldAuthoredSourceIntakeServiceBlockingStub stub = + mock( + WorldAuthoredSourceIntakeServiceGrpc.WorldAuthoredSourceIntakeServiceBlockingStub + .class); + WorldAuthoredSourceIntakeClient client = clientWithStub(dir, stub); + when(stub.withDeadlineAfter(anyLong(), eq(TimeUnit.SECONDS))).thenReturn(stub); + when(stub.readAuthoredWorldSourceIntake(any(ReadAuthoredWorldSourceIntakeRequest.class))) + .thenReturn(readResponse(READ_REQUEST)); + + WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt receipt = client.read(READ_REQUEST); + + assertThat(receipt.intakeRequestId()).isEqualTo(INTAKE_REQUEST.intakeRequestId()); + assertThat(receipt.sourceOperationId()).isEqualTo(INTAKE_REQUEST.sourceOperationId()); + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + verify(stub) + .readAuthoredWorldSourceIntake( + WorldAuthoredSourceIntakeGrpcCodec.toReadRequest(READ_REQUEST)); + } + + private static WorldAuthoredSourceIntakeClient clientWithStub( + Path directory, + WorldAuthoredSourceIntakeServiceGrpc.WorldAuthoredSourceIntakeServiceBlockingStub stub) + throws Exception { + WorldAuthoredSourceIntakeClient client = + newClient(fileBackedMtls(directory), mock(GrpcChannelFactory.class)); + setField(AbstractReloadingBlockingGrpcClient.class, client, "stub", stub); + setField(WorldAuthoredSourceIntakeClient.class, client, "initialized", true); + return client; + } + + private static IntakeAuthoredWorldSourceResponse intakeResponse( + WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest request) { + return WorldAuthoredSourceIntakeGrpcCodec.toIntakeResponse(request, receipt(request)); + } + + private static ReadAuthoredWorldSourceIntakeResponse readResponse( + WorldAuthoredSourceIntakeGrpcCodec.ReadRequest request) { + return WorldAuthoredSourceIntakeGrpcCodec.toReadResponse(request, receipt(request.binding())); + } + + private static WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt receipt( + WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest request) { + return new WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt( + request.schemaVersion(), + request.targetNamespace(), + request.intakeRequestId(), + UUID.fromString("52345678-1234-4234-8234-123456789abc"), + request.canonicalTenantId(), + request.worldSlug(), + request.sourceOperationId(), + request.expectedSourceEvidenceDigest(), + WorldAuthoredSourceIntakeGrpcCodec.requestDigest(request), + RECEIPT_DIGEST); + } + + private static UnknownFieldSet unknownField() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + } + + private static void setField(Class declaringClass, Object target, String name, Object value) + throws Exception { + Field field = declaringClass.getDeclaredField(name); + field.setAccessible(true); + field.set(target, value); + } + + private static WorldAuthoredSourceIntakeClient newClient( + CommonGrpcClientProperties tls, GrpcChannelFactory channelFactory) { + return new WorldAuthoredSourceIntakeClient( + new ServiceEndpointsProperties(), tls, channelFactory, NAMESPACE); + } + + private static CommonGrpcClientProperties fileBackedMtls(Path directory) throws Exception { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(Files.writeString(directory.resolve("client.crt"), "certificate").toString()); + tls.setPrivateKey(Files.writeString(directory.resolve("client.key"), "private key").toString()); + tls.setCaCert( + Files.writeString(directory.resolve("server-ca.crt"), "CA certificate").toString()); + return tls; + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeGrpcCodecTest.java new file mode 100644 index 0000000000..80fb74bda4 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeGrpcCodecTest.java @@ -0,0 +1,242 @@ +package net.firedevops.firemud.common.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.UnknownFieldSet; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.ReadRequest; +import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceRequest; +import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeResponse; +import org.junit.jupiter.api.Test; + +class WorldAuthoredSourceIntakeGrpcCodecTest { + private static final String NAMESPACE = "firemud"; + private static final UUID INTAKE_REQUEST_ID = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID READ_REQUEST_ID = + UUID.fromString("66666666-6666-4666-8666-666666666666"); + private static final UUID TENANT_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID SOURCE_OPERATION_ID = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID OPERATION_ID = UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final String WORLD_SLUG = "violet-wilds"; + private static final String SOURCE_DIGEST = digest('a'); + private static final String REQUEST_DIGEST = + "sha256:d8b4609586debeae9752cc22ddb58a686fa770ea5928a52aefab71494164e1ce"; + private static final String RECEIPT_DIGEST = digest('b'); + private static final IntakeRequest BINDING = + new IntakeRequest( + 1, + NAMESPACE, + INTAKE_REQUEST_ID, + TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + SOURCE_DIGEST); + + @Test + void decodesAndEchoesTheFullIntakeBindingAndPublicReceipt() { + var request = intakeRequest(); + assertThat(WorldAuthoredSourceIntakeGrpcCodec.fromIntakeRequest(request)).isEqualTo(BINDING); + assertThat(WorldAuthoredSourceIntakeGrpcCodec.toIntakeRequest(BINDING)).isEqualTo(request); + assertThat( + WorldAuthoredSourceIntakeGrpcCodec.toIntakeRequest(BINDING).getUnknownFields().asMap()) + .isEmpty(); + + CommittedReceipt receipt = committedReceipt(BINDING); + assertThat(WorldAuthoredSourceIntakeGrpcCodec.requestDigest(BINDING)).isEqualTo(REQUEST_DIGEST); + IntakeAuthoredWorldSourceResponse response = + WorldAuthoredSourceIntakeGrpcCodec.toIntakeResponse(BINDING, receipt); + assertThat(response.getSchemaVersion()).isEqualTo(1); + assertThat(response.getTargetNamespace()).isEqualTo(NAMESPACE); + assertThat(response.getIntakeRequestId()).isEqualTo(INTAKE_REQUEST_ID.toString()); + assertThat(response.getCanonicalTenantId()).isEqualTo(TENANT_ID.toString()); + assertThat(response.getWorldSlug()).isEqualTo(WORLD_SLUG); + assertThat(response.getSourceOperationId()).isEqualTo(SOURCE_OPERATION_ID.toString()); + assertThat(response.getExpectedSourceEvidenceDigest()).isEqualTo(SOURCE_DIGEST); + assertThat(response.getOperationId()).isEqualTo(OPERATION_ID.toString()); + assertThat(response.getRequestDigest()).isEqualTo(REQUEST_DIGEST); + assertThat(response.getReceiptDigest()).isEqualTo(RECEIPT_DIGEST); + assertThat(WorldAuthoredSourceIntakeGrpcCodec.fromIntakeResponse(BINDING, response)) + .isEqualTo(receipt); + assertThat(response.getAllFields().keySet()) + .extracting(field -> field.getName()) + .doesNotContain("local_tenant_key", "localTenantKey"); + } + + @Test + void exactReadUsesAndEchoesItsSeparateRequestIdentity() { + ReadAuthoredWorldSourceIntakeRequest request = readRequest(); + ReadRequest decoded = WorldAuthoredSourceIntakeGrpcCodec.fromReadRequest(request); + assertThat(decoded.binding()).isEqualTo(BINDING); + assertThat(decoded.requestId()).isEqualTo(READ_REQUEST_ID); + assertThat(WorldAuthoredSourceIntakeGrpcCodec.toReadRequest(decoded)).isEqualTo(request); + assertThat(WorldAuthoredSourceIntakeGrpcCodec.toReadRequest(decoded).getUnknownFields().asMap()) + .isEmpty(); + + CommittedReceipt receipt = committedReceipt(BINDING); + ReadAuthoredWorldSourceIntakeResponse response = + WorldAuthoredSourceIntakeGrpcCodec.toReadResponse(decoded, receipt); + assertThat(response.getRequestId()).isEqualTo(READ_REQUEST_ID.toString()); + assertThat(response.getIntakeRequestId()).isEqualTo(INTAKE_REQUEST_ID.toString()); + assertThat(response.getCanonicalTenantId()).isEqualTo(TENANT_ID.toString()); + assertThat(response.getWorldSlug()).isEqualTo(WORLD_SLUG); + assertThat(response.getSourceOperationId()).isEqualTo(SOURCE_OPERATION_ID.toString()); + assertThat(WorldAuthoredSourceIntakeGrpcCodec.fromReadResponse(decoded, response)) + .isEqualTo(receipt); + } + + @Test + void rejectsMalformedClosedIntakeRequests() { + for (IntakeAuthoredWorldSourceRequest invalid : + List.of( + intakeRequest().toBuilder().setSchemaVersion(2).build(), + intakeRequest().toBuilder().setTargetNamespace("FireMUD").build(), + intakeRequest().toBuilder().setIntakeRequestId("not-a-uuid").build(), + intakeRequest().toBuilder().setCanonicalTenantId(new UUID(0L, 0L).toString()).build(), + intakeRequest().toBuilder().setWorldSlug("Violet-Wilds").build(), + intakeRequest().toBuilder().setWorldSlug("w".repeat(121)).build(), + intakeRequest().toBuilder() + .setSourceOperationId("00000000-0000-0000-0000-000000000000") + .build(), + intakeRequest().toBuilder().setExpectedSourceEvidenceDigest("sha256:BAD").build(), + intakeRequest().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) { + assertThatThrownBy(() -> WorldAuthoredSourceIntakeGrpcCodec.fromIntakeRequest(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void rejectsReadRequestsThatReuseTheIntakeIdentityOrContainUnknownFields() { + for (ReadAuthoredWorldSourceIntakeRequest invalid : + List.of( + readRequest().toBuilder().setRequestId(INTAKE_REQUEST_ID.toString()).build(), + readRequest().toBuilder().setRequestId("00000000-0000-0000-0000-000000000000").build(), + readRequest().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) { + assertThatThrownBy(() -> WorldAuthoredSourceIntakeGrpcCodec.fromReadRequest(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void rejectsChangedEchoesMalformedDigestsAndUnknownResponseFields() { + IntakeAuthoredWorldSourceResponse valid = + WorldAuthoredSourceIntakeGrpcCodec.toIntakeResponse(BINDING, committedReceipt(BINDING)); + for (IntakeAuthoredWorldSourceResponse invalid : + List.of( + valid.toBuilder().setTargetNamespace("other").build(), + valid.toBuilder().setIntakeRequestId(READ_REQUEST_ID.toString()).build(), + valid.toBuilder().setCanonicalTenantId(READ_REQUEST_ID.toString()).build(), + valid.toBuilder().setWorldSlug("other-world").build(), + valid.toBuilder().setSourceOperationId(READ_REQUEST_ID.toString()).build(), + valid.toBuilder().setExpectedSourceEvidenceDigest(digest('c')).build(), + valid.toBuilder().setOperationId("not-a-uuid").build(), + valid.toBuilder().setRequestDigest(digest('c')).build(), + valid.toBuilder().setReceiptDigest("sha256:invalid").build(), + valid.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) { + assertThatThrownBy( + () -> WorldAuthoredSourceIntakeGrpcCodec.fromIntakeResponse(BINDING, invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + + ReadRequest readRequest = new ReadRequest(BINDING, READ_REQUEST_ID); + ReadAuthoredWorldSourceIntakeResponse readResponse = + WorldAuthoredSourceIntakeGrpcCodec.toReadResponse(readRequest, committedReceipt(BINDING)); + assertThatThrownBy( + () -> + WorldAuthoredSourceIntakeGrpcCodec.fromReadResponse( + readRequest, + readResponse.toBuilder().setRequestId(INTAKE_REQUEST_ID.toString()).build())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void refusesToEncodeAReceiptForAnotherBinding() { + CommittedReceipt changed = + new CommittedReceipt( + 1, + NAMESPACE, + INTAKE_REQUEST_ID, + OPERATION_ID, + TENANT_ID, + "other-world", + SOURCE_OPERATION_ID, + SOURCE_DIGEST, + WorldAuthoredSourceIntakeGrpcCodec.requestDigest( + new IntakeRequest( + 1, + NAMESPACE, + INTAKE_REQUEST_ID, + TENANT_ID, + "other-world", + SOURCE_OPERATION_ID, + SOURCE_DIGEST)), + RECEIPT_DIGEST); + assertThatThrownBy(() -> WorldAuthoredSourceIntakeGrpcCodec.toIntakeResponse(BINDING, changed)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static IntakeAuthoredWorldSourceRequest intakeRequest() { + return IntakeAuthoredWorldSourceRequest.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(NAMESPACE) + .setIntakeRequestId(INTAKE_REQUEST_ID.toString()) + .setCanonicalTenantId(TENANT_ID.toString()) + .setWorldSlug(WORLD_SLUG) + .setSourceOperationId(SOURCE_OPERATION_ID.toString()) + .setExpectedSourceEvidenceDigest(SOURCE_DIGEST) + .build(); + } + + private static ReadAuthoredWorldSourceIntakeRequest readRequest() { + return ReadAuthoredWorldSourceIntakeRequest.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(NAMESPACE) + .setRequestId(READ_REQUEST_ID.toString()) + .setIntakeRequestId(INTAKE_REQUEST_ID.toString()) + .setCanonicalTenantId(TENANT_ID.toString()) + .setWorldSlug(WORLD_SLUG) + .setSourceOperationId(SOURCE_OPERATION_ID.toString()) + .setExpectedSourceEvidenceDigest(SOURCE_DIGEST) + .build(); + } + + private static CommittedReceipt committedReceipt(IntakeRequest binding) { + return new CommittedReceipt( + 1, + binding.targetNamespace(), + binding.intakeRequestId(), + OPERATION_ID, + binding.canonicalTenantId(), + binding.worldSlug(), + binding.sourceOperationId(), + binding.expectedSourceEvidenceDigest(), + WorldAuthoredSourceIntakeGrpcCodec.requestDigest(binding), + RECEIPT_DIGEST); + } + + private static String digest(char value) { + return "sha256:" + String.valueOf(value).repeat(64); + } +} diff --git a/services/world-management-service/build.gradle.kts b/services/world-management-service/build.gradle.kts index d6bd731255..3213506b1f 100644 --- a/services/world-management-service/build.gradle.kts +++ b/services/world-management-service/build.gradle.kts @@ -14,4 +14,6 @@ firemudJooq { dependencies { implementation(project(":common-security")) + testImplementation(libs.bouncycastle.pkix) + testCompileOnly(libs.spotbugs.annotations) } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeGrpcService.java new file mode 100644 index 0000000000..ded83a79a8 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeGrpcService.java @@ -0,0 +1,255 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.sql.SQLException; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.ReadRequest; +import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceRequest; +import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldAuthoredSourceIntakeServiceGrpc; +import org.springframework.dao.DataAccessException; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.dao.TransientDataAccessException; + +/** + * Explicitly unregistered gRPC adapter for authenticated authored-source intake and exact receipt + * readback. This class has no Spring gRPC registration annotation or application wiring. + */ +public final class WorldAuthoredSourceIntakeGrpcService + extends WorldAuthoredSourceIntakeServiceGrpc.WorldAuthoredSourceIntakeServiceImplBase { + private final WorldAuthoredSourceIntakeService intakeService; + private final String trustedNamespace; + + public WorldAuthoredSourceIntakeGrpcService( + WorldAuthoredSourceIntakeService intakeService, String trustedNamespace) { + this.intakeService = Objects.requireNonNull(intakeService, "intakeService"); + if (!GrpcPeerIdentity.isValidNamespace(trustedNamespace)) { + throw new IllegalArgumentException("World workload namespace is invalid"); + } + this.trustedNamespace = trustedNamespace; + } + + @Override + public void intakeAuthoredWorldSource( + IntakeAuthoredWorldSourceRequest request, + StreamObserver responseObserver) { + if (!requireAuthenticatedGameDesignPeer(responseObserver)) { + return; + } + IntakeRequest binding; + try { + binding = WorldAuthoredSourceIntakeGrpcCodec.fromIntakeRequest(request); + } catch (IllegalArgumentException exception) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Canonical World intake request is required") + .asRuntimeException()); + return; + } + if (!trustedNamespace.equals(binding.targetNamespace())) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription( + "World intake target namespace must match the authenticated workload") + .asRuntimeException()); + return; + } + + WorldAuthoredSourceIntakeReceipt receipt; + try { + receipt = + intakeService.intake( + binding.schemaVersion(), + binding.targetNamespace(), + binding.intakeRequestId(), + binding.canonicalTenantId(), + binding.worldSlug(), + binding.sourceOperationId(), + binding.expectedSourceEvidenceDigest()); + } catch (RuntimeException exception) { + respondWithOwnerFailure(responseObserver, exception); + return; + } + + IntakeAuthoredWorldSourceResponse response; + try { + response = + WorldAuthoredSourceIntakeGrpcCodec.toIntakeResponse(binding, toCommittedReceipt(receipt)); + } catch (IllegalArgumentException exception) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Committed World intake receipt is inconsistent") + .asRuntimeException()); + return; + } + responseObserver.onNext(response); + responseObserver.onCompleted(); + } + + @Override + public void readAuthoredWorldSourceIntake( + ReadAuthoredWorldSourceIntakeRequest request, + StreamObserver responseObserver) { + if (!requireAuthenticatedGameDesignPeer(responseObserver)) { + return; + } + ReadRequest readRequest; + try { + readRequest = WorldAuthoredSourceIntakeGrpcCodec.fromReadRequest(request); + } catch (IllegalArgumentException exception) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Canonical World intake read request is required") + .asRuntimeException()); + return; + } + if (!trustedNamespace.equals(readRequest.binding().targetNamespace())) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription( + "World intake target namespace must match the authenticated workload") + .asRuntimeException()); + return; + } + + Optional stored; + try { + IntakeRequest binding = readRequest.binding(); + stored = + intakeService.readCommittedReceipt( + binding.schemaVersion(), + binding.targetNamespace(), + readRequest.requestId(), + binding.intakeRequestId(), + binding.canonicalTenantId(), + binding.worldSlug(), + binding.sourceOperationId(), + binding.expectedSourceEvidenceDigest()); + } catch (RuntimeException exception) { + respondWithOwnerFailure(responseObserver, exception); + return; + } + if (stored.isEmpty()) { + responseObserver.onError( + Status.NOT_FOUND + .withDescription("No committed World intake matches the exact request") + .asRuntimeException()); + return; + } + + ReadAuthoredWorldSourceIntakeResponse response; + try { + response = + WorldAuthoredSourceIntakeGrpcCodec.toReadResponse( + readRequest, toCommittedReceipt(stored.orElseThrow())); + } catch (IllegalArgumentException exception) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Committed World intake receipt is inconsistent") + .asRuntimeException()); + return; + } + responseObserver.onNext(response); + responseObserver.onCompleted(); + } + + private static CommittedReceipt toCommittedReceipt(WorldAuthoredSourceIntakeReceipt receipt) { + if (receipt == null) { + throw new IllegalArgumentException("World owner returned no committed intake receipt"); + } + return new CommittedReceipt( + receipt.schemaVersion(), + receipt.targetNamespace(), + receipt.intakeRequestId(), + receipt.operationId(), + receipt.canonicalTenantId(), + receipt.worldSlug(), + receipt.sourceOperationId(), + receipt.sourceEvidenceDigest(), + receipt.requestDigest(), + receipt.receiptDigest()); + } + + private boolean requireAuthenticatedGameDesignPeer(StreamObserver responseObserver) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer != null + && peer.isService("game-design-service") + && peer.isInNamespace(trustedNamespace)) { + return true; + } + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription("Verified same-namespace Game Design workload is required") + .asRuntimeException()); + return false; + } + + private static void respondWithOwnerFailure( + StreamObserver responseObserver, RuntimeException exception) { + if (exception instanceof StatusRuntimeException statusException) { + responseObserver.onError(statusException); + } else if (exception instanceof SecurityException) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription("Verified same-namespace Game Design workload is required") + .asRuntimeException()); + } else if (exception + instanceof WorldAuthoredSourceIntakeRepository.RegistrationConflictException + || exception + instanceof WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("World authored-source intake conflicts with committed evidence") + .asRuntimeException()); + } else if (exception instanceof IllegalArgumentException) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Canonical World intake binding is required") + .asRuntimeException()); + } else if (exception instanceof DataAccessResourceFailureException + || exception instanceof TransientDataAccessException) { + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("World intake is temporarily unavailable") + .asRuntimeException()); + } else if (exception instanceof DataAccessException) { + Status.Code code = + hasConnectionFailureSqlState(exception) ? Status.Code.UNAVAILABLE : Status.Code.INTERNAL; + responseObserver.onError( + Status.fromCode(code) + .withDescription("World intake storage could not complete the request") + .asRuntimeException()); + } else if (exception instanceof IllegalStateException) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("World intake is unavailable in the current transaction state") + .asRuntimeException()); + } else { + responseObserver.onError( + Status.INTERNAL + .withDescription("World authored-source intake failed") + .asRuntimeException()); + } + } + + private static boolean hasConnectionFailureSqlState(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException exception) { + String sqlState = exception.getSQLState(); + if (sqlState != null && sqlState.startsWith("08")) { + return true; + } + } + } + return false; + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeService.java index fae4a474c8..d32ecac3a6 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeService.java @@ -20,6 +20,7 @@ * transaction that retains its complete evidence and private tenant association. */ public class WorldAuthoredSourceIntakeService { + private static final int SCHEMA_VERSION = 1; private static final UUID NIL_UUID = new UUID(0L, 0L); private final AuthoredWorldSourceClient sourceClient; @@ -60,9 +61,30 @@ public WorldAuthoredSourceIntakeReceipt intake( String worldSlug, UUID sourceOperationId, String expectedSourceEvidenceDigest) { + return intake( + SCHEMA_VERSION, + workloadNamespace, + intakeRequestId, + canonicalTenantId, + worldSlug, + sourceOperationId, + expectedSourceEvidenceDigest); + } + + /** Accepts the complete wire binding after authenticating the exact Game Design workload. */ + public WorldAuthoredSourceIntakeReceipt intake( + int schemaVersion, + String targetNamespace, + UUID intakeRequestId, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String expectedSourceEvidenceDigest) { requireAuthenticatedGameDesignCaller(); + validateSchemaAndNamespace(schemaVersion, targetNamespace); requireNoAmbientTransaction(); validateRequest( + targetNamespace, intakeRequestId, canonicalTenantId, worldSlug, @@ -130,6 +152,47 @@ public WorldAuthoredSourceIntakeReceipt intake( return readback; } + /** Reads only an exact committed receipt; it never re-reads Game Design or allocates state. */ + public Optional readCommittedReceipt( + int schemaVersion, + String targetNamespace, + UUID requestId, + UUID intakeRequestId, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String expectedSourceEvidenceDigest) { + requireAuthenticatedGameDesignCaller(); + validateSchemaAndNamespace(schemaVersion, targetNamespace); + requireNoAmbientTransaction(); + requireNonNil(requestId, "requestId"); + requireNonNil(intakeRequestId, "intakeRequestId"); + if (requestId.equals(intakeRequestId)) { + throw new IllegalArgumentException("Read requestId must differ from intakeRequestId"); + } + validateRequest( + targetNamespace, + intakeRequestId, + canonicalTenantId, + worldSlug, + sourceOperationId, + expectedSourceEvidenceDigest); + + Optional receipt = + repository.read(targetNamespace, intakeRequestId); + if (receipt.isEmpty()) { + return Optional.empty(); + } + return Optional.of( + requireReceiptForRequest( + receipt.orElseThrow(), + intakeRequestId, + canonicalTenantId, + worldSlug, + sourceOperationId, + expectedSourceEvidenceDigest)); + } + private void requireAuthenticatedGameDesignCaller() { GrpcPeerIdentity peer = GrpcPeerIdentity.current(); if (peer == null @@ -147,7 +210,18 @@ private static void requireNoAmbientTransaction() { } } + private void validateSchemaAndNamespace(int schemaVersion, String targetNamespace) { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported World authored-source intake version"); + } + if (!workloadNamespace.equals(targetNamespace)) { + throw new SecurityException( + "World authored-source intake target namespace does not match this workload"); + } + } + private void validateRequest( + String targetNamespace, UUID intakeRequestId, UUID canonicalTenantId, String worldSlug, @@ -156,7 +230,7 @@ private void validateRequest( requireNonNil(intakeRequestId, "intakeRequestId"); requireNonNil(canonicalTenantId, "canonicalTenantId"); requireNonNil(sourceOperationId, "sourceOperationId"); - AuthoredWorldSourceDigest.validateReadSelector(workloadNamespace, canonicalTenantId, worldSlug); + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); if (!GameTenantCreationDigest.isDigest(expectedSourceEvidenceDigest)) { throw new IllegalArgumentException( "expectedSourceEvidenceDigest must be a canonical SHA-256 digest"); diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeMtlsIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeMtlsIntegrationTest.java new file mode 100644 index 0000000000..ba30191729 --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeMtlsIntegrationTest.java @@ -0,0 +1,621 @@ +package net.firedevops.firemud.worldmanagement; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.Message; +import io.grpc.ForwardingServerCall; +import io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import java.math.BigInteger; +import java.net.InetSocketAddress; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.PrivateKey; +import java.security.Security; +import java.security.cert.X509Certificate; +import java.time.Instant; +import java.util.Base64; +import java.util.Date; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicLong; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceClient; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceGrpcCodec; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeClient; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.ReadRequest; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeGrpcService; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeReceipt; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeService; +import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeResponse; +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.asn1.x509.BasicConstraints; +import org.bouncycastle.asn1.x509.ExtendedKeyUsage; +import org.bouncycastle.asn1.x509.Extension; +import org.bouncycastle.asn1.x509.GeneralName; +import org.bouncycastle.asn1.x509.GeneralNames; +import org.bouncycastle.asn1.x509.KeyPurposeId; +import org.bouncycastle.asn1.x509.KeyUsage; +import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; +import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; +import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * PostgreSQL owner commit and exact receipt readback over the unregistered physical mTLS boundary. + * Game Design source evidence is synthetic; this does not exercise its producer or network. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + classes = WorldManagementServiceApplication.class, + properties = "spring.grpc.server.port=0") +class WorldAuthoredSourceIntakeMtlsIntegrationTest { + private static final String NAMESPACE = "firemud"; + private static final String WORLD_SERVER_URI = + "spiffe://firemud/ns/firemud/sa/world-management-service"; + private static final AtomicLong CERTIFICATE_SERIAL = new AtomicLong(1); + private static TestPki pki; + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Container + static GenericContainer redis = + new GenericContainer<>("redis:7.2-alpine").withExposedPorts(6379); + + @TempDir Path tempDirectory; + + @Autowired private WorldAuthoredSourceIntakeRepository repository; + @Autowired private DSLContext dsl; + @Autowired private PlatformTransactionManager transactionManager; + + @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + + @MockitoBean + private net.firedevops.firemud.worldmanagement.client.GameDesignClient gameDesignClient; + + @MockitoBean + private net.firedevops.firemud.worldmanagement.client.GameSessionClient gameSessionClient; + + @MockitoBean + private net.firedevops.firemud.worldmanagement.client.EntityManagementClient + entityManagementClient; + + private Server server; + private ConcurrentLinkedQueue wireResponses; + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.registerPostgresService( + registry, postgres, "world_management_service"); + PostgresBackedServiceTestSupport.registerRedisService(registry, redis); + } + + @BeforeAll + static void createFreshTestPki() throws Exception { + if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { + Security.addProvider(new BouncyCastleProvider()); + } + KeyPair caKeyPair = newRsaKeyPair(); + X500Name caName = new X500Name("CN=World Intake Integration Test CA, O=FireMUD Test"); + X509Certificate caCertificate = + issueCertificate(caName, caKeyPair.getPublic(), caName, caKeyPair.getPrivate(), true, null); + pki = + new TestPki( + caCertificate, + issueLeaf(caName, caKeyPair.getPrivate(), "world-management-service", WORLD_SERVER_URI), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "game-design-service", + "spiffe://firemud/ns/firemud/sa/game-design-service"), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "account-service", + "spiffe://firemud/ns/firemud/sa/account-service")); + } + + @AfterEach + void stopPhysicalReceiver() throws Exception { + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } + + @Test + void commitsFreshWorldOwnerReceiptThenReturnsExactReceiptOverAuthenticatedSocket() + throws Exception { + Scenario scenario = newScenario("violet-wilds"); + AuthoredWorldSourceClient syntheticSource = sourceBoundary(scenario); + startReceiver(syntheticSource, new AtomicBoolean(false)); + + try (WorldAuthoredSourceIntakeClient client = + intakeClient(pki.gameDesignClient(), "gd-first")) { + CommittedReceipt intakeReceipt = client.intake(scenario.intakeRequest()); + WorldAuthoredSourceIntakeReceipt persisted = + repository.read(NAMESPACE, scenario.intakeRequestId()).orElseThrow(); + CommittedReceipt exactRead = client.read(scenario.readRequest()); + + assertThat(persisted.source()).isEqualTo(scenario.sourceEvidence()); + assertThat(intakeReceipt).isEqualTo(publicReceipt(persisted)); + assertThat(exactRead).isEqualTo(intakeReceipt); + assertThat(repository.read(NAMESPACE, scenario.intakeRequestId())).contains(persisted); + assertThat(dbCounts(scenario)).isEqualTo(new DbCounts(1L, 1L, 1L)); + assertNoPrivateLocalTenantKeyOnWire(); + verify(syntheticSource, times(1)).read(any(AuthoredWorldSourceGrpcCodec.ReadRequest.class)); + verifyNoMoreInteractions(syntheticSource); + } + } + + @Test + void reconcilesLostSuccessAcknowledgementWithExactRetryAndCommittedReadback() throws Exception { + Scenario scenario = newScenario("amber-coast"); + AuthoredWorldSourceClient syntheticSource = sourceBoundary(scenario); + AtomicBoolean dropNextSuccess = new AtomicBoolean(true); + startReceiver(syntheticSource, dropNextSuccess); + + try (WorldAuthoredSourceIntakeClient client = + intakeClient(pki.gameDesignClient(), "gd-retry")) { + assertThatThrownBy(() -> client.intake(scenario.intakeRequest())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAVAILABLE)); + + WorldAuthoredSourceIntakeReceipt committedAfterLostAck = + repository.read(NAMESPACE, scenario.intakeRequestId()).orElseThrow(); + DbCounts afterCommit = dbCounts(scenario); + assertThat(committedAfterLostAck.source()).isEqualTo(scenario.sourceEvidence()); + assertThat(afterCommit).isEqualTo(new DbCounts(1L, 1L, 1L)); + assertThat(dropNextSuccess.get()).isFalse(); + + CommittedReceipt retryReceipt = client.intake(scenario.intakeRequest()); + CommittedReceipt readReceipt = client.read(scenario.readRequest()); + + assertThat(retryReceipt).isEqualTo(publicReceipt(committedAfterLostAck)); + assertThat(readReceipt).isEqualTo(publicReceipt(committedAfterLostAck)); + assertThat(retryReceipt.operationId()).isEqualTo(committedAfterLostAck.operationId()); + assertThat(retryReceipt.requestDigest()).isEqualTo(committedAfterLostAck.requestDigest()); + assertThat(retryReceipt.receiptDigest()).isEqualTo(committedAfterLostAck.receiptDigest()); + assertThat(repository.read(NAMESPACE, scenario.intakeRequestId())) + .contains(committedAfterLostAck); + assertThat(dbCounts(scenario)).isEqualTo(afterCommit); + assertNoPrivateLocalTenantKeyOnWire(); + verify(syntheticSource, times(1)).read(any(AuthoredWorldSourceGrpcCodec.ReadRequest.class)); + verifyNoMoreInteractions(syntheticSource); + } + } + + @Test + void deniesWrongWorkloadAndChangedBindingWithoutOwnerMutation() throws Exception { + Scenario scenario = newScenario("silver-marsh"); + AuthoredWorldSourceClient syntheticSource = sourceBoundary(scenario); + startReceiver(syntheticSource, new AtomicBoolean(false)); + + try (WorldAuthoredSourceIntakeClient wrongCaller = + intakeClient(pki.accountClient(), "account")) { + assertStatus( + Status.Code.PERMISSION_DENIED, () -> wrongCaller.intake(scenario.intakeRequest())); + assertStatus(Status.Code.PERMISSION_DENIED, () -> wrongCaller.read(scenario.readRequest())); + } + assertThat(dbCounts(scenario)).isEqualTo(new DbCounts(0L, 0L, 0L)); + verifyNoInteractions(syntheticSource); + + try (WorldAuthoredSourceIntakeClient client = + intakeClient(pki.gameDesignClient(), "gd-scope")) { + CommittedReceipt accepted = client.intake(scenario.intakeRequest()); + WorldAuthoredSourceIntakeReceipt original = + repository.read(NAMESPACE, scenario.intakeRequestId()).orElseThrow(); + assertThat(client.read(scenario.readRequest())).isEqualTo(accepted); + + IntakeRequest changedIntake = + new IntakeRequest( + 1, + NAMESPACE, + scenario.intakeRequestId(), + scenario.canonicalTenantId(), + "changed-world-selector", + scenario.sourceOperationId(), + scenario.sourceEvidence().evidenceDigest()); + ReadRequest changedRead = new ReadRequest(changedIntake, UUID.randomUUID()); + + assertStatus(Status.Code.FAILED_PRECONDITION, () -> client.intake(changedIntake)); + assertStatus(Status.Code.FAILED_PRECONDITION, () -> client.read(changedRead)); + + assertThat(repository.read(NAMESPACE, scenario.intakeRequestId())).contains(original); + assertThat(original.source()).isEqualTo(scenario.sourceEvidence()); + assertThat(dbCounts(scenario)).isEqualTo(new DbCounts(1L, 1L, 1L)); + verify(syntheticSource, times(1)).read(any(AuthoredWorldSourceGrpcCodec.ReadRequest.class)); + verifyNoMoreInteractions(syntheticSource); + } + } + + private AuthoredWorldSourceClient sourceBoundary(Scenario scenario) { + AuthoredWorldSourceClient syntheticSource = mock(AuthoredWorldSourceClient.class); + when(syntheticSource.read(any(AuthoredWorldSourceGrpcCodec.ReadRequest.class))) + .thenAnswer( + invocation -> { + AuthoredWorldSourceGrpcCodec.ReadRequest request = invocation.getArgument(0); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(request.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(request.operationId()).isEqualTo(scenario.sourceOperationId()); + assertThat(request.canonicalTenantId()).isEqualTo(scenario.canonicalTenantId()); + assertThat(request.worldSlug()).isEqualTo(scenario.worldSlug()); + AuthoredWorldSourceEvidence answer = scenario.sourceEvidence(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return answer; + }); + return syntheticSource; + } + + private void startReceiver( + AuthoredWorldSourceClient syntheticSource, AtomicBoolean dropNextSuccess) throws Exception { + WorldAuthoredSourceIntakeService owner = + new WorldAuthoredSourceIntakeService( + syntheticSource, repository, transactionManager, NAMESPACE); + WorldAuthoredSourceIntakeGrpcService handler = + new WorldAuthoredSourceIntakeGrpcService(owner, NAMESPACE); + wireResponses = new ConcurrentLinkedQueue<>(); + var withPeerIdentity = ServerInterceptors.intercept(handler, new GrpcPeerIdentityInterceptor()); + var withResponseCapture = + ServerInterceptors.intercept( + withPeerIdentity, responseCaptureAndDrop(wireResponses, dropNextSuccess)); + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + pki.worldServer().privateKey(), pki.worldServer().certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(withResponseCapture) + .build() + .start(); + } + + private WorldAuthoredSourceIntakeClient intakeClient(TestCertificate certificate, String label) + throws Exception { + WorldAuthoredSourceIntakeClient client = + new WorldAuthoredSourceIntakeClient( + endpoints(), tlsProperties(certificate, label), new GrpcChannelFactory(), NAMESPACE); + client.init(); + return client; + } + + private ServiceEndpointsProperties endpoints() { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setWorldManagementService("127.0.0.1:" + server.getPort()); + return endpoints; + } + + private CommonGrpcClientProperties tlsProperties(TestCertificate certificate, String label) + throws Exception { + Path clientCertificate = tempDirectory.resolve(label + "-client.crt"); + Path clientPrivateKey = tempDirectory.resolve(label + "-client.key"); + Path caCertificate = tempDirectory.resolve("test-ca.crt"); + Files.writeString( + clientCertificate, pem("CERTIFICATE", certificate.certificate().getEncoded())); + Files.writeString(clientPrivateKey, pem("PRIVATE KEY", certificate.privateKey().getEncoded())); + Files.writeString(caCertificate, pem("CERTIFICATE", pki.caCertificate().getEncoded())); + + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(clientCertificate.toString()); + tls.setPrivateKey(clientPrivateKey.toString()); + tls.setCaCert(caCertificate.toString()); + return tls; + } + + private static ServerInterceptor responseCaptureAndDrop( + ConcurrentLinkedQueue capturedResponses, AtomicBoolean dropNextSuccess) { + return new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + ServerCall forwardingCall = + new ForwardingServerCall.SimpleForwardingServerCall<>(call) { + private boolean droppedResponse; + + @Override + public void sendMessage(RespT message) { + if (message instanceof Message protobufMessage) { + capturedResponses.add(protobufMessage); + } + if (message instanceof IntakeAuthoredWorldSourceResponse + && dropNextSuccess.compareAndSet(true, false)) { + droppedResponse = true; + return; + } + super.sendMessage(message); + } + + @Override + public void close(Status status, Metadata trailers) { + if (droppedResponse && status.isOk()) { + super.close( + Status.UNAVAILABLE.withDescription( + "Test deliberately lost a committed intake acknowledgement"), + trailers); + return; + } + super.close(status, trailers); + } + }; + return next.startCall(forwardingCall, headers); + } + }; + } + + private void assertNoPrivateLocalTenantKeyOnWire() { + assertThat( + IntakeAuthoredWorldSourceResponse.getDescriptor().findFieldByName("local_tenant_key")) + .isNull(); + assertThat( + ReadAuthoredWorldSourceIntakeResponse.getDescriptor() + .findFieldByName("local_tenant_key")) + .isNull(); + assertThat(wireResponses).isNotEmpty(); + for (Message response : wireResponses) { + assertThat(response.getDescriptorForType().findFieldByName("local_tenant_key")).isNull(); + assertThat(response.getUnknownFields().asMap()).isEmpty(); + assertThat(response.getAllFields().keySet()) + .noneMatch(field -> field.getName().equals("local_tenant_key")); + } + } + + private DbCounts dbCounts(Scenario scenario) { + return new DbCounts( + count( + "SELECT COUNT(*) FROM world_authored_source_intake " + + "WHERE target_namespace = ? AND intake_request_id = ?", + NAMESPACE, + scenario.intakeRequestId()), + count( + "SELECT COUNT(*) FROM world_authored_source_tenant_association " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + NAMESPACE, + scenario.canonicalTenantId()), + count( + "SELECT COUNT(*) FROM world_authored_source_tenant_key_reservation " + + "WHERE target_namespace = ? AND canonical_tenant_id = ? " + + "AND claim_kind = 'CANONICAL_AUTHORED_SOURCE'", + NAMESPACE, + scenario.canonicalTenantId())); + } + + private long count(String query, Object... bindings) { + return Objects.requireNonNull( + dsl.fetchOne(query, bindings), "World intake count query returned no row") + .get(0, Long.class); + } + + private static CommittedReceipt publicReceipt(WorldAuthoredSourceIntakeReceipt receipt) { + return new CommittedReceipt( + receipt.schemaVersion(), + receipt.targetNamespace(), + receipt.intakeRequestId(), + receipt.operationId(), + receipt.canonicalTenantId(), + receipt.worldSlug(), + receipt.sourceOperationId(), + receipt.sourceEvidenceDigest(), + receipt.requestDigest(), + receipt.receiptDigest()); + } + + private static Scenario newScenario(String worldSlug) { + UUID tenantId = UUID.randomUUID(); + UUID intakeRequestId = UUID.randomUUID(); + UUID sourceOperationId = UUID.randomUUID(); + UUID registrationRequestId = UUID.randomUUID(); + String tenantSlug = "tenant-" + tenantId.toString().replace("-", "").substring(0, 12); + String displayName = "World " + worldSlug; + long sourceGameRowId = + Math.abs(UUID.randomUUID().getMostSignificantBits() % 1_000_000_000L) + 1L; + String sourceGameTenantKey = "source-key-" + UUID.randomUUID(); + String sourceRequestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registrationRequestId, tenantId, tenantSlug, worldSlug, displayName); + String sourceEvidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequestId, + sourceOperationId, + sourceRequestDigest, + tenantId, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceGameTenantKey, + "NEW_GAME_ROW"); + AuthoredWorldSourceEvidence evidence = + new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequestId, + sourceOperationId, + sourceRequestDigest, + tenantId, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceGameTenantKey, + "NEW_GAME_ROW", + sourceEvidenceDigest); + return new Scenario( + tenantId, intakeRequestId, sourceOperationId, UUID.randomUUID(), worldSlug, evidence); + } + + private static void assertStatus(Status.Code expected, ThrowingAction action) { + assertThatThrownBy(action::run) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expected)); + } + + private static String pem(String type, byte[] bytes) { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return "-----BEGIN " + type + "-----\n" + body + "\n-----END " + type + "-----\n"; + } + + private static TestCertificate issueLeaf( + X500Name caName, PrivateKey caPrivateKey, String commonName, String workloadUri) + throws Exception { + KeyPair keyPair = newRsaKeyPair(); + X500Name subject = new X500Name("CN=" + commonName + ", O=FireMUD Test"); + GeneralNames subjectAltNames = + new GeneralNames( + new GeneralName[] { + new GeneralName(GeneralName.uniformResourceIdentifier, workloadUri), + new GeneralName(GeneralName.dNSName, "localhost"), + new GeneralName(GeneralName.iPAddress, "127.0.0.1") + }); + X509Certificate certificate = + issueCertificate( + subject, keyPair.getPublic(), caName, caPrivateKey, false, subjectAltNames); + return new TestCertificate(keyPair.getPrivate(), certificate); + } + + private static X509Certificate issueCertificate( + X500Name subject, + java.security.PublicKey publicKey, + X500Name issuer, + PrivateKey issuerPrivateKey, + boolean ca, + GeneralNames subjectAltNames) + throws Exception { + Instant now = Instant.now().minusSeconds(60); + JcaX509v3CertificateBuilder builder = + new JcaX509v3CertificateBuilder( + issuer, + BigInteger.valueOf(CERTIFICATE_SERIAL.getAndIncrement()), + Date.from(now), + Date.from(now.plusSeconds(60L * 60L * 24L * 14L)), + subject, + publicKey); + builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(ca)); + if (ca) { + builder.addExtension( + Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign)); + } else { + builder.addExtension( + Extension.keyUsage, + true, + new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); + builder.addExtension( + Extension.extendedKeyUsage, + false, + new ExtendedKeyUsage( + new KeyPurposeId[] {KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth})); + builder.addExtension(Extension.subjectAlternativeName, false, subjectAltNames); + } + return new JcaX509CertificateConverter() + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .getCertificate( + builder.build( + new JcaContentSignerBuilder("SHA256withRSA") + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .build(issuerPrivateKey))); + } + + private static KeyPair newRsaKeyPair() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + return generator.generateKeyPair(); + } + + private record Scenario( + UUID canonicalTenantId, + UUID intakeRequestId, + UUID sourceOperationId, + UUID readRequestId, + String worldSlug, + AuthoredWorldSourceEvidence sourceEvidence) { + IntakeRequest intakeRequest() { + return new IntakeRequest( + 1, + NAMESPACE, + intakeRequestId, + canonicalTenantId, + worldSlug, + sourceOperationId, + sourceEvidence.evidenceDigest()); + } + + ReadRequest readRequest() { + return new ReadRequest(intakeRequest(), readRequestId); + } + } + + private record DbCounts(long receipts, long associations, long reservations) {} + + private record TestCertificate(PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestCertificate worldServer, + TestCertificate gameDesignClient, + TestCertificate accountClient) {} + + @FunctionalInterface + private interface ThrowingAction { + void run() throws Throwable; + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeGrpcServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeGrpcServiceTest.java new file mode 100644 index 0000000000..62c5b598c6 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeGrpcServiceTest.java @@ -0,0 +1,438 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest; +import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceRequest; +import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeResponse; +import org.junit.jupiter.api.Test; +import org.springframework.dao.DataAccessResourceFailureException; + +class WorldAuthoredSourceIntakeGrpcServiceTest { + private static final String NAMESPACE = "firemud"; + private static final UUID INTAKE_REQUEST_ID = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID READ_REQUEST_ID = + UUID.fromString("66666666-6666-4666-8666-666666666666"); + private static final UUID TENANT_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID SOURCE_OPERATION_ID = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID OPERATION_ID = UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final String WORLD_SLUG = "violet-wilds"; + private static final String SOURCE_DIGEST = + source(NAMESPACE, TENANT_ID, SOURCE_OPERATION_ID, WORLD_SLUG).evidenceDigest(); + + private final WorldAuthoredSourceIntakeService intakeService = + mock(WorldAuthoredSourceIntakeService.class); + private final WorldAuthoredSourceIntakeGrpcService grpcService = + new WorldAuthoredSourceIntakeGrpcService(intakeService, NAMESPACE); + + @Test + void intakeReturnsOnlyTheExactCommittedReceiptBinding() { + IntakeRequest binding = binding(); + WorldAuthoredSourceIntakeReceipt receipt = receipt(binding, 9001L); + when(intakeService.intake( + 1, + NAMESPACE, + INTAKE_REQUEST_ID, + TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + SOURCE_DIGEST)) + .thenReturn(receipt); + RecordingObserver observer = new RecordingObserver<>(); + + withGameDesign(() -> grpcService.intakeAuthoredWorldSource(intakeRequest(), observer)); + + assertThat(observer.error).isNull(); + assertThat(observer.completed).isTrue(); + assertThat(observer.values).hasSize(1); + IntakeAuthoredWorldSourceResponse response = observer.values.get(0); + CommittedReceipt decoded = + WorldAuthoredSourceIntakeGrpcCodec.fromIntakeResponse(binding, response); + assertThat(decoded.operationId()).isEqualTo(OPERATION_ID); + assertThat(decoded.requestDigest()) + .isEqualTo(WorldAuthoredSourceIntakeGrpcCodec.requestDigest(binding)); + assertThat(response.getReceiptDigest()).isEqualTo(receipt.receiptDigest()); + assertThat(response.getAllFields().keySet()) + .extracting(field -> field.getName()) + .doesNotContain("local_tenant_key", "localTenantKey"); + verify(intakeService) + .intake( + 1, + NAMESPACE, + INTAKE_REQUEST_ID, + TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + SOURCE_DIGEST); + } + + @Test + void readReturnsCommittedReceiptAndEchoesSeparateRequestIdentity() { + IntakeRequest binding = binding(); + WorldAuthoredSourceIntakeReceipt receipt = receipt(binding, 9001L); + when(intakeService.readCommittedReceipt( + 1, + NAMESPACE, + READ_REQUEST_ID, + INTAKE_REQUEST_ID, + TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + SOURCE_DIGEST)) + .thenReturn(Optional.of(receipt)); + RecordingObserver observer = new RecordingObserver<>(); + + withGameDesign(() -> grpcService.readAuthoredWorldSourceIntake(readRequest(), observer)); + + assertThat(observer.error).isNull(); + assertThat(observer.completed).isTrue(); + assertThat(observer.values).hasSize(1); + ReadAuthoredWorldSourceIntakeResponse response = observer.values.get(0); + assertThat(response.getRequestId()).isEqualTo(READ_REQUEST_ID.toString()); + assertThat(response.getIntakeRequestId()).isEqualTo(INTAKE_REQUEST_ID.toString()); + CommittedReceipt decoded = + WorldAuthoredSourceIntakeGrpcCodec.fromReadResponse( + new WorldAuthoredSourceIntakeGrpcCodec.ReadRequest(binding, READ_REQUEST_ID), response); + assertThat(decoded.operationId()).isEqualTo(OPERATION_ID); + assertThat(decoded.requestDigest()) + .isEqualTo(WorldAuthoredSourceIntakeGrpcCodec.requestDigest(binding)); + verify(intakeService) + .readCommittedReceipt( + 1, + NAMESPACE, + READ_REQUEST_ID, + INTAKE_REQUEST_ID, + TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + SOURCE_DIGEST); + } + + @Test + void rejectsUnknownWireFieldsBeforeCallingOwnerService() { + IntakeAuthoredWorldSourceRequest request = + intakeRequest().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build(); + RecordingObserver observer = new RecordingObserver<>(); + + grpcService.intakeAuthoredWorldSource(request, observer); + + assertThat(Status.fromThrowable(observer.error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(observer.values).isEmpty(); + assertThat(observer.completed).isFalse(); + verifyNoInteractions(intakeService); + + RecordingObserver invalid = new RecordingObserver<>(); + withGameDesign(() -> grpcService.intakeAuthoredWorldSource(request, invalid)); + assertThat(Status.fromThrowable(invalid.error).getCode()) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(invalid.values).isEmpty(); + verifyNoInteractions(intakeService); + + RecordingObserver wrongTargetNamespace = + new RecordingObserver<>(); + IntakeAuthoredWorldSourceRequest crossNamespaceRequest = + intakeRequest().toBuilder().setTargetNamespace("other").build(); + withGameDesign( + () -> grpcService.intakeAuthoredWorldSource(crossNamespaceRequest, wrongTargetNamespace)); + assertThat(Status.fromThrowable(wrongTargetNamespace.error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(wrongTargetNamespace.values).isEmpty(); + verifyNoInteractions(intakeService); + + RecordingObserver wrongWorkload = + new RecordingObserver<>(); + withPeer( + NAMESPACE, + "game-session-service", + () -> grpcService.readAuthoredWorldSourceIntake(readRequest(), wrongWorkload)); + assertThat(Status.fromThrowable(wrongWorkload.error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(wrongWorkload.values).isEmpty(); + verifyNoInteractions(intakeService); + + RecordingObserver wrongNamespace = new RecordingObserver<>(); + withPeer( + "other", + "game-design-service", + () -> grpcService.intakeAuthoredWorldSource(intakeRequest(), wrongNamespace)); + assertThat(Status.fromThrowable(wrongNamespace.error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(wrongNamespace.values).isEmpty(); + verifyNoInteractions(intakeService); + + RecordingObserver wrongReadTargetNamespace = + new RecordingObserver<>(); + ReadAuthoredWorldSourceIntakeRequest crossNamespaceReadRequest = + readRequest().toBuilder().setTargetNamespace("other").build(); + withGameDesign( + () -> + grpcService.readAuthoredWorldSourceIntake( + crossNamespaceReadRequest, wrongReadTargetNamespace)); + assertThat(Status.fromThrowable(wrongReadTargetNamespace.error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(wrongReadTargetNamespace.values).isEmpty(); + verifyNoInteractions(intakeService); + } + + @Test + void mapsPeerDenialAndRepositoryConflictToNonSuccessGrpcOutcomes() { + doThrow( + new SecurityException("not the Game Design workload"), + new WorldAuthoredSourceIntakeRepository.RegistrationConflictException("changed source")) + .when(intakeService) + .intake( + 1, + NAMESPACE, + INTAKE_REQUEST_ID, + TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + SOURCE_DIGEST); + RecordingObserver denied = new RecordingObserver<>(); + withGameDesign(() -> grpcService.intakeAuthoredWorldSource(intakeRequest(), denied)); + assertThat(Status.fromThrowable(denied.error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(denied.values).isEmpty(); + + RecordingObserver conflict = new RecordingObserver<>(); + withGameDesign(() -> grpcService.intakeAuthoredWorldSource(intakeRequest(), conflict)); + assertThat(Status.fromThrowable(conflict.error).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(conflict.values).isEmpty(); + } + + @Test + void preservesTransientStorageFailureAndReportsAbsentReadWithoutReceipt() { + when(intakeService.intake( + 1, + NAMESPACE, + INTAKE_REQUEST_ID, + TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + SOURCE_DIGEST)) + .thenThrow(new DataAccessResourceFailureException("database unavailable")); + RecordingObserver unavailable = new RecordingObserver<>(); + withGameDesign(() -> grpcService.intakeAuthoredWorldSource(intakeRequest(), unavailable)); + assertThat(Status.fromThrowable(unavailable.error).getCode()) + .isEqualTo(Status.Code.UNAVAILABLE); + assertThat(unavailable.values).isEmpty(); + + when(intakeService.readCommittedReceipt( + 1, + NAMESPACE, + READ_REQUEST_ID, + INTAKE_REQUEST_ID, + TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + SOURCE_DIGEST)) + .thenReturn(Optional.empty()); + RecordingObserver missing = new RecordingObserver<>(); + withGameDesign(() -> grpcService.readAuthoredWorldSourceIntake(readRequest(), missing)); + assertThat(Status.fromThrowable(missing.error).getCode()).isEqualTo(Status.Code.NOT_FOUND); + assertThat(missing.values).isEmpty(); + verify(intakeService) + .readCommittedReceipt( + 1, + NAMESPACE, + READ_REQUEST_ID, + INTAKE_REQUEST_ID, + TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + SOURCE_DIGEST); + } + + @Test + void refusesToReturnAnOwnerReceiptWhoseBindingDoesNotMatch() { + WorldAuthoredSourceIntakeReceipt changed = receipt(binding("other-world"), 9001L); + when(intakeService.intake( + 1, + NAMESPACE, + INTAKE_REQUEST_ID, + TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + SOURCE_DIGEST)) + .thenReturn(changed); + RecordingObserver observer = new RecordingObserver<>(); + + withGameDesign(() -> grpcService.intakeAuthoredWorldSource(intakeRequest(), observer)); + + assertThat(Status.fromThrowable(observer.error).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(observer.values).isEmpty(); + verify(intakeService) + .intake( + 1, + NAMESPACE, + INTAKE_REQUEST_ID, + TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + SOURCE_DIGEST); + } + + private static IntakeRequest binding() { + return binding(WORLD_SLUG); + } + + private static IntakeRequest binding(String worldSlug) { + AuthoredWorldSourceEvidence source = + source(NAMESPACE, TENANT_ID, SOURCE_OPERATION_ID, worldSlug); + return new IntakeRequest( + 1, + NAMESPACE, + INTAKE_REQUEST_ID, + TENANT_ID, + worldSlug, + SOURCE_OPERATION_ID, + source.evidenceDigest()); + } + + private static IntakeAuthoredWorldSourceRequest intakeRequest() { + return WorldAuthoredSourceIntakeGrpcCodec.toIntakeRequest(binding()); + } + + private static ReadAuthoredWorldSourceIntakeRequest readRequest() { + return WorldAuthoredSourceIntakeGrpcCodec.toReadRequest( + new WorldAuthoredSourceIntakeGrpcCodec.ReadRequest(binding(), READ_REQUEST_ID)); + } + + private static WorldAuthoredSourceIntakeReceipt receipt( + IntakeRequest binding, long localTenantKey) { + AuthoredWorldSourceEvidence source = + source( + binding.targetNamespace(), + binding.canonicalTenantId(), + binding.sourceOperationId(), + binding.worldSlug()); + if (!binding.expectedSourceEvidenceDigest().equals(source.evidenceDigest())) { + throw new IllegalArgumentException("Test source evidence does not match intake binding"); + } + String requestDigest = + WorldAuthoredSourceIntakeDigest.requestDigest( + binding.targetNamespace(), binding.intakeRequestId(), source); + return new WorldAuthoredSourceIntakeReceipt( + 1, + binding.targetNamespace(), + binding.intakeRequestId(), + OPERATION_ID, + binding.canonicalTenantId(), + binding.worldSlug(), + binding.sourceOperationId(), + binding.expectedSourceEvidenceDigest(), + requestDigest, + WorldAuthoredSourceIntakeDigest.receiptDigest( + binding.targetNamespace(), OPERATION_ID, requestDigest, source, localTenantKey), + localTenantKey, + source); + } + + private static AuthoredWorldSourceEvidence source( + String namespace, UUID tenantId, UUID sourceOperationId, String worldSlug) { + UUID registrationRequestId = UUID.fromString("11111111-1111-4111-8111-111111111111"); + String sourceRequestDigest = + AuthoredWorldSourceDigest.requestDigest( + namespace, registrationRequestId, tenantId, "north-star", worldSlug, "Café 🐉"); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + namespace, + registrationRequestId, + sourceOperationId, + sourceRequestDigest, + tenantId, + "north-star", + worldSlug, + "Café 🐉", + 42L, + "legacy-game-tenant-42", + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + namespace, + registrationRequestId, + sourceOperationId, + sourceRequestDigest, + tenantId, + "north-star", + worldSlug, + "Café 🐉", + 42L, + "legacy-game-tenant-42", + "NEW_GAME_ROW", + evidenceDigest); + } + + private static void withGameDesign(Runnable action) { + withPeer(NAMESPACE, "game-design-service", action); + } + + private static void withPeer(String namespace, String service, Runnable action) { + GrpcPeerIdentity peer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + action.run(); + } finally { + context.detach(previous); + } + } + + private static final class RecordingObserver implements StreamObserver { + private final List values = new ArrayList<>(); + private Throwable error; + private boolean completed; + + @Override + public void onNext(T value) { + values.add(value); + } + + @Override + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "The test recorder retains the exact original throwable solely for assertion.") + public void onError(Throwable throwable) { + error = throwable; + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeMtlsTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeMtlsTest.java new file mode 100644 index 0000000000..0e5cb1d834 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeMtlsTest.java @@ -0,0 +1,695 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.ForwardingServerCall; +import io.grpc.ManagedChannel; +import io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.ServerServiceDefinition; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.MetadataUtils; +import java.math.BigInteger; +import java.net.InetSocketAddress; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.PrivateKey; +import java.security.Security; +import java.security.cert.X509Certificate; +import java.time.Instant; +import java.util.Base64; +import java.util.Date; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicLong; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeClient; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.ReadRequest; +import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceRequest; +import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldAuthoredSourceIntakeServiceGrpc; +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.asn1.x509.BasicConstraints; +import org.bouncycastle.asn1.x509.ExtendedKeyUsage; +import org.bouncycastle.asn1.x509.Extension; +import org.bouncycastle.asn1.x509.GeneralName; +import org.bouncycastle.asn1.x509.GeneralNames; +import org.bouncycastle.asn1.x509.KeyPurposeId; +import org.bouncycastle.asn1.x509.KeyUsage; +import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; +import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** Physical socket proof with a mocked owner service, not database-to-socket proof. */ +class WorldAuthoredSourceIntakeMtlsTest { + private static final String NAMESPACE = "test"; + private static final String WORLD_PEER_URI = + "spiffe://firemud/ns/test/sa/world-management-service"; + private static final Metadata.Key AUTHORIZATION = + Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER); + private static final UUID INTAKE_ID = UUID.fromString("12345678-1234-4234-8234-123456789abc"); + private static final UUID TENANT_ID = UUID.fromString("22345678-1234-4234-8234-123456789abc"); + private static final UUID SOURCE_OPERATION_ID = + UUID.fromString("32345678-1234-4234-8234-123456789abc"); + private static final UUID READ_ID = UUID.fromString("42345678-1234-4234-8234-123456789abc"); + private static final UUID WORLD_OPERATION_ID = + UUID.fromString("52345678-1234-4234-8234-123456789abc"); + private static final long PRIVATE_WORLD_TENANT_KEY = 987654321L; + private static final AtomicLong CERTIFICATE_SERIAL = new AtomicLong(1); + private static final UnknownFieldSet UNKNOWN_FIELD = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + private static TestPki pki; + + @TempDir Path tempDirectory; + + private Server server; + private WorldAuthoredSourceIntakeService intakeService; + + private static final AuthoredWorldSourceEvidence SOURCE_EVIDENCE = sourceEvidence(); + private static final String SOURCE_EVIDENCE_DIGEST = SOURCE_EVIDENCE.evidenceDigest(); + private static final IntakeRequest INTAKE_REQUEST = + new IntakeRequest( + 1, + NAMESPACE, + INTAKE_ID, + TENANT_ID, + "world-one", + SOURCE_OPERATION_ID, + SOURCE_EVIDENCE_DIGEST); + private static final ReadRequest READ_REQUEST = new ReadRequest(INTAKE_REQUEST, READ_ID); + private static final WorldAuthoredSourceIntakeReceipt WORLD_RECEIPT = worldReceipt(); + + @BeforeAll + static void generateFreshTestPki() throws Exception { + if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { + Security.addProvider(new BouncyCastleProvider()); + } + KeyPair caKeyPair = newRsaKeyPair(); + X500Name caName = new X500Name("CN=Fresh World Authored Intake Test CA, O=FireMUD Test"); + X509Certificate caCertificate = + issueCertificate(caName, caKeyPair.getPublic(), caName, caKeyPair.getPrivate(), true, null); + pki = + new TestPki( + caCertificate, + issueLeaf(caName, caKeyPair.getPrivate(), "world-management-server", WORLD_PEER_URI), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "wrong-world-server-identity", + "spiffe://firemud/ns/test/sa/game-design-service"), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "game-design-service", + "spiffe://firemud/ns/test/sa/game-design-service"), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "account-service", + "spiffe://firemud/ns/test/sa/account-service"), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "game-session-service", + "spiffe://firemud/ns/test/sa/game-session-service"), + issueLeaf(caName, caKeyPair.getPrivate(), "world-management-service", WORLD_PEER_URI), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "wrong-namespace-game-design-service", + "spiffe://firemud/ns/other-test/sa/game-design-service"), + issueLeaf(caName, caKeyPair.getPrivate(), "shared-workload-certificate", null)); + } + + @AfterEach + void stopPhysicalReceiver() throws Exception { + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + } + + @Test + void sameNamespaceGameDesignIntakesThenReadsExactReceiptOverSocketMtls() throws Exception { + startServer(pki.worldServer(), null); + try (WorldAuthoredSourceIntakeClient client = client(pki.gameDesignClient(), "game-design")) { + CommittedReceipt accepted = client.intake(INTAKE_REQUEST); + CommittedReceipt readback = client.read(READ_REQUEST); + + assertPublicReceipt(accepted); + assertPublicReceipt(readback); + verify(intakeService) + .intake( + 1, + NAMESPACE, + INTAKE_ID, + TENANT_ID, + "world-one", + SOURCE_OPERATION_ID, + SOURCE_EVIDENCE_DIGEST); + verify(intakeService) + .readCommittedReceipt( + 1, + NAMESPACE, + READ_ID, + INTAKE_ID, + TENANT_ID, + "world-one", + SOURCE_OPERATION_ID, + SOURCE_EVIDENCE_DIGEST); + } + } + + @Test + void wrongWorkloadsAndWrongNamespaceAreDeniedBeforeDecodeOrOwnerAccess() throws Exception { + startServer(pki.worldServer(), null); + for (TestCertificate wrongCaller : + List.of( + pki.accountClient(), + pki.gameSessionClient(), + pki.worldClient(), + pki.otherNamespaceClient())) { + try (WorldAuthoredSourceIntakeClient client = client(wrongCaller, "caller")) { + assertPermissionDenied(() -> client.intake(INTAKE_REQUEST)); + assertPermissionDenied(() -> client.read(READ_REQUEST)); + } + } + + ManagedChannel malformedCallerChannel = rawMtlsChannel(pki.accountClient()); + try { + WorldAuthoredSourceIntakeServiceGrpc.WorldAuthoredSourceIntakeServiceBlockingStub stub = + WorldAuthoredSourceIntakeServiceGrpc.newBlockingStub(malformedCallerChannel) + .withDeadlineAfter(3, TimeUnit.SECONDS); + Throwable failure = + catchFailure( + () -> + stub.intakeAuthoredWorldSource( + IntakeAuthoredWorldSourceRequest.getDefaultInstance())); + assertThat(failure).isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(Status.Code.PERMISSION_DENIED); + } finally { + stopChannel(malformedCallerChannel); + } + verifyNoInteractions(intakeService); + } + + @Test + void sharedCertificateWithoutWorkloadUriCannotReachOwner() throws Exception { + startServer(pki.worldServer(), null); + try (WorldAuthoredSourceIntakeClient client = + client(pki.noWorkloadUriClient(), "shared-certificate")) { + assertPermissionDenied(() -> client.intake(INTAKE_REQUEST)); + assertPermissionDenied(() -> client.read(READ_REQUEST)); + } + verifyNoInteractions(intakeService); + } + + @Test + void jwtOnlyAndPlaintextCallersFailAtThePhysicalTransportBoundary() throws Exception { + startServer(pki.worldServer(), null); + Metadata jwtOnlyHeaders = new Metadata(); + jwtOnlyHeaders.put(AUTHORIZATION, "Bearer header.payload.signature"); + ManagedChannel noCertificateChannel = rawMtlsChannel(null); + try { + assertTransportFailure( + () -> + WorldAuthoredSourceIntakeServiceGrpc.newBlockingStub(noCertificateChannel) + .withInterceptors(MetadataUtils.newAttachHeadersInterceptor(jwtOnlyHeaders)) + .withDeadlineAfter(3, TimeUnit.SECONDS) + .intakeAuthoredWorldSource( + WorldAuthoredSourceIntakeGrpcCodec.toIntakeRequest(INTAKE_REQUEST))); + } finally { + stopChannel(noCertificateChannel); + } + + ManagedChannel plaintextChannel = + NettyChannelBuilder.forAddress(new InetSocketAddress("127.0.0.1", server.getPort())) + .usePlaintext() + .build(); + try { + assertTransportFailure( + () -> + WorldAuthoredSourceIntakeServiceGrpc.newBlockingStub(plaintextChannel) + .withDeadlineAfter(3, TimeUnit.SECONDS) + .intakeAuthoredWorldSource( + WorldAuthoredSourceIntakeGrpcCodec.toIntakeRequest(INTAKE_REQUEST))); + } finally { + stopChannel(plaintextChannel); + } + + CommonGrpcClientProperties plaintext = tlsProperties(pki.gameDesignClient(), "constructor"); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new WorldAuthoredSourceIntakeClient( + endpoints(), + plaintext, + new net.firedevops.firemud.common.grpc.GrpcChannelFactory(), + NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + verifyNoInteractions(intakeService); + } + + @Test + void clientRejectsAResponseFromTheWrongAuthenticatedWorldServerIdentity() throws Exception { + startServer(pki.wrongWorldServer(), null); + try (WorldAuthoredSourceIntakeClient client = client(pki.gameDesignClient(), "wrong-server")) { + assertUnauthenticated(() -> client.intake(INTAKE_REQUEST)); + assertUnauthenticated(() -> client.read(READ_REQUEST)); + } + verifyNoInteractions(intakeService); + } + + @Test + void changedEchoDigestAndUnknownFieldsAreRejectedAfterSocketResponse() throws Exception { + startServer(pki.worldServer(), responseMutation(ResponseMutation.CHANGED_ECHO)); + try (WorldAuthoredSourceIntakeClient client = client(pki.gameDesignClient(), "changed-echo")) { + assertThatThrownBy(() -> client.intake(INTAKE_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid authored-source intake receipt"); + } + stopServer(); + + startServer(pki.worldServer(), responseMutation(ResponseMutation.CHANGED_DIGEST)); + try (WorldAuthoredSourceIntakeClient client = + client(pki.gameDesignClient(), "changed-digest")) { + assertThatThrownBy(() -> client.intake(INTAKE_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid authored-source intake receipt"); + } + stopServer(); + + startServer(pki.worldServer(), responseMutation(ResponseMutation.UNKNOWN_FIELDS)); + try (WorldAuthoredSourceIntakeClient client = + client(pki.gameDesignClient(), "unknown-fields")) { + assertThatThrownBy(() -> client.intake(INTAKE_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid authored-source intake receipt"); + } + stopServer(); + + startServer(pki.worldServer(), responseMutation(ResponseMutation.CHANGED_READ_ID)); + try (WorldAuthoredSourceIntakeClient client = + client(pki.gameDesignClient(), "changed-read-id")) { + assertThatThrownBy(() -> client.read(READ_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid authored-source intake readback"); + } + } + + @Test + void publicWireMessagesNeverContainWorldPrivateNumericTenantKey() { + List messages = + List.of( + IntakeAuthoredWorldSourceRequest.getDescriptor(), + IntakeAuthoredWorldSourceResponse.getDescriptor(), + ReadAuthoredWorldSourceIntakeRequest.getDescriptor(), + ReadAuthoredWorldSourceIntakeResponse.getDescriptor()); + + for (var descriptor : messages) { + assertThat(descriptor.getFields()) + .extracting(field -> field.getName()) + .doesNotContain("local_tenant_key", "world_tenant_key", "tenant_id"); + } + assertThat(WORLD_RECEIPT.localTenantKey()).isEqualTo(PRIVATE_WORLD_TENANT_KEY); + } + + private void startServer(TestCertificate serverCertificate, ServerInterceptor responseInterceptor) + throws Exception { + intakeService = mock(WorldAuthoredSourceIntakeService.class); + when(intakeService.intake( + eq(1), + eq(NAMESPACE), + eq(INTAKE_ID), + eq(TENANT_ID), + eq("world-one"), + eq(SOURCE_OPERATION_ID), + eq(SOURCE_EVIDENCE_DIGEST))) + .thenReturn(WORLD_RECEIPT); + when(intakeService.readCommittedReceipt( + eq(1), + eq(NAMESPACE), + eq(READ_ID), + eq(INTAKE_ID), + eq(TENANT_ID), + eq("world-one"), + eq(SOURCE_OPERATION_ID), + eq(SOURCE_EVIDENCE_DIGEST))) + .thenReturn(Optional.of(WORLD_RECEIPT)); + + WorldAuthoredSourceIntakeGrpcService handler = + new WorldAuthoredSourceIntakeGrpcService(intakeService, NAMESPACE); + ServerServiceDefinition intercepted = + ServerInterceptors.intercept(handler, new GrpcPeerIdentityInterceptor()); + if (responseInterceptor != null) { + intercepted = ServerInterceptors.intercept(intercepted, responseInterceptor); + } + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + serverCertificate.privateKey(), serverCertificate.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(intercepted) + .build() + .start(); + } + + private void stopServer() throws Exception { + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } + + private WorldAuthoredSourceIntakeClient client(TestCertificate certificate, String label) + throws Exception { + WorldAuthoredSourceIntakeClient client = + new WorldAuthoredSourceIntakeClient( + endpoints(), + tlsProperties(certificate, label), + new net.firedevops.firemud.common.grpc.GrpcChannelFactory(), + NAMESPACE); + client.init(); + return client; + } + + private ServiceEndpointsProperties endpoints() { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setWorldManagementService("127.0.0.1:" + server.getPort()); + return endpoints; + } + + private CommonGrpcClientProperties tlsProperties(TestCertificate certificate, String label) + throws Exception { + Path clientCertificate = tempDirectory.resolve(label + "-client.crt"); + Path clientPrivateKey = tempDirectory.resolve(label + "-client.key"); + Files.writeString( + clientCertificate, pem("CERTIFICATE", certificate.certificate().getEncoded())); + Files.writeString(clientPrivateKey, pem("PRIVATE KEY", certificate.privateKey().getEncoded())); + Path caCertificate = tempDirectory.resolve("test-ca.crt"); + Files.writeString(caCertificate, pem("CERTIFICATE", pki.caCertificate().getEncoded())); + + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(clientCertificate.toString()); + tls.setPrivateKey(clientPrivateKey.toString()); + tls.setCaCert(caCertificate.toString()); + return tls; + } + + private ManagedChannel rawMtlsChannel(TestCertificate certificate) throws Exception { + var sslBuilder = GrpcSslContexts.forClient().trustManager(pki.caCertificate()); + if (certificate != null) { + sslBuilder.keyManager(certificate.privateKey(), certificate.certificate()); + } + return NettyChannelBuilder.forAddress(new InetSocketAddress("127.0.0.1", server.getPort())) + .sslContext(sslBuilder.build()) + .build(); + } + + private static ServerInterceptor responseMutation(ResponseMutation mutation) { + return new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + ServerCall forwardingCall = + new ForwardingServerCall.SimpleForwardingServerCall<>(call) { + @Override + public void sendMessage(RespT message) { + Object changed = mutateResponse(message, mutation); + @SuppressWarnings("unchecked") + RespT typedChanged = (RespT) changed; + super.sendMessage(typedChanged); + } + }; + return next.startCall(forwardingCall, headers); + } + }; + } + + private static Object mutateResponse(Object response, ResponseMutation mutation) { + if (response instanceof IntakeAuthoredWorldSourceResponse intake) { + return switch (mutation) { + case CHANGED_ECHO -> intake.toBuilder().setWorldSlug("other-world").build(); + case CHANGED_DIGEST -> + intake.toBuilder().setRequestDigest("sha256:" + "c".repeat(64)).build(); + case UNKNOWN_FIELDS -> intake.toBuilder().setUnknownFields(UNKNOWN_FIELD).build(); + case CHANGED_READ_ID -> intake; + }; + } + if (response instanceof ReadAuthoredWorldSourceIntakeResponse read) { + return switch (mutation) { + case CHANGED_READ_ID -> read.toBuilder().setRequestId(INTAKE_ID.toString()).build(); + case UNKNOWN_FIELDS -> read.toBuilder().setUnknownFields(UNKNOWN_FIELD).build(); + case CHANGED_ECHO, CHANGED_DIGEST -> read; + }; + } + return response; + } + + private static void assertPublicReceipt(CommittedReceipt actual) { + assertThat(actual.schemaVersion()).isEqualTo(1); + assertThat(actual.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(actual.intakeRequestId()).isEqualTo(INTAKE_ID); + assertThat(actual.operationId()).isEqualTo(WORLD_OPERATION_ID); + assertThat(actual.canonicalTenantId()).isEqualTo(TENANT_ID); + assertThat(actual.worldSlug()).isEqualTo("world-one"); + assertThat(actual.sourceOperationId()).isEqualTo(SOURCE_OPERATION_ID); + assertThat(actual.sourceEvidenceDigest()).isEqualTo(SOURCE_EVIDENCE_DIGEST); + assertThat(actual.requestDigest()).isEqualTo(WORLD_RECEIPT.requestDigest()); + assertThat(actual.receiptDigest()).isEqualTo(WORLD_RECEIPT.receiptDigest()); + } + + private static void assertPermissionDenied(Runnable call) { + Throwable failure = catchFailure(call); + assertThat(failure).isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(Status.Code.PERMISSION_DENIED); + } + + private static void assertUnauthenticated(Runnable call) { + Throwable failure = catchFailure(call); + assertThat(failure).isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); + } + + private static void assertTransportFailure(Runnable call) { + Throwable failure = catchFailure(call); + assertThat(failure).isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(failure).getCode()).isNotEqualTo(Status.Code.DEADLINE_EXCEEDED); + } + + private static Throwable catchFailure(Runnable call) { + try { + call.run(); + return null; + } catch (Throwable throwable) { + return throwable; + } + } + + private static void stopChannel(ManagedChannel channel) throws InterruptedException { + channel.shutdownNow(); + assertThat(channel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + + private static AuthoredWorldSourceEvidence sourceEvidence() { + UUID registrationId = UUID.fromString("62345678-1234-4234-8234-123456789abc"); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registrationId, TENANT_ID, "tenant-one", "world-one", "World One"); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationId, + SOURCE_OPERATION_ID, + requestDigest, + TENANT_ID, + "tenant-one", + "world-one", + "World One", + 17L, + "source-game-key", + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationId, + SOURCE_OPERATION_ID, + requestDigest, + TENANT_ID, + "tenant-one", + "world-one", + "World One", + 17L, + "source-game-key", + "NEW_GAME_ROW", + evidenceDigest); + } + + private static WorldAuthoredSourceIntakeReceipt worldReceipt() { + String requestDigest = + WorldAuthoredSourceIntakeDigest.requestDigest(NAMESPACE, INTAKE_ID, SOURCE_EVIDENCE); + String receiptDigest = + WorldAuthoredSourceIntakeDigest.receiptDigest( + NAMESPACE, + WORLD_OPERATION_ID, + requestDigest, + SOURCE_EVIDENCE, + PRIVATE_WORLD_TENANT_KEY); + return new WorldAuthoredSourceIntakeReceipt( + 1, + NAMESPACE, + INTAKE_ID, + WORLD_OPERATION_ID, + TENANT_ID, + "world-one", + SOURCE_OPERATION_ID, + SOURCE_EVIDENCE_DIGEST, + requestDigest, + receiptDigest, + PRIVATE_WORLD_TENANT_KEY, + SOURCE_EVIDENCE); + } + + private static String pem(String type, byte[] bytes) { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return "-----BEGIN " + type + "-----\n" + body + "\n-----END " + type + "-----\n"; + } + + private static TestCertificate issueLeaf( + X500Name caName, PrivateKey caPrivateKey, String commonName, String workloadUri) + throws Exception { + KeyPair keyPair = newRsaKeyPair(); + X500Name subject = new X500Name("CN=" + commonName + ", O=FireMUD Test"); + GeneralName[] subjectAltNames = + workloadUri == null + ? new GeneralName[] { + new GeneralName(GeneralName.dNSName, "localhost"), + new GeneralName(GeneralName.iPAddress, "127.0.0.1") + } + : new GeneralName[] { + new GeneralName(GeneralName.uniformResourceIdentifier, workloadUri), + new GeneralName(GeneralName.dNSName, "localhost"), + new GeneralName(GeneralName.iPAddress, "127.0.0.1") + }; + X509Certificate certificate = + issueCertificate( + subject, + keyPair.getPublic(), + caName, + caPrivateKey, + false, + new GeneralNames(subjectAltNames)); + return new TestCertificate(keyPair.getPrivate(), certificate); + } + + private static X509Certificate issueCertificate( + X500Name subject, + java.security.PublicKey publicKey, + X500Name issuer, + PrivateKey issuerPrivateKey, + boolean ca, + GeneralNames subjectAltNames) + throws Exception { + Instant now = Instant.now().minusSeconds(60); + JcaX509v3CertificateBuilder builder = + new JcaX509v3CertificateBuilder( + issuer, + BigInteger.valueOf(CERTIFICATE_SERIAL.getAndIncrement()), + Date.from(now), + Date.from(now.plusSeconds(60L * 60L * 24L * 14L)), + subject, + publicKey); + builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(ca)); + if (ca) { + builder.addExtension( + Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign)); + } else { + builder.addExtension( + Extension.keyUsage, + true, + new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); + builder.addExtension( + Extension.extendedKeyUsage, + false, + new ExtendedKeyUsage( + new KeyPurposeId[] {KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth})); + builder.addExtension(Extension.subjectAlternativeName, false, subjectAltNames); + } + return new JcaX509CertificateConverter() + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .getCertificate( + builder.build( + new JcaContentSignerBuilder("SHA256withRSA") + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .build(issuerPrivateKey))); + } + + private static KeyPair newRsaKeyPair() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + return generator.generateKeyPair(); + } + + private enum ResponseMutation { + CHANGED_ECHO, + CHANGED_DIGEST, + UNKNOWN_FIELDS, + CHANGED_READ_ID + } + + private record TestCertificate(PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestCertificate worldServer, + TestCertificate wrongWorldServer, + TestCertificate gameDesignClient, + TestCertificate accountClient, + TestCertificate gameSessionClient, + TestCertificate worldClient, + TestCertificate otherNamespaceClient, + TestCertificate noWorkloadUriClient) {} +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeServiceTest.java index b3ea8870ac..d978161ef6 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeServiceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeServiceTest.java @@ -34,6 +34,7 @@ class WorldAuthoredSourceIntakeServiceTest { private static final UUID TENANT = UUID.fromString("22222222-2222-4222-8222-222222222222"); private static final UUID SOURCE_OPERATION = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID READ_REQUEST = UUID.fromString("66666666-6666-4666-8666-666666666666"); private static final String WORLD = "violet-wilds"; private final AuthoredWorldSourceClient client = mock(AuthoredWorldSourceClient.class); @@ -110,6 +111,22 @@ INTAKE_REQUEST, new UUID(0L, 0L), WORLD, SOURCE_OPERATION, digest('a'))) () -> service.intake(INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, "sha256:bad")) .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + service.intake( + 2, + NAMESPACE, + INTAKE_REQUEST, + TENANT, + WORLD, + SOURCE_OPERATION, + digest('a'))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + service.intake( + 1, "other", INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, digest('a'))) + .isInstanceOf(SecurityException.class); return null; }); @@ -164,6 +181,124 @@ void exactStoredRetryReturnsOriginalReceiptWithoutCallingGameDesign() { assertThat(transactionManager.startedWith).isNull(); } + @Test + void exactCommittedReadReturnsWorldReceiptWithoutSourceReadOrAllocation() { + AuthoredWorldSourceEvidence source = source(NAMESPACE, TENANT, SOURCE_OPERATION, WORLD); + WorldAuthoredSourceIntakeReceipt receipt = receipt(source, 9001L); + when(repository.read(NAMESPACE, INTAKE_REQUEST)).thenReturn(Optional.of(receipt)); + + Optional result = + withGameDesign( + () -> + service.readCommittedReceipt( + 1, + NAMESPACE, + READ_REQUEST, + INTAKE_REQUEST, + TENANT, + WORLD, + SOURCE_OPERATION, + source.evidenceDigest())); + + assertThat(result).containsSame(receipt); + verify(repository).read(NAMESPACE, INTAKE_REQUEST); + verify(repository, never()).acceptFresh(any(), any(), any()); + verifyNoInteractions(client); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void exactCommittedReadRejectsWrongPeerNamespaceAndChangedReceiptBindingBeforeOwnerAccess() { + AuthoredWorldSourceEvidence source = source(NAMESPACE, TENANT, SOURCE_OPERATION, WORLD); + WorldAuthoredSourceIntakeReceipt receipt = receipt(source, 9001L); + when(repository.read(NAMESPACE, INTAKE_REQUEST)).thenReturn(Optional.of(receipt)); + + assertThatThrownBy( + () -> + withoutPeer( + () -> + service.readCommittedReceipt( + 1, + NAMESPACE, + READ_REQUEST, + INTAKE_REQUEST, + TENANT, + WORLD, + SOURCE_OPERATION, + source.evidenceDigest()))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withPeer( + peer(NAMESPACE, "game-session-service"), + () -> + service.readCommittedReceipt( + 1, + NAMESPACE, + READ_REQUEST, + INTAKE_REQUEST, + TENANT, + WORLD, + SOURCE_OPERATION, + source.evidenceDigest()))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.readCommittedReceipt( + 1, + "other", + READ_REQUEST, + INTAKE_REQUEST, + TENANT, + WORLD, + SOURCE_OPERATION, + source.evidenceDigest()))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.readCommittedReceipt( + 1, + NAMESPACE, + INTAKE_REQUEST, + INTAKE_REQUEST, + TENANT, + WORLD, + SOURCE_OPERATION, + source.evidenceDigest()))) + .isInstanceOf(IllegalArgumentException.class); + + verifyNoInteractions(client, repository); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void exactCommittedReadReturnsAbsentWithoutMutationWhenNoReceiptExists() { + when(repository.read(NAMESPACE, INTAKE_REQUEST)).thenReturn(Optional.empty()); + + Optional result = + withGameDesign( + () -> + service.readCommittedReceipt( + 1, + NAMESPACE, + READ_REQUEST, + INTAKE_REQUEST, + TENANT, + WORLD, + SOURCE_OPERATION, + digest('a'))); + + assertThat(result).isEmpty(); + verify(repository).read(NAMESPACE, INTAKE_REQUEST); + verify(repository, never()).acceptFresh(any(), any(), any()); + verifyNoInteractions(client); + assertThat(transactionManager.startedWith).isNull(); + } + @Test void changedRequestScopeOrExpectedDigestConflictsBeforeRemoteReadOrMutation() { AuthoredWorldSourceEvidence source = source(NAMESPACE, TENANT, SOURCE_OPERATION, WORLD); From 202c58f1605018f6bf51277ac4f431497eca9a34 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 00:49:54 +1300 Subject: [PATCH 09/13] Fix canonical JOIN diagnostic recovery and Game Session intake transactions --- .github/workflows/ci.yml | 14 +- .../game-session-service/api-contracts.md | 2 +- .../player-access-and-session.md | 6 +- .../world-runtime-and-movement.md | 4 +- ...ical_join_terminal_attempt_diagnostics.sql | 21 ++ ...icalJoinReconciliationIntegrationTest.java | 4 + ...ScopeCanonicalIdentityIntegrationTest.java | 74 ++++- ...eSessionAuthoredWorldSourceRepository.java | 30 ++ ...GameSessionAuthoredWorldIntakeService.java | 78 ++++- ...dWorldSourceRepositoryIntegrationTest.java | 260 ++++++++++++++++- ...SessionAuthoredWorldIntakeServiceTest.java | 276 +++++++++++++++--- ...thoredSourceIntakeMtlsIntegrationTest.java | 2 +- 12 files changed, 705 insertions(+), 66 deletions(-) create mode 100644 services/account-service/src/main/resources/db/migration/V51__canonical_join_terminal_attempt_diagnostics.sql diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e77f768ff2..df6814573e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1108,7 +1108,7 @@ jobs: retention-days: 7 - name: Run Game Session authored-world intake PostgreSQL component proof - if: ${{ matrix.module == 'game-session-service' }} + if: ${{ !cancelled() && matrix.module == 'game-session-service' }} run: | ./gradlew :game-session-service:integrationTest \ --tests integration.net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepositoryIntegrationTest \ @@ -1119,8 +1119,20 @@ jobs: --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepositoryIntegrationTest#registersAdditionalWorldsAndReplaysExactReceiptWithoutMutation()' \ --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepositoryIntegrationTest#requiresOwnerTransactionRollsBackClaimsAndReadsOnlyCommittedRows()' \ --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepositoryIntegrationTest#concurrentExactIntakeRetriesReturnOneReceiptAndSlugRaceHasOneWinner()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepositoryIntegrationTest#serviceCommitsReadsBackAndReplaysExactStoredRequestWithoutAnotherSourceRead()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepositoryIntegrationTest#serviceRollbackAndRejectedSourceLeaveNoClaims()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepositoryIntegrationTest#serviceLostPostCommitReadbackRetryReturnsOriginalCommittedReceiptWithoutMutation()' \ game-session-service + - name: Upload Game Session authored-world intake PostgreSQL proof results + if: ${{ !cancelled() && matrix.module == 'game-session-service' }} + uses: actions/upload-artifact@v4 + with: + name: game-session-authored-world-intake-proof-${{ github.run_id }}-${{ github.run_attempt }} + path: services/game-session-service/build/test-results/integrationTest/TEST-*GameSessionAuthoredWorldSourceRepositoryIntegrationTest.xml + if-no-files-found: warn + retention-days: 7 + - name: Run Game Session retained tenant snapshot and association PostgreSQL component proof if: ${{ matrix.module == 'game-session-service' }} run: | diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 3b58cc9853..5be893a981 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -44,7 +44,7 @@ The separate [audited retained-tenant association](../game-design-service/api-co Game Session's source intake binds its own stable non-nil UUID `intakeRequestId` to the complete immutable Game Design source receipt under the exact workload namespace. The intake service obtains that receipt through the authenticated Game Design source client using a separate read-attempt identity and verifies the requested source operation, tenant UUID and world selector. Before delivering response headers or content, the source client also checks the authenticated TLS leaf's single exact `spiffe://firemud/ns//sa/game-design-service` URI; a trusted CA or matching DNS name alone cannot substitute for workload identity. Missing, ambiguous, another-service or cross-namespace peers fail closed. A caller-constructed receipt, digest alone, Account migration manifest or unchecked transport is not a source authorization. Game Design remains the normative source owner; Game Session's stored copy is the exact consumed evidence, not a new authored selector issuer. -The owner transaction atomically persists the local non-nil UUID operation, immutable source evidence and tenant selector claim. Within a namespace, one tenant UUID has one `tenantSlug`, one `tenantSlug` has one tenant UUID, and each `(tenantId, worldSlug)` has one exact consumed source. Compatible additional worlds reuse the same tenant source claim; a conflicting tenant/world/source or changed request fails without partial claims. Exact retries return the original local operation and receipt without changing rows. The transient read-attempt ID is an authenticated response echo, not a replacement intake request or persisted registration field. Exact committed readback is non-mutating and checks the complete stored source and selector binding; it cannot allocate missing state or choose another candidate. +Reject an ambient transaction before the authenticated source call; no Game Session owner transaction or row lock spans that network read. After validating the immutable source, a short writable READ COMMITTED owner transaction atomically persists the local non-nil UUID operation, immutable source evidence and tenant selector claim. Within a namespace, one tenant UUID has one `tenantSlug`, one `tenantSlug` has one tenant UUID, and each `(tenantId, worldSlug)` has one exact consumed source. Compatible additional worlds reuse the same tenant source claim; a conflicting tenant/world/source or changed request fails without partial claims. After the write commits, independently read and compare the complete original local request, operation, source and digests before returning success; missing, changed or unavailable readback denies success without repairing or replacing committed evidence. Exact retries first read the original committed request and return its original local operation and receipt without changing rows or repeating the upstream source call; changed tenant, source operation or world scope conflicts. The transient read-attempt ID is an authenticated response echo, not a replacement intake request or persisted registration field. Committed readback is non-mutating and checks the complete stored source and selector binding; it cannot allocate missing state or choose another candidate. `game-session-authored-world-intake-request/v1` hashes, in order, the domain, canonical `intakeRequestId` and Game Design `evidenceDigest`. `game-session-authored-world-intake-receipt/v1` hashes the domain, canonical local operation UUID, exact local request digest and exact Game Design evidence digest. Each value is encoded in UTF-8 as its decimal byte length, a colon, then those bytes; results are lowercase `sha256:` SHA-256 values. Game Design's closed source codec independently verifies all source fields and both owner digests before either local digest is calculated. A local digest never replaces the authenticated source read or its exact scope checks. 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 d6fa32131e..58eabbddad 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,7 +6,11 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status -Published `a0f4ee82dbb740ea741c83615bc13036ca9968e9` [CI37114161961](https://github.com/benhook1013/FireMUD/actions/runs/37114161961) ended in terminal failure. Independently parsed raw XML shows the four canonical reconciliation methods all failed during fixture setup because the fixture username was 51 characters against the unchanged 50-character column. The four canonical journal methods had two passes and two failures: one bound `Boolean.class` as a SQL parameter in `fetchValue`, and one retained a V47 fixture expectation although V50 preserves an earlier AVAILABLE policy when a later UNAVAILABLE attempt records diagnostics. The follow-up shortens only the username, reads `resultQuery.fetchOne(0, Boolean.class)` without changing the query or guards, and migrates the fixture to V50 while asserting the original AVAILABLE policy remains intact and the operation stays PENDING. Corrected PostgreSQL execution remains required; the failed run proves neither correction. Positive JOIN production, authenticated current-target/entitlement evidence and complete runtime reconciliation remain open, and runtime paths and the Account ring mount remain denied/unpublished. +The explicitly unwired Game Session authored-source intake now rejects an ambient transaction or synchronization before reading Game Design, fetches fresh immutable evidence outside its owner transaction, and opens a short writable READ COMMITTED transaction only for local registration. It independently reads and compares the complete committed result before success. Exact retries first read the original immutable local request, source and tenant binding, without another source call or write; changed tenant, source operation or world scope conflicts. Missing or contradictory post-commit readback denies success without replacing committed evidence. This corrects the former mandatory outer-transaction prerequisite; it does not add a creator API, automatic handoff, runtime catalog activation or admission. The [Game Session API contract](../../architecture/microservices/game-session-service/api-contracts.md#authored-world-source-intake-and-durable-readback) owns the transaction and retry boundary. + +The corrected full Game Session check, boot JAR, formatting, Checkstyle, SpotBugs, coverage, links and Markdown pass locally in 2m33s (134 tasks: 56 executed, 78 up-to-date). Independently parsed XML records 1,886 unit, 18 non-Docker integration and 26 cross-service cases executed cleanly, including all ten intake service unit cases. Seventeen unit, 172 integration and 54 cross-service cases skip locally without Docker. All eight authored-source PostgreSQL methods compile and skip, including the three new real-service cases for committed readback/exact retry, rollback/no partial claims and retained commit recovery after a lost post-commit readback. Their upstream Game Design response is explicitly synthetic; no authenticated source producer or network handoff is proved by them. CI requires all three new methods and captures the raw suite XML. Actual corrected-head PostgreSQL execution, fresh-image/live proof and automatic authorized creation/delivery remain open; runtime and ring-mount gates are unchanged. Gradle completed successfully while discarding its configuration-cache entry with 71 reported protobuf serialization problems; this is not a failed test gate or proof that the cache works. + +Exact published `00285d5a9474a01970293d5a225ad0c63ce1a611` [CI37118817841](https://github.com/benhook1013/FireMUD/actions/runs/37118817841) is terminal failure and its sole observer has finished. Independently parsed and rehashed raw XML shows eight Account cases executed without skips: four passed and four failed. The canonical journal's three nonterminal cases pass after the typed-query and fixture corrections. Its terminal case and three reconciler cases expose the inherited V26 `account_join_pending_attempt_failure_check`: it rejects a COMMITTED row retaining an earlier UNAVAILABLE diagnostic although V50 explicitly permits that exact canonical recovery with the original AVAILABLE policy. Forward V51 now corrects only that check, preserving the original V1 rule, immutable diagnostic/history bytes and every V50 guard; it neither rewrites old migrations nor clears diagnostics, fabricates policy or relaxes readback, expiry or current-membership gates. Focused fixtures retain successful AVAILABLE-policy rebinding proof and additionally prove diagnostic-preserving terminal retry and malformed/V1 terminal denial. The final composed Account/Game Session/World checks, all three boot JARs and documentation pass in 2m6s (182 tasks: 49 executed, 133 up-to-date); the final Account fixture-preservation gate passes in 28s (72 tasks: 14 executed, 58 up-to-date). Same-code XML records 715 Account and 146 World clean unit cases; final matching results are reused. Account's 276 and World's 18 integration nodes still skip locally, so corrected-head PostgreSQL execution remains required. The same runner proves seven physical World socket cases and eight World owner-local PostgreSQL cases cleanly, but all three newer World PostgreSQL/socket cases fail during synthetic source-key setup before their assertions. No full workflow, aggregate success or activation follows. Positive JOIN production, authenticated current-target/entitlement evidence and complete runtime reconciliation remain open, and runtime paths and the Account ring mount remain denied/unpublished. Exact #2949 `996d99ca11c99c685fdef0dd35a859a25ce3fc8b` [CI37097862965](https://github.com/benhook1013/FireMUD/actions/runs/37097862965) completed with aggregate failure; its sole observer finished. Independently parsed and rehashed raw XML proves all 56 captured methods executed cleanly without skips: three Account audit, one retained-row migration, fifteen Logging receiver, one Logging migration, nine physical mTLS, and the prior 27 scope/receipt/catalog/CLOSED methods. The corrected malformed-row case rejects every invalid write at the exact constraint and proves no projection growth. Physical mTLS uses production peer extraction and handler code with ephemeral fixture PKI and a mocked receiver service; it does not prove an Account-to-Logging database workflow or deployment. Concrete tooling, Automation formatting and Game Design duplicate-tenant fixture failures remain separately owned; no aggregate success, activation or ring mount is claimed. diff --git a/design/project-management/implementation-tracking/world-runtime-and-movement.md b/design/project-management/implementation-tracking/world-runtime-and-movement.md index ef0a6b4ff6..f76e02d7b0 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -8,7 +8,9 @@ This is a non-normative implementation tracker for world runtime and movement. C **Canonical launch prerequisite:** Current World design/materialization rows and `PrepareWorldInstance` still use World's private numeric tenant key. V23 and the explicitly unwired owner-local fresh-source intake service/repository persist complete authenticated Game Design `NEW_GAME_ROW` evidence, a private World tenant association, numeric-key reservation and immutable intake receipt together, with exact independent readback. Legacy numeric writes cannot take a reserved canonical selector; existing legacy keys are reserved without inventing UUID associations. Exact [CI37111727823](https://github.com/benhook1013/FireMUD/actions/runs/37111727823) at `73ab357d694618a56c65129394fd324b38ad652e` proves all eight intake PostgreSQL cases and nine Game Design source-read socket cases executed cleanly without skips. Independent raw-XML verification confirms the reservation rejection, SQL state `23514`, unchanged legacy row and no-region assertions. That prior checkpoint does not prove the newer World receiver. -The newer transport is explicitly unregistered: closed shared codec/client, exact Game Design peer guard before decoding or owner access, exact namespace enforcement, and non-mutating committed-receipt readback. The client verifies World's exact workload before releasing requests, not merely before accepting replies. Seven physical socket cases execute cleanly locally with a mocked owner, including wrong-server intake/read rejection with no owner interaction. The full Core/Account/World gate, both affected boot JARs, formatting, static analysis, coverage and documentation checks pass; Core208 and World146 unit cases are clean. All eighteen World integration nodes compile but skip locally without Docker, including three new real World PostgreSQL-through-socket composition cases for committed readback, lost acknowledgement/exact retry and denial without mutation. Their upstream Game Design source answer is synthetic; even successful execution would not prove its producer or automatic delivery. CI strictly requires and captures both new socket suites. Corrected-head database composition execution and live deployment remain unproved. +The newer transport is explicitly unregistered: closed shared codec/client, exact Game Design peer guard before decoding or owner access, exact namespace enforcement, and non-mutating committed-receipt readback. The client verifies World's exact workload before releasing requests, not merely before accepting replies. Seven physical socket cases execute cleanly locally with a mocked owner, including wrong-server intake/read rejection with no owner interaction. The full Core/Account/World gate, both affected boot JARs, formatting, static analysis, coverage and documentation checks pass; Core208 and World146 unit cases are clean. All eighteen World integration nodes compile but skip locally without Docker, including three new real World PostgreSQL-through-socket composition cases for committed readback, lost acknowledgement/exact retry and denial without mutation. Their upstream Game Design source answer is synthetic; even successful execution would not prove its producer or automatic delivery. CI strictly requires and captures both new socket suites. + +Exact `00285d5a9474a01970293d5a225ad0c63ce1a611` [CI37118817841](https://github.com/benhook1013/FireMUD/actions/runs/37118817841) independently proves all seven physical socket and eight owner-local PostgreSQL cases executed cleanly, with zero skips. All three newer PostgreSQL/socket methods executed but failed during source-fixture construction: `source-key-` plus a full random UUID exceeded Game Design's unchanged 36-code-point key bound. The test-only correction uses `src-` plus an independently random hyphenless UUID, exactly 36 characters; it neither derives a tenant association nor changes the owner validator. Corrected database/socket execution remains required, rather than claiming the failed setup exercised its socket or owner assertions. The aggregate run is red on this fixture, Account's terminal-diagnostic constraint and concrete other-owner failures. Live deployment and all activation gates remain unproved/denied. The automatic normal Game Design registration/delivery producer, canonical-source-qualified content writer, exact content/descriptor/release readback, separate audited retained-World association and canonical lifecycle composition remain required. The [World API contract](../../architecture/microservices/world-management-service/api-contracts.md#authenticated-authored-content-intake-and-tenant-association) owns this boundary. Numeric similarity, selectors and Account's migration manifest are not substitutes, and no runtime activation is authorized. The prior World full CI job passed while aggregate CI failed on identified Game Design fixture, Automation formatting and shared-tooling checks; no aggregate-green claim follows from focused proof. diff --git a/services/account-service/src/main/resources/db/migration/V51__canonical_join_terminal_attempt_diagnostics.sql b/services/account-service/src/main/resources/db/migration/V51__canonical_join_terminal_attempt_diagnostics.sql new file mode 100644 index 0000000000..9827864a51 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V51__canonical_join_terminal_attempt_diagnostics.sql @@ -0,0 +1,21 @@ +-- Preserve the original V1 pending-only diagnostic rule while retaining a later unavailable +-- attempt when a V2 canonical JOIN recovers its already-bound available policy result. +ALTER TABLE account_join_operations + DROP CONSTRAINT account_join_pending_attempt_failure_check; + +ALTER TABLE account_join_operations + ADD CONSTRAINT account_join_pending_attempt_failure_check + CHECK (last_attempt_failure_code IS NULL + OR (status = 'PENDING' AND btrim(last_attempt_failure_code) <> '') + OR (operation_representation_version = 2 + AND status = 'COMMITTED' + AND entitlement_authority_availability = 'AVAILABLE' + AND entitlement_version IS NOT NULL + AND entitlement_version > 0 + AND allow_public_join IS TRUE + AND request_digest_version IS NOT NULL + AND request_digest_version = 2 + AND request_digest IS NOT NULL + AND request_digest ~ '^sha256:[0-9a-f]{64}$' + AND last_attempt_authority_availability = 'UNAVAILABLE' + AND btrim(last_attempt_failure_code) <> '')); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCanonicalJoinReconciliationIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCanonicalJoinReconciliationIntegrationTest.java index df9b14fd0c..3ea5238f1b 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCanonicalJoinReconciliationIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCanonicalJoinReconciliationIntegrationTest.java @@ -249,6 +249,8 @@ void concurrentExactTerminalRetryAndReconcilerRetainOneHistoricalWriteSet() thro CanonicalJoinOperationEvidence retried = retry.get(30, TimeUnit.SECONDS); assertThat(retried.status()).isEqualTo("COMMITTED"); assertThat(retried.outcome()).isEqualTo("JOINED"); + assertThat(retried.lastAttemptAuthorityAvailability()).isEqualTo("UNAVAILABLE"); + assertThat(retried.lastAttemptFailureCode()).isEqualTo("ENTITLEMENT_TIMEOUT"); assertThat(exactTerminalRetry(fixture)).isEqualTo(retried); } finally { start.countDown(); @@ -258,6 +260,8 @@ void concurrentExactTerminalRetryAndReconcilerRetainOneHistoricalWriteSet() thro CanonicalJoinOperationEvidence committed = readOperation(fixture); assertThat(committed.status()).isEqualTo("COMMITTED"); assertThat(committed.outcome()).isEqualTo("JOINED"); + assertThat(committed.lastAttemptAuthorityAvailability()).isEqualTo("UNAVAILABLE"); + assertThat(committed.lastAttemptFailureCode()).isEqualTo("ENTITLEMENT_TIMEOUT"); assertThat(evidenceCounts(fixture)).isEqualTo(before); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountConnectScopeCanonicalIdentityIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountConnectScopeCanonicalIdentityIntegrationTest.java index a84176d538..38412b8663 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountConnectScopeCanonicalIdentityIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountConnectScopeCanonicalIdentityIntegrationTest.java @@ -944,6 +944,7 @@ void canonicalTerminalJournalPreservesHistoryAndOnlyStoresContractShapedOutcomes retainedRequestId), "Retained V1 JOIN operation must exist before V50"); flyway(fixture.dataSource(), fixture.schema(), "50").migrate(); + flyway(fixture.dataSource(), fixture.schema(), "51").migrate(); AccountConnectScopeRepository scopes = scopeRepository(fixture).scopes(); AccountJoinOperationRepository operations = @@ -1014,6 +1015,20 @@ void canonicalTerminalJournalPreservesHistoryAndOnlyStoresContractShapedOutcomes assertThat(availableAgain.entitlementAuthorityAvailability()).isEqualTo("AVAILABLE"); assertThat(availableAgain.lastAttemptAuthorityAvailability()).isEqualTo("AVAILABLE"); assertThat(availableAgain.lastAttemptFailureCode()).isNull(); + CanonicalJoinOperationEvidence latestUnavailableAttempt = + fixture + .transaction() + .execute( + status -> + operations.recordCanonicalPolicyUnavailable( + committedRequestId, + unexpiredScope, + callerBinding, + "ENTITLEMENT_UNAVAILABLE")); + assertThat(latestUnavailableAttempt.requestDigest()).isEqualTo(availableAgain.requestDigest()); + assertThat(latestUnavailableAttempt.entitlementVersion()).isEqualTo(19L); + assertThat(latestUnavailableAttempt.lastAttemptAuthorityAvailability()) + .isEqualTo("UNAVAILABLE"); Long membershipId = fixture @@ -1038,7 +1053,13 @@ void canonicalTerminalJournalPreservesHistoryAndOnlyStoresContractShapedOutcomes assertThat(committed.membershipId()).isEqualTo(membershipId); assertThat(committed.membershipVersion()).isEqualTo(2L); assertThat(committed.membershipAuthorityGeneration()).isEqualTo(1L); - assertThat(committed.scopeEvidence()).isEqualTo(availableAgain.scopeEvidence()); + assertThat(committed.entitlementAuthorityAvailability()).isEqualTo("AVAILABLE"); + assertThat(committed.allowPublicJoin()).isTrue(); + assertThat(committed.entitlementVersion()).isEqualTo(19L); + assertThat(committed.requestDigestVersion()).isEqualTo(2); + assertThat(committed.lastAttemptAuthorityAvailability()).isEqualTo("UNAVAILABLE"); + assertThat(committed.lastAttemptFailureCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); + assertThat(committed.scopeEvidence()).isEqualTo(unavailableAfterPolicy.scopeEvidence()); CanonicalJoinOperationEvidence committedRetry = fixture .transaction() @@ -1070,6 +1091,16 @@ void canonicalTerminalJournalPreservesHistoryAndOnlyStoresContractShapedOutcomes + "WHERE request_id = ?", committedRequestId)) .isInstanceOf(DataAccessException.class); + assertTerminalJournalCheckRejectsNullField( + fixture, "last_attempt_failure_code = ' '", committedRequestId); + assertTerminalJournalCheckRejectsNullField( + fixture, "last_attempt_authority_availability = 'AVAILABLE'", committedRequestId); + assertThat( + fixture + .transaction() + .execute(status -> operations.findCanonicalEvidenceByRequestId(committedRequestId)) + .orElseThrow()) + .isEqualTo(committed); assertTerminalJournalCheckRejectsNullField(fixture, "outcome = NULL", committedRequestId); assertTerminalJournalCheckRejectsNullField( fixture, "outcome_membership_version = NULL", committedRequestId); @@ -1141,6 +1172,17 @@ void canonicalTerminalJournalPreservesHistoryAndOnlyStoresContractShapedOutcomes null)); assertThat(failedRetry).isEqualTo(failed); assertTerminalJournalCheckRejectsNullField(fixture, "outcome = NULL", deniedRequestId); + assertTerminalJournalCheckRejectsNullField( + fixture, + "last_attempt_authority_availability = 'UNAVAILABLE', " + + "last_attempt_failure_code = 'ENTITLEMENT_TIMEOUT'", + deniedRequestId); + assertThat( + fixture + .transaction() + .execute(status -> operations.findCanonicalEvidenceByRequestId(deniedRequestId)) + .orElseThrow()) + .isEqualTo(failed); String unavailableRequestId = "canonical-join-terminal-unavailable"; fixture @@ -1471,15 +1513,39 @@ void canonicalTerminalJournalPreservesHistoryAndOnlyStoresContractShapedOutcomes assertThat(canonicalTerminalReadback).contains(committed); assertThat(v1OperationProjection(fixture.setupDsl(), retainedRequestId)) .containsExactlyEntriesOf(retainedOperationBefore); - Record retainedOperationAfterV50 = + Record retainedOperationAfterV51 = + Objects.requireNonNull( + fixture + .setupDsl() + .fetchOne( + "SELECT * FROM account_join_operations WHERE request_id = ?", + retainedRequestId), + "Retained V1 JOIN operation must exist after V51"); + assertThat(retainedOperationAfterV51.intoMap()) + .containsExactlyEntriesOf(retainedOperationBeforeV50.intoMap()); + assertTerminalJournalCheckRejectsNullField( + fixture, + "status = 'COMMITTED', outcome = 'JOINED', membership_id = " + + membershipId + + ", outcome_membership_version = 2, " + + "outcome_membership_authority_generation = 1, entitlement_version = 19, " + + "allow_public_join = TRUE, entitlement_authority_availability = 'AVAILABLE', " + + "request_digest_version = 1, request_digest = 'sha256:" + + "c".repeat(64) + + "', last_attempt_authority_availability = 'UNAVAILABLE', " + + "last_attempt_failure_code = 'LEGACY_UNAVAILABLE'", + retainedRequestId); + assertThat(v1OperationProjection(fixture.setupDsl(), retainedRequestId)) + .containsExactlyEntriesOf(retainedOperationBefore); + Record retainedOperationAfterRejectedTerminalDiagnostic = Objects.requireNonNull( fixture .setupDsl() .fetchOne( "SELECT * FROM account_join_operations WHERE request_id = ?", retainedRequestId), - "Retained V1 JOIN operation must exist after V50"); - assertThat(retainedOperationAfterV50.intoMap()) + "Retained V1 JOIN operation must remain after rejected terminal diagnostics"); + assertThat(retainedOperationAfterRejectedTerminalDiagnostic.intoMap()) .containsExactlyEntriesOf(retainedOperationBeforeV50.intoMap()); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldSourceRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldSourceRepository.java index 2d90f82cee..9cadb667af 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldSourceRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldSourceRepository.java @@ -4,6 +4,7 @@ import java.util.Objects; import java.util.Optional; import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import org.jooq.DSLContext; @@ -201,6 +202,35 @@ public Optional read( return Optional.of(receipt); } + /** Reads an exact committed retry by its stable intake request without allocating owner state. */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional readByIntakeRequest(String namespace, UUID intakeRequestId) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Authored-world source intake read requires a committed-outcome owner read"); + } + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Game Session workload namespace is invalid"); + } + requireNonNil(intakeRequestId, "intakeRequestId"); + + Record record = + dsl.selectFrom(INTAKE) + .where(OPERATION_NAMESPACE.eq(namespace).and(INTAKE_REQUEST_ID.eq(intakeRequestId))) + .fetchOne(); + if (record == null) { + return Optional.empty(); + } + IntakeReceipt receipt = toReceipt(record); + if (!receipt.intakeRequestId().equals(intakeRequestId) + || !receipt.source().targetNamespace().equals(namespace)) { + throw new InvalidIntakeEvidenceException( + "Persisted authored-world source intake request binding is invalid"); + } + requireTenantBinding(receipt.source()); + return Optional.of(receipt); + } + private void ensureTenantBinding(AuthoredWorldSourceEvidence source) { Record existing = findTenantBinding(source.targetNamespace(), source.canonicalTenantId()); if (existing != null) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionAuthoredWorldIntakeService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionAuthoredWorldIntakeService.java index a6305ee1c5..8921e489e0 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionAuthoredWorldIntakeService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionAuthoredWorldIntakeService.java @@ -8,45 +8,65 @@ import net.firedevops.firemud.gamesession.client.GameDesignRuntimeTenantIdentityClient; import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository; import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; -import org.springframework.transaction.annotation.Propagation; -import org.springframework.transaction.annotation.Transactional; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.InvalidIntakeEvidenceException; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.RegistrationConflictException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; /** - * Unwired Game Session source intake. Only an authenticated exact Game Design read can reach local - * persistence; this does not enroll runtime instances, admit gameplay, or authorize creator writes. + * Unwired Game Session source intake. Fresh writes require an authenticated exact Game Design read; + * exact retries use committed local evidence. This does not enroll runtime instances, admit + * gameplay, or authorize creator writes. */ public class GameSessionAuthoredWorldIntakeService { private final GameDesignRuntimeTenantIdentityClient sourceClient; private final GameSessionAuthoredWorldSourceRepository repository; private final String workloadNamespace; + private final TransactionTemplate ownerTransaction; @SuppressFBWarnings( value = "CT_CONSTRUCTOR_THROW", justification = - "Trusted owner configuration is validated before use; no resources or finalizer are acquired." - + " The class remains non-final for transaction proxying.") + "Trusted owner configuration is validated before use; no resources or finalizer are" + + " acquired.") public GameSessionAuthoredWorldIntakeService( GameDesignRuntimeTenantIdentityClient sourceClient, GameSessionAuthoredWorldSourceRepository repository, + PlatformTransactionManager transactionManager, String workloadNamespace) { this.sourceClient = Objects.requireNonNull(sourceClient, "sourceClient"); this.repository = Objects.requireNonNull(repository, "repository"); + Objects.requireNonNull(transactionManager, "transactionManager"); if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { throw new IllegalArgumentException("Game Session workload namespace is invalid"); } this.workloadNamespace = workloadNamespace; + this.ownerTransaction = new TransactionTemplate(transactionManager); + this.ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + this.ownerTransaction.setReadOnly(false); } - @Transactional(propagation = Propagation.MANDATORY) + /** Reads immutable source evidence before opening the short, local owner write transaction. */ public IntakeReceipt intake( UUID intakeRequestId, UUID canonicalTenantId, UUID sourceOperationId, String worldSlug) { - if (!TransactionSynchronizationManager.isActualTransactionActive()) { - throw new IllegalStateException("Authored-world intake requires its owner transaction"); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Authored-world intake cannot enter from an ambient transaction"); } requireIdentity(intakeRequestId, "intakeRequestId"); requireIdentity(sourceOperationId, "sourceOperationId"); AuthoredWorldSourceDigest.validateReadSelector(workloadNamespace, canonicalTenantId, worldSlug); + + var prior = repository.readByIntakeRequest(workloadNamespace, intakeRequestId); + if (prior.isPresent()) { + return requireRequestBinding( + prior.orElseThrow(), intakeRequestId, canonicalTenantId, sourceOperationId, worldSlug); + } + // A response echo is scoped to this read attempt, not the durable local intake request. var source = sourceClient.resolveAuthoredWorldSource( @@ -61,7 +81,45 @@ public IntakeReceipt intake( || !worldSlug.equals(source.worldSlug())) { throw new IllegalStateException("Authenticated authored-world source does not match intake"); } - return repository.register(intakeRequestId, source); + + IntakeReceipt written = + ownerTransaction.execute(status -> repository.register(intakeRequestId, source)); + if (written == null) { + throw new InvalidIntakeEvidenceException( + "Game Session owner transaction returned no authored-world intake receipt"); + } + + var committed = + repository.read(written.operationId(), canonicalTenantId, worldSlug, workloadNamespace); + if (committed.isEmpty()) { + throw new InvalidIntakeEvidenceException( + "Game Session authored-world intake is missing after commit readback"); + } + IntakeReceipt readback = committed.orElseThrow(); + requireRequestBinding( + readback, intakeRequestId, canonicalTenantId, sourceOperationId, worldSlug); + if (!written.equals(readback) || !source.equals(readback.source())) { + throw new InvalidIntakeEvidenceException( + "Game Session authored-world intake changed during commit readback"); + } + return readback; + } + + private IntakeReceipt requireRequestBinding( + IntakeReceipt receipt, + UUID intakeRequestId, + UUID canonicalTenantId, + UUID sourceOperationId, + String worldSlug) { + if (!receipt.intakeRequestId().equals(intakeRequestId) + || !receipt.source().canonicalTenantId().equals(canonicalTenantId) + || !receipt.source().operationId().equals(sourceOperationId) + || !receipt.source().worldSlug().equals(worldSlug) + || !receipt.source().targetNamespace().equals(workloadNamespace)) { + throw new RegistrationConflictException( + "Authored-world intake identity was reused with changed source scope"); + } + return receipt; } private static void requireIdentity(UUID value, String name) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldSourceRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldSourceRepositoryIntegrationTest.java index 2fe36e802b..8dea3a22f8 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldSourceRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldSourceRepositoryIntegrationTest.java @@ -2,19 +2,31 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import java.nio.file.Path; +import java.util.Optional; import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamesession.client.GameDesignRuntimeTenantIdentityClient; import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository; import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.InvalidIntakeEvidenceException; import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.RegistrationConflictException; +import net.firedevops.firemud.gamesession.service.GameSessionAuthoredWorldIntakeService; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; @@ -25,6 +37,7 @@ import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; @@ -219,6 +232,249 @@ void requiresOwnerTransactionRollsBackClaimsAndReadsOnlyCommittedRows() { assertThat(fixture.repository.read(uuid(301), uuid(4), "one-world", NAMESPACE)).isEmpty(); } + @Test + void serviceCommitsReadsBackAndReplaysExactStoredRequestWithoutAnotherSourceRead() { + Fixture fixture = fixture(); + UUID tenantId = uuid(70); + UUID intakeRequestId = uuid(71); + AuthoredWorldSourceEvidence source = + source(tenantId, uuid(171), uuid(271), "service-tenant", "service-world", "Service World"); + // This mocked client is synthetic owner evidence; it does not exercise Game Design transport. + GameDesignRuntimeTenantIdentityClient syntheticClient = + mock(GameDesignRuntimeTenantIdentityClient.class); + when(syntheticClient.resolveAuthoredWorldSource( + eq(tenantId.toString()), + eq(source.operationId().toString()), + eq(source.worldSlug()), + anyString())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return source; + }); + GameSessionAuthoredWorldIntakeService service = + new GameSessionAuthoredWorldIntakeService( + syntheticClient, fixture.repository, fixture.transactionManager, NAMESPACE); + + IntakeReceipt first = + service.intake(intakeRequestId, tenantId, source.operationId(), source.worldSlug()); + String bindingXmin = + fixture.xmin( + "SELECT xmin::text AS xmin FROM game_session_authored_world_tenant_source_binding " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + NAMESPACE, + tenantId); + String intakeXmin = + fixture.xmin( + "SELECT xmin::text AS xmin FROM game_session_authored_world_source_intake " + + "WHERE target_namespace = ? AND intake_request_id = ?", + NAMESPACE, + intakeRequestId); + + assertThat(service.intake(intakeRequestId, tenantId, source.operationId(), source.worldSlug())) + .isEqualTo(first); + assertThatThrownBy( + () -> + service.intake(intakeRequestId, uuid(99), source.operationId(), source.worldSlug())) + .isInstanceOf(RegistrationConflictException.class); + assertThatThrownBy( + () -> service.intake(intakeRequestId, tenantId, uuid(99), source.worldSlug())) + .isInstanceOf(RegistrationConflictException.class); + assertThatThrownBy( + () -> service.intake(intakeRequestId, tenantId, source.operationId(), "other-world")) + .isInstanceOf(RegistrationConflictException.class); + assertThat( + fixture.repository.read(first.operationId(), tenantId, source.worldSlug(), NAMESPACE)) + .contains(first); + assertThat( + fixture.xmin( + "SELECT xmin::text AS xmin FROM game_session_authored_world_tenant_source_binding " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + NAMESPACE, + tenantId)) + .isEqualTo(bindingXmin); + assertThat( + fixture.xmin( + "SELECT xmin::text AS xmin FROM game_session_authored_world_source_intake " + + "WHERE target_namespace = ? AND intake_request_id = ?", + NAMESPACE, + intakeRequestId)) + .isEqualTo(intakeXmin); + verify(syntheticClient, times(1)) + .resolveAuthoredWorldSource( + eq(tenantId.toString()), + eq(source.operationId().toString()), + eq(source.worldSlug()), + anyString()); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(INTAKES)).isEqualTo(1); + } + + @Test + void serviceRollbackAndRejectedSourceLeaveNoClaims() { + Fixture fixture = fixture(); + UUID tenantId = uuid(72); + UUID intakeRequestId = uuid(73); + AuthoredWorldSourceEvidence source = + source( + tenantId, uuid(172), uuid(272), "rollback-tenant", "rollback-world", "Rollback World"); + // This mocked client supplies explicitly synthetic immutable source evidence for composition. + GameDesignRuntimeTenantIdentityClient syntheticClient = + mock(GameDesignRuntimeTenantIdentityClient.class); + AtomicReference upstreamEvidence = new AtomicReference<>(source); + when(syntheticClient.resolveAuthoredWorldSource( + eq(tenantId.toString()), + eq(source.operationId().toString()), + eq(source.worldSlug()), + anyString())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return upstreamEvidence.get(); + }); + GameSessionAuthoredWorldSourceRepository rollbackRepository = + new GameSessionAuthoredWorldSourceRepository(fixture.dsl) { + @Override + public IntakeReceipt register(UUID requestId, AuthoredWorldSourceEvidence evidence) { + super.register(requestId, evidence); + throw new IllegalStateException("simulated failure after local writes"); + } + }; + GameSessionAuthoredWorldIntakeService rollbackService = + new GameSessionAuthoredWorldIntakeService( + syntheticClient, rollbackRepository, fixture.transactionManager, NAMESPACE); + + assertThatThrownBy( + () -> + rollbackService.intake( + intakeRequestId, tenantId, source.operationId(), source.worldSlug())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("simulated failure after local writes"); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isZero(); + assertThat(fixture.dsl.fetchCount(INTAKES)).isZero(); + assertThat(fixture.repository.readByIntakeRequest(NAMESPACE, intakeRequestId)).isEmpty(); + + UUID rejectedRequestId = uuid(74); + AuthoredWorldSourceEvidence wrongScope = + source( + tenantId, + uuid(174), + source.operationId(), + "rollback-tenant", + "other-world", + "Other World"); + upstreamEvidence.set(wrongScope); + GameSessionAuthoredWorldIntakeService rejectionService = + new GameSessionAuthoredWorldIntakeService( + syntheticClient, fixture.repository, fixture.transactionManager, NAMESPACE); + assertThatThrownBy( + () -> + rejectionService.intake( + rejectedRequestId, tenantId, source.operationId(), source.worldSlug())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("does not match intake"); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isZero(); + assertThat(fixture.dsl.fetchCount(INTAKES)).isZero(); + assertThat(fixture.repository.readByIntakeRequest(NAMESPACE, rejectedRequestId)).isEmpty(); + } + + @Test + void serviceLostPostCommitReadbackRetryReturnsOriginalCommittedReceiptWithoutMutation() { + Fixture fixture = fixture(); + UUID tenantId = uuid(75); + UUID intakeRequestId = uuid(76); + AuthoredWorldSourceEvidence source = + source( + tenantId, + uuid(175), + uuid(275), + "lost-readback-tenant", + "lost-readback-world", + "Lost Readback World"); + GameDesignRuntimeTenantIdentityClient syntheticClient = + mock(GameDesignRuntimeTenantIdentityClient.class); + AtomicInteger sourceReads = new AtomicInteger(); + when(syntheticClient.resolveAuthoredWorldSource( + eq(tenantId.toString()), + eq(source.operationId().toString()), + eq(source.worldSlug()), + anyString())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + sourceReads.incrementAndGet(); + return source; + }); + + AtomicInteger committedReadbacks = new AtomicInteger(); + GameSessionAuthoredWorldSourceRepository readbackUnavailableOnce = + new GameSessionAuthoredWorldSourceRepository(fixture.dsl) { + @Override + public Optional read( + UUID operationId, UUID canonicalTenantId, String worldSlug, String namespace) { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + if (committedReadbacks.getAndIncrement() == 0) { + return Optional.empty(); + } + return super.read(operationId, canonicalTenantId, worldSlug, namespace); + } + }; + GameSessionAuthoredWorldIntakeService service = + new GameSessionAuthoredWorldIntakeService( + syntheticClient, readbackUnavailableOnce, fixture.transactionManager, NAMESPACE); + + assertThatThrownBy( + () -> + service.intake(intakeRequestId, tenantId, source.operationId(), source.worldSlug())) + .isInstanceOf(InvalidIntakeEvidenceException.class) + .hasMessageContaining("missing after commit readback"); + + IntakeReceipt committed = + fixture.repository.readByIntakeRequest(NAMESPACE, intakeRequestId).orElseThrow(); + assertThat(committed.source()).isEqualTo(source); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(INTAKES)).isEqualTo(1); + String bindingXmin = + fixture.xmin( + "SELECT xmin::text AS xmin FROM game_session_authored_world_tenant_source_binding " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + NAMESPACE, + tenantId); + String intakeXmin = + fixture.xmin( + "SELECT xmin::text AS xmin FROM game_session_authored_world_source_intake " + + "WHERE target_namespace = ? AND intake_request_id = ?", + NAMESPACE, + intakeRequestId); + + assertThat(service.intake(intakeRequestId, tenantId, source.operationId(), source.worldSlug())) + .isEqualTo(committed); + assertThat(sourceReads.get()).isEqualTo(1); + assertThat(committedReadbacks.get()).isEqualTo(1); + assertThat( + fixture.xmin( + "SELECT xmin::text AS xmin FROM game_session_authored_world_tenant_source_binding " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + NAMESPACE, + tenantId)) + .isEqualTo(bindingXmin); + assertThat( + fixture.xmin( + "SELECT xmin::text AS xmin FROM game_session_authored_world_source_intake " + + "WHERE target_namespace = ? AND intake_request_id = ?", + NAMESPACE, + intakeRequestId)) + .isEqualTo(intakeXmin); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(INTAKES)).isEqualTo(1); + verify(syntheticClient, times(1)) + .resolveAuthoredWorldSource( + eq(tenantId.toString()), + eq(source.operationId().toString()), + eq(source.worldSlug()), + anyString()); + } + @Test void sourceAndTenantClaimsRejectMutationDeleteTruncateAndClaimOnlyCommit() { Fixture fixture = fixture(); @@ -484,7 +740,8 @@ private Fixture fixture() { TransactionTemplate transactions = new TransactionTemplate(transactionManager); DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); - return new Fixture(dsl, new GameSessionAuthoredWorldSourceRepository(dsl), transactions); + return new Fixture( + dsl, new GameSessionAuthoredWorldSourceRepository(dsl), transactionManager, transactions); } private void assertConflict(Runnable registration) { @@ -515,6 +772,7 @@ private enum RegistrationOutcome { private record Fixture( DSLContext dsl, GameSessionAuthoredWorldSourceRepository repository, + DataSourceTransactionManager transactionManager, TransactionTemplate transactions) { IntakeReceipt register(UUID intakeRequestId, AuthoredWorldSourceEvidence source) { IntakeReceipt receipt = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionAuthoredWorldIntakeServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionAuthoredWorldIntakeServiceTest.java index 9fd8ce4e1b..c027628517 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionAuthoredWorldIntakeServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionAuthoredWorldIntakeServiceTest.java @@ -2,13 +2,17 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; +import java.util.List; +import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; @@ -16,9 +20,15 @@ import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldIntakeDigest; import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository; import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.InvalidIntakeEvidenceException; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.RegistrationConflictException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; import org.springframework.transaction.support.TransactionSynchronizationManager; class GameSessionAuthoredWorldIntakeServiceTest { @@ -27,12 +37,14 @@ class GameSessionAuthoredWorldIntakeServiceTest { private static final UUID SOURCE_OPERATION = UUID.fromString("33333333-3333-4333-8333-333333333333"); private static final String WORLD = "violet-wilds"; + private final GameDesignRuntimeTenantIdentityClient client = mock(GameDesignRuntimeTenantIdentityClient.class); private final GameSessionAuthoredWorldSourceRepository repository = mock(GameSessionAuthoredWorldSourceRepository.class); + private final RecordingTransactionManager transactionManager = new RecordingTransactionManager(); private final GameSessionAuthoredWorldIntakeService service = - new GameSessionAuthoredWorldIntakeService(client, repository, "firemud"); + new GameSessionAuthoredWorldIntakeService(client, repository, transactionManager, "firemud"); @AfterEach void clearTransaction() { @@ -40,15 +52,30 @@ void clearTransaction() { } @Test - void requiresOwnerTransactionBeforeSourceReadOrPersistence() { + void rejectsAmbientTransactionBeforeSourceOrOwnerRead() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + assertThatThrownBy(() -> service.intake(REQUEST, TENANT, SOURCE_OPERATION, WORLD)) - .isInstanceOf(IllegalStateException.class); + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient transaction"); verifyNoInteractions(client, repository); + assertThat(transactionManager.startedWith).isNull(); } @Test - void rejectsInvalidSelectorsBeforeSourceReadOrPersistence() { - ownerTransaction(); + void rejectsAmbientSynchronizationBeforeSourceOrOwnerRead() { + TransactionSynchronizationManager.initSynchronization(); + + assertThatThrownBy(() -> service.intake(REQUEST, TENANT, SOURCE_OPERATION, WORLD)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient transaction"); + verifyNoInteractions(client, repository); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void rejectsInvalidSelectorsBeforeSourceOrOwnerRead() { assertThatThrownBy(() -> service.intake(null, TENANT, SOURCE_OPERATION, WORLD)) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> service.intake(REQUEST, TENANT, new UUID(0, 0), WORLD)) @@ -61,81 +88,196 @@ void rejectsInvalidSelectorsBeforeSourceReadOrPersistence() { } @Test - void persistsOnlyTheAuthenticatedExactSourceAndKeepsReadIdentitySeparate() { - ownerTransaction(); - var source = source("firemud", TENANT, SOURCE_OPERATION, WORLD); - var localOperation = UUID.fromString("55555555-5555-4555-8555-555555555555"); - var requestDigest = GameSessionAuthoredWorldIntakeDigest.requestDigest(REQUEST, source); - var receipt = - new IntakeReceipt( - localOperation, - REQUEST, - requestDigest, - source, - GameSessionAuthoredWorldIntakeDigest.receiptDigest( - localOperation, requestDigest, source.evidenceDigest())); + void obtainsSourceOutsideWritableReadCommittedOwnerTransactionAndReadsCommitBack() { + AuthoredWorldSourceEvidence source = source("firemud", TENANT, SOURCE_OPERATION, WORLD); + IntakeReceipt receipt = receipt(source, uuid(55)); + when(repository.readByIntakeRequest("firemud", REQUEST)) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return Optional.empty(); + }); when(client.resolveAuthoredWorldSource( eq(TENANT.toString()), eq(SOURCE_OPERATION.toString()), eq(WORLD), anyString())) - .thenReturn(source); - when(repository.register(REQUEST, source)).thenReturn(receipt); + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return source; + }); + when(repository.register(REQUEST, source)) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) + .isFalse(); + assertThat(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + return receipt; + }); + when(repository.read(receipt.operationId(), TENANT, WORLD, "firemud")) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return Optional.of(receipt); + }); assertThat(service.intake(REQUEST, TENANT, SOURCE_OPERATION, WORLD)).isEqualTo(receipt); - verify(repository).register(REQUEST, source); - var readRequest = ArgumentCaptor.forClass(String.class); + assertThat(transactionManager.startedWith.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(transactionManager.startedWith.isReadOnly()).isFalse(); + assertThat(transactionManager.startedWith.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(transactionManager.commitCount).isEqualTo(1); + + ArgumentCaptor readRequest = ArgumentCaptor.forClass(String.class); verify(client) .resolveAuthoredWorldSource( eq(TENANT.toString()), eq(SOURCE_OPERATION.toString()), eq(WORLD), readRequest.capture()); - assertThat(UUID.fromString(readRequest.getValue())) - .isNotEqualTo(new UUID(0, 0)) - .isNotEqualTo(REQUEST); + assertThat(UUID.fromString(readRequest.getValue())).isNotEqualTo(REQUEST); + verify(repository).register(REQUEST, source); + verify(repository).read(receipt.operationId(), TENANT, WORLD, "firemud"); } @Test - void coherentlyRedigestedWrongScopeCannotReachPersistence() { - ownerTransaction(); - var wrongSources = - java.util.List.of( + void exactStoredRetryReturnsOriginalReceiptWithoutSourceReadOrMutation() { + AuthoredWorldSourceEvidence source = source("firemud", TENANT, SOURCE_OPERATION, WORLD); + IntakeReceipt receipt = receipt(source, uuid(55)); + when(repository.readByIntakeRequest("firemud", REQUEST)).thenReturn(Optional.of(receipt)); + + assertThat(service.intake(REQUEST, TENANT, SOURCE_OPERATION, WORLD)).isEqualTo(receipt); + + verifyNoInteractions(client); + verify(repository, never()).register(any(UUID.class), any(AuthoredWorldSourceEvidence.class)); + verify(repository, never()).read(any(UUID.class), any(UUID.class), anyString(), anyString()); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void changedRetryBindingsConflictWithoutSourceReadOrMutation() { + AuthoredWorldSourceEvidence source = source("firemud", TENANT, SOURCE_OPERATION, WORLD); + IntakeReceipt receipt = receipt(source, uuid(55)); + when(repository.readByIntakeRequest("firemud", REQUEST)).thenReturn(Optional.of(receipt)); + + List changedBindings = + List.of( + () -> service.intake(REQUEST, uuid(99), SOURCE_OPERATION, WORLD), + () -> service.intake(REQUEST, TENANT, uuid(99), WORLD), + () -> service.intake(REQUEST, TENANT, SOURCE_OPERATION, "other-world")); + for (Runnable changedBinding : changedBindings) { + assertThatThrownBy(changedBinding::run).isInstanceOf(RegistrationConflictException.class); + } + + verifyNoInteractions(client); + verify(repository, never()).register(any(UUID.class), any(AuthoredWorldSourceEvidence.class)); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void coherentlyRedigestedWrongScopeCannotReachOwnerWrite() { + when(repository.readByIntakeRequest("firemud", REQUEST)).thenReturn(Optional.empty()); + List wrongSources = + List.of( source("other", TENANT, SOURCE_OPERATION, WORLD), source("firemud", REQUEST, SOURCE_OPERATION, WORLD), source("firemud", TENANT, REQUEST, WORLD), source("firemud", TENANT, SOURCE_OPERATION, "other-world")); - for (var wrong : wrongSources) { - when(client.resolveAuthoredWorldSource(anyString(), anyString(), anyString(), anyString())) - .thenReturn(wrong); + when(client.resolveAuthoredWorldSource(anyString(), anyString(), anyString(), anyString())) + .thenReturn(wrongSources.get(0)) + .thenReturn(wrongSources.get(1)) + .thenReturn(wrongSources.get(2)) + .thenReturn(wrongSources.get(3)); + + for (int index = 0; index < wrongSources.size(); index++) { assertThatThrownBy(() -> service.intake(REQUEST, TENANT, SOURCE_OPERATION, WORLD)) .isInstanceOf(IllegalStateException.class); } - verifyNoInteractions(repository); + + verify(repository, never()).register(any(UUID.class), any(AuthoredWorldSourceEvidence.class)); + verify(repository, never()).read(any(UUID.class), any(UUID.class), anyString(), anyString()); + assertThat(transactionManager.startedWith).isNull(); } @Test - void absentOrUnavailableOwnerCannotLeaveAnyLocalClaim() { - ownerTransaction(); - when(client.resolveAuthoredWorldSource(anyString(), anyString(), anyString(), anyString())) - .thenReturn(null); - assertThatThrownBy(() -> service.intake(REQUEST, TENANT, SOURCE_OPERATION, WORLD)) - .isInstanceOf(IllegalStateException.class); + void unavailableOwnerCannotLeaveAnyLocalClaim() { + when(repository.readByIntakeRequest("firemud", REQUEST)).thenReturn(Optional.empty()); when(client.resolveAuthoredWorldSource(anyString(), anyString(), anyString(), anyString())) + .thenReturn(null) .thenThrow(new IllegalStateException("source unavailable")); + + assertThatThrownBy(() -> service.intake(REQUEST, TENANT, SOURCE_OPERATION, WORLD)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("does not match intake"); assertThatThrownBy(() -> service.intake(REQUEST, TENANT, SOURCE_OPERATION, WORLD)) .isInstanceOf(IllegalStateException.class) .hasMessage("source unavailable"); - verifyNoInteractions(repository); + + verify(repository, never()).register(any(UUID.class), any(AuthoredWorldSourceEvidence.class)); + verify(repository, never()).read(any(UUID.class), any(UUID.class), anyString(), anyString()); + assertThat(transactionManager.startedWith).isNull(); } - private static void ownerTransaction() { - TransactionSynchronizationManager.setActualTransactionActive(true); + @Test + void deniesMissingPostCommitReadback() { + AuthoredWorldSourceEvidence source = source("firemud", TENANT, SOURCE_OPERATION, WORLD); + IntakeReceipt receipt = receipt(source, uuid(55)); + stubFreshWrite(source, receipt); + when(repository.read(receipt.operationId(), TENANT, WORLD, "firemud")) + .thenReturn(Optional.empty()); + + assertThatThrownBy(() -> service.intake(REQUEST, TENANT, SOURCE_OPERATION, WORLD)) + .isInstanceOf(InvalidIntakeEvidenceException.class) + .hasMessageContaining("missing after commit readback"); + assertThat(transactionManager.commitCount).isEqualTo(1); + } + + @Test + void deniesChangedPostCommitReadback() { + AuthoredWorldSourceEvidence source = source("firemud", TENANT, SOURCE_OPERATION, WORLD); + IntakeReceipt written = receipt(source, uuid(55)); + AuthoredWorldSourceEvidence changedSource = + source("firemud", TENANT, SOURCE_OPERATION, WORLD, "Changed display"); + IntakeReceipt corruptReadback = + new IntakeReceipt( + written.operationId(), + REQUEST, + GameSessionAuthoredWorldIntakeDigest.requestDigest(REQUEST, changedSource), + changedSource, + GameSessionAuthoredWorldIntakeDigest.receiptDigest( + written.operationId(), + GameSessionAuthoredWorldIntakeDigest.requestDigest(REQUEST, changedSource), + changedSource.evidenceDigest())); + stubFreshWrite(source, written); + when(repository.read(written.operationId(), TENANT, WORLD, "firemud")) + .thenReturn(Optional.of(corruptReadback)); + + assertThatThrownBy(() -> service.intake(REQUEST, TENANT, SOURCE_OPERATION, WORLD)) + .isInstanceOf(InvalidIntakeEvidenceException.class) + .hasMessageContaining("changed during commit readback"); + assertThat(transactionManager.commitCount).isEqualTo(1); + } + + private void stubFreshWrite(AuthoredWorldSourceEvidence source, IntakeReceipt receipt) { + when(repository.readByIntakeRequest("firemud", REQUEST)).thenReturn(Optional.empty()); + when(client.resolveAuthoredWorldSource( + eq(TENANT.toString()), eq(SOURCE_OPERATION.toString()), eq(WORLD), anyString())) + .thenReturn(source); + when(repository.register(REQUEST, source)).thenReturn(receipt); } private static AuthoredWorldSourceEvidence source( String namespace, UUID tenant, UUID operation, String world) { - var registration = UUID.fromString("11111111-1111-4111-8111-111111111111"); + return source(namespace, tenant, operation, world, "Café 🐉"); + } + + private static AuthoredWorldSourceEvidence source( + String namespace, UUID tenant, UUID operation, String world, String displayName) { + UUID registration = uuid(11); String request = AuthoredWorldSourceDigest.requestDigest( - namespace, registration, tenant, "north-star", world, "Café 🐉"); + namespace, registration, tenant, "north-star", world, displayName); String evidence = AuthoredWorldSourceDigest.evidenceDigest( namespace, @@ -145,7 +287,7 @@ private static AuthoredWorldSourceEvidence source( tenant, "north-star", world, - "Café 🐉", + displayName, 42L, "legacy-game-tenant-42", "RETAINED_GAME_V30"); @@ -158,10 +300,52 @@ private static AuthoredWorldSourceEvidence source( tenant, "north-star", world, - "Café 🐉", + displayName, 42L, "legacy-game-tenant-42", "RETAINED_GAME_V30", evidence); } + + private static IntakeReceipt receipt(AuthoredWorldSourceEvidence source, UUID operationId) { + String requestDigest = GameSessionAuthoredWorldIntakeDigest.requestDigest(REQUEST, source); + return new IntakeReceipt( + operationId, + REQUEST, + requestDigest, + source, + GameSessionAuthoredWorldIntakeDigest.receiptDigest( + operationId, requestDigest, source.evidenceDigest())); + } + + private static UUID uuid(int value) { + return UUID.fromString(String.format("%08d-1111-4111-8111-111111111111", value)); + } + + private static final class RecordingTransactionManager implements PlatformTransactionManager { + private TransactionDefinition startedWith; + private int commitCount; + + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + startedWith = definition; + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(definition.isReadOnly()); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + definition.getIsolationLevel()); + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) { + commitCount++; + TransactionSynchronizationManager.clear(); + } + + @Override + public void rollback(TransactionStatus status) { + TransactionSynchronizationManager.clear(); + } + } } diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeMtlsIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeMtlsIntegrationTest.java index ba30191729..7e8cdcc1b8 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeMtlsIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeMtlsIntegrationTest.java @@ -467,7 +467,7 @@ private static Scenario newScenario(String worldSlug) { String displayName = "World " + worldSlug; long sourceGameRowId = Math.abs(UUID.randomUUID().getMostSignificantBits() % 1_000_000_000L) + 1L; - String sourceGameTenantKey = "source-key-" + UUID.randomUUID(); + String sourceGameTenantKey = "src-" + UUID.randomUUID().toString().replace("-", ""); String sourceRequestDigest = AuthoredWorldSourceDigest.requestDigest( NAMESPACE, registrationRequestId, tenantId, tenantSlug, worldSlug, displayName); From ab0b055a5c25b418cf5b29ab127e2f806118fea6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 01:26:14 +1300 Subject: [PATCH 10/13] Authenticate authored-world servers before sending requests --- .github/workflows/ci.yml | 4 +- .../game-design-service/api-contracts.md | 4 +- .../player-access-and-session.md | 2 + .../world-runtime-and-movement.md | 4 + .../AuthoredWorldLaunchDescriptorClient.java | 8 +- ...GrpcServerPeerIdentityCallCredentials.java | 41 +++++++ .../tenant/AuthoredWorldSourceClient.java | 8 +- .../WorldAuthoredSourceIntakeClient.java | 39 +------ ...ServerPeerIdentityCallCredentialsTest.java | 109 ++++++++++++++++++ ...AuthoredWorldLaunchDescriptorMtlsTest.java | 68 +++++++++-- .../impl/AuthoredWorldSourceMtlsTest.java | 64 ++++++++-- 11 files changed, 287 insertions(+), 64 deletions(-) create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityCallCredentials.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityCallCredentialsTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index df6814573e..4947b73ce5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -901,7 +901,9 @@ jobs: permissions: contents: read id-token: write - timeout-minutes: 20 + # Game Session runs composed owner proofs before its full checks and runtime JAR. + # Exact CI37121026340 exhausted 20m after those proofs passed, at JAR packaging. + timeout-minutes: ${{ matrix.module == 'game-session-service' && 30 || 20 }} strategy: fail-fast: false matrix: diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index fe9b420f58..1115d72628 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -36,7 +36,7 @@ The owner claims `(targetNamespace, registrationRequestId)` and commits the tena Both digests are SHA-256 rendered as `sha256:` plus 64 lowercase hexadecimal digits over fixed-order UTF-8 segments with decimal byte-length `:` framing, as in the fresh-creation contract. The request preimage is `game-design-authored-world-source-request/v1`, namespace, registration request UUID, canonical tenant UUID, tenant slug, world slug and world display name. The evidence preimage is `game-design-authored-world-source-receipt/v1`, namespace, registration request UUID, operation UUID, request digest, canonical tenant UUID, tenant slug, world slug, world display name, canonical decimal source row ID, exact source game tenant key and provenance kind. No field, implicit normalization or unframed concatenation is omitted. Producer and consumer recompute both digests and share positive/changed-field vectors. -The readback request binds a distinct canonical non-nil read `requestId` to the exact source `operationId`, canonical tenant UUID and world slug; the closed response echoes that read identity separately from the original registration identity and carries the complete source evidence. Only the verified same-namespace Game Session and World workloads may read it for their respective catalog and [World intake](../world-management-service/api-contracts.md#authenticated-authored-content-intake-and-tenant-association) consequences. The guard precedes owner data access, and the receiver authenticates Game Design rather than accepting a JWT service claim or digest alone. Missing or changed source, digest/echo/scope mismatch, wrong workload or namespace, and unknown wire fields fail closed. Exact committed readback returns the same source receipt without mutation; it is not a catalog enrollment, released-content or admission result. +The readback request binds a distinct canonical non-nil read `requestId` to the exact source `operationId`, canonical tenant UUID and world slug; the closed response echoes that read identity separately from the original registration identity and carries the complete source evidence. Only the verified same-namespace Game Session and World workloads may read it for their respective catalog and [World intake](../world-management-service/api-contracts.md#authenticated-authored-content-intake-and-tenant-association) consequences. The guard precedes owner data access, and the receiver authenticates Game Design rather than accepting a JWT service claim or digest alone. The consuming client proves the exact same-namespace Game Design workload from the negotiated TLS transport before releasing request metadata or body; response-only verification is insufficient. Missing or changed source, digest/echo/scope mismatch, wrong workload or namespace, and unknown wire fields fail closed. Exact committed readback returns the same source receipt without mutation; it is not a catalog enrollment, released-content or admission result. **Implementation and activation boundary:** The source repository/codec/readback is a prerequisite candidate, not a protected product creator or a live catalog handoff. Normal official-hosted authoring remains subject to the Account-owned commit-bound creator/terms gate below, which cannot be replaced by the source transaction or a caller-supplied authorization flag. No new public creation route or catalog admission is enabled before its producer, receiver, owner authorization and negative proof pass. Retained Game Session tenant keys need a separate audited, Game Design-authenticated association and Game Session's own exact retained-row readback; Account's manifest and numeric/slug similarity cannot establish it. The [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md) owns the remaining implementation and proof. @@ -48,7 +48,7 @@ The committed descriptor retains those source fields and the exact resolved temp The closed binding schema has `schemaVersion=1`. Its request preimage begins with the segment `game-design-authored-world-launch-descriptor-request/v1`, followed by field-name/value segment pairs in this order: `schemaVersion`, `targetNamespace`, `controlPlaneRequestId`, `canonicalTenantId`, `worldSlug`, `authoredWorldSourceOperationId`, `authoredWorldSourceEvidenceDigest`, `gameTemplateId`, then presence/value pairs for `requestedScriptPatchVersion`, `sourceVersionId`, `targetVersionId` and `requestedRuntimeFlagsJson`. Each optional pair uses the exact field names `.present` and `.value`; presence is lowercase `true` or `false`, absent values are empty, and present-empty text is distinct from absence. The result preimage begins with `game-design-authored-world-launch-descriptor-result/v1`, carries the same ordered request pairs, then `requestDigest`, `launchDescriptorId`, `versionId`, presence/value for `scriptPatchVersion`, `runtimeFlagsJson`, `generationConfigRevision`, `versionStateEpoch`, `releaseBundleId`, `publishedReleaseBundleRef`, and presence/value for `remapSetId`. Only `resultDigest` is excluded from that result preimage. Every segment is decimal UTF-8 byte length, `:`, and its exact strict UTF-8 bytes; no trimming, case folding or Unicode normalization occurs. UUIDs are canonical non-nil text, counters use positive canonical decimal text, and each digest is `sha256:` plus 64 lowercase hexadecimal digits. Numeric template/version/release representation in this candidate remains the explicitly tracked owner-graph limitation, not a new canonical identity rule. -Only the exact same-namespace Game Session workload may resolve a new canonical descriptor. Its request claim and immutable result commit atomically in the existing descriptor family. An identical retry returns the stored descriptor without resolving changed defaults, another version or another release. Conflicting source, scope or request input denies without replacing the original. Retained unbound or unmapped rows cannot be interpreted as canonical evidence. Exact committed readback is non-mutating and checks the complete stored binding; it cannot create a descriptor or repair an association. Only the exact same-namespace Game Session and World workloads may consume that owner readback, and consumers authenticate Game Design rather than trusting a forwarded digest or JWT service claim. +Only the exact same-namespace Game Session workload may resolve a new canonical descriptor. Its request claim and immutable result commit atomically in the existing descriptor family. An identical retry returns the stored descriptor without resolving changed defaults, another version or another release. Conflicting source, scope or request input denies without replacing the original. Retained unbound or unmapped rows cannot be interpreted as canonical evidence. Exact committed readback is non-mutating and checks the complete stored binding; it cannot create a descriptor or repair an association. Only the exact same-namespace Game Session and World workloads may consume that owner readback, and consumers authenticate Game Design rather than trusting a forwarded digest or JWT service claim. Both resolution and read clients prove the exact same-namespace Game Design workload from the negotiated TLS transport before releasing request metadata or body and independently verify the response; a trusted certificate for another workload or namespace cannot receive the request. A committed deterministic business denial is also an immutable launch-request outcome: exact `ResolveLaunchDescriptor` retries return its original error code/message even after template, readiness or release state changes. The same owner family retains the exact request digest and verified source evidence; an unsuccessful resolution does not fabricate a descriptor, version, release or successful-result digest. A new attempt requires a new `controlPlaneRequestId`. Wrong caller, invalid request/source, storage corruption, transient unavailability and ambiguous transaction outcomes are not converted into terminal business receipts. `GetLaunchDescriptor` remains exact successful-descriptor readback rather than a synthetic failed descriptor. 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 58eabbddad..da5d321b41 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 `202c58f1605018f6bf51277ac4f431497eca9a34` [CI37121026340](https://github.com/benhook1013/FireMUD/actions/runs/37121026340) completed with aggregate failure and its sole observer finished. Independently parsed/rehashed raw XML proves all34 focused Account/World/Game Session methods executed cleanly with zero skips: canonical journal4, reconciliation4, World physical socket7, owner-local PostgreSQL8, real World PostgreSQL/socket3 and Game Session source intake8. The V51 diagnostic-preserving recovery, corrected World source fixture and all three real Game Session service/transaction/readback methods are now executed component proof. Upstream source/policy fixtures remain synthetic; this is not public JOIN or normal creation/delivery. The Game Session job exhausted its exact20-minute budget after focused proof passed and while packaging the runtime JAR, as its check annotation confirms; the bounded job allowance is now30minutes for Game Session only, leaving other modules at20 and retaining all proof/check/failure propagation. Its later whole-job success still needs execution. Game Design's duplicate-key fixture, Automation formatting, Python lint and the dev-demo workflow validator remain concrete other-owner failures. No aggregate-green, fresh-image/live or activation claim follows, and the Account ring mount remains unpublished. + The explicitly unwired Game Session authored-source intake now rejects an ambient transaction or synchronization before reading Game Design, fetches fresh immutable evidence outside its owner transaction, and opens a short writable READ COMMITTED transaction only for local registration. It independently reads and compares the complete committed result before success. Exact retries first read the original immutable local request, source and tenant binding, without another source call or write; changed tenant, source operation or world scope conflicts. Missing or contradictory post-commit readback denies success without replacing committed evidence. This corrects the former mandatory outer-transaction prerequisite; it does not add a creator API, automatic handoff, runtime catalog activation or admission. The [Game Session API contract](../../architecture/microservices/game-session-service/api-contracts.md#authored-world-source-intake-and-durable-readback) owns the transaction and retry boundary. The corrected full Game Session check, boot JAR, formatting, Checkstyle, SpotBugs, coverage, links and Markdown pass locally in 2m33s (134 tasks: 56 executed, 78 up-to-date). Independently parsed XML records 1,886 unit, 18 non-Docker integration and 26 cross-service cases executed cleanly, including all ten intake service unit cases. Seventeen unit, 172 integration and 54 cross-service cases skip locally without Docker. All eight authored-source PostgreSQL methods compile and skip, including the three new real-service cases for committed readback/exact retry, rollback/no partial claims and retained commit recovery after a lost post-commit readback. Their upstream Game Design response is explicitly synthetic; no authenticated source producer or network handoff is proved by them. CI requires all three new methods and captures the raw suite XML. Actual corrected-head PostgreSQL execution, fresh-image/live proof and automatic authorized creation/delivery remain open; runtime and ring-mount gates are unchanged. Gradle completed successfully while discarding its configuration-cache entry with 71 reported protobuf serialization problems; this is not a failed test gate or proof that the cache works. diff --git a/design/project-management/implementation-tracking/world-runtime-and-movement.md b/design/project-management/implementation-tracking/world-runtime-and-movement.md index f76e02d7b0..e7861b52a8 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -10,8 +10,12 @@ This is a non-normative implementation tracker for world runtime and movement. C The newer transport is explicitly unregistered: closed shared codec/client, exact Game Design peer guard before decoding or owner access, exact namespace enforcement, and non-mutating committed-receipt readback. The client verifies World's exact workload before releasing requests, not merely before accepting replies. Seven physical socket cases execute cleanly locally with a mocked owner, including wrong-server intake/read rejection with no owner interaction. The full Core/Account/World gate, both affected boot JARs, formatting, static analysis, coverage and documentation checks pass; Core208 and World146 unit cases are clean. All eighteen World integration nodes compile but skip locally without Docker, including three new real World PostgreSQL-through-socket composition cases for committed readback, lost acknowledgement/exact retry and denial without mutation. Their upstream Game Design source answer is synthetic; even successful execution would not prove its producer or automatic delivery. CI strictly requires and captures both new socket suites. +The Game Design source/descriptor consumers now use the same pre-send exact-server guard as World intake, retaining independent response verification. The prior response-only guard could reject a wrong workload's response after delivering the request; the old source socket fixture explicitly expected two owner reads on wrong-server attempts. The corrected socket fixtures instead observe zero inbound RPCs, metadata, messages and owner calls for wrong workload/namespace servers, including descriptor resolution. All thirteen descriptor, nine source-read and seven World socket methods execute cleanly locally, with mocked owners; three shared guard unit methods pass. The full Core/Game Design/World/Game Session checks and all three affected boot JARs pass in 4m08s (203 tasks; 80 executed, 123 up-to-date). Parsed XML is clean for Core211, Game Design349, World146 and Game Session1886 unit executions plus18 integration and26 cross-service executions. All54 Game Design and18 World PostgreSQL cases, plus172 Game Session integration nodes, skip locally without Docker. This strengthens transport proof only; database/source producer composition and activation remain separate gates under the [Game Design owner contract](../../architecture/microservices/game-design-service/api-contracts.md#authored-source-bound-launch-descriptor-and-exact-readback). + Exact `00285d5a9474a01970293d5a225ad0c63ce1a611` [CI37118817841](https://github.com/benhook1013/FireMUD/actions/runs/37118817841) independently proves all seven physical socket and eight owner-local PostgreSQL cases executed cleanly, with zero skips. All three newer PostgreSQL/socket methods executed but failed during source-fixture construction: `source-key-` plus a full random UUID exceeded Game Design's unchanged 36-code-point key bound. The test-only correction uses `src-` plus an independently random hyphenless UUID, exactly 36 characters; it neither derives a tenant association nor changes the owner validator. Corrected database/socket execution remains required, rather than claiming the failed setup exercised its socket or owner assertions. The aggregate run is red on this fixture, Account's terminal-diagnostic constraint and concrete other-owner failures. Live deployment and all activation gates remain unproved/denied. +Exact corrected `202c58f1605018f6bf51277ac4f431497eca9a34` [CI37121026340](https://github.com/benhook1013/FireMUD/actions/runs/37121026340) now proves all three World PostgreSQL/socket methods, all eight owner-local PostgreSQL methods and all seven World socket methods executed cleanly without skips. Root independently parsed and rehashed their raw XML. The three composed methods use real World persistence, service, transaction manager, handler and transport but synthetic upstream Game Design source evidence; they are not automatic creation/delivery or live deployment. Aggregate CI remains red on concrete other-owner checks and Game Session's20-minute packaging timeout; none is relabeled flaky or presumed fixed. This run precedes the subsequent Game Design client pre-send guard correction above, which has local socket proof and still needs its own corrected-state runner. + The automatic normal Game Design registration/delivery producer, canonical-source-qualified content writer, exact content/descriptor/release readback, separate audited retained-World association and canonical lifecycle composition remain required. The [World API contract](../../architecture/microservices/world-management-service/api-contracts.md#authenticated-authored-content-intake-and-tenant-association) owns this boundary. Numeric similarity, selectors and Account's migration manifest are not substitutes, and no runtime activation is authorized. The prior World full CI job passed while aggregate CI failed on identified Game Design fixture, Automation formatting and shared-tooling checks; no aggregate-green claim follows from focused proof. The canonical launch correction must also supply genuinely fresh instance creation, not merely attach a UUID carrier to the legacy prepare call: Game Session's `game_instances.tenant_id` and World's lifecycle/topology tenant selectors remain required numeric fields on this tree. A fresh canonical catalog provides no numeric tenant alias. Widen the actual owner instance/lifecycle representation and source-qualified creation/readback together; adding a binding table while inventing a numeric tenant selector would not close this gate. Exact retained instance associations remain separately source-proved and cannot be inferred from the Game Session row number or an Account mapping. diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClient.java index 02808eedf5..26521808af 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClient.java @@ -12,6 +12,7 @@ import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; import net.firedevops.firemud.gamedesign.v1.GameDesignServiceGrpc; @@ -109,10 +110,11 @@ protected String defaultTarget() { @Override protected GameDesignServiceGrpc.GameDesignServiceBlockingStub buildStub(ManagedChannel channel) { + String expectedGameDesignPeerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service"; return GameDesignServiceGrpc.newBlockingStub(channel) - .withInterceptors( - new GrpcServerPeerIdentityClientInterceptor( - "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service")) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedGameDesignPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedGameDesignPeerUri)) .withCompression("gzip"); } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityCallCredentials.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityCallCredentials.java new file mode 100644 index 0000000000..a53c0b5511 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityCallCredentials.java @@ -0,0 +1,41 @@ +package net.firedevops.firemud.common.grpc; + +import io.grpc.CallCredentials; +import io.grpc.Grpc; +import io.grpc.Metadata; +import io.grpc.Status; +import java.util.concurrent.Executor; + +/** Authenticates the exact server workload before gRPC releases request headers or body. */ +public final class GrpcServerPeerIdentityCallCredentials extends CallCredentials { + private final String expectedPeerUri; + + public GrpcServerPeerIdentityCallCredentials(String expectedPeerUri) { + this.expectedPeerUri = + GrpcPeerIdentity.parseUri(expectedPeerUri) + .map(GrpcPeerIdentity::uri) + .filter(uri -> uri.equals(expectedPeerUri)) + .orElseThrow( + () -> new IllegalArgumentException("Exact server workload URI is required")); + } + + @Override + public void applyRequestMetadata( + RequestInfo requestInfo, Executor appExecutor, MetadataApplier applier) { + var sslSession = + requestInfo == null || requestInfo.getTransportAttrs() == null + ? null + : requestInfo.getTransportAttrs().get(Grpc.TRANSPORT_ATTR_SSL_SESSION); + boolean exactPeer = + GrpcPeerIdentity.fromSslSession(sslSession) + .map(peer -> expectedPeerUri.equals(peer.uri())) + .orElse(false); + if (!exactPeer) { + applier.fail( + Status.UNAUTHENTICATED.withDescription( + "Request requires the exact authenticated server workload identity")); + return; + } + applier.apply(new Metadata()); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceClient.java index fff22828fd..aa43249ae9 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceClient.java @@ -12,6 +12,7 @@ import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; import net.firedevops.firemud.gamedesign.v1.TenantIdentityServiceGrpc; @@ -87,10 +88,11 @@ protected String defaultTarget() { @Override protected TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub buildStub( ManagedChannel channel) { + String expectedGameDesignPeerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service"; return TenantIdentityServiceGrpc.newBlockingStub(channel) - .withInterceptors( - new GrpcServerPeerIdentityClientInterceptor( - "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service")) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedGameDesignPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedGameDesignPeerUri)) .withCompression("gzip"); } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeClient.java index 05190c81df..9bd4be4004 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeClient.java @@ -1,15 +1,10 @@ package net.firedevops.firemud.common.tenant; -import io.grpc.CallCredentials; -import io.grpc.Grpc; import io.grpc.ManagedChannel; -import io.grpc.Metadata; -import io.grpc.Status; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Objects; -import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLException; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; @@ -17,6 +12,7 @@ import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; import net.firedevops.firemud.worldmanagement.v1.WorldAuthoredSourceIntakeServiceGrpc; @@ -113,7 +109,7 @@ protected String defaultTarget() { String expectedWorldPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service"; return WorldAuthoredSourceIntakeServiceGrpc.newBlockingStub(channel) - .withCallCredentials(new ExactWorldServerCallCredentials(expectedWorldPeerUri)) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedWorldPeerUri)) .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedWorldPeerUri)) .withCompression("gzip"); } @@ -142,37 +138,6 @@ private void requireNamespace(String targetNamespace) { } } - /** Authenticates the negotiated server before gRPC releases request headers or body. */ - private static final class ExactWorldServerCallCredentials extends CallCredentials { - private final String expectedPeerUri; - - private ExactWorldServerCallCredentials(String expectedPeerUri) { - this.expectedPeerUri = expectedPeerUri; - } - - @Override - public void applyRequestMetadata( - CallCredentials.RequestInfo requestInfo, - Executor appExecutor, - CallCredentials.MetadataApplier applier) { - var sslSession = - requestInfo == null || requestInfo.getTransportAttrs() == null - ? null - : requestInfo.getTransportAttrs().get(Grpc.TRANSPORT_ATTR_SSL_SESSION); - boolean exactPeer = - GrpcPeerIdentity.fromSslSession(sslSession) - .map(peer -> expectedPeerUri.equals(peer.uri())) - .orElse(false); - if (!exactPeer) { - applier.fail( - Status.UNAUTHENTICATED.withDescription( - "World intake requires the exact authenticated World workload identity")); - return; - } - applier.apply(new Metadata()); - } - } - private static CommonGrpcClientProperties requireFileBackedMtls( CommonGrpcClientProperties tlsProperties) { if (tlsProperties == null) { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityCallCredentialsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityCallCredentialsTest.java new file mode 100644 index 0000000000..5aec1c8190 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityCallCredentialsTest.java @@ -0,0 +1,109 @@ +package net.firedevops.firemud.common.grpc; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.grpc.Attributes; +import io.grpc.CallCredentials; +import io.grpc.Grpc; +import io.grpc.Metadata; +import io.grpc.Status; +import java.security.cert.Certificate; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.List; +import javax.net.ssl.SSLSession; +import org.junit.jupiter.api.Test; + +class GrpcServerPeerIdentityCallCredentialsTest { + private static final String EXPECTED = "spiffe://firemud/ns/test/sa/game-design-service"; + + @Test + void appliesOnlyEmptyMetadataAfterExactServerIdentityIsVerified() throws Exception { + CallCredentials.MetadataApplier applier = mock(CallCredentials.MetadataApplier.class); + var credentials = new GrpcServerPeerIdentityCallCredentials(EXPECTED); + + credentials.applyRequestMetadata(requestInfo(session(EXPECTED)), Runnable::run, applier); + + var metadata = org.mockito.ArgumentCaptor.forClass(Metadata.class); + verify(applier).apply(metadata.capture()); + assertThat(metadata.getValue().keys()).isEmpty(); + verify(applier, never()).fail(any()); + } + + @Test + void missingAmbiguousWrongNamespaceOrWrongWorkloadIdentityFailsWithoutMetadata() + throws Exception { + var credentials = new GrpcServerPeerIdentityCallCredentials(EXPECTED); + List requests = new ArrayList<>(); + requests.add(requestInfo(null)); + requests.add(requestInfo(session())); + requests.add(requestInfo(session(EXPECTED, "spiffe://firemud/ns/test/sa/account-service"))); + requests.add(requestInfo(session("spiffe://firemud/ns/other/sa/game-design-service"))); + requests.add(requestInfo(session("spiffe://firemud/ns/test/sa/account-service"))); + + for (CallCredentials.RequestInfo request : requests) { + CallCredentials.MetadataApplier applier = mock(CallCredentials.MetadataApplier.class); + credentials.applyRequestMetadata(request, Runnable::run, applier); + + verify(applier, never()).apply(any()); + var status = org.mockito.ArgumentCaptor.forClass(Status.class); + verify(applier).fail(status.capture()); + assertThat(status.getValue().getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); + } + + CallCredentials.MetadataApplier missingRequestInfoApplier = + mock(CallCredentials.MetadataApplier.class); + credentials.applyRequestMetadata(null, Runnable::run, missingRequestInfoApplier); + verify(missingRequestInfoApplier, never()).apply(any()); + var missingRequestInfoStatus = org.mockito.ArgumentCaptor.forClass(Status.class); + verify(missingRequestInfoApplier).fail(missingRequestInfoStatus.capture()); + assertThat(missingRequestInfoStatus.getValue().getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED); + } + + @Test + void constructorRequiresOneExactCanonicalWorkloadUri() { + assertThatThrownBy(() -> new GrpcServerPeerIdentityCallCredentials(null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new GrpcServerPeerIdentityCallCredentials("not-a-workload")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new GrpcServerPeerIdentityCallCredentials( + "spiffe://FIREMUD/ns/test/sa/game-design-service")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new GrpcServerPeerIdentityCallCredentials( + "spiffe://firemud/ns/test/sa/not-a-service")) + .isInstanceOf(IllegalArgumentException.class); + } + + private static CallCredentials.RequestInfo requestInfo(SSLSession session) { + CallCredentials.RequestInfo requestInfo = mock(CallCredentials.RequestInfo.class); + Attributes attributes = + session == null + ? Attributes.EMPTY + : Attributes.newBuilder().set(Grpc.TRANSPORT_ATTR_SSL_SESSION, session).build(); + when(requestInfo.getTransportAttrs()).thenReturn(attributes); + return requestInfo; + } + + private static SSLSession session(String... peerUris) throws Exception { + SSLSession session = mock(SSLSession.class); + X509Certificate certificate = mock(X509Certificate.class); + List> alternatives = new ArrayList<>(); + for (String uri : peerUris) { + alternatives.add(List.of(6, uri)); + } + when(certificate.getSubjectAlternativeNames()).thenReturn(alternatives); + when(session.getPeerCertificates()).thenReturn(new Certificate[] {certificate}); + return session; + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldLaunchDescriptorMtlsTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldLaunchDescriptorMtlsTest.java index c0aa33c658..1f2555b239 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldLaunchDescriptorMtlsTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldLaunchDescriptorMtlsTest.java @@ -9,6 +9,7 @@ import com.google.protobuf.UnknownFieldSet; import io.grpc.ForwardingServerCall.SimpleForwardingServerCall; +import io.grpc.ForwardingServerCallListener.SimpleForwardingServerCallListener; import io.grpc.ManagedChannel; import io.grpc.Metadata; import io.grpc.Server; @@ -44,6 +45,7 @@ import java.util.Set; import java.util.UUID; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; @@ -217,6 +219,11 @@ void startPhysicalReceiver() throws Exception { } private Server startReceiver(TestCertificate serverCertificate) throws Exception { + return startReceiver(serverCertificate, null); + } + + private Server startReceiver( + TestCertificate serverCertificate, InboundRpcCapture inboundRpcCapture) throws Exception { GameDesignGrpcService service = new GameDesignGrpcService( Mockito.mock(PingService.class), @@ -232,6 +239,23 @@ private Server startReceiver(TestCertificate serverCertificate) throws Exception ReflectionTestUtils.setField(service, "workloadNamespace", NAMESPACE); Set unauthenticatedMethods = publicMethods("application.yml"); + ServerInterceptor[] interceptors = + inboundRpcCapture == null + ? new ServerInterceptor[] { + responseMutationInterceptor(responseMutation), + new AuthTokenInterceptor( + new JwtUtil("test-secret-key-test-secret-key-32-bytes", 60_000), + unauthenticatedMethods), + new GrpcPeerIdentityInterceptor() + } + : new ServerInterceptor[] { + inboundRpcCapture, + responseMutationInterceptor(responseMutation), + new AuthTokenInterceptor( + new JwtUtil("test-secret-key-test-secret-key-32-bytes", 60_000), + unauthenticatedMethods), + new GrpcPeerIdentityInterceptor() + }; return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) .sslContext( GrpcSslContexts.configure( @@ -240,14 +264,7 @@ private Server startReceiver(TestCertificate serverCertificate) throws Exception .trustManager(pki.caCertificate()) .clientAuth(ClientAuth.REQUIRE) .build()) - .addService( - ServerInterceptors.intercept( - service, - responseMutationInterceptor(responseMutation), - new AuthTokenInterceptor( - new JwtUtil("test-secret-key-test-secret-key-32-bytes", 60_000), - unauthenticatedMethods), - new GrpcPeerIdentityInterceptor())) + .addService(ServerInterceptors.intercept(service, interceptors)) .build() .start(); } @@ -354,18 +371,21 @@ void sharedClientRejectsWrongGameDesignServerWorkloadAndNamespaceBeforeReturning for (TestCertificate serverCertificate : List.of(pki.wrongServerWorkloadCertificate(), pki.wrongServerNamespaceCertificate())) { - Server wrongIdentityServer = startReceiver(serverCertificate); + InboundRpcCapture inboundRpcCapture = new InboundRpcCapture(); + Server wrongIdentityServer = startReceiver(serverCertificate, inboundRpcCapture); AuthoredWorldLaunchDescriptorClient client = newSharedClient(directory.resolve(UUID.randomUUID().toString()), wrongIdentityServer); try { client.init(); assertServerPeerRefused(() -> client.resolve(BOUND_REQUEST)); assertServerPeerRefused(() -> client.get(readClientRequest())); + inboundRpcCapture.assertNoInboundRequests(); } finally { client.close(); stopServer(wrongIdentityServer); } } + verifyNoInteractions(launchDescriptorService); } @Test @@ -558,6 +578,36 @@ private static void assertServerPeerRefused(Runnable call) { assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); } + private static final class InboundRpcCapture implements ServerInterceptor { + private final AtomicInteger rpcCount = new AtomicInteger(); + private final AtomicInteger requestMessageCount = new AtomicInteger(); + private final AtomicReference methodName = new AtomicReference<>(); + private final AtomicReference requestMetadata = new AtomicReference<>(); + + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + rpcCount.incrementAndGet(); + methodName.set(call.getMethodDescriptor().getFullMethodName()); + requestMetadata.set(headers); + ServerCall.Listener listener = next.startCall(call, headers); + return new SimpleForwardingServerCallListener<>(listener) { + @Override + public void onMessage(ReqT message) { + requestMessageCount.incrementAndGet(); + super.onMessage(message); + } + }; + } + + private void assertNoInboundRequests() { + assertThat(rpcCount.get()).isZero(); + assertThat(requestMessageCount.get()).isZero(); + assertThat(methodName.get()).isNull(); + assertThat(requestMetadata.get()).isNull(); + } + } + private static void assertClientCodecRejected(Runnable call, String expectedCauseMessage) { Throwable failure = catchFailure(call); assertThat(failure).isInstanceOf(IllegalStateException.class); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceMtlsTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceMtlsTest.java index 0d27b8182f..296356f2ee 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceMtlsTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceMtlsTest.java @@ -9,6 +9,7 @@ import com.google.protobuf.UnknownFieldSet; import io.grpc.ForwardingServerCall.SimpleForwardingServerCall; +import io.grpc.ForwardingServerCallListener.SimpleForwardingServerCallListener; import io.grpc.ManagedChannel; import io.grpc.Metadata; import io.grpc.Server; @@ -44,6 +45,7 @@ import java.util.Set; import java.util.UUID; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; @@ -306,7 +308,8 @@ void sharedClientRefusesWrongGameDesignServerWorkloadAndNamespace(@TempDir Path throws Exception { for (TestCertificate serverCertificate : List.of(pki.wrongServerWorkloadCertificate(), pki.wrongServerNamespaceCertificate())) { - Server wrongIdentityServer = startReceiver(serverCertificate); + InboundRpcCapture inboundRpcCapture = new InboundRpcCapture(); + Server wrongIdentityServer = startReceiver(serverCertificate, inboundRpcCapture); AuthoredWorldSourceClient client = newSharedClient( directory.resolve(UUID.randomUUID().toString()), @@ -315,14 +318,14 @@ void sharedClientRefusesWrongGameDesignServerWorkloadAndNamespace(@TempDir Path try { client.init(); assertServerPeerRefused(() -> client.read(READ_REQUEST)); + inboundRpcCapture.assertNoInboundRequests(); } finally { client.close(); stopServer(wrongIdentityServer); } } - verify(authoredWorldRepository, times(2)) - .read(SOURCE_OPERATION_ID, TENANT_ID, "harbor-world", NAMESPACE); + verifyNoInteractions(authoredWorldRepository); } @Test @@ -432,6 +435,11 @@ void productionYamlAndSocketGuardsKeepWorldAccessLimitedToExactSourceMethod() th } private Server startReceiver(TestCertificate serverCertificate) throws Exception { + return startReceiver(serverCertificate, null); + } + + private Server startReceiver( + TestCertificate serverCertificate, InboundRpcCapture inboundRpcCapture) throws Exception { TenantIdentityGrpcService service = new TenantIdentityGrpcService( gameRepository, @@ -441,6 +449,19 @@ private Server startReceiver(TestCertificate serverCertificate) throws Exception gameSessionAssociationRepository, NAMESPACE); Set unauthenticatedMethods = publicMethods("application.yml"); + ServerInterceptor[] interceptors = + inboundRpcCapture == null + ? new ServerInterceptor[] { + responseMutationInterceptor(responseMutation), + new AuthTokenInterceptor(new JwtUtil(JWT_SECRET, 60_000L), unauthenticatedMethods), + new GrpcPeerIdentityInterceptor() + } + : new ServerInterceptor[] { + inboundRpcCapture, + responseMutationInterceptor(responseMutation), + new AuthTokenInterceptor(new JwtUtil(JWT_SECRET, 60_000L), unauthenticatedMethods), + new GrpcPeerIdentityInterceptor() + }; return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) .sslContext( GrpcSslContexts.configure( @@ -449,12 +470,7 @@ private Server startReceiver(TestCertificate serverCertificate) throws Exception .trustManager(pki.caCertificate()) .clientAuth(ClientAuth.REQUIRE) .build()) - .addService( - ServerInterceptors.intercept( - service, - responseMutationInterceptor(responseMutation), - new AuthTokenInterceptor(new JwtUtil(JWT_SECRET, 60_000L), unauthenticatedMethods), - new GrpcPeerIdentityInterceptor())) + .addService(ServerInterceptors.intercept(service, interceptors)) .build() .start(); } @@ -598,6 +614,36 @@ private static void assertServerPeerRefused(Runnable call) { .contains("exact authenticated server workload identity"); } + private static final class InboundRpcCapture implements ServerInterceptor { + private final AtomicInteger rpcCount = new AtomicInteger(); + private final AtomicInteger requestMessageCount = new AtomicInteger(); + private final AtomicReference methodName = new AtomicReference<>(); + private final AtomicReference requestMetadata = new AtomicReference<>(); + + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + rpcCount.incrementAndGet(); + methodName.set(call.getMethodDescriptor().getFullMethodName()); + requestMetadata.set(headers); + ServerCall.Listener listener = next.startCall(call, headers); + return new SimpleForwardingServerCallListener<>(listener) { + @Override + public void onMessage(ReqT message) { + requestMessageCount.incrementAndGet(); + super.onMessage(message); + } + }; + } + + private void assertNoInboundRequests() { + assertThat(rpcCount.get()).isZero(); + assertThat(requestMessageCount.get()).isZero(); + assertThat(methodName.get()).isNull(); + assertThat(requestMetadata.get()).isNull(); + } + } + private static void assertClientCodecRejected(Runnable call, String expectedEvidence) { Throwable failure = catchFailure(call); assertThat(failure).isInstanceOf(IllegalStateException.class); From 045e712213456ea067f94736ad77d85b2e4309cd Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 04:26:51 +1300 Subject: [PATCH 11/13] Pin composed migration incident to its exact CI run --- .../implementation-tracking/player-access-and-session.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 a28c00c7af..fe8e58e422 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -13,7 +13,7 @@ The explicitly unwired Game Session authored-source intake now rejects an ambien The corrected full Game Session check, boot JAR, formatting, Checkstyle, SpotBugs, coverage, links and Markdown pass locally in 2m33s (134 tasks: 56 executed, 78 up-to-date). Independently parsed XML records 1,886 unit, 18 non-Docker integration and 26 cross-service cases executed cleanly, including all ten intake service unit cases. Seventeen unit, 172 integration and 54 cross-service cases skip locally without Docker. All eight authored-source PostgreSQL methods compile and skip, including the three new real-service cases for committed readback/exact retry, rollback/no partial claims and retained commit recovery after a lost post-commit readback. Their upstream Game Design response is explicitly synthetic; no authenticated source producer or network handoff is proved by them. CI requires all three new methods and captures the raw suite XML. Actual corrected-head PostgreSQL execution, fresh-image/live proof and automatic authorized creation/delivery remain open; runtime and ring-mount gates are unchanged. Gradle completed successfully while discarding its configuration-cache entry with 71 reported protobuf serialization problems; this is not a failed test gate or proof that the cache works. Exact published `00285d5a9474a01970293d5a225ad0c63ce1a611` [CI37118817841](https://github.com/benhook1013/FireMUD/actions/runs/37118817841) is terminal failure and its sole observer has finished. Independently parsed and rehashed raw XML shows eight Account cases executed without skips: four passed and four failed. The canonical journal's three nonterminal cases pass after the typed-query and fixture corrections. Its terminal case and three reconciler cases expose the inherited V26 `account_join_pending_attempt_failure_check`: it rejects a COMMITTED row retaining an earlier UNAVAILABLE diagnostic although V50 explicitly permits that exact canonical recovery with the original AVAILABLE policy. Forward V51 now corrects only that check, preserving the original V1 rule, immutable diagnostic/history bytes and every V50 guard; it neither rewrites old migrations nor clears diagnostics, fabricates policy or relaxes readback, expiry or current-membership gates. Focused fixtures retain successful AVAILABLE-policy rebinding proof and additionally prove diagnostic-preserving terminal retry and malformed/V1 terminal denial. The final composed Account/Game Session/World checks, all three boot JARs and documentation pass in 2m6s (182 tasks: 49 executed, 133 up-to-date); the final Account fixture-preservation gate passes in 28s (72 tasks: 14 executed, 58 up-to-date). Same-code XML records 715 Account and 146 World clean unit cases; final matching results are reused. Account's 276 and World's 18 integration nodes still skip locally, so corrected-head PostgreSQL execution remains required. The same runner proves seven physical World socket cases and eight World owner-local PostgreSQL cases cleanly, but all three newer World PostgreSQL/socket cases fail during synthetic source-key setup before their assertions. No full workflow, aggregate success or activation follows. Positive JOIN production, authenticated current-target/entitlement evidence and complete runtime reconciliation remain open, and runtime paths and the Account ring mount remain denied/unpublished. -The same exact run's Game Session/TCP startup evidence exposes V13 duplicating the V7 `realm_id` audit column; `catalog_revision` was also already present. The retained-safe correction reuses both columns, preserves legitimate legacy realm/namespace/catalog values and their pair invariant, and applies canonical CLOSED's no-runtime/namespace-alias shape only to representation two. The existing retained-row fixture now captures the actual V7 values before upgrade and compares them afterward; a new mandatory PostgreSQL case rejects numeric and namespace aliases without pointer/audit/outcome growth. Corrected runner execution is required. The earlier Game Session authored-source failures do not have separately uploaded raw XML, so their shared migration root cause is an inference from startup evidence rather than five independently verified executions. +Exact #2949 `d557bd49c0fa6e162af2006be326bd89e5b6f156` [CI37209247075](https://github.com/benhook1013/FireMUD/actions/runs/37209247075)'s Game Session/TCP startup evidence exposes V13 duplicating the V7 `realm_id` audit column; `catalog_revision` was also already present. The retained-safe correction reuses both columns, preserves legitimate legacy realm/namespace/catalog values and their pair invariant, and applies canonical CLOSED's no-runtime/namespace-alias shape only to representation two. The existing retained-row fixture now captures the actual V7 values before upgrade and compares them afterward; a new mandatory PostgreSQL case rejects numeric and namespace aliases without pointer/audit/outcome growth. Corrected runner execution is required. This run's Game Session authored-source failures do not have separately uploaded raw XML, so their shared migration root cause is an inference from startup evidence rather than five independently verified executions. Exact #2949 `d557bd49c0fa6e162af2006be326bd89e5b6f156` [CI37209247075](https://github.com/benhook1013/FireMUD/actions/runs/37209247075) completed with aggregate failure. Raw XML establishes three canonical scope cases, one canonical membership-identity case, six of seven canonical receipt cases and all nine physical Logging mTLS cases passed without skips. The retained receipt upgrade failed in V48 because its migration-owned `receipt_head_id` backfill invoked V41's runtime append-only trigger. The bounded correction suspends only that named trigger around the transactional backfill and immediately restores it; the retained-upgrade fixture proves unchanged original receipt fields and sequence plus subsequent UPDATE/DELETE rejection. The Logging strict gate also demanded four obsolete successful-Create method names; their replacements require the actual current denied-Create/allowed-readback cases, retaining all nine mandatory physical mTLS cases. Corrected-head PostgreSQL execution remains required. Missing first-JOIN, typed Logging migration and catalog/CLOSED raw XML is unavailable proof, not a pass. Shared Ruff and Python websocket dependency failures remain separately routed. No runtime activation, deployed migration repair or fresh-image success is claimed. From e8f97baf50635f61782b23a6b986819ed3b4b1ef Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 12:24:16 +1300 Subject: [PATCH 12/13] 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 da3c0c8ee9..e9070fabf5 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 0505219c62d38d92e208c6abeb9769e238050dbd Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 17:35:51 +1300 Subject: [PATCH 13/13] 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 e9070fabf5..8fa7591382 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2222,7 +2222,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) {