diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 0ea25d084c..9e00790dc6 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -100,6 +100,14 @@ The receipt digest uses the same framing over `game-session-canonical-launch-pre This local consumer and persistence remain an unwired candidate until their focused producer/consumer proof is complete; implementation and execution limits belong to the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md). Preparation survivor evidence has no invented TTL or automatic release; cleanup requires its owning retention proof. +### Fresh STARTING owner association and protected World read + +For a fresh runtime, Game Session resolves the canonical tenant through Game Design's authenticated `ResolveRuntimeTenantIdentity` read, with a separate request identity and exact namespace, tenant UUID and `NEW_GAME_ROW` source. Game Session allocates its own private tenant key and preserves the complete immutable source association; that key is neither public tenant identity nor permission. The association's source row, former key and provenance must match the committed authored-world intake used by the selected catalog and preparation. + +The explicit STARTING owner composes that association, the committed preparation and Game Design's complete descriptor/release-attestation pair outside an ambient transaction. Its short writable READ COMMITTED transaction serializes the namespace/request, creates or exactly reuses the Game Session-owned instance, and captures the immutable launch association atomically. A new instance is `STARTING` and semantically unpinned; no World lifecycle, pointer opening or gameplay admission is created. Independent committed association and instance readback must match before success. Changed owner, request, source or complete pair conflicts without another row; a historical retry cannot assert that World is still preparing or that admission is open. The acting Account UUID remains a management-owner binding, not proof of current Account authorization. + +`GetCanonicalGameInstanceLaunchAssociation` is a protected, read-only World composition surface. Require the exact `spiffe://firemud/ns//sa/world-management-service` mTLS caller and equality with the request namespace. The separate read UUID and exact tenant/world/instance/control-plane-request/descriptor selectors, descriptor request/result digests and release-attestation evidence digest must all match the persisted association. Return their exact echoes, complete descriptor and separate attestation, playable namespace/scope, public-production flag and current Game Session row status/version. Missing, contradictory, cross-namespace or changed evidence denies without allocation or enrollment. World independently validates these results; caller-supplied expected digests are selectors, not authority. Current Game Session status/version is not World lifecycle evidence. Optional read wiring defaults off, and the STARTING producer remains explicitly constructed rather than automatically activated. Required execution and complete World/Account/coordinator composition remain tracked in [Player Access](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). + ### Retained tenant identity snapshot and local association Game Session owns the evidence behind `gameSessionEvidenceDigest` in [Game Design's audited association](../game-design-service/api-contracts.md#audited-retained-game-session-tenant-association). It captures an exact, declared identity projection of its retained rows, not a complete runtime backup or proof of historical lifecycle, effects or admission. The closed version-2 snapshot contains `schemaVersion=2`, the exact `targetNamespace`, canonical positive BIGINT decimal-string `legacyGameSessionTenantId`, and all six arrays below. Each array includes every row for that tenant, in ascending numeric primary-key order; the shared namespace uses its tenant primary key. Row objects contain exactly their listed SQL field names. SQL integer values are canonical decimal strings, UUIDs are canonical lowercase strings, booleans are JSON booleans, text is exact valid Unicode, and absent nullable fields are explicit JSON null. Each instance binds both its nullable retained numeric `owner_account_id` and nullable canonical `owner_account_uuid`; at least one must be present. Capturing those exact slots does not prove an association between them, authorize a guessed mapping, or make a retained numeric owner a canonical Account identity. No timestamp, display label, actor/reason or participant-result payload is reconstructed or asserted by this projection. diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index b4cf845cf4..98543490fd 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -8,6 +8,8 @@ The service runtime model assumes replaceable workers, not authoritative in-proc ## Implementation Status +- The nonactivating fresh launch-owner cut adds authenticated Game Design `NEW_GAME_ROW` tenant association (V15), an explicitly constructed STARTING producer, and atomic instance/complete descriptor-release-attestation capture (V16). The protected `GetCanonicalGameInstanceLaunchAssociation` read requires the exact same-namespace World workload and echoes its immutable selectors; returned status/version describe the current Game Session row, not World lifecycle or admission readiness. Complete-binding preparation independently rechecks the committed local snapshot before its protected Game Design read. Optional receiving configuration defaults off. The producer is not wired into the run-owned coordinator; World prepare/commit/lifecycle composition and deployed proof remain incomplete. The [local API boundary](./api-contracts.md#fresh-starting-owner-association-and-protected-world-read) and [Player Access](../../../project-management/implementation-tracking/player-access-and-session.md) separate this source implementation from activation and execution evidence. + - The unregistered initial canonical realm-catalog candidate stores exact committed authored-world intake evidence and owner-allocated realm/namespace results under the [Game Session catalog contract](./api-contracts.md#initial-canonical-public-production-realm-catalog). V12.1 widens the existing SHARED allocation family without mapping or rewriting retained numeric rows; ISOLATED allocations remain realm-local. This is not a complete catalog lifecycle, creator authorization, instance/pointer producer or admission path. Execution evidence and remaining composition/activation gates belong to [Player Access](../../../project-management/implementation-tracking/player-access-and-session.md). The sections below define the target-state runtime contract. Current implementation and proof status is: 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 2331947679..9759c1e824 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 +The fresh Game Session launch-owner receiving candidate adds a separately authenticated Game Design tenant association, a Game Session-owned private key, and complete v2 launch association capture/read. It retains V15/V16 source/transaction guards, same-namespace World-only transport, genuine SHARED/public-production catalog evidence and exact immutable selector echoes. The explicit, unregistered STARTING producer allocates or exactly retries a real Game Session instance and captures its full descriptor/attestation association in the same owner transaction, with independent committed readback. The source-qualified complete binding read validates the committed preparation before network I/O; no flat numeric launch fallback or runtime activation is supplied. Consolidated jOOQ, main/unit/integration-source compilation, boot JAR, formatting and documentation checks pass; 36 focused Game Session and five shared policy cases pass without failures or skips. PostgreSQL producer, retry, changed-pair rollback and migration definitions compile but have not executed locally. Physical PostgreSQL proof, runtime coordinator wiring, authenticated World preparation/through-commit/lifecycle readback and fresh-image playable proof remain open. Existing numeric capability fields are not canonical tenant association evidence, and Game Session status is not World lifecycle authority. + The current #3029 local candidate adds unwired Account V79 publication participation and the shared exact selected-Draft codec. The existing Game Design adapter preserves its original eight-input selection bytes/digest. Publication reservations and immutable publication/revocation orders share the existing source locks and WAITING journal; source changes cannot finish while any affected publication lacks its own authenticated terminal results. Earlier Draft outcomes cannot satisfy this predicate. Twelve new PostgreSQL definitions cover replay/restart, source races, rollback, direct-SQL guards and retained V78 history, but have not executed locally without Docker. The current authority producer, Game Design no-publication seal, both-owner terminal verification and settlement remain required; nothing here enables publication or creator authority. See [Account's publication authorization owner contract](../../architecture/microservices/account-service/api-contracts.md#account-owned-publication-authorization-fence). Exact source `d87f9cc2d30e775ea1e0c31f98ddfc64ec28c5ec` [CI37458361299](https://github.com/benhook1013/FireMUD/actions/runs/37458361299) executes nineteen Draft authorization-fence PostgreSQL cases with eighteen passes, one failure and zero skips. Stable unresolved pagination fails because its plain-SQL timestamp cursor is bound as varchar; the correction explicitly casts the original timestamp/UUID cursor without changing ordering or original operation identity. A separate V78 creator-party retained-history fixture targets nonexistent reserved V77; it now migrates genuine V74 history through V78 and compares the complete Account and membership rows, with no party enrollment. Corrected Account check and boot JAR pass in the combined affected gate; all 488 Account integration definitions skip locally without Docker. Corrected PostgreSQL pagination and migration execution remain required. Existing Account proofs do not establish current creator-party/terms authorization or the four live Gameplay owner handoffs. diff --git a/protos/game-session/v1/game_session_service.proto b/protos/game-session/v1/game_session_service.proto index adf1810f08..e1f159729a 100644 --- a/protos/game-session/v1/game_session_service.proto +++ b/protos/game-session/v1/game_session_service.proto @@ -41,6 +41,10 @@ service GameSessionControlPlaneService { // Read exact durable owner proof for a World-owned initial-admission hold. rpc GetInitialAdmissionBindProof(GetInitialAdmissionBindProofRequest) returns (GetInitialAdmissionBindProofResponse); + // Read the exact Game Session-owned STARTING launch association for World composition. + rpc GetCanonicalGameInstanceLaunchAssociation( + GetCanonicalGameInstanceLaunchAssociationRequest) + returns (GetCanonicalGameInstanceLaunchAssociationResponse); rpc ValidateBuiltInCommandAlias(ValidateBuiltInCommandAliasRequest) returns (ValidateBuiltInCommandAliasResponse); rpc ListAdmissionPointers(ListAdmissionPointersRequest) @@ -500,6 +504,42 @@ message GetInitialAdmissionBindProofResponse { shared.v1.ErrorDetail error = 20; } +// A transport retry has a separate read identity and cannot create a new launch operation. +message GetCanonicalGameInstanceLaunchAssociationRequest { + string read_request_id = 1; + string target_namespace = 2; + string canonical_tenant_id = 3; + string world_slug = 4; + string game_instance_uuid = 5; + string control_plane_request_id = 6; + string launch_descriptor_id = 7; + string expected_descriptor_request_digest = 8; + string expected_descriptor_result_digest = 9; + string expected_release_attestation_evidence_digest = 10; +} + +message GetCanonicalGameInstanceLaunchAssociationResponse { + string read_request_id = 1; + string target_namespace = 2; + string canonical_tenant_id = 3; + string world_slug = 4; + string game_instance_uuid = 5; + string control_plane_request_id = 6; + string launch_descriptor_id = 7; + string descriptor_request_digest = 8; + string descriptor_result_digest = 9; + string release_attestation_evidence_digest = 10; + string playable_state_namespace_id = 11; + string playable_state_scope = 12; + // Current Game Session row projection only; World lifecycle authority remains separate. + string current_game_instance_status = 13; + int64 current_row_version = 14; + gamedesign.v1.LaunchDescriptor launch_descriptor = 15; + gamedesign.v1.AuthoredWorldReleaseAttestationEvidence release_attestation = 16; + shared.v1.ErrorDetail error = 17; + bool public_production = 18; +} + message GetGameplayCommandStatusRequest { string command_id = 1; string tenant_id = 2; diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyEvidence.java new file mode 100644 index 0000000000..089563b574 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyEvidence.java @@ -0,0 +1,232 @@ +package net.firedevops.firemud.common.publication; + +import java.io.IOException; +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 net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.node.ObjectNode; + +/** Immutable typed owner evidence shared by Game Design producers and runtime receivers. */ +public record PublishedRealmEntryPolicyEvidence( + UUID policyId, + UUID canonicalTenantId, + String tenantIdentityProvenanceKind, + long sourceGameRowId, + String sourceGameTenantKey, + long versionId, + int versionNumber, + long sourceRevisionId, + String releaseBundleIdentity, + String publishWorkflowId, + String manifestHash, + RealmEntryPolicy policy, + String policyDigest) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final int MAX_TENANT_KEY_CODE_POINTS = 36; + private static final int MAX_TENANT_KEY_UTF16_LENGTH = 72; + + public PublishedRealmEntryPolicyEvidence { + requireNonNil(policyId, "policyId"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + if (!"NEW_GAME_ROW".equals(tenantIdentityProvenanceKind) + && !"RETAINED_GAME_V29".equals(tenantIdentityProvenanceKind)) { + throw new IllegalArgumentException("Tenant identity provenance kind is not recognized"); + } + if (sourceGameRowId <= 0 + || sourceGameTenantKey == null + || sourceGameTenantKey.isBlank() + || sourceGameTenantKey.length() > MAX_TENANT_KEY_UTF16_LENGTH + || sourceGameTenantKey.codePointCount(0, sourceGameTenantKey.length()) + > MAX_TENANT_KEY_CODE_POINTS + || !StandardCharsets.UTF_8.newEncoder().canEncode(sourceGameTenantKey) + || versionId <= 0 + || versionNumber <= 0 + || sourceRevisionId <= 0 + || releaseBundleIdentity == null + || !releaseBundleIdentity.matches("sha256:[0-9a-f]{64}") + || publishWorkflowId == null + || publishWorkflowId.isBlank() + || manifestHash == null + || manifestHash.isBlank()) { + throw new IllegalArgumentException("Published realm-entry policy evidence is incomplete"); + } + Objects.requireNonNull(policy, "policy"); + if (policyDigest == null || !policyDigest.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Published realm-entry policy digest is malformed"); + } + } + + public static PublishedRealmEntryPolicyEvidence create( + UUID policyId, + UUID canonicalTenantId, + String tenantIdentityProvenanceKind, + long sourceGameRowId, + String sourceGameTenantKey, + long versionId, + int versionNumber, + long sourceRevisionId, + String releaseBundleIdentity, + String publishWorkflowId, + String manifestHash, + RealmEntryPolicy policy, + ObjectMapper objectMapper) { + requireCanonicalPolicy(policy, objectMapper); + String digest = + calculateDigest( + policyId, + canonicalTenantId, + tenantIdentityProvenanceKind, + sourceGameRowId, + sourceGameTenantKey, + versionId, + versionNumber, + sourceRevisionId, + releaseBundleIdentity, + publishWorkflowId, + manifestHash, + policy, + objectMapper); + return new PublishedRealmEntryPolicyEvidence( + policyId, + canonicalTenantId, + tenantIdentityProvenanceKind, + sourceGameRowId, + sourceGameTenantKey, + versionId, + versionNumber, + sourceRevisionId, + releaseBundleIdentity, + publishWorkflowId, + manifestHash, + policy, + digest); + } + + /** Verifies the evidence digest against every immutable owner and policy field. */ + public boolean hasValidDigest(ObjectMapper objectMapper) { + try { + requireCanonicalPolicy(policy, objectMapper); + return policyDigest.equals( + calculateDigest( + policyId, + canonicalTenantId, + tenantIdentityProvenanceKind, + sourceGameRowId, + sourceGameTenantKey, + versionId, + versionNumber, + sourceRevisionId, + releaseBundleIdentity, + publishWorkflowId, + manifestHash, + policy, + objectMapper)); + } catch (IllegalArgumentException exception) { + return false; + } + } + + /** Requires exact digest agreement and returns this immutable evidence. */ + public PublishedRealmEntryPolicyEvidence requireValidDigest(ObjectMapper objectMapper) { + if (!hasValidDigest(objectMapper)) { + throw new IllegalArgumentException( + "Published realm-entry policy digest does not match evidence"); + } + return this; + } + + /** Deterministic identity for a full-version release bundle, excluding local database IDs. */ + public static String releaseBundleIdentity( + UUID canonicalTenantId, + long versionId, + String publishWorkflowId, + String manifestHash, + ObjectMapper objectMapper) { + requireNonNil(canonicalTenantId, "canonicalTenantId"); + if (versionId <= 0 || publishWorkflowId == null || publishWorkflowId.isBlank()) { + throw new IllegalArgumentException("Published release bundle identity is incomplete"); + } + ObjectNode identity = objectMapper.createObjectNode(); + identity.put("canonicalTenantId", canonicalTenantId.toString()); + identity.put("versionId", versionId); + identity.put("publishWorkflowId", publishWorkflowId); + identity.put("manifestHash", Objects.requireNonNull(manifestHash, "manifestHash")); + return sha256(canonicalize(identity.toString())); + } + + private static String calculateDigest( + UUID policyId, + UUID canonicalTenantId, + String tenantIdentityProvenanceKind, + long sourceGameRowId, + String sourceGameTenantKey, + long versionId, + int versionNumber, + long sourceRevisionId, + String releaseBundleIdentity, + String publishWorkflowId, + String manifestHash, + RealmEntryPolicy policy, + ObjectMapper objectMapper) { + Objects.requireNonNull(objectMapper, "objectMapper"); + ObjectNode preimage = objectMapper.createObjectNode(); + preimage.put("schemaVersion", RealmEntryPolicy.SCHEMA_VERSION); + preimage.put("policyId", requireNonNil(policyId, "policyId").toString()); + preimage.put( + "canonicalTenantId", requireNonNil(canonicalTenantId, "canonicalTenantId").toString()); + preimage.put("tenantIdentityProvenanceKind", tenantIdentityProvenanceKind); + preimage.put("sourceGameRowId", sourceGameRowId); + preimage.put("sourceGameTenantKey", sourceGameTenantKey); + preimage.put("versionId", versionId); + preimage.put("versionNumber", versionNumber); + preimage.put("sourceRevisionId", sourceRevisionId); + preimage.put("releaseBundleIdentity", releaseBundleIdentity); + preimage.put("publishWorkflowId", publishWorkflowId); + preimage.put("manifestHash", manifestHash); + try { + preimage.set("policy", objectMapper.readTree(policy.canonicalJson())); + } catch (RuntimeException exception) { + throw new IllegalArgumentException("Published realm-entry policy JSON is invalid", exception); + } + return sha256(canonicalize(preimage.toString())); + } + + private static byte[] canonicalize(String json) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(json); + } catch (IOException exception) { + throw new IllegalStateException("RFC 8785 canonicalization failed", exception); + } + } + + private static void requireCanonicalPolicy(RealmEntryPolicy policy, ObjectMapper objectMapper) { + Objects.requireNonNull(policy, "policy"); + RealmEntryPolicy parsed = RealmEntryPolicy.parseCanonical(policy.canonicalJson(), objectMapper); + if (!parsed.equals(policy)) { + throw new IllegalArgumentException( + "Published realm-entry policy fields contradict canonical JSON"); + } + } + + private static String sha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static UUID requireNonNil(UUID value, String label) { + Objects.requireNonNull(value, label); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must not be nil"); + } + return value; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicySetEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicySetEvidence.java new file mode 100644 index 0000000000..ea0903e2fe --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicySetEvidence.java @@ -0,0 +1,218 @@ +package net.firedevops.firemud.common.publication; + +import java.io.IOException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.node.ArrayNode; +import tools.jackson.databind.node.ObjectNode; + +/** Complete, bounded and owner-bound published realm policy set for one tenant version. */ +public record PublishedRealmEntryPolicySetEvidence( + UUID canonicalTenantId, + long versionId, + int versionNumber, + String releaseBundleIdentity, + String publishWorkflowId, + String manifestHash, + List policies, + String policySetDigest) { + public static final int MAX_POLICIES = 128; + + public PublishedRealmEntryPolicySetEvidence { + if (canonicalTenantId == null || new UUID(0L, 0L).equals(canonicalTenantId)) { + throw new IllegalArgumentException("canonicalTenantId must be a non-nil UUID"); + } + if (versionId <= 0 || versionNumber <= 0) { + throw new IllegalArgumentException("Published policy set version must be positive"); + } + if (releaseBundleIdentity == null + || !releaseBundleIdentity.matches("sha256:[0-9a-f]{64}") + || publishWorkflowId == null + || publishWorkflowId.isBlank() + || manifestHash == null + || manifestHash.isBlank()) { + throw new IllegalArgumentException("Published policy set owner identity is incomplete"); + } + policies = List.copyOf(Objects.requireNonNull(policies, "policies")); + if (policies.isEmpty() || policies.size() > MAX_POLICIES) { + throw new IllegalArgumentException("Published realm-entry policy set is empty or oversized"); + } + String sourceProvenance = null; + Long sourceGameRowId = null; + String sourceGameTenantKey = null; + String previousWorld = null; + String previousRealm = null; + int visiblePublicProductionCount = 0; + Set realmSlugs = new HashSet<>(); + for (PublishedRealmEntryPolicyEvidence policy : policies) { + if (policy == null + || !canonicalTenantId.equals(policy.canonicalTenantId()) + || versionId != policy.versionId() + || versionNumber != policy.versionNumber() + || !releaseBundleIdentity.equals(policy.releaseBundleIdentity()) + || !publishWorkflowId.equals(policy.publishWorkflowId()) + || !manifestHash.equals(policy.manifestHash())) { + throw new IllegalArgumentException( + "Published policy set contains contradictory owner evidence"); + } + if (sourceProvenance == null) { + sourceProvenance = policy.tenantIdentityProvenanceKind(); + sourceGameRowId = policy.sourceGameRowId(); + sourceGameTenantKey = policy.sourceGameTenantKey(); + } else if (!sourceProvenance.equals(policy.tenantIdentityProvenanceKind()) + || !sourceGameRowId.equals(policy.sourceGameRowId()) + || !sourceGameTenantKey.equals(policy.sourceGameTenantKey())) { + throw new IllegalArgumentException( + "Published policy set contains contradictory tenant provenance"); + } + String world = policy.policy().worldSlug(); + String realm = policy.policy().realmSlug(); + if (!realmSlugs.add(realm)) { + throw new IllegalArgumentException( + "Published policy set contains a realm slug more than once within its tenant"); + } + if (previousWorld != null + && (previousWorld.compareTo(world) > 0 + || (previousWorld.equals(world) && previousRealm.compareTo(realm) >= 0))) { + throw new IllegalArgumentException("Published policy set selector order is not canonical"); + } + previousWorld = world; + previousRealm = realm; + if (policy.policy().visible() && policy.policy().publicProduction()) { + visiblePublicProductionCount++; + } + } + if (visiblePublicProductionCount != 1) { + throw new IllegalArgumentException( + "Published policy set must contain exactly one visible publicProduction realm"); + } + if (policySetDigest == null || !policySetDigest.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Published realm-entry policy set digest is malformed"); + } + } + + public static PublishedRealmEntryPolicySetEvidence create( + UUID canonicalTenantId, + long versionId, + int versionNumber, + String releaseBundleIdentity, + String publishWorkflowId, + String manifestHash, + List policies, + ObjectMapper objectMapper) { + Objects.requireNonNull(policies, "policies"); + if (policies.isEmpty() || policies.size() > MAX_POLICIES) { + throw new IllegalArgumentException("Published realm-entry policy set is empty or oversized"); + } + List ordered = + policies.stream() + .sorted( + (left, right) -> { + int worldOrder = left.policy().worldSlug().compareTo(right.policy().worldSlug()); + return worldOrder != 0 + ? worldOrder + : left.policy().realmSlug().compareTo(right.policy().realmSlug()); + }) + .toList(); + String digest = + calculateDigest( + canonicalTenantId, + versionId, + versionNumber, + releaseBundleIdentity, + publishWorkflowId, + manifestHash, + ordered, + objectMapper); + return new PublishedRealmEntryPolicySetEvidence( + canonicalTenantId, + versionId, + versionNumber, + releaseBundleIdentity, + publishWorkflowId, + manifestHash, + ordered, + digest); + } + + /** Verifies the complete-set digest and every child policy digest. */ + public boolean hasValidDigest(ObjectMapper objectMapper) { + return policies.stream().allMatch(policy -> policy.hasValidDigest(objectMapper)) + && policySetDigest.equals( + calculateDigest( + canonicalTenantId, + versionId, + versionNumber, + releaseBundleIdentity, + publishWorkflowId, + manifestHash, + policies, + objectMapper)); + } + + public PublishedRealmEntryPolicySetEvidence requireValidDigest(ObjectMapper objectMapper) { + if (!hasValidDigest(objectMapper)) { + throw new IllegalArgumentException( + "Published realm-entry policy set digest does not match evidence"); + } + return this; + } + + private static String calculateDigest( + UUID canonicalTenantId, + long versionId, + int versionNumber, + String releaseBundleIdentity, + String publishWorkflowId, + String manifestHash, + List policies, + ObjectMapper objectMapper) { + Objects.requireNonNull(objectMapper, "objectMapper"); + ObjectNode preimage = objectMapper.createObjectNode(); + preimage.put("schemaVersion", RealmEntryPolicy.SCHEMA_VERSION); + preimage.put("canonicalTenantId", canonicalTenantId.toString()); + preimage.put( + "tenantIdentityProvenanceKind", policies.getFirst().tenantIdentityProvenanceKind()); + preimage.put("sourceGameRowId", policies.getFirst().sourceGameRowId()); + preimage.put("sourceGameTenantKey", policies.getFirst().sourceGameTenantKey()); + preimage.put("versionId", versionId); + preimage.put("versionNumber", versionNumber); + preimage.put("releaseBundleIdentity", releaseBundleIdentity); + preimage.put("publishWorkflowId", publishWorkflowId); + preimage.put("manifestHash", manifestHash); + preimage.put("policyCount", policies.size()); + ArrayNode selectors = objectMapper.createArrayNode(); + for (PublishedRealmEntryPolicyEvidence policy : policies) { + ObjectNode selector = objectMapper.createObjectNode(); + selector.put("policyId", policy.policyId().toString()); + selector.put("sourceRevisionId", policy.sourceRevisionId()); + selector.put("worldSlug", policy.policy().worldSlug()); + selector.put("realmSlug", policy.policy().realmSlug()); + selector.put("policyDigest", policy.policyDigest()); + selectors.add(selector); + } + preimage.set("policies", selectors); + try { + return sha256(Rfc8785CanonicalJson.canonicalizeUtf8(preimage.toString())); + } catch (IOException exception) { + throw new IllegalStateException("RFC 8785 canonicalization failed", exception); + } + } + + private static String sha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/RealmEntryPolicy.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/RealmEntryPolicy.java new file mode 100644 index 0000000000..75ccc90dc2 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/RealmEntryPolicy.java @@ -0,0 +1,176 @@ +package net.firedevops.firemud.common.publication; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.Set; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; + +/** Closed v1 authored realm-entry policy shared by the publication owner and runtime receivers. */ +public record RealmEntryPolicy( + int schemaVersion, + String worldSlug, + String worldDisplayName, + String realmSlug, + String realmDisplayName, + boolean visible, + boolean publicProduction, + StateScope stateScope, + EntryPolicy entryPolicy, + String canonicalJson) { + public static final String REVISION_KIND = "REALM_ENTRY_POLICY"; + public static final int SCHEMA_VERSION = 1; + public static final int MAX_JSON_BYTES = 4096; + public static final int MAX_SLUG_LENGTH = 64; + public static final int MAX_DISPLAY_NAME_CODE_POINTS = 128; + + private static final Set FIELDS = + Set.of( + "schemaVersion", + "worldSlug", + "worldDisplayName", + "realmSlug", + "realmDisplayName", + "visible", + "publicProduction", + "stateScope", + "entryPolicy"); + private static final Pattern SLUG_PATTERN = Pattern.compile("[a-z0-9]+(?:-[a-z0-9]+)*"); + + public enum StateScope { + SHARED, + ISOLATED + } + + public enum EntryPolicy { + PRESEEDED_ONLY + } + + /** Parses valid v1 JSON and returns the RFC 8785 canonical policy representation. */ + public static RealmEntryPolicy parse(String json, ObjectMapper objectMapper) { + if (json == null || json.isBlank()) { + throw invalid("data is required"); + } + if (!StandardCharsets.UTF_8.newEncoder().canEncode(json)) { + throw invalid("data must be valid UTF-8"); + } + ByteBuffer inputBytes = StandardCharsets.UTF_8.encode(json); + if (inputBytes.remaining() > MAX_JSON_BYTES) { + throw invalid("data exceeds the v1 byte limit"); + } + + JsonNode root; + String canonicalJson; + try { + canonicalJson = + new String(Rfc8785CanonicalJson.canonicalizeUtf8(json), StandardCharsets.UTF_8); + root = objectMapper.readTree(canonicalJson); + } catch (IOException | RuntimeException exception) { + throw invalid("data must be valid unambiguous JSON"); + } + if (root == null || !root.isObject()) { + throw invalid("must be a JSON object"); + } + for (String field : FIELDS) { + if (!root.has(field)) { + throw invalid(field + " is required"); + } + } + if (root.size() != FIELDS.size()) { + throw invalid("must contain exactly the v1 fields"); + } + + JsonNode schemaVersion = root.get("schemaVersion"); + if (schemaVersion == null + || !schemaVersion.isIntegralNumber() + || !schemaVersion.canConvertToInt() + || schemaVersion.intValue() != SCHEMA_VERSION) { + throw invalid("schemaVersion must be the integer 1"); + } + String worldSlug = requireSlug(root, "worldSlug"); + String worldDisplayName = requireDisplayName(root, "worldDisplayName"); + String realmSlug = requireSlug(root, "realmSlug"); + String realmDisplayName = requireDisplayName(root, "realmDisplayName"); + boolean visible = requireBoolean(root, "visible"); + boolean publicProduction = requireBoolean(root, "publicProduction"); + StateScope stateScope = requireEnum(root, "stateScope", StateScope.class); + EntryPolicy entryPolicy = requireEnum(root, "entryPolicy", EntryPolicy.class); + + return new RealmEntryPolicy( + SCHEMA_VERSION, + worldSlug, + worldDisplayName, + realmSlug, + realmDisplayName, + visible, + publicProduction, + stateScope, + entryPolicy, + canonicalJson); + } + + /** Parses policy evidence that is required to already use its exact canonical JSON spelling. */ + public static RealmEntryPolicy parseCanonical(String json, ObjectMapper objectMapper) { + RealmEntryPolicy policy = parse(json, objectMapper); + if (!json.equals(policy.canonicalJson())) { + throw invalid("published policy JSON is not canonical"); + } + return policy; + } + + public static boolean isCanonicalSlug(String value) { + return value != null + && value.length() <= MAX_SLUG_LENGTH + && SLUG_PATTERN.matcher(value).matches(); + } + + private static String requireSlug(JsonNode root, String field) { + String value = requireText(root, field); + if (!isCanonicalSlug(value)) { + throw invalid(field + " must be a canonical lower-case slug"); + } + return value; + } + + private static String requireDisplayName(JsonNode root, String field) { + String value = requireText(root, field); + if (!value.equals(value.strip()) + || value.codePointCount(0, value.length()) > MAX_DISPLAY_NAME_CODE_POINTS + || value.codePoints().anyMatch(Character::isISOControl)) { + throw invalid(field + " is outside the v1 text bounds"); + } + return value; + } + + private static String requireText(JsonNode root, String field) { + JsonNode value = root.get(field); + if (value == null || !value.isTextual() || value.asText().isBlank()) { + throw invalid(field + " must be a nonblank string"); + } + return value.asText(); + } + + private static boolean requireBoolean(JsonNode root, String field) { + JsonNode value = root.get(field); + if (value == null || !value.isBoolean()) { + throw invalid(field + " must be an explicit boolean"); + } + return value.booleanValue(); + } + + private static > T requireEnum(JsonNode root, String field, Class type) { + String value = requireText(root, field); + try { + return Enum.valueOf(type, value); + } catch (IllegalArgumentException exception) { + throw invalid("unsupported " + field); + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException("INVALID_ARGUMENT: realmEntryPolicy " + message); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyEvidenceTest.java new file mode 100644 index 0000000000..a34d39ba4d --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyEvidenceTest.java @@ -0,0 +1,207 @@ +package net.firedevops.firemud.common.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; + +import java.util.List; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.ObjectMapper; + +class PublishedRealmEntryPolicyEvidenceTest { + private static final UUID TENANT_ID = UUID.fromString("e84e0676-77f2-4bac-8be5-e89d4f8b8f01"); + private static final String WORKFLOW = "publish:tenant:publish-request:req"; + private static final String MANIFEST = "manifest-sha256"; + private static final ObjectMapper MAPPER = new ObjectMapper(); + + @Test + void parserAcceptsOnlyClosedV1AndCanonicalReadbackRequiresExactJson() { + String authored = + "{ \"schemaVersion\":1, \"worldSlug\":\"earth\", " + + "\"worldDisplayName\":\"Earth\", \"realmSlug\":\"main\", " + + "\"realmDisplayName\":\"Main\", \"visible\":true, " + + "\"publicProduction\":true, \"stateScope\":\"SHARED\", " + + "\"entryPolicy\":\"PRESEEDED_ONLY\" }"; + + RealmEntryPolicy policy = RealmEntryPolicy.parse(authored, MAPPER); + + assertThat(policy.stateScope()).isEqualTo(RealmEntryPolicy.StateScope.SHARED); + assertThat(policy.entryPolicy()).isEqualTo(RealmEntryPolicy.EntryPolicy.PRESEEDED_ONLY); + assertThat(policy.canonicalJson()).doesNotContain(": "); + assertThat(RealmEntryPolicy.isCanonicalSlug("demo--world")).isFalse(); + assertThatIllegalArgumentException() + .isThrownBy(() -> RealmEntryPolicy.parseCanonical(authored, MAPPER)); + assertThat(RealmEntryPolicy.parseCanonical(policy.canonicalJson(), MAPPER)).isEqualTo(policy); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + RealmEntryPolicy.parse( + policy.canonicalJson().replace("\"visible\":true", "\"visible\":1"), MAPPER)); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + RealmEntryPolicy.parse( + policy + .canonicalJson() + .replace("\"worldSlug\":\"earth\"", "\"worldSlug\":\"demo--world\""), + MAPPER)); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + RealmEntryPolicy.parse( + policy.canonicalJson().replace("\"entryPolicy\":\"PRESEEDED_ONLY\"", ""), + MAPPER)); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + RealmEntryPolicy.parse( + policy.canonicalJson().substring(0, policy.canonicalJson().length() - 1) + + ",\"descriptor\":{}}", + MAPPER)); + } + + @Test + void policyEvidenceDigestBindsTenantSourceVersionBundleAndCanonicalPolicy() { + PublishedRealmEntryPolicyEvidence evidence = policyEvidence("main", true, true); + + assertThat(evidence.hasValidDigest(MAPPER)).isTrue(); + assertThat(evidence.requireValidDigest(MAPPER)).isSameAs(evidence); + assertThat(evidence.policyDigest()).startsWith("sha256:").hasSize(71); + assertThat( + PublishedRealmEntryPolicyEvidence.releaseBundleIdentity( + TENANT_ID, 7L, WORKFLOW, MANIFEST, MAPPER)) + .isEqualTo(evidence.releaseBundleIdentity()); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + new PublishedRealmEntryPolicyEvidence( + evidence.policyId(), + evidence.canonicalTenantId(), + evidence.tenantIdentityProvenanceKind(), + evidence.sourceGameRowId(), + evidence.sourceGameTenantKey(), + evidence.versionId() + 1, + evidence.versionNumber(), + evidence.sourceRevisionId(), + evidence.releaseBundleIdentity(), + evidence.publishWorkflowId(), + evidence.manifestHash(), + evidence.policy(), + evidence.policyDigest()) + .requireValidDigest(MAPPER)); + } + + @Test + void completeSetSortsRowsAndBindsCountAndEveryPolicyDigest() { + PublishedRealmEntryPolicyEvidence main = policyEvidence("main", true, true); + PublishedRealmEntryPolicyEvidence side = policyEvidence("side", false, false); + + PublishedRealmEntryPolicySetEvidence set = + PublishedRealmEntryPolicySetEvidence.create( + TENANT_ID, + 7L, + 3, + main.releaseBundleIdentity(), + WORKFLOW, + MANIFEST, + List.of(side, main), + MAPPER); + + assertThat(set.policies()).containsExactly(main, side); + assertThat(set.hasValidDigest(MAPPER)).isTrue(); + assertThat(set.requireValidDigest(MAPPER)).isSameAs(set); + assertThat(set.policySetDigest()).startsWith("sha256:").hasSize(71); + assertThat( + PublishedRealmEntryPolicySetEvidence.create( + TENANT_ID, + 7L, + 3, + main.releaseBundleIdentity(), + WORKFLOW, + MANIFEST, + List.of(main, side), + MAPPER) + .policySetDigest()) + .isEqualTo(set.policySetDigest()); + } + + @Test + void completeSetRejectsMissingMultipleOrOversizedAddressableSets() { + PublishedRealmEntryPolicyEvidence main = policyEvidence("main", true, true); + PublishedRealmEntryPolicyEvidence side = policyEvidence("side", true, true); + String identity = main.releaseBundleIdentity(); + + assertThatIllegalArgumentException() + .isThrownBy(() -> createSet(identity, List.of(policyEvidence("hidden", false, false)))); + assertThatIllegalArgumentException().isThrownBy(() -> createSet(identity, List.of(main, side))); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + createSet( + identity, + java.util.Collections.nCopies( + PublishedRealmEntryPolicySetEvidence.MAX_POLICIES + 1, main))); + } + + @Test + void completeSetRejectsRealmSlugRepeatedAcrossDifferentWorlds() { + PublishedRealmEntryPolicyEvidence publicRealm = policyEvidence("main", "earth", true, true); + PublishedRealmEntryPolicyEvidence duplicateRealm = policyEvidence("main", "mars", false, false); + + assertThatIllegalArgumentException() + .isThrownBy( + () -> + createSet( + publicRealm.releaseBundleIdentity(), List.of(publicRealm, duplicateRealm))) + .withMessageContaining("realm slug more than once"); + } + + private static PublishedRealmEntryPolicySetEvidence createSet( + String releaseBundleIdentity, List policies) { + return PublishedRealmEntryPolicySetEvidence.create( + TENANT_ID, 7L, 3, releaseBundleIdentity, WORKFLOW, MANIFEST, policies, MAPPER); + } + + private static PublishedRealmEntryPolicyEvidence policyEvidence( + String realmSlug, boolean visible, boolean publicProduction) { + return policyEvidence(realmSlug, "earth", visible, publicProduction); + } + + private static PublishedRealmEntryPolicyEvidence policyEvidence( + String realmSlug, String worldSlug, boolean visible, boolean publicProduction) { + String sourceJson = + "{\"schemaVersion\":1,\"worldSlug\":\"" + + worldSlug + + "\",\"worldDisplayName\":\"" + + worldSlug + + "\"," + + "\"realmSlug\":\"" + + realmSlug + + "\",\"realmDisplayName\":\"" + + realmSlug + + "\",\"visible\":" + + visible + + ",\"publicProduction\":" + + publicProduction + + ",\"stateScope\":\"SHARED\",\"entryPolicy\":\"PRESEEDED_ONLY\"}"; + RealmEntryPolicy policy = RealmEntryPolicy.parse(sourceJson, MAPPER); + String releaseIdentity = + PublishedRealmEntryPolicyEvidence.releaseBundleIdentity( + TENANT_ID, 7L, WORKFLOW, MANIFEST, MAPPER); + return PublishedRealmEntryPolicyEvidence.create( + UUID.nameUUIDFromBytes( + (worldSlug + ":" + realmSlug).getBytes(java.nio.charset.StandardCharsets.UTF_8)), + TENANT_ID, + "NEW_GAME_ROW", + 12L, + "tenant-key", + 7L, + 3, + realmSlug.equals("main") ? 42L : 43L, + releaseIdentity, + WORKFLOW, + MANIFEST, + policy, + MAPPER); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/CanonicalGameInstanceLaunchAssociationReadConfiguration.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/CanonicalGameInstanceLaunchAssociationReadConfiguration.java new file mode 100644 index 0000000000..0248369bb5 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/CanonicalGameInstanceLaunchAssociationReadConfiguration.java @@ -0,0 +1,31 @@ +package net.firedevops.firemud.gamesession.config; + +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import net.firedevops.firemud.gamesession.service.CanonicalGameInstanceLaunchAssociationReadService; +import org.jooq.DSLContext; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** Explicit opt-in wiring for the World-only canonical Game Session owner read boundary. */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnProperty( + prefix = "firemud.canonical-game-instance-launch-association-owner-read", + name = "enabled", + havingValue = "true") +public class CanonicalGameInstanceLaunchAssociationReadConfiguration { + @Bean + CanonicalGameInstanceLaunchAssociationRepository canonicalGameInstanceLaunchAssociationRepository( + DSLContext dsl, @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + return new CanonicalGameInstanceLaunchAssociationRepository(dsl, workloadNamespace); + } + + @Bean + CanonicalGameInstanceLaunchAssociationReadService + canonicalGameInstanceLaunchAssociationReadService( + CanonicalGameInstanceLaunchAssociationRepository repository, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + return new CanonicalGameInstanceLaunchAssociationReadService(repository, workloadNamespace); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameInstanceLaunchAssociation.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameInstanceLaunchAssociation.java new file mode 100644 index 0000000000..d58cdedeba --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameInstanceLaunchAssociation.java @@ -0,0 +1,92 @@ +package net.firedevops.firemud.gamesession.dto; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; + +/** Durable fresh-tenant launch association plus a separate current Game Session row projection. */ +public record CanonicalGameInstanceLaunchAssociation( + String targetNamespace, + long gameSessionTenantId, + UUID tenantAssociationOperationId, + UUID canonicalTenantId, + UUID gameInstanceUuid, + String worldSlug, + UUID playableStateNamespaceId, + RealmEntryPolicy.StateScope playableStateScope, + boolean publicProduction, + String controlPlaneRequestId, + String launchDescriptorId, + long capturedStartingRowVersion, + CompleteLaunchBindingEvidence launchBindingEvidence, + CurrentGameInstanceStatus currentGameInstanceStatus, + long currentRowVersion) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public enum CurrentGameInstanceStatus { + STARTING, + RUNNING, + STOPPING, + STOPPED + } + + public CanonicalGameInstanceLaunchAssociation { + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requirePositive(gameSessionTenantId, "gameSessionTenantId"); + requireNonNil(tenantAssociationOperationId, "tenantAssociationOperationId"); + requireNonNil(gameInstanceUuid, "gameInstanceUuid"); + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + Objects.requireNonNull(playableStateScope, "playableStateScope"); + if (playableStateScope != RealmEntryPolicy.StateScope.SHARED) { + throw new IllegalArgumentException("Canonical launch association requires SHARED scope"); + } + if (!publicProduction) { + throw new IllegalArgumentException( + "Canonical launch association requires owner-confirmed public production"); + } + requireText(controlPlaneRequestId, "controlPlaneRequestId"); + requireText(launchDescriptorId, "launchDescriptorId"); + if (capturedStartingRowVersion < 0) { + throw new IllegalArgumentException("capturedStartingRowVersion must not be negative"); + } + Objects.requireNonNull(launchBindingEvidence, "launchBindingEvidence"); + Objects.requireNonNull(currentGameInstanceStatus, "currentGameInstanceStatus"); + if (currentRowVersion < capturedStartingRowVersion) { + throw new IllegalArgumentException( + "currentRowVersion must not precede the captured STARTING row version"); + } + + var descriptor = launchBindingEvidence.descriptor(); + descriptor.requireValid(); + launchBindingEvidence.releaseAttestation().requireValid(descriptor); + if (!targetNamespace.equals(descriptor.targetNamespace()) + || !canonicalTenantId.equals(descriptor.canonicalTenantId()) + || !worldSlug.equals(descriptor.worldSlug()) + || !controlPlaneRequestId.equals(descriptor.controlPlaneRequestId()) + || !launchDescriptorId.equals(descriptor.launchDescriptorId())) { + throw new IllegalArgumentException( + "Launch association does not match its complete authored launch binding"); + } + } + + 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"); + } + } + + private static void requirePositive(long value, String name) { + if (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"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java new file mode 100644 index 0000000000..ab408123fd --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java @@ -0,0 +1,617 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.tenant.RuntimeTenantIdentityEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; +import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus; +import net.firedevops.firemud.gamesession.service.FreshGameSessionTenantAssociation; +import org.jooq.DSLContext; +import org.jooq.JSONB; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.core.JacksonException; +import tools.jackson.databind.ObjectMapper; + +/** Explicit Game Session owner persistence for the exact launch-to-instance binding. */ +public final class CanonicalGameInstanceLaunchAssociationRepository { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final ObjectMapper JSON = new ObjectMapper(); + private static final String ASSOCIATION_TABLE = "game_session_canonical_instance_launch"; + + private final DSLContext dsl; + private final String workloadNamespace; + + public CanonicalGameInstanceLaunchAssociationRepository( + DSLContext dsl, String workloadNamespace) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Game Session workload namespace is invalid"); + } + this.workloadNamespace = workloadNamespace; + } + + /** + * Captures an existing STARTING owner row and its exact launch binding in the same writable READ + * COMMITTED transaction. This method does not allocate or create a runtime row. + */ + public CanonicalGameInstanceLaunchAssociation capture( + FreshGameSessionTenantAssociation tenantAssociation, + long gameInstanceId, + CompleteLaunchBindingEvidence launchBindingEvidence) { + requireWritableReadCommittedOwnerTransaction(); + Objects.requireNonNull(tenantAssociation, "tenantAssociation"); + requirePositive(gameInstanceId, "gameInstanceId"); + ValidatedBinding binding = validateBinding(launchBindingEvidence); + if (!workloadNamespace.equals(binding.descriptor().targetNamespace())) { + throw new IllegalArgumentException("Launch binding targets another Game Session namespace"); + } + + RuntimeTenantIdentityEvidence source = tenantAssociation.sourceEvidence(); + requireFreshSourceIdentity(tenantAssociation, source); + if (!binding.descriptor().canonicalTenantId().equals(source.canonicalTenantId())) { + throw new IllegalArgumentException("Launch binding does not match its fresh tenant owner"); + } + + lockRequest(binding.descriptor().controlPlaneRequestId()); + FreshTenantOwnerMapping mapping = requireFreshTenantMapping(tenantAssociation); + GameInstanceRow runtime = + requireLockedRuntime(tenantAssociation.legacyGameSessionTenantId(), gameInstanceId); + RealmOwnerProjection realm = requirePublicSharedRealm(binding.descriptor()); + CanonicalGameInstanceLaunchAssociation existing = + findByRequest(binding.descriptor().controlPlaneRequestId(), true) + .map(this::toAssociation) + .orElse(null); + if (existing != null) { + requireExactRetry( + existing, tenantAssociation, gameInstanceId, runtime, binding.evidence(), mapping, realm); + return existing; + } + + requireStartingRuntime(runtime, binding.evidence()); + String evidenceJson = serializeEvidence(binding.evidence()); + RuntimeTenantIdentityEvidence sourceEvidence = tenantAssociation.sourceEvidence(); + dsl.execute( + "INSERT INTO " + + ASSOCIATION_TABLE + + " (target_namespace, control_plane_request_id, game_session_tenant_id, " + + "canonical_tenant_id, tenant_association_operation_id, tenant_association_request_id, " + + "tenant_source_schema_version, tenant_source_target_namespace, " + + "tenant_source_request_id, tenant_source_canonical_tenant_id, " + + "tenant_source_game_row_id, tenant_source_game_tenant_key, " + + "tenant_source_provenance_kind, tenant_association_kind, game_instance_id, " + + "game_instance_uuid, canonical_realm_id, world_slug, playable_state_namespace_id, playable_state_scope, " + + "public_production, captured_starting_row_version, game_template_id, " + + "launch_descriptor_id, version_id, release_bundle_id, generation_config_revision, " + + "version_state_epoch, complete_launch_binding_evidence) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'FRESH_SOURCE_BOUND', ?, ?, ?, ?, ?, " + + "'SHARED', TRUE, ?, ?, ?, ?, ?, ?, ?, CAST(? AS jsonb))", + workloadNamespace, + binding.descriptor().controlPlaneRequestId(), + tenantAssociation.legacyGameSessionTenantId(), + sourceEvidence.canonicalTenantId(), + mapping.operationId(), + sourceEvidence.requestId(), + sourceEvidence.schemaVersion(), + sourceEvidence.targetNamespace(), + sourceEvidence.requestId(), + sourceEvidence.canonicalTenantId(), + sourceEvidence.sourceGameRowId(), + sourceEvidence.sourceGameTenantKey(), + sourceEvidence.provenanceKind(), + gameInstanceId, + runtime.gameInstanceUuid(), + realm.realmId(), + binding.descriptor().worldSlug(), + realm.playableStateNamespaceId(), + runtime.rowVersion(), + binding.descriptor().gameTemplateId(), + binding.descriptor().launchDescriptorId(), + binding.descriptor().versionId(), + binding.descriptor().releaseBundleId(), + binding.descriptor().generationConfigRevision(), + binding.descriptor().versionStateEpoch(), + evidenceJson); + + CanonicalGameInstanceLaunchAssociation inserted = + findByRequest(binding.descriptor().controlPlaneRequestId(), true) + .map(this::toAssociation) + .orElseThrow( + () -> + new IllegalStateException( + "Canonical launch association insert readback is missing")); + requireExactRetry( + inserted, tenantAssociation, gameInstanceId, runtime, binding.evidence(), mapping, realm); + return inserted; + } + + /** Serializes a STARTING-row producer on the exact namespace/request key used by capture. */ + public void lockRequestForStartingGameInstance(String controlPlaneRequestId) { + requireWritableReadCommittedOwnerTransaction(); + requireRequestId(controlPlaneRequestId); + lockRequest(controlPlaneRequestId); + } + + /** + * Reads one committed immutable owner association plus the transient current GameInstance row. + */ + public Optional read(String controlPlaneRequestId) { + requireOutsideTransaction(); + requireRequestId(controlPlaneRequestId); + return findByRequest(controlPlaneRequestId, false).map(this::toAssociation); + } + + private void lockRequest(String controlPlaneRequestId) { + dsl.fetchOne( + "SELECT pg_advisory_xact_lock(hashtextextended(? || ':' || ?, 0))", + workloadNamespace, + controlPlaneRequestId); + } + + private GameInstanceRow requireLockedRuntime(long tenantId, long gameInstanceId) { + Record row = + dsl.fetchOne( + "SELECT id, tenant_id, game_instance_uuid, status, row_version, game_template_id, " + + "launch_descriptor_id, version_id, release_bundle_id, generation_config_revision, " + + "version_state_epoch, run_owned_start_request_id, " + + "run_owned_start_published_release_bundle_ref FROM game_instances " + + "WHERE tenant_id = ? AND id = ? FOR UPDATE", + tenantId, + gameInstanceId); + if (row == null) { + throw new IllegalStateException("Game Session owner instance row is missing in tenant scope"); + } + return toRuntime(row, "status", "row_version"); + } + + private RealmOwnerProjection requirePublicSharedRealm( + net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence descriptor) { + Record row = + dsl.fetchOne( + "SELECT realm_id, playable_state_namespace_id, state_scope, public_production, visible " + + "FROM game_session_canonical_realm_catalog WHERE target_namespace = ? " + + "AND canonical_tenant_id = ? AND world_slug = ? AND public_production = TRUE " + + "AND visible = TRUE", + workloadNamespace, + descriptor.canonicalTenantId(), + descriptor.worldSlug()); + if (row == null + || !Boolean.TRUE.equals(row.get("public_production", Boolean.class)) + || !Boolean.TRUE.equals(row.get("visible", Boolean.class)) + || !RealmEntryPolicy.StateScope.SHARED + .name() + .equals(row.get("state_scope", String.class))) { + throw new IllegalStateException( + "Canonical launch association requires the owner's visible public SHARED realm"); + } + UUID namespaceId = row.get("playable_state_namespace_id", UUID.class); + UUID realmId = row.get("realm_id", UUID.class); + requireNonNil(namespaceId, "playableStateNamespaceId"); + requireNonNil(realmId, "canonicalRealmId"); + return new RealmOwnerProjection(realmId, namespaceId); + } + + private FreshTenantOwnerMapping requireFreshTenantMapping( + FreshGameSessionTenantAssociation expected) { + RuntimeTenantIdentityEvidence source = expected.sourceEvidence(); + Record row = + dsl.fetchOne( + "SELECT association.association_operation_id, association.association_request_id, " + + "association.source_schema_version, association.source_target_namespace, " + + "association.source_request_id, association.source_canonical_tenant_id, " + + "association.canonical_tenant_id, association.legacy_game_session_tenant_id, " + + "association.source_game_row_id, association.source_game_tenant_key, " + + "association.provenance_kind, association.association_kind, " + + "claim.association_operation_id AS claim_operation_id, " + + "claim.association_request_id AS claim_request_id, " + + "claim.association_kind AS claim_kind, claim.reservation_kind AS claim_reservation_kind, " + + "reservation.reservation_kind " + + "FROM game_session_fresh_tenant_association association " + + "JOIN game_session_tenant_canonical_claim claim ON " + + "claim.target_namespace = association.target_namespace " + + "AND claim.canonical_tenant_id = association.canonical_tenant_id " + + "AND claim.legacy_game_session_tenant_id = association.legacy_game_session_tenant_id " + + "AND claim.association_operation_id = association.association_operation_id " + + "AND claim.association_kind = association.association_kind " + + "JOIN game_session_tenant_scope_reservation reservation ON " + + "reservation.game_session_tenant_id = association.legacy_game_session_tenant_id " + + "WHERE association.target_namespace = ? AND association.association_operation_id = ?", + workloadNamespace, + expected.associationOperationId()); + if (row == null) { + throw new IllegalStateException( + "Persisted fresh Game Session tenant association is unavailable"); + } + UUID operationId = row.get("association_operation_id", UUID.class); + long localTenantId = row.get("legacy_game_session_tenant_id", Long.class); + if (!expected.associationOperationId().equals(operationId) + || localTenantId != expected.legacyGameSessionTenantId() + || !source.requestId().equals(row.get("association_request_id", UUID.class)) + || !source.requestId().equals(row.get("source_request_id", UUID.class)) + || source.schemaVersion() != row.get("source_schema_version", Integer.class) + || !source.targetNamespace().equals(row.get("source_target_namespace", String.class)) + || !source.canonicalTenantId().equals(row.get("source_canonical_tenant_id", UUID.class)) + || !source.canonicalTenantId().equals(row.get("canonical_tenant_id", UUID.class)) + || source.sourceGameRowId() != row.get("source_game_row_id", Long.class) + || !source.sourceGameTenantKey().equals(row.get("source_game_tenant_key", String.class)) + || !source.provenanceKind().equals(row.get("provenance_kind", String.class)) + || !operationId.equals(row.get("claim_operation_id", UUID.class)) + || !source.requestId().equals(row.get("claim_request_id", UUID.class)) + || !"FRESH_SOURCE_BOUND".equals(row.get("association_kind", String.class)) + || !"FRESH_SOURCE_BOUND".equals(row.get("claim_kind", String.class)) + || !"FRESH_SOURCE_BOUND".equals(row.get("reservation_kind", String.class)) + || !"FRESH_SOURCE_BOUND".equals(row.get("claim_reservation_kind", String.class))) { + throw new IllegalStateException( + "Persisted fresh tenant source identity does not match its owner"); + } + return new FreshTenantOwnerMapping(operationId); + } + + private Optional findByRequest(String controlPlaneRequestId, boolean forUpdate) { + String sql = + "SELECT association.*, current.status AS current_status, " + + "current.row_version AS current_row_version, current.game_instance_uuid AS " + + "current_game_instance_uuid, current.game_template_id AS current_game_template_id, " + + "current.launch_descriptor_id AS current_launch_descriptor_id, " + + "current.version_id AS current_version_id, current.release_bundle_id AS " + + "current_release_bundle_id, current.generation_config_revision AS " + + "current_generation_config_revision, current.version_state_epoch AS " + + "current_version_state_epoch, current.run_owned_start_request_id AS " + + "current_run_owned_start_request_id, current.run_owned_start_published_release_bundle_ref " + + "AS current_run_owned_start_published_release_bundle_ref " + + "FROM " + + ASSOCIATION_TABLE + + " association JOIN game_instances current " + + "ON current.id = association.game_instance_id " + + "AND current.tenant_id = association.game_session_tenant_id " + + "JOIN game_session_canonical_realm_catalog realm " + + "ON realm.target_namespace = association.target_namespace " + + "AND realm.realm_id = association.canonical_realm_id " + + "AND realm.canonical_tenant_id = association.canonical_tenant_id " + + "AND realm.world_slug = association.world_slug " + + "AND realm.playable_state_namespace_id = association.playable_state_namespace_id " + + "AND realm.visible = TRUE AND realm.public_production = TRUE " + + "AND realm.state_scope = 'SHARED' " + + "WHERE association.target_namespace = ? AND association.control_plane_request_id = ?" + + (forUpdate ? " FOR UPDATE OF association, current" : ""); + return Optional.ofNullable(dsl.fetchOne(sql, workloadNamespace, controlPlaneRequestId)); + } + + private CanonicalGameInstanceLaunchAssociation toAssociation(Record row) { + try { + CompleteLaunchBindingEvidence evidence = + JSON.readValue( + row.get("complete_launch_binding_evidence", JSONB.class).data(), + CompleteLaunchBindingEvidence.class); + ValidatedBinding binding = validateBinding(evidence); + UUID canonicalTenantId = row.get("canonical_tenant_id", UUID.class); + UUID associationOperationId = row.get("tenant_association_operation_id", UUID.class); + UUID gameInstanceUuid = row.get("game_instance_uuid", UUID.class); + UUID namespaceId = row.get("playable_state_namespace_id", UUID.class); + Boolean publicProduction = row.get("public_production", Boolean.class); + if (!workloadNamespace.equals(row.get("target_namespace", String.class)) + || !"FRESH_SOURCE_BOUND".equals(row.get("tenant_association_kind", String.class)) + || !binding.descriptor().targetNamespace().equals(workloadNamespace) + || !binding + .descriptor() + .controlPlaneRequestId() + .equals(row.get("control_plane_request_id", String.class)) + || !canonicalTenantId.equals(binding.descriptor().canonicalTenantId()) + || !row.get("world_slug", String.class).equals(binding.descriptor().worldSlug()) + || !row.get("launch_descriptor_id", String.class) + .equals(binding.descriptor().launchDescriptorId()) + || row.get("game_template_id", Long.class) != binding.descriptor().gameTemplateId() + || row.get("version_id", Long.class) != binding.descriptor().versionId() + || row.get("release_bundle_id", Long.class) != binding.descriptor().releaseBundleId() + || !row.get("generation_config_revision", String.class) + .equals(binding.descriptor().generationConfigRevision()) + || row.get("version_state_epoch", Long.class) != binding.descriptor().versionStateEpoch() + || !Boolean.TRUE.equals(publicProduction)) { + throw new IllegalStateException( + "Persisted launch association contradicts its typed binding"); + } + RuntimeTenantIdentityEvidence source = sourceFromRow(row); + FreshGameSessionTenantAssociation mapping = + new FreshGameSessionTenantAssociation( + associationOperationId, row.get("game_session_tenant_id", Long.class), source); + requireFreshTenantMapping(mapping); + GameInstanceRow current = + new GameInstanceRow( + row.get("game_instance_id", Long.class), + row.get("game_session_tenant_id", Long.class), + row.get("current_game_instance_uuid", UUID.class), + row.get("current_status", String.class), + row.get("current_row_version", Long.class), + row.get("current_game_template_id", Long.class), + row.get("current_launch_descriptor_id", String.class), + row.get("current_version_id", Long.class), + row.get("current_release_bundle_id", Long.class), + row.get("current_generation_config_revision", String.class), + row.get("current_version_state_epoch", Long.class), + row.get("current_run_owned_start_request_id", String.class), + row.get("current_run_owned_start_published_release_bundle_ref", String.class)); + requireRuntimeBinding(current, evidence); + if (!gameInstanceUuid.equals(current.gameInstanceUuid()) + || current.rowVersion() < row.get("captured_starting_row_version", Long.class) + || !RealmEntryPolicy.StateScope.SHARED + .name() + .equals(row.get("playable_state_scope", String.class))) { + throw new IllegalStateException( + "Current Game Session row contradicts its launch association"); + } + return new CanonicalGameInstanceLaunchAssociation( + workloadNamespace, + row.get("game_session_tenant_id", Long.class), + associationOperationId, + canonicalTenantId, + gameInstanceUuid, + row.get("world_slug", String.class), + namespaceId, + RealmEntryPolicy.StateScope.SHARED, + true, + binding.descriptor().controlPlaneRequestId(), + binding.descriptor().launchDescriptorId(), + row.get("captured_starting_row_version", Long.class), + evidence, + CurrentGameInstanceStatus.valueOf(current.status()), + current.rowVersion()); + } catch (RuntimeException exception) { + if (exception instanceof IllegalStateException illegalState) { + throw illegalState; + } + throw new IllegalStateException( + "Persisted canonical launch association is malformed", exception); + } + } + + private static RuntimeTenantIdentityEvidence sourceFromRow(Record row) { + return new RuntimeTenantIdentityEvidence( + row.get("tenant_source_schema_version", Integer.class), + row.get("tenant_source_target_namespace", String.class), + row.get("tenant_source_request_id", UUID.class), + row.get("tenant_source_canonical_tenant_id", UUID.class), + row.get("tenant_source_game_row_id", Long.class), + row.get("tenant_source_game_tenant_key", String.class), + row.get("tenant_source_provenance_kind", String.class)); + } + + private void requireExactRetry( + CanonicalGameInstanceLaunchAssociation stored, + FreshGameSessionTenantAssociation expectedTenant, + long expectedGameInstanceId, + GameInstanceRow current, + CompleteLaunchBindingEvidence expectedEvidence, + FreshTenantOwnerMapping mapping, + RealmOwnerProjection realm) { + if (stored.gameSessionTenantId() != expectedTenant.legacyGameSessionTenantId() + || !stored.tenantAssociationOperationId().equals(mapping.operationId()) + || !stored.canonicalTenantId().equals(expectedTenant.sourceEvidence().canonicalTenantId()) + || !stored.playableStateNamespaceId().equals(realm.playableStateNamespaceId()) + || !stored.launchBindingEvidence().equals(expectedEvidence) + || !stored.gameInstanceUuid().equals(current.gameInstanceUuid()) + || stored.currentRowVersion() > current.rowVersion() + || stored.capturedStartingRowVersion() > current.rowVersion()) { + throw new CanonicalGameInstanceLaunchAssociationConflictException( + "Launch association request was reused with a changed tenant, instance, or source binding"); + } + Record row = + dsl.fetchOne( + "SELECT game_instance_id FROM " + + ASSOCIATION_TABLE + + " WHERE target_namespace = ? AND control_plane_request_id = ?", + workloadNamespace, + stored.controlPlaneRequestId()); + if (row == null || row.get("game_instance_id", Long.class) != expectedGameInstanceId) { + throw new CanonicalGameInstanceLaunchAssociationConflictException( + "Launch association request was reused for another Game Session instance"); + } + requireRuntimeBinding(current, expectedEvidence); + } + + private static void requireStartingRuntime( + GameInstanceRow runtime, CompleteLaunchBindingEvidence evidence) { + requireRuntimeBinding(runtime, evidence); + if (!"STARTING".equals(runtime.status()) + || !evidence.descriptor().controlPlaneRequestId().equals(runtime.runOwnedStartRequestId()) + || !evidence + .descriptor() + .publishedReleaseBundleRef() + .equals(runtime.runOwnedStartPublishedReleaseBundleRef())) { + throw new IllegalStateException( + "Launch association capture requires the exact persisted run-owned STARTING instance"); + } + } + + private static void requireRuntimeBinding( + GameInstanceRow runtime, CompleteLaunchBindingEvidence evidence) { + var descriptor = evidence.descriptor(); + if (runtime.id() <= 0 + || runtime.tenantId() <= 0 + || runtime.gameInstanceUuid() == null + || NIL_UUID.equals(runtime.gameInstanceUuid()) + || runtime.rowVersion() < 0 + || runtime.gameTemplateId() == null + || runtime.gameTemplateId() != descriptor.gameTemplateId() + || !Objects.equals(runtime.launchDescriptorId(), descriptor.launchDescriptorId()) + || runtime.versionId() == null + || runtime.versionId() != descriptor.versionId() + || runtime.releaseBundleId() == null + || runtime.releaseBundleId() != descriptor.releaseBundleId() + || runtime.versionStateEpoch() == null + || runtime.versionStateEpoch() != descriptor.versionStateEpoch() + || !Objects.equals( + runtime.generationConfigRevision(), descriptor.generationConfigRevision()) + || !Objects.equals(runtime.runOwnedStartRequestId(), descriptor.controlPlaneRequestId()) + || !Objects.equals( + runtime.runOwnedStartPublishedReleaseBundleRef(), + descriptor.publishedReleaseBundleRef())) { + throw new IllegalStateException( + "Game Session instance does not match the complete launch binding"); + } + try { + CurrentGameInstanceStatus.valueOf(runtime.status()); + } catch (RuntimeException invalidStatus) { + throw new IllegalStateException("Game Session instance status is unavailable", invalidStatus); + } + } + + private static GameInstanceRow toRuntime( + Record row, String statusColumn, String rowVersionColumn) { + return toRuntime( + row, + statusColumn, + rowVersionColumn, + "game_instance_uuid", + "game_template_id", + "launch_descriptor_id", + "version_id", + "release_bundle_id", + "generation_config_revision", + "version_state_epoch", + "run_owned_start_request_id", + "run_owned_start_published_release_bundle_ref"); + } + + private static GameInstanceRow toRuntime( + Record row, + String statusColumn, + String rowVersionColumn, + String uuidColumn, + String templateColumn, + String descriptorColumn, + String versionColumn, + String bundleColumn, + String configColumn, + String epochColumn, + String requestColumn, + String publishedRefColumn) { + return new GameInstanceRow( + row.get("id", Long.class), + row.get("tenant_id", Long.class), + row.get(uuidColumn, UUID.class), + row.get(statusColumn, String.class), + row.get(rowVersionColumn, Long.class), + row.get(templateColumn, Long.class), + row.get(descriptorColumn, String.class), + row.get(versionColumn, Long.class), + row.get(bundleColumn, Long.class), + row.get(configColumn, String.class), + row.get(epochColumn, Long.class), + row.get(requestColumn, String.class), + row.get(publishedRefColumn, String.class)); + } + + private static ValidatedBinding validateBinding(CompleteLaunchBindingEvidence evidence) { + Objects.requireNonNull(evidence, "launchBindingEvidence"); + var descriptor = evidence.descriptor(); + descriptor.requireValid(); + evidence.releaseAttestation().requireValid(descriptor); + requireRequestId(descriptor.controlPlaneRequestId()); + return new ValidatedBinding(evidence); + } + + private void requireFreshSourceIdentity( + FreshGameSessionTenantAssociation association, RuntimeTenantIdentityEvidence evidence) { + if (evidence.schemaVersion() != 1 + || !workloadNamespace.equals(evidence.targetNamespace()) + || evidence.requestId() == null + || NIL_UUID.equals(evidence.requestId()) + || evidence.canonicalTenantId() == null + || NIL_UUID.equals(evidence.canonicalTenantId()) + || association.legacyGameSessionTenantId() <= 0 + || !"NEW_GAME_ROW".equals(evidence.provenanceKind())) { + throw new IllegalArgumentException( + "Only exact fresh NEW_GAME_ROW owner identity is supported"); + } + } + + private static String serializeEvidence(CompleteLaunchBindingEvidence evidence) { + try { + return JSON.writeValueAsString(evidence); + } catch (JacksonException exception) { + throw new IllegalStateException( + "Failed to persist complete launch binding evidence", exception); + } + } + + private void requireWritableReadCommittedOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Canonical launch association capture requires a writable owner transaction"); + } + 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".equals(settings.get("transaction_isolation", String.class)) + || !"off".equals(settings.get("transaction_read_only", String.class))) { + throw new IllegalStateException( + "Canonical launch association capture requires writable READ COMMITTED isolation"); + } + } + + private static void requireOutsideTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Canonical launch association read requires a committed owner read"); + } + } + + private static void requireRequestId(String value) { + Objects.requireNonNull(value, "controlPlaneRequestId"); + if (value.isBlank() || value.length() > 128) { + throw new IllegalArgumentException("controlPlaneRequestId must contain 1 to 128 characters"); + } + } + + private static void requirePositive(long value, String label) { + if (value <= 0) { + throw new IllegalArgumentException(label + " must be positive"); + } + } + + 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 record ValidatedBinding(CompleteLaunchBindingEvidence evidence) { + private net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence + descriptor() { + return evidence.descriptor(); + } + } + + private record FreshTenantOwnerMapping(UUID operationId) {} + + private record RealmOwnerProjection(UUID realmId, UUID playableStateNamespaceId) {} + + private record GameInstanceRow( + long id, + long tenantId, + UUID gameInstanceUuid, + String status, + long rowVersion, + Long gameTemplateId, + String launchDescriptorId, + Long versionId, + Long releaseBundleId, + String generationConfigRevision, + Long versionStateEpoch, + String runOwnedStartRequestId, + String runOwnedStartPublishedReleaseBundleRef) {} + + public static final class CanonicalGameInstanceLaunchAssociationConflictException + extends RuntimeException { + public CanonicalGameInstanceLaunchAssociationConflictException(String message) { + super(message); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/FreshGameSessionTenantAssociationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/FreshGameSessionTenantAssociationRepository.java new file mode 100644 index 0000000000..39311a13fe --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/FreshGameSessionTenantAssociationRepository.java @@ -0,0 +1,373 @@ +package net.firedevops.firemud.gamesession.repository; + +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.RuntimeTenantIdentityEvidence; +import net.firedevops.firemud.gamesession.service.FreshGameSessionTenantAssociation; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Explicit owner repository for immutable fresh source identity and a Game Session-private key. */ +@SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "The explicit owner boundary validates trusted collaborators and performs no I/O while" + + " constructing; this repository is deliberately not a Spring bean.") +public class FreshGameSessionTenantAssociationRepository { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String RESERVATION_TABLE = "game_session_tenant_scope_reservation"; + private static final String CLAIM_TABLE = "game_session_tenant_canonical_claim"; + private static final String ASSOCIATION_TABLE = "game_session_fresh_tenant_association"; + + private final DSLContext dsl; + private final String workloadNamespace; + private final TransactionTemplate ownerTransaction; + private final TransactionTemplate committedRead; + + public FreshGameSessionTenantAssociationRepository( + DSLContext dsl, PlatformTransactionManager transactionManager, String workloadNamespace) { + this.dsl = Objects.requireNonNull(dsl, "dsl must not be null"); + Objects.requireNonNull(transactionManager, "transactionManager must not be null"); + 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.committedRead = new TransactionTemplate(transactionManager); + this.committedRead.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED); + this.committedRead.setReadOnly(true); + } + + /** Commits one exact source identity mapping, then verifies it in a separate committed read. */ + public FreshGameSessionTenantAssociation registerAndReadback( + RuntimeTenantIdentityEvidence sourceEvidence) { + Objects.requireNonNull(sourceEvidence, "sourceEvidence"); + requireOutsideTransaction(); + requireFreshEvidence(sourceEvidence); + + FreshGameSessionTenantAssociation committed; + try { + committed = ownerTransaction.execute(status -> registerInTransaction(sourceEvidence)); + } catch (FreshTenantAssociationConflictException conflict) { + Optional racedOutcome = + readByRequestCommitted(sourceEvidence.requestId()); + if (racedOutcome.isPresent() && racedOutcome.get().sourceEvidence().equals(sourceEvidence)) { + return racedOutcome.get(); + } + throw conflict; + } + if (committed == null) { + throw new IllegalStateException("Fresh Game Session tenant association was not committed"); + } + return readCommitted( + committed.associationOperationId(), sourceEvidence.requestId(), sourceEvidence); + } + + /** Reads one exact committed local mapping without allocation, repair, or source calls. */ + public Optional readByRequestCommitted( + UUID associationRequestId) { + requireOutsideTransaction(); + requireNonNil(associationRequestId, "associationRequestId"); + return committedRead.execute( + status -> { + Record row = + dsl.fetchOne( + "SELECT association_operation_id FROM " + + ASSOCIATION_TABLE + + " WHERE target_namespace = ? AND association_request_id = ?", + workloadNamespace, + associationRequestId); + if (row == null) { + return Optional.empty(); + } + return Optional.of( + readByOperationInTransaction(row.get("association_operation_id", UUID.class))); + }); + } + + private FreshGameSessionTenantAssociation registerInTransaction( + RuntimeTenantIdentityEvidence evidence) { + requireWritableReadCommittedOwnerTransaction(); + FreshGameSessionTenantAssociation exactRetry = + findByRequestInTransaction(evidence.requestId()).orElse(null); + if (exactRetry != null) { + if (!exactRetry.sourceEvidence().equals(evidence)) { + throw new FreshTenantAssociationConflictException( + "Fresh tenant association request was reused with changed source identity"); + } + return exactRetry; + } + + acquireRequestFence(evidence.requestId()); + exactRetry = findByRequestInTransaction(evidence.requestId()).orElse(null); + if (exactRetry != null) { + if (!exactRetry.sourceEvidence().equals(evidence)) { + throw new FreshTenantAssociationConflictException( + "Fresh tenant association request was reused with changed source identity"); + } + return exactRetry; + } + + UUID associationOperationId = UUID.randomUUID(); + long privateTenantId = allocateFreshReservation(evidence); + int claimInserted = + dsl.execute( + "INSERT INTO " + + CLAIM_TABLE + + " (target_namespace, canonical_tenant_id, legacy_game_session_tenant_id, " + + "association_kind, reservation_kind, association_operation_id, " + + "association_request_id) " + + "VALUES (?, ?, ?, 'FRESH_SOURCE_BOUND', 'FRESH_SOURCE_BOUND', ?, ?) " + + "ON CONFLICT DO NOTHING", + workloadNamespace, + evidence.canonicalTenantId(), + privateTenantId, + associationOperationId, + evidence.requestId()); + if (claimInserted != 1) { + throw new FreshTenantAssociationConflictException( + "Canonical tenant already has a Game Session owner mapping"); + } + + int associationInserted = + dsl.execute( + "INSERT INTO " + + ASSOCIATION_TABLE + + " (association_operation_id, target_namespace, association_request_id, " + + "source_schema_version, source_target_namespace, source_request_id, " + + "source_canonical_tenant_id, canonical_tenant_id, " + + "legacy_game_session_tenant_id, source_game_row_id, " + + "source_game_tenant_key, provenance_kind, association_kind) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'FRESH_SOURCE_BOUND') " + + "ON CONFLICT DO NOTHING", + associationOperationId, + workloadNamespace, + evidence.requestId(), + evidence.schemaVersion(), + evidence.targetNamespace(), + evidence.requestId(), + evidence.canonicalTenantId(), + evidence.canonicalTenantId(), + privateTenantId, + evidence.sourceGameRowId(), + evidence.sourceGameTenantKey(), + evidence.provenanceKind()); + if (associationInserted != 1) { + throw new FreshTenantAssociationConflictException( + "Fresh tenant request or source identity conflicts with an existing mapping"); + } + return new FreshGameSessionTenantAssociation(associationOperationId, privateTenantId, evidence); + } + + private long allocateFreshReservation(RuntimeTenantIdentityEvidence evidence) { + Long numericSourceTenantKey = numericSourceTenantKey(evidence.sourceGameTenantKey()); + for (int attempt = 0; attempt < 1024; attempt++) { + Record reserved = + dsl.fetchOne( + "SELECT nextval(pg_get_serial_sequence('" + + RESERVATION_TABLE + + "', 'game_session_tenant_id')) AS candidate"); + Long candidate = reserved == null ? null : reserved.get("candidate", Long.class); + if (candidate == null || candidate <= 0) { + throw new IllegalStateException("Game Session tenant reservation returned an invalid key"); + } + if (candidate == evidence.sourceGameRowId() || candidate.equals(numericSourceTenantKey)) { + continue; + } + int inserted = + dsl.execute( + "INSERT INTO " + + RESERVATION_TABLE + + " (game_session_tenant_id, reservation_kind) " + + "VALUES (?, 'FRESH_SOURCE_BOUND') " + + "ON CONFLICT (game_session_tenant_id) DO NOTHING", + candidate); + if (inserted == 1) { + return candidate; + } + } + throw new IllegalStateException( + "Game Session tenant reservation sequence repeatedly collided with occupied scopes"); + } + + private static Long numericSourceTenantKey(String sourceGameTenantKey) { + if (sourceGameTenantKey == null + || sourceGameTenantKey.length() > 19 + || !sourceGameTenantKey.matches("[1-9][0-9]*")) { + return null; + } + try { + return Long.valueOf(sourceGameTenantKey); + } catch (NumberFormatException exception) { + return null; + } + } + + private void acquireRequestFence(UUID associationRequestId) { + dsl.fetchOne( + "SELECT pg_advisory_xact_lock(hashtextextended(? || ':' || ?, 0))", + workloadNamespace, + associationRequestId.toString()); + } + + private Optional findByRequestInTransaction( + UUID associationRequestId) { + Record row = + dsl.fetchOne( + "SELECT association_operation_id FROM " + + ASSOCIATION_TABLE + + " WHERE target_namespace = ? AND association_request_id = ?", + workloadNamespace, + associationRequestId); + return row == null + ? Optional.empty() + : Optional.of( + readByOperationInTransaction(row.get("association_operation_id", UUID.class))); + } + + private FreshGameSessionTenantAssociation readCommitted( + UUID operationId, UUID requestId, RuntimeTenantIdentityEvidence expectedEvidence) { + requireOutsideTransaction(); + requireNonNil(operationId, "operationId"); + requireNonNil(requestId, "requestId"); + return committedRead.execute( + status -> { + FreshGameSessionTenantAssociation association = readByOperationInTransaction(operationId); + if (!association.sourceEvidence().equals(expectedEvidence) + || !association.sourceEvidence().requestId().equals(requestId)) { + throw new IllegalStateException( + "Committed fresh tenant association contradicts its exact source identity"); + } + return association; + }); + } + + private FreshGameSessionTenantAssociation readByOperationInTransaction(UUID operationId) { + Record row = + dsl.fetchOne( + "SELECT association.association_operation_id, association.association_kind, " + + "association.association_request_id, association.source_schema_version, " + + "association.source_target_namespace, association.source_request_id, " + + "association.source_canonical_tenant_id, association.canonical_tenant_id, " + + "association.legacy_game_session_tenant_id, association.source_game_row_id, " + + "association.source_game_tenant_key, association.provenance_kind, " + + "reservation.reservation_kind, claim.association_kind AS claim_kind, " + + "claim.association_operation_id AS claim_operation_id, " + + "claim.association_request_id AS claim_request_id, " + + "claim.legacy_game_session_tenant_id AS claim_tenant_id " + + "FROM " + + ASSOCIATION_TABLE + + " association JOIN " + + RESERVATION_TABLE + + " reservation ON reservation.game_session_tenant_id = " + + "association.legacy_game_session_tenant_id JOIN " + + CLAIM_TABLE + + " claim ON claim.target_namespace = association.target_namespace " + + "AND claim.canonical_tenant_id = association.canonical_tenant_id " + + "AND claim.legacy_game_session_tenant_id = " + + "association.legacy_game_session_tenant_id " + + "AND claim.association_operation_id = association.association_operation_id " + + "AND claim.association_kind = association.association_kind " + + "WHERE association.target_namespace = ? " + + "AND association.association_operation_id = ?", + workloadNamespace, + operationId); + if (row == null) { + throw new IllegalStateException("Committed fresh tenant association readback is missing"); + } + + try { + UUID storedOperationId = row.get("association_operation_id", UUID.class); + UUID requestId = row.get("association_request_id", UUID.class); + long privateTenantId = row.get("legacy_game_session_tenant_id", Long.class); + if (!operationId.equals(storedOperationId) + || privateTenantId <= 0 + || !requestId.equals(row.get("source_request_id", UUID.class)) + || !requestId.equals(row.get("claim_request_id", UUID.class)) + || !row.get("canonical_tenant_id", UUID.class) + .equals(row.get("source_canonical_tenant_id", UUID.class)) + || privateTenantId != row.get("claim_tenant_id", Long.class) + || !"FRESH_SOURCE_BOUND".equals(row.get("association_kind", String.class)) + || !"FRESH_SOURCE_BOUND".equals(row.get("reservation_kind", String.class)) + || !"FRESH_SOURCE_BOUND".equals(row.get("claim_kind", String.class)) + || !operationId.equals(row.get("claim_operation_id", UUID.class))) { + throw new IllegalStateException( + "Committed fresh tenant association owner fence is invalid"); + } + RuntimeTenantIdentityEvidence evidence = + new RuntimeTenantIdentityEvidence( + row.get("source_schema_version", Integer.class), + row.get("source_target_namespace", String.class), + row.get("source_request_id", UUID.class), + row.get("source_canonical_tenant_id", UUID.class), + row.get("source_game_row_id", Long.class), + row.get("source_game_tenant_key", String.class), + row.get("provenance_kind", String.class)); + if (!workloadNamespace.equals(evidence.targetNamespace()) + || !requestId.equals(evidence.requestId()) + || !"NEW_GAME_ROW".equals(evidence.provenanceKind())) { + throw new IllegalStateException("Committed fresh tenant source identity is invalid"); + } + return new FreshGameSessionTenantAssociation(storedOperationId, privateTenantId, evidence); + } catch (RuntimeException exception) { + if (exception instanceof IllegalStateException) { + throw exception; + } + throw new IllegalStateException("Committed fresh tenant association is invalid", exception); + } + } + + private void requireFreshEvidence(RuntimeTenantIdentityEvidence evidence) { + if (!workloadNamespace.equals(evidence.targetNamespace()) + || !"NEW_GAME_ROW".equals(evidence.provenanceKind())) { + throw new IllegalArgumentException( + "Game Design identity must target this namespace and prove NEW_GAME_ROW provenance"); + } + } + + private void requireWritableReadCommittedOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Fresh tenant association requires a writable owner transaction"); + } + 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".equals(settings.get("transaction_isolation", String.class)) + || !"off".equals(settings.get("transaction_read_only", String.class))) { + throw new IllegalStateException( + "Fresh tenant association requires writable READ COMMITTED isolation"); + } + } + + private static void requireOutsideTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Fresh tenant source lookup and committed readback must run outside owner transactions"); + } + } + + 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 class FreshTenantAssociationConflictException extends RuntimeException { + public FreshTenantAssociationConflictException(String message) { + super(message); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameInstanceLaunchAssociationReadRequest.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameInstanceLaunchAssociationReadRequest.java new file mode 100644 index 0000000000..f80c5e7ad6 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameInstanceLaunchAssociationReadRequest.java @@ -0,0 +1,55 @@ +package net.firedevops.firemud.gamesession.service; + +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; + +/** Exact independent World read selector for one committed Game Session launch association. */ +public record CanonicalGameInstanceLaunchAssociationReadRequest( + UUID readRequestId, + String targetNamespace, + UUID canonicalTenantId, + String worldSlug, + UUID gameInstanceUuid, + String controlPlaneRequestId, + String launchDescriptorId, + String expectedDescriptorRequestDigest, + String expectedDescriptorResultDigest, + String expectedReleaseAttestationEvidenceDigest) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); + + public CanonicalGameInstanceLaunchAssociationReadRequest { + requireNonNil(readRequestId, "readRequestId"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(gameInstanceUuid, "gameInstanceUuid"); + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requireText(controlPlaneRequestId, "controlPlaneRequestId"); + requireText(launchDescriptorId, "launchDescriptorId"); + requireDigest(expectedDescriptorRequestDigest, "expectedDescriptorRequestDigest"); + requireDigest(expectedDescriptorResultDigest, "expectedDescriptorResultDigest"); + requireDigest( + expectedReleaseAttestationEvidenceDigest, "expectedReleaseAttestationEvidenceDigest"); + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + } + + private static void requireText(String value, String name) { + Objects.requireNonNull(value, name); + if (value.isBlank() || value.length() > 256) { + throw new IllegalArgumentException(name + " must be non-blank and bounded"); + } + } + + private static void requireDigest(String value, String name) { + if (value == null || !DIGEST.matcher(value).matches()) { + throw new IllegalArgumentException(name + " must be a canonical SHA-256 digest"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameInstanceLaunchAssociationReadService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameInstanceLaunchAssociationReadService.java new file mode 100644 index 0000000000..36847fbe6d --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameInstanceLaunchAssociationReadService.java @@ -0,0 +1,54 @@ +package net.firedevops.firemud.gamesession.service; + +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; + +/** Reads and qualifies exact durable Game Session owner evidence without changing it. */ +public final class CanonicalGameInstanceLaunchAssociationReadService { + private final CanonicalGameInstanceLaunchAssociationRepository repository; + private final String configuredNamespace; + + public CanonicalGameInstanceLaunchAssociationReadService( + CanonicalGameInstanceLaunchAssociationRepository repository, String configuredNamespace) { + this.repository = Objects.requireNonNull(repository, "repository"); + this.configuredNamespace = Objects.requireNonNull(configuredNamespace, "configuredNamespace"); + } + + public CanonicalGameInstanceLaunchAssociation read( + CanonicalGameInstanceLaunchAssociationReadRequest request) { + Objects.requireNonNull(request, "request"); + if (!configuredNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException("Read namespace does not match this Game Session owner"); + } + CanonicalGameInstanceLaunchAssociation association = + repository + .read(request.controlPlaneRequestId()) + .orElseThrow( + () -> new IllegalStateException("Canonical launch association is unavailable")); + CompleteLaunchBindingEvidence binding = association.launchBindingEvidence(); + var descriptor = binding.descriptor(); + var attestation = binding.releaseAttestation(); + descriptor.requireValid(); + attestation.requireValid(descriptor); + if (request.readRequestId().equals(descriptor.authoredWorldSourceOperationId()) + || request.readRequestId().toString().equals(descriptor.controlPlaneRequestId()) + || !configuredNamespace.equals(association.targetNamespace()) + || !request.targetNamespace().equals(association.targetNamespace()) + || !request.canonicalTenantId().equals(association.canonicalTenantId()) + || !request.worldSlug().equals(association.worldSlug()) + || !request.gameInstanceUuid().equals(association.gameInstanceUuid()) + || !request.controlPlaneRequestId().equals(association.controlPlaneRequestId()) + || !request.launchDescriptorId().equals(association.launchDescriptorId()) + || !request.expectedDescriptorRequestDigest().equals(descriptor.requestDigest()) + || !request.expectedDescriptorResultDigest().equals(descriptor.resultDigest()) + || !request + .expectedReleaseAttestationEvidenceDigest() + .equals(attestation.evidenceDigest())) { + throw new IllegalStateException( + "Canonical launch association does not match the exact read selector"); + } + return association; + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalStartingGameInstanceOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalStartingGameInstanceOwner.java new file mode 100644 index 0000000000..50eb918f37 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalStartingGameInstanceOwner.java @@ -0,0 +1,381 @@ +package net.firedevops.firemud.gamesession.service; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.RuntimeTenantIdentityEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; +import net.firedevops.firemud.gamesession.dto.CanonicalLaunchPreparationSnapshot; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalLaunchPreparationRequest; +import net.firedevops.firemud.gamesession.entity.GameInstance; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository.CanonicalGameInstanceLaunchAssociationConflictException; +import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalLaunchPreparationRepository.InvalidLaunchPreparationEvidenceException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Explicit non-bean producer for a source-qualified Game Session STARTING row and its immutable + * launch association. It does not authorize the acting Account, call World, or admit gameplay. + */ +public final class CanonicalStartingGameInstanceOwner { + private static final String STARTING = "STARTING"; + private static final String RUN_OWNED_LAUNCH_DIGEST_SCHEMA = + "firemud.run-owned-initial-launch/v1"; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final FreshGameSessionTenantAssociationService tenantAssociationService; + private final GameSessionCanonicalLaunchPreparationService launchPreparationService; + private final CanonicalGameInstanceLaunchAssociationRepository launchAssociationRepository; + private final GameInstanceRepository gameInstanceRepository; + private final String workloadNamespace; + private final TransactionTemplate ownerTransaction; + + public CanonicalStartingGameInstanceOwner( + FreshGameSessionTenantAssociationService tenantAssociationService, + GameSessionCanonicalLaunchPreparationService launchPreparationService, + CanonicalGameInstanceLaunchAssociationRepository launchAssociationRepository, + GameInstanceRepository gameInstanceRepository, + PlatformTransactionManager transactionManager, + String workloadNamespace) { + this.tenantAssociationService = + Objects.requireNonNull(tenantAssociationService, "tenantAssociationService"); + this.launchPreparationService = + Objects.requireNonNull(launchPreparationService, "launchPreparationService"); + this.launchAssociationRepository = + Objects.requireNonNull(launchAssociationRepository, "launchAssociationRepository"); + this.gameInstanceRepository = + Objects.requireNonNull(gameInstanceRepository, "gameInstanceRepository"); + 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); + } + + /** + * Resolves both owner sources without an ambient transaction, then atomically creates or exactly + * reuses the STARTING row and its complete launch association in one local owner transaction. + */ + public CanonicalGameInstanceLaunchAssociation createStartingInstance( + CreateCanonicalLaunchPreparationRequest request, UUID associationRequestId) { + Objects.requireNonNull(request, "request"); + requireNoAmbientTransaction(); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new SecurityException("Launch request namespace does not match this workload"); + } + requireNonNil(associationRequestId, "associationRequestId"); + + FreshGameSessionTenantAssociation tenantAssociation = + tenantAssociationService.associate(associationRequestId, request.canonicalTenantId()); + requireFreshTenantJoin(request, associationRequestId, tenantAssociation); + + CanonicalLaunchPreparationSnapshot preparation = launchPreparationService.prepare(request); + if (preparation == null) { + throw new InvalidLaunchPreparationEvidenceException( + "Canonical launch preparation returned no committed snapshot"); + } + preparation.requireValid(); + if (!request.equals(preparation.request())) { + throw new InvalidLaunchPreparationEvidenceException( + "Committed launch preparation differs from the exact requested owner identity"); + } + requirePublicSharedCatalog(preparation); + requireFreshTenantSourceJoin(tenantAssociation, preparation.sourceIntakeReceipt().source()); + + CompleteLaunchBindingEvidence binding = + launchPreparationService.readCompleteBinding(preparation); + requireCompleteBinding(request, preparation, binding); + requireNoAmbientTransaction(); + + OwnerWriteResult written = + ownerTransaction.execute( + status -> createOrReuseAndCapture(request, tenantAssociation, binding)); + if (written == null) { + throw new InvalidLaunchPreparationEvidenceException( + "Canonical STARTING owner transaction returned no captured association"); + } + + Optional committedAssociation = + launchAssociationRepository.read(request.controlPlaneRequestId()); + if (committedAssociation.isEmpty() + || !written.association().equals(committedAssociation.orElseThrow())) { + throw new InvalidLaunchPreparationEvidenceException( + "Committed canonical STARTING association differs from its owner transaction result"); + } + GameInstance committedInstance = + gameInstanceRepository + .findById(written.gameInstanceId()) + .orElseThrow( + () -> + new InvalidLaunchPreparationEvidenceException( + "Committed canonical STARTING instance is missing after readback")); + requireExactInstance(committedInstance, request, written.tenantAssociation(), binding, false); + requireAssociationProjection( + committedAssociation.orElseThrow(), committedInstance, request, binding); + return committedAssociation.orElseThrow(); + } + + private OwnerWriteResult createOrReuseAndCapture( + CreateCanonicalLaunchPreparationRequest request, + FreshGameSessionTenantAssociation tenantAssociation, + CompleteLaunchBindingEvidence binding) { + launchAssociationRepository.lockRequestForStartingGameInstance(request.controlPlaneRequestId()); + Optional existing = + gameInstanceRepository.findByTenantIdAndRunOwnedStartRequestIdForUpdate( + tenantAssociation.legacyGameSessionTenantId(), request.controlPlaneRequestId()); + + GameInstance instance; + if (existing.isPresent()) { + instance = existing.orElseThrow(); + requireExactInstance(instance, request, tenantAssociation, binding, false); + } else { + instance = + gameInstanceRepository.save(newStartingInstance(request, tenantAssociation, binding)); + requireExactInstance(instance, request, tenantAssociation, binding, true); + } + + CanonicalGameInstanceLaunchAssociation association = + launchAssociationRepository.capture(tenantAssociation, instance.getId(), binding); + if (association == null + || !association.launchBindingEvidence().equals(binding) + || !association + .tenantAssociationOperationId() + .equals(tenantAssociation.associationOperationId()) + || !association.gameInstanceUuid().equals(instance.getGameInstanceUuid()) + || !association.controlPlaneRequestId().equals(request.controlPlaneRequestId())) { + throw new InvalidLaunchPreparationEvidenceException( + "Captured launch association differs from the exact STARTING owner row"); + } + return new OwnerWriteResult(instance.getId(), tenantAssociation, association); + } + + private GameInstance newStartingInstance( + CreateCanonicalLaunchPreparationRequest request, + FreshGameSessionTenantAssociation tenantAssociation, + CompleteLaunchBindingEvidence binding) { + var descriptor = binding.descriptor(); + GameInstance instance = new GameInstance(); + instance.setTenantId(tenantAssociation.legacyGameSessionTenantId()); + instance.setRuntimeVersion(Long.toString(descriptor.versionId())); + instance.setGameTemplateId(descriptor.gameTemplateId()); + instance.setLaunchDescriptorId(descriptor.launchDescriptorId()); + instance.setVersionId(descriptor.versionId()); + instance.setReleaseBundleId(descriptor.releaseBundleId()); + instance.setVersionStateEpoch(descriptor.versionStateEpoch()); + instance.setGenerationConfigRevision(descriptor.generationConfigRevision()); + instance.setRemapSetId(descriptor.remapSetId()); + instance.setOwnerAccountId(request.actingAccountUuid().toString()); + instance.setStatus(STARTING); + instance.setRunOwnedStartRequestId(request.controlPlaneRequestId()); + instance.setRunOwnedStartRequestDigest(runOwnedStartRequestDigest(request, tenantAssociation)); + instance.setRunOwnedStartPublishedReleaseBundleRef(descriptor.publishedReleaseBundleRef()); + // A descriptor patch is only a candidate; a newly allocated runtime remains semantically + // UNPINNED until Game Session's separate owner pin transition commits its exact tuple. + instance.setScriptPatchVersion(null); + instance.setScriptPatchBaseVersionId(null); + instance.setScriptPinEpoch(null); + instance.setScriptPatchPinnedControlPlaneRequestId(null); + return instance; + } + + private static void requireFreshTenantJoin( + CreateCanonicalLaunchPreparationRequest request, + UUID associationRequestId, + FreshGameSessionTenantAssociation association) { + Objects.requireNonNull(association, "tenantAssociation"); + RuntimeTenantIdentityEvidence source = association.sourceEvidence(); + if (!associationRequestId.equals(source.requestId()) + || !request.canonicalTenantId().equals(source.canonicalTenantId()) + || !request.targetNamespace().equals(source.targetNamespace()) + || !"NEW_GAME_ROW".equals(source.provenanceKind())) { + throw new InvalidLaunchPreparationEvidenceException( + "Fresh Game Session tenant association differs from the exact launch tenant"); + } + } + + private static void requireFreshTenantSourceJoin( + FreshGameSessionTenantAssociation association, AuthoredWorldSourceEvidence source) { + RuntimeTenantIdentityEvidence tenant = association.sourceEvidence(); + if (tenant.schemaVersion() != source.schemaVersion() + || !tenant.targetNamespace().equals(source.targetNamespace()) + || !tenant.canonicalTenantId().equals(source.canonicalTenantId()) + || tenant.sourceGameRowId() != source.sourceGameRowId() + || !tenant.sourceGameTenantKey().equals(source.sourceGameTenantKey()) + || !tenant.provenanceKind().equals(source.provenanceKind()) + || !"NEW_GAME_ROW".equals(source.provenanceKind())) { + throw new InvalidLaunchPreparationEvidenceException( + "Fresh tenant identity does not match the exact authored-world source intake"); + } + } + + private void requirePublicSharedCatalog(CanonicalLaunchPreparationSnapshot preparation) { + var catalog = preparation.catalogSnapshot(); + if (!workloadNamespace.equals(catalog.targetNamespace()) + || !preparation.request().canonicalTenantId().equals(catalog.tenantId()) + || !preparation.request().realmId().equals(catalog.realmId()) + || !catalog.visible() + || !catalog.publicProduction() + || !"SHARED".equals(catalog.stateScope())) { + throw new InvalidLaunchPreparationEvidenceException( + "Canonical STARTING owner requires the exact visible public SHARED catalog"); + } + } + + private void requireCompleteBinding( + CreateCanonicalLaunchPreparationRequest request, + CanonicalLaunchPreparationSnapshot preparation, + CompleteLaunchBindingEvidence binding) { + Objects.requireNonNull(binding, "completeLaunchBinding"); + var descriptor = binding.descriptor(); + descriptor.requireValid(); + binding.releaseAttestation().requireValid(descriptor); + if (!descriptor.equals(preparation.launchDescriptorEvidence()) + || !workloadNamespace.equals(descriptor.targetNamespace()) + || !request.canonicalTenantId().equals(descriptor.canonicalTenantId()) + || !request.controlPlaneRequestId().equals(descriptor.controlPlaneRequestId()) + || request.gameTemplateId() != descriptor.gameTemplateId()) { + throw new InvalidLaunchPreparationEvidenceException( + "Complete Game Design binding differs from the exact committed launch preparation"); + } + } + + private static void requireExactInstance( + GameInstance instance, + CreateCanonicalLaunchPreparationRequest request, + FreshGameSessionTenantAssociation tenantAssociation, + CompleteLaunchBindingEvidence binding, + boolean newlyAllocated) { + Objects.requireNonNull(instance, "gameInstance"); + var descriptor = binding.descriptor(); + String expectedRequestDigest = runOwnedStartRequestDigest(request, tenantAssociation); + if (instance.getId() == null + || instance.getId() <= 0L + || instance.getGameInstanceUuid() == null + || NIL_UUID.equals(instance.getGameInstanceUuid()) + || instance.getTenantId() == null + || instance.getTenantId() != tenantAssociation.legacyGameSessionTenantId() + || !Objects.equals(instance.getOwnerAccountId(), request.actingAccountUuid().toString()) + || instance.getLegacyOwnerAccountId() != null + || !Objects.equals(instance.getRuntimeVersion(), Long.toString(descriptor.versionId())) + || !Objects.equals(instance.getGameTemplateId(), descriptor.gameTemplateId()) + || !Objects.equals(instance.getLaunchDescriptorId(), descriptor.launchDescriptorId()) + || !Objects.equals(instance.getVersionId(), descriptor.versionId()) + || !Objects.equals(instance.getReleaseBundleId(), descriptor.releaseBundleId()) + || !Objects.equals(instance.getVersionStateEpoch(), descriptor.versionStateEpoch()) + || !Objects.equals( + instance.getGenerationConfigRevision(), descriptor.generationConfigRevision()) + || !Objects.equals(instance.getRemapSetId(), descriptor.remapSetId()) + || !Objects.equals(instance.getRunOwnedStartRequestId(), request.controlPlaneRequestId()) + || !Objects.equals(instance.getRunOwnedStartRequestDigest(), expectedRequestDigest) + || !Objects.equals( + instance.getRunOwnedStartPublishedReleaseBundleRef(), + descriptor.publishedReleaseBundleRef()) + || instance.getRowVersion() == null + || instance.getRowVersion() < 0L + || !isSupportedCurrentStatus(instance.getStatus()) + || (newlyAllocated + && (!STARTING.equals(instance.getStatus()) || instance.getRowVersion() != 0L)) + || (STARTING.equals(instance.getStatus()) && hasCurrentPin(instance))) { + throw new CanonicalGameInstanceLaunchAssociationConflictException( + "Run-owned STARTING request conflicts with the persisted owner instance"); + } + } + + private static void requireAssociationProjection( + CanonicalGameInstanceLaunchAssociation association, + GameInstance instance, + CreateCanonicalLaunchPreparationRequest request, + CompleteLaunchBindingEvidence binding) { + if (!association.launchBindingEvidence().equals(binding) + || !association.canonicalTenantId().equals(request.canonicalTenantId()) + || !association.controlPlaneRequestId().equals(request.controlPlaneRequestId()) + || !association.gameInstanceUuid().equals(instance.getGameInstanceUuid()) + || association.gameSessionTenantId() != instance.getTenantId() + || association.currentRowVersion() != instance.getRowVersion() + || !association.currentGameInstanceStatus().name().equals(instance.getStatus())) { + throw new InvalidLaunchPreparationEvidenceException( + "Committed launch association does not match the exact current Game Session row"); + } + } + + private static boolean hasCurrentPin(GameInstance instance) { + return instance.getScriptPatchVersion() != null + || instance.getScriptPinEpoch() != null + || instance.getScriptPatchPinnedControlPlaneRequestId() != null; + } + + private static boolean isSupportedCurrentStatus(String status) { + return STARTING.equals(status) + || "RUNNING".equals(status) + || "STOPPING".equals(status) + || "STOPPED".equals(status); + } + + /** Mirrors GameInstanceServiceImpl's run-owned request digest for exact future resumption. */ + private static String runOwnedStartRequestDigest( + CreateCanonicalLaunchPreparationRequest request, + FreshGameSessionTenantAssociation tenantAssociation) { + StringBuilder preimage = new StringBuilder(); + appendDigestField(preimage, "schema", RUN_OWNED_LAUNCH_DIGEST_SCHEMA); + appendDigestField( + preimage, "tenantId", Long.toString(tenantAssociation.legacyGameSessionTenantId())); + appendDigestField(preimage, "gameTemplateId", Long.toString(request.gameTemplateId())); + appendDigestField(preimage, "controlPlaneRequestId", request.controlPlaneRequestId()); + appendDigestField(preimage, "ownerAccountId", request.actingAccountUuid().toString()); + appendDigestField(preimage, "replaceExistingFirst", "false"); + try { + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(preimage.toString().getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 unavailable", exception); + } + } + + private static void appendDigestField(StringBuilder preimage, String name, String value) { + int nameByteLength = name.getBytes(StandardCharsets.UTF_8).length; + int valueByteLength = value.getBytes(StandardCharsets.UTF_8).length; + preimage + .append(nameByteLength) + .append(':') + .append(name) + .append(valueByteLength) + .append(':') + .append(value); + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Canonical STARTING preparation and source reads require no ambient transaction"); + } + } + + 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 record OwnerWriteResult( + long gameInstanceId, + FreshGameSessionTenantAssociation tenantAssociation, + CanonicalGameInstanceLaunchAssociation association) {} +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FreshGameSessionTenantAssociation.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FreshGameSessionTenantAssociation.java new file mode 100644 index 0000000000..bf3aa9a4bb --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FreshGameSessionTenantAssociation.java @@ -0,0 +1,26 @@ +package net.firedevops.firemud.gamesession.service; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.tenant.RuntimeTenantIdentityEvidence; + +/** Immutable Game Session-local mapping to exact authenticated fresh Game Design identity. */ +public record FreshGameSessionTenantAssociation( + UUID associationOperationId, + long legacyGameSessionTenantId, + RuntimeTenantIdentityEvidence sourceEvidence) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public FreshGameSessionTenantAssociation { + if (associationOperationId == null || NIL_UUID.equals(associationOperationId)) { + throw new IllegalArgumentException("associationOperationId must be a non-nil UUID"); + } + if (legacyGameSessionTenantId <= 0) { + throw new IllegalArgumentException("legacyGameSessionTenantId must be positive"); + } + Objects.requireNonNull(sourceEvidence, "sourceEvidence"); + if (!"NEW_GAME_ROW".equals(sourceEvidence.provenanceKind())) { + throw new IllegalArgumentException("Fresh association requires NEW_GAME_ROW provenance"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FreshGameSessionTenantAssociationService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FreshGameSessionTenantAssociationService.java new file mode 100644 index 0000000000..f2ea471496 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FreshGameSessionTenantAssociationService.java @@ -0,0 +1,66 @@ +package net.firedevops.firemud.gamesession.service; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.RuntimeTenantIdentityEvidence; +import net.firedevops.firemud.gamesession.client.GameDesignRuntimeTenantIdentityClient; +import net.firedevops.firemud.gamesession.repository.FreshGameSessionTenantAssociationRepository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Explicit, non-bean boundary for exact authenticated fresh Game Design identity and its Game + * Session-owned local association. This is identity ownership only, not admission authority. + */ +public final class FreshGameSessionTenantAssociationService { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final GameDesignRuntimeTenantIdentityClient sourceClient; + private final FreshGameSessionTenantAssociationRepository repository; + private final String workloadNamespace; + + public FreshGameSessionTenantAssociationService( + GameDesignRuntimeTenantIdentityClient sourceClient, + FreshGameSessionTenantAssociationRepository repository, + String workloadNamespace) { + this.sourceClient = Objects.requireNonNull(sourceClient, "sourceClient"); + this.repository = Objects.requireNonNull(repository, "repository"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Game Session workload namespace is invalid"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Reads exact owner evidence before the repository opens its short local owner transaction. */ + @Transactional(propagation = Propagation.NOT_SUPPORTED) + public FreshGameSessionTenantAssociation associate( + UUID associationRequestId, UUID canonicalTenantId) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Game Design runtime identity read must finish before the local owner transaction"); + } + requireNonNil(associationRequestId, "associationRequestId"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + + RuntimeTenantIdentityEvidence evidence = + sourceClient.resolveRuntimeTenantIdentity( + canonicalTenantId.toString(), associationRequestId.toString()); + if (evidence == null + || !workloadNamespace.equals(evidence.targetNamespace()) + || !associationRequestId.equals(evidence.requestId()) + || !canonicalTenantId.equals(evidence.canonicalTenantId()) + || !"NEW_GAME_ROW".equals(evidence.provenanceKind())) { + throw new IllegalStateException( + "Authenticated Game Design runtime identity does not match the exact fresh request"); + } + return repository.registerAndReadback(evidence); + } + + 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/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java index f1080ab98f..57d25a4a29 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java @@ -6,7 +6,9 @@ import java.util.UUID; 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.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.gamesession.dto.CanonicalLaunchPreparationSnapshot; import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; @@ -150,6 +152,53 @@ public CanonicalLaunchPreparationSnapshot prepare( return exact; } + /** + * Reads the complete authenticated Game Design binding for one exact committed preparation. This + * is a non-admitting evidence read: it neither creates nor advances a game instance. + */ + public CompleteLaunchBindingEvidence readCompleteBinding( + CanonicalLaunchPreparationSnapshot snapshot) { + Objects.requireNonNull(snapshot, "snapshot"); + requireNoAmbientTransaction(); + snapshot.requireValid(); + if (!workloadNamespace.equals(snapshot.request().targetNamespace())) { + throw new SecurityException("Launch preparation namespace does not match this workload"); + } + + CanonicalLaunchPreparationSnapshot committed = + preparationRepository + .readByControlPlaneRequestId( + workloadNamespace, snapshot.request().controlPlaneRequestId()) + .orElseThrow( + () -> + new InvalidLaunchPreparationEvidenceException( + "Committed launch preparation is missing before complete binding read")); + committed.requireValid(); + if (!snapshot.equals(committed)) { + throw new InvalidLaunchPreparationEvidenceException( + "Committed launch preparation changed before complete binding read"); + } + + AuthoredWorldLaunchDescriptorEvidence descriptor = snapshot.launchDescriptorEvidence(); + GetRequest readSelector = + new GetRequest(randomNonNilUuid(), descriptor.request(), descriptor.resultDigest()); + CompleteLaunchBindingEvidence binding = + descriptorClient.getComplete( + AuthoredWorldLaunchDescriptorGrpcCodec.toGetRequest(readSelector)); + if (binding == null) { + throw new InvalidLaunchPreparationEvidenceException( + "Game Design returned no complete launch binding"); + } + binding.descriptor().requireValid(); + binding.releaseAttestation().requireValid(binding.descriptor()); + if (!descriptor.equals(binding.descriptor()) + || !workloadNamespace.equals(binding.descriptor().targetNamespace())) { + throw new InvalidLaunchPreparationEvidenceException( + "Complete Game Design binding differs from the committed launch descriptor"); + } + return binding; + } + private static void requireCatalogBinding( CreateCanonicalLaunchPreparationRequest request, CanonicalRealmCatalogSnapshot catalog) { if (!request.targetNamespace().equals(catalog.targetNamespace()) @@ -186,4 +235,12 @@ private static void requireNoAmbientTransaction() { "Canonical launch preparation cannot enter from an ambient transaction"); } } + + private static UUID randomNonNilUuid() { + UUID value; + do { + value = UUID.randomUUID(); + } while (new UUID(0L, 0L).equals(value)); + return value; + } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameInstanceLaunchAssociationReadGrpcCodec.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameInstanceLaunchAssociationReadGrpcCodec.java new file mode 100644 index 0000000000..0794a137d4 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameInstanceLaunchAssociationReadGrpcCodec.java @@ -0,0 +1,139 @@ +package net.firedevops.firemud.gamesession.service.impl; + +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; +import net.firedevops.firemud.gamesession.service.CanonicalGameInstanceLaunchAssociationReadRequest; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameInstanceLaunchAssociationRequest; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameInstanceLaunchAssociationResponse; + +/** Lossless mapping between typed launch-owner evidence and the World-only RPC response. */ +final class CanonicalGameInstanceLaunchAssociationReadGrpcCodec { + private CanonicalGameInstanceLaunchAssociationReadGrpcCodec() {} + + static CanonicalGameInstanceLaunchAssociationReadRequest fromWire( + GetCanonicalGameInstanceLaunchAssociationRequest request) { + if (!request.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException( + "Canonical Game Session owner-read request has unknown fields"); + } + return new CanonicalGameInstanceLaunchAssociationReadRequest( + parseUuid(request.getReadRequestId(), "read_request_id"), + request.getTargetNamespace(), + parseUuid(request.getCanonicalTenantId(), "canonical_tenant_id"), + request.getWorldSlug(), + parseUuid(request.getGameInstanceUuid(), "game_instance_uuid"), + request.getControlPlaneRequestId(), + request.getLaunchDescriptorId(), + request.getExpectedDescriptorRequestDigest(), + request.getExpectedDescriptorResultDigest(), + request.getExpectedReleaseAttestationEvidenceDigest()); + } + + static GetCanonicalGameInstanceLaunchAssociationResponse toWire( + GetCanonicalGameInstanceLaunchAssociationRequest request, + CanonicalGameInstanceLaunchAssociation association) { + CompleteLaunchBindingEvidence binding = association.launchBindingEvidence(); + AuthoredWorldLaunchDescriptorEvidence descriptor = binding.descriptor(); + AuthoredWorldReleaseAttestationEvidence attestation = binding.releaseAttestation(); + descriptor.requireValid(); + attestation.requireValid(descriptor); + return GetCanonicalGameInstanceLaunchAssociationResponse.newBuilder() + .setReadRequestId(request.getReadRequestId()) + .setTargetNamespace(request.getTargetNamespace()) + .setCanonicalTenantId(request.getCanonicalTenantId()) + .setWorldSlug(request.getWorldSlug()) + .setGameInstanceUuid(request.getGameInstanceUuid()) + .setControlPlaneRequestId(request.getControlPlaneRequestId()) + .setLaunchDescriptorId(request.getLaunchDescriptorId()) + .setDescriptorRequestDigest(descriptor.requestDigest()) + .setDescriptorResultDigest(descriptor.resultDigest()) + .setReleaseAttestationEvidenceDigest(attestation.evidenceDigest()) + .setPlayableStateNamespaceId(association.playableStateNamespaceId().toString()) + .setPlayableStateScope(association.playableStateScope().name()) + .setPublicProduction(association.publicProduction()) + .setCurrentGameInstanceStatus(association.currentGameInstanceStatus().name()) + .setCurrentRowVersion(association.currentRowVersion()) + .setLaunchDescriptor(toLaunchDescriptor(descriptor)) + .setReleaseAttestation( + AuthoredWorldLaunchDescriptorGrpcCodec.toReleaseAttestation(attestation)) + .build(); + } + + private static net.firedevops.firemud.gamedesign.v1.LaunchDescriptor toLaunchDescriptor( + AuthoredWorldLaunchDescriptorEvidence source) { + var binding = + net.firedevops.firemud.gamedesign.v1.AuthoredWorldLaunchDescriptorEvidence.newBuilder() + .setSchemaVersion(source.schemaVersion()) + .setTargetNamespace(source.targetNamespace()) + .setControlPlaneRequestId(source.controlPlaneRequestId()) + .setCanonicalTenantId(source.canonicalTenantId().toString()) + .setWorldSlug(source.worldSlug()) + .setAuthoredWorldSourceOperationId(source.authoredWorldSourceOperationId().toString()) + .setAuthoredWorldSourceEvidenceDigest(source.authoredWorldSourceEvidenceDigest()) + .setGameTemplateId(source.gameTemplateId()) + .setRequestDigest(source.requestDigest()) + .setLaunchDescriptorId(source.launchDescriptorId()) + .setVersionId(source.versionId()) + .setRuntimeFlagsJson(source.runtimeFlagsJson()) + .setGenerationConfigRevision(source.generationConfigRevision()) + .setVersionStateEpoch(source.versionStateEpoch()) + .setReleaseBundleId(source.releaseBundleId()) + .setPublishedReleaseBundleRef(source.publishedReleaseBundleRef()) + .setResultDigest(source.resultDigest()); + if (source.requestedScriptPatchVersionPresent()) { + binding.setRequestedScriptPatchVersion(source.requestedScriptPatchVersion()); + } + if (source.sourceVersionIdPresent()) { + binding.setSourceVersionId(source.sourceVersionId()); + } + if (source.targetVersionIdPresent()) { + binding.setTargetVersionId(source.targetVersionId()); + } + if (source.requestedRuntimeFlagsJsonPresent()) { + binding.setRequestedRuntimeFlagsJson(source.requestedRuntimeFlagsJson()); + } + if (source.scriptPatchVersionPresent()) { + binding.setScriptPatchVersion(source.scriptPatchVersion()); + } + if (source.remapSetIdPresent()) { + binding.setRemapSetId(source.remapSetId()); + } + + var descriptor = + net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.newBuilder() + .setLaunchDescriptorId(source.launchDescriptorId()) + .setCanonicalTenantId(source.canonicalTenantId().toString()) + .setGameTemplateId(source.gameTemplateId()) + .setControlPlaneRequestId(source.controlPlaneRequestId()) + .setVersionId(source.versionId()) + .setRuntimeFlagsJson(source.runtimeFlagsJson()) + .setGenerationConfigRevision(source.generationConfigRevision()) + .setVersionStateEpoch(source.versionStateEpoch()) + .setReleaseBundleId(source.releaseBundleId()) + .setPublishedReleaseBundleRef(source.publishedReleaseBundleRef()) + .setAuthoredWorldBinding(binding); + if (source.scriptPatchVersionPresent()) { + descriptor.setScriptPatchVersion(source.scriptPatchVersion()); + } + if (source.remapSetIdPresent()) { + descriptor.setRemapSetId(source.remapSetId()); + } + return descriptor.build(); + } + + private static UUID parseUuid(String value, String field) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value)) { + throw new IllegalArgumentException(field + " must be a canonical UUID"); + } + return parsed; + } catch (RuntimeException exception) { + throw new IllegalArgumentException(field + " must be a canonical UUID", exception); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameInstanceLaunchAssociationReadWorkloadGuard.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameInstanceLaunchAssociationReadWorkloadGuard.java new file mode 100644 index 0000000000..843e4a9613 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameInstanceLaunchAssociationReadWorkloadGuard.java @@ -0,0 +1,44 @@ +package net.firedevops.firemud.gamesession.service.impl; + +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.AdminAuthorizationException; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamesession.v1.GameSessionControlPlaneServiceGrpc; + +/** Same-namespace World Management workload-only authorization for the non-mutating owner read. */ +public final class CanonicalGameInstanceLaunchAssociationReadWorkloadGuard { + private static final String METHOD_NAME = + "game_session.v1.GameSessionControlPlaneService/GetCanonicalGameInstanceLaunchAssociation"; + private static final String WORLD_MANAGEMENT_SERVICE = "world-management-service"; + + private final String trustedNamespace; + + public CanonicalGameInstanceLaunchAssociationReadWorkloadGuard(String trustedNamespace) { + this.trustedNamespace = trustedNamespace; + } + + public void requireWorldManagementOwnerReadCaller() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (!METHOD_NAME.equals( + GameSessionControlPlaneServiceGrpc.getGetCanonicalGameInstanceLaunchAssociationMethod() + .getFullMethodName()) + || !GrpcPeerIdentity.isValidNamespace(trustedNamespace) + || peer == null + || !WORLD_MANAGEMENT_SERVICE.equals(peer.service()) + || !trustedNamespace.equals(peer.namespace()) + || !("spiffe://firemud/ns/" + trustedNamespace + "/sa/" + WORLD_MANAGEMENT_SERVICE) + .equals(peer.uri()) + || SessionContext.hasAuthenticatedCallerContext()) { + throw new AdminAuthorizationException( + "Canonical Game Session owner read requires the exact same-namespace World Management workload without caller context"); + } + } + + public void requireConfiguredTargetNamespace(String targetNamespace) { + if (!GrpcPeerIdentity.isValidNamespace(trustedNamespace) + || !trustedNamespace.equals(targetNamespace)) { + throw new AdminAuthorizationException( + "Canonical Game Session owner read target namespace is not configured here"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java index bfe78ed281..50da5591ec 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java @@ -18,6 +18,8 @@ import net.firedevops.firemud.common.security.AdminRoleGuard; import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.gamesession.service.AdmissionPointerVersionMismatchException; +import net.firedevops.firemud.gamesession.service.CanonicalGameInstanceLaunchAssociationReadRequest; +import net.firedevops.firemud.gamesession.service.CanonicalGameInstanceLaunchAssociationReadService; import net.firedevops.firemud.gamesession.service.InitialAdmissionBindHoldBinding; import net.firedevops.firemud.gamesession.service.InitialAdmissionBindOwnerProof; import net.firedevops.firemud.gamesession.service.InitialAdmissionBindOwnerProofReader; @@ -27,6 +29,8 @@ import net.firedevops.firemud.gamesession.v1.ExecutePreparedVersionCutoverRequest; import net.firedevops.firemud.gamesession.v1.ExecutePreparedVersionCutoverResponse; import net.firedevops.firemud.gamesession.v1.GameSessionControlPlaneServiceGrpc; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameInstanceLaunchAssociationRequest; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameInstanceLaunchAssociationResponse; import net.firedevops.firemud.gamesession.v1.GetGameInstanceRuntimeStateRequest; import net.firedevops.firemud.gamesession.v1.GetGameInstanceRuntimeStateResponse; import net.firedevops.firemud.gamesession.v1.GetGameSessionPinConvergenceRequest; @@ -84,6 +88,7 @@ import net.firedevops.firemud.shared.v1.ErrorDetail; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.dao.DataAccessResourceFailureException; @@ -112,6 +117,10 @@ public final class GameSessionControlPlaneGrpcService private final MeterRegistry meterRegistry; private InitialAdmissionBindOwnerProofReader initialAdmissionBindOwnerProofReader; private InitialAdmissionBindOwnerReadWorkloadGuard initialAdmissionBindOwnerReadWorkloadGuard; + private CanonicalGameInstanceLaunchAssociationReadService + canonicalGameInstanceLaunchAssociationReadService; + private CanonicalGameInstanceLaunchAssociationReadWorkloadGuard + canonicalGameInstanceLaunchAssociationReadWorkloadGuard; private static final Pattern SHA_256 = Pattern.compile("[0-9a-f]{64}"); @@ -145,6 +154,16 @@ public void configureInitialAdmissionBindOwnerReadBoundary( new InitialAdmissionBindOwnerReadWorkloadGuard(workloadNamespace); } + @Autowired + public void configureCanonicalGameInstanceLaunchAssociationOwnerReadBoundary( + ObjectProvider ownerReadServiceProvider, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + this.canonicalGameInstanceLaunchAssociationReadService = + ownerReadServiceProvider.getIfAvailable(); + this.canonicalGameInstanceLaunchAssociationReadWorkloadGuard = + new CanonicalGameInstanceLaunchAssociationReadWorkloadGuard(workloadNamespace); + } + private long parseTenantId(String tenantId) { return ControlPlaneRequestParser.parsePositiveLong(tenantId, "tenant_id"); } @@ -285,6 +304,94 @@ public void getInitialAdmissionBindProof( responseObserver.onCompleted(); } + @Override + @Timed(value = "gamesessionGrpc.controlPlane.getCanonicalGameInstanceLaunchAssociation") + public void getCanonicalGameInstanceLaunchAssociation( + GetCanonicalGameInstanceLaunchAssociationRequest request, + StreamObserver responseObserver) { + if (request == null) { + responseObserver.onNext( + GetCanonicalGameInstanceLaunchAssociationResponse.newBuilder() + .setError( + GrpcAppErrors.error( + meterRegistry, "INVALID_ARGUMENT", "Invalid owner-read request")) + .build()); + responseObserver.onCompleted(); + return; + } + try { + if (canonicalGameInstanceLaunchAssociationReadWorkloadGuard == null) { + throw new AdminAuthorizationException("Canonical owner-read boundary is not configured"); + } + canonicalGameInstanceLaunchAssociationReadWorkloadGuard + .requireWorldManagementOwnerReadCaller(); + } catch (AdminAuthorizationException exception) { + responseObserver.onNext( + GetCanonicalGameInstanceLaunchAssociationResponse.newBuilder() + .setError(authorizationError("GetCanonicalGameInstanceLaunchAssociation", exception)) + .build()); + responseObserver.onCompleted(); + return; + } + + CanonicalGameInstanceLaunchAssociationReadRequest target; + try { + target = CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromWire(request); + canonicalGameInstanceLaunchAssociationReadWorkloadGuard.requireConfiguredTargetNamespace( + target.targetNamespace()); + } catch (AdminAuthorizationException exception) { + responseObserver.onNext( + GetCanonicalGameInstanceLaunchAssociationResponse.newBuilder() + .setError(authorizationError("GetCanonicalGameInstanceLaunchAssociation", exception)) + .build()); + responseObserver.onCompleted(); + return; + } catch (IllegalArgumentException exception) { + responseObserver.onNext( + GetCanonicalGameInstanceLaunchAssociationResponse.newBuilder() + .setError( + invalidArgumentError("GetCanonicalGameInstanceLaunchAssociation", exception)) + .build()); + responseObserver.onCompleted(); + return; + } + + if (canonicalGameInstanceLaunchAssociationReadService == null) { + responseObserver.onNext( + GetCanonicalGameInstanceLaunchAssociationResponse.newBuilder() + .setError( + GrpcAppErrors.error( + meterRegistry, + "UNAVAILABLE", + "Canonical owner-read authority is unavailable")) + .build()); + responseObserver.onCompleted(); + return; + } + try { + var association = canonicalGameInstanceLaunchAssociationReadService.read(target); + responseObserver.onNext( + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.toWire(request, association)); + responseObserver.onCompleted(); + } catch (IllegalArgumentException exception) { + responseObserver.onNext( + GetCanonicalGameInstanceLaunchAssociationResponse.newBuilder() + .setError( + invalidArgumentError("GetCanonicalGameInstanceLaunchAssociation", exception)) + .build()); + responseObserver.onCompleted(); + } catch (Exception exception) { + logger.error("GetCanonicalGameInstanceLaunchAssociation failed", exception); + responseObserver.onNext( + GetCanonicalGameInstanceLaunchAssociationResponse.newBuilder() + .setError( + GrpcAppErrors.error( + meterRegistry, "UNAVAILABLE", "Canonical owner association is unavailable")) + .build()); + responseObserver.onCompleted(); + } + } + private GetInitialAdmissionBindProofResponse.Builder echoInitialAdmissionBindTuple( GetInitialAdmissionBindProofRequest request) { return GetInitialAdmissionBindProofResponse.newBuilder() diff --git a/services/game-session-service/src/main/resources/db/migration/V15__fresh_game_session_tenant_association.sql b/services/game-session-service/src/main/resources/db/migration/V15__fresh_game_session_tenant_association.sql new file mode 100644 index 0000000000..e20ee53a96 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V15__fresh_game_session_tenant_association.sql @@ -0,0 +1,325 @@ +CREATE TABLE game_session_tenant_scope_reservation ( + game_session_tenant_id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + reservation_kind VARCHAR(32) NOT NULL, + reserved_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT uq_gs_tenant_scope_reservation_kind + UNIQUE (game_session_tenant_id, reservation_kind), + CONSTRAINT chk_gs_tenant_scope_reservation_positive + CHECK (game_session_tenant_id > 0), + CONSTRAINT chk_gs_tenant_scope_reservation_kind + CHECK (reservation_kind IN ('LEGACY_OCCUPIED', 'FRESH_SOURCE_BOUND')) +); + +CREATE TABLE game_session_tenant_canonical_claim ( + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + legacy_game_session_tenant_id BIGINT NOT NULL, + association_kind VARCHAR(32) NOT NULL, + reservation_kind VARCHAR(32) NOT NULL, + association_operation_id UUID NOT NULL, + association_request_id UUID NOT NULL, + claimed_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gs_tenant_canonical_claim + PRIMARY KEY (target_namespace, canonical_tenant_id), + CONSTRAINT uq_gs_tenant_canonical_claim_private_key + UNIQUE (target_namespace, legacy_game_session_tenant_id), + CONSTRAINT uq_gs_tenant_canonical_claim_operation + UNIQUE (association_operation_id), + CONSTRAINT uq_gs_tenant_canonical_claim_request + UNIQUE (target_namespace, association_request_id), + CONSTRAINT uq_gs_tenant_canonical_claim_association + UNIQUE (target_namespace, canonical_tenant_id, legacy_game_session_tenant_id, + association_operation_id, association_kind), + CONSTRAINT fk_gs_tenant_canonical_claim_reservation + FOREIGN KEY (legacy_game_session_tenant_id, reservation_kind) + REFERENCES game_session_tenant_scope_reservation + (game_session_tenant_id, reservation_kind), + CONSTRAINT chk_gs_tenant_canonical_claim_namespace CHECK ( + octet_length(target_namespace) BETWEEN 1 AND 63 + AND target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + ), + CONSTRAINT chk_gs_tenant_canonical_claim_uuid + CHECK (canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT chk_gs_tenant_canonical_claim_ids CHECK ( + legacy_game_session_tenant_id > 0 + AND association_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND association_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT chk_gs_tenant_canonical_claim_kind CHECK ( + (association_kind = 'RETAINED_V8_1' AND reservation_kind = 'LEGACY_OCCUPIED') + OR + (association_kind = 'FRESH_SOURCE_BOUND' AND reservation_kind = 'FRESH_SOURCE_BOUND') + ) +); + +CREATE TABLE game_session_fresh_tenant_association ( + association_operation_id UUID PRIMARY KEY, + target_namespace VARCHAR(63) NOT NULL, + association_request_id UUID NOT NULL, + source_schema_version INTEGER NOT NULL, + source_target_namespace VARCHAR(63) NOT NULL, + source_request_id UUID NOT NULL, + source_canonical_tenant_id UUID NOT NULL, + canonical_tenant_id UUID NOT NULL, + legacy_game_session_tenant_id BIGINT NOT NULL, + source_game_row_id BIGINT NOT NULL, + source_game_tenant_key VARCHAR(72) NOT NULL, + provenance_kind VARCHAR(32) NOT NULL, + association_kind VARCHAR(32) NOT NULL DEFAULT 'FRESH_SOURCE_BOUND', + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT uq_gs_fresh_tenant_association_request + UNIQUE (target_namespace, association_request_id), + CONSTRAINT uq_gs_fresh_tenant_association_canonical + UNIQUE (target_namespace, canonical_tenant_id), + CONSTRAINT uq_gs_fresh_tenant_association_private_key + UNIQUE (legacy_game_session_tenant_id), + CONSTRAINT fk_gs_fresh_tenant_association_reservation + FOREIGN KEY (legacy_game_session_tenant_id, association_kind) + REFERENCES game_session_tenant_scope_reservation + (game_session_tenant_id, reservation_kind), + CONSTRAINT fk_gs_fresh_tenant_association_claim + FOREIGN KEY (target_namespace, canonical_tenant_id, legacy_game_session_tenant_id, + association_operation_id, association_kind) + REFERENCES game_session_tenant_canonical_claim + (target_namespace, canonical_tenant_id, legacy_game_session_tenant_id, + association_operation_id, association_kind), + CONSTRAINT chk_gs_fresh_tenant_association_identity CHECK ( + octet_length(target_namespace) BETWEEN 1 AND 63 + AND target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND source_target_namespace = target_namespace + AND source_schema_version = 1 + AND source_request_id = association_request_id + AND source_canonical_tenant_id = canonical_tenant_id + AND association_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND association_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND source_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT chk_gs_fresh_tenant_association_source CHECK ( + legacy_game_session_tenant_id > 0 + AND source_game_row_id > 0 + AND char_length(source_game_tenant_key) BETWEEN 1 AND 72 + AND source_game_tenant_key !~ '^[[:space:]]*$' + AND provenance_kind = 'NEW_GAME_ROW' + AND association_kind = 'FRESH_SOURCE_BOUND' + ) +); + +-- [jooq ignore start] +CREATE FUNCTION reject_game_session_tenant_owner_evidence_mutation() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Game Session tenant owner evidence is immutable' + USING ERRCODE = 'check_violation'; +END; +$$; + +CREATE TRIGGER game_session_tenant_scope_reservation_immutable + BEFORE UPDATE OR DELETE ON game_session_tenant_scope_reservation + FOR EACH ROW EXECUTE FUNCTION reject_game_session_tenant_owner_evidence_mutation(); +CREATE TRIGGER game_session_tenant_scope_reservation_no_truncate + BEFORE TRUNCATE ON game_session_tenant_scope_reservation + FOR EACH STATEMENT EXECUTE FUNCTION reject_game_session_tenant_owner_evidence_mutation(); +CREATE TRIGGER game_session_tenant_canonical_claim_immutable + BEFORE UPDATE OR DELETE ON game_session_tenant_canonical_claim + FOR EACH ROW EXECUTE FUNCTION reject_game_session_tenant_owner_evidence_mutation(); +CREATE TRIGGER game_session_tenant_canonical_claim_no_truncate + BEFORE TRUNCATE ON game_session_tenant_canonical_claim + FOR EACH STATEMENT EXECUTE FUNCTION reject_game_session_tenant_owner_evidence_mutation(); +CREATE TRIGGER game_session_fresh_tenant_association_immutable + BEFORE UPDATE OR DELETE ON game_session_fresh_tenant_association + FOR EACH ROW EXECUTE FUNCTION reject_game_session_tenant_owner_evidence_mutation(); +CREATE TRIGGER game_session_fresh_tenant_association_no_truncate + BEFORE TRUNCATE ON game_session_fresh_tenant_association + FOR EACH STATEMENT EXECUTE FUNCTION reject_game_session_tenant_owner_evidence_mutation(); + +CREATE FUNCTION reserve_game_session_tenant_scope() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + current_kind VARCHAR(32); +BEGIN + IF TG_OP = 'UPDATE' AND NEW.tenant_id IS NOT DISTINCT FROM OLD.tenant_id THEN + RETURN NEW; + END IF; + IF NEW.tenant_id IS NULL THEN + RETURN NEW; + END IF; + IF NEW.tenant_id <= 0 THEN + RAISE EXCEPTION 'Game Session tenant scope must be positive' + USING ERRCODE = '23514', CONSTRAINT = 'chk_gs_tenant_scope_reservation_positive'; + END IF; + + INSERT INTO game_session_tenant_scope_reservation + (game_session_tenant_id, reservation_kind) + VALUES (NEW.tenant_id, 'LEGACY_OCCUPIED') + ON CONFLICT (game_session_tenant_id) DO NOTHING; + + SELECT reservation_kind + INTO current_kind + FROM game_session_tenant_scope_reservation + WHERE game_session_tenant_id = NEW.tenant_id + FOR KEY SHARE; + IF current_kind IS DISTINCT FROM 'LEGACY_OCCUPIED' THEN + RAISE EXCEPTION 'Numeric-only tenant scope cannot use a fresh source-bound key' + USING ERRCODE = '23514', CONSTRAINT = 'chk_gs_numeric_fresh_tenant_scope_denied'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION claim_retained_game_session_tenant_identity() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + current_kind VARCHAR(32); +BEGIN + INSERT INTO game_session_tenant_scope_reservation + (game_session_tenant_id, reservation_kind) + VALUES (NEW.legacy_game_session_tenant_id, 'LEGACY_OCCUPIED') + ON CONFLICT (game_session_tenant_id) DO NOTHING; + + SELECT reservation_kind + INTO current_kind + FROM game_session_tenant_scope_reservation + WHERE game_session_tenant_id = NEW.legacy_game_session_tenant_id + FOR KEY SHARE; + IF current_kind IS DISTINCT FROM 'LEGACY_OCCUPIED' THEN + RAISE EXCEPTION 'Retained tenant mapping cannot claim a fresh source-bound key' + USING ERRCODE = '23514', CONSTRAINT = 'chk_gs_retained_fresh_tenant_scope_denied'; + END IF; + + INSERT INTO game_session_tenant_canonical_claim + (target_namespace, canonical_tenant_id, legacy_game_session_tenant_id, + association_kind, reservation_kind, association_operation_id, association_request_id) + VALUES + (NEW.target_namespace, NEW.canonical_tenant_id, NEW.legacy_game_session_tenant_id, + 'RETAINED_V8_1', 'LEGACY_OCCUPIED', NEW.operation_id, NEW.association_request_id) + ON CONFLICT DO NOTHING; + + IF NOT EXISTS ( + SELECT 1 + FROM game_session_tenant_canonical_claim + WHERE target_namespace = NEW.target_namespace + AND canonical_tenant_id = NEW.canonical_tenant_id + AND legacy_game_session_tenant_id = NEW.legacy_game_session_tenant_id + AND association_kind = 'RETAINED_V8_1' + AND reservation_kind = 'LEGACY_OCCUPIED' + AND association_operation_id = NEW.operation_id + AND association_request_id = NEW.association_request_id + ) THEN + RAISE EXCEPTION 'Retained tenant mapping conflicts with a Game Session owner claim' + USING ERRCODE = '23505', CONSTRAINT = 'pk_gs_tenant_canonical_claim'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER game_session_retained_association_claim + BEFORE INSERT ON game_session_retained_tenant_association + FOR EACH ROW EXECUTE FUNCTION claim_retained_game_session_tenant_identity(); + +DO $$ +DECLARE + scope_table RECORD; + scope_count INTEGER := 0; + max_reserved_tenant BIGINT; + identity_sequence TEXT; +BEGIN + FOR scope_table IN + SELECT column_info.table_name + FROM information_schema.columns column_info + JOIN information_schema.tables table_info + ON table_info.table_schema = column_info.table_schema + AND table_info.table_name = column_info.table_name + WHERE column_info.table_schema = current_schema() + AND column_info.column_name = 'tenant_id' + AND table_info.table_type = 'BASE TABLE' + GROUP BY column_info.table_name + ORDER BY column_info.table_name + LOOP + scope_count := scope_count + 1; + EXECUTE format( + 'CREATE TRIGGER reserve_game_session_tenant_scope ' + || 'BEFORE INSERT OR UPDATE ON %I ' + || 'FOR EACH ROW EXECUTE FUNCTION reserve_game_session_tenant_scope()', + scope_table.table_name); + EXECUTE format( + 'INSERT INTO game_session_tenant_scope_reservation ' + || '(game_session_tenant_id, reservation_kind) ' + || 'SELECT DISTINCT tenant_id, ''LEGACY_OCCUPIED'' FROM %I ' + || 'WHERE tenant_id IS NOT NULL ' + || 'ON CONFLICT (game_session_tenant_id) DO NOTHING', + scope_table.table_name); + EXECUTE format( + 'ALTER TABLE %I ADD CONSTRAINT fk_tenant_scope_reservation ' + || 'FOREIGN KEY (tenant_id) REFERENCES game_session_tenant_scope_reservation ' + || '(game_session_tenant_id) NOT VALID', + scope_table.table_name); + EXECUTE format( + 'ALTER TABLE %I VALIDATE CONSTRAINT fk_tenant_scope_reservation', + scope_table.table_name); + END LOOP; + + IF scope_count = 0 THEN + RAISE EXCEPTION 'No Game Session tenant scope tables were found'; + END IF; + + INSERT INTO game_session_tenant_scope_reservation + (game_session_tenant_id, reservation_kind) + SELECT DISTINCT legacy_game_session_tenant_id, 'LEGACY_OCCUPIED' + FROM game_session_retained_tenant_association + ON CONFLICT (game_session_tenant_id) DO NOTHING; + + ALTER TABLE game_session_retained_tenant_association + ADD CONSTRAINT fk_gs_retained_tenant_reservation + FOREIGN KEY (legacy_game_session_tenant_id) + REFERENCES game_session_tenant_scope_reservation (game_session_tenant_id) NOT VALID; + ALTER TABLE game_session_retained_tenant_association + VALIDATE CONSTRAINT fk_gs_retained_tenant_reservation; + + INSERT INTO game_session_tenant_canonical_claim + (target_namespace, canonical_tenant_id, legacy_game_session_tenant_id, + association_kind, reservation_kind, association_operation_id, association_request_id) + SELECT target_namespace, canonical_tenant_id, legacy_game_session_tenant_id, + 'RETAINED_V8_1', 'LEGACY_OCCUPIED', operation_id, association_request_id + FROM game_session_retained_tenant_association + ON CONFLICT DO NOTHING; + + IF EXISTS ( + SELECT 1 + FROM game_session_retained_tenant_association retained + WHERE NOT EXISTS ( + SELECT 1 + FROM game_session_tenant_canonical_claim claim + WHERE claim.target_namespace = retained.target_namespace + AND claim.canonical_tenant_id = retained.canonical_tenant_id + AND claim.legacy_game_session_tenant_id = retained.legacy_game_session_tenant_id + AND claim.association_kind = 'RETAINED_V8_1' + AND claim.reservation_kind = 'LEGACY_OCCUPIED' + AND claim.association_operation_id = retained.operation_id + AND claim.association_request_id = retained.association_request_id + ) + ) THEN + RAISE EXCEPTION 'Retained Game Session identity could not be claimed exactly'; + END IF; + + SELECT max(game_session_tenant_id) + INTO max_reserved_tenant + FROM game_session_tenant_scope_reservation; + identity_sequence := pg_get_serial_sequence( + 'game_session_tenant_scope_reservation', 'game_session_tenant_id'); + IF identity_sequence IS NULL THEN + RAISE EXCEPTION 'Game Session tenant reservation identity sequence is unavailable'; + ELSIF max_reserved_tenant IS NULL THEN + PERFORM setval(identity_sequence, 1, FALSE); + ELSE + PERFORM setval(identity_sequence, max_reserved_tenant, TRUE); + END IF; +END; +$$; +-- [jooq ignore stop] diff --git a/services/game-session-service/src/main/resources/db/migration/V16__canonical_launch_association.sql b/services/game-session-service/src/main/resources/db/migration/V16__canonical_launch_association.sql new file mode 100644 index 0000000000..d93752b851 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V16__canonical_launch_association.sql @@ -0,0 +1,407 @@ +-- A launch association is durable Game Session owner evidence, not World lifecycle authority. +-- Historical instances are intentionally neither inferred nor backfilled. +ALTER TABLE game_session_fresh_tenant_association + ADD CONSTRAINT uq_gs_fresh_tenant_association_launch_identity + UNIQUE (target_namespace, association_operation_id, association_request_id, + source_schema_version, source_target_namespace, source_request_id, + source_canonical_tenant_id, canonical_tenant_id, + legacy_game_session_tenant_id, source_game_row_id, + source_game_tenant_key, provenance_kind, association_kind); + +ALTER TABLE game_instances + ADD CONSTRAINT uq_game_instances_tenant_id_id UNIQUE (tenant_id, id); + +CREATE TABLE game_session_canonical_instance_launch ( + target_namespace VARCHAR(63) NOT NULL, + control_plane_request_id VARCHAR(128) NOT NULL, + game_session_tenant_id BIGINT NOT NULL, + canonical_tenant_id UUID NOT NULL, + tenant_association_operation_id UUID NOT NULL, + tenant_association_request_id UUID NOT NULL, + tenant_source_schema_version INTEGER NOT NULL, + tenant_source_target_namespace VARCHAR(63) NOT NULL, + tenant_source_request_id UUID NOT NULL, + tenant_source_canonical_tenant_id UUID NOT NULL, + tenant_source_game_row_id BIGINT NOT NULL, + tenant_source_game_tenant_key VARCHAR(72) NOT NULL, + tenant_source_provenance_kind VARCHAR(32) NOT NULL, + tenant_association_kind VARCHAR(32) NOT NULL, + game_instance_id BIGINT NOT NULL, + game_instance_uuid UUID NOT NULL, + canonical_realm_id UUID NOT NULL, + world_slug VARCHAR(120) NOT NULL, + playable_state_namespace_id UUID NOT NULL, + playable_state_scope VARCHAR(16) NOT NULL, + public_production BOOLEAN NOT NULL, + captured_starting_row_version BIGINT NOT NULL, + game_template_id BIGINT NOT NULL, + launch_descriptor_id VARCHAR(128) NOT NULL, + version_id BIGINT NOT NULL, + release_bundle_id BIGINT NOT NULL, + generation_config_revision VARCHAR(128) NOT NULL, + version_state_epoch BIGINT NOT NULL, + complete_launch_binding_evidence JSONB NOT NULL, + captured_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_game_session_canonical_instance_launch + PRIMARY KEY (target_namespace, control_plane_request_id), + CONSTRAINT uq_gs_canonical_instance_launch_uuid + UNIQUE (target_namespace, game_instance_uuid), + CONSTRAINT uq_gs_canonical_instance_launch_runtime + UNIQUE (game_session_tenant_id, game_instance_id), + CONSTRAINT fk_gs_canonical_instance_launch_fresh_identity + FOREIGN KEY (target_namespace, tenant_association_operation_id, + tenant_association_request_id, tenant_source_schema_version, + tenant_source_target_namespace, tenant_source_request_id, + tenant_source_canonical_tenant_id, canonical_tenant_id, + game_session_tenant_id, tenant_source_game_row_id, + tenant_source_game_tenant_key, tenant_source_provenance_kind, + tenant_association_kind) + REFERENCES game_session_fresh_tenant_association + (target_namespace, association_operation_id, association_request_id, + source_schema_version, source_target_namespace, source_request_id, + source_canonical_tenant_id, canonical_tenant_id, + legacy_game_session_tenant_id, source_game_row_id, + source_game_tenant_key, provenance_kind, association_kind), + CONSTRAINT fk_gs_canonical_instance_launch_claim + FOREIGN KEY (target_namespace, canonical_tenant_id, game_session_tenant_id, + tenant_association_operation_id, tenant_association_kind) + REFERENCES game_session_tenant_canonical_claim + (target_namespace, canonical_tenant_id, legacy_game_session_tenant_id, + association_operation_id, association_kind), + CONSTRAINT fk_gs_canonical_instance_launch_runtime + FOREIGN KEY (game_session_tenant_id, game_instance_id) + REFERENCES game_instances (tenant_id, id), + CONSTRAINT fk_gs_canonical_instance_launch_realm + FOREIGN KEY (target_namespace, canonical_realm_id) + REFERENCES game_session_canonical_realm_catalog (target_namespace, realm_id), + CONSTRAINT chk_gs_canonical_instance_launch_namespace CHECK ( + octet_length(target_namespace) BETWEEN 1 AND 63 + AND target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND tenant_source_target_namespace = target_namespace + ), + CONSTRAINT chk_gs_canonical_instance_launch_request CHECK ( + char_length(control_plane_request_id) BETWEEN 1 AND 128 + AND control_plane_request_id !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gs_canonical_instance_launch_source_identity CHECK ( + tenant_association_kind = 'FRESH_SOURCE_BOUND' + AND tenant_source_schema_version = 1 + AND tenant_association_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND tenant_association_request_id = tenant_source_request_id + AND canonical_tenant_id = tenant_source_canonical_tenant_id + AND tenant_source_provenance_kind = 'NEW_GAME_ROW' + AND tenant_source_game_row_id > 0 + AND char_length(tenant_source_game_tenant_key) BETWEEN 1 AND 72 + AND tenant_source_game_tenant_key !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gs_canonical_instance_launch_ids CHECK ( + game_session_tenant_id > 0 + AND game_instance_id > 0 + AND game_template_id > 0 + AND version_id > 0 + AND release_bundle_id > 0 + AND version_state_epoch > 0 + AND captured_starting_row_version >= 0 + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND tenant_association_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND game_instance_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_realm_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT chk_gs_canonical_instance_launch_world CHECK ( + octet_length(world_slug) BETWEEN 1 AND 120 + AND world_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + ), + CONSTRAINT chk_gs_canonical_instance_launch_owner_scope CHECK ( + playable_state_scope = 'SHARED' AND public_production + ), + CONSTRAINT chk_gs_canonical_instance_launch_binding CHECK ( + char_length(launch_descriptor_id) BETWEEN 1 AND 128 + AND launch_descriptor_id !~ '^[[:space:]]*$' + AND char_length(generation_config_revision) BETWEEN 1 AND 128 + AND generation_config_revision !~ '^[[:space:]]*$' + AND jsonb_typeof(complete_launch_binding_evidence) = 'object' + AND jsonb_typeof(complete_launch_binding_evidence -> 'descriptor') = 'object' + AND jsonb_typeof(complete_launch_binding_evidence -> 'releaseAttestation') = 'object' + ) +); + +-- A fresh tenant key can own a GameInstance, but no other numeric-only tenant writer may claim it. +-- [jooq ignore start] +CREATE FUNCTION require_starting_game_instance_for_launch_association() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + runtime_row game_instances%ROWTYPE; + descriptor JSONB; +BEGIN + SELECT * INTO runtime_row + FROM game_instances + WHERE tenant_id = NEW.game_session_tenant_id + AND id = NEW.game_instance_id + FOR UPDATE; + IF NOT FOUND OR runtime_row.status IS DISTINCT FROM 'STARTING' + OR runtime_row.row_version IS DISTINCT FROM NEW.captured_starting_row_version + OR runtime_row.game_instance_uuid IS DISTINCT FROM NEW.game_instance_uuid + OR runtime_row.run_owned_start_request_id IS DISTINCT FROM NEW.control_plane_request_id + OR runtime_row.run_owned_start_published_release_bundle_ref IS DISTINCT FROM + (NEW.complete_launch_binding_evidence -> 'descriptor' ->> 'publishedReleaseBundleRef') THEN + RAISE EXCEPTION 'Launch association requires the exact persisted run-owned STARTING row' + USING ERRCODE = '23514', + CONSTRAINT = 'chk_gs_launch_association_starting_row_required'; + END IF; + + descriptor := NEW.complete_launch_binding_evidence -> 'descriptor'; + IF descriptor ->> 'targetNamespace' IS DISTINCT FROM NEW.target_namespace + OR descriptor ->> 'controlPlaneRequestId' IS DISTINCT FROM NEW.control_plane_request_id + OR descriptor ->> 'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::text + OR descriptor ->> 'worldSlug' IS DISTINCT FROM NEW.world_slug + OR descriptor ->> 'gameTemplateId' IS DISTINCT FROM NEW.game_template_id::text + OR descriptor ->> 'launchDescriptorId' IS DISTINCT FROM NEW.launch_descriptor_id + OR descriptor ->> 'versionId' IS DISTINCT FROM NEW.version_id::text + OR descriptor ->> 'releaseBundleId' IS DISTINCT FROM NEW.release_bundle_id::text + OR descriptor ->> 'generationConfigRevision' IS DISTINCT FROM NEW.generation_config_revision + OR descriptor ->> 'versionStateEpoch' IS DISTINCT FROM NEW.version_state_epoch::text + OR runtime_row.game_template_id IS DISTINCT FROM NEW.game_template_id + OR runtime_row.launch_descriptor_id IS DISTINCT FROM NEW.launch_descriptor_id + OR runtime_row.version_id IS DISTINCT FROM NEW.version_id + OR runtime_row.release_bundle_id IS DISTINCT FROM NEW.release_bundle_id + OR runtime_row.generation_config_revision IS DISTINCT FROM NEW.generation_config_revision + OR runtime_row.version_state_epoch IS DISTINCT FROM NEW.version_state_epoch THEN + RAISE EXCEPTION 'Launch association differs from its complete descriptor binding' + USING ERRCODE = '23514', + CONSTRAINT = 'chk_gs_launch_association_descriptor_binding'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER game_session_canonical_instance_launch_starting_owner + BEFORE INSERT ON game_session_canonical_instance_launch + FOR EACH ROW EXECUTE FUNCTION require_starting_game_instance_for_launch_association(); + +CREATE OR REPLACE FUNCTION reserve_game_session_tenant_scope() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + current_kind VARCHAR(32); +BEGIN + IF TG_OP = 'UPDATE' AND NEW.tenant_id IS NOT DISTINCT FROM OLD.tenant_id THEN + RETURN NEW; + END IF; + IF NEW.tenant_id IS NULL THEN + RETURN NEW; + END IF; + IF NEW.tenant_id <= 0 THEN + RAISE EXCEPTION 'Game Session tenant scope must be positive' + USING ERRCODE = '23514', CONSTRAINT = 'chk_gs_tenant_scope_reservation_positive'; + END IF; + + INSERT INTO game_session_tenant_scope_reservation + (game_session_tenant_id, reservation_kind) + VALUES (NEW.tenant_id, 'LEGACY_OCCUPIED') + ON CONFLICT (game_session_tenant_id) DO NOTHING; + + SELECT reservation_kind INTO current_kind + FROM game_session_tenant_scope_reservation + WHERE game_session_tenant_id = NEW.tenant_id + FOR KEY SHARE; + + IF current_kind = 'FRESH_SOURCE_BOUND' AND TG_TABLE_NAME = 'game_instances' + AND EXISTS ( + SELECT 1 + FROM game_session_tenant_canonical_claim claim + JOIN game_session_fresh_tenant_association association + ON association.target_namespace = claim.target_namespace + AND association.canonical_tenant_id = claim.canonical_tenant_id + AND association.legacy_game_session_tenant_id = claim.legacy_game_session_tenant_id + AND association.association_operation_id = claim.association_operation_id + AND association.association_kind = claim.association_kind + WHERE claim.legacy_game_session_tenant_id = NEW.tenant_id + AND claim.association_kind = 'FRESH_SOURCE_BOUND' + AND association.association_kind = 'FRESH_SOURCE_BOUND' + ) THEN + RETURN NEW; + END IF; + + IF current_kind IS DISTINCT FROM 'LEGACY_OCCUPIED' THEN + RAISE EXCEPTION 'Numeric-only tenant scope cannot use a fresh source-bound key' + USING ERRCODE = '23514', CONSTRAINT = 'chk_gs_numeric_fresh_tenant_scope_denied'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION guard_fresh_game_instance_owner_write() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + current_kind VARCHAR(32); + previous_kind VARCHAR(32); +BEGIN + IF TG_OP = 'UPDATE' AND NEW.tenant_id IS DISTINCT FROM OLD.tenant_id THEN + SELECT reservation_kind INTO previous_kind + FROM game_session_tenant_scope_reservation + WHERE game_session_tenant_id = OLD.tenant_id; + IF previous_kind = 'FRESH_SOURCE_BOUND' THEN + RAISE EXCEPTION 'Fresh Game Session instance tenant scope is immutable' + USING ERRCODE = '23514', + CONSTRAINT = 'chk_gs_instance_fresh_tenant_scope_immutable'; + END IF; + END IF; + + SELECT reservation_kind INTO current_kind + FROM game_session_tenant_scope_reservation + WHERE game_session_tenant_id = NEW.tenant_id + FOR KEY SHARE; + IF current_kind IS DISTINCT FROM 'FRESH_SOURCE_BOUND' THEN + RETURN NEW; + END IF; + + IF NOT EXISTS ( + SELECT 1 + FROM game_session_tenant_canonical_claim claim + JOIN game_session_fresh_tenant_association association + ON association.target_namespace = claim.target_namespace + AND association.canonical_tenant_id = claim.canonical_tenant_id + AND association.legacy_game_session_tenant_id = claim.legacy_game_session_tenant_id + AND association.association_operation_id = claim.association_operation_id + AND association.association_kind = claim.association_kind + WHERE claim.legacy_game_session_tenant_id = NEW.tenant_id + AND claim.association_kind = 'FRESH_SOURCE_BOUND' + AND association.association_kind = 'FRESH_SOURCE_BOUND' + ) THEN + RAISE EXCEPTION 'Fresh Game Session instance requires exact persisted source identity' + USING ERRCODE = '23514', + CONSTRAINT = 'chk_gs_instance_fresh_tenant_owner_missing'; + END IF; + + IF TG_OP = 'INSERT' + AND (NEW.status IS DISTINCT FROM 'STARTING' + OR NEW.run_owned_start_request_id IS NULL + OR NEW.run_owned_start_published_release_bundle_ref IS NULL) THEN + RAISE EXCEPTION 'Fresh Game Session runtime row must be owner-created in STARTING' + USING ERRCODE = '23514', + CONSTRAINT = 'chk_gs_instance_fresh_starting_owner_required'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER game_instances_fresh_canonical_owner_guard + BEFORE INSERT OR UPDATE ON game_instances + FOR EACH ROW EXECUTE FUNCTION guard_fresh_game_instance_owner_write(); + +CREATE FUNCTION require_complete_game_instance_launch_association() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + runtime_row game_instances%ROWTYPE; + reservation_type VARCHAR(32); + match_count BIGINT; +BEGIN + SELECT * INTO runtime_row FROM game_instances WHERE id = NEW.id; + IF NOT FOUND THEN + RETURN NULL; + END IF; + + SELECT reservation_kind INTO reservation_type + FROM game_session_tenant_scope_reservation + WHERE game_session_tenant_id = runtime_row.tenant_id; + IF reservation_type IS DISTINCT FROM 'FRESH_SOURCE_BOUND' THEN + RETURN NULL; + END IF; + + SELECT count(*) INTO match_count + FROM game_session_canonical_instance_launch launch + JOIN game_session_fresh_tenant_association fresh + ON fresh.target_namespace = launch.target_namespace + AND fresh.association_operation_id = launch.tenant_association_operation_id + AND fresh.association_request_id = launch.tenant_association_request_id + AND fresh.source_schema_version = launch.tenant_source_schema_version + AND fresh.source_target_namespace = launch.tenant_source_target_namespace + AND fresh.source_request_id = launch.tenant_source_request_id + AND fresh.source_canonical_tenant_id = launch.tenant_source_canonical_tenant_id + AND fresh.canonical_tenant_id = launch.canonical_tenant_id + AND fresh.legacy_game_session_tenant_id = launch.game_session_tenant_id + AND fresh.source_game_row_id = launch.tenant_source_game_row_id + AND fresh.source_game_tenant_key = launch.tenant_source_game_tenant_key + AND fresh.provenance_kind = launch.tenant_source_provenance_kind + AND fresh.association_kind = launch.tenant_association_kind + JOIN game_session_canonical_realm_catalog realm + ON realm.target_namespace = launch.target_namespace + AND realm.realm_id = launch.canonical_realm_id + WHERE launch.target_namespace = realm.target_namespace + AND launch.game_session_tenant_id = runtime_row.tenant_id + AND launch.game_instance_id = runtime_row.id + AND launch.game_instance_uuid = runtime_row.game_instance_uuid + AND launch.canonical_tenant_id = fresh.canonical_tenant_id + AND realm.canonical_tenant_id = launch.canonical_tenant_id + AND launch.world_slug = realm.world_slug + AND launch.playable_state_namespace_id = realm.playable_state_namespace_id + AND realm.visible AND realm.public_production AND realm.state_scope = 'SHARED' + AND launch.playable_state_scope = 'SHARED' AND launch.public_production + AND launch.game_template_id = runtime_row.game_template_id + AND launch.launch_descriptor_id = runtime_row.launch_descriptor_id + AND launch.version_id = runtime_row.version_id + AND launch.release_bundle_id = runtime_row.release_bundle_id + AND launch.generation_config_revision = runtime_row.generation_config_revision + AND launch.version_state_epoch = runtime_row.version_state_epoch + AND launch.control_plane_request_id = runtime_row.run_owned_start_request_id + AND launch.captured_starting_row_version <= runtime_row.row_version + AND runtime_row.run_owned_start_published_release_bundle_ref = + launch.complete_launch_binding_evidence -> 'descriptor' ->> 'publishedReleaseBundleRef' + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'targetNamespace' = launch.target_namespace + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'controlPlaneRequestId' + = launch.control_plane_request_id + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'canonicalTenantId' + = launch.canonical_tenant_id::text + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'worldSlug' = launch.world_slug + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'launchDescriptorId' + = launch.launch_descriptor_id + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'gameTemplateId' + = launch.game_template_id::text + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'versionId' + = launch.version_id::text + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'releaseBundleId' + = launch.release_bundle_id::text + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'generationConfigRevision' + = launch.generation_config_revision + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'versionStateEpoch' + = launch.version_state_epoch::text; + + IF match_count <> 1 THEN + RAISE EXCEPTION 'Fresh Game Session instance requires one exact complete launch association' + USING ERRCODE = '23514', + CONSTRAINT = 'chk_gs_instance_complete_launch_association_required'; + END IF; + RETURN NULL; +END; +$$; + +CREATE CONSTRAINT TRIGGER game_instances_complete_launch_association_required + AFTER INSERT OR UPDATE ON game_instances + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION require_complete_game_instance_launch_association(); + +CREATE FUNCTION reject_game_session_canonical_instance_launch_mutation() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Game Session canonical instance launch evidence is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'gs_canonical_instance_launch_immutable'; +END; +$$; + +CREATE TRIGGER game_session_canonical_instance_launch_immutable + BEFORE UPDATE OR DELETE ON game_session_canonical_instance_launch + FOR EACH ROW EXECUTE FUNCTION reject_game_session_canonical_instance_launch_mutation(); +CREATE TRIGGER game_session_canonical_instance_launch_no_truncate + BEFORE TRUNCATE ON game_session_canonical_instance_launch + FOR EACH STATEMENT EXECUTE FUNCTION reject_game_session_canonical_instance_launch_mutation(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationIntegrationTest.java new file mode 100644 index 0000000000..32ebb84d2d --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationIntegrationTest.java @@ -0,0 +1,688 @@ +package integration.net.firedevops.firemud.gamesession.repository; + +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.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.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.RuntimeTenantIdentityEvidence; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; +import net.firedevops.firemud.gamesession.client.GameDesignRuntimeTenantIdentityClient; +import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalLaunchPreparationRequest; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalRealmCatalogRequest; +import net.firedevops.firemud.gamesession.entity.GameInstance; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import net.firedevops.firemud.gamesession.repository.FreshGameSessionTenantAssociationRepository; +import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalLaunchPreparationRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import net.firedevops.firemud.gamesession.service.CanonicalStartingGameInstanceOwner; +import net.firedevops.firemud.gamesession.service.FreshGameSessionTenantAssociation; +import net.firedevops.firemud.gamesession.service.FreshGameSessionTenantAssociationService; +import net.firedevops.firemud.gamesession.service.GameSessionCanonicalLaunchPreparationService; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class CanonicalGameInstanceLaunchAssociationIntegrationTest { + private static final String NAMESPACE = "canonical-launch-association-it"; + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void capturesAnExistingRunOwnedStartingRowThroughTheExactFreshOwnerMapping() { + String schema = "gs_launch_assoc_capture_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.postgresql.Driver"); + dataSource.setUrl(postgres.getJdbcUrl() + "?currentSchema=" + schema); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + try { + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + DataSourceTransactionManager transactionManager = + new DataSourceTransactionManager(dataSource); + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + GameSessionAuthoredWorldSourceRepository sourceRepository = + new GameSessionAuthoredWorldSourceRepository(dsl); + GameSessionCanonicalRealmCatalogRepository catalogRepository = + new GameSessionCanonicalRealmCatalogRepository(dsl); + var intake = + transaction.execute(status -> sourceRepository.register(uuid(4), sourceEvidence())); + assertThat(intake).isNotNull(); + CreateCanonicalRealmCatalogRequest catalogRequest = + new CreateCanonicalRealmCatalogRequest( + uuid(5), + NAMESPACE, + uuid(2), + intake.operationId(), + "owner-realm", + "Owner Realm", + true, + true, + "SHARED", + "explicit-policy-v1", + null, + null); + var preparedCatalog = catalogRepository.prepareInitialPublicProduction(catalogRequest); + CanonicalRealmCatalogSnapshot createdCatalog = + transaction.execute( + status -> catalogRepository.createInitialPublicProduction(preparedCatalog)); + assertThat(createdCatalog).isNotNull(); + + var tenantRepository = + new FreshGameSessionTenantAssociationRepository(dsl, transactionManager, NAMESPACE); + FreshGameSessionTenantAssociation tenant = + tenantRepository.registerAndReadback( + new RuntimeTenantIdentityEvidence( + 1, + NAMESPACE, + uuid(6), + uuid(2), + intake.source().sourceGameRowId(), + intake.source().sourceGameTenantKey(), + "NEW_GAME_ROW")); + CompleteLaunchBindingEvidence binding = launchBinding(intake); + GameInstance instance = startingInstance(tenant, binding); + GameInstanceRepository instances = new GameInstanceRepository(dsl); + CanonicalGameInstanceLaunchAssociationRepository associations = + new CanonicalGameInstanceLaunchAssociationRepository(dsl, NAMESPACE); + + CanonicalGameInstanceLaunchAssociation captured = + transaction.execute( + status -> { + GameInstance saved = instances.save(instance); + return associations.capture(tenant, saved.getId(), binding); + }); + + assertThat(captured).isNotNull(); + assertThat(captured.tenantAssociationOperationId()) + .isEqualTo(tenant.associationOperationId()); + assertThat(captured.capturedStartingRowVersion()).isZero(); + assertThat(captured.currentGameInstanceStatus()) + .isEqualTo(CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus.STARTING); + assertThat(associations.read(binding.descriptor().controlPlaneRequestId())) + .contains(captured); + } finally { + dropSchema(schema); + } + } + + @Test + void canonicalStartingOwnerCreatesStartingInstanceAndCapturesAssociationAtomically() { + StartingOwnerFixture fixture = startingOwnerFixture(); + try { + assertThat( + fixture + .sourceRepository() + .read( + fixture.intake().operationId(), + fixture.request().canonicalTenantId(), + fixture.intake().source().worldSlug(), + NAMESPACE)) + .contains(fixture.intake()); + assertThat( + fixture + .catalogRepository() + .readByRequest(NAMESPACE, fixture.catalog().creationRequestId())) + .contains(fixture.catalog()); + + CanonicalGameInstanceLaunchAssociation created = + fixture.owner().createStartingInstance(fixture.request(), fixture.associationRequestId()); + Record instance = + fixture + .dsl() + .fetchOne( + "SELECT * FROM game_instances WHERE tenant_id = ? " + + "AND run_owned_start_request_id = ?", + created.gameSessionTenantId(), + fixture.request().controlPlaneRequestId()); + assertThat(instance).isNotNull(); + assertThat(instance.get("status", String.class)).isEqualTo("STARTING"); + assertThat(instance.get("game_instance_uuid", UUID.class)) + .isEqualTo(created.gameInstanceUuid()); + assertThat(instance.get("row_version", Long.class)).isEqualTo(0L); + assertThat(instance.get("owner_account_uuid", UUID.class)) + .isEqualTo(fixture.request().actingAccountUuid()); + assertThat(instance.get("run_owned_start_request_id", String.class)) + .isEqualTo(fixture.request().controlPlaneRequestId()); + assertThat( + fixture + .dsl() + .fetchCount(DSL.table(DSL.name("game_session_canonical_instance_launch")))) + .isEqualTo(1); + assertThat( + fixture + .dsl() + .fetchCount(DSL.table(DSL.name("game_session_canonical_launch_preparation")))) + .isEqualTo(1); + assertThat(fixture.launchAssociations().read(fixture.request().controlPlaneRequestId())) + .contains(created); + assertThat(created.currentGameInstanceStatus()) + .isEqualTo(CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus.STARTING); + assertThat(created.capturedStartingRowVersion()).isZero(); + assertThat(created.launchBindingEvidence()).isEqualTo(fixture.binding()); + } finally { + dropSchema(fixture.schema()); + } + } + + @Test + void exactStartingOwnerRetryPreservesTheOriginalInstanceAndAssociation() { + StartingOwnerFixture fixture = startingOwnerFixture(); + try { + CanonicalGameInstanceLaunchAssociation first = + fixture.owner().createStartingInstance(fixture.request(), fixture.associationRequestId()); + Record originalInstance = instanceRow(fixture); + Record originalAssociation = associationRow(fixture); + + CanonicalGameInstanceLaunchAssociation retry = + fixture.owner().createStartingInstance(fixture.request(), fixture.associationRequestId()); + + assertThat(retry).isEqualTo(first); + assertThat(instanceRow(fixture)).isEqualTo(originalInstance); + assertThat(associationRow(fixture)).isEqualTo(originalAssociation); + assertThat(fixture.dsl().fetchCount(DSL.table(DSL.name("game_instances")))).isEqualTo(1); + assertThat( + fixture + .dsl() + .fetchCount(DSL.table(DSL.name("game_session_canonical_instance_launch")))) + .isEqualTo(1); + verify(fixture.descriptorClient(), times(1)).resolve(any()); + verify(fixture.descriptorClient(), times(1)).get(any(GetRequest.class)); + verify(fixture.descriptorClient(), times(2)) + .getComplete(any(GetLaunchDescriptorRequest.class)); + } finally { + dropSchema(fixture.schema()); + } + } + + @Test + void changedCompleteDescriptorAttestationPairConflictsWithoutPartialMutation() { + StartingOwnerFixture fixture = startingOwnerFixture(); + try { + fixture.owner().createStartingInstance(fixture.request(), fixture.associationRequestId()); + Record originalInstance = instanceRow(fixture); + Record originalAssociation = associationRow(fixture); + CompleteLaunchBindingEvidence changedPair = launchBinding(fixture.intake(), uuid(11)); + assertThat(changedPair.descriptor()).isEqualTo(fixture.binding().descriptor()); + assertThat(changedPair.releaseAttestation()) + .isNotEqualTo(fixture.binding().releaseAttestation()); + when(fixture.descriptorClient().getComplete(any(GetLaunchDescriptorRequest.class))) + .thenReturn(changedPair); + + assertThatThrownBy( + () -> + fixture + .owner() + .createStartingInstance(fixture.request(), fixture.associationRequestId())) + .isInstanceOf( + CanonicalGameInstanceLaunchAssociationRepository + .CanonicalGameInstanceLaunchAssociationConflictException.class) + .hasMessageContaining("changed tenant, instance, or source binding"); + + assertThat(instanceRow(fixture)).isEqualTo(originalInstance); + assertThat(associationRow(fixture)).isEqualTo(originalAssociation); + assertThat(fixture.dsl().fetchCount(DSL.table(DSL.name("game_instances")))).isEqualTo(1); + assertThat( + fixture + .dsl() + .fetchCount(DSL.table(DSL.name("game_session_canonical_instance_launch")))) + .isEqualTo(1); + assertThat( + fixture + .dsl() + .fetchCount(DSL.table(DSL.name("game_session_canonical_launch_preparation")))) + .isEqualTo(1); + } finally { + dropSchema(fixture.schema()); + } + } + + @Test + void freshStartingInstanceCannotCommitWithoutItsExactLaunchAssociation() { + String schema = "gs_launch_assoc_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.postgresql.Driver"); + dataSource.setUrl(postgres.getJdbcUrl() + "?currentSchema=" + schema); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + try { + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + DataSourceTransactionManager transactionManager = + new DataSourceTransactionManager(dataSource); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + FreshGameSessionTenantAssociationRepository tenantRepository = + new FreshGameSessionTenantAssociationRepository(dsl, transactionManager, NAMESPACE); + FreshGameSessionTenantAssociation tenant = + tenantRepository.registerAndReadback( + new RuntimeTenantIdentityEvidence( + 1, + NAMESPACE, + uuid(1), + uuid(2), + 9_001L, + "source-game-tenant-9002", + "NEW_GAME_ROW")); + GameInstance instance = startingInstance(tenant); + GameInstanceRepository instances = new GameInstanceRepository(dsl); + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + + assertThatThrownBy(() -> transaction.execute(status -> instances.save(instance))) + .hasRootCauseMessage( + "Fresh Game Session instance requires one exact complete launch association"); + Record gameInstanceCountRow = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM game_instances WHERE tenant_id = ?", + tenant.legacyGameSessionTenantId()), + "game instance count query must return one row"); + assertThat( + Objects.requireNonNull( + gameInstanceCountRow.get(0, Long.class), "game instance count must be present")) + .isZero(); + + GameInstance legacy = new GameInstance(); + legacy.setTenantId(99_001L); + legacy.setRuntimeVersion("legacy-row"); + legacy.setOwnerAccountId(uuid(3).toString()); + legacy.setStatus("STOPPED"); + GameInstance savedLegacy = transaction.execute(status -> instances.save(legacy)); + assertThat(savedLegacy).isNotNull(); + } finally { + dropSchema(schema); + } + } + + private static void dropSchema(String schema) { + try (var connection = + java.sql.DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + var statement = connection.createStatement()) { + statement.execute("DROP SCHEMA IF EXISTS " + schema + " CASCADE"); + } catch (Exception failure) { + throw new IllegalStateException("Failed to dispose canonical launch test schema", failure); + } + } + + private static AuthoredWorldSourceEvidence sourceEvidence() { + String worldSlug = "owner-world"; + String tenantSlug = "owner-tenant"; + String displayName = "Owner World"; + UUID registrationRequestId = uuid(7); + UUID sourceOperationId = uuid(8); + long sourceGameRowId = 9_001L; + String sourceGameTenantKey = "source-game-tenant-9002"; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registrationRequestId, uuid(2), tenantSlug, worldSlug, displayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequestId, + sourceOperationId, + requestDigest, + uuid(2), + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceGameTenantKey, + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequestId, + sourceOperationId, + requestDigest, + uuid(2), + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceGameTenantKey, + "NEW_GAME_ROW", + evidenceDigest); + } + + private static CompleteLaunchBindingEvidence launchBinding( + GameSessionAuthoredWorldSourceRepository.IntakeReceipt intake) { + return launchBinding(intake, uuid(10)); + } + + private static CompleteLaunchBindingEvidence launchBinding( + GameSessionAuthoredWorldSourceRepository.IntakeReceipt intake, UUID attestationRequestId) { + AuthoredWorldSourceEvidence source = intake.source(); + String requestId = "launch-request-1"; + var descriptorRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + requestId, + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + 801L, + false, + null, + false, + null, + false, + null, + false, + null); + var descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + descriptorRequest, + "launch-descriptor-1", + 902L, + false, + null, + "{}", + "generation-4", + 4L, + 903L, + "prb:tenant:902:903", + false, + null); + List participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + "902", + false, + null, + "publish-commit-902", + "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "d".repeat(64) : null)) + .toList(); + var attestation = + AuthoredWorldReleaseAttestationEvidence.create( + NAMESPACE, + descriptor.resultDigest(), + source.canonicalTenantId(), + attestationRequestId, + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + "publish-workflow-1", + "publish-commit-902", + participants, + "sha256:" + "b".repeat(64), + 1, + List.of(), + List.of(), + List.of(), + descriptor.generationConfigRevision()); + return new CompleteLaunchBindingEvidence(descriptor, attestation); + } + + private static GameInstance startingInstance( + FreshGameSessionTenantAssociation tenant, CompleteLaunchBindingEvidence binding) { + GameInstance instance = new GameInstance(); + instance.setTenantId(tenant.legacyGameSessionTenantId()); + instance.setRuntimeVersion("owner-created-starting-row"); + instance.setOwnerAccountId(uuid(3).toString()); + instance.setStatus("STARTING"); + instance.setGameTemplateId(binding.descriptor().gameTemplateId()); + instance.setLaunchDescriptorId(binding.descriptor().launchDescriptorId()); + instance.setVersionId(binding.descriptor().versionId()); + instance.setReleaseBundleId(binding.descriptor().releaseBundleId()); + instance.setVersionStateEpoch(binding.descriptor().versionStateEpoch()); + instance.setGenerationConfigRevision(binding.descriptor().generationConfigRevision()); + instance.setRunOwnedStartRequestId(binding.descriptor().controlPlaneRequestId()); + instance.setRunOwnedStartRequestDigest("a".repeat(64)); + instance.setRunOwnedStartPublishedReleaseBundleRef( + binding.descriptor().publishedReleaseBundleRef()); + return instance; + } + + private static GameInstance startingInstance(FreshGameSessionTenantAssociation tenant) { + GameInstance instance = new GameInstance(); + instance.setTenantId(tenant.legacyGameSessionTenantId()); + instance.setRuntimeVersion("owner-created-starting-row"); + instance.setOwnerAccountId(uuid(3).toString()); + instance.setStatus("STARTING"); + instance.setGameTemplateId(801L); + instance.setLaunchDescriptorId("launch-descriptor-1"); + instance.setVersionId(902L); + instance.setReleaseBundleId(903L); + instance.setVersionStateEpoch(4L); + instance.setGenerationConfigRevision("generation-4"); + instance.setRunOwnedStartRequestId("launch-request-1"); + instance.setRunOwnedStartRequestDigest("a".repeat(64)); + instance.setRunOwnedStartPublishedReleaseBundleRef("prb:tenant:902:903"); + return instance; + } + + private static UUID uuid(long value) { + return new UUID(0x123e4567e89b12d3L, value); + } + + private static StartingOwnerFixture startingOwnerFixture() { + String schema = "gs_starting_owner_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.postgresql.Driver"); + dataSource.setUrl(postgres.getJdbcUrl() + "?currentSchema=" + schema); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + GameSessionAuthoredWorldSourceRepository sourceRepository = + new GameSessionAuthoredWorldSourceRepository(dsl); + GameSessionCanonicalRealmCatalogRepository catalogRepository = + new GameSessionCanonicalRealmCatalogRepository(dsl); + var intake = + transaction.execute(status -> sourceRepository.register(uuid(4), sourceEvidence())); + assertThat(intake).isNotNull(); + UUID catalogRequestId = uuid(5); + var preparedCatalog = + catalogRepository.prepareInitialPublicProduction( + new CreateCanonicalRealmCatalogRequest( + catalogRequestId, + NAMESPACE, + uuid(2), + intake.operationId(), + "owner-realm", + "Owner Realm", + true, + true, + "SHARED", + "explicit-policy-v1", + null, + null)); + CanonicalRealmCatalogSnapshot catalog = + transaction.execute( + status -> catalogRepository.createInitialPublicProduction(preparedCatalog)); + assertThat(catalog).isNotNull(); + + UUID associationRequestId = uuid(6); + RuntimeTenantIdentityEvidence tenantEvidence = + new RuntimeTenantIdentityEvidence( + 1, + NAMESPACE, + associationRequestId, + uuid(2), + intake.source().sourceGameRowId(), + intake.source().sourceGameTenantKey(), + "NEW_GAME_ROW"); + GameDesignRuntimeTenantIdentityClient tenantIdentityClient = + mock(GameDesignRuntimeTenantIdentityClient.class); + when(tenantIdentityClient.resolveRuntimeTenantIdentity(anyString(), anyString())) + .thenReturn(tenantEvidence); + var tenantAssociationService = + new FreshGameSessionTenantAssociationService( + tenantIdentityClient, + new FreshGameSessionTenantAssociationRepository(dsl, transactionManager, NAMESPACE), + NAMESPACE); + + CompleteLaunchBindingEvidence binding = launchBinding(intake); + AuthoredWorldLaunchDescriptorClient descriptorClient = + mock(AuthoredWorldLaunchDescriptorClient.class); + when(descriptorClient.resolve(any(AuthoredWorldLaunchDescriptorEvidence.Request.class))) + .thenReturn(binding.descriptor()); + when(descriptorClient.get(any(GetRequest.class))).thenReturn(binding.descriptor()); + when(descriptorClient.getComplete(any(GetLaunchDescriptorRequest.class))).thenReturn(binding); + GameSessionCanonicalLaunchPreparationRepository preparationRepository = + new GameSessionCanonicalLaunchPreparationRepository(dsl, catalogRepository); + GameSessionCanonicalLaunchPreparationService preparationService = + new GameSessionCanonicalLaunchPreparationService( + descriptorClient, + catalogRepository, + sourceRepository, + preparationRepository, + transactionManager, + NAMESPACE); + CreateCanonicalLaunchPreparationRequest request = + new CreateCanonicalLaunchPreparationRequest( + binding.descriptor().controlPlaneRequestId(), + uuid(3), + NAMESPACE, + uuid(2), + catalog.realmId(), + catalogRequestId, + catalog.catalogRevision(), + intake.operationId(), + binding.descriptor().gameTemplateId(), + false, + null, + false, + null, + false, + null, + false, + null); + CanonicalGameInstanceLaunchAssociationRepository launchAssociations = + new CanonicalGameInstanceLaunchAssociationRepository(dsl, NAMESPACE); + GameInstanceRepository instances = new GameInstanceRepository(dsl); + CanonicalStartingGameInstanceOwner owner = + new CanonicalStartingGameInstanceOwner( + tenantAssociationService, + preparationService, + launchAssociations, + instances, + transactionManager, + NAMESPACE); + + // These mocks stop at Game Design's authenticated tenant and descriptor reads. They provide + // deterministic owner evidence only; this fixture is not mTLS, Account authorization, World, + // lifecycle, or gameplay-admission proof. + return new StartingOwnerFixture( + schema, + dsl, + intake, + catalog, + sourceRepository, + catalogRepository, + associationRequestId, + request, + binding, + descriptorClient, + launchAssociations, + owner); + } + + private static Record instanceRow(StartingOwnerFixture fixture) { + CanonicalGameInstanceLaunchAssociation association = + fixture.launchAssociations().read(fixture.request().controlPlaneRequestId()).orElseThrow(); + return fixture + .dsl() + .fetchOne( + "SELECT * FROM game_instances WHERE tenant_id = ? " + + "AND run_owned_start_request_id = ?", + association.gameSessionTenantId(), + fixture.request().controlPlaneRequestId()); + } + + private static Record associationRow(StartingOwnerFixture fixture) { + return fixture + .dsl() + .fetchOne( + "SELECT * FROM game_session_canonical_instance_launch " + + "WHERE target_namespace = ? AND control_plane_request_id = ?", + NAMESPACE, + fixture.request().controlPlaneRequestId()); + } + + private record StartingOwnerFixture( + String schema, + DSLContext dsl, + GameSessionAuthoredWorldSourceRepository.IntakeReceipt intake, + CanonicalRealmCatalogSnapshot catalog, + GameSessionAuthoredWorldSourceRepository sourceRepository, + GameSessionCanonicalRealmCatalogRepository catalogRepository, + UUID associationRequestId, + CreateCanonicalLaunchPreparationRequest request, + CompleteLaunchBindingEvidence binding, + AuthoredWorldLaunchDescriptorClient descriptorClient, + CanonicalGameInstanceLaunchAssociationRepository launchAssociations, + CanonicalStartingGameInstanceOwner owner) {} +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/FreshGameSessionTenantAssociationIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/FreshGameSessionTenantAssociationIntegrationTest.java new file mode 100644 index 0000000000..c7c1c4d196 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/FreshGameSessionTenantAssociationIntegrationTest.java @@ -0,0 +1,488 @@ +package integration.net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.net.URI; +import java.nio.file.Path; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Objects; +import java.util.Properties; +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.TimeoutException; +import net.firedevops.firemud.common.tenant.RuntimeTenantIdentityEvidence; +import net.firedevops.firemud.gamesession.repository.FreshGameSessionTenantAssociationRepository; +import net.firedevops.firemud.gamesession.repository.FreshGameSessionTenantAssociationRepository.FreshTenantAssociationConflictException; +import net.firedevops.firemud.gamesession.service.FreshGameSessionTenantAssociation; +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.AfterAll; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.DockerClientFactory; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.utility.DockerImageName; + +@SuppressWarnings("resource") +class FreshGameSessionTenantAssociationIntegrationTest { + private static final String NAMESPACE = "fresh-tenant-association-test"; + private static final String POSTGRES_URL_ENV = "FIREMUD_ACCOUNT_SIGNER_TEST_POSTGRES_URL"; + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + private static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(DockerImageName.parse("postgres:16-alpine")); + private static String postgresJdbcUrl; + private static String postgresUsername; + private static String postgresPassword; + private static boolean externalPostgres; + private static boolean startedOwnedContainer; + + @BeforeAll + static void configureDatabase() { + String externalUrl = System.getenv(POSTGRES_URL_ENV); + if (externalUrl != null) { + postgresJdbcUrl = validateExternalLoopbackPostgresUrl(externalUrl); + postgresUsername = "postgres"; + postgresPassword = ""; + externalPostgres = true; + return; + } + Assumptions.assumeTrue( + DockerClientFactory.instance().isDockerAvailable(), "PostgreSQL proof requires Docker"); + POSTGRES.start(); + startedOwnedContainer = true; + postgresJdbcUrl = POSTGRES.getJdbcUrl(); + postgresUsername = POSTGRES.getUsername(); + postgresPassword = POSTGRES.getPassword(); + } + + @AfterAll + static void stopOwnedContainer() { + if (startedOwnedContainer) { + POSTGRES.stop(); + } + } + + @Test + void migrationFencesExistingScopesAndFreshAssociationIsExactImmutableAndRaceSafe() + throws Exception { + try (TestSchema database = new TestSchema("gs_fresh_tenant_")) { + DriverManagerDataSource dataSource = database.dataSource(); + migrateThroughV14(dataSource, database.schema()); + DSLContext seedDsl = DSL.using(dataSource, SQLDialect.POSTGRES); + seedPreV15ScopesAndRetainedAssociation(seedDsl); + migrateLatest(dataSource, database.schema()); + + DSLContext migrationDsl = DSL.using(dataSource, SQLDialect.POSTGRES); + org.jooq.Record tenantScopeTableCountRow = + Objects.requireNonNull( + migrationDsl.fetchOne( + "SELECT count(DISTINCT table_name) FROM information_schema.columns " + + "WHERE table_schema = current_schema() AND column_name = 'tenant_id'"), + "tenant scope table count query must return one row"); + int tenantScopeTables = + Objects.requireNonNull( + tenantScopeTableCountRow.get(0, Integer.class), + "tenant scope table count must be present"); + org.jooq.Record reservationForeignKeyCountRow = + Objects.requireNonNull( + migrationDsl.fetchOne( + "SELECT count(*) FROM information_schema.table_constraints " + + "WHERE table_schema = current_schema() AND constraint_type = 'FOREIGN KEY' " + + "AND constraint_name = 'fk_tenant_scope_reservation'"), + "reservation foreign key count query must return one row"); + int reservedScopeForeignKeys = + Objects.requireNonNull( + reservationForeignKeyCountRow.get(0, Integer.class), + "reservation foreign key count must be present"); + assertThat(tenantScopeTables).isPositive(); + assertThat(reservedScopeForeignKeys).isEqualTo(tenantScopeTables); + assertThat(reservationKind(migrationDsl, 701L)).isEqualTo("LEGACY_OCCUPIED"); + assertThat(reservationKind(migrationDsl, 702L)).isEqualTo("LEGACY_OCCUPIED"); + assertThat(reservationKind(migrationDsl, 812L)).isEqualTo("LEGACY_OCCUPIED"); + org.jooq.Record retainedAssociationRow = + Objects.requireNonNull( + migrationDsl.fetchOne( + "SELECT association_kind FROM game_session_tenant_canonical_claim " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + NAMESPACE, + uuid(3)), + "retained association query must return one row"); + assertThat( + Objects.requireNonNull( + retainedAssociationRow.get(0, String.class), + "retained association kind must be present")) + .isEqualTo("RETAINED_V8_1"); + + DataSourceTransactionManager transactionManager = + new DataSourceTransactionManager(dataSource); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + FreshGameSessionTenantAssociationRepository repository = + new FreshGameSessionTenantAssociationRepository(dsl, transactionManager, NAMESPACE); + + RuntimeTenantIdentityEvidence evidence = freshEvidence(uuid(1), uuid(2), 9_001L, "9002"); + FreshGameSessionTenantAssociation association = repository.registerAndReadback(evidence); + assertThat(association.legacyGameSessionTenantId()) + .isNotIn(evidence.sourceGameRowId(), 9_002L); + assertThat(reservationKind(dsl, association.legacyGameSessionTenantId())) + .isEqualTo("FRESH_SOURCE_BOUND"); + assertThat(repository.readByRequestCommitted(evidence.requestId())).contains(association); + assertThat(repository.registerAndReadback(evidence)).isEqualTo(association); + + RuntimeTenantIdentityEvidence changedRetry = + freshEvidence(evidence.requestId(), evidence.canonicalTenantId(), 9_003L, "other-source"); + assertThatThrownBy(() -> repository.registerAndReadback(changedRetry)) + .isInstanceOf(FreshTenantAssociationConflictException.class); + RuntimeTenantIdentityEvidence canonicalConflict = + freshEvidence(uuid(4), evidence.canonicalTenantId(), 9_004L, "different-source"); + assertThatThrownBy(() -> repository.registerAndReadback(canonicalConflict)) + .isInstanceOf(FreshTenantAssociationConflictException.class); + + assertThatThrownBy( + () -> + dsl.execute( + "INSERT INTO feature_flag (id, tenant_id, name, enabled) " + + "VALUES (2, ?, 'numeric-fresh-use', true)", + association.legacyGameSessionTenantId())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("Numeric-only tenant scope cannot use a fresh source-bound key"); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE feature_flag SET tenant_id = ? WHERE id = 1", + association.legacyGameSessionTenantId())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("Numeric-only tenant scope cannot use a fresh source-bound key"); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE game_session_fresh_tenant_association " + + "SET source_game_tenant_key = ? WHERE association_operation_id = ?", + "changed-source", + association.associationOperationId())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("owner evidence is immutable"); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE game_session_tenant_canonical_claim SET association_kind = ? " + + "WHERE association_operation_id = ?", + "RETAINED_V8_1", + association.associationOperationId())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("owner evidence is immutable"); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE game_session_tenant_scope_reservation SET reservation_kind = ? " + + "WHERE game_session_tenant_id = ?", + "LEGACY_OCCUPIED", + association.legacyGameSessionTenantId())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("owner evidence is immutable"); + + insertRetainedAssociation(dsl, uuid(5), uuid(6), 820L, uuid(7)); + assertThat(reservationKind(dsl, 820L)).isEqualTo("LEGACY_OCCUPIED"); + org.jooq.Record concurrentlyRetainedAssociationRow = + Objects.requireNonNull( + migrationDsl.fetchOne( + "SELECT association_kind FROM game_session_tenant_canonical_claim " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + NAMESPACE, + uuid(7)), + "concurrently retained association query must return one row"); + assertThat( + Objects.requireNonNull( + concurrentlyRetainedAssociationRow.get(0, String.class), + "concurrently retained association kind must be present")) + .isEqualTo("RETAINED_V8_1"); + + verifyConcurrentExactRetry(repository); + verifyLegacyScopeWinsConcurrentAllocation(dsl, transactionManager, repository); + } + } + + private static void verifyConcurrentExactRetry( + FreshGameSessionTenantAssociationRepository repository) throws Exception { + RuntimeTenantIdentityEvidence evidence = + freshEvidence(uuid(8), uuid(9), 9_005L, "future-source"); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit( + () -> { + start.await(); + return repository.registerAndReadback(evidence); + }); + Future second = + executor.submit( + () -> { + start.await(); + return repository.registerAndReadback(evidence); + }); + start.countDown(); + assertThat(first.get(20, TimeUnit.SECONDS)).isEqualTo(second.get(20, TimeUnit.SECONDS)); + } finally { + executor.shutdownNow(); + } + } + + private static void verifyLegacyScopeWinsConcurrentAllocation( + DSLContext dsl, + DataSourceTransactionManager transactionManager, + FreshGameSessionTenantAssociationRepository repository) + throws Exception { + org.jooq.Record sequenceNameRow = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT pg_get_serial_sequence(" + + "'game_session_tenant_scope_reservation', 'game_session_tenant_id')"), + "reservation sequence lookup must return one row"); + String sequence = + Objects.requireNonNull( + sequenceNameRow.get(0, String.class), "reservation sequence name must be present"); + org.jooq.Record sequenceState = + Objects.requireNonNull( + dsl.fetchOne("SELECT last_value, is_called FROM " + sequence), + "reservation sequence state query must return one row"); + Long sequenceLastValue = + Objects.requireNonNull( + sequenceState.get("last_value", Long.class), + "reservation sequence last value must be present"); + long candidate = + Boolean.TRUE.equals(sequenceState.get("is_called", Boolean.class)) + ? sequenceLastValue + 1L + : 1L; + + CountDownLatch legacyReserved = new CountDownLatch(1); + CountDownLatch permitLegacyCommit = new CountDownLatch(1); + TransactionTemplate legacyTransaction = new TransactionTemplate(transactionManager); + legacyTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future legacyWriter = + executor.submit( + () -> + legacyTransaction.execute( + status -> { + dsl.execute( + "INSERT INTO feature_flag (id, tenant_id, name, enabled) " + + "VALUES (3, ?, 'concurrent-legacy-scope', true)", + candidate); + legacyReserved.countDown(); + await(permitLegacyCommit, "legacy scope commit"); + return null; + })); + await(legacyReserved, "legacy scope reservation"); + + RuntimeTenantIdentityEvidence evidence = freshEvidence(uuid(31), uuid(32), 9_101L, "9102"); + Future freshWriter = + executor.submit(() -> repository.registerAndReadback(evidence)); + assertThatThrownBy(() -> freshWriter.get(100, TimeUnit.MILLISECONDS)) + .isInstanceOf(TimeoutException.class); + permitLegacyCommit.countDown(); + legacyWriter.get(20, TimeUnit.SECONDS); + FreshGameSessionTenantAssociation association = freshWriter.get(20, TimeUnit.SECONDS); + assertThat(association.legacyGameSessionTenantId()).isNotEqualTo(candidate); + assertThat(reservationKind(dsl, candidate)).isEqualTo("LEGACY_OCCUPIED"); + assertThat(reservationKind(dsl, association.legacyGameSessionTenantId())) + .isEqualTo("FRESH_SOURCE_BOUND"); + } finally { + permitLegacyCommit.countDown(); + executor.shutdownNow(); + } + } + + private static void await(CountDownLatch latch, String label) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting for " + label); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted while waiting for " + label, exception); + } + } + + private static void seedPreV15ScopesAndRetainedAssociation(DSLContext dsl) { + dsl.execute( + "INSERT INTO feature_flag (id, tenant_id, name, enabled) " + + "VALUES (1, 701, 'legacy-feature', false)"); + dsl.execute( + "INSERT INTO game_instances (id, tenant_id, runtime_version, owner_account_id, status) " + + "VALUES (1, 702, 'legacy-runtime', 9007, 'STOPPED')"); + insertRetainedAssociation(dsl, uuid(10), uuid(11), 812L, uuid(3)); + } + + private static void insertRetainedAssociation( + DSLContext dsl, UUID operationId, UUID requestId, long tenantId, UUID canonicalTenantId) { + dsl.execute( + "INSERT INTO game_session_retained_tenant_association (" + + "operation_id, approval_schema_version, target_namespace, association_request_id, " + + "request_digest, approval_operation_id, signer_key_id, approved_by, " + + "approval_reference, signed_at, legacy_game_session_tenant_id, " + + "canonical_tenant_id, source_game_row_id, source_game_tenant_key, provenance_kind, " + + "game_session_evidence_digest, approval_manifest_digest, approval_signature, " + + "snapshot_canonical_json, snapshot_evidence_digest, receipt_digest) " + + "VALUES (?, 1, ?, ?, ?, ?, 'test-key', 'test-reviewer', 'fixture', " + + "'2026-01-01T00:00:00Z', ?, ?, 501, 'retained-source-key', 'RETAINED_GAME_V30', " + + "?, ?, ?, '{}', ?, ?)", + operationId, + NAMESPACE, + requestId, + digest('a'), + uuid(12), + tenantId, + canonicalTenantId, + digest('b'), + digest('c'), + "A".repeat(86) + "==", + digest('d'), + digest('e'), + digest('f')); + } + + private static RuntimeTenantIdentityEvidence freshEvidence( + UUID requestId, UUID tenantId, long sourceRowId, String sourceTenantKey) { + return new RuntimeTenantIdentityEvidence( + 1, NAMESPACE, requestId, tenantId, sourceRowId, sourceTenantKey, "NEW_GAME_ROW"); + } + + private static String reservationKind(DSLContext dsl, long tenantId) { + org.jooq.Record reservationRow = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT reservation_kind FROM game_session_tenant_scope_reservation " + + "WHERE game_session_tenant_id = ?", + tenantId), + "reservation lookup must return one row"); + return Objects.requireNonNull( + reservationRow.get(0, String.class), "reservation kind must be present"); + } + + private static String digest(char character) { + return "sha256:" + String.valueOf(character).repeat(64); + } + + private static void migrateThroughV14(DriverManagerDataSource dataSource, String schema) { + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .target(MigrationVersion.fromVersion("14")) + .load() + .migrate(); + } + + private static void migrateLatest(DriverManagerDataSource dataSource, String schema) { + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + } + + private static String validateExternalLoopbackPostgresUrl(String jdbcUrl) { + final URI uri; + try { + if (!jdbcUrl.startsWith("jdbc:")) { + throw new IllegalArgumentException("not a JDBC URL"); + } + uri = URI.create(jdbcUrl.substring("jdbc:".length())); + } catch (RuntimeException malformed) { + throw new IllegalStateException( + POSTGRES_URL_ENV + " must target jdbc:postgresql://127.0.0.1:/postgres", malformed); + } + if (!"postgresql".equals(uri.getScheme()) + || !"127.0.0.1".equals(uri.getHost()) + || uri.getPort() < 1 + || uri.getPort() > 65_535 + || !"/postgres".equals(uri.getPath()) + || uri.getRawUserInfo() != null + || uri.getRawQuery() != null + || uri.getRawFragment() != null) { + throw new IllegalStateException( + POSTGRES_URL_ENV + " must target jdbc:postgresql://127.0.0.1:/postgres"); + } + return jdbcUrl; + } + + private static UUID uuid(long value) { + return new UUID(0x123e4567e89b12d3L, value); + } + + private static final class TestSchema implements AutoCloseable { + private final String schema; + + private TestSchema(String prefix) { + schema = prefix + UUID.randomUUID().toString().replace("-", ""); + } + + private String schema() { + return schema; + } + + private DriverManagerDataSource dataSource() { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.postgresql.Driver"); + String separator = postgresJdbcUrl.contains("?") ? "&" : "?"; + dataSource.setUrl(postgresJdbcUrl + separator + "currentSchema=" + schema); + dataSource.setUsername(postgresUsername); + dataSource.setPassword(postgresPassword); + configureExternalConnectionProperties(dataSource); + return dataSource; + } + + @Override + public void close() { + DriverManagerDataSource adminDataSource = new DriverManagerDataSource(); + adminDataSource.setDriverClassName("org.postgresql.Driver"); + adminDataSource.setUrl(postgresJdbcUrl); + adminDataSource.setUsername(postgresUsername); + adminDataSource.setPassword(postgresPassword); + configureExternalConnectionProperties(adminDataSource); + try (Connection connection = adminDataSource.getConnection(); + Statement statement = connection.createStatement()) { + statement.execute("DROP SCHEMA IF EXISTS " + schema + " CASCADE"); + } catch (SQLException failure) { + throw new IllegalStateException("Failed to drop isolated test schema " + schema, failure); + } + } + } + + private static void configureExternalConnectionProperties(DriverManagerDataSource dataSource) { + if (!externalPostgres) { + return; + } + Properties properties = new Properties(); + properties.setProperty("connectTimeout", "10"); + properties.setProperty("socketTimeout", "60"); + properties.setProperty("sslmode", "disable"); + properties.setProperty("gssEncMode", "disable"); + dataSource.setConnectionProperties(properties); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameInstanceLaunchAssociationTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameInstanceLaunchAssociationTest.java new file mode 100644 index 0000000000..5308699e5c --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameInstanceLaunchAssociationTest.java @@ -0,0 +1,189 @@ +package unit.net.firedevops.firemud.gamesession.dto; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; +import org.junit.jupiter.api.Test; + +class CanonicalGameInstanceLaunchAssociationTest { + private static final String NAMESPACE = "launch-owner"; + private static final UUID TENANT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID INSTANCE_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID ASSOCIATION_ID = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID STATE_NAMESPACE_ID = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + + @Test + void retainsTheCompleteBindingAndSeparatesCapturedFromCurrentOwnerProjection() { + CompleteLaunchBindingEvidence evidence = evidence(); + CanonicalGameInstanceLaunchAssociation association = + new CanonicalGameInstanceLaunchAssociation( + NAMESPACE, + 701L, + ASSOCIATION_ID, + TENANT_ID, + INSTANCE_ID, + "earth", + STATE_NAMESPACE_ID, + RealmEntryPolicy.StateScope.SHARED, + true, + "launch-request-1", + "descriptor-902", + 3L, + evidence, + CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus.RUNNING, + 8L); + + assertThat(association.capturedStartingRowVersion()).isEqualTo(3L); + assertThat(association.currentRowVersion()).isEqualTo(8L); + assertThat(association.currentGameInstanceStatus()) + .isEqualTo(CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus.RUNNING); + assertThat(association.launchBindingEvidence()).isSameAs(evidence); + } + + @Test + void rejectsNonSharedAndNonProductionLaunchAssociations() { + assertThatThrownBy( + () -> association(evidence(), RealmEntryPolicy.StateScope.ISOLATED, true, 3L, 3L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("SHARED"); + assertThatThrownBy( + () -> association(evidence(), RealmEntryPolicy.StateScope.SHARED, false, 3L, 3L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("public production"); + } + + @Test + void rejectsSelectorsAndCurrentRowVersionsThatDifferFromTheOwnerEvidence() { + assertThatThrownBy( + () -> + new CanonicalGameInstanceLaunchAssociation( + NAMESPACE, + 701L, + ASSOCIATION_ID, + TENANT_ID, + INSTANCE_ID, + "mars", + STATE_NAMESPACE_ID, + RealmEntryPolicy.StateScope.SHARED, + true, + "launch-request-1", + "descriptor-902", + 3L, + evidence(), + CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus.STARTING, + 3L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("does not match"); + assertThatThrownBy( + () -> association(evidence(), RealmEntryPolicy.StateScope.SHARED, true, 4L, 3L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("must not precede"); + } + + private static CanonicalGameInstanceLaunchAssociation association( + CompleteLaunchBindingEvidence evidence, + RealmEntryPolicy.StateScope scope, + boolean publicProduction, + long capturedVersion, + long currentVersion) { + return new CanonicalGameInstanceLaunchAssociation( + NAMESPACE, + 701L, + ASSOCIATION_ID, + TENANT_ID, + INSTANCE_ID, + "earth", + STATE_NAMESPACE_ID, + scope, + publicProduction, + "launch-request-1", + "descriptor-902", + capturedVersion, + evidence, + CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus.STARTING, + currentVersion); + } + + private static CompleteLaunchBindingEvidence evidence() { + UUID sourceOperationId = UUID.fromString("55555555-5555-4555-8555-555555555555"); + String sourceEvidenceDigest = "sha256:" + "a".repeat(64); + AuthoredWorldLaunchDescriptorEvidence.Request request = + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + "launch-request-1", + TENANT_ID, + "earth", + sourceOperationId, + sourceEvidenceDigest, + 810L, + false, + null, + false, + null, + false, + null, + false, + null); + AuthoredWorldLaunchDescriptorEvidence descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + request, + "descriptor-902", + 902L, + false, + null, + "{}", + "generation-4", + 4L, + 903L, + "prb:tenant:902:903", + false, + null); + List participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + "902", + false, + null, + "publish-commit-902", + "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "d".repeat(64) : null)) + .toList(); + AuthoredWorldReleaseAttestationEvidence attestation = + AuthoredWorldReleaseAttestationEvidence.create( + NAMESPACE, + descriptor.resultDigest(), + TENANT_ID, + UUID.fromString("66666666-6666-4666-8666-666666666666"), + "earth", + sourceOperationId, + sourceEvidenceDigest, + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + "publish:tenant:version:request", + "publish-commit-902", + participants, + "sha256:" + "b".repeat(64), + 1, + List.of(), + List.of(), + List.of(), + descriptor.generationConfigRevision()); + return new CompleteLaunchBindingEvidence(descriptor, attestation); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepositoryTest.java new file mode 100644 index 0000000000..d8e97a1639 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepositoryTest.java @@ -0,0 +1,63 @@ +package unit.net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.util.UUID; +import net.firedevops.firemud.common.tenant.RuntimeTenantIdentityEvidence; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import net.firedevops.firemud.gamesession.service.FreshGameSessionTenantAssociation; +import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class CanonicalGameInstanceLaunchAssociationRepositoryTest { + private static final String NAMESPACE = "launch-owner"; + + @AfterEach + void clearTransactionContext() { + TransactionSynchronizationManager.clear(); + } + + @Test + void captureRequiresAWritableOwnerTransactionBeforeReadingAnyRuntimeRow() { + DSLContext dsl = mock(DSLContext.class); + var repository = new CanonicalGameInstanceLaunchAssociationRepository(dsl, NAMESPACE); + var tenant = freshTenant(); + + assertThatThrownBy(() -> repository.capture(tenant, 92L, null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable owner transaction"); + + verifyNoInteractions(dsl); + } + + @Test + void committedReadCannotBeComposedInsideAnotherOwnerTransaction() { + DSLContext dsl = mock(DSLContext.class); + var repository = new CanonicalGameInstanceLaunchAssociationRepository(dsl, NAMESPACE); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy(() -> repository.read("launch-request-1")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("committed owner read"); + + verifyNoInteractions(dsl); + } + + private static FreshGameSessionTenantAssociation freshTenant() { + RuntimeTenantIdentityEvidence source = + new RuntimeTenantIdentityEvidence( + 1, + NAMESPACE, + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("22222222-2222-4222-8222-222222222222"), + 1L, + "source-game-tenant-key", + "NEW_GAME_ROW"); + return new FreshGameSessionTenantAssociation( + UUID.fromString("33333333-3333-4333-8333-333333333333"), 701L, source); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalStartingGameInstanceOwnerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalStartingGameInstanceOwnerTest.java new file mode 100644 index 0000000000..2fa4e707c4 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalStartingGameInstanceOwnerTest.java @@ -0,0 +1,694 @@ +package unit.net.firedevops.firemud.gamesession.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.anyLong; +import static org.mockito.Mockito.doAnswer; +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.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +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.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.RuntimeTenantIdentityEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; +import net.firedevops.firemud.gamesession.dto.CanonicalLaunchPreparationSnapshot; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalLaunchPreparationRequest; +import net.firedevops.firemud.gamesession.entity.GameInstance; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldIntakeDigest; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalLaunchPreparationRepository; +import net.firedevops.firemud.gamesession.service.CanonicalStartingGameInstanceOwner; +import net.firedevops.firemud.gamesession.service.FreshGameSessionTenantAssociation; +import net.firedevops.firemud.gamesession.service.FreshGameSessionTenantAssociationService; +import net.firedevops.firemud.gamesession.service.GameSessionCanonicalLaunchPreparationService; +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 CanonicalStartingGameInstanceOwnerTest { + private static final String NAMESPACE = "starting-owner-test"; + private static final UUID TENANT = uuid(1); + private static final UUID REALM = uuid(2); + private static final UUID CATALOG_REQUEST = uuid(3); + private static final UUID SOURCE_INTAKE_OPERATION = uuid(4); + private static final UUID INTAKE_REQUEST = uuid(5); + private static final UUID SOURCE_REGISTRATION_REQUEST = uuid(6); + private static final UUID SOURCE_OPERATION = uuid(7); + private static final UUID ACTING_ACCOUNT = uuid(8); + private static final UUID ASSOCIATION_REQUEST = uuid(9); + private static final UUID TENANT_ASSOCIATION_OPERATION = uuid(10); + private static final UUID INSTANCE_UUID = uuid(11); + private static final long GAME_SESSION_TENANT_ID = 901L; + private static final long SOURCE_GAME_ROW_ID = 9_001L; + private static final String SOURCE_GAME_TENANT_KEY = "gd-private-tenant-9002"; + private static final String CONTROL_PLANE_REQUEST = "canonical-start-1"; + private static final long GAME_TEMPLATE_ID = 71L; + private static final long INSTANCE_ID = 902L; + + private final FreshGameSessionTenantAssociationService tenantAssociationService = + mock(FreshGameSessionTenantAssociationService.class); + private final GameSessionCanonicalLaunchPreparationService launchPreparationService = + mock(GameSessionCanonicalLaunchPreparationService.class); + private final CanonicalGameInstanceLaunchAssociationRepository launchAssociationRepository = + mock(CanonicalGameInstanceLaunchAssociationRepository.class); + private final GameInstanceRepository gameInstanceRepository = mock(GameInstanceRepository.class); + private final RecordingTransactionManager transactionManager = new RecordingTransactionManager(); + + @AfterEach + void clearTransaction() { + TransactionSynchronizationManager.clear(); + } + + @Test + void createsAndReadsBackAnUnpinnedStartingInstanceWithItsExactCompleteAssociation() { + Fixture fixture = fixture(); + stubComposition(fixture); + AtomicReference persisted = new AtomicReference<>(); + AtomicReference captured = new AtomicReference<>(); + stubOwnerWrite(fixture, persisted, captured, Optional.empty()); + + CanonicalGameInstanceLaunchAssociation result = + owner().createStartingInstance(fixture.request(), ASSOCIATION_REQUEST); + + assertThat(result).isEqualTo(captured.get()); + assertThat(result.launchBindingEvidence()).isEqualTo(fixture.binding()); + assertThat(result.currentGameInstanceStatus()) + .isEqualTo(CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus.STARTING); + assertThat(result.capturedStartingRowVersion()).isZero(); + assertThat(transactionManager.startedWith.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(transactionManager.startedWith.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(transactionManager.startedWith.isReadOnly()).isFalse(); + assertThat(transactionManager.commitCount).isEqualTo(1); + + ArgumentCaptor newInstance = ArgumentCaptor.forClass(GameInstance.class); + verify(gameInstanceRepository).save(newInstance.capture()); + GameInstance candidate = newInstance.getValue(); + assertThat(candidate.getId()).isNull(); + assertThat(candidate.getGameInstanceUuid()).isNull(); + assertThat(candidate.getTenantId()).isEqualTo(GAME_SESSION_TENANT_ID); + assertThat(candidate.getOwnerAccountId()).isEqualTo(ACTING_ACCOUNT.toString()); + assertThat(candidate.getStatus()).isEqualTo("STARTING"); + assertThat(candidate.getRuntimeVersion()) + .isEqualTo(Long.toString(fixture.binding().descriptor().versionId())); + assertThat(candidate.getRunOwnedStartRequestId()).isEqualTo(CONTROL_PLANE_REQUEST); + assertThat(candidate.getRunOwnedStartRequestDigest()) + .isEqualTo(expectedRunOwnedStartDigest(fixture.request())); + assertThat(candidate.getRunOwnedStartPublishedReleaseBundleRef()) + .isEqualTo(fixture.binding().descriptor().publishedReleaseBundleRef()); + assertThat(candidate.getScriptPatchVersion()).isNull(); + assertThat(candidate.getScriptPinEpoch()).isNull(); + assertThat(candidate.getScriptPatchPinnedControlPlaneRequestId()).isNull(); + verify(launchAssociationRepository).lockRequestForStartingGameInstance(CONTROL_PLANE_REQUEST); + verify(launchAssociationRepository) + .capture(fixture.tenantAssociation(), INSTANCE_ID, fixture.binding()); + assertThat(transactionManager.commitCount).isEqualTo(1); + } + + @Test + void exactRetryReusesThePersistedInstanceAndAssociationWithoutSavingAnotherRow() { + Fixture fixture = fixture(); + stubComposition(fixture); + GameInstance existing = persistedInstance(fixture, "STARTING", 0L); + CanonicalGameInstanceLaunchAssociation association = association(fixture, existing, 0L); + AtomicReference persisted = new AtomicReference<>(existing); + AtomicReference captured = + new AtomicReference<>(association); + stubOwnerWrite(fixture, persisted, captured, Optional.of(existing)); + + assertThat(owner().createStartingInstance(fixture.request(), ASSOCIATION_REQUEST)) + .isEqualTo(association); + + verify(gameInstanceRepository, never()).save(any(GameInstance.class)); + verify(launchAssociationRepository) + .capture(fixture.tenantAssociation(), INSTANCE_ID, fixture.binding()); + assertThat(transactionManager.commitCount).isEqualTo(1); + } + + @Test + void changedPersistedOwnerAccountConflictsBeforeCaptureOrMutation() { + Fixture fixture = fixture(); + stubComposition(fixture); + GameInstance changedOwner = persistedInstance(fixture, "STARTING", 0L); + changedOwner.setOwnerAccountId(uuid(99).toString()); + AtomicReference persisted = new AtomicReference<>(changedOwner); + AtomicReference captured = new AtomicReference<>(); + when(gameInstanceRepository.findByTenantIdAndRunOwnedStartRequestIdForUpdate( + GAME_SESSION_TENANT_ID, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.of(changedOwner)); + stubRequestLock(); + + assertThatThrownBy(() -> owner().createStartingInstance(fixture.request(), ASSOCIATION_REQUEST)) + .isInstanceOf( + CanonicalGameInstanceLaunchAssociationRepository + .CanonicalGameInstanceLaunchAssociationConflictException.class) + .hasMessageContaining("conflicts with the persisted owner instance"); + + verify(gameInstanceRepository, never()).save(any(GameInstance.class)); + verify(launchAssociationRepository, never()) + .capture(any(), anyLong(), any(CompleteLaunchBindingEvidence.class)); + assertThat(transactionManager.rollbackCount).isEqualTo(1); + assertThat(persisted.get()).isSameAs(changedOwner); + assertThat(captured.get()).isNull(); + } + + @Test + void changedCompleteBindingOnExactRetryConflictsBeforeCreatingAnotherInstance() { + Fixture fixture = fixture(); + stubComposition(fixture); + CompleteLaunchBindingEvidence changedBinding = + completeBinding(fixture.binding().descriptor(), uuid(15)); + when(launchPreparationService.readCompleteBinding(fixture.preparation())) + .thenReturn(changedBinding); + GameInstance existing = persistedInstance(fixture, "STARTING", 0L); + AtomicReference persisted = new AtomicReference<>(existing); + AtomicReference captured = + new AtomicReference<>(association(fixture, existing, 0L)); + stubOwnerWrite(fixture, persisted, captured, Optional.of(existing)); + when(launchAssociationRepository.capture( + fixture.tenantAssociation(), INSTANCE_ID, changedBinding)) + .thenThrow( + new CanonicalGameInstanceLaunchAssociationRepository + .CanonicalGameInstanceLaunchAssociationConflictException( + "Launch association request was reused with a changed source binding")); + + assertThatThrownBy(() -> owner().createStartingInstance(fixture.request(), ASSOCIATION_REQUEST)) + .isInstanceOf( + CanonicalGameInstanceLaunchAssociationRepository + .CanonicalGameInstanceLaunchAssociationConflictException.class) + .hasMessageContaining("changed source binding"); + + verify(gameInstanceRepository, never()).save(any(GameInstance.class)); + verify(launchAssociationRepository) + .capture(fixture.tenantAssociation(), INSTANCE_ID, changedBinding); + assertThat(transactionManager.rollbackCount).isEqualTo(1); + assertThat(captured.get()).isEqualTo(association(fixture, existing, 0L)); + } + + @Test + void rejectsFreshTenantSourceThatDoesNotJoinThePreparedAuthoredSource() { + Fixture fixture = fixture(); + RuntimeTenantIdentityEvidence changedSource = + new RuntimeTenantIdentityEvidence( + 1, + NAMESPACE, + ASSOCIATION_REQUEST, + TENANT, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY + "-changed", + "NEW_GAME_ROW"); + FreshGameSessionTenantAssociation changedAssociation = + new FreshGameSessionTenantAssociation( + TENANT_ASSOCIATION_OPERATION, GAME_SESSION_TENANT_ID, changedSource); + when(tenantAssociationService.associate(ASSOCIATION_REQUEST, TENANT)) + .thenReturn(changedAssociation); + when(launchPreparationService.prepare(fixture.request())).thenReturn(fixture.preparation()); + + assertThatThrownBy(() -> owner().createStartingInstance(fixture.request(), ASSOCIATION_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("does not match the exact authored-world source intake"); + + verify(launchPreparationService, never()).readCompleteBinding(any()); + verifyNoInteractions(launchAssociationRepository, gameInstanceRepository); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void rejectsAmbientTransactionBeforeAuthenticatedSourceOrPreparationReads() { + Fixture fixture = fixture(); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + + assertThatThrownBy(() -> owner().createStartingInstance(fixture.request(), ASSOCIATION_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient transaction"); + + verifyNoInteractions( + tenantAssociationService, + launchPreparationService, + launchAssociationRepository, + gameInstanceRepository); + assertThat(transactionManager.startedWith).isNull(); + } + + private CanonicalStartingGameInstanceOwner owner() { + return new CanonicalStartingGameInstanceOwner( + tenantAssociationService, + launchPreparationService, + launchAssociationRepository, + gameInstanceRepository, + transactionManager, + NAMESPACE); + } + + private void stubComposition(Fixture fixture) { + when(tenantAssociationService.associate(ASSOCIATION_REQUEST, TENANT)) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return fixture.tenantAssociation(); + }); + when(launchPreparationService.prepare(fixture.request())) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return fixture.preparation(); + }); + when(launchPreparationService.readCompleteBinding(fixture.preparation())) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return fixture.binding(); + }); + } + + private void stubOwnerWrite( + Fixture fixture, + AtomicReference persisted, + AtomicReference captured, + Optional existing) { + stubRequestLock(); + when(gameInstanceRepository.findByTenantIdAndRunOwnedStartRequestIdForUpdate( + GAME_SESSION_TENANT_ID, CONTROL_PLANE_REQUEST)) + .thenReturn(existing); + when(gameInstanceRepository.save(any(GameInstance.class))) + .thenAnswer( + invocation -> { + assertOwnerTransaction(); + GameInstance candidate = invocation.getArgument(0); + assertThat(candidate.getId()).isNull(); + assertThat(candidate.getGameInstanceUuid()).isNull(); + GameInstance stored = persistedInstance(candidate, INSTANCE_ID, INSTANCE_UUID, 0L); + persisted.set(stored); + return stored; + }); + when(launchAssociationRepository.capture( + fixture.tenantAssociation(), INSTANCE_ID, fixture.binding())) + .thenAnswer( + ignored -> { + assertOwnerTransaction(); + CanonicalGameInstanceLaunchAssociation association = + association(fixture, persisted.get(), 0L); + captured.set(association); + return association; + }); + when(launchAssociationRepository.read(CONTROL_PLANE_REQUEST)) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return Optional.ofNullable(captured.get()); + }); + when(gameInstanceRepository.findById(INSTANCE_ID)) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return Optional.ofNullable(persisted.get()); + }); + } + + private void stubRequestLock() { + doAnswer( + ignored -> { + assertOwnerTransaction(); + return null; + }) + .when(launchAssociationRepository) + .lockRequestForStartingGameInstance(CONTROL_PLANE_REQUEST); + } + + private void assertOwnerTransaction() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + } + + private static Fixture fixture() { + AuthoredWorldSourceEvidence source = sourceEvidence(); + IntakeReceipt intake = intake(source); + CanonicalRealmCatalogSnapshot catalog = catalog(intake); + CreateCanonicalLaunchPreparationRequest request = request(); + AuthoredWorldLaunchDescriptorEvidence descriptor = descriptor(request, catalog, source); + String requestDigest = + GameSessionCanonicalLaunchPreparationRepository.requestDigest( + request, catalog, intake, descriptor); + UUID preparationOperationId = uuid(12); + CanonicalLaunchPreparationSnapshot preparation = + new CanonicalLaunchPreparationSnapshot( + preparationOperationId, + request, + catalog, + intake, + descriptor, + requestDigest, + GameSessionCanonicalLaunchPreparationRepository.receiptDigest( + preparationOperationId, request, catalog, intake, descriptor, requestDigest)); + RuntimeTenantIdentityEvidence tenantSource = + new RuntimeTenantIdentityEvidence( + 1, + NAMESPACE, + ASSOCIATION_REQUEST, + TENANT, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + "NEW_GAME_ROW"); + FreshGameSessionTenantAssociation tenantAssociation = + new FreshGameSessionTenantAssociation( + TENANT_ASSOCIATION_OPERATION, GAME_SESSION_TENANT_ID, tenantSource); + return new Fixture(request, preparation, completeBinding(descriptor), tenantAssociation); + } + + private static CreateCanonicalLaunchPreparationRequest request() { + return new CreateCanonicalLaunchPreparationRequest( + CONTROL_PLANE_REQUEST, + ACTING_ACCOUNT, + NAMESPACE, + TENANT, + REALM, + CATALOG_REQUEST, + 1L, + SOURCE_INTAKE_OPERATION, + GAME_TEMPLATE_ID, + false, + null, + false, + null, + false, + null, + false, + null); + } + + private static AuthoredWorldSourceEvidence sourceEvidence() { + String tenantSlug = "owner-tenant"; + String worldSlug = "owner-world"; + String displayName = "Owner World"; + String sourceRequestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, SOURCE_REGISTRATION_REQUEST, TENANT, tenantSlug, worldSlug, displayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + SOURCE_REGISTRATION_REQUEST, + SOURCE_OPERATION, + sourceRequestDigest, + TENANT, + tenantSlug, + worldSlug, + displayName, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + SOURCE_REGISTRATION_REQUEST, + SOURCE_OPERATION, + sourceRequestDigest, + TENANT, + tenantSlug, + worldSlug, + displayName, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + "NEW_GAME_ROW", + evidenceDigest); + } + + private static IntakeReceipt intake(AuthoredWorldSourceEvidence source) { + String requestDigest = + GameSessionAuthoredWorldIntakeDigest.requestDigest(INTAKE_REQUEST, source); + return new IntakeReceipt( + SOURCE_INTAKE_OPERATION, + INTAKE_REQUEST, + requestDigest, + source, + GameSessionAuthoredWorldIntakeDigest.receiptDigest( + SOURCE_INTAKE_OPERATION, requestDigest, source.evidenceDigest())); + } + + private static CanonicalRealmCatalogSnapshot catalog(IntakeReceipt source) { + return new CanonicalRealmCatalogSnapshot( + NAMESPACE, + TENANT, + source.source().tenantSlug(), + source.source().worldSlug(), + REALM, + "owner-realm", + "Owner Realm", + true, + true, + "SHARED", + uuid(13), + "explicit-policy-v1", + 1, + CATALOG_REQUEST, + digest('c'), + digest('d'), + source); + } + + private static AuthoredWorldLaunchDescriptorEvidence descriptor( + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot catalog, + AuthoredWorldSourceEvidence source) { + return AuthoredWorldLaunchDescriptorEvidence.create( + request.descriptorRequest(catalog, source), + "launch-descriptor-1", + 72L, + false, + null, + "{}", + "generation-1", + 3L, + 73L, + "bundle-73", + false, + null); + } + + private static CompleteLaunchBindingEvidence completeBinding( + AuthoredWorldLaunchDescriptorEvidence descriptor) { + return completeBinding(descriptor, uuid(14)); + } + + private static CompleteLaunchBindingEvidence completeBinding( + AuthoredWorldLaunchDescriptorEvidence descriptor, UUID attestationOperationId) { + String commitId = "publish-commit-902"; + List participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptor.versionId()), + false, + null, + commitId, + "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? digest('e') : null)) + .toList(); + AuthoredWorldReleaseAttestationEvidence attestation = + AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + descriptor.canonicalTenantId(), + attestationOperationId, + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + "publish:tenant:version:request", + commitId, + participants, + digest('f'), + 1, + List.of(), + List.of(), + List.of(), + descriptor.generationConfigRevision()); + return new CompleteLaunchBindingEvidence(descriptor, attestation); + } + + private static GameInstance persistedInstance(Fixture fixture, String status, long rowVersion) { + return persistedInstance( + instanceCandidate(fixture), INSTANCE_ID, INSTANCE_UUID, rowVersion, status); + } + + private static GameInstance persistedInstance( + GameInstance candidate, long id, UUID gameInstanceUuid, long rowVersion) { + return persistedInstance(candidate, id, gameInstanceUuid, rowVersion, candidate.getStatus()); + } + + private static GameInstance persistedInstance( + GameInstance candidate, long id, UUID gameInstanceUuid, long rowVersion, String status) { + GameInstance instance = new GameInstance(); + instance.setId(id); + instance.setGameInstanceUuid(gameInstanceUuid); + instance.setTenantId(candidate.getTenantId()); + instance.setRuntimeVersion(candidate.getRuntimeVersion()); + instance.setScriptPatchVersion(candidate.getScriptPatchVersion()); + instance.setScriptPatchBaseVersionId(candidate.getScriptPatchBaseVersionId()); + instance.setScriptPinEpoch(candidate.getScriptPinEpoch()); + instance.setGameTemplateId(candidate.getGameTemplateId()); + instance.setLaunchDescriptorId(candidate.getLaunchDescriptorId()); + instance.setVersionId(candidate.getVersionId()); + instance.setReleaseBundleId(candidate.getReleaseBundleId()); + instance.setVersionStateEpoch(candidate.getVersionStateEpoch()); + instance.setGenerationConfigRevision(candidate.getGenerationConfigRevision()); + instance.setRemapSetId(candidate.getRemapSetId()); + instance.setScriptPatchPinnedControlPlaneRequestId( + candidate.getScriptPatchPinnedControlPlaneRequestId()); + instance.setOwnerAccountId(candidate.getOwnerAccountId()); + instance.setLegacyOwnerAccountId(candidate.getLegacyOwnerAccountId()); + instance.setStatus(status); + instance.setRowVersion(rowVersion); + instance.setRunOwnedStartRequestId(candidate.getRunOwnedStartRequestId()); + instance.setRunOwnedStartRequestDigest(candidate.getRunOwnedStartRequestDigest()); + instance.setRunOwnedStartPublishedReleaseBundleRef( + candidate.getRunOwnedStartPublishedReleaseBundleRef()); + return instance; + } + + private static GameInstance instanceCandidate(Fixture fixture) { + AuthoredWorldLaunchDescriptorEvidence descriptor = fixture.binding().descriptor(); + GameInstance instance = new GameInstance(); + instance.setTenantId(GAME_SESSION_TENANT_ID); + instance.setRuntimeVersion(Long.toString(descriptor.versionId())); + instance.setGameTemplateId(descriptor.gameTemplateId()); + instance.setLaunchDescriptorId(descriptor.launchDescriptorId()); + instance.setVersionId(descriptor.versionId()); + instance.setReleaseBundleId(descriptor.releaseBundleId()); + instance.setVersionStateEpoch(descriptor.versionStateEpoch()); + instance.setGenerationConfigRevision(descriptor.generationConfigRevision()); + instance.setRemapSetId(descriptor.remapSetId()); + instance.setOwnerAccountId(ACTING_ACCOUNT.toString()); + instance.setStatus("STARTING"); + instance.setRunOwnedStartRequestId(CONTROL_PLANE_REQUEST); + instance.setRunOwnedStartRequestDigest(expectedRunOwnedStartDigest(fixture.request())); + instance.setRunOwnedStartPublishedReleaseBundleRef(descriptor.publishedReleaseBundleRef()); + return instance; + } + + private static CanonicalGameInstanceLaunchAssociation association( + Fixture fixture, GameInstance instance, long capturedRowVersion) { + return new CanonicalGameInstanceLaunchAssociation( + NAMESPACE, + GAME_SESSION_TENANT_ID, + TENANT_ASSOCIATION_OPERATION, + TENANT, + instance.getGameInstanceUuid(), + fixture.preparation().catalogSnapshot().worldSlug(), + fixture.preparation().catalogSnapshot().playableStateNamespaceId(), + net.firedevops.firemud.common.publication.RealmEntryPolicy.StateScope.SHARED, + true, + CONTROL_PLANE_REQUEST, + fixture.binding().descriptor().launchDescriptorId(), + capturedRowVersion, + fixture.binding(), + CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus.valueOf( + instance.getStatus()), + instance.getRowVersion()); + } + + private static String expectedRunOwnedStartDigest( + CreateCanonicalLaunchPreparationRequest request) { + StringBuilder preimage = new StringBuilder(); + appendDigestField(preimage, "schema", "firemud.run-owned-initial-launch/v1"); + appendDigestField(preimage, "tenantId", Long.toString(GAME_SESSION_TENANT_ID)); + appendDigestField(preimage, "gameTemplateId", Long.toString(request.gameTemplateId())); + appendDigestField(preimage, "controlPlaneRequestId", request.controlPlaneRequestId()); + appendDigestField(preimage, "ownerAccountId", request.actingAccountUuid().toString()); + appendDigestField(preimage, "replaceExistingFirst", "false"); + try { + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(preimage.toString().getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException(exception); + } + } + + private static void appendDigestField(StringBuilder preimage, String name, String value) { + preimage + .append(name.getBytes(StandardCharsets.UTF_8).length) + .append(':') + .append(name) + .append(value.getBytes(StandardCharsets.UTF_8).length) + .append(':') + .append(value); + } + + private static String digest(char character) { + return "sha256:" + String.valueOf(character).repeat(64); + } + + private static UUID uuid(int value) { + return UUID.fromString(String.format("%08d-1111-4111-8111-111111111111", value)); + } + + private record Fixture( + CreateCanonicalLaunchPreparationRequest request, + CanonicalLaunchPreparationSnapshot preparation, + CompleteLaunchBindingEvidence binding, + FreshGameSessionTenantAssociation tenantAssociation) {} + + private static final class RecordingTransactionManager implements PlatformTransactionManager { + private TransactionDefinition startedWith; + private int commitCount; + private int rollbackCount; + + @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) { + rollbackCount++; + TransactionSynchronizationManager.clear(); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FreshGameSessionTenantAssociationServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FreshGameSessionTenantAssociationServiceTest.java new file mode 100644 index 0000000000..039eb10c84 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FreshGameSessionTenantAssociationServiceTest.java @@ -0,0 +1,119 @@ +package unit.net.firedevops.firemud.gamesession.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.inOrder; +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.UUID; +import net.firedevops.firemud.common.tenant.RuntimeTenantIdentityEvidence; +import net.firedevops.firemud.gamesession.client.GameDesignRuntimeTenantIdentityClient; +import net.firedevops.firemud.gamesession.repository.FreshGameSessionTenantAssociationRepository; +import net.firedevops.firemud.gamesession.service.FreshGameSessionTenantAssociation; +import net.firedevops.firemud.gamesession.service.FreshGameSessionTenantAssociationService; +import org.junit.jupiter.api.Test; +import org.mockito.InOrder; + +class FreshGameSessionTenantAssociationServiceTest { + private static final String NAMESPACE = "game-session-test"; + private static final UUID REQUEST_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID CANONICAL_TENANT_ID = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + + private final GameDesignRuntimeTenantIdentityClient sourceClient = + mock(GameDesignRuntimeTenantIdentityClient.class); + private final FreshGameSessionTenantAssociationRepository repository = + mock(FreshGameSessionTenantAssociationRepository.class); + private final FreshGameSessionTenantAssociationService service = + new FreshGameSessionTenantAssociationService(sourceClient, repository, NAMESPACE); + + @Test + void readsExactAuthenticatedFreshIdentityBeforeStartingLocalAssociation() { + RuntimeTenantIdentityEvidence evidence = + evidence(NAMESPACE, REQUEST_ID, CANONICAL_TENANT_ID, "NEW_GAME_ROW"); + FreshGameSessionTenantAssociation expected = + new FreshGameSessionTenantAssociation(UUID.randomUUID(), 812L, evidence); + when(sourceClient.resolveRuntimeTenantIdentity( + CANONICAL_TENANT_ID.toString(), REQUEST_ID.toString())) + .thenReturn(evidence); + when(repository.registerAndReadback(evidence)).thenReturn(expected); + + assertThat(service.associate(REQUEST_ID, CANONICAL_TENANT_ID)).isEqualTo(expected); + + InOrder order = inOrder(sourceClient, repository); + order + .verify(sourceClient) + .resolveRuntimeTenantIdentity(CANONICAL_TENANT_ID.toString(), REQUEST_ID.toString()); + order.verify(repository).registerAndReadback(evidence); + } + + @Test + void namespaceRequestTenantOrProvenanceMismatchCannotReachLocalOwnerWrite() { + when(sourceClient.resolveRuntimeTenantIdentity( + CANONICAL_TENANT_ID.toString(), REQUEST_ID.toString())) + .thenReturn(evidence("other-namespace", REQUEST_ID, CANONICAL_TENANT_ID, "NEW_GAME_ROW")); + assertMismatchedSourceIsRejected(); + + when(sourceClient.resolveRuntimeTenantIdentity( + CANONICAL_TENANT_ID.toString(), REQUEST_ID.toString())) + .thenReturn(evidence(NAMESPACE, UUID.randomUUID(), CANONICAL_TENANT_ID, "NEW_GAME_ROW")); + assertMismatchedSourceIsRejected(); + + when(sourceClient.resolveRuntimeTenantIdentity( + CANONICAL_TENANT_ID.toString(), REQUEST_ID.toString())) + .thenReturn(evidence(NAMESPACE, REQUEST_ID, UUID.randomUUID(), "NEW_GAME_ROW")); + assertMismatchedSourceIsRejected(); + + when(sourceClient.resolveRuntimeTenantIdentity( + CANONICAL_TENANT_ID.toString(), REQUEST_ID.toString())) + .thenReturn(evidence(NAMESPACE, REQUEST_ID, CANONICAL_TENANT_ID, "RETAINED_GAME_V30")); + assertMismatchedSourceIsRejected(); + + verify(sourceClient, org.mockito.Mockito.times(4)) + .resolveRuntimeTenantIdentity(CANONICAL_TENANT_ID.toString(), REQUEST_ID.toString()); + verifyNoInteractions(repository); + } + + @Test + void invalidIdentityInputsDoNotCallEitherOwner() { + assertThatThrownBy(() -> service.associate(new UUID(0L, 0L), CANONICAL_TENANT_ID)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("associationRequestId"); + assertThatThrownBy(() -> service.associate(REQUEST_ID, new UUID(0L, 0L))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonicalTenantId"); + + verifyNoInteractions(sourceClient, repository); + } + + @Test + void unavailableAuthenticatedSourceReadNeverOpensLocalOwnerWrite() { + when(sourceClient.resolveRuntimeTenantIdentity( + CANONICAL_TENANT_ID.toString(), REQUEST_ID.toString())) + .thenThrow(new IllegalStateException("source identity unavailable")); + + assertThatThrownBy(() -> service.associate(REQUEST_ID, CANONICAL_TENANT_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("source identity unavailable"); + + verify(sourceClient) + .resolveRuntimeTenantIdentity(CANONICAL_TENANT_ID.toString(), REQUEST_ID.toString()); + verify(repository, never()).registerAndReadback(org.mockito.ArgumentMatchers.any()); + } + + private void assertMismatchedSourceIsRejected() { + assertThatThrownBy(() -> service.associate(REQUEST_ID, CANONICAL_TENANT_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("does not match the exact fresh request"); + } + + private static RuntimeTenantIdentityEvidence evidence( + String namespace, UUID requestId, UUID tenantId, String provenanceKind) { + return new RuntimeTenantIdentityEvidence( + 1, namespace, requestId, tenantId, 9_001L, "source-tenant-key-9002", provenanceKind); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceTest.java index 5cf3d26346..2c2536f491 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceTest.java @@ -10,13 +10,18 @@ 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.gamedesign.AuthoredWorldLaunchDescriptorClient; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; import net.firedevops.firemud.gamesession.dto.CanonicalLaunchPreparationSnapshot; import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; import net.firedevops.firemud.gamesession.dto.CreateCanonicalLaunchPreparationRequest; @@ -84,6 +89,143 @@ void rejectsAmbientTransactionBeforeAnyOwnerReadOrNetworkCall() { assertThat(transactionManager.startedWith).isNull(); } + @Test + void rejectsAmbientTransactionBeforeCompleteBindingOwnerReadOrNetworkCall() { + CanonicalLaunchPreparationSnapshot snapshot = preparedSnapshot(); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + + assertThatThrownBy(() -> service.readCompleteBinding(snapshot)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient transaction"); + + verifyNoInteractions( + descriptorClient, catalogRepository, sourceRepository, preparationRepository); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void readsCompleteBindingOnlyForExactCommittedPreparationAndPreservesBothSharedEvidenceValues() { + CanonicalLaunchPreparationSnapshot snapshot = preparedSnapshot(); + CompleteLaunchBindingEvidence binding = completeBinding(snapshot.launchDescriptorEvidence()); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.of(snapshot)); + when(descriptorClient.getComplete(any(GetLaunchDescriptorRequest.class))).thenReturn(binding); + + assertThat(service.readCompleteBinding(snapshot)).isEqualTo(binding); + + ArgumentCaptor request = + ArgumentCaptor.forClass(GetLaunchDescriptorRequest.class); + verify(descriptorClient).getComplete(request.capture()); + GetLaunchDescriptorRequest selector = request.getValue(); + assertThat(UUID.fromString(selector.getRequestId())).isNotEqualTo(SOURCE_OPERATION); + assertThat(selector) + .isEqualTo( + AuthoredWorldLaunchDescriptorGrpcCodec.toGetRequest( + new GetRequest( + UUID.fromString(selector.getRequestId()), + snapshot.launchDescriptorEvidence().request(), + snapshot.launchDescriptorEvidence().resultDigest()))); + assertThat(selector.getCanonicalTenantId()).isEqualTo(TENANT.toString()); + assertThat(selector.getWorldSlug()).isEqualTo(snapshot.launchDescriptorEvidence().worldSlug()); + assertThat(selector.getControlPlaneRequestId()).isEqualTo(CONTROL_PLANE_REQUEST); + assertThat(selector.getExpectedRequestDigest()) + .isEqualTo(snapshot.launchDescriptorEvidence().requestDigest()); + assertThat(selector.getExpectedResultDigest()) + .isEqualTo(snapshot.launchDescriptorEvidence().resultDigest()); + verify(preparationRepository).readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST); + verify(descriptorClient, never()).resolve(any()); + verify(descriptorClient, never()).get(any(GetRequest.class)); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void changedCommittedSourceFailsBeforeCompleteBindingNetworkRead() { + CanonicalLaunchPreparationSnapshot requested = preparedSnapshot(); + AuthoredWorldSourceEvidence changedSource = source("emerald-grove"); + IntakeReceipt changedIntake = intake(changedSource); + CanonicalRealmCatalogSnapshot changedCatalog = catalog(changedIntake); + CanonicalLaunchPreparationSnapshot changedCommitted = + snapshot( + requested.request(), + changedCatalog, + changedIntake, + descriptor(requested.request(), changedCatalog, changedSource)); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.of(changedCommitted)); + + assertThatThrownBy(() -> service.readCompleteBinding(requested)) + .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("changed before complete binding read"); + + verify(preparationRepository).readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST); + verifyNoInteractions(descriptorClient); + } + + @Test + void missingCommittedPreparationFailsBeforeCompleteBindingNetworkRead() { + CanonicalLaunchPreparationSnapshot snapshot = preparedSnapshot(); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.empty()); + + assertThatThrownBy(() -> service.readCompleteBinding(snapshot)) + .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("missing before complete binding read"); + + verifyNoInteractions(descriptorClient); + } + + @Test + void namespaceMismatchFailsBeforeCompleteBindingOwnerReadOrNetworkCall() { + CanonicalLaunchPreparationSnapshot snapshot = preparedSnapshot(); + GameSessionCanonicalLaunchPreparationService otherNamespaceService = + new GameSessionCanonicalLaunchPreparationService( + descriptorClient, + catalogRepository, + sourceRepository, + preparationRepository, + transactionManager, + NAMESPACE + "-other"); + + assertThatThrownBy(() -> otherNamespaceService.readCompleteBinding(snapshot)) + .isInstanceOf(SecurityException.class) + .hasMessageContaining("namespace"); + + verifyNoInteractions( + descriptorClient, catalogRepository, sourceRepository, preparationRepository); + } + + @Test + void changedCompleteDescriptorFailsAfterExactCommittedPreparationRead() { + CanonicalLaunchPreparationSnapshot snapshot = preparedSnapshot(); + AuthoredWorldLaunchDescriptorEvidence original = snapshot.launchDescriptorEvidence(); + AuthoredWorldLaunchDescriptorEvidence changed = + AuthoredWorldLaunchDescriptorEvidence.create( + original.request(), + original.launchDescriptorId() + "-changed", + original.versionId(), + original.scriptPatchVersionPresent(), + original.scriptPatchVersion(), + original.runtimeFlagsJson(), + original.generationConfigRevision(), + original.versionStateEpoch(), + original.releaseBundleId(), + original.publishedReleaseBundleRef(), + original.remapSetIdPresent(), + original.remapSetId()); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.of(snapshot)); + when(descriptorClient.getComplete(any(GetLaunchDescriptorRequest.class))) + .thenReturn(completeBinding(changed)); + + assertThatThrownBy(() -> service.readCompleteBinding(snapshot)) + .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("differs from the committed launch descriptor"); + + verify(preparationRepository).readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST); + verify(descriptorClient).getComplete(any(GetLaunchDescriptorRequest.class)); + } + @Test void resolvesThenGetsExactDescriptorOutsideShortOwnerTransactionAndReadsCommitBack() { CreateCanonicalLaunchPreparationRequest request = request(); @@ -469,6 +611,14 @@ private void resetRepositories() { descriptorClient, catalogRepository, sourceRepository, preparationRepository); } + private static CanonicalLaunchPreparationSnapshot preparedSnapshot() { + CreateCanonicalLaunchPreparationRequest request = request(); + AuthoredWorldSourceEvidence source = source(); + IntakeReceipt intake = intake(source); + CanonicalRealmCatalogSnapshot catalog = catalog(intake); + return snapshot(request, catalog, intake, descriptor(request, catalog, source)); + } + private static CreateCanonicalLaunchPreparationRequest request() { return request(NAMESPACE, TENANT, CATALOG_REQUEST, 1); } @@ -496,9 +646,12 @@ private static CreateCanonicalLaunchPreparationRequest request( } private static AuthoredWorldSourceEvidence source() { - String world = "violet-wilds"; + return source("violet-wilds"); + } + + private static AuthoredWorldSourceEvidence source(String world) { String tenantSlug = "north-star"; - String displayName = "Violet Wilds"; + String displayName = "emerald-grove".equals(world) ? "Emerald Grove" : "Violet Wilds"; UUID registrationId = uuid(10); String sourceRequestDigest = AuthoredWorldSourceDigest.requestDigest( @@ -592,6 +745,49 @@ private static AuthoredWorldLaunchDescriptorEvidence descriptor( null); } + private static CompleteLaunchBindingEvidence completeBinding( + AuthoredWorldLaunchDescriptorEvidence descriptor) { + String publishCommitId = "publish-commit-902"; + List participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptor.versionId()), + false, + null, + publishCommitId, + "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? digest("d") : null)) + .toList(); + AuthoredWorldReleaseAttestationEvidence releaseAttestation = + AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + descriptor.canonicalTenantId(), + uuid(15), + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + "publish:tenant:version:request", + publishCommitId, + participants, + digest("b"), + 1, + List.of(), + List.of(), + List.of(), + descriptor.generationConfigRevision()); + return new CompleteLaunchBindingEvidence(descriptor, releaseAttestation); + } + private static CanonicalLaunchPreparationSnapshot snapshot( CreateCanonicalLaunchPreparationRequest request, CanonicalRealmCatalogSnapshot catalog, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameInstanceLaunchAssociationReadGrpcAuthTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameInstanceLaunchAssociationReadGrpcAuthTest.java new file mode 100644 index 0000000000..16a0cac7fb --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameInstanceLaunchAssociationReadGrpcAuthTest.java @@ -0,0 +1,103 @@ +package unit.net.firedevops.firemud.gamesession.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +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 net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamesession.service.CanonicalGameInstanceLaunchAssociationReadService; +import net.firedevops.firemud.gamesession.service.impl.GameSessionControlPlaneGrpcService; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameInstanceLaunchAssociationRequest; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameInstanceLaunchAssociationResponse; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.ObjectProvider; + +class CanonicalGameInstanceLaunchAssociationReadGrpcAuthTest { + private static final String NAMESPACE = "gameplay"; + + @AfterEach + void tearDown() { + SessionContext.clear(); + } + + @Test + void rejectsNonWorldPeerBeforeInvokingTheOwnerReadService() { + CanonicalGameInstanceLaunchAssociationReadService ownerReadService = + mock(CanonicalGameInstanceLaunchAssociationReadService.class); + GameSessionControlPlaneGrpcService grpcService = grpcService(ownerReadService); + CapturingObserver response = new CapturingObserver(); + + runAsPeer( + "entity-management-service", + () -> + grpcService.getCanonicalGameInstanceLaunchAssociation( + GetCanonicalGameInstanceLaunchAssociationRequest.newBuilder().build(), response)); + + assertThat(response.value.getError().getCode()).isEqualTo("PERMISSION_DENIED"); + verifyNoInteractions(ownerReadService); + } + + @Test + void rejectsAuthenticatedUserContextEvenWhenWorldPeerCertificateMatches() { + CanonicalGameInstanceLaunchAssociationReadService ownerReadService = + mock(CanonicalGameInstanceLaunchAssociationReadService.class); + GameSessionControlPlaneGrpcService grpcService = grpcService(ownerReadService); + SessionContext.setContext("account", List.of("player"), Map.of()); + CapturingObserver response = new CapturingObserver(); + + runAsPeer( + "world-management-service", + () -> + grpcService.getCanonicalGameInstanceLaunchAssociation( + GetCanonicalGameInstanceLaunchAssociationRequest.newBuilder().build(), response)); + + assertThat(response.value.getError().getCode()).isEqualTo("PERMISSION_DENIED"); + verifyNoInteractions(ownerReadService); + } + + private static GameSessionControlPlaneGrpcService grpcService( + CanonicalGameInstanceLaunchAssociationReadService ownerReadService) { + var service = + new GameSessionControlPlaneGrpcService( + null, null, null, null, null, null, new SimpleMeterRegistry()); + @SuppressWarnings("unchecked") + ObjectProvider provider = + mock(ObjectProvider.class); + when(provider.getIfAvailable()).thenReturn(ownerReadService); + service.configureCanonicalGameInstanceLaunchAssociationOwnerReadBoundary(provider, NAMESPACE); + return service; + } + + private static void runAsPeer(String service, Runnable action) { + String uri = "spiffe://firemud/ns/" + NAMESPACE + "/sa/" + service; + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, new GrpcPeerIdentity(uri, NAMESPACE, service)) + .run(action); + } + + private static final class CapturingObserver + implements StreamObserver { + private GetCanonicalGameInstanceLaunchAssociationResponse value; + + @Override + public void onNext(GetCanonicalGameInstanceLaunchAssociationResponse response) { + value = response; + } + + @Override + public void onError(Throwable throwable) { + throw new AssertionError(throwable); + } + + @Override + public void onCompleted() {} + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameInstanceLaunchAssociationReadGrpcCodecTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameInstanceLaunchAssociationReadGrpcCodecTest.java new file mode 100644 index 0000000000..8e8a2e2a2d --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameInstanceLaunchAssociationReadGrpcCodecTest.java @@ -0,0 +1,227 @@ +package net.firedevops.firemud.gamesession.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.gamedesign.v1.GetCompleteLaunchBindingResponse; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; +import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import net.firedevops.firemud.gamesession.service.CanonicalGameInstanceLaunchAssociationReadRequest; +import net.firedevops.firemud.gamesession.service.CanonicalGameInstanceLaunchAssociationReadService; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameInstanceLaunchAssociationRequest; +import org.junit.jupiter.api.Test; + +class CanonicalGameInstanceLaunchAssociationReadGrpcCodecTest { + private static final String NAMESPACE = "gameplay"; + private static final UUID TENANT = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID INSTANCE = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID TENANT_ASSOCIATION = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + + @Test + void returnsCompleteTypedPairAndCurrentGsProjectionForTheExactReadSelector() throws Exception { + CompleteLaunchBindingEvidence evidence = evidence(); + var association = association(evidence); + var request = wireRequest(evidence); + + var decoded = CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromWire(request); + assertThat(decoded) + .isEqualTo( + new CanonicalGameInstanceLaunchAssociationReadRequest( + UUID.fromString(request.getReadRequestId()), + NAMESPACE, + TENANT, + "earth", + INSTANCE, + evidence.descriptor().controlPlaneRequestId(), + evidence.descriptor().launchDescriptorId(), + evidence.descriptor().requestDigest(), + evidence.descriptor().resultDigest(), + evidence.releaseAttestation().evidenceDigest())); + + var response = CanonicalGameInstanceLaunchAssociationReadGrpcCodec.toWire(request, association); + var parsed = response.getParserForType().parseFrom(response.toByteArray()); + assertThat(parsed.getReadRequestId()).isEqualTo(request.getReadRequestId()); + assertThat(parsed.getGameInstanceUuid()).isEqualTo(INSTANCE.toString()); + assertThat(parsed.getPlayableStateScope()).isEqualTo("SHARED"); + assertThat(parsed.getPublicProduction()).isTrue(); + assertThat(parsed.getCurrentGameInstanceStatus()).isEqualTo("RUNNING"); + assertThat(parsed.getCurrentRowVersion()).isEqualTo(8L); + assertThat(parsed.getLaunchDescriptor().getAuthoredWorldBinding().hasSourceVersionId()) + .isTrue(); + assertThat(parsed.getLaunchDescriptor().getAuthoredWorldBinding().getSourceVersionId()) + .isEqualTo(3_000_000_001L); + assertThat(parsed.getReleaseAttestation().getParticipantDigests(2).hasAbilitySchemaDigest()) + .isTrue(); + + GetLaunchDescriptorRequest gdRequest = + GetLaunchDescriptorRequest.newBuilder() + .setRequestId(request.getReadRequestId()) + .setCanonicalTenantId(request.getCanonicalTenantId()) + .setWorldSlug(request.getWorldSlug()) + .setControlPlaneRequestId(request.getControlPlaneRequestId()) + .setExpectedRequestDigest(request.getExpectedDescriptorRequestDigest()) + .setExpectedResultDigest(request.getExpectedDescriptorResultDigest()) + .build(); + CompleteLaunchBindingEvidence roundTrip = + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + gdRequest, + GetCompleteLaunchBindingResponse.newBuilder() + .setRequestId(request.getReadRequestId()) + .setLaunchDescriptor(parsed.getLaunchDescriptor()) + .setReleaseAttestation(parsed.getReleaseAttestation()) + .build()); + assertThat(roundTrip).isEqualTo(evidence); + } + + @Test + void rejectsNoncanonicalReadIdentityAndChangedOwnerSelector() { + CompleteLaunchBindingEvidence evidence = evidence(); + GetCanonicalGameInstanceLaunchAssociationRequest invalid = + wireRequest(evidence).toBuilder().setReadRequestId("1-1-1-1-1").build(); + assertThatThrownBy(() -> CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromWire(invalid)) + .isInstanceOf(IllegalArgumentException.class); + + CanonicalGameInstanceLaunchAssociationRepository repository = + mock(CanonicalGameInstanceLaunchAssociationRepository.class); + when(repository.read(evidence.descriptor().controlPlaneRequestId())) + .thenReturn(Optional.of(association(evidence))); + var service = new CanonicalGameInstanceLaunchAssociationReadService(repository, NAMESPACE); + var request = + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromWire(wireRequest(evidence)); + var mismatched = + new CanonicalGameInstanceLaunchAssociationReadRequest( + request.readRequestId(), + NAMESPACE, + TENANT, + "earth", + INSTANCE, + request.controlPlaneRequestId(), + request.launchDescriptorId(), + request.expectedDescriptorRequestDigest(), + "sha256:" + "f".repeat(64), + request.expectedReleaseAttestationEvidenceDigest()); + assertThatThrownBy(() -> service.read(mismatched)).isInstanceOf(IllegalStateException.class); + } + + private static GetCanonicalGameInstanceLaunchAssociationRequest wireRequest( + CompleteLaunchBindingEvidence evidence) { + return GetCanonicalGameInstanceLaunchAssociationRequest.newBuilder() + .setReadRequestId("44444444-4444-4444-8444-444444444444") + .setTargetNamespace(NAMESPACE) + .setCanonicalTenantId(TENANT.toString()) + .setWorldSlug("earth") + .setGameInstanceUuid(INSTANCE.toString()) + .setControlPlaneRequestId(evidence.descriptor().controlPlaneRequestId()) + .setLaunchDescriptorId(evidence.descriptor().launchDescriptorId()) + .setExpectedDescriptorRequestDigest(evidence.descriptor().requestDigest()) + .setExpectedDescriptorResultDigest(evidence.descriptor().resultDigest()) + .setExpectedReleaseAttestationEvidenceDigest(evidence.releaseAttestation().evidenceDigest()) + .build(); + } + + private static CanonicalGameInstanceLaunchAssociation association( + CompleteLaunchBindingEvidence evidence) { + return new CanonicalGameInstanceLaunchAssociation( + NAMESPACE, + 19L, + TENANT_ASSOCIATION, + TENANT, + INSTANCE, + "earth", + UUID.fromString("77777777-7777-4777-8777-777777777777"), + RealmEntryPolicy.StateScope.SHARED, + true, + evidence.descriptor().controlPlaneRequestId(), + evidence.descriptor().launchDescriptorId(), + 5L, + evidence, + CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus.RUNNING, + 8L); + } + + private static CompleteLaunchBindingEvidence evidence() { + UUID sourceOperationId = UUID.fromString("55555555-5555-4555-8555-555555555555"); + String sourceDigest = "sha256:" + "a".repeat(64); + var request = + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + "launch-op-1", + TENANT, + "earth", + sourceOperationId, + sourceDigest, + 3_000_000_000L, + true, + "requested-script", + true, + 3_000_000_001L, + true, + 3_000_000_002L, + true, + "{\"seed\":true}"); + var descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + request, + "descriptor-large-counter", + 4_000_000_001L, + true, + "script-9", + "{\"runtime\":true}", + "generation-9", + 5_000_000_001L, + 6_000_000_001L, + "release-large-counter", + true, + "remap-9"); + List participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptor.versionId()), + false, + null, + "commit-9", + "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "d".repeat(64) : null)) + .toList(); + var attestation = + AuthoredWorldReleaseAttestationEvidence.create( + NAMESPACE, + descriptor.resultDigest(), + TENANT, + UUID.fromString("66666666-6666-4666-8666-666666666666"), + "earth", + sourceOperationId, + sourceDigest, + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + "publish-workflow-large", + "commit-9", + participants, + "sha256:" + "b".repeat(64), + 1, + List.of(), + List.of(), + List.of(), + descriptor.generationConfigRevision()); + return new CompleteLaunchBindingEvidence(descriptor, attestation); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameInstanceLaunchAssociationReadWorkloadGuardTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameInstanceLaunchAssociationReadWorkloadGuardTest.java new file mode 100644 index 0000000000..a52a4da536 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameInstanceLaunchAssociationReadWorkloadGuardTest.java @@ -0,0 +1,69 @@ +package unit.net.firedevops.firemud.gamesession.service.impl; + +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Context; +import java.util.List; +import java.util.Map; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.AdminAuthorizationException; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamesession.service.impl.CanonicalGameInstanceLaunchAssociationReadWorkloadGuard; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +class CanonicalGameInstanceLaunchAssociationReadWorkloadGuardTest { + private static final String NAMESPACE = "gameplay"; + private static final String WORLD_SERVICE = "world-management-service"; + + @AfterEach + void tearDown() { + SessionContext.clear(); + } + + @Test + void acceptsOnlyTheExactSameNamespaceWorldManagementPeer() { + var guard = new CanonicalGameInstanceLaunchAssociationReadWorkloadGuard(NAMESPACE); + assertThatCode( + () -> + runAsPeer( + WORLD_SERVICE, + NAMESPACE, + () -> { + guard.requireWorldManagementOwnerReadCaller(); + guard.requireConfiguredTargetNamespace(NAMESPACE); + })) + .doesNotThrowAnyException(); + } + + @Test + void rejectsWrongPeerNamespaceTargetAndAuthenticatedCallerContext() { + var guard = new CanonicalGameInstanceLaunchAssociationReadWorkloadGuard(NAMESPACE); + denied( + () -> + runAsPeer( + "entity-management-service", + NAMESPACE, + guard::requireWorldManagementOwnerReadCaller)); + denied(() -> runAsPeer(WORLD_SERVICE, "other", guard::requireWorldManagementOwnerReadCaller)); + denied(guard::requireWorldManagementOwnerReadCaller); + denied( + () -> + runAsPeer( + WORLD_SERVICE, NAMESPACE, () -> guard.requireConfiguredTargetNamespace("other"))); + SessionContext.setContext("account", List.of("player"), Map.of()); + denied(() -> runAsPeer(WORLD_SERVICE, NAMESPACE, guard::requireWorldManagementOwnerReadCaller)); + } + + private static void denied(Runnable action) { + assertThatThrownBy(action::run).isInstanceOf(AdminAuthorizationException.class); + } + + private static void runAsPeer(String service, String namespace, Runnable action) { + String uri = "spiffe://firemud/ns/" + namespace + "/sa/" + service; + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, new GrpcPeerIdentity(uri, namespace, service)) + .run(action); + } +}