From 44675c5c2cb95b8c78cd9c16027bee6536b3cb37 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 21 Nov 2026 06:10:32 +1300 Subject: [PATCH 01/28] Serve the run-owned fixture's World lifecycle through the canonical lifecycle read The fixture has no Human launch binding: World answers its exact request (fixture descriptor digests plus the fixture provenance digest in the release-attestation slot) with the closed WorldRunOwnedFixtureLifecycleEvidence, and the Human read treats a fixture association as an ordinary miss. Co-Authored-By: Claude Opus 5.5 --- ...WorldCanonicalInstanceLifecycleClient.java | 25 ++++++ ...ldCanonicalInstanceLifecycleGrpcCodec.java | 33 +++++++ ...nicalInstanceLifecycleReadGrpcService.java | 9 ++ ...onicalInstanceLifecycleReadRepository.java | 86 ++++++++++++++++++- 4 files changed, 152 insertions(+), 1 deletion(-) diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleClient.java index 541f9a56be..b859c2bac7 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleClient.java @@ -89,6 +89,31 @@ public WorldCanonicalInstanceLifecycleEvidence read( } } + /** Reads the exact run-owned fixture lifecycle, whose request carries its provenance digest. */ + public WorldRunOwnedFixtureLifecycleEvidence readRunOwnedFixture( + WorldCanonicalInstanceLifecycleEvidence.Request request, Deadline operationDeadline) { + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "World canonical lifecycle request must use the configured workload namespace"); + } + var stub = requireStub(); + var timedStub = + operationDeadline == null + ? stub.withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + : stub.withDeadline( + operationDeadline.minimum(Deadline.after(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS))); + var response = + timedStub.readWorldCanonicalInstanceLifecycle( + WorldCanonicalInstanceLifecycleGrpcCodec.toRequest(request)); + try { + return WorldCanonicalInstanceLifecycleGrpcCodec.fromFixtureResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "World returned invalid run-owned fixture lifecycle evidence", invalid); + } + } + @Override protected String configuredTarget(ServiceEndpointsProperties endpoints) { return endpoints.getWorldManagementService(); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleGrpcCodec.java index 9caf305d68..34c7b90ffd 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleGrpcCodec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleGrpcCodec.java @@ -61,6 +61,39 @@ public static WorldCanonicalInstanceLifecycleEvidence fromResponse( return evidence; } + /** Encodes the run-owned fixture variant for the exact caller request. */ + public static ReadWorldCanonicalInstanceLifecycleResponse toFixtureResponse( + Request request, WorldRunOwnedFixtureLifecycleEvidence evidence) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(evidence, "evidence"); + if (!request.equals(evidence.request())) { + throw new IllegalArgumentException( + "World fixture lifecycle evidence differs from exact read request"); + } + return ReadWorldCanonicalInstanceLifecycleResponse.newBuilder() + .setCanonicalResponseBytes(ByteString.copyFrom(evidence.canonicalBytes())) + .build(); + } + + /** Validates the closed run-owned fixture response and its exact request echo. */ + public static WorldRunOwnedFixtureLifecycleEvidence fromFixtureResponse( + Request request, ReadWorldCanonicalInstanceLifecycleResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "ReadWorldCanonicalInstanceLifecycleResponse"); + if (response.getCanonicalResponseBytes().isEmpty()) { + throw new IllegalArgumentException("World fixture lifecycle response bytes are required"); + } + WorldRunOwnedFixtureLifecycleEvidence evidence = + WorldRunOwnedFixtureLifecycleEvidence.fromStored( + response.getCanonicalResponseBytes().toByteArray()); + if (!request.equals(evidence.request())) { + throw new IllegalArgumentException( + "World fixture lifecycle response changed exact read request"); + } + return evidence; + } + private static void requireNoUnknownFields(Message message, String label) { if (!message.getUnknownFields().asMap().isEmpty()) { throw new IllegalArgumentException(label + " contains unsupported fields"); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadGrpcService.java index 54f0d54731..2940ef60d4 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadGrpcService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadGrpcService.java @@ -69,6 +69,15 @@ public void readWorldCanonicalInstanceLifecycle( WorldCanonicalInstanceLifecycleEvidence evidence; try { evidence = repository.read(readRequest).orElse(null); + if (evidence == null) { + var fixture = repository.readRunOwnedFixture(readRequest).orElse(null); + if (fixture != null) { + responseObserver.onNext( + WorldCanonicalInstanceLifecycleGrpcCodec.toFixtureResponse(readRequest, fixture)); + responseObserver.onCompleted(); + return; + } + } } catch ( WorldCanonicalInstanceLifecycleReadRepository.InvalidLifecycleEvidenceException inconsistent) { diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java index 60045c83fc..28044ac41f 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java @@ -21,6 +21,7 @@ import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.common.world.WorldRunOwnedFixtureLifecycleEvidence; import net.firedevops.firemud.worldmanagement.v1.WorldInboundSourceFamily; import org.jooq.DSLContext; import org.jooq.Record; @@ -113,6 +114,88 @@ public Optional read( })); } + /** + * Reads the exact run-owned fixture lifecycle. A fixture has no Human release attestation: its + * request carries the retained fixture descriptor digests and the fixture provenance digest in + * place of the release attestation. Any other association is an ordinary empty read. + */ + public Optional readRunOwnedFixture( + WorldCanonicalInstanceLifecycleEvidence.Request request) { + Objects.requireNonNull(request, "request"); + requireNoActiveTransaction("World run-owned fixture lifecycle read"); + return Optional.ofNullable( + transaction.execute( + status -> { + requireReadOnlyRepeatableReadOwnerTransaction(); + return readRunOwnedFixtureInCurrentOwnerTransaction(request); + })); + } + + private WorldRunOwnedFixtureLifecycleEvidence readRunOwnedFixtureInCurrentOwnerTransaction( + WorldCanonicalInstanceLifecycleEvidence.Request request) { + try { + Optional maybeAssociation = + associationRepository.readOwnerAssociationInOwnerTransaction( + request.canonicalGameInstanceId()); + if (maybeAssociation.isEmpty()) return null; + WorldCanonicalInstanceAssociation association = maybeAssociation.orElseThrow(); + if (!association.isRunOwnedFixture() || !matchesFixtureRequest(request, association)) { + return null; + } + Record row = + dsl.fetchOne( + "SELECT status,lifecycle_epoch,row_version FROM world_instance WHERE id=?", + association.worldInstanceId()); + if (row == null) return null; + var fixture = association.runOwnedFixture(); + return new WorldRunOwnedFixtureLifecycleEvidence( + request, + fixture.fixtureProvenanceDigest(), + fixture.preparationInputDigest(), + required(row, "status", String.class), + required(row, "lifecycle_epoch", Long.class), + required(row, "row_version", Long.class)); + } catch (org.springframework.dao.DataAccessException | DataAccessException unavailable) { + throw unavailable; + } catch ( + WorldCanonicalInstanceAssociationRepository.InvalidAssociationEvidenceException + inconsistent) { + throw new InvalidLifecycleEvidenceException( + "Canonical World fixture association source evidence is inconsistent", inconsistent); + } + } + + private boolean matchesFixtureRequest( + WorldCanonicalInstanceLifecycleEvidence.Request request, + WorldCanonicalInstanceAssociation association) { + var identity = association.identity(); + Record descriptor = + dsl.fetchOne( + "SELECT descriptor_request_digest, descriptor_result_digest " + + "FROM world_canonical_instance_association " + + "WHERE canonical_game_instance_id = ? AND canonical_authority_kind = 'RUN_OWNED_FIXTURE'", + identity.canonicalGameInstanceId()); + return descriptor != null + && request.canonicalGameInstanceId().equals(identity.canonicalGameInstanceId()) + && request.targetNamespace().equals(identity.targetNamespace()) + && request.canonicalTenantId().equals(identity.canonicalTenantId()) + && request.worldSlug().equals(identity.worldSlug()) + && request.playableStateNamespaceId().equals(identity.playableStateNamespaceId()) + && request.playableStateScope().equals(identity.playableStateScope()) + && request.publicProduction() == identity.publicProduction() + && request.controlPlaneRequestId().equals(identity.controlPlaneRequestId()) + && request.canonicalVersionId().equals(association.canonicalVersionId()) + && request + .expectedDescriptorRequestDigest() + .equals(required(descriptor, "descriptor_request_digest", String.class)) + && request + .expectedDescriptorResultDigest() + .equals(required(descriptor, "descriptor_result_digest", String.class)) + && request + .expectedReleaseAttestationDigest() + .equals(association.runOwnedFixture().fixtureProvenanceDigest()); + } + /** * Reconstructs the same exact owner evidence while a writable activation transaction holds it. */ @@ -142,7 +225,8 @@ private WorldCanonicalInstanceLifecycleEvidence readInCurrentOwnerTransaction( request.canonicalGameInstanceId()); if (maybeAssociation.isEmpty()) return null; WorldCanonicalInstanceAssociation association = maybeAssociation.orElseThrow(); - if (!matchesRequest(request, association)) return null; + // The run-owned fixture has no Human launch binding; it answers readRunOwnedFixture only. + if (association.isRunOwnedFixture() || !matchesRequest(request, association)) return null; Record preparation = dsl.fetchOne( From f1515f2f4b9816b4bab68d4c07799d852082a0b0 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:59:59 +1300 Subject: [PATCH 02/28] Run Telnet JOIN on the run-owned fixture through the canonical chain The fixture has no Game Design Human publication, so the published realm owner read gains a closed run-owned fixture variant: Game Session reads the retained catalog fixture policy and seal instead of a Game Design policy set, verifies it against the launch association's fixture provenance, reads World's fixture lifecycle, and answers with run_owned_fixture_source (field 5) and fixture lifecycle bytes. The shared codec validates the variant; Account JOIN accepts it, while PLAY entitlement and bootstrap characters fail closed until PLAY moves onto the chain. A player's first JOIN now enrolls the never-joined membership authority scope if absent, which the first-JOIN authority event reads; only creators had it. Live Compose: LOGIN, WORLDS, REALMS and JOIN succeed; full smoke passes. Co-Authored-By: Claude Opus 5.5 --- ...cal_gameplay_admission_decision_read.proto | 18 +- .../AccountAuthorityGenerationRepository.java | 26 ++ .../AccountTenantMembershipRepository.java | 9 + ...ccountPlayerAdmissionEntitlementOwner.java | 3 + .../service/impl/AccountServiceImpl.java | 6 +- ...onicalGameplayRosterOwnerReadEvidence.java | 2 +- ...GameplayRunOwnedFixtureSourceEvidence.java | 369 ++++++++++++++++++ ...ameplayAdmissionDecisionReadGrpcCodec.java | 192 ++++++++- .../dto/CanonicalRealmCatalogSnapshot.java | 103 ++++- ...essionCanonicalRealmCatalogRepository.java | 10 +- ...onicalPublishedPlayerRouteReadService.java | 246 +++++++++++- ...eplayAdmissionDecisionReadGrpcService.java | 165 ++++++-- ...layAdmissionPublishedFixtureCodecTest.java | 300 ++++++++++++++ ...AdmissionPublishedReadGrpcServiceTest.java | 78 ++++ ...calGameplayRosterSelectionServiceTest.java | 1 + ...alPublishedPlayerRouteReadServiceTest.java | 1 + 16 files changed, 1456 insertions(+), 73 deletions(-) create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRunOwnedFixtureSourceEvidence.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionPublishedFixtureCodecTest.java diff --git a/protos/game-session/v1/canonical_gameplay_admission_decision_read.proto b/protos/game-session/v1/canonical_gameplay_admission_decision_read.proto index e40465795d..93f5f4c2c2 100644 --- a/protos/game-session/v1/canonical_gameplay_admission_decision_read.proto +++ b/protos/game-session/v1/canonical_gameplay_admission_decision_read.proto @@ -175,17 +175,23 @@ message CanonicalPlayableTargetEvidence { repeated string character_creation_policy = 32; } -// Complete current GS target, the existing full publication source, and a mandatory fresh World -// ACTIVE capture of the same launch. Existing owner codecs independently validate both carried -// sources. The complete 6,422,545-byte bound includes all three carriers and protobuf framing; -// oversized complete source refuses rather than dropping evidence. +// Complete current GS target, exactly one source (the full Human publication source or the +// run-owned fixture's retained policy source), and a mandatory fresh World ACTIVE capture of the +// same launch. Existing owner codecs independently validate every carried source. The complete +// 6,422,545-byte bound includes all carriers and protobuf framing; oversized complete source +// refuses rather than dropping evidence. message GetPublishedRealmAdmissionOwnerReadResponse { repeated uint32 schema_version = 1; + // Human variant only. Exactly one of published_source and run_owned_fixture_source is present. repeated GetCanonicalGameplayRosterOwnerReadResponse published_source = 2; repeated CanonicalPlayableTargetEvidence current_target = 3; - // Exact existing WorldCanonicalInstanceLifecycleEvidence canonical bytes. Required once; - // ACTIVE and complete request/launch/publication binding must match the same owner target. + // Required once. Human: exact WorldCanonicalInstanceLifecycleEvidence canonical bytes whose + // ACTIVE request/launch/publication binding matches the same owner target. Run-owned fixture: + // exact WorldRunOwnedFixtureLifecycleEvidence canonical bytes for the same ACTIVE launch. repeated bytes world_lifecycle_evidence = 4; + // Run-owned fixture variant only: exact CanonicalGameplayRunOwnedFixtureSourceEvidence + // canonical bytes (owner proof plus the catalog-retained sealed fixture policy). + repeated bytes run_owned_fixture_source = 5; } // Independently reads the original selected abandonment and actual qualified physical closure. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java index f6c3fd5bca..d9a47e726b 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java @@ -130,6 +130,32 @@ public ScopeState initializeTenantIfAbsent(UUID canonicalTenantId) { return readScopeState(scope, true); } + /** + * Enrolls one never-joined membership scope once, preserving any existing generation. The Account + * and tenant scopes must already exist; establishing the scope does not advance the Account + * issuance fence. + */ + @Transactional(propagation = Propagation.MANDATORY) + public ScopeState initializeMembershipIfAbsent(UUID accountUuid, UUID tenantUuid) { + AuthorityScope scope = AuthorityScope.membership(accountUuid, tenantUuid); + validateScope(scope); + requireAccountState(accountUuid, true); + readScopeState(AuthorityScope.tenant(tenantUuid), true); + int inserted = + dsl.execute( + "INSERT INTO " + + GENERATION_TABLE + + " (scope_kind, issuer_id, account_uuid, tenant_uuid, generation, source_version) " + + "VALUES ('MEMBERSHIP', NULL, ?, ?, 1, 1) " + + "ON CONFLICT (account_uuid, tenant_uuid) WHERE scope_kind = 'MEMBERSHIP' DO NOTHING", + accountUuid, + tenantUuid); + if (inserted < 0 || inserted > 1) { + throw new IllegalStateException("Account membership authority enrollment was ambiguous"); + } + return readScopeState(scope, true); + } + /** Reads one initialized exact scope and fails closed for absent or malformed state. */ @Transactional(propagation = Propagation.MANDATORY) public ScopeState read(AuthorityScope scope) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java index f5fac1625f..711ed35f21 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java @@ -33,6 +33,7 @@ public class AccountTenantMembershipRepository { private final AccountRepository accountRepository; private final FreshTenantIdentityAssociationRepository freshTenantIdentityAssociationRepository; private final AccountMembershipPairAuthorityRepository pairAuthorityRepository; + private final AccountAuthorityGenerationRepository authorityGenerationRepository; public AccountTenantMembershipRepository( DSLContext dsl, @@ -43,6 +44,7 @@ public AccountTenantMembershipRepository( this.accountRepository = accountRepository; this.freshTenantIdentityAssociationRepository = freshTenantIdentityAssociationRepository; this.pairAuthorityRepository = pairAuthorityRepository; + this.authorityGenerationRepository = new AccountAuthorityGenerationRepository(dsl); } public Optional findByAccountIdAndTenantId( @@ -229,6 +231,13 @@ public AccountTenantMembership createFreshMembershipForJoin(UUID accountUuid, UU pairAuthorityRepository.readForUpdate(accountUuid, tenantUuid); PairAuthority baseline; if (existingPair.isEmpty()) { + // A player who never joined has no membership scope yet; the first JOIN's authority event + // reads it, so establish the pristine scope with the never-joined pair, as creators do. + var generation = + authorityGenerationRepository.initializeMembershipIfAbsent(accountUuid, tenantUuid); + if (generation.generation() != 1L || generation.sourceVersion() != 1L) { + throw new IllegalStateException("Fresh first JOIN membership generation is not pristine"); + } baseline = pairAuthorityRepository.enrollAbsence(accountUuid, tenantUuid, expectedProvenance); if (!absenceBaseline.equals(baseline)) { throw new IllegalStateException( diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java index dcb9aef626..b9b04ec6bd 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java @@ -572,6 +572,9 @@ private PublishedRealmEvidence readProtectedTarget( if (!resolved.strictSelector().equals(result.selector()) || !resolved.currentTarget().equals(result.currentTarget())) throw targetPrecondition(); requireSupportedTarget(result.currentTarget()); + // The entitlement capture binds Human published and World lifecycle evidence; the run-owned + // fixture has neither, so its PLAY entitlement remains unsupported until its own schema. + if (result.isRunOwnedFixture()) throw targetPrecondition(); return result; } catch (CanonicalGameplayAdmissionDecisionReadClient.ClientUnavailableException failure) { throw unavailable(); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java index 32e6309c42..4d58f7214f 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java @@ -1009,7 +1009,10 @@ public List listBootstrapCharacters( "REALM_UNAVAILABLE", "Bootstrap actor discovery does not yet support this realm policy"); } PublishedRealmEvidence published = readCanonicalScopePublishedTarget(consumers, scope); - if (!"SHARED".equals(published.currentTarget().playableStateScope()) + // Entity bootstrap discovery binds the Human published policy set; the run-owned fixture has + // no publication, so its bootstrap discovery stays unsupported rather than partially bound. + if (published.isRunOwnedFixture() + || !"SHARED".equals(published.currentTarget().playableStateScope()) || !"PRESEEDED_ONLY".equals(published.currentTarget().characterCreationPolicy())) { throw new AuthenticationException( "REALM_UNAVAILABLE", "Bootstrap actor discovery does not yet support this realm policy"); @@ -1157,6 +1160,7 @@ private JoinPublicProductionResult joinCanonicalPublicProduction( recordFailure.getClass().getSimpleName()); } if (failure instanceof AuthenticationException authentication) throw authentication; + logger.warn("Canonical JOIN authority failed: {}", failure.getClass().getName(), failure); throw new AuthenticationException( code, "Canonical JOIN authority is unavailable; retry the same request", failure); } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadEvidence.java index 905932f518..10c6adce0a 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadEvidence.java @@ -59,7 +59,7 @@ public PublishedRealmEntryPolicyEvidence selectedPolicyEvidence() { .orElseThrow(() -> new IllegalStateException("Exact published policy is unavailable")); } - private static void requireProofMatches( + static void requireProofMatches( Request request, GameSessionCanonicalInitialAdmissionOwnerProof proof) { var hold = proof.holdIdentity().request(); if (proof.outcome() != GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRunOwnedFixtureSourceEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRunOwnedFixtureSourceEvidence.java new file mode 100644 index 0000000000..529672b3dd --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRunOwnedFixtureSourceEvidence.java @@ -0,0 +1,369 @@ +package net.firedevops.firemud.common.world; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Base64; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Closed run-owned fixture counterpart of {@link CanonicalGameplayRosterOwnerReadEvidence}: the + * exact committed Game Session owner proof plus the catalog-retained sealed fixture policy instead + * of a Game Design publication. The fixture has no Human publication, so this carrier never + * satisfies a Human published-source consumer. The account UUID is correlation only; this is source + * evidence, not Account authority, actor ownership or gameplay admission. + */ +public final class CanonicalGameplayRunOwnedFixtureSourceEvidence { + public static final String SCHEMA = "canonical-gameplay-run-owned-fixture-source/v1"; + public static final int MAX_CANONICAL_BYTES = 64 * 1024; + + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern POINTER_SNAPSHOT_DIGEST = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern PREFIXED_SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Set FIELDS = + Set.of( + "schema", + "requestUuid", + "canonicalAccountUuid", + "targetNamespace", + "canonicalTenantUuid", + "worldSlug", + "realmUuid", + "realmSlug", + "playableStateNamespaceUuid", + "playableStateScope", + "canonicalGameInstanceUuid", + "canonicalVersionUuid", + "expectedCatalogRevision", + "expectedPointerVersion", + "expectedActiveWorldEpoch", + "admissionPointerSnapshotDigest", + "ownerProofBase64", + "fixturePolicyRequestBase64", + "fixturePolicySealOperationId", + "fixturePolicySealRequestDigest", + "fixturePolicySealEvidenceDigest"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .build(); + + private final CanonicalGameplayRosterOwnerReadEvidence.Request request; + private final String admissionPointerSnapshotDigest; + private final GameSessionCanonicalInitialAdmissionOwnerProof gameSessionOwnerProof; + private final byte[] fixturePolicyRequestBytes; + private final UUID fixturePolicySealOperationId; + private final String fixturePolicySealRequestDigest; + private final String fixturePolicySealEvidenceDigest; + private final RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicyRequest fixturePolicy; + + public CanonicalGameplayRunOwnedFixtureSourceEvidence( + CanonicalGameplayRosterOwnerReadEvidence.Request request, + String admissionPointerSnapshotDigest, + GameSessionCanonicalInitialAdmissionOwnerProof gameSessionOwnerProof, + byte[] fixturePolicyRequestBytes, + UUID fixturePolicySealOperationId, + String fixturePolicySealRequestDigest, + String fixturePolicySealEvidenceDigest) { + this.request = Objects.requireNonNull(request, "request"); + if (admissionPointerSnapshotDigest == null + || !POINTER_SNAPSHOT_DIGEST.matcher(admissionPointerSnapshotDigest).matches()) { + throw new IllegalArgumentException( + "Admission pointer snapshot digest must be raw lowercase 64-character SHA-256 hex"); + } + this.admissionPointerSnapshotDigest = admissionPointerSnapshotDigest; + Objects.requireNonNull(gameSessionOwnerProof, "gameSessionOwnerProof"); + byte[] proofBytes = + GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes(gameSessionOwnerProof); + if (proofBytes.length > CanonicalGameplayRosterOwnerReadEvidence.MAX_OWNER_PROOF_BYTES) { + throw new IllegalArgumentException("Run-owned fixture owner proof exceeds its size bound"); + } + this.gameSessionOwnerProof = + GameSessionCanonicalInitialAdmissionOwnerProofCodec.fromStored(proofBytes); + CanonicalGameplayRosterOwnerReadEvidence.requireProofMatches( + request, this.gameSessionOwnerProof); + + Objects.requireNonNull(fixturePolicyRequestBytes, "fixturePolicyRequestBytes"); + this.fixturePolicyRequestBytes = fixturePolicyRequestBytes.clone(); + if (fixturePolicySealOperationId == null || NIL_UUID.equals(fixturePolicySealOperationId)) { + throw new IllegalArgumentException("Fixture policy seal operation id must be non-nil"); + } + requireDigest(fixturePolicySealRequestDigest, "fixturePolicySealRequestDigest"); + requireDigest(fixturePolicySealEvidenceDigest, "fixturePolicySealEvidenceDigest"); + this.fixturePolicySealOperationId = fixturePolicySealOperationId; + this.fixturePolicySealRequestDigest = fixturePolicySealRequestDigest; + this.fixturePolicySealEvidenceDigest = fixturePolicySealEvidenceDigest; + this.fixturePolicy = requireFixturePolicyMatches(request, this.fixturePolicyRequestBytes); + var capability = fixturePolicy.capability(); + String requestDigest = + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestDigest( + capability, + fixturePolicy.creationEvidence(), + fixturePolicy.sourceEvidence(), + fixturePolicy.launchReadEvidence()); + if (!UUID.fromString(capability.operationId()).equals(fixturePolicySealOperationId) + || !requestDigest.equals(fixturePolicySealRequestDigest) + || !RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyEvidenceDigest( + fixturePolicySealOperationId, fixturePolicySealRequestDigest) + .equals(fixturePolicySealEvidenceDigest)) { + throw new IllegalArgumentException( + "Run-owned fixture policy seal differs from its exact retained policy request"); + } + } + + /** + * Validates retained fixture policy bytes for one exact route selector and returns the decoded + * request. Decoding grants no authority; only the owning catalog readback establishes provenance. + */ + public static RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicyRequest + requireFixturePolicyMatches( + CanonicalGameplayRosterOwnerReadEvidence.Request request, byte[] fixturePolicyBytes) { + Objects.requireNonNull(request, "request"); + var parsed = + RunOwnedInitialAdmissionFixtureWireCodec.parseFixturePolicyRequestBytes(fixturePolicyBytes); + var capability = parsed.capability(); + var source = parsed.sourceEvidence(); + String canonicalVersion = + parsed.launchReadEvidence().publishedReleaseBundle().getCanonicalVersionId(); + if (!capability.visible() + || !capability.publicProductionRealm() + || !"SHARED".equals(capability.stateScope()) + || !"PRESEEDED_ONLY".equals(capability.characterCreationPolicy()) + || !"SHARED".equals(request.playableStateScope()) + || !capability.worldSlug().equals(request.worldSlug()) + || !capability.realmSlug().equals(request.realmSlug()) + || !source.targetNamespace().equals(request.targetNamespace()) + || !source.canonicalTenantId().equals(request.canonicalTenantUuid()) + || !source.worldSlug().equals(request.worldSlug()) + || !request.canonicalVersionUuid().toString().equals(canonicalVersion)) { + throw new IllegalArgumentException( + "Run-owned fixture policy is not the exact visible public-production SHARED" + + " PRESEEDED_ONLY route"); + } + return parsed; + } + + public CanonicalGameplayRosterOwnerReadEvidence.Request request() { + return request; + } + + public String admissionPointerSnapshotDigest() { + return admissionPointerSnapshotDigest; + } + + public GameSessionCanonicalInitialAdmissionOwnerProof gameSessionOwnerProof() { + return gameSessionOwnerProof; + } + + public byte[] fixturePolicyRequestBytes() { + return fixturePolicyRequestBytes.clone(); + } + + public UUID fixturePolicySealOperationId() { + return fixturePolicySealOperationId; + } + + public String fixturePolicySealRequestDigest() { + return fixturePolicySealRequestDigest; + } + + public String fixturePolicySealEvidenceDigest() { + return fixturePolicySealEvidenceDigest; + } + + /** Decoded retained policy request; structurally validated, never independent authority. */ + public RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicyRequest fixturePolicy() { + return fixturePolicy; + } + + /** The sealed fixture policy's character-creation policy (always PRESEEDED_ONLY). */ + public String characterCreationPolicy() { + return fixturePolicy.capability().characterCreationPolicy(); + } + + public byte[] canonicalBytes() { + Map value = new LinkedHashMap<>(); + value.put("schema", SCHEMA); + value.put("requestUuid", request.requestUuid().toString()); + value.put("canonicalAccountUuid", request.canonicalAccountUuid().toString()); + value.put("targetNamespace", request.targetNamespace()); + value.put("canonicalTenantUuid", request.canonicalTenantUuid().toString()); + value.put("worldSlug", request.worldSlug()); + value.put("realmUuid", request.realmUuid().toString()); + value.put("realmSlug", request.realmSlug()); + value.put("playableStateNamespaceUuid", request.playableStateNamespaceUuid().toString()); + value.put("playableStateScope", request.playableStateScope()); + value.put("canonicalGameInstanceUuid", request.canonicalGameInstanceUuid().toString()); + value.put("canonicalVersionUuid", request.canonicalVersionUuid().toString()); + value.put("expectedCatalogRevision", Long.toString(request.expectedCatalogRevision())); + value.put("expectedPointerVersion", Long.toString(request.expectedPointerVersion())); + value.put("expectedActiveWorldEpoch", Long.toString(request.expectedActiveWorldEpoch())); + value.put("admissionPointerSnapshotDigest", admissionPointerSnapshotDigest); + value.put( + "ownerProofBase64", + Base64.getEncoder() + .encodeToString( + GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes( + gameSessionOwnerProof))); + value.put( + "fixturePolicyRequestBase64", + Base64.getEncoder().encodeToString(fixturePolicyRequestBytes)); + value.put("fixturePolicySealOperationId", fixturePolicySealOperationId.toString()); + value.put("fixturePolicySealRequestDigest", fixturePolicySealRequestDigest); + value.put("fixturePolicySealEvidenceDigest", fixturePolicySealEvidenceDigest); + try { + byte[] bytes = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + if (bytes.length > MAX_CANONICAL_BYTES) { + throw new IllegalArgumentException("Run-owned fixture source evidence exceeds its limit"); + } + return bytes; + } catch (IOException impossible) { + throw new IllegalStateException( + "Run-owned fixture source evidence cannot be encoded", impossible); + } + } + + /** Decodes only complete, canonical, bounded evidence; this does not authenticate its sender. */ + public static CanonicalGameplayRunOwnedFixtureSourceEvidence fromStored(byte[] stored) { + Objects.requireNonNull(stored, "stored"); + if (stored.length == 0 || stored.length > MAX_CANONICAL_BYTES) { + throw new IllegalArgumentException("Run-owned fixture source evidence exceeds its limit"); + } + try { + JsonNode root = JSON.readTree(strictUtf8(stored)); + if (root == null || !root.isObject()) { + throw new IllegalArgumentException("Run-owned fixture source evidence must be an object"); + } + Set actual = new HashSet<>(); + root.propertyNames().forEach(actual::add); + if (!actual.equals(FIELDS) || !SCHEMA.equals(text(root, "schema"))) { + throw new IllegalArgumentException( + "Run-owned fixture source evidence has an unsupported shape"); + } + var request = + new CanonicalGameplayRosterOwnerReadEvidence.Request( + uuid(root, "requestUuid"), + uuid(root, "canonicalAccountUuid"), + text(root, "targetNamespace"), + uuid(root, "canonicalTenantUuid"), + text(root, "worldSlug"), + uuid(root, "realmUuid"), + text(root, "realmSlug"), + uuid(root, "playableStateNamespaceUuid"), + text(root, "playableStateScope"), + uuid(root, "canonicalGameInstanceUuid"), + uuid(root, "canonicalVersionUuid"), + parseLong(text(root, "expectedCatalogRevision")), + parseLong(text(root, "expectedPointerVersion")), + parseLong(text(root, "expectedActiveWorldEpoch"))); + var evidence = + new CanonicalGameplayRunOwnedFixtureSourceEvidence( + request, + text(root, "admissionPointerSnapshotDigest"), + GameSessionCanonicalInitialAdmissionOwnerProofCodec.fromStored( + base64(root, "ownerProofBase64")), + base64(root, "fixturePolicyRequestBase64"), + uuid(root, "fixturePolicySealOperationId"), + text(root, "fixturePolicySealRequestDigest"), + text(root, "fixturePolicySealEvidenceDigest")); + if (!Arrays.equals(stored, evidence.canonicalBytes())) { + throw new IllegalArgumentException("Run-owned fixture source evidence is not canonical"); + } + return evidence; + } catch (tools.jackson.core.JacksonException invalid) { + throw new IllegalArgumentException("Run-owned fixture source evidence is invalid", invalid); + } + } + + @Override + public boolean equals(Object other) { + return other instanceof CanonicalGameplayRunOwnedFixtureSourceEvidence that + && Arrays.equals(canonicalBytes(), that.canonicalBytes()); + } + + @Override + public int hashCode() { + return Arrays.hashCode(canonicalBytes()); + } + + @Override + public String toString() { + return "CanonicalGameplayRunOwnedFixtureSourceEvidence[request=" + + request.requestUuid() + + ", sealEvidenceDigest=" + + fixturePolicySealEvidenceDigest + + "]"; + } + + private static byte[] base64(JsonNode root, String field) { + String encoded = text(root, field); + byte[] decoded = Base64.getDecoder().decode(encoded); + if (!Base64.getEncoder().encodeToString(decoded).equals(encoded)) { + throw new IllegalArgumentException(field + " must use canonical base64"); + } + return decoded; + } + + private static UUID uuid(JsonNode root, String field) { + String value = text(root, field); + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value)) { + throw new IllegalArgumentException(field + " must be a canonical UUID"); + } + return parsed; + } + + private static long parseLong(String value) { + try { + long parsed = Long.parseLong(value); + if (!Long.toString(parsed).equals(value)) throw new NumberFormatException(value); + return parsed; + } catch (NumberFormatException invalid) { + throw new IllegalArgumentException("Run-owned fixture source number is invalid", invalid); + } + } + + private static void requireDigest(String value, String label) { + if (value == null || !PREFIXED_SHA256.matcher(value).matches()) { + throw new IllegalArgumentException(label + " must be a prefixed SHA-256 digest"); + } + } + + private static String text(JsonNode object, String field) { + JsonNode value = object.get(field); + if (value == null || !value.isTextual()) { + throw new IllegalArgumentException(field + " must be text"); + } + return value.textValue(); + } + + private static String strictUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (java.nio.charset.CharacterCodingException invalid) { + throw new IllegalArgumentException( + "Run-owned fixture source evidence is not strict UTF-8", invalid); + } + } +} diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameplayAdmissionDecisionReadGrpcCodec.java b/services/common-security/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameplayAdmissionDecisionReadGrpcCodec.java index 22bc86bd2b..86944db97d 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameplayAdmissionDecisionReadGrpcCodec.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameplayAdmissionDecisionReadGrpcCodec.java @@ -25,10 +25,12 @@ import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadGrpcCodec; +import net.firedevops.firemud.common.world.CanonicalGameplayRunOwnedFixtureSourceEvidence; import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProofCodec; import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldRunOwnedFixtureLifecycleEvidence; import net.firedevops.firemud.gamesession.v1.CanonicalGameplayAdmissionCandidate; import net.firedevops.firemud.gamesession.v1.CanonicalGameplayAdmissionDecisionStatus; import net.firedevops.firemud.gamesession.v1.CanonicalGameplayAdmissionOriginKind; @@ -70,6 +72,8 @@ public final class CanonicalGameplayAdmissionDecisionReadGrpcCodec { + framedFieldBytes(2, CanonicalGameplayRosterOwnerReadGrpcCodec.MAX_RESPONSE_BYTES) + framedFieldBytes(3, MAX_TARGET_RESOLUTION_RESPONSE_WIRE_BYTES) + framedFieldBytes(4, GrpcRequestBytePolicy.ORDINARY_MAXIMUM_BYTES); + // The run-owned fixture source (field 5, at most 64 KiB) replaces the Human source (field 2), + // never joins it, so the Human field-2 budget above also bounds the fixture variant. private static final int SCHEMA_VERSION = 1; private static final UUID NIL_UUID = new UUID(0L, 0L); @@ -493,12 +497,18 @@ public CanonicalGameplayRosterOwnerReadEvidence.Request selector() { } } - /** Complete current target tied to the existing validated route proof and policy-set evidence. */ + /** + * Complete current target tied to the existing validated route proof and exactly one source: the + * Human policy-set evidence with its World lifecycle, or the run-owned fixture's sealed retained + * policy with its World fixture lifecycle. Human accessors refuse the fixture variant. + */ public static final class PublishedRealmEvidence { private final CanonicalGameplayRosterOwnerReadEvidence.Request selector; private final CanonicalGameplayRosterOwnerReadEvidence sourceEvidence; private final Target currentTarget; private final WorldCanonicalInstanceLifecycleEvidence worldLifecycleEvidence; + private final CanonicalGameplayRunOwnedFixtureSourceEvidence fixtureSource; + private final WorldRunOwnedFixtureLifecycleEvidence fixtureLifecycleEvidence; private PublishedRealmEvidence( CanonicalGameplayRosterOwnerReadEvidence.Request selector, @@ -509,13 +519,34 @@ private PublishedRealmEvidence( this.sourceEvidence = sourceEvidence; this.currentTarget = currentTarget; this.worldLifecycleEvidence = worldLifecycleEvidence; + this.fixtureSource = null; + this.fixtureLifecycleEvidence = null; + } + + private PublishedRealmEvidence( + CanonicalGameplayRosterOwnerReadEvidence.Request selector, + CanonicalGameplayRunOwnedFixtureSourceEvidence fixtureSource, + Target currentTarget, + WorldRunOwnedFixtureLifecycleEvidence fixtureLifecycleEvidence) { + this.selector = selector; + this.sourceEvidence = null; + this.currentTarget = currentTarget; + this.worldLifecycleEvidence = null; + this.fixtureSource = fixtureSource; + this.fixtureLifecycleEvidence = fixtureLifecycleEvidence; } public CanonicalGameplayRosterOwnerReadEvidence.Request selector() { return selector; } + public boolean isRunOwnedFixture() { + return fixtureSource != null; + } + + /** Human published source; the run-owned fixture has none. */ public CanonicalGameplayRosterOwnerReadEvidence sourceEvidence() { + requireHuman(); return sourceEvidence; } @@ -523,9 +554,34 @@ public Target currentTarget() { return currentTarget; } + /** Human World lifecycle evidence; the run-owned fixture carries its own lifecycle variant. */ public WorldCanonicalInstanceLifecycleEvidence worldLifecycleEvidence() { + requireHuman(); return worldLifecycleEvidence; } + + public CanonicalGameplayRunOwnedFixtureSourceEvidence fixtureSource() { + requireFixture(); + return fixtureSource; + } + + public WorldRunOwnedFixtureLifecycleEvidence fixtureLifecycleEvidence() { + requireFixture(); + return fixtureLifecycleEvidence; + } + + private void requireHuman() { + if (fixtureSource != null) { + throw new IllegalStateException( + "Run-owned fixture realm evidence has no Human published source or lifecycle"); + } + } + + private void requireFixture() { + if (fixtureSource == null) { + throw new IllegalStateException("Human published realm evidence has no fixture source"); + } + } } /** Complete CanonicalGameplayBindingIdentity in Account-independent common types. */ @@ -693,6 +749,37 @@ public static GetPublishedRealmAdmissionOwnerReadResponse toPublishedRealmRespon return response; } + /** + * Produces the run-owned fixture variant: the exact sealed fixture source plus the same read's + * exact current route and World fixture lifecycle. It carries no Human published source. + */ + public static GetPublishedRealmAdmissionOwnerReadResponse toPublishedRealmFixtureResponse( + PublishedRealmRequest request, + CanonicalGameplayRunOwnedFixtureSourceEvidence fixtureSource, + Target currentTarget, + WorldRunOwnedFixtureLifecycleEvidence fixtureLifecycleEvidence) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(fixtureSource, "fixtureSource"); + Objects.requireNonNull(currentTarget, "currentTarget"); + requirePublishedTargetMatchesFixtureSource(currentTarget, request.selector(), fixtureSource); + requirePublishedRunOwnedFixtureLifecycle( + request.selector(), currentTarget, fixtureSource, fixtureLifecycleEvidence); + GetPublishedRealmAdmissionOwnerReadResponse response = + GetPublishedRealmAdmissionOwnerReadResponse.newBuilder() + .addSchemaVersion(SCHEMA_VERSION) + .addCurrentTarget(toTargetEvidence(currentTarget)) + .addWorldLifecycleEvidence( + ByteString.copyFrom(fixtureLifecycleEvidence.canonicalBytes())) + .addRunOwnedFixtureSource(ByteString.copyFrom(fixtureSource.canonicalBytes())) + .build(); + requireWireSize( + response.getSerializedSize(), + MAX_PUBLISHED_REALM_RESPONSE_WIRE_BYTES, + "published realm read response"); + fromPublishedRealmResponse(request, response); + return response; + } + /** Reuses the existing full source validator and validates the complete route-to-source tuple. */ public static PublishedRealmEvidence fromPublishedRealmResponse( PublishedRealmRequest request, GetPublishedRealmAdmissionOwnerReadResponse response) { @@ -706,6 +793,12 @@ public static PublishedRealmEvidence fromPublishedRealmResponse( || one(response.getSchemaVersionList(), "published schemaVersion") != SCHEMA_VERSION) { throw invalid("Closed schema-1 published realm response required"); } + if (response.getPublishedSourceCount() + response.getRunOwnedFixtureSourceCount() != 1) { + throw invalid("Exactly one published or run-owned fixture source is required"); + } + if (response.getRunOwnedFixtureSourceCount() == 1) { + return fromPublishedRealmFixtureResponse(request, response); + } CanonicalGameplayRosterOwnerReadEvidence sourceEvidence = CanonicalGameplayRosterOwnerReadGrpcCodec.fromResponse( request.selector(), one(response.getPublishedSourceList(), "published source")); @@ -720,6 +813,86 @@ public static PublishedRealmEvidence fromPublishedRealmResponse( return new PublishedRealmEvidence(request.selector(), sourceEvidence, currentTarget, lifecycle); } + private static PublishedRealmEvidence fromPublishedRealmFixtureResponse( + PublishedRealmRequest request, GetPublishedRealmAdmissionOwnerReadResponse response) { + final CanonicalGameplayRunOwnedFixtureSourceEvidence fixtureSource; + final WorldRunOwnedFixtureLifecycleEvidence lifecycle; + try { + fixtureSource = + CanonicalGameplayRunOwnedFixtureSourceEvidence.fromStored( + one(response.getRunOwnedFixtureSourceList(), "run-owned fixture source") + .toByteArray()); + lifecycle = + WorldRunOwnedFixtureLifecycleEvidence.fromStored( + one(response.getWorldLifecycleEvidenceList(), "World lifecycle evidence") + .toByteArray()); + } catch (IllegalArgumentException malformed) { + throw invalid("Run-owned fixture source or lifecycle evidence is invalid"); + } + Target currentTarget = + parseTargetEvidence(one(response.getCurrentTargetList(), "current target")); + requirePublishedTargetMatchesFixtureSource(currentTarget, request.selector(), fixtureSource); + requirePublishedRunOwnedFixtureLifecycle( + request.selector(), currentTarget, fixtureSource, lifecycle); + return new PublishedRealmEvidence(request.selector(), fixtureSource, currentTarget, lifecycle); + } + + private static void requirePublishedTargetMatchesFixtureSource( + Target target, + CanonicalGameplayRosterOwnerReadEvidence.Request selector, + CanonicalGameplayRunOwnedFixtureSourceEvidence fixtureSource) { + if (!fixtureSource.request().equals(selector)) { + throw invalid("Run-owned fixture source differs from its exact selector"); + } + requirePublishedTargetMatchesSelector( + target, selector, fixtureSource.admissionPointerSnapshotDigest()); + byte[] targetProof = + GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes( + ownerProofFromTarget(target)); + byte[] sourceProof = + GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes( + fixtureSource.gameSessionOwnerProof()); + if (!Arrays.equals(targetProof, sourceProof)) { + throw invalid("Published realm target changed the exact Game Session owner proof"); + } + var capability = fixtureSource.fixturePolicy().capability(); + if (!target.characterCreationPolicy().equals(capability.characterCreationPolicy()) + || !target.worldSlug().equals(capability.worldSlug()) + || !target.realmSlug().equals(capability.realmSlug())) { + throw invalid("Published realm target differs from the exact sealed fixture policy"); + } + } + + /** Fixture counterpart of the Human lifecycle check: exact request tuple, ACTIVE, epoch, seal. */ + private static void requirePublishedRunOwnedFixtureLifecycle( + CanonicalGameplayRosterOwnerReadEvidence.Request selector, + Target target, + CanonicalGameplayRunOwnedFixtureSourceEvidence fixtureSource, + WorldRunOwnedFixtureLifecycleEvidence lifecycle) { + Objects.requireNonNull(lifecycle, "Fresh World fixture lifecycle evidence is required"); + var request = lifecycle.request(); + var bundle = fixtureSource.fixturePolicy().launchReadEvidence().publishedReleaseBundle(); + String sealEvidenceDigest = fixtureSource.fixturePolicySealEvidenceDigest(); + if (!selector.requestUuid().equals(request.readRequestId()) + || !selector.targetNamespace().equals(request.targetNamespace()) + || !selector.canonicalTenantUuid().equals(request.canonicalTenantId()) + || !selector.worldSlug().equals(request.worldSlug()) + || !selector.canonicalGameInstanceUuid().equals(request.canonicalGameInstanceId()) + || !selector.playableStateNamespaceUuid().equals(request.playableStateNamespaceId()) + || !selector.playableStateScope().equals(request.playableStateScope()) + || !request.publicProduction() + || !selector.canonicalVersionUuid().equals(request.canonicalVersionId()) + || !target.canonicalVersionId().toString().equals(bundle.getCanonicalVersionId()) + || target.runtimeVersionId() != bundle.getVersionId() + || !"ACTIVE".equals(lifecycle.lifecycleStatus()) + || lifecycle.lifecycleEpoch() != target.activeWorldEpoch() + || !sealEvidenceDigest.equals(request.expectedReleaseAttestationDigest()) + || !sealEvidenceDigest.equals(lifecycle.fixtureProvenanceDigest())) { + throw invalid( + "Fresh World ACTIVE fixture lifecycle differs from the exact target and sealed policy"); + } + } + private static void requirePublishedWorldLifecycle( CanonicalGameplayRosterOwnerReadEvidence.Request selector, Target target, @@ -1193,6 +1366,15 @@ private static void requirePublishedTargetMatchesSource( Target target, CanonicalGameplayRosterOwnerReadEvidence.Request selector, CanonicalGameplayRosterOwnerReadEvidence sourceEvidence) { + requirePublishedTargetMatchesSelector( + target, selector, sourceEvidence.admissionPointerSnapshotDigest()); + requirePublishedHumanSourceProof(target, sourceEvidence); + } + + private static void requirePublishedTargetMatchesSelector( + Target target, + CanonicalGameplayRosterOwnerReadEvidence.Request selector, + String admissionPointerSnapshotDigest) { if (!target.targetNamespace().equals(selector.targetNamespace()) || !target.canonicalTenantId().equals(selector.canonicalTenantUuid()) || !target.worldSlug().equals(selector.worldSlug()) @@ -1205,11 +1387,13 @@ private static void requirePublishedTargetMatchesSource( || target.catalogRevision() != selector.expectedCatalogRevision() || target.pointerVersion() != selector.expectedPointerVersion() || target.activeWorldEpoch() != selector.expectedActiveWorldEpoch() - || !target - .admissionPointerSnapshotDigest() - .equals(sourceEvidence.admissionPointerSnapshotDigest())) { + || !target.admissionPointerSnapshotDigest().equals(admissionPointerSnapshotDigest)) { throw invalid("Published realm target differs from its exact source selector or pointer"); } + } + + private static void requirePublishedHumanSourceProof( + Target target, CanonicalGameplayRosterOwnerReadEvidence sourceEvidence) { byte[] targetProof = GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes( ownerProofFromTarget(target)); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalRealmCatalogSnapshot.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalRealmCatalogSnapshot.java index c6ddb1c37e..d87ded7c19 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalRealmCatalogSnapshot.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalRealmCatalogSnapshot.java @@ -1,10 +1,14 @@ package net.firedevops.firemud.gamesession.dto; +import java.util.Arrays; import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; -/** Immutable catalog evidence for one public-production realm; it is not admission authority. */ +/** + * Immutable catalog evidence for one public-production realm; it is not admission authority. A + * run-owned fixture row carries its retained sealed fixture policy; Human rows carry none. + */ public record CanonicalRealmCatalogSnapshot( String targetNamespace, UUID tenantId, @@ -22,9 +26,104 @@ public record CanonicalRealmCatalogSnapshot( UUID creationRequestId, String requestDigest, String receiptDigest, - IntakeReceipt sourceIntakeReceipt) { + IntakeReceipt sourceIntakeReceipt, + FixturePolicy fixturePolicy) { private static final UUID NIL_UUID = new UUID(0L, 0L); + /** + * Catalog-retained run-owned fixture policy request bytes and its owner seal. Structural copy + * only; the catalog repository independently verified it on readback. + */ + public record FixturePolicy( + byte[] requestBytes, + UUID sealOperationId, + String sealRequestDigest, + String sealEvidenceDigest) { + public FixturePolicy { + Objects.requireNonNull(requestBytes, "requestBytes"); + if (requestBytes.length == 0) { + throw new IllegalArgumentException("Fixture policy request bytes are required"); + } + requestBytes = requestBytes.clone(); + requireNonNil(sealOperationId, "sealOperationId"); + Objects.requireNonNull(sealRequestDigest, "sealRequestDigest"); + Objects.requireNonNull(sealEvidenceDigest, "sealEvidenceDigest"); + } + + @Override + public byte[] requestBytes() { + return requestBytes.clone(); + } + + @Override + public boolean equals(Object other) { + return other instanceof FixturePolicy that + && Arrays.equals(requestBytes, that.requestBytes) + && sealOperationId.equals(that.sealOperationId) + && sealRequestDigest.equals(that.sealRequestDigest) + && sealEvidenceDigest.equals(that.sealEvidenceDigest); + } + + @Override + public int hashCode() { + return Objects.hash( + Arrays.hashCode(requestBytes), sealOperationId, sealRequestDigest, sealEvidenceDigest); + } + + @Override + public String toString() { + return "FixturePolicy[sealOperationId=" + + sealOperationId + + ", sealEvidenceDigest=" + + sealEvidenceDigest + + "]"; + } + } + + /** Human catalog row without a run-owned fixture policy. */ + public CanonicalRealmCatalogSnapshot( + String targetNamespace, + UUID tenantId, + String tenantSlug, + String worldSlug, + UUID realmId, + String realmSlug, + String realmDisplayName, + boolean visible, + boolean publicProduction, + String stateScope, + UUID playableStateNamespaceId, + String characterCreationPolicy, + long catalogRevision, + UUID creationRequestId, + String requestDigest, + String receiptDigest, + IntakeReceipt sourceIntakeReceipt) { + this( + targetNamespace, + tenantId, + tenantSlug, + worldSlug, + realmId, + realmSlug, + realmDisplayName, + visible, + publicProduction, + stateScope, + playableStateNamespaceId, + characterCreationPolicy, + catalogRevision, + creationRequestId, + requestDigest, + receiptDigest, + sourceIntakeReceipt, + null); + } + + public boolean isRunOwnedFixture() { + return fixturePolicy != null; + } + public CanonicalRealmCatalogSnapshot { Objects.requireNonNull(targetNamespace, "targetNamespace"); requireNonNil(tenantId, "tenantId"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepository.java index bb1242d251..66eb491342 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepository.java @@ -823,11 +823,18 @@ private CanonicalRealmCatalogSnapshot toSnapshot(Record record) { null); byte[] policyBytes = record.get("complete_policy_set_evidence", byte[].class); byte[] fixtureBytes = record.get("fixture_policy_request_bytes", byte[].class); + CanonicalRealmCatalogSnapshot.FixturePolicy fixturePolicy = null; if (policyBytes != null && fixtureBytes == null) { validateCompleteCatalogPolicy( storedRequest, sourceReceipt, RealmPolicyPublishedEvidenceCodec.decode(policyBytes)); } else if (policyBytes == null && fixtureBytes != null) { validateRetainedFixturePolicy(record, storedRequest, sourceReceipt, fixtureBytes); + fixturePolicy = + new CanonicalRealmCatalogSnapshot.FixturePolicy( + fixtureBytes, + required(record, "fixture_policy_seal_operation_id", UUID.class), + required(record, "fixture_policy_seal_request_digest", String.class), + required(record, "fixture_policy_seal_evidence_digest", String.class)); policyBytes = fixtureBytes; } else { throw new InvalidCatalogEvidenceException( @@ -877,7 +884,8 @@ private CanonicalRealmCatalogSnapshot toSnapshot(Record record) { requestId, persistedRequestDigest, required(record, RECEIPT_DIGEST, "catalog receipt digest"), - sourceReceipt); + sourceReceipt, + fixturePolicy); } catch (InvalidCatalogEvidenceException | CatalogConflictException exception) { throw exception; } catch (RuntimeException exception) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPublishedPlayerRouteReadService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPublishedPlayerRouteReadService.java index 1fd447c38f..17a7c086ee 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPublishedPlayerRouteReadService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPublishedPlayerRouteReadService.java @@ -2,6 +2,7 @@ import io.grpc.Status; import io.grpc.StatusRuntimeException; +import java.util.Arrays; import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; @@ -10,7 +11,9 @@ import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyEvidence; import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec; import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; +import net.firedevops.firemud.common.world.CanonicalGameplayRunOwnedFixtureSourceEvidence; import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProofCodec; import net.firedevops.firemud.common.world.PreseededActorAssignmentOwnerReadEvidence; @@ -29,7 +32,8 @@ /** * Read-only composition of current Game Session routing and a fresh complete Game Design policy - * set. A result is source evidence only and does not enable PLAY or actor admission. + * set, or for the run-owned Compose fixture its catalog-retained sealed fixture policy. A result is + * source evidence only and does not enable PLAY or actor admission. */ public final class CanonicalPublishedPlayerRouteReadService { private final String targetNamespace; @@ -62,7 +66,7 @@ public static CanonicalPublishedPlayerRouteReadService unavailable() { */ public CanonicalPublishedPlayerRoute readCurrent(CanonicalPlayableTarget expected) { Objects.requireNonNull(expected, "expected"); - return readCurrent(expected, null); + return requirePublished(readCurrent(expected, null)); } /** @@ -73,7 +77,7 @@ public CanonicalPublishedPlayerRoute readCurrent(CanonicalPlayableTarget expecte public CanonicalGameplayRosterOwnerReadEvidence readCurrent( CanonicalGameplayRosterOwnerReadEvidence.Request request) { Objects.requireNonNull(request, "request"); - CanonicalPublishedPlayerRoute route = readCurrent(null, request); + CanonicalPublishedPlayerRoute route = requirePublished(readCurrent(null, request)); return new CanonicalGameplayRosterOwnerReadEvidence( request, route.route().admissionPointerSnapshotDigest(), @@ -81,6 +85,80 @@ public CanonicalGameplayRosterOwnerReadEvidence readCurrent( route.policySetEvidence()); } + /** + * Reads the exact caller-selected target for the Account published-realm owner read: the full + * Human published source, or for a run-owned fixture launch its retained sealed fixture policy. + * Neither variant establishes Account membership or PLAY authority. + */ + public AdmissionSource readCurrentAdmissionSource( + CanonicalGameplayRosterOwnerReadEvidence.Request request) { + Objects.requireNonNull(request, "request"); + CurrentSource current = readCurrent(null, request); + if (current.published() != null) { + CanonicalPublishedPlayerRoute route = current.published(); + return new AdmissionSource( + new CanonicalGameplayRosterOwnerReadEvidence( + request, + route.route().admissionPointerSnapshotDigest(), + ownerProof(route.route()), + route.policySetEvidence()), + null); + } + var fixture = current.fixturePolicy(); + try { + return new AdmissionSource( + null, + new CanonicalGameplayRunOwnedFixtureSourceEvidence( + request, + current.route().admissionPointerSnapshotDigest(), + ownerProof(current.route()), + fixture.requestBytes(), + fixture.sealOperationId(), + fixture.sealRequestDigest(), + fixture.sealEvidenceDigest())); + } catch (IllegalArgumentException invalid) { + throw new InvalidAuthorityException( + "Run-owned fixture source is not the exact current route", invalid); + } + } + + /** Exactly one Human published source or run-owned fixture source for one exact route. */ + public record AdmissionSource( + CanonicalGameplayRosterOwnerReadEvidence published, + CanonicalGameplayRunOwnedFixtureSourceEvidence runOwnedFixture) { + public AdmissionSource { + if ((published == null) == (runOwnedFixture == null)) { + throw new IllegalArgumentException( + "Exactly one published or run-owned fixture admission source is required"); + } + } + + public boolean isRunOwnedFixture() { + return runOwnedFixture != null; + } + } + + /** Exactly one Human published route or run-owned fixture route with its retained policy. */ + private record CurrentSource( + CanonicalPlayableTarget route, + CanonicalPublishedPlayerRoute published, + CanonicalRealmCatalogSnapshot.FixturePolicy fixturePolicy) { + private CurrentSource { + Objects.requireNonNull(route, "route"); + if ((published == null) == (fixturePolicy == null)) { + throw new IllegalArgumentException("Exactly one canonical route source is required"); + } + } + } + + private static CanonicalPublishedPlayerRoute requirePublished(CurrentSource current) { + if (current.published() == null) { + throw new InvalidAuthorityException( + "Run-owned fixture route has no Game Design published policy source"); + } + return current.published(); + } + /** * Reads assignment source evidence from exact immutable selectors while deriving current pointer * and lifecycle counters from Game Session-owned route evidence. This is a staging-only source @@ -102,7 +180,7 @@ public PreseededActorAssignmentOwnerReadEvidence readCurrentForAssignment( return new PreseededActorAssignmentOwnerReadEvidence(request, sourceEvidence); } - private CanonicalPublishedPlayerRoute readCurrent( + private CurrentSource readCurrent( CanonicalPlayableTarget expected, CanonicalGameplayRosterOwnerReadEvidence.Request request) { if ((expected == null) == (request == null)) { throw new IllegalArgumentException("Exactly one canonical route selector is required"); @@ -125,6 +203,9 @@ private CanonicalPublishedPlayerRoute readCurrent( CanonicalRealmCatalogSnapshot catalogBefore = readCatalog(before); CanonicalInitialAdmissionLaunchTarget launchBefore = readLaunch(before); requireCurrentRouteBinding(before, catalogBefore, launchBefore); + if (launchBefore.association().isRunOwnedFixture()) { + return readCurrentFixture(expected, request, before, catalogBefore, launchBefore); + } PublishedRealmEntryPolicySetEvidence policySet = readPolicy(before.canonicalTenantId(), before.canonicalVersionId()); @@ -156,7 +237,108 @@ private CanonicalPublishedPlayerRoute readCurrent( "Game Design policy source or capture changed during owner read"); } - return new CanonicalPublishedPlayerRoute(after, complete, selected); + return new CurrentSource( + after, new CanonicalPublishedPlayerRoute(after, complete, selected), null); + } + + /** + * Run-owned fixture variant: no Game Design publication exists, so the catalog-retained sealed + * fixture policy (independently verified by the catalog owner on readback) replaces the policy + * read, and the same complete route/catalog/launch reread brackets it. + */ + private CurrentSource readCurrentFixture( + CanonicalPlayableTarget expected, + CanonicalGameplayRosterOwnerReadEvidence.Request request, + CanonicalPlayableTarget before, + CanonicalRealmCatalogSnapshot catalogBefore, + CanonicalInitialAdmissionLaunchTarget launchBefore) { + requireRunOwnedFixturePolicy(before, catalogBefore, launchBefore); + + CanonicalPlayableTarget after = + expected == null ? readRoute(request.canonicalTenantUuid()) : readRoute(before); + if (!before.equals(after)) { + throw new StaleAuthorityException("Canonical player route changed during fixture read"); + } + if (request != null) { + requireExpectedRequest(request, after); + } + CanonicalRealmCatalogSnapshot catalogAfter = readCatalog(after); + CanonicalInitialAdmissionLaunchTarget launchAfter = readLaunch(after); + if (!catalogBefore.equals(catalogAfter) + || !sameCurrentLaunchBinding(launchBefore, launchAfter)) { + throw new StaleAuthorityException( + "Canonical source or complete fixture launch binding changed during owner read"); + } + requireCurrentRouteBinding(after, catalogAfter, launchAfter); + requireRunOwnedFixturePolicy(after, catalogAfter, launchAfter); + return new CurrentSource(after, null, catalogAfter.fixturePolicy()); + } + + private void requireRunOwnedFixturePolicy( + CanonicalPlayableTarget route, + CanonicalRealmCatalogSnapshot catalog, + CanonicalInitialAdmissionLaunchTarget launch) { + CanonicalGameInstanceLaunchAssociation association = launch.association(); + CanonicalRealmCatalogSnapshot.FixturePolicy fixture = catalog.fixturePolicy(); + if (!association.isRunOwnedFixture() || fixture == null) { + throw new InvalidAuthorityException( + "Run-owned fixture route requires its catalog-retained fixture policy"); + } + final RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicyRequest parsed; + final String requestDigest; + final String evidenceDigest; + try { + byte[] requestBytes = fixture.requestBytes(); + parsed = + RunOwnedInitialAdmissionFixtureWireCodec.parseFixturePolicyRequestBytes(requestBytes); + requestDigest = + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestDigest( + parsed.capability(), + parsed.creationEvidence(), + parsed.sourceEvidence(), + parsed.launchReadEvidence()); + evidenceDigest = + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyEvidenceDigest( + fixture.sealOperationId(), fixture.sealRequestDigest()); + if (!Arrays.equals( + requestBytes, + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestBytes( + parsed.capability(), + parsed.creationEvidence(), + parsed.sourceEvidence(), + parsed.launchReadEvidence()))) { + throw new InvalidAuthorityException("Retained fixture policy is not canonical"); + } + } catch (IllegalArgumentException invalid) { + throw new InvalidAuthorityException("Retained fixture policy is invalid", invalid); + } + var capability = parsed.capability(); + var bundle = parsed.launchReadEvidence().publishedReleaseBundle(); + var versionState = parsed.launchReadEvidence().versionState(); + var descriptor = association.descriptor(); + if (!capability.visible() + || !capability.publicProductionRealm() + || !"SHARED".equals(capability.stateScope()) + || !"PRESEEDED_ONLY".equals(capability.characterCreationPolicy()) + || !catalog.visible() + || !catalog.publicProduction() + || !"SHARED".equals(catalog.stateScope()) + || !capability.characterCreationPolicy().equals(catalog.characterCreationPolicy()) + || !capability.worldSlug().equals(route.worldSlug()) + || !capability.realmSlug().equals(route.realmSlug()) + || !parsed.sourceEvidence().equals(catalog.sourceIntakeReceipt().source()) + || !route.canonicalVersionId().toString().equals(bundle.getCanonicalVersionId()) + || !route.canonicalVersionId().equals(association.fixtureCanonicalVersionId()) + || !UUID.fromString(capability.operationId()).equals(fixture.sealOperationId()) + || !requestDigest.equals(fixture.sealRequestDigest()) + || !evidenceDigest.equals(fixture.sealEvidenceDigest()) + || !fixture.sealEvidenceDigest().equals(association.fixtureProvenanceDigest()) + || !descriptor.publishedReleaseBundleRef().equals(bundle.getPublishedReleaseBundleRef()) + || descriptor.versionId() != bundle.getVersionId() + || descriptor.versionStateEpoch() != versionState.getVersionStateEpoch()) { + throw new InvalidAuthorityException( + "Retained fixture policy does not match the current PRESEEDED_ONLY fixture launch"); + } } private GameSessionCanonicalInitialAdmissionOwnerProof ownerProof(CanonicalPlayableTarget route) { @@ -349,7 +531,10 @@ private PublishedRealmEntryPolicyEvidence requirePublishedPreseededPolicy( var terminal = GameDesignPublicationTerminalEvidence.fromStored(complete.terminalEvidenceBytes()); var association = launch.association(); - var descriptor = association.launchBindingEvidence().descriptor(); + if (association.isRunOwnedFixture()) { + throw new InvalidAuthorityException("Run-owned fixture launch has no published policy"); + } + var descriptor = association.descriptor(); var release = association.launchBindingEvidence().releaseAttestation(); if (!operation.account().input().selection().target().equals(targetProof) || !targetNamespace.equals(operation.world().request().targetNamespace()) @@ -413,8 +598,42 @@ private void requireCurrentRouteBinding( CanonicalInitialAdmissionLaunchTarget launch) { CanonicalGameInstanceLaunchAssociation association = launch.association(); var source = catalog.sourceIntakeReceipt().source(); - var descriptor = association.launchBindingEvidence().descriptor(); + var descriptor = association.descriptor(); + if (association.isRunOwnedFixture() != catalog.isRunOwnedFixture()) { + throw new InvalidAuthorityException( + "Canonical catalog and launch disagree on run-owned fixture provenance"); + } + if (association.isRunOwnedFixture()) { + requireCurrentRouteSharedBinding(route, catalog, launch, association, source, descriptor); + if (!route.canonicalVersionId().equals(association.fixtureCanonicalVersionId())) { + throw new InvalidAuthorityException( + "Canonical route and run-owned fixture launch disagree on content version"); + } + return; + } var release = association.launchBindingEvidence().releaseAttestation(); + requireCurrentRouteSharedBinding(route, catalog, launch, association, source, descriptor); + if (!route.canonicalTenantId().equals(release.canonicalTenantId()) + || !route.canonicalVersionId().equals(release.canonicalVersionId()) + || !route.worldSlug().equals(release.worldSlug()) + || !targetNamespace.equals(release.targetNamespace()) + || !source.operationId().equals(release.authoredWorldSourceOperationId()) + || !source.evidenceDigest().equals(release.authoredWorldSourceEvidenceDigest()) + || descriptor.versionStateEpoch() != release.versionStateEpoch() + || !descriptor.publishedReleaseBundleRef().equals(release.publishedReleaseBundleRef())) { + throw new InvalidAuthorityException( + "Canonical catalog, route, and complete launch binding disagree"); + } + } + + /** Route, catalog, launch and descriptor binding shared by the Human and fixture variants. */ + private void requireCurrentRouteSharedBinding( + CanonicalPlayableTarget route, + CanonicalRealmCatalogSnapshot catalog, + CanonicalInitialAdmissionLaunchTarget launch, + CanonicalGameInstanceLaunchAssociation association, + net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence source, + net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence descriptor) { if (!targetNamespace.equals(route.targetNamespace()) || !targetNamespace.equals(catalog.targetNamespace()) || !route.canonicalTenantId().equals(catalog.tenantId()) @@ -441,17 +660,9 @@ private void requireCurrentRouteBinding( || !targetNamespace.equals(descriptor.targetNamespace()) || !route.canonicalTenantId().equals(descriptor.canonicalTenantId()) || !route.worldSlug().equals(descriptor.worldSlug()) - || !route.canonicalTenantId().equals(release.canonicalTenantId()) - || !route.canonicalVersionId().equals(release.canonicalVersionId()) - || !route.worldSlug().equals(release.worldSlug()) - || !targetNamespace.equals(release.targetNamespace()) || !source.operationId().equals(descriptor.authoredWorldSourceOperationId()) || !source.evidenceDigest().equals(descriptor.authoredWorldSourceEvidenceDigest()) - || !source.operationId().equals(release.authoredWorldSourceOperationId()) - || !source.evidenceDigest().equals(release.authoredWorldSourceEvidenceDigest()) || descriptor.versionId() != route.runtimeVersionId() - || descriptor.versionStateEpoch() != release.versionStateEpoch() - || !descriptor.publishedReleaseBundleRef().equals(release.publishedReleaseBundleRef()) || !association.controlPlaneRequestId().equals(descriptor.controlPlaneRequestId()) || !association.launchDescriptorId().equals(descriptor.launchDescriptorId())) { throw new InvalidAuthorityException( @@ -490,7 +701,10 @@ private static boolean sameCurrentLaunchBinding( && first.launchDescriptorId().equals(second.launchDescriptorId()) && first.capturedStartingRowVersion() == second.capturedStartingRowVersion() && first.currentRowVersion() == second.currentRowVersion() - && first.launchBindingEvidence().equals(second.launchBindingEvidence()) + && Objects.equals(first.launchBindingEvidence(), second.launchBindingEvidence()) + && Objects.equals(first.fixtureDescriptor(), second.fixtureDescriptor()) + && Objects.equals(first.fixtureProvenanceDigest(), second.fixtureProvenanceDigest()) + && Objects.equals(first.fixtureCanonicalVersionId(), second.fixtureCanonicalVersionId()) && first.currentGameInstanceStatus() == second.currentGameInstanceStatus(); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayAdmissionDecisionReadGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayAdmissionDecisionReadGrpcService.java index 5a9188b515..2aecd47179 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayAdmissionDecisionReadGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayAdmissionDecisionReadGrpcService.java @@ -20,6 +20,7 @@ import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleClient; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldRunOwnedFixtureLifecycleEvidence; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision; import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionLaunchTarget; @@ -260,49 +261,58 @@ public void getPublishedRealmAdmissionOwnerRead( return; } var launchBefore = readCurrentLaunch(before); - var sourceBefore = publishedReader.readCurrent(parsed.selector()); - var association = launchBefore.association(); - var descriptor = association.launchBindingEvidence().descriptor(); - var lifecycleRequest = - new WorldCanonicalInstanceLifecycleEvidence.Request( - 1, - parsed.selector().requestUuid(), - workloadNamespace, - before.canonicalTenantId(), - before.worldSlug(), - before.canonicalGameInstanceId(), - before.playableStateNamespaceId(), - before.playableStateScope(), - true, - association.controlPlaneRequestId(), - before.canonicalVersionId(), - descriptor.requestDigest(), - descriptor.resultDigest(), - association.launchBindingEvidence().releaseAttestation().evidenceDigest()); - requireOutsideSourceSql(); - var lifecycle = readWorld(lifecycleRequest); - if (lifecycle == null - || !lifecycleRequest.equals(lifecycle.request()) - || !"ACTIVE".equals(lifecycle.lifecycleStatus()) - || lifecycle.lifecycleEpoch() != before.activeWorldEpoch() - || !association.launchBindingEvidence().equals(lifecycle.launchBinding())) { - fail(observer, Status.FAILED_PRECONDITION); - return; - } - var sourceAfter = publishedReader.readCurrent(parsed.selector()); - var after = routeReader.readCurrentTarget(parsed.selector().canonicalTenantUuid()); - if (!before.equals(after)) { - fail(observer, Status.FAILED_PRECONDITION); - return; - } - var launchAfter = readCurrentLaunch(after); - if (!launchBefore.equals(launchAfter) || !sourceBefore.equals(sourceAfter)) { - fail(observer, Status.FAILED_PRECONDITION); - return; + if (launchBefore.association().isRunOwnedFixture()) { + var fixtureResponse = readRunOwnedFixtureOwner(parsed, before, launchBefore); + if (fixtureResponse == null) { + fail(observer, Status.FAILED_PRECONDITION); + return; + } + response = fixtureResponse; + } else { + var sourceBefore = publishedReader.readCurrent(parsed.selector()); + var association = launchBefore.association(); + var descriptor = association.launchBindingEvidence().descriptor(); + var lifecycleRequest = + new WorldCanonicalInstanceLifecycleEvidence.Request( + 1, + parsed.selector().requestUuid(), + workloadNamespace, + before.canonicalTenantId(), + before.worldSlug(), + before.canonicalGameInstanceId(), + before.playableStateNamespaceId(), + before.playableStateScope(), + true, + association.controlPlaneRequestId(), + before.canonicalVersionId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + association.launchBindingEvidence().releaseAttestation().evidenceDigest()); + requireOutsideSourceSql(); + var lifecycle = readWorld(lifecycleRequest); + if (lifecycle == null + || !lifecycleRequest.equals(lifecycle.request()) + || !"ACTIVE".equals(lifecycle.lifecycleStatus()) + || lifecycle.lifecycleEpoch() != before.activeWorldEpoch() + || !association.launchBindingEvidence().equals(lifecycle.launchBinding())) { + fail(observer, Status.FAILED_PRECONDITION); + return; + } + var sourceAfter = publishedReader.readCurrent(parsed.selector()); + var after = routeReader.readCurrentTarget(parsed.selector().canonicalTenantUuid()); + if (!before.equals(after)) { + fail(observer, Status.FAILED_PRECONDITION); + return; + } + var launchAfter = readCurrentLaunch(after); + if (!launchBefore.equals(launchAfter) || !sourceBefore.equals(sourceAfter)) { + fail(observer, Status.FAILED_PRECONDITION); + return; + } + response = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toPublishedRealmResponse( + parsed, sourceAfter, toTarget(after), lifecycle); } - response = - CanonicalGameplayAdmissionDecisionReadGrpcCodec.toPublishedRealmResponse( - parsed, sourceAfter, toTarget(after), lifecycle); } catch (RuntimeException failure) { failSource(observer, failure); return; @@ -310,6 +320,64 @@ public void getPublishedRealmAdmissionOwnerRead( sendSource(observer, response); } + /** + * Run-owned fixture variant of the strict owner read: the catalog-retained sealed fixture policy + * replaces the Game Design source and World's fixture lifecycle replaces the Human lifecycle. The + * same complete route, launch and source reread brackets the World read. Returns null for a stale + * or non-ACTIVE observation. + */ + private GetPublishedRealmAdmissionOwnerReadResponse readRunOwnedFixtureOwner( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmRequest parsed, + CanonicalPlayableTarget before, + CanonicalInitialAdmissionLaunchTarget launchBefore) { + var sourceBefore = publishedReader.readCurrentAdmissionSource(parsed.selector()); + var association = launchBefore.association(); + if (!sourceBefore.isRunOwnedFixture()) { + return null; + } + var descriptor = association.descriptor(); + var lifecycleRequest = + new WorldCanonicalInstanceLifecycleEvidence.Request( + 1, + parsed.selector().requestUuid(), + workloadNamespace, + before.canonicalTenantId(), + before.worldSlug(), + before.canonicalGameInstanceId(), + before.playableStateNamespaceId(), + before.playableStateScope(), + true, + association.controlPlaneRequestId(), + before.canonicalVersionId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + association.attestationDigest()); + requireOutsideSourceSql(); + var lifecycle = readWorldFixture(lifecycleRequest); + if (lifecycle == null + || !lifecycleRequest.equals(lifecycle.request()) + || !"ACTIVE".equals(lifecycle.lifecycleStatus()) + || lifecycle.lifecycleEpoch() != before.activeWorldEpoch() + || !association.fixtureProvenanceDigest().equals(lifecycle.fixtureProvenanceDigest()) + || !sourceBefore + .runOwnedFixture() + .fixturePolicySealEvidenceDigest() + .equals(lifecycle.fixtureProvenanceDigest())) { + return null; + } + var sourceAfter = publishedReader.readCurrentAdmissionSource(parsed.selector()); + var after = routeReader.readCurrentTarget(parsed.selector().canonicalTenantUuid()); + if (!before.equals(after)) { + return null; + } + var launchAfter = readCurrentLaunch(after); + if (!launchBefore.equals(launchAfter) || !sourceBefore.equals(sourceAfter)) { + return null; + } + return CanonicalGameplayAdmissionDecisionReadGrpcCodec.toPublishedRealmFixtureResponse( + parsed, sourceAfter.runOwnedFixture(), toTarget(after), lifecycle); + } + private static boolean matchesPublishedRoute( CanonicalPlayableTarget route, CanonicalGameplayRosterOwnerReadEvidence.Request selector) { return selector.targetNamespace().equals(route.targetNamespace()) @@ -372,6 +440,19 @@ private WorldCanonicalInstanceLifecycleEvidence readWorld( } } + private WorldRunOwnedFixtureLifecycleEvidence readWorldFixture( + WorldCanonicalInstanceLifecycleEvidence.Request request) { + try { + return world.readRunOwnedFixture(request, null); + } catch (IllegalStateException failure) { + if (failure.getCause() instanceof IllegalArgumentException malformed) { + throw new CanonicalPublishedPlayerRouteReadService.InvalidAuthorityException( + "World fixture lifecycle response is invalid", malformed); + } + throw new WorldReadUnavailableException(failure); + } + } + private static void requireOutsideSourceSql() { if (TransactionSynchronizationManager.isActualTransactionActive() || TransactionSynchronizationManager.isSynchronizationActive()) { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionPublishedFixtureCodecTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionPublishedFixtureCodecTest.java new file mode 100644 index 0000000000..57eed8f720 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionPublishedFixtureCodecTest.java @@ -0,0 +1,300 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import java.time.Instant; +import java.util.UUID; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.OriginKind; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.OwnerProofOutcome; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; +import net.firedevops.firemud.common.world.CanonicalGameplayRunOwnedFixtureSourceEvidence; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldRunOwnedFixtureLifecycleEvidence; +import net.firedevops.firemud.gamesession.data.RunOwnedInitialAdmissionLaunchEvidence; +import net.firedevops.firemud.gamesession.data.RunOwnedInitialAdmissionLaunchEvidenceTestFixture; +import net.firedevops.firemud.gamesession.dto.StartSessionRequest; +import org.junit.jupiter.api.Test; + +/** Closed run-owned fixture variant of the Account published-realm owner-read wire contract. */ +class CanonicalGameplayAdmissionPublishedFixtureCodecTest { + private static final String NAMESPACE = "dev"; + private static final UUID TENANT = UUID.fromString("9db3ab6f-cc09-49d2-8f93-84484397a120"); + private static final UUID SOURCE_OPERATION_ID = + UUID.fromString("3f773701-e812-44f5-8ae0-7268d543beed"); + private static final UUID REALM = UUID.fromString("23d39978-9d44-4e1a-8659-998ff9239b01"); + private static final UUID PLAYABLE_NAMESPACE = + UUID.fromString("ed1b4d88-81f8-4404-af7c-9a5dc91d3043"); + private static final UUID INSTANCE = UUID.fromString("7556e829-d531-4c61-b8d4-350c8514c4f1"); + private static final UUID VERSION = UUID.fromString("10000000-0000-4000-8000-000000000011"); + + @Test + void roundTripsRunOwnedFixtureVariantAndRefusesHumanAccessors() { + var launch = fixtureEvidence(); + var source = fixtureSource(launch, launch.fixturePolicySeal().evidenceDigest()); + assertThat(CanonicalGameplayRunOwnedFixtureSourceEvidence.fromStored(source.canonicalBytes())) + .isEqualTo(source); + + var parsed = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toPublishedRealmRequest( + source.request())); + var target = target(source); + var lifecycle = lifecycle(source, "ACTIVE", 82L); + var response = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toPublishedRealmFixtureResponse( + parsed, source, target, lifecycle); + assertThat(response.getPublishedSourceCount()).isZero(); + assertThat(response.getRunOwnedFixtureSourceCount()).isOne(); + + var evidence = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( + parsed, response); + assertThat(evidence.isRunOwnedFixture()).isTrue(); + assertThat(evidence.selector()).isEqualTo(source.request()); + assertThat(evidence.currentTarget()).isEqualTo(target); + assertThat(evidence.fixtureSource()).isEqualTo(source); + assertThat(evidence.fixtureLifecycleEvidence()).isEqualTo(lifecycle); + assertThatThrownBy(evidence::sourceEvidence).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(evidence::worldLifecycleEvidence).isInstanceOf(IllegalStateException.class); + + // Exactly one source variant: a fixture response may not also carry a Human source slot. + var both = + response.toBuilder() + .addPublishedSource( + net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterOwnerReadResponse + .getDefaultInstance()) + .build(); + assertThatThrownBy( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( + parsed, both)) + .isInstanceOf(IllegalArgumentException.class); + var neither = response.toBuilder().clearRunOwnedFixtureSource().build(); + assertThatThrownBy( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( + parsed, neither)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void refusesInactiveOrWrongEpochLifecycleAndForgedSeal() { + var launch = fixtureEvidence(); + var source = fixtureSource(launch, launch.fixturePolicySeal().evidenceDigest()); + var parsed = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toPublishedRealmRequest( + source.request())); + var target = target(source); + for (var lifecycle : + java.util.List.of( + lifecycle(source, "TERMINATING", 82L), lifecycle(source, "ACTIVE", 83L))) { + assertThatThrownBy( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toPublishedRealmFixtureResponse( + parsed, source, target, lifecycle)) + .isInstanceOf(IllegalArgumentException.class); + } + var tampered = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toPublishedRealmFixtureResponse( + parsed, source, target, lifecycle(source, "ACTIVE", 82L)) + .toBuilder() + .setWorldLifecycleEvidence( + 0, + ByteString.copyFrom( + new WorldRunOwnedFixtureLifecycleEvidence( + lifecycleRequest(source, "sha256:" + "9".repeat(64)), + "sha256:" + "9".repeat(64), + "sha256:" + "8".repeat(64), + "ACTIVE", + 82L, + 1L) + .canonicalBytes())) + .build(); + assertThatThrownBy( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( + parsed, tampered)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> fixtureSource(launch, "sha256:" + "9".repeat(64))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static CanonicalGameplayRunOwnedFixtureSourceEvidence fixtureSource( + RunOwnedInitialAdmissionLaunchEvidence launch, String sealEvidenceDigest) { + var request = + new CanonicalGameplayRosterOwnerReadEvidence.Request( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + NAMESPACE, + TENANT, + "demo", + REALM, + "production", + PLAYABLE_NAMESPACE, + "SHARED", + INSTANCE, + VERSION, + 1L, + 73L, + 82L); + var holdRequest = + new WorldCanonicalInitialAdmissionHold.Request( + NAMESPACE, + TENANT, + "demo", + REALM, + PLAYABLE_NAMESPACE, + "SHARED", + INSTANCE, + VERSION, + 82L, + "first-open-request-1", + "a".repeat(64), + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, + 1L, + null); + var proof = + new GameSessionCanonicalInitialAdmissionOwnerProof( + new WorldCanonicalInitialAdmissionHold.HoldIdentity( + holdRequest, + UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + UUID.fromString("ffffffff-ffff-4fff-8fff-ffffffffffff")), + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, + 73L, + 91L, + "sha256:" + "b".repeat(64), + false, + Instant.parse("2026-10-08T03:04:05Z")); + var seal = launch.fixturePolicySeal(); + return new CanonicalGameplayRunOwnedFixtureSourceEvidence( + request, + "1".repeat(64), + proof, + launch.fixturePolicyRequestBytes(), + seal.operationId(), + seal.requestDigest(), + sealEvidenceDigest); + } + + private static Target target(CanonicalGameplayRunOwnedFixtureSourceEvidence source) { + var request = source.request(); + var proof = source.gameSessionOwnerProof(); + var hold = proof.holdIdentity(); + return new Target( + request.targetNamespace(), + "fixture-tenant", + request.canonicalTenantUuid(), + request.worldSlug(), + "Demo World", + request.realmUuid(), + request.realmSlug(), + "Live Realm", + 1L, + 71L, + request.playableStateNamespaceUuid(), + request.playableStateScope(), + request.canonicalGameInstanceUuid(), + request.canonicalVersionUuid(), + source.fixturePolicy().launchReadEvidence().publishedReleaseBundle().getVersionId(), + request.expectedCatalogRevision(), + request.expectedPointerVersion(), + source.admissionPointerSnapshotDigest(), + request.expectedActiveWorldEpoch(), + hold.request().initialAdmissionRequestId(), + hold.request().initialAdmissionRequestDigest(), + OriginKind.NO_PRIOR_POINTER, + null, + hold.holdId(), + hold.holdFence(), + hold.holdBindingDigest(), + proof.auditEventId(), + proof.proofDigest(), + OwnerProofOutcome.COMMITTED, + false, + proof.terminalAt(), + "PRESEEDED_ONLY"); + } + + private static WorldRunOwnedFixtureLifecycleEvidence lifecycle( + CanonicalGameplayRunOwnedFixtureSourceEvidence source, String status, long epoch) { + String provenance = source.fixturePolicySealEvidenceDigest(); + return new WorldRunOwnedFixtureLifecycleEvidence( + lifecycleRequest(source, provenance), + provenance, + "sha256:" + "f".repeat(64), + status, + epoch, + 1L); + } + + private static WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest( + CanonicalGameplayRunOwnedFixtureSourceEvidence source, String attestationDigest) { + var request = source.request(); + return new WorldCanonicalInstanceLifecycleEvidence.Request( + 1, + request.requestUuid(), + request.targetNamespace(), + request.canonicalTenantUuid(), + request.worldSlug(), + request.canonicalGameInstanceUuid(), + request.playableStateNamespaceUuid(), + request.playableStateScope(), + true, + RunOwnedInitialAdmissionLaunchEvidenceTestFixture.operationId(), + request.canonicalVersionUuid(), + "sha256:" + "a".repeat(64), + "sha256:" + "b".repeat(64), + attestationDigest); + } + + private static RunOwnedInitialAdmissionLaunchEvidence fixtureEvidence() { + String operationId = RunOwnedInitialAdmissionLaunchEvidenceTestFixture.operationId(); + StartSessionRequest start = new StartSessionRequest(1L, 17L, operationId, 27L); + UUID requestId = UUID.fromString(operationId); + String tenantSlug = "fixture-tenant"; + String worldSlug = "demo"; + String worldDisplayName = "Demo World"; + long sourceGameRowId = 29L; + String sourceGameTenantKey = "1"; + String provenanceKind = "NEW_GAME_ROW"; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, requestId, TENANT, tenantSlug, worldSlug, worldDisplayName); + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + requestId, + SOURCE_OPERATION_ID, + requestDigest, + TENANT, + tenantSlug, + worldSlug, + worldDisplayName, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind, + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + requestId, + SOURCE_OPERATION_ID, + requestDigest, + TENANT, + tenantSlug, + worldSlug, + worldDisplayName, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind)); + return RunOwnedInitialAdmissionLaunchEvidenceTestFixture.create(start, source); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionPublishedReadGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionPublishedReadGrpcServiceTest.java index 3e7673a4aa..b9c1987f4e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionPublishedReadGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionPublishedReadGrpcServiceTest.java @@ -27,8 +27,10 @@ import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector; import net.firedevops.firemud.common.publication.RealmEntryPolicy; import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; +import net.firedevops.firemud.common.world.CanonicalGameplayRunOwnedFixtureSourceEvidence; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleClient; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldRunOwnedFixtureLifecycleEvidence; import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionLaunchTarget; import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof; @@ -509,6 +511,82 @@ void strictReadRefusesPublicationChangeAfterTheHealthyWorldRead() { assertFailure(f.publishedObserver, Status.Code.FAILED_PRECONDITION); } + @ParameterizedTest + @ValueSource(strings = {"ACTIVE", "TERMINATING"}) + void strictReadServesRunOwnedFixtureFromRetainedSourceAndFixtureLifecycleOnlyWhenActive( + String lifecycleStatus) { + Fixture f = new Fixture(); + var request = GetPublishedRealmAdmissionOwnerReadRequest.getDefaultInstance(); + var parsed = mock(CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmRequest.class); + var selector = strictSelector(f.selector); + when(parsed.selector()).thenReturn(selector); + f.configureStrictRoute(selector); + String provenance = "sha256:" + "e".repeat(64); + var association = + f.launches + .readForInitialAdmission( + "test", TENANT, selector.realmUuid(), selector.canonicalGameInstanceUuid()) + .orElseThrow() + .association(); + var descriptor = f.binding.descriptor(); + when(association.isRunOwnedFixture()).thenReturn(true); + when(association.launchBindingEvidence()).thenReturn(null); + when(association.descriptor()).thenReturn(descriptor); + when(association.attestationDigest()).thenReturn(provenance); + when(association.fixtureProvenanceDigest()).thenReturn(provenance); + var fixtureSource = mock(CanonicalGameplayRunOwnedFixtureSourceEvidence.class); + when(fixtureSource.fixturePolicySealEvidenceDigest()).thenReturn(provenance); + when(f.published.readCurrentAdmissionSource(selector)) + .thenReturn( + new CanonicalPublishedPlayerRouteReadService.AdmissionSource(null, fixtureSource)); + when(f.world.readRunOwnedFixture(any(), any())) + .thenAnswer( + invocation -> + new WorldRunOwnedFixtureLifecycleEvidence( + invocation.getArgument(0), + provenance, + "sha256:" + "f".repeat(64), + lifecycleStatus, + 7, + 1)); + var response = + GetPublishedRealmAdmissionOwnerReadResponse.newBuilder().addSchemaVersion(1).build(); + var encodedWorld = ArgumentCaptor.forClass(WorldRunOwnedFixtureLifecycleEvidence.class); + try (var codec = mockStatic(CanonicalGameplayAdmissionDecisionReadGrpcCodec.class)) { + codec + .when( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest( + request)) + .thenReturn(parsed); + codec + .when( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toPublishedRealmFixtureResponse( + eq(parsed), eq(fixtureSource), any(), encodedWorld.capture())) + .thenReturn(response); + f.service.getPublishedRealmAdmissionOwnerRead(request, f.publishedObserver); + } + verify(f.world, never()).read(any()); + verify(f.published, never()) + .readCurrent(any(CanonicalGameplayRosterOwnerReadEvidence.Request.class)); + if (!"ACTIVE".equals(lifecycleStatus)) { + verify(f.published, times(1)).readCurrentAdmissionSource(selector); + assertFailure(f.publishedObserver, Status.Code.FAILED_PRECONDITION); + return; + } + verify(f.published, times(2)).readCurrentAdmissionSource(selector); + var worldRequest = encodedWorld.getValue().request(); + assertThat(worldRequest.readRequestId()).isEqualTo(selector.requestUuid()); + assertThat(worldRequest.canonicalVersionId()).isEqualTo(selector.canonicalVersionUuid()); + assertThat(worldRequest.expectedDescriptorRequestDigest()) + .isEqualTo("sha256:" + "a".repeat(64)); + assertThat(worldRequest.expectedDescriptorResultDigest()).isEqualTo("sha256:" + "b".repeat(64)); + assertThat(worldRequest.expectedReleaseAttestationDigest()).isEqualTo(provenance); + verify(f.publishedObserver).onNext(response); + verify(f.publishedObserver).onCompleted(); + } + @Test void closedInvalidRequestAndAbsentCompositionFailWithoutSourceReads() { Fixture f = new Fixture(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java index 937e42612b..5ebf476fce 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java @@ -1439,6 +1439,7 @@ private static TestHarness harness( when(association.capturedStartingRowVersion()).thenReturn(1L); when(association.currentRowVersion()).thenReturn(2L); when(association.launchBindingEvidence()).thenReturn(binding); + when(association.descriptor()).thenReturn(descriptor); when(association.currentGameInstanceStatus()) .thenReturn(CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus.RUNNING); CanonicalInitialAdmissionLaunchTarget launch = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPublishedPlayerRouteReadServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPublishedPlayerRouteReadServiceTest.java index eb1954d68b..5c2ecb256d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPublishedPlayerRouteReadServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPublishedPlayerRouteReadServiceTest.java @@ -327,6 +327,7 @@ private static Fixture fixture() { when(association.currentRowVersion()).thenReturn(2L); when(association.launchBindingEvidence()).thenReturn(completeBinding); when(completeBinding.descriptor()).thenReturn(descriptor); + when(association.descriptor()).thenReturn(descriptor); when(completeBinding.releaseAttestation()).thenReturn(release); when(descriptor.targetNamespace()).thenReturn(NAMESPACE); when(descriptor.canonicalTenantId()).thenReturn(TENANT); From 6384a7e8e36c90374aa2ec64efa90514d74c986b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:43:40 +1300 Subject: [PATCH 03/28] Keep the persisted catalog evidence form and inject the membership generation owner The fixture policy and its isRunOwnedFixture helper are read-side only: they are excluded from the persisted launch-preparation catalog JSON and from catalog equality, so stored launch and pointer snapshots keep matching the live row. The membership repository takes its authority-generation owner by constructor, so the first-JOIN scope enrolment is unit-testable. Co-Authored-By: Claude Opus 5.5 --- .../AccountTenantMembershipRepository.java | 17 ++++++- ...AccountTenantMembershipRepositoryTest.java | 13 ++++- .../dto/CanonicalRealmCatalogSnapshot.java | 50 ++++++++++++++++++- 3 files changed, 77 insertions(+), 3 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java index 711ed35f21..33d6f4d147 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java @@ -40,11 +40,26 @@ public AccountTenantMembershipRepository( AccountRepository accountRepository, FreshTenantIdentityAssociationRepository freshTenantIdentityAssociationRepository, AccountMembershipPairAuthorityRepository pairAuthorityRepository) { + this( + dsl, + accountRepository, + freshTenantIdentityAssociationRepository, + pairAuthorityRepository, + new AccountAuthorityGenerationRepository(dsl)); + } + + @org.springframework.beans.factory.annotation.Autowired + public AccountTenantMembershipRepository( + DSLContext dsl, + AccountRepository accountRepository, + FreshTenantIdentityAssociationRepository freshTenantIdentityAssociationRepository, + AccountMembershipPairAuthorityRepository pairAuthorityRepository, + AccountAuthorityGenerationRepository authorityGenerationRepository) { this.dsl = dsl; this.accountRepository = accountRepository; this.freshTenantIdentityAssociationRepository = freshTenantIdentityAssociationRepository; this.pairAuthorityRepository = pairAuthorityRepository; - this.authorityGenerationRepository = new AccountAuthorityGenerationRepository(dsl); + this.authorityGenerationRepository = authorityGenerationRepository; } public Optional findByAccountIdAndTenantId( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepositoryTest.java index aa265736f8..abbe256f46 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepositoryTest.java @@ -183,8 +183,18 @@ void firstFreshJoinPreparesMembershipWithoutAdvancingPairAuthority() { doReturn(73L).when(insertQuery).fetchOne(0, Long.class); TransactionSynchronizationManager.setActualTransactionActive(true); + AccountAuthorityGenerationRepository generations = + mock(AccountAuthorityGenerationRepository.class); + when(generations.initializeMembershipIfAbsent(ACCOUNT_UUID, TENANT_UUID)) + .thenReturn( + new AccountAuthorityGenerationRepository.ScopeState( + AccountAuthorityGenerationRepository.AuthorityScope.membership( + ACCOUNT_UUID, TENANT_UUID), + 1L, + 1L, + null)); AccountTenantMembershipRepository repository = - new AccountTenantMembershipRepository(dsl, accounts, tenants, pairs); + new AccountTenantMembershipRepository(dsl, accounts, tenants, pairs, generations); AccountTenantMembership result = repository.createFreshMembershipForJoin(ACCOUNT_UUID, TENANT_UUID); @@ -198,6 +208,7 @@ void firstFreshJoinPreparesMembershipWithoutAdvancingPairAuthority() { assertThat(result.getAuthorityProvenance()).isEqualTo("EXPLICIT_JOIN"); assertThat(result.isGameplayAdmissionAllowed()).isTrue(); verify(pairs).enrollAbsence(ACCOUNT_UUID, TENANT_UUID, freshProvenance()); + verify(generations).initializeMembershipIfAbsent(ACCOUNT_UUID, TENANT_UUID); verify(pairs, org.mockito.Mockito.never()).commitTransition(any(), any()); var order = inOrder(accounts, dsl, tenants, pairs); order.verify(accounts).findByAccountUuid(ACCOUNT_UUID); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalRealmCatalogSnapshot.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalRealmCatalogSnapshot.java index d87ded7c19..2133991916 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalRealmCatalogSnapshot.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalRealmCatalogSnapshot.java @@ -27,7 +27,9 @@ public record CanonicalRealmCatalogSnapshot( String requestDigest, String receiptDigest, IntakeReceipt sourceIntakeReceipt, - FixturePolicy fixturePolicy) { + // Read-side only: the persisted catalog evidence form, its equality and stored launch/pointer + // snapshots stay the shared catalog row identity; the fixture policy is re-read from the row. + @com.fasterxml.jackson.annotation.JsonIgnore FixturePolicy fixturePolicy) { private static final UUID NIL_UUID = new UUID(0L, 0L); /** @@ -120,6 +122,7 @@ public CanonicalRealmCatalogSnapshot( null); } + @com.fasterxml.jackson.annotation.JsonIgnore public boolean isRunOwnedFixture() { return fixturePolicy != null; } @@ -158,4 +161,49 @@ private static void requireNonNil(UUID value, String name) { throw new IllegalArgumentException(name + " must be a non-nil UUID"); } } + + /** Catalog identity excludes the read-side fixture policy, which persisted snapshots omit. */ + @Override + public boolean equals(Object other) { + return other instanceof CanonicalRealmCatalogSnapshot that + && java.util.Objects.equals(targetNamespace, that.targetNamespace) + && java.util.Objects.equals(tenantId, that.tenantId) + && java.util.Objects.equals(tenantSlug, that.tenantSlug) + && java.util.Objects.equals(worldSlug, that.worldSlug) + && java.util.Objects.equals(realmId, that.realmId) + && java.util.Objects.equals(realmSlug, that.realmSlug) + && java.util.Objects.equals(realmDisplayName, that.realmDisplayName) + && visible == that.visible + && publicProduction == that.publicProduction + && java.util.Objects.equals(stateScope, that.stateScope) + && java.util.Objects.equals(playableStateNamespaceId, that.playableStateNamespaceId) + && java.util.Objects.equals(characterCreationPolicy, that.characterCreationPolicy) + && catalogRevision == that.catalogRevision + && java.util.Objects.equals(creationRequestId, that.creationRequestId) + && java.util.Objects.equals(requestDigest, that.requestDigest) + && java.util.Objects.equals(receiptDigest, that.receiptDigest) + && java.util.Objects.equals(sourceIntakeReceipt, that.sourceIntakeReceipt); + } + + @Override + public int hashCode() { + return java.util.Objects.hash( + targetNamespace, + tenantId, + tenantSlug, + worldSlug, + realmId, + realmSlug, + realmDisplayName, + visible, + publicProduction, + stateScope, + playableStateNamespaceId, + characterCreationPolicy, + catalogRevision, + creationRequestId, + requestDigest, + receiptDigest, + sourceIntakeReceipt); + } } From a71be0ed3f85f03fe3f64ab902c8b818d7f505b6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 22 Nov 2026 03:05:45 +1300 Subject: [PATCH 04/28] Add pre-v1 PLAY stand-ins for the issuer layout, incarnations and budgets Co-Authored-By: Claude Opus 5.5 --- ...unOwnedFixtureDemoTenantConfiguration.java | 7 + ...wnedFixtureDemoTenantEnrollmentDriver.java | 24 +- .../PreV1CanonicalPlayConfiguration.java | 71 ++++++ .../PreV1CanonicalPlayBootstrapDriver.java | 67 +++++ ...alGameplayTenantGameplayTagRepository.java | 43 ++++ .../PreV1CanonicalGameplayStoreBootstrap.java | 230 ++++++++++++++++++ .../repository/PreV1CanonicalPlayBudgets.java | 70 ++++++ .../PreV1CanonicalPlayManualFactory.java | 80 ++++++ .../PreV1CanonicalPlayStandIns.java | 76 ++++++ .../PreV1CoordinationIncarnation.java | 106 ++++++++ .../PreV1CoordinationStorageObserver.java | 62 +++++ .../PreV1CurrentIssuerStateSource.java | 65 +++++ .../PreV1LocalIncarnationAttestor.java | 136 +++++++++++ .../PreV1RegionIncarnationSource.java | 46 ++++ ...GameplayStoreBootstrapIntegrationTest.java | 141 +++++++++++ .../PreV1CanonicalPlayConfigurationTest.java | 66 +++++ .../PreV1CanonicalPlayStandInsTest.java | 208 ++++++++++++++++ 17 files changed, 1496 insertions(+), 2 deletions(-) create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/PreV1CanonicalPlayConfiguration.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/PreV1CanonicalPlayBootstrapDriver.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalGameplayStoreBootstrap.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayBudgets.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayManualFactory.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayStandIns.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CoordinationIncarnation.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CoordinationStorageObserver.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CurrentIssuerStateSource.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1LocalIncarnationAttestor.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1RegionIncarnationSource.java create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PreV1CanonicalGameplayStoreBootstrapIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/PreV1CanonicalPlayConfigurationTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayStandInsTest.java diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/RunOwnedFixtureDemoTenantConfiguration.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/RunOwnedFixtureDemoTenantConfiguration.java index 8d9bdbed8d..45029dde00 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/RunOwnedFixtureDemoTenantConfiguration.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/RunOwnedFixtureDemoTenantConfiguration.java @@ -11,11 +11,14 @@ import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.prev1.PreV1GateWaivers; +import org.jooq.DSLContext; import org.springframework.beans.factory.annotation.Qualifier; 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; +import org.springframework.core.env.Environment; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionTemplate; @@ -45,6 +48,8 @@ RunOwnedFixtureDemoTenantEnrollmentDriver runOwnedFixtureDemoTenantEnrollmentDri FreshTenantIdentityAssociationRepository fresh, AccountAuthorityGenerationRepository generations, AccountDemoTenantEntitlementRepository demos, + DSLContext dsl, + Environment environment, @Qualifier("transactionManager") PlatformTransactionManager transactions, @Value("${FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH:}") String capabilityPath, @Value("${FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_PATH:}") String receiptPath, @@ -56,6 +61,8 @@ RunOwnedFixtureDemoTenantEnrollmentDriver runOwnedFixtureDemoTenantEnrollmentDri return new RunOwnedFixtureDemoTenantEnrollmentDriver( new FreshTenantIdentityEnrollmentService(gameDesign, fresh, generations, importTransaction), demos, + dsl, + PreV1GateWaivers.from(environment).enabled(), transactions, Path.of(capabilityPath), Path.of(receiptPath), diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/RunOwnedFixtureDemoTenantEnrollmentDriver.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/RunOwnedFixtureDemoTenantEnrollmentDriver.java index 3257ccc9cf..7a18127999 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/RunOwnedFixtureDemoTenantEnrollmentDriver.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/RunOwnedFixtureDemoTenantEnrollmentDriver.java @@ -13,6 +13,7 @@ import net.firedevops.firemud.accountservice.service.FreshTenantIdentityEnrollmentService; import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import org.jooq.DSLContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Scheduled; @@ -24,7 +25,8 @@ * Enrolls the run-owned Compose fixture's fresh Game Design tenant into Account and provisions its * non-paid demo entitlement, so public REALMS and JOIN can admit players to it. The fixture receipt * only locates the creation; Account imports the authenticated Game Design readback. Retries until - * Game Design has committed the fixture, and replays idempotently after a restart. + * Game Design has committed the fixture, and replays idempotently after a restart. Under the pre-v1 + * gate waivers it also provisions the tenant's capacity-origin refusal budget for canonical PLAY. */ public final class RunOwnedFixtureDemoTenantEnrollmentDriver { private static final Logger LOG = @@ -33,9 +35,12 @@ public final class RunOwnedFixtureDemoTenantEnrollmentDriver { private static final int MAX_FILE_BYTES = 16 * 1024; private static final DemoTenantEntitlementRequest.Quotas FIXTURE_QUOTAS = new DemoTenantEntitlementRequest.Quotas(3L, 2L, 4096L); + static final int PRE_V1_CAPACITY_ORIGIN_REFUSALS = 128; private final FreshTenantIdentityEnrollmentService enrollment; private final AccountDemoTenantEntitlementRepository demos; + private final DSLContext dsl; + private final boolean preV1RefusalBudget; private final TransactionTemplate transaction; private final Path capabilityPath; private final Path receiptPath; @@ -46,6 +51,8 @@ public final class RunOwnedFixtureDemoTenantEnrollmentDriver { public RunOwnedFixtureDemoTenantEnrollmentDriver( FreshTenantIdentityEnrollmentService enrollment, AccountDemoTenantEntitlementRepository demos, + DSLContext dsl, + boolean preV1RefusalBudget, PlatformTransactionManager transactions, Path capabilityPath, Path receiptPath, @@ -53,6 +60,8 @@ public RunOwnedFixtureDemoTenantEnrollmentDriver( String composeProjectName) { this.enrollment = Objects.requireNonNull(enrollment, "enrollment"); this.demos = Objects.requireNonNull(demos, "demos"); + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.preV1RefusalBudget = preV1RefusalBudget; this.capabilityPath = Objects.requireNonNull(capabilityPath, "capabilityPath"); this.receiptPath = Objects.requireNonNull(receiptPath, "receiptPath"); this.runId = requireText(runId, "runId"); @@ -111,7 +120,18 @@ FreshTenantCreationEvidence enroll() throws IOException { true, true, FIXTURE_QUOTAS); - transaction.executeWithoutResult(status -> demos.provision(request, creation)); + transaction.executeWithoutResult( + status -> { + demos.provision(request, creation); + if (preV1RefusalBudget) { + // Pre-v1 gate waiver (ADR 0185): operational capacity refusal budgets are owed. + dsl.execute( + "INSERT INTO account_capacity_origin_refusal_budget" + + " (tenant_uuid, maximum_refusals) VALUES (?, ?) ON CONFLICT DO NOTHING", + creation.canonicalTenantId(), + PRE_V1_CAPACITY_ORIGIN_REFUSALS); + } + }); return creation; } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/PreV1CanonicalPlayConfiguration.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/PreV1CanonicalPlayConfiguration.java new file mode 100644 index 0000000000..37fcb659fe --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/PreV1CanonicalPlayConfiguration.java @@ -0,0 +1,71 @@ +package net.firedevops.firemud.gamesession.config; + +import io.lettuce.core.ClientOptions; +import io.lettuce.core.RedisClient; +import net.firedevops.firemud.common.prev1.PreV1GateWaivers; +import net.firedevops.firemud.gamesession.data.PreV1CanonicalPlayBootstrapDriver; +import net.firedevops.firemud.gamesession.repository.PreV1CanonicalPlayManualFactory; +import net.firedevops.firemud.gamesession.repository.PreV1CanonicalPlayStandIns; +import org.jooq.DSLContext; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; + +/** + * Pre-v1 gate waiver (ADR 0185): composes the canonical PLAY stand-ins (store bootstrap, issuer + * state, INITIAL attestor, region incarnation, budgets) over the LOGIN Coordination Redis. Needs + * {@value #PROPERTY} and the gate waivers; the prod profile is refused. Nothing is wired into PLAY + * yet. + */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnExpression( + "${firemud.game-session.canonical-play.pre-v1.enabled:false}" + + " and ${firemud.pre-v1.gate-waivers.enabled:false}") +public class PreV1CanonicalPlayConfiguration { + static final String PROPERTY = "firemud.game-session.canonical-play.pre-v1.enabled"; + + @Bean(destroyMethod = "shutdown") + RedisClient preV1CanonicalPlayCoordinationRedis( + Environment environment, + @Value("${firemud.game-session.initial-gameplay-login.protected-sources.coordination.uri:}") + String configuredUri, + @Value( + "${firemud.game-session.initial-gameplay-login.protected-sources.coordination.command-timeout-millis:0}") + int commandTimeoutMillis) { + requireWaivers(environment); + RedisClient client = + RedisClient.create( + InitialGameplayLoginProtectedSourcesConfiguration.requiredCoordinationUri( + configuredUri, commandTimeoutMillis, true)); + client.setOptions(ClientOptions.builder().autoReconnect(false).build()); + return client; + } + + @Bean + PreV1CanonicalPlayStandIns preV1CanonicalPlayStandIns( + Environment environment, + DSLContext dsl, + @Qualifier("preV1CanonicalPlayCoordinationRedis") RedisClient coordination, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + return PreV1CanonicalPlayManualFactory.create( + requireWaivers(environment), dsl, coordination, workloadNamespace); + } + + @Bean + PreV1CanonicalPlayBootstrapDriver preV1CanonicalPlayBootstrapDriver( + PreV1CanonicalPlayStandIns standIns) { + return new PreV1CanonicalPlayBootstrapDriver(standIns); + } + + /** Re-reads the switch so the prod profile is refused even if the property was forced on. */ + static PreV1GateWaivers requireWaivers(Environment environment) { + PreV1GateWaivers waivers = PreV1GateWaivers.from(environment); + if (!waivers.enabled()) { + throw new IllegalStateException(PROPERTY + " requires the pre-v1 gate waivers"); + } + return waivers; + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/PreV1CanonicalPlayBootstrapDriver.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/PreV1CanonicalPlayBootstrapDriver.java new file mode 100644 index 0000000000..d4be99a38d --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/PreV1CanonicalPlayBootstrapDriver.java @@ -0,0 +1,67 @@ +package net.firedevops.firemud.gamesession.data; + +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.gamesession.repository.PreV1CanonicalGameplayStoreBootstrap; +import net.firedevops.firemud.gamesession.repository.PreV1CanonicalPlayStandIns; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.scheduling.annotation.Scheduled; + +/** + * Pre-v1 gate waiver (ADR 0185): runs the canonical gameplay store bootstrap once at startup, then + * provisions the fixture tenant's budgets once its realm exists. Each tick replays the owners' + * retained state; a failure is logged and retried. PLAY stays unavailable until {@link #ready()}. + */ +public final class PreV1CanonicalPlayBootstrapDriver { + private static final Logger LOG = + LoggerFactory.getLogger(PreV1CanonicalPlayBootstrapDriver.class); + private static final long RETRY_INTERVAL_MS = 10_000L; + + private final PreV1CanonicalPlayStandIns standIns; + private final AtomicReference store = + new AtomicReference<>(); + private final AtomicBoolean budgets = new AtomicBoolean(); + + public PreV1CanonicalPlayBootstrapDriver(PreV1CanonicalPlayStandIns standIns) { + this.standIns = Objects.requireNonNull(standIns, "standIns"); + } + + @Scheduled(initialDelay = 1_000L, fixedDelay = RETRY_INTERVAL_MS) + public void bootstrapWhenReady() { + if (store.get() == null) { + try { + var result = standIns.storeBootstrap().run(); + store.set(result); + LOG.info( + "Pre-v1 canonical gameplay store ready (legacy={}, issuer={}, bootstrap={})", + result.legacyMigrationState(), + result.issuerAdmissionControlState(), + result.issuerBootstrapOperationId()); + } catch (RuntimeException notYet) { + LOG.warn("Pre-v1 canonical gameplay store bootstrap not complete: {}", notYet.toString()); + return; + } + } + if (budgets.get()) return; + try { + var tenant = standIns.budgets().fixtureTenant(); + if (tenant.isEmpty()) return; + standIns.budgets().provision(tenant.get()); + budgets.set(true); + LOG.info("Pre-v1 canonical PLAY budgets provisioned for fixture tenant {}", tenant.get()); + } catch (RuntimeException notYet) { + LOG.warn("Pre-v1 canonical PLAY budgets not provisioned: {}", notYet.toString()); + } + } + + public Optional storeResult() { + return Optional.ofNullable(store.get()); + } + + public boolean ready() { + return store.get() != null && budgets.get(); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepository.java index 845fd108e6..382e3699fc 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepository.java @@ -319,6 +319,49 @@ Assignment assignmentForInitialBarrierTarget(UUID originalRequestId) { }); } + /** + * Loads or allocates the canonical mapping for one tenant this workload has durably claimed, + * ahead of its first transition, so tenant-keyed budget rows can reference it. It uses the same + * lock order, claim check and tag derivation as the transition paths and returns no Assignment. + */ + String tagForClaimedTenant(UUID tenantId) { + requireNonNil(tenantId, "tenantId"); + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + requireTenantClaim(transaction, tenantId); + transaction.execute( + "INSERT INTO " + + MAPPING + + " (tenant_id, allocation_version, tenant_gameplay_tag) VALUES (?, ?, ?)" + + " ON CONFLICT DO NOTHING", + tenantId, + allocationVersion, + tagFor(tenantId, allocationVersion)); + Record mapping = + transaction.fetchOne( + "SELECT allocation_version, tenant_gameplay_tag FROM " + + MAPPING + + " WHERE tenant_id = ? FOR UPDATE", + tenantId); + if (mapping == null) { + throw conflict("A gameplay tag candidate is already owned by a different tenant"); + } + Integer storedVersion = mapping.get("allocation_version", Integer.class); + String storedTag = mapping.get("tenant_gameplay_tag", String.class); + if (storedVersion == null || storedVersion <= 0) { + throw conflict("Persisted tenant gameplay tag allocation version is invalid"); + } + requireCanonicalTag(storedTag); + if (!tagFor(tenantId, storedVersion).equals(storedTag)) { + throw conflict( + "Persisted tenant tag differs from its immutable tenant/version assignment"); + } + return storedTag; + }); + } + /** * Narrow package-private collision path for native database proof. The tenant still comes from * the exact persisted transition; only the candidate output is controlled to exercise the global diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalGameplayStoreBootstrap.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalGameplayStoreBootstrap.java new file mode 100644 index 0000000000..e285896a61 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalGameplayStoreBootstrap.java @@ -0,0 +1,230 @@ +package net.firedevops.firemud.gamesession.repository; + +import io.lettuce.core.RedisClient; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.EnumSet; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventorySnapshot; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationReadback; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot.Family; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationStorageIdentity; +import org.jooq.DSLContext; + +/** + * Pre-v1 gate waiver (ADR 0185): one-time canonical gameplay store bootstrap at Game Session + * startup. It drives the actual legacy migration owner to VERIFIED over an empty cohort, then the + * actual issuer layout bootstrap, coverage and live-control owners to an installed anchor and OPEN. + * The empty legacy source, namespace index, storage identity, issuer checkpoint and incarnation are + * stand-ins owed before v1. Every request id is a UUIDv5 of the PostgreSQL system identity, so a + * restart replays the same retained operations; a changed Redis {@code run_id} fails closed. + */ +public final class PreV1CanonicalGameplayStoreBootstrap { + public static final BigInteger LAYOUT_VERSION = BigInteger.ONE; + public static final BigInteger PARTITION_COUNT = BigInteger.ONE; + public static final BigInteger PARTITION_CAPACITY = BigInteger.valueOf(128); + private static final UUID NAMESPACE = UUID.fromString("6f0b7c64-3b44-5d4c-9a56-8a1f2f7e1c01"); + private static final String WAIVED = "pre-v1-waiver-no-kubernetes"; + + private final DSLContext dsl; + private final RedisClient redis; + private final RedisScriptCatalog catalog; + private final PreV1CoordinationStorageObserver observer; + private final PreV1CurrentIssuerStateSource issuerSource; + + PreV1CanonicalGameplayStoreBootstrap( + DSLContext dsl, + RedisClient redis, + RedisScriptCatalog catalog, + PreV1CoordinationStorageObserver observer, + PreV1CurrentIssuerStateSource issuerSource) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.redis = Objects.requireNonNull(redis, "redis"); + this.catalog = Objects.requireNonNull(catalog, "catalog"); + this.observer = Objects.requireNonNull(observer, "observer"); + this.issuerSource = Objects.requireNonNull(issuerSource, "issuerSource"); + } + + /** Runs or replays the bootstrap; returns only after VERIFIED and the initial OPEN. */ + public Result run() { + var postgres = observer.postgresIdentity(); + String pgScope = postgres.systemIdentifier() + "|" + postgres.databaseOid(); + var storage = observedStorage(postgres, observer.redisRunId()); + var migration = establishLegacyDisposition(pgScope, storage); + + String exactDescriptor = + "issuer-layout-descriptor/v1|" + + PreV1CurrentIssuerStateSource.ISSUER + + "|" + + LAYOUT_VERSION + + "|" + + PARTITION_COUNT + + "|" + + PARTITION_CAPACITY + + "|" + + CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY; + var layout = + new CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedLayoutDescriptor( + PreV1CurrentIssuerStateSource.ISSUER, + LAYOUT_VERSION, + PARTITION_COUNT, + PARTITION_CAPACITY, + CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY, + exactDescriptor.getBytes(StandardCharsets.UTF_8)); + UUID bootstrapRequestId = uuidV5("issuer-layout-bootstrap|" + pgScope + "|" + exactDescriptor); + var intent = + new CanonicalGameplayIssuerLayoutBootstrapRepository(dsl) + .beginInitialBootstrapIntent( + bootstrapRequestId, layout, issuerSource.trustedCheckpoint()); + var partitionOwner = + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner(redis, catalog, issuerSource); + CanonicalGameplayIssuerInstalledAnchor anchor = + new CanonicalGameplayIssuerBootstrapCoverageOwner(dsl, partitionOwner, issuerSource) + .completeInitialBootstrap(intent.operationId(), bootstrapRequestId); + var control = + new CanonicalGameplayIssuerAdmissionControlRepository(dsl) + .installInitialOpen(anchor, issuerSource); + if (control.state() != CanonicalGameplayIssuerAdmissionControlValue.State.OPEN) { + throw new IllegalStateException("Issuer live admission control did not reach OPEN"); + } + return new Result( + migration.operationId(), + migration.state().name(), + anchor.bootstrapOperationId(), + bootstrapRequestId, + control.state().name(), + storage.redisRunId()); + } + + private CanonicalGameplayLegacyMigrationOperation establishLegacyDisposition( + String pgScope, CanonicalGameplayLegacyMigrationStorageIdentity storage) { + var inventory = new CanonicalGameplayBindingInventoryRepository(dsl); + var migration = new CanonicalGameplayLegacyMigrationRepository(dsl, inventory); + UUID cohortId = uuidV5("legacy-cohort|" + pgScope); + UUID writerFence = uuidV5("legacy-writer-fence|" + pgScope); + var cohort = + new CanonicalGameplayLegacyMigrationOwner.FencedCohort() { + @Override + public UUID cohortId() { + return cohortId; + } + + @Override + public UUID legacyWriterFence() { + return writerFence; + } + + @Override + public CanonicalGameplayLegacyMigrationStorageIdentity storageIdentity() { + return storage; + } + + @Override + public void requireStillFenced(CanonicalGameplayLegacyMigrationStorageIdentity expected) { + if (!storage.equals(expected) + || !storage.equals( + observedStorage(observer.postgresIdentity(), observer.redisRunId()))) { + throw new IllegalStateException("Pre-v1 storage identity changed"); + } + } + }; + var operation = + new CanonicalGameplayLegacyMigrationOwner( + migration, + inventory, + () -> cohort, + ignored -> + new CanonicalGameplayLegacyMigrationSourceSnapshot( + EnumSet.of( + Family.TENANT_SESSION_CONTEXT, + Family.SESSION_ALIAS_CONTEXT, + Family.GAMEPLAY_IDENTITY_CONTEXT, + Family.GAMEPLAY_NAME_CONTEXT, + Family.MOVEMENT_EFFECT, + Family.DURABLE_EFFECT), + List.of()), + new CanonicalGameplayLegacyMigrationOwner.NamespaceIndexOwner() { + @Override + public void rebuildExact( + CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, + CanonicalGameplayLegacyMigrationSourceSnapshot source, + CanonicalGameplayBindingInventorySnapshot canonical) { + requireEmptyCanonical(canonical); + } + + @Override + public CanonicalGameplayLegacyMigrationReadback readBackExact( + CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, + CanonicalGameplayBindingInventorySnapshot canonical) { + requireEmptyCanonical(canonical); + return new CanonicalGameplayLegacyMigrationReadback( + List.of(), List.of(), List.of(), List.of()); + } + }) + .migrate(); + if (operation.state() != CanonicalGameplayLegacyMigrationOperation.State.VERIFIED) { + throw new IllegalStateException("Legacy migration owner did not publish VERIFIED"); + } + return operation; + } + + private static CanonicalGameplayLegacyMigrationStorageIdentity observedStorage( + PreV1CoordinationStorageObserver.PostgresIdentity postgres, String redisRunId) { + return new CanonicalGameplayLegacyMigrationStorageIdentity( + WAIVED, + WAIVED, + "pre-v1-game-session", + "pre-v1-game-session-process", + "pre-v1-compose-host", + postgres.systemIdentifier(), + postgres.databaseOid(), + "pre-v1-postgres-" + postgres.systemIdentifier(), + redisRunId, + "pre-v1-redis-" + redisRunId); + } + + private static void requireEmptyCanonical(CanonicalGameplayBindingInventorySnapshot canonical) { + if (!canonical.bindings().isEmpty() + || !canonical.reservations().isEmpty() + || !canonical.transitions().isEmpty() + || !canonical.accountIndexObligations().isEmpty() + || !canonical.issuerIndexObligations().isEmpty() + || !canonical.regionBridgeObligations().isEmpty()) { + throw new IllegalStateException("Pre-v1 empty-cohort migration found canonical state"); + } + } + + static UUID uuidV5(String name) { + try { + MessageDigest sha1 = MessageDigest.getInstance("SHA-1"); + sha1.update( + ByteBuffer.allocate(16) + .putLong(NAMESPACE.getMostSignificantBits()) + .putLong(NAMESPACE.getLeastSignificantBits()) + .array()); + byte[] value = sha1.digest(name.getBytes(StandardCharsets.UTF_8)); + value[6] = (byte) ((value[6] & 0x0f) | 0x50); + value[8] = (byte) ((value[8] & 0x3f) | 0x80); + ByteBuffer bytes = ByteBuffer.wrap(value); + return new UUID(bytes.getLong(), bytes.getLong()); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("JVM does not provide SHA-1", impossible); + } + } + + /** Durable bootstrap outcome; states are the owners' own names (VERIFIED, OPEN). */ + public record Result( + UUID legacyMigrationOperationId, + String legacyMigrationState, + UUID issuerBootstrapOperationId, + UUID issuerBootstrapRequestId, + String issuerAdmissionControlState, + String redisRunId) {} +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayBudgets.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayBudgets.java new file mode 100644 index 0000000000..68c2b6187e --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayBudgets.java @@ -0,0 +1,70 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import org.jooq.DSLContext; + +/** + * Pre-v1 gate waiver (ADR 0185): provisions the per-tenant capacity-evidence and region + * transfer-history budgets for the run-owned fixture tenant. Operational budget provisioning is + * owed before v1. Rows are inserted once and never changed; a retry is a no-op. + */ +public final class PreV1CanonicalPlayBudgets { + public static final int CAPACITY_EVIDENCE_RECORDS = 128; + public static final long CAPACITY_EVIDENCE_BYTES_PER_RECORD = 1_048_576L; + public static final int REGION_TRANSFERS = 256; + public static final int REGION_TRANSFER_ITEMS = 1024; + + private final DSLContext dsl; + private final GameSessionCanonicalRealmCatalogRepository catalog; + private final CanonicalGameplayTenantGameplayTagRepository tags; + private final String workloadNamespace; + + PreV1CanonicalPlayBudgets( + DSLContext dsl, + GameSessionCanonicalRealmCatalogRepository catalog, + CanonicalGameplayTenantGameplayTagRepository tags, + String workloadNamespace) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.catalog = Objects.requireNonNull(catalog, "catalog"); + this.tags = Objects.requireNonNull(tags, "tags"); + this.workloadNamespace = Objects.requireNonNull(workloadNamespace, "workloadNamespace"); + } + + /** The unique run-owned fixture tenant in this workload's catalog, once its realm exists. */ + public Optional fixtureTenant() { + List tenants = + catalog.readVisiblePublicProductionSnapshots(workloadNamespace).stream() + .filter(snapshot -> snapshot.fixturePolicy() != null) + .map(CanonicalRealmCatalogSnapshot::tenantId) + .distinct() + .toList(); + if (tenants.size() > 1) { + throw new IllegalStateException("Run-owned fixture tenant is ambiguous"); + } + return tenants.stream().findFirst(); + } + + /** Allocates the tenant's gameplay tag if absent, then inserts both budget rows if absent. */ + public void provision(UUID tenantId) { + tags.tagForClaimedTenant(tenantId); + dsl.execute( + "INSERT INTO game_session_capacity_evidence_budget" + + " (tenant_id, maximum_records, maximum_binding_bytes, maximum_retained_records)" + + " VALUES (?, ?, ?, ?) ON CONFLICT DO NOTHING", + tenantId, + CAPACITY_EVIDENCE_RECORDS, + CAPACITY_EVIDENCE_RECORDS * CAPACITY_EVIDENCE_BYTES_PER_RECORD, + CAPACITY_EVIDENCE_RECORDS); + dsl.execute( + "INSERT INTO game_session_region_transfer_history_budget" + + " (tenant_id, maximum_transfers, maximum_items) VALUES (?, ?, ?)" + + " ON CONFLICT DO NOTHING", + tenantId, + REGION_TRANSFERS, + REGION_TRANSFER_ITEMS); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayManualFactory.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayManualFactory.java new file mode 100644 index 0000000000..52d1593f6d --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayManualFactory.java @@ -0,0 +1,80 @@ +package net.firedevops.firemud.gamesession.repository; + +import io.lettuce.core.RedisClient; +import java.util.List; +import java.util.Objects; +import net.firedevops.firemud.common.prev1.PreV1GateWaivers; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayAccountInitialBarrierRedisScriptContribution; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayAccountMemberRepairRedisScriptContribution; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayCapacityOriginCustodyRedisScriptContribution; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalRedisScriptContribution; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalRetirementRedisScriptContribution; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayOriginalNewCandidateClosureRedisScriptContribution; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayOriginalNewCandidateRedisScriptContribution; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayOriginalNewFinalAdmissionRedisScriptContribution; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayOriginalNewOriginFinalAdmissionRedisScriptContribution; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayRegionBindingBridgeRedisScriptContribution; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayRegionLeaseRedisScriptContribution; +import org.jooq.DSLContext; + +/** Public construction path for the pre-v1 canonical PLAY stand-ins (ADR 0185 waiver). */ +public final class PreV1CanonicalPlayManualFactory { + private PreV1CanonicalPlayManualFactory() {} + + /** Every canonical gameplay Coordination script the issuer and PLAY composition fixtures use. */ + public static RedisScriptCatalog mergedScriptCatalog() { + return RedisScriptCatalog.fromContributions( + List.of( + new CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution(), + new CanonicalGameplayIssuerBindingLocalRedisScriptContribution(), + new CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution(), + new CanonicalGameplayIssuerBindingLocalRetirementRedisScriptContribution(), + new CanonicalGameplayOriginalNewCandidateRedisScriptContribution(), + new CanonicalGameplayOriginalNewCandidateClosureRedisScriptContribution(), + new CanonicalGameplayAccountInitialBarrierRedisScriptContribution(), + new CanonicalGameplayAccountMemberRepairRedisScriptContribution(), + new CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution(), + new CanonicalGameplayOriginalNewFinalAdmissionRedisScriptContribution(), + new CanonicalGameplayRegionLeaseRedisScriptContribution(), + new CanonicalGameplayRegionBindingBridgeRedisScriptContribution(), + new CanonicalGameplayCapacityOriginCustodyRedisScriptContribution(), + new CanonicalGameplayOriginalNewOriginFinalAdmissionRedisScriptContribution())); + } + + /** + * Composes the stand-ins. Refuses unless the pre-v1 gate waivers are enabled; {@link + * PreV1GateWaivers#from} already refuses them under the prod profile. Nothing touches Redis or + * SQL until a stand-in is used. + */ + public static PreV1CanonicalPlayStandIns create( + PreV1GateWaivers waivers, + DSLContext dsl, + RedisClient coordination, + String workloadNamespace) { + if (waivers == null || !waivers.enabled()) { + throw new IllegalStateException("Pre-v1 canonical PLAY stand-ins require the gate waivers"); + } + Objects.requireNonNull(dsl, "dsl"); + Objects.requireNonNull(coordination, "coordination"); + var scripts = mergedScriptCatalog(); + var tags = + new CanonicalGameplayTenantGameplayTagRepository( + dsl, workloadNamespace, PreV1CanonicalPlayStandIns.TAG_ALLOCATION_VERSION); + var observer = new PreV1CoordinationStorageObserver(dsl, coordination); + var issuerState = new PreV1CurrentIssuerStateSource(observer::redisRunId); + return new PreV1CanonicalPlayStandIns( + coordination, + scripts, + tags, + issuerState, + new PreV1LocalIncarnationAttestor(observer::redisRunId), + new PreV1RegionIncarnationSource(observer::redisRunId), + new PreV1CanonicalGameplayStoreBootstrap(dsl, coordination, scripts, observer, issuerState), + new PreV1CanonicalPlayBudgets( + dsl, new GameSessionCanonicalRealmCatalogRepository(dsl), tags, workloadNamespace)); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayStandIns.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayStandIns.java new file mode 100644 index 0000000000..9a12c82147 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayStandIns.java @@ -0,0 +1,76 @@ +package net.firedevops.firemud.gamesession.repository; + +import io.lettuce.core.RedisClient; +import java.util.Objects; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; + +/** + * Pre-v1 gate waiver (ADR 0185) stand-ins for canonical PLAY, composed once per process over the + * Game Session Coordination Redis. Public callers get the startup bootstrap and budgets; the issuer + * state source, INITIAL attestor and region incarnation source stay package-private for the PLAY + * composition in this package. + */ +public final class PreV1CanonicalPlayStandIns { + /** Tenant gameplay tag allocation version shared by every canonical PLAY owner. */ + public static final int TAG_ALLOCATION_VERSION = 1; + + private final RedisClient coordination; + private final RedisScriptCatalog scripts; + private final CanonicalGameplayTenantGameplayTagRepository tags; + private final PreV1CurrentIssuerStateSource issuerState; + private final PreV1LocalIncarnationAttestor attestor; + private final PreV1RegionIncarnationSource regionIncarnation; + private final PreV1CanonicalGameplayStoreBootstrap storeBootstrap; + private final PreV1CanonicalPlayBudgets budgets; + + PreV1CanonicalPlayStandIns( + RedisClient coordination, + RedisScriptCatalog scripts, + CanonicalGameplayTenantGameplayTagRepository tags, + PreV1CurrentIssuerStateSource issuerState, + PreV1LocalIncarnationAttestor attestor, + PreV1RegionIncarnationSource regionIncarnation, + PreV1CanonicalGameplayStoreBootstrap storeBootstrap, + PreV1CanonicalPlayBudgets budgets) { + this.coordination = Objects.requireNonNull(coordination, "coordination"); + this.scripts = Objects.requireNonNull(scripts, "scripts"); + this.tags = Objects.requireNonNull(tags, "tags"); + this.issuerState = Objects.requireNonNull(issuerState, "issuerState"); + this.attestor = Objects.requireNonNull(attestor, "attestor"); + this.regionIncarnation = Objects.requireNonNull(regionIncarnation, "regionIncarnation"); + this.storeBootstrap = Objects.requireNonNull(storeBootstrap, "storeBootstrap"); + this.budgets = Objects.requireNonNull(budgets, "budgets"); + } + + public PreV1CanonicalGameplayStoreBootstrap storeBootstrap() { + return storeBootstrap; + } + + public PreV1CanonicalPlayBudgets budgets() { + return budgets; + } + + RedisClient coordination() { + return coordination; + } + + RedisScriptCatalog scripts() { + return scripts; + } + + CanonicalGameplayTenantGameplayTagRepository tags() { + return tags; + } + + PreV1CurrentIssuerStateSource issuerState() { + return issuerState; + } + + PreV1LocalIncarnationAttestor attestor() { + return attestor; + } + + PreV1RegionIncarnationSource regionIncarnation() { + return regionIncarnation; + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CoordinationIncarnation.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CoordinationIncarnation.java new file mode 100644 index 0000000000..2fae941778 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CoordinationIncarnation.java @@ -0,0 +1,106 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.regex.Pattern; + +/** + * Pre-v1 gate waiver (ADR 0185): the stable Coordination Redis incarnation, derived only from the + * live Redis {@code run_id}. It stands in for operational deployment/incarnation custody, which is + * owed before v1. A Redis restart changes the {@code run_id}, so every value here changes and the + * canonical owners that compare incarnations fail closed. + */ +final class PreV1CoordinationIncarnation { + static final String ATTESTOR_BINDING = "pre-v1-local-coordination-attestor"; + private static final Pattern REDIS_RUN_ID = Pattern.compile("[0-9a-f]{40}"); + + private final String redisRunId; + private final CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence + deployment; + private final String acceptedAttestationDigest; + private final String coordOpsRoAclDigest; + private final String coordRedisConfigObservedDigest; + + private PreV1CoordinationIncarnation(String redisRunId) { + this.redisRunId = redisRunId; + this.deployment = + new CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence( + "pre-v1-coordination-redis", + "run-" + redisRunId, + List.of("pre-v1-coordination-node"), + "pre-v1-coordination-redis-build", + "pre-v1-lua-registry-v1", + sha256("lua-registry", redisRunId), + "READY", + "boot-" + redisRunId, + "startup-" + redisRunId, + "storage-" + redisRunId, + "aof-" + redisRunId); + this.acceptedAttestationDigest = sha256("accepted-attestation", redisRunId); + this.coordOpsRoAclDigest = sha256("coord-ops-ro-acl", redisRunId); + this.coordRedisConfigObservedDigest = sha256("coord-redis-config", redisRunId); + } + + static PreV1CoordinationIncarnation forRedisRunId(String redisRunId) { + if (redisRunId == null || !REDIS_RUN_ID.matcher(redisRunId).matches()) { + throw new IllegalStateException("Coordination Redis run_id is unavailable or malformed"); + } + return new PreV1CoordinationIncarnation(redisRunId); + } + + String redisRunId() { + return redisRunId; + } + + CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence deployment() { + return deployment; + } + + /** {@code sha256:}-prefixed digests, as the issuer and protected receiver values require. */ + String acceptedAttestationDigest() { + return acceptedAttestationDigest; + } + + String coordOpsRoAclDigest() { + return coordOpsRoAclDigest; + } + + String coordRedisConfigObservedDigest() { + return coordRedisConfigObservedDigest; + } + + CanonicalGameplayIssuerMemberV2Value.Incarnation issuerIncarnation() { + return new CanonicalGameplayIssuerMemberV2Value.Incarnation( + ATTESTOR_BINDING, + acceptedAttestationDigest, + deployment, + coordOpsRoAclDigest, + coordRedisConfigObservedDigest); + } + + /** Bare 64-hex form of one of this incarnation's digests, as region evidence requires. */ + static String bareHex(String prefixedDigest) { + Objects.requireNonNull(prefixedDigest, "prefixedDigest"); + if (!prefixedDigest.startsWith("sha256:")) { + throw new IllegalArgumentException("Digest is not sha256-prefixed"); + } + return prefixedDigest.substring("sha256:".length()); + } + + static String sha256(String label, String seed) { + try { + byte[] digest = + MessageDigest.getInstance("SHA-256") + .digest( + ("firemud.gs.pre-v1-coordination/" + label + "/v1|" + seed) + .getBytes(StandardCharsets.UTF_8)); + return "sha256:" + HexFormat.of().formatHex(digest); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("JVM does not provide SHA-256", impossible); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CoordinationStorageObserver.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CoordinationStorageObserver.java new file mode 100644 index 0000000000..487a551e23 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CoordinationStorageObserver.java @@ -0,0 +1,62 @@ +package net.firedevops.firemud.gamesession.repository; + +import io.lettuce.core.RedisClient; +import io.lettuce.core.api.StatefulRedisConnection; +import java.util.Objects; +import org.jooq.DSLContext; +import org.jooq.Record; + +/** + * Pre-v1 gate waiver (ADR 0185): re-observes the live Coordination Redis {@code run_id} and the + * Game Session PostgreSQL system identity on every call. It stands in for the trusted migration + * factory's Kubernetes, Pod and volume evidence, which is owed before v1. + */ +final class PreV1CoordinationStorageObserver { + private final DSLContext dsl; + private final RedisClient redis; + + PreV1CoordinationStorageObserver(DSLContext dsl, RedisClient redis) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.redis = Objects.requireNonNull(redis, "redis"); + } + + String redisRunId() { + String info; + try (StatefulRedisConnection connection = redis.connect()) { + info = connection.sync().info("server"); + } catch (RuntimeException failure) { + throw new IllegalStateException("Coordination Redis run_id is unavailable", failure); + } + if (info != null) { + for (String line : info.split("\r?\n")) { + if (line.startsWith("run_id:")) { + // Validates the exact 40-hex shape before the value is used anywhere. + return PreV1CoordinationIncarnation.forRedisRunId(line.substring("run_id:".length())) + .redisRunId(); + } + } + } + throw new IllegalStateException("Coordination Redis run_id is unavailable"); + } + + PostgresIdentity postgresIdentity() { + Record system = + dsl.fetchOne("SELECT system_identifier::text AS id FROM pg_catalog.pg_control_system()"); + Record database = + dsl.fetchOne( + "SELECT oid::bigint AS oid FROM pg_catalog.pg_database" + + " WHERE datname = pg_catalog.current_database()"); + String systemIdentifier = system == null ? null : system.get("id", String.class); + Long databaseOid = database == null ? null : database.get("oid", Long.class); + if (systemIdentifier == null + || !systemIdentifier.matches("[1-9][0-9]{0,19}") + || databaseOid == null + || databaseOid <= 0L + || databaseOid > 0xffff_ffffL) { + throw new IllegalStateException("Game Session PostgreSQL identity is unavailable"); + } + return new PostgresIdentity(systemIdentifier, databaseOid); + } + + record PostgresIdentity(String systemIdentifier, long databaseOid) {} +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CurrentIssuerStateSource.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CurrentIssuerStateSource.java new file mode 100644 index 0000000000..7092b99c28 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CurrentIssuerStateSource.java @@ -0,0 +1,65 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.Objects; +import java.util.function.Supplier; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; + +/** + * Pre-v1 gate waiver (ADR 0185): the current Account issuer checkpoint and Coordination incarnation + * for the canonical gameplay owners. + * + *

Game Session has no read of Account's issuer authority source. The checkpoint is the + * sequence-zero initial generation 1, which carries no source event: Account initializes the issuer + * scope at generation 1 and has no reachable path that advances it ({@code + * AccountAuthoritySourceEvidenceRepository.appendIssuerAuthorityChange} has no caller). A later + * generation needs the sealed Account source event and is not invented here; owners then fail + * closed on the generation mismatch. The incarnation is re-derived from the live Redis {@code + * run_id} on every read. + */ +final class PreV1CurrentIssuerStateSource + implements CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource { + static final String ISSUER = GameSessionAccountDelegationProfile.ISSUER; + static final BigInteger INITIAL_GENERATION = BigInteger.ONE; + + private final Supplier redisRunId; + private final byte[] checkpointBytes = + ("pre-v1-initial-issuer-checkpoint/v1|" + ISSUER + "|" + INITIAL_GENERATION) + .getBytes(StandardCharsets.UTF_8); + + PreV1CurrentIssuerStateSource(Supplier redisRunId) { + this.redisRunId = Objects.requireNonNull(redisRunId, "redisRunId"); + } + + CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint + trustedCheckpoint() { + return new CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint( + ISSUER, INITIAL_GENERATION, checkpointBytes, null); + } + + CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint checkpoint() { + return new CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint( + ISSUER, INITIAL_GENERATION, checkpointBytes, sha256(checkpointBytes), null, null); + } + + @Override + public CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState + readFreshCurrentState() { + return new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + checkpoint(), + PreV1CoordinationIncarnation.forRedisRunId(redisRunId.get()).issuerIncarnation()); + } + + private static String sha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("JVM does not provide SHA-256", impossible); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1LocalIncarnationAttestor.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1LocalIncarnationAttestor.java new file mode 100644 index 0000000000..93b63cda05 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1LocalIncarnationAttestor.java @@ -0,0 +1,136 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.Signature; +import java.security.interfaces.RSAPublicKey; +import java.time.Clock; +import java.time.Duration; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.function.Supplier; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.json.JsonMapper; + +/** + * Pre-v1 gate waiver (ADR 0185): an in-process attestor for INITIAL account-barrier observations. + * It holds a per-process RSA key and signs the receiver's own current SQL context with the + * Coordination incarnation derived from the Redis {@code run_id}. It stands in for the protected + * operational attestor, owed before v1, and observes nothing outside this process. Other owner + * kinds are refused. + */ +final class PreV1LocalIncarnationAttestor + implements CanonicalGameplayProtectedIncarnationReceiver.ProtectedObservationChannel { + static final String KEY_ID = "pre-v1-local-attestor"; + private static final int MAX_SIGNED_BYTES = 16 * 1024; + private static final Duration OBSERVATION_TTL = Duration.ofSeconds(30); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final Supplier redisRunId; + private final KeyPair keys; + + PreV1LocalIncarnationAttestor(Supplier redisRunId) { + this.redisRunId = Objects.requireNonNull(redisRunId, "redisRunId"); + try { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + keys = generator.generateKeyPair(); + } catch (GeneralSecurityException unavailable) { + throw new IllegalStateException("Pre-v1 attestor key is unavailable", unavailable); + } + } + + /** Pins this process's key to the incarnation of the Redis {@code run_id} read now. */ + CanonicalGameplayProtectedIncarnationReceiver.TrustedConfiguration trustedConfiguration() { + var incarnation = PreV1CoordinationIncarnation.forRedisRunId(redisRunId.get()); + return new CanonicalGameplayProtectedIncarnationReceiver.TrustedConfiguration( + PreV1CoordinationIncarnation.ATTESTOR_BINDING, + incarnation.acceptedAttestationDigest(), + Map.of(KEY_ID, (RSAPublicKey) keys.getPublic()), + incarnation.deployment(), + incarnation.coordOpsRoAclDigest(), + incarnation.coordRedisConfigObservedDigest(), + MAX_SIGNED_BYTES, + 1, + OBSERVATION_TTL); + } + + /** The actual receiver, verifying this attestor's signatures for INITIAL observations. */ + CanonicalGameplayProtectedIncarnationReceiver initialBarrierReceiver( + CanonicalGameplayAccountInitialBarrierInitializerRepository repository, + CanonicalGameplayTenantGameplayTagRepository tags, + Clock clock) { + return new CanonicalGameplayProtectedIncarnationReceiver( + repository, tags, this, trustedConfiguration(), clock); + } + + @Override + public CanonicalGameplayProtectedIncarnationReceiver.SignedObservation observe( + CanonicalGameplayProtectedIncarnationReceiver.ObservationRequest request) { + var context = request.context(); + if (context.ownerKind() + != CanonicalGameplayProtectedIncarnationReceiver.OwnerKind.INITIAL_ACCOUNT_BARRIER) { + throw new IllegalArgumentException("Pre-v1 attestor is limited to INITIAL observations"); + } + Map owner = new LinkedHashMap<>(); + owner.put("ownerKind", context.ownerKind().name()); + owner.put("initializerId", context.operationId().toString()); + owner.put("originalRequestId", context.requestId().toString()); + owner.put("originalCallerContextId", context.originalCallerContextId().toString()); + owner.put("originalAttemptFence", context.originalAttemptFence()); + owner.put("accountId", context.accountId().toString()); + owner.put("sourceControlState", context.sourceControlState()); + owner.put("sourceControlEpoch", context.sourceControlEpoch()); + owner.put("inventorySnapshotRevision", context.inventorySnapshotRevision()); + owner.put("accountLoginEvidenceDigest", context.accountLoginEvidenceDigest()); + owner.put("sourceControlDigest", context.sourceControlDigest()); + owner.put("targetDigest", context.barrierTargetDigest()); + Map target = new LinkedHashMap<>(); + target.put("targetOrdinal", context.targetOrdinal()); + target.put("tenantId", context.tenantId().toString()); + target.put("playableStateNamespaceId", context.playableStateNamespaceId().toString()); + target.put("tenantGameplayTag", context.tenantGameplayTag()); + target.put("workloadNamespace", context.workloadNamespace()); + target.put("allocationVersion", context.allocationVersion()); + var evidence = request.expectedEvidence(); + Map deployment = new LinkedHashMap<>(); + deployment.put("deploymentIdentity", evidence.deploymentIdentity()); + deployment.put("deploymentGeneration", evidence.deploymentGeneration()); + deployment.put("canonicalNodeSet", evidence.canonicalNodeSet()); + deployment.put("redisBuildIdentity", evidence.redisBuildIdentity()); + deployment.put("luaScriptRegistryVersion", evidence.luaScriptRegistryVersion()); + deployment.put("luaScriptRegistryDigest", evidence.luaScriptRegistryDigest()); + deployment.put("startupState", evidence.startupState()); + deployment.put("bootGeneration", evidence.bootGeneration()); + deployment.put("startupGeneration", evidence.startupGeneration()); + deployment.put("storageGeneration", evidence.storageGeneration()); + deployment.put("aofGeneration", evidence.aofGeneration()); + Map root = new LinkedHashMap<>(); + root.put("schema", "firemud.gs.protected-initial-account-barrier-read/v1"); + root.put("attestorBinding", request.attestorBinding()); + root.put("attestorKeyId", KEY_ID); + root.put("acceptedAttestationDigest", request.acceptedAttestationDigest()); + root.put("observationNonce", request.nonce()); + root.put("observationIssuedAtEpochMillis", request.issuedAtEpochMillis()); + root.put("observationObservedAtEpochMillis", request.issuedAtEpochMillis()); + root.put("observationExpiresAtEpochMillis", request.expiresAtEpochMillis()); + root.put("owner", owner); + root.put("target", target); + root.put("targetDeploymentEvidence", deployment); + root.put("coordOpsRoAclDigest", request.coordOpsRoAclDigest()); + root.put("coordRedisConfigObservedDigest", request.coordRedisConfigObservedDigest()); + try { + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(root)); + Signature signer = Signature.getInstance("SHA256withRSA"); + signer.initSign(keys.getPrivate()); + signer.update(canonical); + return new CanonicalGameplayProtectedIncarnationReceiver.SignedObservation( + KEY_ID, canonical, signer.sign()); + } catch (GeneralSecurityException | IOException failure) { + throw new IllegalStateException("Pre-v1 INITIAL observation signing failed", failure); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1RegionIncarnationSource.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1RegionIncarnationSource.java new file mode 100644 index 0000000000..f5ca2c9cda --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1RegionIncarnationSource.java @@ -0,0 +1,46 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.util.Objects; +import java.util.function.Supplier; + +/** + * Pre-v1 gate waiver (ADR 0185): stable region incarnation evidence for the Coordination Redis, + * derived from the live Redis {@code run_id} on every read. The non-reset profile, inactive + * recovery and no-unfinished-work qualifications are asserted, not observed; their operational + * sources are owed before v1. + */ +final class PreV1RegionIncarnationSource implements CanonicalGameplayRegionIncarnationSource { + static final String NON_RESET_PROFILE_ID = "pre-v1-compose-non-reset-profile-v1"; + + private final Supplier redisRunId; + + PreV1RegionIncarnationSource(Supplier redisRunId) { + this.redisRunId = Objects.requireNonNull(redisRunId, "redisRunId"); + } + + @Override + public StableEvidence readCurrent(RegionScope scope) { + Objects.requireNonNull(scope, "scope"); + var incarnation = PreV1CoordinationIncarnation.forRedisRunId(redisRunId.get()); + String runId = incarnation.redisRunId(); + return StableEvidence.fromCurrentSource( + scope, + PreV1CoordinationIncarnation.ATTESTOR_BINDING, + PreV1CoordinationIncarnation.bareHex(incarnation.acceptedAttestationDigest()), + incarnation.deployment(), + PreV1CoordinationIncarnation.bareHex(incarnation.coordOpsRoAclDigest()), + PreV1CoordinationIncarnation.bareHex(incarnation.coordRedisConfigObservedDigest()), + true, + NON_RESET_PROFILE_ID, + waived("non-reset-profile", runId), + true, + waived("recovery-inactive", runId), + true, + waived("no-unfinished-prior-work", runId)); + } + + private static String waived(String label, String runId) { + return PreV1CoordinationIncarnation.bareHex( + PreV1CoordinationIncarnation.sha256("region-" + label, runId)); + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PreV1CanonicalGameplayStoreBootstrapIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PreV1CanonicalGameplayStoreBootstrapIntegrationTest.java new file mode 100644 index 0000000000..fa8c638c6e --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PreV1CanonicalGameplayStoreBootstrapIntegrationTest.java @@ -0,0 +1,141 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.lettuce.core.RedisClient; +import java.nio.file.Path; +import java.util.UUID; +import net.firedevops.firemud.common.prev1.PreV1GateWaivers; +import net.firedevops.firemud.test.TestContainerImages; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class PreV1CanonicalGameplayStoreBootstrapIntegrationTest { + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + private static final String PRINCIPAL = "gamesession_coord_app"; + private static final String PASSWORD = "pre-v1-game-session-coordination"; + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + // Same ACL shape as the pre-v1 Compose Coordination override. + @Container + static GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()) + .withExposedPorts(6379) + .withCommand( + "redis-server", "--user", PRINCIPAL, "on", ">" + PASSWORD, "~*", "&*", "+@all"); + + @Test + void bootstrapReachesVerifiedAndOpenAndReplaysIdenticallyAfterRestart() { + String schema = CanonicalGameplayIssuerTestFixtures.schemaName("gs_prev1_bootstrap_"); + DriverManagerDataSource dataSource = dataSource(schema); + CanonicalGameplayIssuerTestFixtures.migrateSchema(dataSource, schema, MIGRATION_LOCATION, null); + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + RedisClient first = coordinationClient(); + RedisClient second = coordinationClient(); + try { + var original = standIns(dsl, first).storeBootstrap().run(); + // A fresh process composes new stand-ins over the same retained SQL and Redis state. + var replay = standIns(dsl, second).storeBootstrap().run(); + + assertThat(original.legacyMigrationState()).isEqualTo("VERIFIED"); + assertThat(original.issuerAdmissionControlState()).isEqualTo("OPEN"); + assertThat(replay).isEqualTo(original); + assertThat( + dsl.fetchValue( + "SELECT disposition_state FROM game_session_canonical_binding_legacy_disposition" + + " WHERE singleton_id = 1")) + .isEqualTo("VERIFIED"); + assertThat(dsl.fetchCount(DSL.table("game_session_canonical_legacy_migration_operation"))) + .isEqualTo(1); + assertThat(dsl.fetchCount(DSL.table("game_session_canonical_issuer_layout_bootstrap_intent"))) + .isEqualTo(1); + assertThat( + dsl.fetchValue( + "SELECT state FROM game_session_canonical_issuer_admission_control" + + " WHERE issuer_id = ?", + PreV1CurrentIssuerStateSource.ISSUER)) + .isEqualTo("OPEN"); + assertThat(original.redisRunId()).matches("[0-9a-f]{40}"); + } finally { + first.shutdown(); + second.shutdown(); + dropSchema(schema); + } + } + + @Test + void budgetsAllocateTheTenantTagAndInsertOnce() { + String schema = CanonicalGameplayIssuerTestFixtures.schemaName("gs_prev1_budgets_"); + DriverManagerDataSource dataSource = dataSource(schema); + CanonicalGameplayIssuerTestFixtures.migrateSchema(dataSource, schema, MIGRATION_LOCATION, null); + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + RedisClient client = coordinationClient(); + try { + UUID tenantId = UUID.randomUUID(); + CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch(dataSource, tenantId, "test"); + var budgets = standIns(dsl, client).budgets(); + + assertThat(budgets.fixtureTenant()).as("a Human catalog row is not the fixture").isEmpty(); + budgets.provision(tenantId); + budgets.provision(tenantId); + + assertThat( + dsl.fetchValue( + "SELECT tenant_gameplay_tag FROM game_session_canonical_tenant_gameplay_tag" + + " WHERE tenant_id = ?", + tenantId)) + .isEqualTo("g1-" + tenantId.toString().replace("-", "")); + var capacity = + dsl.fetchSingle( + "SELECT maximum_records, maximum_binding_bytes, maximum_retained_records" + + " FROM game_session_capacity_evidence_budget WHERE tenant_id = ?", + tenantId); + assertThat(capacity.get(0, Integer.class)).isEqualTo(128); + assertThat(capacity.get(1, Long.class)).isEqualTo(128L * 1_048_576L); + assertThat(capacity.get(2, Integer.class)).isEqualTo(128); + var history = + dsl.fetchSingle( + "SELECT maximum_transfers, maximum_items" + + " FROM game_session_region_transfer_history_budget WHERE tenant_id = ?", + tenantId); + assertThat(history.get(0, Integer.class)).isEqualTo(256); + assertThat(history.get(1, Integer.class)).isEqualTo(1024); + } finally { + client.shutdown(); + dropSchema(schema); + } + } + + private static PreV1CanonicalPlayStandIns standIns(DSLContext dsl, RedisClient client) { + return PreV1CanonicalPlayManualFactory.create( + PreV1GateWaivers.enabledForTest(), dsl, client, "test"); + } + + private static RedisClient coordinationClient() { + return CanonicalGameplayIssuerTestFixtures.createRedisClient( + redis.getHost(), redis.getMappedPort(6379), PRINCIPAL, PASSWORD); + } + + private static DriverManagerDataSource dataSource(String schema) { + return CanonicalGameplayIssuerTestFixtures.dataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword(), schema); + } + + private static void dropSchema(String schema) { + CanonicalGameplayIssuerTestFixtures.dropSchema( + dataSource("public"), schema, "Could not drop the pre-v1 bootstrap test schema"); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/PreV1CanonicalPlayConfigurationTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/PreV1CanonicalPlayConfigurationTest.java new file mode 100644 index 0000000000..59f0b2c288 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/PreV1CanonicalPlayConfigurationTest.java @@ -0,0 +1,66 @@ +package net.firedevops.firemud.gamesession.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; + +import net.firedevops.firemud.gamesession.repository.PreV1CanonicalPlayStandIns; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.mock.env.MockEnvironment; + +class PreV1CanonicalPlayConfigurationTest { + private static final String COORDINATION = + "firemud.game-session.initial-gameplay-login.protected-sources.coordination."; + + private final ApplicationContextRunner runner = + new ApplicationContextRunner() + .withUserConfiguration(PreV1CanonicalPlayConfiguration.class) + .withBean(DSLContext.class, () -> mock(DSLContext.class)) + .withPropertyValues( + COORDINATION + "uri=redis://gamesession_coord_app:secret@redis-coord:6379/0", + COORDINATION + "command-timeout-millis=2000", + "firemud.grpc.workload-namespace=test"); + + @Test + void absentWithoutTheCanonicalPlaySwitchOrTheWaivers() { + runner.run(context -> assertThat(context).doesNotHaveBean(PreV1CanonicalPlayStandIns.class)); + runner + .withPropertyValues(PreV1CanonicalPlayConfiguration.PROPERTY + "=true") + .run(context -> assertThat(context).doesNotHaveBean(PreV1CanonicalPlayStandIns.class)); + runner + .withPropertyValues("firemud.pre-v1.gate-waivers.enabled=true") + .run(context -> assertThat(context).doesNotHaveBean(PreV1CanonicalPlayStandIns.class)); + } + + @Test + void composesUnderBothSwitchesWithoutConnecting() { + runner + .withPropertyValues( + PreV1CanonicalPlayConfiguration.PROPERTY + "=true", + "firemud.pre-v1.gate-waivers.enabled=true") + .run(context -> assertThat(context).hasSingleBean(PreV1CanonicalPlayStandIns.class)); + } + + @Test + void prodProfileFailsStartup() { + runner + .withPropertyValues( + PreV1CanonicalPlayConfiguration.PROPERTY + "=true", + "firemud.pre-v1.gate-waivers.enabled=true", + "spring.profiles.active=prod") + .run(context -> assertThat(context).hasFailed()); + } + + @Test + void requireWaiversRefusesOffAndProd() { + assertThatThrownBy(() -> PreV1CanonicalPlayConfiguration.requireWaivers(new MockEnvironment())) + .isInstanceOf(IllegalStateException.class); + var prod = new MockEnvironment().withProperty("firemud.pre-v1.gate-waivers.enabled", "true"); + prod.setActiveProfiles("prod"); + assertThatThrownBy(() -> PreV1CanonicalPlayConfiguration.requireWaivers(prod)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("prod"); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayStandInsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayStandInsTest.java new file mode 100644 index 0000000000..f137df31dd --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayStandInsTest.java @@ -0,0 +1,208 @@ +package 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.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.lettuce.core.RedisClient; +import java.math.BigInteger; +import java.time.Clock; +import java.util.UUID; +import net.firedevops.firemud.common.prev1.PreV1GateWaivers; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; + +class PreV1CanonicalPlayStandInsTest { + private static final String RUN_ID = "0123456789abcdef0123456789abcdef01234567"; + private static final String OTHER_RUN_ID = "fedcba9876543210fedcba9876543210fedcba98"; + private static final String DIGEST = "sha256:" + "a".repeat(64); + + @Test + void factoryRefusesWithoutTheGateWaivers() { + DSLContext dsl = mock(DSLContext.class); + RedisClient redis = mock(RedisClient.class); + + assertThatThrownBy(() -> PreV1CanonicalPlayManualFactory.create(null, dsl, redis, "test")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("gate waivers"); + assertThatThrownBy( + () -> + PreV1CanonicalPlayManualFactory.create( + PreV1GateWaivers.disabled(), dsl, redis, "test")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("gate waivers"); + verifyNoInteractions(dsl, redis); + } + + @Test + void factoryComposesWithoutTouchingRedisOrSql() { + DSLContext dsl = mock(DSLContext.class); + RedisClient redis = mock(RedisClient.class); + + var standIns = + PreV1CanonicalPlayManualFactory.create( + PreV1GateWaivers.enabledForTest(), dsl, redis, "test"); + + assertThat(standIns.storeBootstrap()).isNotNull(); + assertThat(standIns.budgets()).isNotNull(); + assertThat(standIns.coordination()).isSameAs(redis); + verifyNoInteractions(dsl, redis); + } + + @Test + void mergedCatalogCarriesTheIssuerAndPlayScripts() { + RedisScriptCatalog catalog = PreV1CanonicalPlayManualFactory.mergedScriptCatalog(); + + assertThat(catalog.descriptors()).hasSizeGreaterThanOrEqualTo(14); + } + + @Test + void issuerStateIsTheInitialGenerationWithARunIdIncarnation() { + var source = new PreV1CurrentIssuerStateSource(() -> RUN_ID); + + var state = source.readFreshCurrentState(); + var trusted = source.trustedCheckpoint(); + + assertThat(state.accountCheckpoint().issuerId()) + .isEqualTo(PreV1CurrentIssuerStateSource.ISSUER); + assertThat(state.accountCheckpoint().issuerAuthGeneration()).isEqualTo(BigInteger.ONE); + assertThat(state.accountCheckpoint().latestIssuerEventBytes()).isNull(); + assertThat(state.accountCheckpoint().exactCheckpointBytes()) + .isEqualTo(trusted.checkpointBytes()); + assertThat(trusted.latestEventBytes()).isNull(); + assertThat(state.incarnation()) + .isEqualTo(PreV1CoordinationIncarnation.forRedisRunId(RUN_ID).issuerIncarnation()); + assertThat(new PreV1CurrentIssuerStateSource(() -> OTHER_RUN_ID).readFreshCurrentState()) + .extracting(value -> value.incarnation()) + .isNotEqualTo(state.incarnation()); + } + + @Test + void malformedOrMissingRunIdIsRefused() { + assertThatThrownBy(() -> new PreV1CurrentIssuerStateSource(() -> "abc").readFreshCurrentState()) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> new PreV1CurrentIssuerStateSource(() -> null).readFreshCurrentState()) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + new PreV1LocalIncarnationAttestor(() -> RUN_ID.toUpperCase()) + .trustedConfiguration()) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void regionIncarnationIsStableEvidenceForTheExactScopeAndRunId() { + UUID tenantId = UUID.randomUUID(); + UUID gameInstanceId = UUID.randomUUID(); + UUID regionId = UUID.randomUUID(); + var scope = + new CanonicalGameplayRegionIncarnationSource.RegionScope( + tenantId, + gameInstanceId, + regionId, + CanonicalGameplayRegionRedisKeys.tenantRegionTag(tenantId, gameInstanceId, regionId)); + var source = new PreV1RegionIncarnationSource(() -> RUN_ID); + + var evidence = source.readCurrent(scope); + + assertThat(evidence.scope()).isEqualTo(scope); + assertThat(evidence.qualifiedNonResetProfile()).isTrue(); + assertThat(evidence.attestorBinding()).isEqualTo(PreV1CoordinationIncarnation.ATTESTOR_BINDING); + assertThat(evidence.targetDeploymentEvidence()) + .isEqualTo(PreV1CoordinationIncarnation.forRedisRunId(RUN_ID).deployment()); + assertThat(evidence.timelineInitializationQualification().qualifiedNonResetProfileId()) + .isEqualTo(PreV1RegionIncarnationSource.NON_RESET_PROFILE_ID); + assertThat(source.readCurrent(scope).digest()).isEqualTo(evidence.digest()); + assertThat(new PreV1RegionIncarnationSource(() -> OTHER_RUN_ID).readCurrent(scope).digest()) + .isNotEqualTo(evidence.digest()); + } + + @Test + void localAttestorRoundTripsThroughTheActualReceiver() { + var fixture = new InitialContext(); + var attestor = new PreV1LocalIncarnationAttestor(() -> RUN_ID); + var receiver = + attestor.initialBarrierReceiver(fixture.repository, fixture.tags, Clock.systemUTC()); + + var verified = receiver.observeForInitialAccountBarrier(fixture.requestId); + + assertThat(verified.ownerKind()) + .isEqualTo(CanonicalGameplayProtectedIncarnationReceiver.OwnerKind.INITIAL_ACCOUNT_BARRIER); + assertThat(verified.operationId()).isEqualTo(fixture.initializerId); + assertThat(verified.requestId()).isEqualTo(fixture.requestId); + assertThat(verified.acceptedAttestationDigest()) + .isEqualTo(PreV1CoordinationIncarnation.forRedisRunId(RUN_ID).acceptedAttestationDigest()); + var restartedProcess = new PreV1LocalIncarnationAttestor(() -> RUN_ID); + assertThat( + restartedProcess + .initialBarrierReceiver(fixture.repository, fixture.tags, Clock.systemUTC()) + .observeForInitialAccountBarrier(fixture.requestId) + .incarnationDigest()) + .as("the per-process key is not part of the incarnation") + .isEqualTo(verified.incarnationDigest()); + } + + @Test + void receiverRejectsAnotherProcessesAttestorKey() { + var fixture = new InitialContext(); + var trusted = new PreV1LocalIncarnationAttestor(() -> RUN_ID); + var other = new PreV1LocalIncarnationAttestor(() -> RUN_ID); + var receiver = + new CanonicalGameplayProtectedIncarnationReceiver( + fixture.repository, + fixture.tags, + other, + trusted.trustedConfiguration(), + Clock.systemUTC()); + + assertThatThrownBy(() -> receiver.observeForInitialAccountBarrier(fixture.requestId)) + .isInstanceOf(RuntimeException.class); + } + + private static final class InitialContext { + final UUID requestId = UUID.randomUUID(); + final UUID initializerId = UUID.randomUUID(); + final CanonicalGameplayAccountInitialBarrierInitializerRepository repository = + mock(CanonicalGameplayAccountInitialBarrierInitializerRepository.class); + final CanonicalGameplayTenantGameplayTagRepository tags = + mock(CanonicalGameplayTenantGameplayTagRepository.class); + + InitialContext() { + UUID callerContextId = UUID.randomUUID(); + UUID accountId = UUID.randomUUID(); + UUID tenantId = UUID.randomUUID(); + UUID namespaceId = UUID.randomUUID(); + when(repository.readCurrentObservationContext(requestId)) + .thenReturn( + new CanonicalGameplayAccountInitialBarrierInitializerRepository + .InitialObservationContext( + initializerId, + requestId, + callerContextId, + 17L, + accountId, + tenantId, + namespaceId, + "NO_ACTIVE_ACCOUNT_WIDE_FLOW", + BigInteger.valueOf(8), + BigInteger.valueOf(4), + DIGEST, + DIGEST, + DIGEST)); + var assignment = mock(CanonicalGameplayTenantGameplayTagRepository.Assignment.class); + when(tags.assignmentForInitialBarrierTarget(requestId)).thenReturn(assignment); + when(assignment.isInitialBarrierTarget()).thenReturn(true); + when(assignment.initialBarrierInitializerId()).thenReturn(initializerId); + when(assignment.initialBarrierOriginalRequestId()).thenReturn(requestId); + when(assignment.accountId()).thenReturn(accountId); + when(assignment.tenantId()).thenReturn(tenantId); + when(assignment.playableStateNamespaceId()).thenReturn(namespaceId); + when(assignment.tenantGameplayTag()).thenReturn("g1-" + tenantId.toString().replace("-", "")); + when(assignment.workloadNamespace()).thenReturn("test"); + when(assignment.allocationVersion()).thenReturn(1); + } + } +} From d5d366cf5ff4840cb6172390bf201a808fa0b6b9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 22 Nov 2026 23:30:05 +1300 Subject: [PATCH 05/28] Compose run-owned Telnet PLAY through canonical admission --- .github/workflows/smoke.yml | 2 +- .../game-session-service/protocols.md | 2 +- .../world-management-service/api-contracts.md | 1 + .../player-access-and-session.md | 6 +- dev-tools/smoke/pre-v1-signer-fixtures.py | 2 + dev-tools/smoke/smoke_common.py | 14 +- dev-tools/tests/smoke-transport-contract.sh | 15 +- .../docker-compose.pre-v1-login.override.yml | 1 + ...ld_canonical_instance_lifecycle_read.proto | 12 + ...meplayAdmissionReceiversConfiguration.java | 4 +- ...ccountPlayerAdmissionEntitlementOwner.java | 46 ++- ...PlayerAdmissionEntitlementGrpcService.java | 8 +- ...stJoinAuthorityStorageIntegrationTest.java | 31 +- ...titlementOwnerPostgresIntegrationTest.java | 61 ++- ...imePlayerAdmissionEntitlementEvidence.java | 40 +- ...WorldCanonicalInstanceLifecycleClient.java | 41 +++ ...layerAdmissionEntitlementEvidenceTest.java | 47 +++ ...ayerAdmissionEntitlementGrpcCodecTest.java | 16 + ...GameplayBindingRegionBridgeObligation.java | 11 +- ...anonicalGameplayRuntimeActorReference.java | 8 +- .../PreV1RunOwnedFixtureActorReference.java | 167 +++++++++ ...V1CanonicalPlayAdmissionConfiguration.java | 98 +++++ ...eV1CanonicalPlayReadbackConfiguration.java | 120 ++++++ .../dto/CanonicalPlayableTarget.java | 39 ++ .../CanonicalGameplayRegionRuntimeStatus.java | 17 +- ...calGameplayBindingInventoryRepository.java | 17 +- ...iginalNewFinalAdmissionReadRepository.java | 17 +- ...nicalGameplayRegionBindingBridgeOwner.java | 39 +- ...meplayRegionBindingBridgeOwnerFactory.java | 28 ++ ...icalGameplayRegionBindingBridgeProofs.java | 29 +- .../CanonicalGameplayRegionLeaseOwner.java | 50 ++- ...onicalGameplayRegionLeaseOwnerFactory.java | 26 +- ...anonicalGameplayRegionLeaseRedisOwner.java | 4 +- ...GameplayRegionOwnerTransferRepository.java | 4 +- ...GameplayRegionRuntimeStatusRepository.java | 76 ++-- .../PreV1CanonicalPlayAdmissionOwner.java | 317 ++++++++++++++++ .../PreV1CanonicalPlayManualFactory.java | 4 +- .../PreV1CanonicalPlayStandIns.java | 27 +- .../PreV1RunOwnedFixtureActorSource.java | 126 +++++++ .../PreV1RunOwnedFixturePlacementSource.java | 144 ++++++++ .../PreV1RunOwnedFixturePlayRegion.java | 347 ++++++++++++++++++ ...alInitialPlayerLocationRegionResolver.java | 23 ++ ...icalRegionBootstrapAssignmentResolver.java | 49 ++- .../DirectTextAuthenticatedLobbyOwner.java | 24 ++ ...eplayAdmissionDecisionReadGrpcService.java | 38 +- ...uthenticatedDirectTextCommandReceiver.java | 64 +++- .../AuthenticatedDirectTextSessions.java | 13 +- .../src/main/resources/application.yml | 4 + ...owned_fixture_region_world_source_kind.sql | 217 +++++++++++ ...eFamilyCatalogPostgresIntegrationTest.java | 16 +- .../PreV1RunOwnedFixtureStandInsTest.java | 230 ++++++++++++ ...nticatedDirectTextCommandReceiverTest.java | 12 +- .../AuthenticatedDirectTextSessionsTest.java | 7 +- .../telnet-login-look-smoke.sh | 9 +- .../RunOwnedWorldFixedPresetResources.java | 7 + ...nicalInstanceLifecycleReadGrpcService.java | 54 +++ ...onicalInstanceLifecycleReadRepository.java | 95 ++++- .../src/main/resources/application.yml | 1 + ...resetResourcesPostgresIntegrationTest.java | 15 + ...lInstanceLifecycleReadGrpcServiceTest.java | 85 ++++- 60 files changed, 2816 insertions(+), 211 deletions(-) create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/PreV1RunOwnedFixtureActorReference.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/PreV1CanonicalPlayAdmissionConfiguration.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/PreV1CanonicalPlayReadbackConfiguration.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayAdmissionOwner.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1RunOwnedFixtureActorSource.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1RunOwnedFixturePlacementSource.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1RunOwnedFixturePlayRegion.java create mode 100644 services/game-session-service/src/main/resources/db/migration/V1072__run_owned_fixture_region_world_source_kind.sql create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/PreV1RunOwnedFixtureStandInsTest.java diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index 1950af6289..af2ca1abdb 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -616,7 +616,7 @@ jobs: // Include held-admission proof, authenticated cleanup, and their executed inputs. const canonicalPlayClassifierSha256 = { "dev-tools/verify-smoke-images.sh": "f4cd887dec6c291ac8b31127561dcb510b322bc695034dc58caab50de8d67e19", - "dev-tools/smoke/smoke_common.py": "283804b941306cac3ae9ddf252e90ed7e96e18168d8a635a3ac191c669d3aff1", + "dev-tools/smoke/smoke_common.py": "de558579182f39bf7fd21c65d8df1d3da7b1df13a4bdfe02fa7e18d643a2b017", "services/game-session-service/websocket-login-look-smoke.sh": "c1e04a7b3e0841e0422cd800e7b04430539619f0f8141f9948e30b9d0c6443e1", "dev-tools/smoke/demo-smoke-defaults.sh": "8c9aae1abf005b47af3f313e0d635a666c74776733bcf5278a2e11ac9c8a18fb", "dev-tools/smoke/held-admission-qualification.sh": "b548a773f1786b72d40a3728052a336cb249257a3f40735f005b060812184ed3", diff --git a/design/architecture/microservices/game-session-service/protocols.md b/design/architecture/microservices/game-session-service/protocols.md index bf23f0b46f..aa5635cf6b 100644 --- a/design/architecture/microservices/game-session-service/protocols.md +++ b/design/architecture/microservices/game-session-service/protocols.md @@ -66,7 +66,7 @@ For direct text/Telnet, `HELP` is non-discovery, `WORLDS` is the sole anonymous | `WORLDS` | Lists worlds visible to the caller. Before `LOGIN`, this is a public browse/discovery command intended to let players explore the platform before signing up or logging in. After `LOGIN`, it may also include caller-specific membership or entitlement context. | `WORLDS` | | `HELP` | Returns static command/help content. It is non-discovery: it does not list worlds, realms, characters, membership, or admission state, and it does not replace `WORLDS`. | `HELP` | | `REALMS ` | Requires successful `LOGIN` and lists visible realms for a world, where `` is the stable `tenantSlug/worldSlug` selector or menu index returned by `WORLDS`. A bare `tenantSlug` is accepted only when that tenant exposes exactly one visible authored world; a bare `worldSlug` is never resolved globally. The default public production realm may be visible before membership exists; additional realms require explicit grants. | `REALMS demo/demo` | -| `JOIN ` | **Target-only; not currently implemented.** Explicitly joins the selected world's public production realm through the Account-owned idempotent membership writer. The resulting membership is durable and powers later return discovery. `` follows the same tenant-scoped selector rules as `REALMS`. | `JOIN demo/demo` | +| `JOIN ` | Explicitly joins the selected world's public production realm through the Account-owned idempotent membership writer. The resulting membership is durable and powers later return discovery. `` follows the same tenant-scoped selector rules as `REALMS`. | `JOIN demo/demo` | | `CHARS [realm]` | Requires successful `LOGIN` and presents Entity's persisted roster/policy result for the resolved realm. It is discovery evidence, not admission authority; `PLAY` revalidates the selected actor and current runtime fence. | `CHARS demo/demo production` | | `PLAY [realm] [character]` | Binds the authenticated connection to a world, optional realm, and optional character after the discovery, `LOGIN`, and conditional membership/character gates, enforcing tenant authorization, realm routing, and entitlements. Players may omit `[realm]` or `[character]` only when the fresh target resolution is unambiguous; direct text never reuses the first-party WebSocket discovery snapshot. A public-production player with missing or `INACTIVE` membership must complete `JOIN ` first when fresh joining policy permits; a closed policy denies that required join/repair without changing membership. Existing `ACTIVE` membership skips `JOIN` and is not denied `PLAY` solely because `allowPublicJoin=false`. A grant-backed non-public path may proceed only when its required durable `membershipLifecycleState=ACTIVE` membership already exists. `PLAY` returns `JOIN_REQUIRED` only for the eligible missing/`INACTIVE` public-production predicate and never creates or substitutes membership implicitly. | `PLAY demo/demo production Sora` | | `LOOK` | Requests the current room snapshot aggregated from Game Logic plus World and Entity services. | `LOOK` | diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 602fba97af..256ef50af5 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -34,6 +34,7 @@ Canonical source intake and Version association revalidate the fixed Game Sessio - `GetRoom` – retrieves room data including exits and environmental effects through `RoomInstanceRef`. - `GetRoomSnapshot` – returns a minimal, LOOK-focused view scoped by `RoomInstanceRef`. +- `WorldCanonicalInstanceLifecycleReadService.ReadRunOwnedFixtureStartRoom` reads the World-allocated starter room for the exact ACTIVE run-owned fixture. The same-namespace Game Session workload presents the complete lifecycle selector over mTLS. World validates the retained fixture association and reads the room mapping and lifecycle in one owner snapshot. The reply carries the fixture lifecycle evidence and World room key. Actor placement and player admission remain separate owner operations. - `ListRoomOccupants` – **target state:** returns the authoritative typed occupant list for actors in a room, scoped by `RoomInstanceRef`. The current LOOK path is fixture-backed and has no World-owned location/occupancy persistence or authoritative read/write surface; it must not be treated as gameplay occupancy truth. - `ApplyRoomAmbientStatePatch` – applies a typed ambient fact patch to the target runtime scope under expected epoch/version preconditions and an operation/aggregate/request-digest-bound guard derived from the root `EffectId`; matching replay returns the durable prior result and a conflicting identity or payload fails closed. - `GetDraftDesignDigest` – returns the publish-gating digest for Draft world templates using the typed scope request `GetDraftDesignDigestRequest { tenantId, scope: oneof { versionId, scriptPatchVersion } }`. World Management supports `versionId` scope only and must return `UNSUPPORTED_SCOPE` for `scriptPatchVersion`. 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 ae946df241..50ee5276f4 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -28,15 +28,15 @@ Under ADR 0185 (no data carry-over before v1, proposed in #3459), Compose smoke | World runtime installation for the run-owned Compose fixture is read from a root-owned inventory file (`PreV1ComposeRuntimeInstallationSource`) | A deployed installation controller that holds the completed installation and its workload incarnations through each launch commit | | Account signer promotion uses self-attested validator readiness (`PreV1SelfAttestedReadinessDriver`) | A Pod-bound readiness receiver client and orchestrator that verifies each validator Pod's acceptance | | The run-owned Compose fixture tenant is enrolled into Account from the Game Design receipt as a locator plus the authenticated `ResolveFreshTenantCreation` readback, with a provisioned demo entitlement (`RunOwnedFixtureDemoTenantEnrollmentDriver`) | The Account tenant-creation coordinator and an operator-provisioned entitlement for real tenants | -| Direct-text PLAY runs on the existing direct LOGIN until the authenticated LOGIN, WORLDS, REALMS and JOIN receiver lands (stacked straight after UUID PLAY is green) | Deployed Account JWT signer materializer and public-JWKS API binding, protected Coordination Redis (TLS, ACL, AOF acknowledgement) and the external Coordination qualification authority, then PLAY moved onto the authenticated receiver | +| The authenticated direct-text PLAY composition uses the run-owned fixture's scoped issuer, Coordination, actor, placement and capacity-budget stand-ins | Deployed Account JWT signer and public-JWKS binding, protected Coordination Redis and qualification authority, production Entity actor and World placement owners, and owner-provisioned quota budgets | ### Direct-text scope and JOIN identifier cutover The canonical Account boundary requires non-nil UUID tenant and game-instance identifiers. The held Game Session scope target now takes those UUIDs from `CanonicalPlayableTarget`, and its Account client validates the same canonical shape. JOIN correlation retains exact tenant equality. The numeric transport session identifier remains an independent, bounded positive-long coordinate: its original bytes, including leading zeros, are preserved through scope issuance and JOIN rather than replaced by the proxy connection UUID. -Selected client-wire and Account receiver tests exercise these contracts separately, including malformed identifiers and mismatches. They are not an actual paired Game Session-to-Account RPC or deployed composition proof. The lobby, Account's canonical realm-scope owner and JOIN consumers (`AccountCanonicalRealmAdmissionConfiguration`) and Game Session's Account-only admission decision read (`CanonicalGameplayAdmissionDecisionReadConfiguration`) are now registered, and Account's PLAY receivers (entitlement read, admission lease, tenant capacity) are registered by `AccountGameplayAdmissionReceiversConfiguration`. Paid hosting sources are not composed there, so paid tenants fail closed. Runtime REALMS/JOIN proof and public admission remain unfinished (#3474). The observed backend PLAY `ENTITLEMENT_UNAVAILABLE` is a separate recorded failure. The temporary CI exception supplies neither successful JOIN/PLAY proof nor runtime activation. +Selected client-wire and Account receiver tests exercise malformed identifiers and mismatches. The registered receiving chain connects the authenticated Game Session lobby to Account's canonical realm-scope and JOIN owners, with the Account-only admission decision read supplying the selected target. Fresh run-owned Compose smoke for #3481 returned `OK LOGIN`, `OK WORLDS`, `OK REALMS`, and `OK JOIN` on one Telnet connection after the fixture's first `OPEN`. The same run reached the registered Account player-admission entitlement RPC during PLAY and returned `ADMISSION_UNAVAILABLE`. The live entitlement registration now uses its method-specific mTLS guard. Positive PLAY, LOOK, and WebSocket admission proof remain outstanding. Account's registered PLAY receivers serve the demo source. Paid hosting remains held pending its owning composition. -This is an intentionally breaking preproduction format cutover of the manually composed, currently unregistered lobby. No production rollback or migration compatibility is claimed. Numeric-era retained scope/JOIN bytes are not supported by the canonical UUID decoder; the existing SQL retention and exact-original identity guards remain unchanged. Repository inspection establishes no runtime registration and supplies no inventory of deployed rows. Existing-data verification belongs to future runtime wiring or activation, not a new merge gate or slicing requirement for this PR: before reusing any database populated by an earlier manual composition, establish whether numeric-era companion evidence exists. If it does, preserve that evidence and resolve its retention and recovery requirements before invoking the new owner against it; neither this cutover nor the temporary CI exception authorizes deletion, identity rewriting or retention bypass. Fresh component fixtures do not prove historical compatibility. +The preproduction format cutover requires canonical UUID scope and JOIN bytes. Existing SQL retention and exact-original identity guards continue to apply. Before activating an existing database populated by an earlier manual composition, establish whether numeric-era companion evidence exists. Preserve that evidence and resolve its retention and recovery requirements before invoking the canonical owner against it. Fresh Compose proof covers a newly initialized database. ### Canonical receiving capability boundaries diff --git a/dev-tools/smoke/pre-v1-signer-fixtures.py b/dev-tools/smoke/pre-v1-signer-fixtures.py index 8728a17789..a61740c5f6 100644 --- a/dev-tools/smoke/pre-v1-signer-fixtures.py +++ b/dev-tools/smoke/pre-v1-signer-fixtures.py @@ -341,6 +341,8 @@ def main(): inventory_path.unlink() inventory_path.write_text(json.dumps(world_inventory, separators=(",", ":"))) os.chmod(inventory_path, 0o444) + # The non-root World container must traverse this read-only bind mount under any host umask. + os.chmod(world, 0o755) (out / "identity.json").write_text(json.dumps(identity, indent=2) + "\n") os.chmod(out, 0o755) diff --git a/dev-tools/smoke/smoke_common.py b/dev-tools/smoke/smoke_common.py index 377264207b..4cf9623e0a 100644 --- a/dev-tools/smoke/smoke_common.py +++ b/dev-tools/smoke/smoke_common.py @@ -387,16 +387,14 @@ def login_play_look_steps( ] -def authenticated_telnet_login_steps(username, password, world, login_expect): - """Telnet steps the authenticated Gateway path supports before canonical admission. - - Telnet WORLDS/REALMS/JOIN/PLAY/LOOK is deferred until the canonical admission chain - (realm catalog, initial admission, final binding) has a runtime owner; WebSocket keeps - the LOGIN -> PLAY -> LOOK proof. Until then Telnet PLAY must stay fail-closed. - """ +def authenticated_telnet_play_steps(username, password, world, worlds_expect, login_expect, play_expect): + """Run the canonical Telnet lobby and PLAY on one live connection.""" return [ (f"LOGIN {username} {password}", [login_expect], "LOGIN"), - (f"PLAY {world}", ["ERROR ADMISSION_UNAVAILABLE"], "PLAY"), + ("WORLDS", [worlds_expect], "WORLDS"), + (f"REALMS {world}", ["OK REALMS"], "REALMS"), + (f"JOIN {world}", ["OK JOIN"], "JOIN"), + (f"PLAY {world}", [play_expect], "PLAY"), ] diff --git a/dev-tools/tests/smoke-transport-contract.sh b/dev-tools/tests/smoke-transport-contract.sh index 1a75783de0..e9444e9378 100644 --- a/dev-tools/tests/smoke-transport-contract.sh +++ b/dev-tools/tests/smoke-transport-contract.sh @@ -2016,11 +2016,13 @@ with patch( raise AssertionError("unrelated HTTP exception was incorrectly classified") -telnet_steps = smoke_common.authenticated_telnet_login_steps( - "demo@example.com", "swordfish", "demo", "OK LOGIN" +telnet_steps = smoke_common.authenticated_telnet_play_steps( + "demo@example.com", "swordfish", "demo", "OK WORLDS", "OK LOGIN", "OK PLAY" ) -assert [step[2] for step in telnet_steps] == ["LOGIN", "PLAY"] -assert telnet_steps[1][:2] == ("PLAY demo", ["ERROR ADMISSION_UNAVAILABLE"]) +assert [step[2] for step in telnet_steps] == ["LOGIN", "WORLDS", "REALMS", "JOIN", "PLAY"] +assert telnet_steps[2][:2] == ("REALMS demo", ["OK REALMS"]) +assert telnet_steps[3][:2] == ("JOIN demo", ["OK JOIN"]) +assert telnet_steps[4][:2] == ("PLAY demo", ["OK PLAY"]) item_steps = smoke_common.gameplay_item_container_equipment_steps( @@ -2075,11 +2077,10 @@ for script in \ "$ROOT_DIR/services/game-session-service/websocket-login-look-smoke.sh" \ "$ROOT_DIR/services/tcp-proxy-service/telnet-login-look-smoke.sh"; do if [[ "$script" == *"tcp-proxy-service/telnet-login-look-smoke.sh" ]]; then - # Authenticated Telnet WORLDS/PLAY/LOOK is deferred to the canonical admission chain. grep -Fq 'discovery_selector = world' "$script" || { echo "$script must gate the mutation extension on the configured WORLDS selector" >&2; exit 1; } - grep -Fq 'authenticated_telnet_login_steps(login_email, password, world, login_expect)' "$script" || - { echo "$script baseline must use the authenticated Telnet LOGIN plan" >&2; exit 1; } + grep -Fq 'authenticated_telnet_play_steps(login_email, password, world, worlds_expect, login_expect, play_expect)' "$script" || + { echo "$script baseline must use the authenticated Telnet PLAY plan" >&2; exit 1; } else grep -Fq 'discovery_selector=world' "$script" || { echo "$script must gate LOGIN on the configured WORLDS selector" >&2; exit 1; } diff --git a/docker/docker-compose.pre-v1-login.override.yml b/docker/docker-compose.pre-v1-login.override.yml index 5e22587a8d..9dcc7ef99c 100644 --- a/docker/docker-compose.pre-v1-login.override.yml +++ b/docker/docker-compose.pre-v1-login.override.yml @@ -147,6 +147,7 @@ services: condition: service_healthy environment: FIREMUD_GAME_SESSION_AUTHENTICATED_GAMEPLAY_ENABLED: "true" + FIREMUD_GAME_SESSION_CANONICAL_PLAY_PRE_V1_ENABLED: ${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:-false} FIREMUD_GAME_SESSION_INITIAL_GAMEPLAY_LOGIN_PROTECTED_SOURCES_ENABLED: "true" FIREMUD_GAME_SESSION_INITIAL_GAMEPLAY_LOGIN_PROTECTED_SOURCES_COORDINATION_URI: redis://gamesession_coord_app:pre-v1-game-session-coordination@redis-coord:6379/0 FIREMUD_GAME_SESSION_INITIAL_GAMEPLAY_LOGIN_PROTECTED_SOURCES_COORDINATION_COMMAND_TIMEOUT_MILLIS: "2000" diff --git a/protos/world-management/v1/world_canonical_instance_lifecycle_read.proto b/protos/world-management/v1/world_canonical_instance_lifecycle_read.proto index 2fe0c25a6b..9194be50a2 100644 --- a/protos/world-management/v1/world_canonical_instance_lifecycle_read.proto +++ b/protos/world-management/v1/world_canonical_instance_lifecycle_read.proto @@ -9,6 +9,9 @@ option java_multiple_files = true; service WorldCanonicalInstanceLifecycleReadService { rpc ReadWorldCanonicalInstanceLifecycle(ReadWorldCanonicalInstanceLifecycleRequest) returns (ReadWorldCanonicalInstanceLifecycleResponse); + // Read-only start room of the exact ACTIVE run-owned fixed fixture. + rpc ReadRunOwnedFixtureStartRoom(ReadRunOwnedFixtureStartRoomRequest) + returns (ReadRunOwnedFixtureStartRoomResponse); } message ReadWorldCanonicalInstanceLifecycleRequest { @@ -20,3 +23,12 @@ message ReadWorldCanonicalInstanceLifecycleResponse { // Complete closed evidence bytes, including the exact request echo and full launch binding. bytes canonical_response_bytes = 1; } + +message ReadRunOwnedFixtureStartRoomRequest { + ReadWorldCanonicalInstanceLifecycleRequest lifecycle = 1; +} + +message ReadRunOwnedFixtureStartRoomResponse { + ReadWorldCanonicalInstanceLifecycleResponse lifecycle = 1; + string room_instance_key = 2; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountGameplayAdmissionReceiversConfiguration.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountGameplayAdmissionReceiversConfiguration.java index 0655af109f..1b72ca6c1b 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountGameplayAdmissionReceiversConfiguration.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountGameplayAdmissionReceiversConfiguration.java @@ -125,7 +125,7 @@ AccountCanonicalRuntimeMembershipSnapshotRepository accountCanonicalRuntimeMembe } @Bean - AccountPlayerAdmissionEntitlementGrpcService accountPlayerAdmissionEntitlementReceiver( + BindableService accountPlayerAdmissionEntitlementReceiver( DSLContext dsl, AccountRepository accounts, AccountGameplayAdmissionCallerVerifier verifier, @@ -153,7 +153,7 @@ AccountPlayerAdmissionEntitlementGrpcService accountPlayerAdmissionEntitlementRe transactions, Clock.systemUTC(), namespace); - return new AccountPlayerAdmissionEntitlementGrpcService(owner, namespace); + return new AccountPlayerAdmissionEntitlementGrpcService(owner, namespace)::bindProtectedService; } @Bean diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java index b9b04ec6bd..c849d6d4e5 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java @@ -572,9 +572,8 @@ private PublishedRealmEvidence readProtectedTarget( if (!resolved.strictSelector().equals(result.selector()) || !resolved.currentTarget().equals(result.currentTarget())) throw targetPrecondition(); requireSupportedTarget(result.currentTarget()); - // The entitlement capture binds Human published and World lifecycle evidence; the run-owned - // fixture has neither, so its PLAY entitlement remains unsupported until its own schema. - if (result.isRunOwnedFixture()) throw targetPrecondition(); + // The run-owned fixture (pre-v1 gate waiver) binds its sealed policy and World fixture + // lifecycle through the evidence's fixture source shape instead of Human publication. return result; } catch (CanonicalGameplayAdmissionDecisionReadClient.ClientUnavailableException failure) { throw unavailable(); @@ -622,7 +621,6 @@ private RuntimePlayerAdmissionEntitlementEvidence capture( binding.put("evaluatedAt", scope.evaluatedAt()); binding.put("connectScopeExpiresAt", scope.connectScopeExpiresAt()); var caller = player.issuance(); - var world = target.worldLifecycleEvidence(); Map sources = new LinkedHashMap<>(); sources.put("callerTokenJti", caller.identity().tokenJti().toString()); sources.put( @@ -638,19 +636,33 @@ private RuntimePlayerAdmissionEntitlementEvidence capture( sources.put("callerOperationId", caller.identity().operationId().toString()); sources.put("scopeDigest", scope.scopeDigest()); sources.put("entitlementSourceDigest", entitlementSourceDigest); - sources.put( - "admissionPointerSnapshotDigest", target.sourceEvidence().admissionPointerSnapshotDigest()); - sources.put( - "gameSessionOwnerProofDigest", - target.sourceEvidence().gameSessionOwnerProof().proofDigest()); - sources.put( - "publishedPolicySetDigest", - target.sourceEvidence().publishedPolicySetEvidence().policySetDigest()); - sources.put( - "worldLifecycleDigest", - RuntimePlayerAdmissionEntitlementEvidence.digestBytes(world.canonicalBytes())); - sources.put("worldCaptureId", world.captureId().toString()); - sources.put("worldRowVersion", Long.toString(world.rowVersion())); + if (target.isRunOwnedFixture()) { + var fixture = target.fixtureSource(); + var lifecycle = target.fixtureLifecycleEvidence(); + sources.put("admissionPointerSnapshotDigest", fixture.admissionPointerSnapshotDigest()); + sources.put("gameSessionOwnerProofDigest", fixture.gameSessionOwnerProof().proofDigest()); + sources.put("fixturePolicySealDigest", fixture.fixturePolicySealEvidenceDigest()); + sources.put( + "fixtureLifecycleDigest", + RuntimePlayerAdmissionEntitlementEvidence.digestBytes(lifecycle.canonicalBytes())); + sources.put("worldRowVersion", Long.toString(lifecycle.rowVersion())); + } else { + var world = target.worldLifecycleEvidence(); + sources.put( + "admissionPointerSnapshotDigest", + target.sourceEvidence().admissionPointerSnapshotDigest()); + sources.put( + "gameSessionOwnerProofDigest", + target.sourceEvidence().gameSessionOwnerProof().proofDigest()); + sources.put( + "publishedPolicySetDigest", + target.sourceEvidence().publishedPolicySetEvidence().policySetDigest()); + sources.put( + "worldLifecycleDigest", + RuntimePlayerAdmissionEntitlementEvidence.digestBytes(world.canonicalBytes())); + sources.put("worldCaptureId", world.captureId().toString()); + sources.put("worldRowVersion", Long.toString(world.rowVersion())); + } // The capacity bundle and its live caller/receipt deadlines must agree with the PostgreSQL // clock that stamps the evidence, so application/database skew cannot future-date the bundle. Instant capacityEvaluatedAt = AccountTenantCapacityRepository.databaseNow(dsl); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcService.java index 1a4efe1a70..5b7c1d1193 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcService.java @@ -3,6 +3,7 @@ import com.google.protobuf.Any; import io.grpc.Server; import io.grpc.ServerInterceptors; +import io.grpc.ServerServiceDefinition; import io.grpc.Status; import io.grpc.StatusRuntimeException; import io.grpc.TlsServerCredentials; @@ -58,10 +59,15 @@ public Server createUnregisteredServer( TlsServerCredentials.ClientAuth.REQUIRE, GrpcRequestBytePolicy.ordinary(), RuntimePlayerAdmissionEntitlementGrpcCodec.MAX_REQUEST_WIRE_BYTES); - factory.addService(ServerInterceptors.interceptForward(this, guard)); + factory.addService(bindProtectedService()); return factory.createServer(); } + /** Binds the receiver and its method guard to the same private caller context. */ + public ServerServiceDefinition bindProtectedService() { + return ServerInterceptors.interceptForward(this, guard); + } + @Override public void readPlayerAdmissionEntitlement( ReadPlayerAdmissionEntitlementRequest wire, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFirstJoinAuthorityStorageIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFirstJoinAuthorityStorageIntegrationTest.java index f81e90f9e7..b92719929e 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFirstJoinAuthorityStorageIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFirstJoinAuthorityStorageIntegrationTest.java @@ -18,6 +18,7 @@ import javax.sql.DataSource; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Checkpoint; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; @@ -225,9 +226,19 @@ void v38DoesNotBackfillRetainedMembershipAndCanonicalRoleSnapshotRequiresExactSo .fetchOne(0, Long.class)) .isZero(); + Account freshAccount = new Account(); + freshAccount.setUsername("first-join"); + freshAccount.setEmail("first-join@example.test"); + freshAccount.setPasswordHash("first-join-test-hash"); + inTransaction(transaction, () -> accounts.save(freshAccount)); + UUID freshAccountUuid = freshAccount.getAccountUuid(); UUID tenantUuid = UUID.fromString("f8871fb0-7810-4b72-bb13-09e29a3509f2"); FreshTenantCreationEvidence tenantSource = freshTenantEvidence(tenantUuid); - transaction.executeWithoutResult(status -> freshTenants.importVerified(tenantSource)); + transaction.executeWithoutResult( + status -> { + freshTenants.importVerified(tenantSource); + new AccountAuthorityGenerationRepository(dsl).initializeTenantIfAbsent(tenantUuid); + }); VerifiedTenantProvenance provenance = new VerifiedTenantProvenance( null, @@ -239,11 +250,11 @@ void v38DoesNotBackfillRetainedMembershipAndCanonicalRoleSnapshotRequiresExactSo transaction.execute( status -> { AccountTenantMembership pendingMembership = - memberships.createFreshMembershipForJoin(account.getAccountUuid(), tenantUuid); + memberships.createFreshMembershipForJoin(freshAccountUuid, tenantUuid); long membershipId = Objects.requireNonNull(pendingMembership.getId()); assertThat( roleSnapshots.findForCanonicalUpdate( - account.getAccountUuid(), + freshAccountUuid, tenantUuid, provenance, membershipId, @@ -253,13 +264,13 @@ void v38DoesNotBackfillRetainedMembershipAndCanonicalRoleSnapshotRequiresExactSo AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot written = roleSnapshots.replaceCanonical( pendingMembership, - account.getAccountUuid(), + freshAccountUuid, tenantUuid, provenance, pendingMembership.getMembershipVersion(), List.of()); assertThat(written.roles()).isEmpty(); - assertThat(written.accountUuid()).isEqualTo(account.getAccountUuid()); + assertThat(written.accountUuid()).isEqualTo(freshAccountUuid); assertThat(written.tenantUuid()).isEqualTo(tenantUuid); assertThat(written.tenantId()).isNull(); assertThat(written.tenantProvenance()).isEqualTo(provenance); @@ -273,7 +284,7 @@ void v38DoesNotBackfillRetainedMembershipAndCanonicalRoleSnapshotRequiresExactSo assertThatThrownBy( () -> roleSnapshots.findForCanonicalUpdate( - account.getAccountUuid(), + freshAccountUuid, tenantUuid, changedProvenance, membershipId, @@ -283,7 +294,7 @@ void v38DoesNotBackfillRetainedMembershipAndCanonicalRoleSnapshotRequiresExactSo assertThatThrownBy( () -> roleSnapshots.findForCanonicalUpdate( - account.getAccountUuid(), + freshAccountUuid, tenantUuid, provenance, membershipId, @@ -292,7 +303,7 @@ void v38DoesNotBackfillRetainedMembershipAndCanonicalRoleSnapshotRequiresExactSo .hasMessageContaining("membership version is missing or mismatched"); assertThat( roleSnapshots.findForCanonicalUpdate( - account.getAccountUuid(), + freshAccountUuid, tenantUuid, provenance, membershipId, @@ -300,7 +311,7 @@ void v38DoesNotBackfillRetainedMembershipAndCanonicalRoleSnapshotRequiresExactSo .contains(written); assertThatThrownBy( - () -> memberships.findFreshMembership(account.getAccountUuid(), tenantUuid)) + () -> memberships.findFreshMembership(freshAccountUuid, tenantUuid)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("no positive authority event"); status.setRollbackOnly(); @@ -311,7 +322,7 @@ void v38DoesNotBackfillRetainedMembershipAndCanonicalRoleSnapshotRequiresExactSo dsl.resultQuery( "SELECT count(*) FROM account_tenant_membership " + "WHERE account_id = ? AND tenant_uuid = ?", - accountId, + freshAccount.getId(), tenantUuid) .fetchOne(0, Long.class)) .isZero(); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java index a2a0e7819a..94b87d23e3 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java @@ -307,6 +307,28 @@ void tenantOperationDemoCapturesCurrentSourceOnActualWritableSerializableConnect .containsEntry("requestId", request.requestId().toString()); } + @Test + void runOwnedFixtureTargetCapturesTheFixtureSourceShape() { + Fixture f = fixture(false); + controlledTarget(f.targets, true); + var value = f.owner.evaluate(f.request(), CONTROLLED_COMPACT_TOKEN); + assertThat(value.isRunOwnedFixtureSource()).isTrue(); + assertThat(((Map) value.fields().get("target")).get("targetClass")) + .isEqualTo("PUBLIC_PRODUCTION"); + var references = (Map) value.fields().get("sourceReferences"); + assertThat(references.get("fixturePolicySealDigest")).isEqualTo("sha256:" + "d".repeat(64)); + assertThat(references.get("fixtureLifecycleDigest")) + .isEqualTo( + RuntimePlayerAdmissionEntitlementEvidence.digestBytes( + "controlled-fixture-world-source".getBytes(StandardCharsets.UTF_8))); + assertThat(references.get("worldRowVersion")).isEqualTo("3"); + assertThat(references.containsKey("worldCaptureId")).isFalse(); + assertThat(references.containsKey("publishedPolicySetDigest")).isFalse(); + assertThat(references.containsKey("worldLifecycleDigest")).isFalse(); + assertThat(RuntimePlayerAdmissionEntitlementEvidence.parseCanonical(value.canonicalBytes())) + .isEqualTo(value); + } + @Test void actualAbsenceBaselineReturnsNonadmittingPlayerEvidenceWithoutCreatingMembership() { Fixture f = fixture(false); @@ -586,8 +608,12 @@ private static Instant databaseNow(DSLContext dsl) { /** Controlled protected-client double: no physical GS/World source provenance is claimed. */ private static void controlledTarget(CanonicalGameplayAdmissionDecisionReadClient targets) { - when(targets.resolvePublishedRealmAdmissionTarget(any())) - .thenAnswer( + controlledTarget(targets, false); + } + + private static void controlledTarget( + CanonicalGameplayAdmissionDecisionReadClient targets, boolean runOwnedFixture) { + doAnswer( invocation -> { assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); var selector = @@ -663,6 +689,30 @@ private static void controlledTarget(CanonicalGameplayAdmissionDecisionReadClien .thenReturn(UUID.fromString("44444444-4444-4444-8444-444444444444")); when(world.rowVersion()).thenReturn(2L); when(read.worldLifecycleEvidence()).thenReturn(world); + if (runOwnedFixture) { + when(read.isRunOwnedFixture()).thenReturn(true); + when(read.sourceEvidence()).thenThrow(new IllegalStateException("fixture")); + when(read.worldLifecycleEvidence()).thenThrow(new IllegalStateException("fixture")); + var fixture = + mock( + net.firedevops.firemud.common.world + .CanonicalGameplayRunOwnedFixtureSourceEvidence.class); + when(fixture.admissionPointerSnapshotDigest()).thenReturn("a".repeat(64)); + when(fixture.gameSessionOwnerProof()).thenReturn(ownerProof); + when(fixture.fixturePolicySealEvidenceDigest()) + .thenReturn("sha256:" + "d".repeat(64)); + when(read.fixtureSource()).thenReturn(fixture); + var lifecycle = + mock( + net.firedevops.firemud.common.world.WorldRunOwnedFixtureLifecycleEvidence + .class); + when(lifecycle.canonicalBytes()) + .thenReturn( + "controlled-fixture-world-source" + .getBytes(java.nio.charset.StandardCharsets.UTF_8)); + when(lifecycle.rowVersion()).thenReturn(3L); + when(read.fixtureLifecycleEvidence()).thenReturn(lifecycle); + } when(targets.readPublishedRealmAdmissionOwner(strict)) .thenAnswer( readCall -> { @@ -671,7 +721,9 @@ private static void controlledTarget(CanonicalGameplayAdmissionDecisionReadClien return read; }); return resolved; - }); + }) + .when(targets) + .resolvePublishedRealmAdmissionTarget(any()); } private static final class Fixture { @@ -686,6 +738,7 @@ private static final class Fixture { private final UUID tenantId = UUID.randomUUID(); private final CanonicalJoinScopeV2 scope; private final AccountPlayerAdmissionEntitlementOwner owner; + private final CanonicalGameplayAdmissionDecisionReadClient targets; private Fixture( DriverManagerDataSource dataSource, @@ -881,7 +934,7 @@ private Fixture( .isEqualTo(Connection.TRANSACTION_SERIALIZABLE)); return Optional.of(candidate); }); - var targets = mock(CanonicalGameplayAdmissionDecisionReadClient.class); + targets = mock(CanonicalGameplayAdmissionDecisionReadClient.class); controlledTarget(targets); owner = new AccountPlayerAdmissionEntitlementOwner( diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidence.java index dd88e9fdcd..ca49175031 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidence.java @@ -31,6 +31,12 @@ * Account's PUBLIC_PRODUCTION SHARED PRESEEDED PLAYER_ADMISSION variant of the existing runtime * evidence contract. Content validation is not source authentication or an admission grant. * + *

Source references take exactly one closed shape. The Human shape names the Game Design + * policy-set digest and the World capture lifecycle. The run-owned fixture shape (pre-v1 gate + * waiver) has no Human publication or capture: it names the catalog-retained fixture policy-seal + * evidence digest and World's fixture lifecycle digest instead, with no capture id. The target + * class stays PUBLIC_PRODUCTION for both. + * *

The owner must derive this value from its final Account transaction and protected target read. * Target source references name that complete read; they hold no World lock through later use. * Decoding validates content only and cannot promote caller-supplied data to source authority. @@ -104,6 +110,23 @@ public final class RuntimePlayerAdmissionEntitlementEvidence { "worldLifecycleDigest", "worldCaptureId", "worldRowVersion"); + private static final Set FIXTURE_SOURCE_FIELDS = + Set.of( + "callerTokenJti", + "callerTokenExpiresAt", + "paidReceiptValidUntil", + "callerTokenSha256", + "callerRegistryRecordSha256", + "callerCommitProofSha256", + "callerContextId", + "callerOperationId", + "scopeDigest", + "entitlementSourceDigest", + "admissionPointerSnapshotDigest", + "gameSessionOwnerProofDigest", + "fixturePolicySealDigest", + "fixtureLifecycleDigest", + "worldRowVersion"); private final Snapshot membership; private final byte[] canonicalBytes; @@ -151,7 +174,8 @@ public static RuntimePlayerAdmissionEntitlementEvidence fromOwnerEvaluation( throw invalid("Verified connect scope token hash required"); exact(target, TARGET_FIELDS); exact(facts, FACT_FIELDS); - exact(source, SOURCE_FIELDS); + boolean fixture = source != null && source.keySet().equals(FIXTURE_SOURCE_FIELDS); + exact(source, fixture ? FIXTURE_SOURCE_FIELDS : SOURCE_FIELDS); if (!"PUBLIC_PRODUCTION".equals(target.get("targetClass")) || !"PRESEEDED_ONLY".equals(target.get("characterCreationPolicy")) || !peer.namespace().equals(target.get("targetNamespace")) @@ -177,7 +201,9 @@ public static RuntimePlayerAdmissionEntitlementEvidence fromOwnerEvaluation( || !evaluatedAt.isBefore(scopeExpiry)) throw invalid("Scope is not current at evaluation"); validateFacts(facts, membership); for (String key : - List.of("callerTokenJti", "callerContextId", "callerOperationId", "worldCaptureId")) + fixture + ? List.of("callerTokenJti", "callerContextId", "callerOperationId") + : List.of("callerTokenJti", "callerContextId", "callerOperationId", "worldCaptureId")) requireUuid(text(source.get(key))); for (String key : List.of("callerTokenSha256", "callerRegistryRecordSha256", "callerCommitProofSha256")) @@ -186,8 +212,8 @@ public static RuntimePlayerAdmissionEntitlementEvidence fromOwnerEvaluation( List.of( "scopeDigest", "entitlementSourceDigest", - "worldLifecycleDigest", - "publishedPolicySetDigest", + fixture ? "fixtureLifecycleDigest" : "worldLifecycleDigest", + fixture ? "fixturePolicySealDigest" : "publishedPolicySetDigest", "gameSessionOwnerProofDigest")) if (!text(source.get(key)).matches("sha256:[0-9a-f]{64}")) throw invalid("Source digest required"); @@ -581,6 +607,12 @@ public void requireCurrentAt(Instant now) { throw invalid("Player entitlement source observation expired"); } + /** True when the source references take the run-owned fixture shape (pre-v1 gate waiver). */ + public boolean isRunOwnedFixtureSource() { + return fields().get("sourceReferences") instanceof Map source + && source.containsKey("fixturePolicySealDigest"); + } + public Snapshot membershipSource() { return membership; } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleClient.java index b859c2bac7..e4d88d8c1b 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleClient.java @@ -14,6 +14,7 @@ import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.worldmanagement.v1.ReadRunOwnedFixtureStartRoomRequest; import net.firedevops.firemud.worldmanagement.v1.WorldCanonicalInstanceLifecycleReadServiceGrpc; /** Explicit mTLS client for the exact World canonical instance lifecycle read. */ @@ -114,6 +115,46 @@ public WorldRunOwnedFixtureLifecycleEvidence readRunOwnedFixture( } } + /** Reads the World-owned first room and same-snapshot lifecycle of an exact ACTIVE fixture. */ + public FixtureStartRoom readRunOwnedFixtureStartRoom( + WorldCanonicalInstanceLifecycleEvidence.Request request) { + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "World canonical lifecycle request must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readRunOwnedFixtureStartRoom( + ReadRunOwnedFixtureStartRoomRequest.newBuilder() + .setLifecycle(WorldCanonicalInstanceLifecycleGrpcCodec.toRequest(request)) + .build()); + try { + if (!response.hasLifecycle() || !response.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("World fixture start room has no exact lifecycle"); + } + return new FixtureStartRoom( + WorldCanonicalInstanceLifecycleGrpcCodec.fromFixtureResponse( + request, response.getLifecycle()), + response.getRoomInstanceKey()); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "World returned invalid fixture start room evidence", invalid); + } + } + + public record FixtureStartRoom(WorldRunOwnedFixtureLifecycleEvidence lifecycle, String roomKey) { + public FixtureStartRoom { + Objects.requireNonNull(lifecycle, "lifecycle"); + if (!"ACTIVE".equals(lifecycle.lifecycleStatus()) + || roomKey == null + || !roomKey.matches("R-[1-9][0-9]{0,18}")) { + throw new IllegalArgumentException("World fixture start room evidence is unavailable"); + } + } + } + @Override protected String configuredTarget(ServiceEndpointsProperties endpoints) { return endpoints.getWorldManagementService(); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidenceTest.java index 2ee2480c48..86bfd82222 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidenceTest.java @@ -116,6 +116,43 @@ void identitiesBindActualInputsAndSeparateSnapshotFromEvaluation() { .isNotEqualTo(first.fields().get("snapshotIdentity")); } + @Test + void runOwnedFixtureSourceShapeRoundTripsAndStaysDistinctFromHuman() { + var human = capture(target(), facts(), sources(), NOW); + var fixture = capture(target(), facts(), fixtureSources(), NOW); + assertThat(human.isRunOwnedFixtureSource()).isFalse(); + assertThat(fixture.isRunOwnedFixtureSource()).isTrue(); + assertThat(fixture.fields().get("target")).isEqualTo(human.fields().get("target")); + var references = (Map) fixture.fields().get("sourceReferences"); + assertThat(references.get("fixturePolicySealDigest")).isEqualTo("sha256:" + "c".repeat(64)); + assertThat(references.keySet()) + .doesNotContain("worldCaptureId", "publishedPolicySetDigest", "worldLifecycleDigest"); + assertThat(fixture.fields().get("snapshotIdentity")) + .isNotEqualTo(human.fields().get("snapshotIdentity")); + assertThat(RuntimePlayerAdmissionEntitlementEvidence.parseCanonical(fixture.canonicalBytes())) + .isEqualTo(fixture); + } + + @Test + void runOwnedFixtureSourceShapeIsClosed() { + var mixed = fixtureSources(); + mixed.put("worldCaptureId", REQUEST.toString()); + var unprefixedSeal = fixtureSources(); + unprefixedSeal.put("fixturePolicySealDigest", HASH); + var missingLifecycle = fixtureSources(); + missingLifecycle.remove("fixtureLifecycleDigest"); + var humanPlusSeal = sources(); + humanPlusSeal.put("fixturePolicySealDigest", "sha256:" + HASH); + for (var invalid : List.of(mixed, unprefixedSeal, missingLifecycle, humanPlusSeal)) { + assertThatThrownBy(() -> capture(target(), facts(), invalid, NOW)) + .isInstanceOf(IllegalArgumentException.class); + } + var fixtureClass = target(); + fixtureClass.put("targetClass", "RUN_OWNED_FIXTURE"); + assertThatThrownBy(() -> capture(fixtureClass, facts(), fixtureSources(), NOW)) + .isInstanceOf(IllegalArgumentException.class); + } + @Test void incompleteOrConflictingTargetFactsAndSourcesNeverProduceAValue() { for (String field : List.of("activeWorldEpoch", "canonicalVersionId", "targetClass")) { @@ -325,6 +362,16 @@ private static Map sources() { return source; } + private static Map fixtureSources() { + Map source = sources(); + source.remove("worldCaptureId"); + source.remove("publishedPolicySetDigest"); + source.remove("worldLifecycleDigest"); + source.put("fixturePolicySealDigest", "sha256:" + "c".repeat(64)); + source.put("fixtureLifecycleDigest", "sha256:" + "d".repeat(64)); + return source; + } + private static Snapshot membership() { String requestDigest = GameTenantCreationDigest.requestDigest("prod", REQUEST, "world", "World", null); diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodecTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodecTest.java index 547c3824cd..cfc8c5e56e 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodecTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodecTest.java @@ -199,6 +199,22 @@ void rejectsValidCanonicalEvidenceForDifferentScope() { .isInstanceOf(IllegalArgumentException.class); } + @Test + void runOwnedFixtureSourceShapeRoundTripsThroughTheResponse() { + var request = request(ACCOUNT, REQUEST); + Map fixtureSources = sources(); + fixtureSources.remove("worldCaptureId"); + fixtureSources.remove("publishedPolicySetDigest"); + fixtureSources.remove("worldLifecycleDigest"); + fixtureSources.put("fixturePolicySealDigest", "sha256:" + "c".repeat(64)); + fixtureSources.put("fixtureLifecycleDigest", "sha256:" + "d".repeat(64)); + var value = capture(target(), facts(), fixtureSources, NOW); + var response = RuntimePlayerAdmissionEntitlementGrpcCodec.toResponse(request, value); + var parsed = RuntimePlayerAdmissionEntitlementGrpcCodec.requireResponse(request, response); + assertThat(parsed).isEqualTo(value); + assertThat(parsed.isRunOwnedFixtureSource()).isTrue(); + } + @Test void changedCallerRequestOrScopeCannotBeReturnedAsCorrelatedEvidence() { var request = request(ACCOUNT, REQUEST); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingRegionBridgeObligation.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingRegionBridgeObligation.java index 418bff9f2d..2353b8feb5 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingRegionBridgeObligation.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingRegionBridgeObligation.java @@ -117,8 +117,8 @@ public CanonicalGameplayBindingRegionBridgeObligation( || prepared != (canonicalRegionId != null) || prepared != (worldLifecycleEpoch != null) || prepared != (worldLifecycleRowVersion != null) - || prepared != (worldCaptureId != null) - || prepared != (worldGraphSha256 != null) + || (!prepared && (worldCaptureId != null || worldGraphSha256 != null)) + || (worldCaptureId == null) != (worldGraphSha256 == null) || prepared != (worldPreparationInputDigest != null)) { throw new IllegalArgumentException("Region bridge operation provenance is incomplete"); } @@ -130,10 +130,13 @@ public CanonicalGameplayBindingRegionBridgeObligation( requirePositive(entityProjectionGeneration, "entityProjectionGeneration"); requirePositive(entityProjectionFence, "entityProjectionFence"); requireNonNil(canonicalRegionId, "canonicalRegionId"); - requireNonNil(worldCaptureId, "worldCaptureId"); + // A run-owned fixture World source (pre-v1 gate waiver) has no capture or graph. + if (worldCaptureId != null) { + requireNonNil(worldCaptureId, "worldCaptureId"); + requireDigest(worldGraphSha256, "worldGraphSha256"); + } requireDigest(entityReferenceDigest, "entityReferenceDigest"); requireDigest(worldSourceDigest, "worldSourceDigest"); - requireDigest(worldGraphSha256, "worldGraphSha256"); requirePrefixedDigest(worldPreparationInputDigest, "worldPreparationInputDigest"); if (actorOrigin instanceof CreationOrigin created && !entityWorkloadNamespace.equals(created.original().getTargetNamespace())) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayRuntimeActorReference.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayRuntimeActorReference.java index 531a04b536..9c3aa235f8 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayRuntimeActorReference.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayRuntimeActorReference.java @@ -6,10 +6,14 @@ import net.firedevops.firemud.entitymanagement.v1.PlayerCreatedActorOrigin; import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest; -/** Constructed only by the exact authenticated, purpose-specific Entity response readers. */ +/** + * Constructed only by the exact authenticated, purpose-specific Entity response readers, or by the + * gate-waived pre-v1 run-owned fixture stand-in. + */ public sealed interface CanonicalGameplayRuntimeActorReference permits CanonicalPreseededActorRuntimeReferenceClient.RuntimeActorReference, - CanonicalPlayerCreatedRuntimeReferenceClient.RuntimeActorReference { + CanonicalPlayerCreatedRuntimeReferenceClient.RuntimeActorReference, + PreV1RunOwnedFixtureActorReference { String workloadNamespace(); CanonicalRuntimeEntityId runtimeEntityId(); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/PreV1RunOwnedFixtureActorReference.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/PreV1RunOwnedFixtureActorReference.java new file mode 100644 index 0000000000..8b802a9145 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/PreV1RunOwnedFixtureActorReference.java @@ -0,0 +1,167 @@ +package net.firedevops.firemud.gamesession.client; + +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.prev1.PreV1GateWaivers; +import net.firedevops.firemud.entitymanagement.v1.PreseededActorAssignmentExpectedTarget; +import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest; + +/** + * Pre-v1 gate waiver (ADR 0185) stand-in for the run-owned fixture's actor. The fixture world has + * no Entity preseeded assignment, so this value carries no Entity provenance: Game Session derives + * the actor identity and runtime entity id. Its evidence bytes frame only those derived identities + * and the exact expected target, so repeated reads of one request compare equal. + */ +public final class PreV1RunOwnedFixtureActorReference + implements CanonicalGameplayRuntimeActorReference { + static final String EVIDENCE_LABEL = "pre-v1-run-owned-fixture-actor/v1"; + + private final String workloadNamespace; + private final CanonicalRuntimeEntityId runtimeEntityId; + private final UUID canonicalAccountUuid; + private final UUID characterUuid; + private final PreseededActorAssignmentExpectedTarget target; + private final AssignmentOrigin origin; + + private PreV1RunOwnedFixtureActorReference( + String workloadNamespace, + CanonicalRuntimeEntityId runtimeEntityId, + UUID canonicalAccountUuid, + UUID characterUuid, + PreseededActorAssignmentExpectedTarget target, + AssignmentOrigin origin) { + this.workloadNamespace = workloadNamespace; + this.runtimeEntityId = runtimeEntityId; + this.canonicalAccountUuid = canonicalAccountUuid; + this.characterUuid = characterUuid; + this.target = target; + this.origin = origin; + } + + /** + * Builds the stand-in for one exact schema-1 World request. Refuses without the gate waivers (and + * so under the prod profile). The caller owns the deterministic identity derivations. + */ + public static PreV1RunOwnedFixtureActorReference standIn( + PreV1GateWaivers waivers, + String workloadNamespace, + CanonicalInitialPlayerLocationRequest request, + long runtimeEntityId) { + if (waivers == null || !waivers.enabled()) { + throw new IllegalStateException("Run-owned fixture actor stand-in requires the waivers"); + } + Objects.requireNonNull(request, "request"); + if (workloadNamespace == null || workloadNamespace.isBlank()) { + throw new IllegalArgumentException("Exact Game Session workload namespace required"); + } + if (request.getSchemaVersion() != 1 + || request.hasPlayerCreatedOrigin() + || !request.hasExpectedTarget() + || !request.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Closed schema-1 preseeded World request required"); + } + var target = request.getExpectedTarget(); + var origin = + new AssignmentOrigin( + canonical(request.getAssignmentUuid()), request.getAssignmentIntentDigest()); + return new PreV1RunOwnedFixtureActorReference( + workloadNamespace, + new CanonicalRuntimeEntityId( + canonical(target.getCanonicalTenantUuid()), + target.getGameInstanceId(), + runtimeEntityId), + canonical(request.getCanonicalAccountUuid()), + canonical(request.getCharacterUuid()), + target, + origin); + } + + @Override + public String workloadNamespace() { + return workloadNamespace; + } + + @Override + public CanonicalRuntimeEntityId runtimeEntityId() { + return runtimeEntityId; + } + + /** No Entity projection exists; the stand-in's first and only generation. */ + @Override + public long projectionGeneration() { + return 1L; + } + + @Override + public long projectionFence() { + return 1L; + } + + @Override + public UUID canonicalAccountUuid() { + return canonicalAccountUuid; + } + + @Override + public UUID characterUuid() { + return characterUuid; + } + + @Override + public UUID playableStateNamespaceId() { + return UUID.fromString(target.getPlayableStateNamespaceUuid()); + } + + @Override + public ActorOrigin origin() { + return origin; + } + + @Override + public boolean matchesWorldRequest(CanonicalInitialPlayerLocationRequest request) { + return request != null + && request.getSchemaVersion() == 1 + && !request.hasPlayerCreatedOrigin() + && origin.assignmentId().toString().equals(request.getAssignmentUuid()) + && origin.intentDigest().equals(request.getAssignmentIntentDigest()) + && canonicalAccountUuid.toString().equals(request.getCanonicalAccountUuid()) + && characterUuid.toString().equals(request.getCharacterUuid()) + && target.equals(request.getExpectedTarget()); + } + + @Override + public byte[] canonicalEvidenceBytes() { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + for (byte[] part : + new byte[][] { + EVIDENCE_LABEL.getBytes(StandardCharsets.US_ASCII), + workloadNamespace.getBytes(StandardCharsets.UTF_8), + Long.toString(runtimeEntityId.value()).getBytes(StandardCharsets.US_ASCII), + canonicalAccountUuid.toString().getBytes(StandardCharsets.US_ASCII), + characterUuid.toString().getBytes(StandardCharsets.US_ASCII), + origin.assignmentId().toString().getBytes(StandardCharsets.US_ASCII), + origin.intentDigest().getBytes(StandardCharsets.US_ASCII), + target.toByteArray() + }) { + out.writeBytes(ByteBuffer.allocate(Integer.BYTES).putInt(part.length).array()); + out.writeBytes(part); + } + return out.toByteArray(); + } + + private static UUID canonical(String value) { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || parsed.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("Canonical non-nil UUID required"); + } + return parsed; + } + + @Override + public String toString() { + return "PreV1RunOwnedFixtureActorReference[redacted]"; + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/PreV1CanonicalPlayAdmissionConfiguration.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/PreV1CanonicalPlayAdmissionConfiguration.java new file mode 100644 index 0000000000..ef34a1ac87 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/PreV1CanonicalPlayAdmissionConfiguration.java @@ -0,0 +1,98 @@ +package net.firedevops.firemud.gamesession.config; + +import java.time.Clock; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.runtime.RuntimeIdentity; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleClient; +import net.firedevops.firemud.gamesession.client.AccountGameplayAdmissionLeaseClient; +import net.firedevops.firemud.gamesession.client.AccountPlayerAdmissionEntitlementClient; +import net.firedevops.firemud.gamesession.client.AccountTenantCapacityClient; +import net.firedevops.firemud.gamesession.data.PreV1CanonicalPlayBootstrapDriver; +import net.firedevops.firemud.gamesession.data.RunOwnedCanonicalLaunchPreparationOwner; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import net.firedevops.firemud.gamesession.repository.PreV1CanonicalPlayAdmissionOwner; +import net.firedevops.firemud.gamesession.repository.PreV1CanonicalPlayStandIns; +import org.jooq.DSLContext; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; + +/** Enables the admission composition only on the run-owned pre-v1 fixture deployment. */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnExpression( + "${firemud.game-session.canonical-play.pre-v1.enabled:false}" + + " and ${firemud.pre-v1.gate-waivers.enabled:false}" + + " and ${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:false}") +public class PreV1CanonicalPlayAdmissionConfiguration { + @Bean(initMethod = "init", destroyMethod = "close") + AccountGameplayAdmissionLeaseClient preV1PlayAccountLeaseClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tls, + GrpcChannelFactory channels, + @Value("${firemud.grpc.workload-namespace:}") String namespace) { + return new AccountGameplayAdmissionLeaseClient(endpoints, tls, channels, namespace); + } + + @Bean(initMethod = "init", destroyMethod = "close") + AccountPlayerAdmissionEntitlementClient preV1PlayAccountEntitlements( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tls, + GrpcChannelFactory channels, + @Value("${firemud.grpc.workload-namespace:}") String namespace) { + return new AccountPlayerAdmissionEntitlementClient( + endpoints, tls, channels, namespace, Clock.systemUTC()); + } + + @Bean(initMethod = "init", destroyMethod = "close") + AccountTenantCapacityClient preV1PlayAccountCapacity( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tls, + GrpcChannelFactory channels, + @Value("${firemud.grpc.workload-namespace:}") String namespace) { + return new AccountTenantCapacityClient(endpoints, tls, channels, namespace, Clock.systemUTC()); + } + + @Bean + PreV1CanonicalPlayAdmissionOwner preV1CanonicalPlayAdmissionOwner( + Environment environment, + DSLContext dsl, + PreV1CanonicalPlayStandIns standIns, + @Value("${firemud.game-session.initial-gameplay-login.protected-sources.coordination.uri:}") + String redisUri, + @Value( + "${firemud.game-session.initial-gameplay-login.protected-sources.coordination.command-timeout-millis:0}") + int redisTimeout, + CanonicalGameInstanceLaunchAssociationRepository launches, + @Qualifier("canonicalAdmissionWorldLifecycleClient") + WorldCanonicalInstanceLifecycleClient world, + RuntimeIdentity runtimeIdentity, + RunOwnedCanonicalLaunchPreparationOwner fixture, + PreV1CanonicalPlayBootstrapDriver bootstrap, + AccountPlayerAdmissionEntitlementClient entitlements, + AccountGameplayAdmissionLeaseClient leases, + AccountTenantCapacityClient capacity, + AccountPublicJwksCache jwks) { + PreV1CanonicalPlayConfiguration.requireWaivers(environment); + return new PreV1CanonicalPlayAdmissionOwner( + dsl, + standIns, + InitialGameplayLoginProtectedSourcesConfiguration.requiredCoordinationUri( + redisUri, redisTimeout, true), + launches, + world, + runtimeIdentity, + fixture, + bootstrap, + entitlements, + leases, + capacity, + jwks, + Clock.systemUTC()); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/PreV1CanonicalPlayReadbackConfiguration.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/PreV1CanonicalPlayReadbackConfiguration.java new file mode 100644 index 0000000000..9b6981a6f0 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/PreV1CanonicalPlayReadbackConfiguration.java @@ -0,0 +1,120 @@ +package net.firedevops.firemud.gamesession.config; + +import io.grpc.BindableService; +import io.grpc.Metadata; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.lettuce.core.RedisClient; +import java.time.Clock; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.gamesession.data.RunOwnedCanonicalLaunchPreparationOwner; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayOriginalNewCapacityExecutionOwner; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayOriginalNewFinalAdmissionReadRepository; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayTenantGameplayTagRepository; +import net.firedevops.firemud.gamesession.repository.PreV1CanonicalPlayManualFactory; +import net.firedevops.firemud.gamesession.repository.PreV1CanonicalPlayStandIns; +import net.firedevops.firemud.gamesession.security.CanonicalGameplayOriginalNewCapacityExecutionReadWorkloadGuard; +import net.firedevops.firemud.gamesession.security.CanonicalGameplayOriginalNewFinalAdmissionReadWorkloadGuard; +import net.firedevops.firemud.gamesession.service.impl.CanonicalGameplayOriginalNewCapacityExecutionReadGrpcService; +import net.firedevops.firemud.gamesession.service.impl.CanonicalGameplayOriginalNewFinalAdmissionReadGrpcService; +import org.jooq.DSLContext; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; + +/** Account-only original NEW readbacks for the default-off, run-owned pre-v1 PLAY fixture. */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnExpression( + "${firemud.game-session.canonical-play.pre-v1.enabled:false}" + + " and ${firemud.pre-v1.gate-waivers.enabled:false}") +@ConditionalOnProperty( + name = "FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED", + havingValue = "true") +public class PreV1CanonicalPlayReadbackConfiguration { + + @Bean + BindableService preV1CanonicalPlayFinalAdmissionReadReceiver( + Environment environment, + DSLContext dsl, + @Qualifier("preV1CanonicalPlayCoordinationRedis") RedisClient coordination, + RunOwnedCanonicalLaunchPreparationOwner fixture, + @Value("${firemud.grpc.workload-namespace:}") String namespace) { + PreV1CanonicalPlayConfiguration.requireWaivers(environment); + var tags = + new CanonicalGameplayTenantGameplayTagRepository( + dsl, namespace, PreV1CanonicalPlayStandIns.TAG_ALLOCATION_VERSION); + var guard = new CanonicalGameplayOriginalNewFinalAdmissionReadWorkloadGuard(namespace); + var receiver = + new CanonicalGameplayOriginalNewFinalAdmissionReadGrpcService( + new CanonicalGameplayOriginalNewFinalAdmissionReadRepository( + dsl, coordination, tags, namespace, Clock.systemUTC()), + guard, + namespace); + return () -> + ServerInterceptors.interceptForward( + receiver, + new GrpcPeerIdentityInterceptor(), + guard, + fixtureCapabilityGuard(environment, fixture)); + } + + @Bean + BindableService preV1CanonicalPlayCapacityExecutionReadReceiver( + Environment environment, + DSLContext dsl, + @Qualifier("preV1CanonicalPlayCoordinationRedis") RedisClient coordination, + RunOwnedCanonicalLaunchPreparationOwner fixture, + @Value("${firemud.grpc.workload-namespace:}") String namespace) { + PreV1CanonicalPlayConfiguration.requireWaivers(environment); + var tags = + new CanonicalGameplayTenantGameplayTagRepository( + dsl, namespace, PreV1CanonicalPlayStandIns.TAG_ALLOCATION_VERSION); + var guard = new CanonicalGameplayOriginalNewCapacityExecutionReadWorkloadGuard(namespace); + var receiver = + new CanonicalGameplayOriginalNewCapacityExecutionReadGrpcService( + new CanonicalGameplayOriginalNewCapacityExecutionOwner( + dsl, + coordination, + PreV1CanonicalPlayManualFactory.mergedScriptCatalog(), + Clock.systemUTC(), + tags), + guard, + namespace); + return () -> + ServerInterceptors.interceptForward( + receiver, + new GrpcPeerIdentityInterceptor(), + guard, + fixtureCapabilityGuard(environment, fixture)); + } + + /** + * Checks fixed capability/receipt custody only after the exact Account peer has authenticated. + */ + private static ServerInterceptor fixtureCapabilityGuard( + Environment environment, RunOwnedCanonicalLaunchPreparationOwner fixture) { + return new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + try { + PreV1CanonicalPlayConfiguration.requireWaivers(environment); + fixture.loadFixedVerifiedEvidence().requireVerifiedFixture(); + } catch (RuntimeException unavailable) { + call.close( + Status.UNAVAILABLE.withDescription("Run-owned canonical PLAY fixture is unavailable"), + new Metadata()); + return new ServerCall.Listener<>() {}; + } + return next.startCall(call, headers); + } + }; + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalPlayableTarget.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalPlayableTarget.java index 38a3259ec3..026960144a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalPlayableTarget.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalPlayableTarget.java @@ -5,6 +5,7 @@ import java.util.Objects; import java.util.UUID; import java.util.regex.Pattern; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof.Outcome; import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest.OriginKind; @@ -48,6 +49,44 @@ public record CanonicalPlayableTarget( Instant ownerProofTerminalAt, String characterCreationPolicy) implements Serializable { + public CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target admissionDecisionTarget() { + return new CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target( + targetNamespace(), + tenantSlug(), + canonicalTenantId(), + worldSlug(), + worldDisplayName(), + realmId(), + realmSlug(), + realmDisplayName(), + gameSessionTenantId(), + gameInstanceId(), + playableStateNamespaceId(), + playableStateScope(), + canonicalGameInstanceId(), + canonicalVersionId(), + runtimeVersionId(), + catalogRevision(), + pointerVersion(), + admissionPointerSnapshotDigest(), + activeWorldEpoch(), + initialAdmissionRequestId(), + initialAdmissionRequestDigest(), + CanonicalGameplayAdmissionDecisionReadGrpcCodec.OriginKind.valueOf( + initialAdmissionOriginKind().name()), + expectedPriorPointerVersion(), + holdId(), + holdFence(), + holdBindingDigest(), + auditEventId(), + ownerProofDigest(), + CanonicalGameplayAdmissionDecisionReadGrpcCodec.OwnerProofOutcome.valueOf( + ownerProofOutcome().name()), + positiveDurableAbort(), + ownerProofTerminalAt(), + characterCreationPolicy()); + } + private static final long serialVersionUID = 1L; private static final UUID NIL_UUID = new UUID(0L, 0L); private static final Pattern REQUEST_DIGEST = Pattern.compile("[0-9a-f]{64}"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/CanonicalGameplayRegionRuntimeStatus.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/CanonicalGameplayRegionRuntimeStatus.java index 101b7b331d..2dd3ded6c9 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/CanonicalGameplayRegionRuntimeStatus.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/CanonicalGameplayRegionRuntimeStatus.java @@ -6,7 +6,10 @@ import java.util.UUID; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; -/** Durable owner row for one exact canonical tenant, game-instance, and operational region. */ +/** + * Durable owner row for one exact canonical tenant, game-instance, and operational region. A + * run-owned fixture row (pre-v1 gate waiver) has neither a capture id nor a graph digest. + */ public record CanonicalGameplayRegionRuntimeStatus( UUID tenantId, UUID gameInstanceId, @@ -43,13 +46,16 @@ public record CanonicalGameplayRegionRuntimeStatus( + regionId.toString().replace("-", ""))) { throw new IllegalArgumentException("tenantRegionTag must derive from the exact owner scope"); } - requireId(captureId, "captureId"); + if ((captureId == null) != (graphSha256 == null)) { + throw new IllegalArgumentException("captureId and graphSha256 are both present or absent"); + } + if (captureId != null) requireId(captureId, "captureId"); Objects.requireNonNull(lifecycleRequest, "lifecycleRequest"); if (!tenantId.equals(lifecycleRequest.canonicalTenantId()) || !gameInstanceId.equals(lifecycleRequest.canonicalGameInstanceId())) { throw new IllegalArgumentException("lifecycleRequest belongs to another runtime target"); } - requireDigest(graphSha256, "graphSha256"); + if (graphSha256 != null) requireDigest(graphSha256, "graphSha256"); requirePrefixedDigest(preparationInputDigest, "preparationInputDigest"); requirePositive(regionEpoch, "regionEpoch"); Objects.requireNonNull(executorFence, "executorFence"); @@ -68,6 +74,11 @@ public record CanonicalGameplayRegionRuntimeStatus( Objects.requireNonNull(updatedAt, "updatedAt"); } + /** True for a run-owned fixture World source, which has no capture or graph. */ + public boolean runOwnedFixture() { + return captureId == null; + } + private static void requireId(UUID value, String name) { Objects.requireNonNull(value, name); if (value.equals(new UUID(0L, 0L))) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java index c5fe0b4aac..943f23ad89 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java @@ -1631,8 +1631,11 @@ private CanonicalGameplayBindingRegionBridgeObligation writePreparedBridge( inputs.canonicalRegionId(), inputs.lifecycleEpoch(), inputs.lifecycleRowVersion(), - inputs.captureId(), - inputs.graphSha256(), + CanonicalGameplayRegionRuntimeStatusRepository.captureParam(inputs.captureId()), + CanonicalGameplayRegionRuntimeStatusRepository.graphParam(inputs.graphSha256()), + inputs.captureId() == null + ? CanonicalGameplayRegionRuntimeStatusRepository.RUN_OWNED_FIXTURE_SOURCE_KIND + : CanonicalGameplayRegionRuntimeStatusRepository.HUMAN_CAPTURE_SOURCE_KIND, inputs.preparationInputDigest(), decimal(ownerStatus.executorFence()), ownerStatus.leaseTokenCorrelation(), @@ -1650,7 +1653,7 @@ private CanonicalGameplayBindingRegionBridgeObligation writePreparedBridge( + " assignment_intent_digest = ?, entity_created_origin = CAST(? AS jsonb), entity_reference_digest = ?," + " world_source_digest = ?, canonical_region_id = ?," + " world_lifecycle_epoch = ?, world_lifecycle_row_version = ?," - + " world_capture_id = ?, world_graph_sha256 = ?," + + " world_capture_id = ?, world_graph_sha256 = ?, world_source_kind = ?," + " world_preparation_input_digest = ?, executor_fence = ?," + " lease_token_correlation = ?, inventory_revision = ?" + " WHERE transition_id = ? AND " @@ -1855,8 +1858,8 @@ private static boolean matchesPreparedOperation( && obligation.canonicalRegionId().equals(inputs.canonicalRegionId()) && obligation.worldLifecycleEpoch() == inputs.lifecycleEpoch() && obligation.worldLifecycleRowVersion() == inputs.lifecycleRowVersion() - && obligation.worldCaptureId().equals(inputs.captureId()) - && obligation.worldGraphSha256().equals(inputs.graphSha256()) + && Objects.equals(obligation.worldCaptureId(), inputs.captureId()) + && Objects.equals(obligation.worldGraphSha256(), inputs.graphSha256()) && obligation.worldPreparationInputDigest().equals(inputs.preparationInputDigest()); } @@ -1924,8 +1927,8 @@ private static BridgeInputs requireBridgeInputs( || !identity.gameInstanceId().equals(ownerStatus.gameInstanceId()) || !resolvedRegion.canonicalRegionInstanceId().equals(ownerStatus.canonicalRegionId()) || !resolvedRegion.operationalRegionId().equals(ownerStatus.regionId()) - || !assignment.captureId().equals(ownerStatus.captureId()) - || !assignment.graphSha256().equals(ownerStatus.graphSha256()) + || !Objects.equals(assignment.captureId(), ownerStatus.captureId()) + || !Objects.equals(assignment.graphSha256(), ownerStatus.graphSha256()) || !assignment.preparationInputDigest().equals(ownerStatus.preparationInputDigest()) || !CanonicalGameplayRegionRuntimeStatusRepository.sameLifecycleRequestExceptReadRequestId( assignment.request(), ownerStatus.lifecycleRequest()) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionReadRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionReadRepository.java index fead34a11f..7fb3cc5ccf 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionReadRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionReadRepository.java @@ -719,6 +719,20 @@ private static void requireIssuerObligation( } } + /** Human capture source, or the run-owned fixture's (pre-v1 gate waiver) absent capture. */ + private static boolean completeWorldSource(Record row) { + String kind = requiredText(row, "world_source_kind"); + UUID capture = row.get("world_capture_id", UUID.class); + String graph = row.get("world_graph_sha256", String.class); + if (CanonicalGameplayRegionRuntimeStatusRepository.RUN_OWNED_FIXTURE_SOURCE_KIND.equals(kind)) { + return capture == null && graph == null; + } + return CanonicalGameplayRegionRuntimeStatusRepository.HUMAN_CAPTURE_SOURCE_KIND.equals(kind) + && capture != null + && graph != null + && SHA256.matcher(graph).matches(); + } + private static void requireRegionAcknowledgement( Record row, CanonicalGameplayOriginalNewCandidate candidate, Record transition) { if (row == null @@ -751,9 +765,8 @@ private static void requireRegionAcknowledgement( || !SHA256.matcher(requiredText(row, "entity_reference_digest")).matches() || !SHA256.matcher(requiredText(row, "world_source_digest")).matches() || !PREFIXED_SHA256.matcher(requiredText(row, "world_preparation_input_digest")).matches() - || !SHA256.matcher(requiredText(row, "world_graph_sha256")).matches() + || !completeWorldSource(row) || requiredUuid(row, "canonical_region_id").equals(new UUID(0L, 0L)) - || row.get("world_capture_id", UUID.class) == null || decimal(row, "world_lifecycle_epoch").signum() <= 0 || decimal(row, "world_lifecycle_row_version").signum() < 0 || decimal(row, "inventory_revision").signum() <= 0 diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeOwner.java index 450bb1b78b..fc08fff06b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeOwner.java @@ -34,9 +34,19 @@ public T run(SqlPhase phase, Supplier action) { } }; + /** + * Package-private actor port. Production reads Entity's exact original actor reference; the + * pre-v1 run-owned fixture stand-in (ADR 0185 waiver) supplies its deterministic actor instead. + * Every read is repeated and compared around each bridge phase. + */ + @FunctionalInterface + interface ActorSource { + CanonicalGameplayRuntimeActorReference read( + net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest request); + } + private final CanonicalGameplayRegionLeaseOwner regionLeaseOwner; - private final CanonicalPreseededActorRuntimeReferenceClient entityReferenceClient; - private final CanonicalPlayerCreatedRuntimeReferenceClient createdReferenceClient; + private final ActorSource actorSource; CanonicalGameplayRegionBindingBridgeOwner( CanonicalGameplayRegionLeaseOwner regionLeaseOwner, @@ -48,10 +58,20 @@ public T run(SqlPhase phase, Supplier action) { CanonicalGameplayRegionLeaseOwner regionLeaseOwner, CanonicalPreseededActorRuntimeReferenceClient entityReferenceClient, CanonicalPlayerCreatedRuntimeReferenceClient createdReferenceClient) { + this(regionLeaseOwner, entityActorSource(entityReferenceClient, createdReferenceClient)); + } + + CanonicalGameplayRegionBindingBridgeOwner( + CanonicalGameplayRegionLeaseOwner regionLeaseOwner, ActorSource actorSource) { this.regionLeaseOwner = Objects.requireNonNull(regionLeaseOwner, "regionLeaseOwner"); - this.entityReferenceClient = - Objects.requireNonNull(entityReferenceClient, "entityReferenceClient"); - this.createdReferenceClient = createdReferenceClient; + this.actorSource = Objects.requireNonNull(actorSource, "actorSource"); + } + + private static ActorSource entityActorSource( + CanonicalPreseededActorRuntimeReferenceClient entityReferenceClient, + CanonicalPlayerCreatedRuntimeReferenceClient createdReferenceClient) { + Objects.requireNonNull(entityReferenceClient, "entityReferenceClient"); + return request -> readEntityReference(entityReferenceClient, createdReferenceClient, request); } /** Acquires the real region grant/fence, then performs the selected first-NEW bridge. */ @@ -187,6 +207,15 @@ CanonicalGameplayBindingInventoryRepository.RegionBridgeAcknowledgement bridge( private CanonicalGameplayRuntimeActorReference readReference( net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest request) { + CanonicalGameplayRuntimeActorReference reference = actorSource.read(request); + if (reference == null) throw unavailable(); + return reference; + } + + private static CanonicalGameplayRuntimeActorReference readEntityReference( + CanonicalPreseededActorRuntimeReferenceClient entityReferenceClient, + CanonicalPlayerCreatedRuntimeReferenceClient createdReferenceClient, + net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest request) { var origin = CanonicalGameplayActorOrigins.fromWorldRequest(request); if (origin instanceof CanonicalGameplayRuntimeActorReference.CreationOrigin) { if (createdReferenceClient == null) throw unavailable(); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeOwnerFactory.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeOwnerFactory.java index 56b361ef55..e183441650 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeOwnerFactory.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeOwnerFactory.java @@ -68,4 +68,32 @@ static CanonicalGameplayRegionBindingBridgeOwner compose( entityReferenceClient, createdReferenceClient); } + + /** + * Same composition over explicit placement and actor ports (pre-v1 run-owned fixture stand-ins). + */ + static CanonicalGameplayRegionBindingBridgeOwner compose( + DSLContext dsl, + RedisClient coordinationRedis, + RedisURI coordinationUri, + RedisScriptCatalog scriptCatalog, + CanonicalGameplayRegionIncarnationSource incarnationSource, + CanonicalGameplayRegionLeaseOwner.PlacementSource placementSource, + CanonicalGameplayRegionBindingBridgeOwner.ActorSource actorSource, + RuntimeIdentity runtimeIdentity, + Duration leaseTtl, + Clock clock) { + return new CanonicalGameplayRegionBindingBridgeOwner( + CanonicalGameplayRegionLeaseOwnerFactory.compose( + dsl, + coordinationRedis, + coordinationUri, + scriptCatalog, + incarnationSource, + placementSource, + runtimeIdentity, + leaseTtl, + clock), + Objects.requireNonNull(actorSource, "actorSource")); + } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeProofs.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeProofs.java index 08db1ca81e..e48cdb35e6 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeProofs.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeProofs.java @@ -13,6 +13,10 @@ /** Closed digest projections for exact bridge sources and independently observed readback. */ final class CanonicalGameplayRegionBindingBridgeProofs { + private static final byte[] FIXTURE_SOURCE_KIND_BYTES = + CanonicalGameplayRegionRuntimeStatusRepository.RUN_OWNED_FIXTURE_SOURCE_KIND.getBytes( + StandardCharsets.US_ASCII); + private CanonicalGameplayRegionBindingBridgeProofs() {} static String entityReferenceDigest(CanonicalGameplayRuntimeActorReference reference) { @@ -34,8 +38,8 @@ static String worldSourceDigest( Long.toString(assignment.lifecycleRowVersion()).getBytes(StandardCharsets.US_ASCII), assignment.canonicalRegionId().toString().getBytes(StandardCharsets.US_ASCII), assignment.operationalRegionId().toString().getBytes(StandardCharsets.US_ASCII), - assignment.captureId().toString().getBytes(StandardCharsets.US_ASCII), - assignment.graphSha256().getBytes(StandardCharsets.US_ASCII), + captureBytes(assignment.captureId()), + graphBytes(assignment.graphSha256()), assignment.preparationInputDigest().getBytes(StandardCharsets.US_ASCII)); } @@ -70,8 +74,8 @@ static String timelinePreparationDigest( source.lifecycleRequest().canonicalBytes(), Long.toString(source.lifecycleEpoch()).getBytes(StandardCharsets.US_ASCII), Long.toString(source.lifecycleRowVersion()).getBytes(StandardCharsets.US_ASCII), - source.captureId().toString().getBytes(StandardCharsets.US_ASCII), - source.graphSha256().getBytes(StandardCharsets.US_ASCII), + captureBytes(source.captureId()), + graphBytes(source.graphSha256()), source.preparationInputDigest().getBytes(StandardCharsets.US_ASCII), worldDigest.getBytes(StandardCharsets.US_ASCII), incarnation.scopeBytes(), @@ -94,6 +98,23 @@ static String initialMetaDigest(String tag, UUID operationId, String sourceDiges tag.getBytes(StandardCharsets.US_ASCII), baseline.getBytes(StandardCharsets.US_ASCII)); } + /** + * Human capture bytes are unchanged. A run-owned fixture source (pre-v1 gate waiver) has no + * capture or graph; its framed slot holds the fixture source kind, which no UUID or hex digest + * can equal. + */ + private static byte[] captureBytes(UUID captureId) { + return captureId == null + ? FIXTURE_SOURCE_KIND_BYTES + : captureId.toString().getBytes(StandardCharsets.US_ASCII); + } + + private static byte[] graphBytes(String graphSha256) { + return graphSha256 == null + ? FIXTURE_SOURCE_KIND_BYTES + : graphSha256.getBytes(StandardCharsets.US_ASCII); + } + private static byte[] uuid(UUID value) { return value.toString().getBytes(StandardCharsets.US_ASCII); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java index 346eea7955..1d3b6d8032 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java @@ -31,11 +31,28 @@ * first-NEW session-binding bridge. */ final class CanonicalGameplayRegionLeaseOwner { + /** + * Package-private placement port. Production reads World's authenticated initial placement; the + * pre-v1 run-owned fixture stand-in (ADR 0185 waiver) supplies its fixture lifecycle and start + * room instead. Either result is still revalidated at every binding gate. + */ + @FunctionalInterface + interface PlacementSource { + CanonicalInitialPlayerLocationRegionResolver.ResolvedRegion resolve( + CanonicalInitialPlayerLocationRequest request, Deadline operationDeadline); + + static PlacementSource world(CanonicalInitialPlayerLocationRegionResolver resolver) { + Objects.requireNonNull(resolver, "worldRegionResolver"); + return (request, deadline) -> + deadline == null ? resolver.resolve(request) : resolver.resolve(request, deadline); + } + } + private final CanonicalGameplayBindingInventoryRepository bindingInventory; private final CanonicalGameplayRegionRuntimeStatusRepository statusRepository; private final CanonicalGameplayRegionLeaseRedisOwner redisOwner; private final CanonicalGameplayRegionIncarnationSource incarnationSource; - private final CanonicalInitialPlayerLocationRegionResolver worldRegionResolver; + private final PlacementSource placementSource; private final RuntimeIdentity runtimeIdentity; private final Duration leaseTtl; private final Clock clock; @@ -49,11 +66,31 @@ final class CanonicalGameplayRegionLeaseOwner { RuntimeIdentity runtimeIdentity, Duration leaseTtl, Clock clock) { + this( + bindingInventory, + statusRepository, + redisOwner, + incarnationSource, + PlacementSource.world(worldRegionResolver), + runtimeIdentity, + leaseTtl, + clock); + } + + CanonicalGameplayRegionLeaseOwner( + CanonicalGameplayBindingInventoryRepository bindingInventory, + CanonicalGameplayRegionRuntimeStatusRepository statusRepository, + CanonicalGameplayRegionLeaseRedisOwner redisOwner, + CanonicalGameplayRegionIncarnationSource incarnationSource, + PlacementSource placementSource, + RuntimeIdentity runtimeIdentity, + Duration leaseTtl, + Clock clock) { this.bindingInventory = Objects.requireNonNull(bindingInventory, "bindingInventory"); this.statusRepository = Objects.requireNonNull(statusRepository, "statusRepository"); this.redisOwner = Objects.requireNonNull(redisOwner, "redisOwner"); this.incarnationSource = Objects.requireNonNull(incarnationSource, "incarnationSource"); - this.worldRegionResolver = Objects.requireNonNull(worldRegionResolver, "worldRegionResolver"); + this.placementSource = Objects.requireNonNull(placementSource, "placementSource"); this.runtimeIdentity = Objects.requireNonNull(runtimeIdentity, "runtimeIdentity"); this.leaseTtl = Objects.requireNonNull(leaseTtl, "leaseTtl"); if (leaseTtl.isZero() || leaseTtl.isNegative()) { @@ -1038,8 +1075,8 @@ private static void requireFinalAcknowledgementWorldCurrent( || !acknowledgement.canonicalRegionId().equals(source.canonicalRegionId()) || acknowledgement.worldLifecycleEpoch() != source.lifecycleEpoch() || acknowledgement.worldLifecycleRowVersion() != source.lifecycleRowVersion() - || !acknowledgement.worldCaptureId().equals(source.captureId()) - || !acknowledgement.worldGraphSha256().equals(source.graphSha256()) + || !Objects.equals(acknowledgement.worldCaptureId(), source.captureId()) + || !Objects.equals(acknowledgement.worldGraphSha256(), source.graphSha256()) || !acknowledgement.worldPreparationInputDigest().equals(source.preparationInputDigest()) || !acknowledgement.worldSourceDigest().equals(worldSourceDigest) || !acknowledgement.regionEpoch().equals(BigInteger.valueOf(status.regionEpoch())) @@ -1326,9 +1363,8 @@ private ResolvedBridgeSource resolveExactBridgeSource( } CanonicalInitialPlayerLocationRegionResolver.ResolvedRegion resolved = - operationDeadline == null - ? worldRegionResolver.resolve(request) - : worldRegionResolver.resolve(request, operationDeadline); + placementSource.resolve(request, operationDeadline); + if (resolved == null) throw unavailable(); var assignment = resolved.lifecycleAssignment(); if (!identity.tenantId().equals(assignment.request().canonicalTenantId()) || !identity.gameInstanceId().equals(assignment.request().canonicalGameInstanceId()) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerFactory.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerFactory.java index 8394d4fdca..a9ae07573f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerFactory.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerFactory.java @@ -24,6 +24,30 @@ static CanonicalGameplayRegionLeaseOwner compose( RuntimeIdentity runtimeIdentity, Duration leaseTtl, Clock clock) { + return compose( + dsl, + coordinationRedis, + coordinationUri, + scriptCatalog, + incarnationSource, + CanonicalGameplayRegionLeaseOwner.PlacementSource.world( + Objects.requireNonNull(worldRegionResolver, "worldRegionResolver")), + runtimeIdentity, + leaseTtl, + clock); + } + + /** Same composition over an explicit placement port (World, or the pre-v1 fixture stand-in). */ + static CanonicalGameplayRegionLeaseOwner compose( + DSLContext dsl, + RedisClient coordinationRedis, + RedisURI coordinationUri, + RedisScriptCatalog scriptCatalog, + CanonicalGameplayRegionIncarnationSource incarnationSource, + CanonicalGameplayRegionLeaseOwner.PlacementSource placementSource, + RuntimeIdentity runtimeIdentity, + Duration leaseTtl, + Clock clock) { Objects.requireNonNull(dsl, "dsl"); Objects.requireNonNull(coordinationRedis, "coordinationRedis"); Objects.requireNonNull(scriptCatalog, "scriptCatalog"); @@ -34,7 +58,7 @@ static CanonicalGameplayRegionLeaseOwner compose( new CanonicalGameplayRegionLeaseRedisOwner( coordinationRedis, coordinationUri, scriptCatalog), incarnationSource, - Objects.requireNonNull(worldRegionResolver, "worldRegionResolver"), + Objects.requireNonNull(placementSource, "placementSource"), Objects.requireNonNull(runtimeIdentity, "runtimeIdentity"), Objects.requireNonNull(leaseTtl, "leaseTtl"), Objects.requireNonNull(clock, "clock")); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwner.java index e4685dfb51..c0723fae34 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwner.java @@ -817,8 +817,8 @@ private static void requireGrantBackedStatus( || status.lifecycleRowVersion() != grant.source.lifecycleRowVersion() || !CanonicalGameplayRegionRuntimeStatusRepository.sameLifecycleRequestExceptReadRequestId( status.lifecycleRequest(), grant.source.lifecycleRequest()) - || !status.captureId().equals(grant.source.captureId()) - || !status.graphSha256().equals(grant.source.graphSha256()) + || !Objects.equals(status.captureId(), grant.source.captureId()) + || !Objects.equals(status.graphSha256(), grant.source.graphSha256()) || !status.preparationInputDigest().equals(grant.source.preparationInputDigest()) || !status .tenantRegionTag() diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java index 613504930c..2aac687b1e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java @@ -1196,8 +1196,8 @@ static String sourceDigest( || !source.canonicalRegionId().equals(prior.canonicalRegionId()) || source.lifecycleEpoch() != prior.lifecycleEpoch() || source.lifecycleRowVersion() != prior.lifecycleRowVersion() - || !source.captureId().equals(prior.captureId()) - || !source.graphSha256().equals(prior.graphSha256()) + || !Objects.equals(source.captureId(), prior.captureId()) + || !Objects.equals(source.graphSha256(), prior.graphSha256()) || !source.preparationInputDigest().equals(prior.preparationInputDigest()) || !CanonicalGameplayRegionRuntimeStatusRepository.sameLifecycleRequestExceptReadRequestId( source.lifecycleRequest(), prior.lifecycleRequest())) throw unavailable(); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepository.java index 2dc3026521..b20d1e6e17 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepository.java @@ -29,6 +29,8 @@ final class CanonicalGameplayRegionRuntimeStatusRepository { private static final String TABLE = "game_session_region_runtime_status"; private static final String PREPARATION_TABLE = "game_session_region_timeline_preparation"; private static final String FENCE_SEQUENCE = "game_session_region_executor_fence_seq"; + static final String HUMAN_CAPTURE_SOURCE_KIND = "HUMAN_CAPTURE"; + static final String RUN_OWNED_FIXTURE_SOURCE_KIND = "RUN_OWNED_FIXTURE"; private final DSLContext dsl; CanonicalGameplayRegionRuntimeStatusRepository(DSLContext dsl) { @@ -127,8 +129,9 @@ TimelinePreparation prepareInitialTimeline( + " stable_incarnation_source_bytes, stable_incarnation_qualification_bytes," + " stable_incarnation_digest," + " timeline_preimage_state, timeline_absence_proof_digest, region_epoch," - + " last_committed_tick_id, phase, created_at, updated_at, entity_created_origin)" - + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'ABSENT', ?, 1, -1, 'PREPARED', ?, ?, CAST(? AS jsonb))", + + " last_committed_tick_id, phase, created_at, updated_at, entity_created_origin," + + " world_source_kind)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'ABSENT', ?, 1, -1, 'PREPARED', ?, ?, CAST(? AS jsonb), ?)", operationId, evidence.transition().transitionId(), evidence.candidate().identity().accountId(), @@ -146,9 +149,9 @@ TimelinePreparation prepareInitialTimeline( inputs.tenantRegionTag(), source.lifecycleEpoch(), source.lifecycleRowVersion(), - source.captureId(), + captureParam(source.captureId()), source.lifecycleRequest().canonicalBytes(), - source.graphSha256(), + graphParam(source.graphSha256()), source.preparationInputDigest(), CanonicalGameplayActorOrigins.assignmentId(inputs.actorOrigin()), CanonicalGameplayActorOrigins.assignmentDigest(inputs.actorOrigin()), @@ -161,7 +164,8 @@ TimelinePreparation prepareInitialTimeline( inputs.absenceProofDigest(), java.sql.Timestamp.from(now), java.sql.Timestamp.from(now), - CanonicalGameplayActorOrigins.creationJson(inputs.actorOrigin())); + CanonicalGameplayActorOrigins.creationJson(inputs.actorOrigin()), + source.worldSourceKind()); Record inserted = transaction.fetchOne( "SELECT * FROM " + PREPARATION_TABLE + " WHERE transition_id = ?", @@ -504,8 +508,8 @@ private static InitialTimelineInputs requireInitialTimelineInputs( || !source.lifecycleRequest().equals(assignment.request()) || source.lifecycleEpoch() != assignment.lifecycleEpoch() || source.lifecycleRowVersion() != assignment.lifecycleRowVersion() - || !source.captureId().equals(assignment.captureId()) - || !source.graphSha256().equals(assignment.graphSha256()) + || !Objects.equals(source.captureId(), assignment.captureId()) + || !Objects.equals(source.graphSha256(), assignment.graphSha256()) || !source.preparationInputDigest().equals(assignment.preparationInputDigest()) || !identity.tenantId().equals(assignment.request().canonicalTenantId()) || !identity.gameInstanceId().equals(assignment.request().canonicalGameInstanceId()) @@ -825,8 +829,8 @@ CanonicalGameplayRegionRuntimeStatus installOwner( + " lifecycle_request_bytes, graph_sha256, preparation_input_digest," + " region_epoch, executor_fence," + " lease_token_correlation, owner_service, owner_instance_id, paused," - + " last_committed_tick_id, updated_at)" - + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?, false, -1, ?)" + + " last_committed_tick_id, updated_at, world_source_kind)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?, false, -1, ?, ?)" + " ON CONFLICT (tenant_id, game_instance_id, region_id) DO NOTHING" + " RETURNING *", source.tenantId(), @@ -836,15 +840,16 @@ CanonicalGameplayRegionRuntimeStatus installOwner( expectedTag, source.lifecycleEpoch(), source.lifecycleRowVersion(), - source.captureId(), + captureParam(source.captureId()), source.lifecycleRequest().canonicalBytes(), - source.graphSha256(), + graphParam(source.graphSha256()), source.preparationInputDigest(), fence, leaseTokenCorrelation, ownerService, ownerInstanceId, - localDateTime(now)); + localDateTime(now), + source.worldSourceKind()); } else { installed = transaction.fetchOne( @@ -855,8 +860,8 @@ CanonicalGameplayRegionRuntimeStatus installOwner( + " WHERE tenant_id = ? AND game_instance_id = ? AND region_id = ?" + " AND tenant_region_tag = ? AND canonical_region_id = ?" + " AND lifecycle_epoch = ? AND lifecycle_row_version = ?" - + " AND capture_id = ? AND lifecycle_request_bytes = ?" - + " AND graph_sha256 = ?" + + " AND capture_id IS NOT DISTINCT FROM ? AND lifecycle_request_bytes = ?" + + " AND graph_sha256 IS NOT DISTINCT FROM ?" + " AND preparation_input_digest = ? AND region_epoch = ?" + " AND executor_fence = ? AND lease_token_correlation = ?" + " AND owner_service = ? AND owner_instance_id = ? AND paused = ?" @@ -875,9 +880,9 @@ CanonicalGameplayRegionRuntimeStatus installOwner( current.canonicalRegionId(), current.lifecycleEpoch(), current.lifecycleRowVersion(), - current.captureId(), + captureParam(current.captureId()), current.lifecycleRequest().canonicalBytes(), - current.graphSha256(), + graphParam(current.graphSha256()), current.preparationInputDigest(), current.regionEpoch(), current.executorFence().longValueExact(), @@ -939,8 +944,8 @@ private static boolean matchesSource(CanonicalGameplayRegionRuntimeStatus status && status.lifecycleRowVersion() == source.lifecycleRowVersion() && sameLifecycleRequestExceptReadRequestId( status.lifecycleRequest(), source.lifecycleRequest()) - && status.captureId().equals(source.captureId()) - && status.graphSha256().equals(source.graphSha256()) + && Objects.equals(status.captureId(), source.captureId()) + && Objects.equals(status.graphSha256(), source.graphSha256()) && status.preparationInputDigest().equals(source.preparationInputDigest()); } @@ -953,8 +958,8 @@ static boolean sameRegionSource(Source expected, Source actual) { && expected.lifecycleRowVersion() == actual.lifecycleRowVersion() && sameLifecycleRequestExceptReadRequestId( expected.lifecycleRequest(), actual.lifecycleRequest()) - && expected.captureId().equals(actual.captureId()) - && expected.graphSha256().equals(actual.graphSha256()) + && Objects.equals(expected.captureId(), actual.captureId()) + && Objects.equals(expected.graphSha256(), actual.graphSha256()) && expected.preparationInputDigest().equals(actual.preparationInputDigest()); } @@ -1024,7 +1029,21 @@ private static IllegalStateException unavailable(Throwable cause) { "Canonical Game Session region ownership is unavailable", cause); } - /** Fresh authenticated World assignment supplied by the closed resolver, never caller fields. */ + /** Typed so an absent run-owned fixture capture binds as a SQL NULL uuid. */ + static org.jooq.Param captureParam(UUID captureId) { + return DSL.val(captureId, org.jooq.impl.SQLDataType.UUID); + } + + /** Typed so an absent run-owned fixture graph digest binds as a SQL NULL varchar. */ + static org.jooq.Param graphParam(String graphSha256) { + return DSL.val(graphSha256, org.jooq.impl.SQLDataType.VARCHAR); + } + + /** + * Fresh authenticated World assignment supplied by the closed resolver, never caller fields. A + * run-owned fixture source (pre-v1 gate waiver) has neither a capture id nor a graph digest; its + * lifecycle request carries the fixture provenance digest instead. + */ record Source( UUID tenantId, UUID gameInstanceId, @@ -1041,19 +1060,28 @@ record Source( Objects.requireNonNull(gameInstanceId, "gameInstanceId"); Objects.requireNonNull(canonicalRegionId, "canonicalRegionId"); Objects.requireNonNull(regionId, "regionId"); - Objects.requireNonNull(captureId, "captureId"); Objects.requireNonNull(lifecycleRequest, "lifecycleRequest"); requireNonNil(canonicalRegionId); - requireNonNil(captureId); + if ((captureId == null) != (graphSha256 == null)) throw unavailable(); + if (captureId != null) requireNonNil(captureId); CanonicalGameplayRegionRedisKeys.tenantRegionTag(tenantId, gameInstanceId, regionId); if (!tenantId.equals(lifecycleRequest.canonicalTenantId()) || !gameInstanceId.equals(lifecycleRequest.canonicalGameInstanceId())) { throw unavailable(); } - requireDigest(graphSha256); + if (graphSha256 != null) requireDigest(graphSha256); requirePrefixedDigest(preparationInputDigest); if (lifecycleEpoch <= 0L || lifecycleRowVersion < 0L) throw unavailable(); } + + boolean runOwnedFixture() { + return captureId == null; + } + + /** The persisted World source kind column value. */ + String worldSourceKind() { + return runOwnedFixture() ? RUN_OWNED_FIXTURE_SOURCE_KIND : HUMAN_CAPTURE_SOURCE_KIND; + } } private static void requireNonNil(UUID value) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayAdmissionOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayAdmissionOwner.java new file mode 100644 index 0000000000..5a741149b4 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayAdmissionOwner.java @@ -0,0 +1,317 @@ +package net.firedevops.firemud.gamesession.repository; + +import io.grpc.StatusRuntimeException; +import io.lettuce.core.RedisURI; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Duration; +import java.util.Arrays; +import java.util.UUID; +import java.util.function.BooleanSupplier; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Candidate; +import net.firedevops.firemud.common.runtime.RuntimeIdentity; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleClient; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import net.firedevops.firemud.gamesession.client.AccountGameplayAdmissionLeaseClient; +import net.firedevops.firemud.gamesession.client.AccountPlayerAdmissionEntitlementClient; +import net.firedevops.firemud.gamesession.client.AccountTenantCapacityClient; +import net.firedevops.firemud.gamesession.command.text.ObservedDirectTextTransport; +import net.firedevops.firemud.gamesession.data.PreV1CanonicalPlayBootstrapDriver; +import net.firedevops.firemud.gamesession.data.RunOwnedCanonicalLaunchPreparationOwner; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; +import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyScope; +import org.jooq.DSLContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** Composes ordinary NEW admission for the verified run-owned fixture. */ +public final class PreV1CanonicalPlayAdmissionOwner { + private static final Logger LOG = LoggerFactory.getLogger(PreV1CanonicalPlayAdmissionOwner.class); + private static final Duration SESSION_DURATION = Duration.ofMinutes(2); + + private final DSLContext dsl; + private final PreV1CanonicalPlayStandIns standIns; + private final PreV1RunOwnedFixturePlayRegion regions; + private final RunOwnedCanonicalLaunchPreparationOwner fixture; + private final PreV1CanonicalPlayBootstrapDriver bootstrap; + private final AccountPlayerAdmissionEntitlementClient entitlements; + private final AccountGameplayAdmissionLeaseClient leases; + private final AccountTenantCapacityClient capacity; + private final AccountPublicJwksCache jwks; + private final Clock clock; + + public PreV1CanonicalPlayAdmissionOwner( + DSLContext dsl, + PreV1CanonicalPlayStandIns standIns, + RedisURI coordinationUri, + CanonicalGameInstanceLaunchAssociationRepository launches, + WorldCanonicalInstanceLifecycleClient world, + RuntimeIdentity runtimeIdentity, + RunOwnedCanonicalLaunchPreparationOwner fixture, + PreV1CanonicalPlayBootstrapDriver bootstrap, + AccountPlayerAdmissionEntitlementClient entitlements, + AccountGameplayAdmissionLeaseClient leases, + AccountTenantCapacityClient capacity, + AccountPublicJwksCache jwks, + Clock clock) { + this.dsl = dsl; + this.standIns = standIns; + this.regions = + new PreV1RunOwnedFixturePlayRegion( + dsl, standIns, coordinationUri, launches, world, runtimeIdentity, clock); + this.fixture = fixture; + this.bootstrap = bootstrap; + this.entitlements = entitlements; + this.leases = leases; + this.capacity = capacity; + this.jwks = jwks; + this.clock = clock; + } + + public boolean ready() { + return bootstrap.ready(); + } + + public Admitted play( + DirectTextAuthenticatedLobbyScope scope, + InitialGameplayLoginAttemptCoordinates original, + CanonicalGameplayLoginResult login, + ObservedDirectTextTransport transport, + BooleanSupplier current) { + if (!ready()) throw unavailable(); + CanonicalPlayableTarget target = scope.publicTarget(); + UUID accountId = login.evidence().accountId(); + UUID attempt = UUID.randomUUID(); + requireCurrent(scope, original, login, transport, current); + String phase = "fixture-region"; + try { + fixture.loadFixedVerifiedEvidence().requireVerifiedFixture(); + var region = regions.prepare(target, accountId); + phase = "account-entitlement"; + var entitlement = entitlements.read(scope, original, transport, attempt, login, current); + var capacityEvidence = TenantCapacityAdmission.Evidence.player(entitlement); + if (!entitlement.isRunOwnedFixtureSource() || !capacityEvidence.permitsCreation()) { + throw unavailable(); + } + + phase = "issuer-local-new"; + var identity = + new CanonicalGameplayBindingIdentity( + accountId, + target.canonicalTenantId(), + target.playableStateNamespaceId(), + region.characterId(), + target.playableStateScope(), + target.canonicalGameInstanceId(), + target.gameInstanceId(), + UUID.randomUUID().toString(), + region.operationalRegionId(), + BigInteger.valueOf(region.regionEpoch()), + PreV1CurrentIssuerStateSource.ISSUER, + PreV1CurrentIssuerStateSource.INITIAL_GENERATION, + PreV1CanonicalGameplayStoreBootstrap.LAYOUT_VERSION, + PreV1CanonicalGameplayStoreBootstrap.PARTITION_COUNT, + PreV1CanonicalGameplayStoreBootstrap.PARTITION_CAPACITY); + UUID transitionId = UUID.randomUUID(); + var issuerSource = standIns.issuerState(); + var inventory = new CanonicalGameplayBindingInventoryRepository(dsl); + var operation = + new CanonicalGameplayIssuerBindingLocalOperationRepository(dsl, issuerSource) + .beginOrResumeOrdinaryNew( + new CanonicalGameplayIssuerBindingLocalOperation.Request( + attempt, transitionId, identity, null, null)); + BigInteger generation = operation.preparedTransition().bindingGeneration(); + + phase = "initial-account-barrier"; + var initialRepository = new CanonicalGameplayAccountInitialBarrierInitializerRepository(dsl); + var accountBarrier = + new CanonicalGameplayAccountInitialBarrierRedisOwner( + standIns.coordination(), + standIns.scripts(), + initialRepository, + standIns.tags(), + standIns + .attestor() + .initialBarrierReceiver(initialRepository, standIns.tags(), clock)); + requireCurrent(scope, original, login, transport, current); + if (!(accountBarrier.initializeOnce( + original, login, target.canonicalTenantId(), target.playableStateNamespaceId()) + instanceof CanonicalGameplayAccountInitialOpenProof.CurrentOpen)) { + throw unavailable(); + } + + phase = "account-admission-lease"; + byte[] compact = login.compactJwtBytes(); + try { + String jwt = new String(compact, StandardCharsets.US_ASCII); + requireCurrent(scope, original, login, transport, current); + var lease = + leases + .acquire( + attempt, + jwt, + wireCandidate(identity), + target.admissionDecisionTarget(), + generation) + .originalLeaseEvidence(); + var decision = + new CanonicalGameplayAdmissionDecision( + transitionId, lease, identity, generation, null, target); + + phase = "candidate-and-indexes"; + new CanonicalGameplayOriginalNewCandidateRedisOwner( + standIns.coordination(), standIns.scripts(), inventory, standIns.tags()) + .installOnce(decision); + new CanonicalGameplayAccountMemberRepairOwner( + dsl, standIns.coordination(), standIns.scripts()) + .repair(transitionId); + var projection = + new CanonicalGameplayIssuerBindingLocalRedisOwner( + standIns.coordination(), + standIns.scripts(), + new CanonicalGameplayIssuerBindingLocalProjectionRepository(dsl, issuerSource), + issuerSource) + .projectAndRead(operation); + new CanonicalGameplayIssuerBindingLocalAcknowledgementRepository(dsl, issuerSource) + .acknowledge(projection); + + phase = "region-bridge"; + var bridge = region.bridge(); + var installation = bridge.installForTransition(transitionId, region.request()); + bridge.bridge(installation); + + phase = "account-lease-finalization"; + var capacityRequest = + new TenantCapacityAdmission.Request( + new TenantCapacityAdmission.Identity( + identity.tenantId(), attempt, transitionId), + UUID.randomUUID(), + 1, + target.targetNamespace(), + new TenantCapacityAdmission.PlayerContext( + accountId, + identity.tenantId(), + identity.playableStateNamespaceId(), + identity.gameInstanceId(), + identity.characterId(), + UUID.fromString(identity.sessionId()), + target.realmId(), + attempt, + identity.playableStateScope()), + TenantCapacityAdmission.Operation.CAPACITY_CREATING, + new TenantCapacityAdmission.Shape(0, 0, 0), + new TenantCapacityAdmission.Shape(1, 0, 0), + capacityEvidence, + 1L, + null) + .withDigest(); + byte[] leaseBytes = lease.canonicalJson().getBytes(StandardCharsets.UTF_8); + requireCurrent(scope, original, login, transport, current); + var finalized = leases.finalizeLease(jwt, leaseBytes, transitionId); + if (finalized.state() != AccountGameplayAdmissionLeaseGrpcCodec.State.COMMITTED + || !finalized.originalLeaseEvidence().canonicalJson().equals(lease.canonicalJson())) { + throw unavailable(); + } + + phase = "original-new-final"; + var issuerBarrier = + new CanonicalGameplayIssuerAdmissionBarrierRedisOwner( + standIns.coordination(), + standIns.scripts(), + new CanonicalGameplayIssuerAdmissionBarrierRepository( + dsl, standIns.tags(), issuerSource), + issuerSource); + var coordinator = + new CanonicalGameplayOriginalNewFinalAdmissionCoordinator( + inventory, + leases, + accountBarrier, + issuerBarrier, + bridge, + new CanonicalGameplayOriginalNewBoundCredentialVerifier(jwks, clock), + new CanonicalGameplayOriginalNewFinalAdmissionRedisOwner( + standIns.coordination(), standIns.scripts(), clock, standIns.tags()), + clock, + capacity, + new CanonicalGameplayOriginalNewCapacityExecutionOwner( + dsl, standIns.coordination(), standIns.scripts(), clock, standIns.tags())); + var result = + coordinator.completeOriginalNew( + decision, + jwt, + installation, + SESSION_DURATION.toMillis(), + Math.min( + clock.millis() + 5_000L, decision.leaseExpiresAtEpochMillis().longValueExact()), + capacityRequest); + requireCurrent(scope, original, login, transport, current); + return new Admitted( + target, + identity, + transitionId, + generation, + region.roomKey(), + result.continuityExpiresAtMillis()); + } finally { + Arrays.fill(compact, (byte) 0); + } + } catch (RuntimeException failure) { + StackTraceElement[] trace = failure.getStackTrace(); + LOG.warn( + "Run-owned PLAY unavailable phase={} type={} grpcStatus={} source={}", + phase, + failure.getClass().getSimpleName(), + failure instanceof StatusRuntimeException rpc ? rpc.getStatus().getCode() : null, + trace.length == 0 ? "unknown" : trace[0]); + throw unavailable(); + } + } + + private void requireCurrent( + DirectTextAuthenticatedLobbyScope scope, + InitialGameplayLoginAttemptCoordinates original, + CanonicalGameplayLoginResult login, + ObservedDirectTextTransport transport, + BooleanSupplier current) { + if (!current.getAsBoolean()) throw unavailable(); + scope.requireCurrent(original, login, transport, clock); + } + + private static Candidate wireCandidate(CanonicalGameplayBindingIdentity identity) { + return new Candidate( + identity.accountId(), + identity.tenantId(), + identity.playableStateNamespaceId(), + identity.characterId(), + identity.playableStateScope(), + identity.gameInstanceId(), + identity.runtimeGameInstanceId(), + UUID.fromString(identity.sessionId()), + identity.regionId(), + identity.regionEpoch(), + identity.issuerId(), + identity.issuerAuthGeneration(), + identity.issuerIndexLayoutVersion(), + identity.issuerIndexPartitionCount(), + identity.issuerIndexPartitionCapacity()); + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Run-owned canonical PLAY unavailable"); + } + + public record Admitted( + CanonicalPlayableTarget target, + CanonicalGameplayBindingIdentity binding, + UUID transitionId, + BigInteger bindingGeneration, + String roomKey, + long expiresAtMillis) {} +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayManualFactory.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayManualFactory.java index 52d1593f6d..37b9143b86 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayManualFactory.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayManualFactory.java @@ -75,6 +75,8 @@ public static PreV1CanonicalPlayStandIns create( new PreV1RegionIncarnationSource(observer::redisRunId), new PreV1CanonicalGameplayStoreBootstrap(dsl, coordination, scripts, observer, issuerState), new PreV1CanonicalPlayBudgets( - dsl, new GameSessionCanonicalRealmCatalogRepository(dsl), tags, workloadNamespace)); + dsl, new GameSessionCanonicalRealmCatalogRepository(dsl), tags, workloadNamespace), + waivers, + new PreV1RunOwnedFixtureActorSource(waivers, workloadNamespace)); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayStandIns.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayStandIns.java index 9a12c82147..1a9d771993 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayStandIns.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayStandIns.java @@ -2,13 +2,14 @@ import io.lettuce.core.RedisClient; import java.util.Objects; +import net.firedevops.firemud.common.prev1.PreV1GateWaivers; import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; /** * Pre-v1 gate waiver (ADR 0185) stand-ins for canonical PLAY, composed once per process over the * Game Session Coordination Redis. Public callers get the startup bootstrap and budgets; the issuer - * state source, INITIAL attestor and region incarnation source stay package-private for the PLAY - * composition in this package. + * state source, INITIAL attestor, region incarnation source and the run-owned fixture actor and + * placement stand-ins stay package-private for the PLAY composition in this package. */ public final class PreV1CanonicalPlayStandIns { /** Tenant gameplay tag allocation version shared by every canonical PLAY owner. */ @@ -22,6 +23,8 @@ public final class PreV1CanonicalPlayStandIns { private final PreV1RegionIncarnationSource regionIncarnation; private final PreV1CanonicalGameplayStoreBootstrap storeBootstrap; private final PreV1CanonicalPlayBudgets budgets; + private final PreV1GateWaivers waivers; + private final PreV1RunOwnedFixtureActorSource fixtureActor; PreV1CanonicalPlayStandIns( RedisClient coordination, @@ -31,7 +34,9 @@ public final class PreV1CanonicalPlayStandIns { PreV1LocalIncarnationAttestor attestor, PreV1RegionIncarnationSource regionIncarnation, PreV1CanonicalGameplayStoreBootstrap storeBootstrap, - PreV1CanonicalPlayBudgets budgets) { + PreV1CanonicalPlayBudgets budgets, + PreV1GateWaivers waivers, + PreV1RunOwnedFixtureActorSource fixtureActor) { this.coordination = Objects.requireNonNull(coordination, "coordination"); this.scripts = Objects.requireNonNull(scripts, "scripts"); this.tags = Objects.requireNonNull(tags, "tags"); @@ -40,6 +45,8 @@ public final class PreV1CanonicalPlayStandIns { this.regionIncarnation = Objects.requireNonNull(regionIncarnation, "regionIncarnation"); this.storeBootstrap = Objects.requireNonNull(storeBootstrap, "storeBootstrap"); this.budgets = Objects.requireNonNull(budgets, "budgets"); + this.waivers = Objects.requireNonNull(waivers, "waivers"); + this.fixtureActor = Objects.requireNonNull(fixtureActor, "fixtureActor"); } public PreV1CanonicalGameplayStoreBootstrap storeBootstrap() { @@ -73,4 +80,18 @@ PreV1LocalIncarnationAttestor attestor() { PreV1RegionIncarnationSource regionIncarnation() { return regionIncarnation; } + + PreV1RunOwnedFixtureActorSource fixtureActor() { + return fixtureActor; + } + + /** + * The fixture placement over a fresh World fixture lifecycle read and the World-owned fixture + * start room. + */ + PreV1RunOwnedFixturePlacementSource fixturePlacement( + PreV1RunOwnedFixturePlacementSource.FixtureLifecycleReader lifecycleReader, + String startRoomKey) { + return new PreV1RunOwnedFixturePlacementSource(waivers, lifecycleReader, startRoomKey); + } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1RunOwnedFixtureActorSource.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1RunOwnedFixtureActorSource.java new file mode 100644 index 0000000000..c97931a0f5 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1RunOwnedFixtureActorSource.java @@ -0,0 +1,126 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.nio.ByteBuffer; +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.prev1.PreV1GateWaivers; +import net.firedevops.firemud.entitymanagement.v1.PreseededActorAssignmentExpectedTarget; +import net.firedevops.firemud.gamesession.client.CanonicalGameplayRuntimeActorReference; +import net.firedevops.firemud.gamesession.client.PreV1RunOwnedFixtureActorReference; +import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest; + +/** + * Pre-v1 gate waiver (ADR 0185): the run-owned fixture's actor, standing in for Entity's preseeded + * assignment. Each account gets one deterministic character, {@code characterId = UUIDv5(NAMESPACE, + * accountId)}, with a derived assignment id, intent digest and runtime entity id. Nothing is read + * from Entity; a real fixture assignment is owed before v1. + */ +final class PreV1RunOwnedFixtureActorSource + implements CanonicalGameplayRegionBindingBridgeOwner.ActorSource { + static final UUID NAMESPACE = UUID.fromString("6902fca9-8a6b-4f58-883e-452bf96b4b0f"); + private static final long MAX_RUNTIME_ENTITY_ID = (1L << 53) - 1L; + + private final PreV1GateWaivers waivers; + private final String workloadNamespace; + + PreV1RunOwnedFixtureActorSource(PreV1GateWaivers waivers, String workloadNamespace) { + if (waivers == null || !waivers.enabled()) { + throw new IllegalStateException("Run-owned fixture actor stand-in requires the waivers"); + } + if (workloadNamespace == null || workloadNamespace.isBlank()) { + throw new IllegalArgumentException("Exact Game Session workload namespace required"); + } + this.waivers = waivers; + this.workloadNamespace = workloadNamespace; + } + + /** The deterministic actor identities the PLAY composition puts in its World request. */ + record Identity(UUID characterId, UUID assignmentId, String intentDigest, long runtimeEntityId) {} + + static Identity identity(UUID accountId, PreseededActorAssignmentExpectedTarget target) { + Objects.requireNonNull(accountId, "accountId"); + Objects.requireNonNull(target, "target"); + UUID characterId = characterId(accountId); + UUID assignmentId = uuidV5(NAMESPACE, "assignment|" + accountId); + String intentDigest = + sha256Hex( + "pre-v1-run-owned-fixture-actor-intent/v1".getBytes(StandardCharsets.US_ASCII), + accountId.toString().getBytes(StandardCharsets.US_ASCII), + characterId.toString().getBytes(StandardCharsets.US_ASCII), + target.toByteArray()); + UUID entity = + uuidV5(NAMESPACE, "runtime-entity|" + accountId + "|" + target.getGameInstanceId()); + long runtimeEntityId = + (entity.getMostSignificantBits() ^ entity.getLeastSignificantBits()) + & MAX_RUNTIME_ENTITY_ID; + return new Identity( + characterId, assignmentId, intentDigest, runtimeEntityId == 0L ? 1L : runtimeEntityId); + } + + static UUID characterId(UUID accountId) { + return uuidV5(NAMESPACE, Objects.requireNonNull(accountId, "accountId").toString()); + } + + @Override + public CanonicalGameplayRuntimeActorReference read( + CanonicalInitialPlayerLocationRequest request) { + Objects.requireNonNull(request, "request"); + final Identity expected; + try { + expected = + identity(UUID.fromString(request.getCanonicalAccountUuid()), request.getExpectedTarget()); + } catch (IllegalArgumentException malformed) { + throw unavailable(); + } + if (request.getSchemaVersion() != 1 + || request.hasPlayerCreatedOrigin() + || !request.hasExpectedTarget() + || !expected.characterId().toString().equals(request.getCharacterUuid()) + || !expected.assignmentId().toString().equals(request.getAssignmentUuid()) + || !expected.intentDigest().equals(request.getAssignmentIntentDigest())) { + throw unavailable(); + } + return PreV1RunOwnedFixtureActorReference.standIn( + waivers, workloadNamespace, request, expected.runtimeEntityId()); + } + + static UUID uuidV5(UUID namespace, String name) { + try { + MessageDigest sha1 = MessageDigest.getInstance("SHA-1"); + sha1.update( + ByteBuffer.allocate(16) + .putLong(namespace.getMostSignificantBits()) + .putLong(namespace.getLeastSignificantBits()) + .array()); + byte[] value = sha1.digest(name.getBytes(StandardCharsets.UTF_8)); + value[6] = (byte) ((value[6] & 0x0f) | 0x50); + value[8] = (byte) ((value[8] & 0x3f) | 0x80); + ByteBuffer bytes = ByteBuffer.wrap(value); + return new UUID(bytes.getLong(), bytes.getLong()); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("JVM does not provide SHA-1", impossible); + } + } + + private static String sha256Hex(byte[]... parts) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + for (byte[] part : parts) { + digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(part.length).array()); + digest.update(part); + } + return HexFormat.of().formatHex(digest.digest()); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("JVM does not provide SHA-256", impossible); + } + } + + private static IllegalStateException unavailable() { + return new IllegalStateException( + "Run-owned fixture actor stand-in requires its exact derived World request"); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1RunOwnedFixturePlacementSource.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1RunOwnedFixturePlacementSource.java new file mode 100644 index 0000000000..4a11c24c55 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1RunOwnedFixturePlacementSource.java @@ -0,0 +1,144 @@ +package net.firedevops.firemud.gamesession.repository; + +import com.google.protobuf.ByteString; +import io.grpc.Deadline; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.prev1.PreV1GateWaivers; +import net.firedevops.firemud.common.world.WorldRunOwnedFixtureLifecycleEvidence; +import net.firedevops.firemud.gamesession.service.CanonicalInitialPlayerLocationRegionResolver; +import net.firedevops.firemud.gamesession.service.CanonicalRegionBootstrapAssignmentResolver; +import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationLifecycleConsequence; +import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationOutcome; +import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRegionResponse; +import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest; +import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationResponse; + +/** + * Pre-v1 gate waiver (ADR 0185): the run-owned fixture's initial placement, standing in for World's + * initial-placement owner. It joins World's current ACTIVE fixture lifecycle (read fresh on every + * call through {@link FixtureLifecycleReader}) to the World-owned fixture start room. The fixture + * has one region per game instance; its canonical and operational ids derive from the game instance + * and start room. World places no fixture actor; a real placement is owed before v1. + */ +final class PreV1RunOwnedFixturePlacementSource + implements CanonicalGameplayRegionLeaseOwner.PlacementSource { + static final UUID NAMESPACE = UUID.fromString("d900cc0a-6282-4e8f-9888-2163bc1591f1"); + + /** Fresh authenticated World fixture lifecycle read for one exact World request's target. */ + @FunctionalInterface + interface FixtureLifecycleReader { + WorldRunOwnedFixtureLifecycleEvidence read( + CanonicalInitialPlayerLocationRequest request, Deadline operationDeadline); + } + + private final PreV1GateWaivers waivers; + private final FixtureLifecycleReader lifecycleReader; + private final String startRoomKey; + + PreV1RunOwnedFixturePlacementSource( + PreV1GateWaivers waivers, FixtureLifecycleReader lifecycleReader, String startRoomKey) { + if (waivers == null || !waivers.enabled()) { + throw new IllegalStateException("Run-owned fixture placement stand-in requires the waivers"); + } + if (startRoomKey == null + || startRoomKey.isBlank() + || !startRoomKey.equals(startRoomKey.trim())) { + throw new IllegalArgumentException("World-owned fixture start room required"); + } + this.waivers = waivers; + this.lifecycleReader = Objects.requireNonNull(lifecycleReader, "lifecycleReader"); + this.startRoomKey = startRoomKey; + } + + /** The fixture's single canonical region for one game instance. */ + UUID canonicalRegionId(UUID gameInstanceId) { + return PreV1RunOwnedFixtureActorSource.uuidV5( + NAMESPACE, "canonical-region|" + gameInstanceId + "|" + startRoomKey); + } + + /** The operational region the PLAY composition binds its candidate to. */ + UUID operationalRegionId(UUID tenantId, UUID gameInstanceId) { + return PreV1RunOwnedFixtureActorSource.uuidV5( + NAMESPACE, "operational-region|" + tenantId + "|" + gameInstanceId + "|" + startRoomKey); + } + + String startRoomKey() { + return startRoomKey; + } + + @Override + public CanonicalInitialPlayerLocationRegionResolver.ResolvedRegion resolve( + CanonicalInitialPlayerLocationRequest request, Deadline operationDeadline) { + Objects.requireNonNull(request, "request"); + if (request.getSchemaVersion() != 1 + || request.hasPlayerCreatedOrigin() + || !request.hasExpectedTarget()) { + throw unavailable(); + } + var target = request.getExpectedTarget(); + final UUID tenantId; + final UUID gameInstanceId; + final UUID versionId; + try { + tenantId = UUID.fromString(target.getCanonicalTenantUuid()); + gameInstanceId = UUID.fromString(target.getGameInstanceId()); + versionId = UUID.fromString(target.getCanonicalVersionUuid()); + } catch (IllegalArgumentException malformed) { + throw unavailable(); + } + WorldRunOwnedFixtureLifecycleEvidence lifecycle = + lifecycleReader.read(request, operationDeadline); + if (lifecycle == null + || !"ACTIVE".equals(lifecycle.lifecycleStatus()) + || lifecycle.lifecycleEpoch() != request.getActiveLifecycleEpoch() + || !tenantId.equals(lifecycle.request().canonicalTenantId()) + || !gameInstanceId.equals(lifecycle.request().canonicalGameInstanceId()) + || !versionId.equals(lifecycle.request().canonicalVersionId()) + || !target.getWorldSlug().equals(lifecycle.request().worldSlug())) { + throw unavailable(); + } + UUID canonicalRegionId = canonicalRegionId(gameInstanceId); + UUID operationalRegionId = operationalRegionId(tenantId, gameInstanceId); + var assignment = + CanonicalRegionBootstrapAssignmentResolver.Assignment.preV1RunOwnedFixture( + waivers, lifecycle, canonicalRegionId, operationalRegionId); + var placement = + CanonicalInitialPlayerLocationResponse.newBuilder() + .setSchemaVersion(1) + .setPlacementOperationUuid(request.getPlacementOperationUuid()) + .setCanonicalAccountUuid(request.getCanonicalAccountUuid()) + .setCharacterUuid(request.getCharacterUuid()) + .setAssignmentUuid(request.getAssignmentUuid()) + .setAssignmentIntentDigest(request.getAssignmentIntentDigest()) + .setOutcome( + CanonicalInitialPlayerLocationOutcome + .CANONICAL_INITIAL_PLAYER_LOCATION_OUTCOME_APPLIED) + .setPrivateRuntimeRoomKey(startRoomKey) + .build(); + var observation = + CanonicalInitialPlayerLocationRegionResponse.newBuilder() + .setSchemaVersion(1) + .setPlacementResult(placement) + .setExpectedTarget(target) + .setCanonicalRegionInstanceUuid(canonicalRegionId.toString()) + .setOperationalRegionUuid(operationalRegionId.toString()) + .setLifecycle( + CanonicalInitialPlayerLocationLifecycleConsequence.newBuilder() + .setCanonicalRequestBytes( + ByteString.copyFrom(lifecycle.request().canonicalBytes())) + .setLifecycleStatus(lifecycle.lifecycleStatus()) + .setLifecycleEpoch(lifecycle.lifecycleEpoch()) + .setRowVersion(lifecycle.rowVersion()) + .setPreparationInputDigest(lifecycle.preparationInputDigest()) + .build()) + .build(); + return CanonicalInitialPlayerLocationRegionResolver.ResolvedRegion.preV1RunOwnedFixture( + observation, assignment); + } + + private static IllegalStateException unavailable() { + return new IllegalStateException( + "Run-owned fixture placement requires its exact current ACTIVE fixture lifecycle"); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1RunOwnedFixturePlayRegion.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1RunOwnedFixturePlayRegion.java new file mode 100644 index 0000000000..645c267485 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1RunOwnedFixturePlayRegion.java @@ -0,0 +1,347 @@ +package net.firedevops.firemud.gamesession.repository; + +import io.grpc.Deadline; +import io.lettuce.core.RedisURI; +import java.time.Clock; +import java.time.Duration; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.runtime.RuntimeIdentity; +import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleClient; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldRunOwnedFixtureLifecycleEvidence; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.entitymanagement.v1.PreseededActorAssignmentExpectedTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionLaunchTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayRegionRuntimeStatusRepository.Source; +import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest; +import org.jooq.DSLContext; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Manual pre-v1 run-owned fixture region composition; it grants no authority to other targets. */ +final class PreV1RunOwnedFixturePlayRegion { + private static final Duration REGION_LEASE_TTL = Duration.ofSeconds(30); + + private final DSLContext dsl; + private final PreV1CanonicalPlayStandIns standIns; + private final RedisURI coordinationUri; + private final CanonicalGameInstanceLaunchAssociationRepository launches; + private final WorldCanonicalInstanceLifecycleClient world; + private final RuntimeIdentity runtimeIdentity; + private final Clock clock; + + PreV1RunOwnedFixturePlayRegion( + DSLContext dsl, + PreV1CanonicalPlayStandIns standIns, + RedisURI coordinationUri, + CanonicalGameInstanceLaunchAssociationRepository launches, + WorldCanonicalInstanceLifecycleClient world, + RuntimeIdentity runtimeIdentity, + Clock clock) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.standIns = Objects.requireNonNull(standIns, "standIns"); + this.coordinationUri = Objects.requireNonNull(coordinationUri, "coordinationUri"); + this.launches = Objects.requireNonNull(launches, "launches"); + this.world = Objects.requireNonNull(world, "world"); + this.runtimeIdentity = Objects.requireNonNull(runtimeIdentity, "runtimeIdentity"); + this.clock = Objects.requireNonNull(clock, "clock"); + } + + Prepared prepare(CanonicalPlayableTarget target, UUID accountId) { + Objects.requireNonNull(target, "target"); + requireNonNil(accountId, "accountId"); + requireNoAmbientTransaction(); + + CanonicalInitialAdmissionLaunchTarget launch = readCurrentLaunch(target); + if (!launch.association().isRunOwnedFixture()) throw unavailable(); + + CanonicalRealmCatalogSnapshot catalog = + new GameSessionCanonicalRealmCatalogRepository(dsl) + .readByRealm(target.targetNamespace(), target.canonicalTenantId(), target.realmId()) + .orElseThrow(PreV1RunOwnedFixturePlayRegion::unavailable); + String frozenPolicyDigest = fixturePolicyDigest(target, launch.association(), catalog); + PreseededActorAssignmentExpectedTarget expectedTarget = + expectedTarget(target, launch.association(), frozenPolicyDigest); + PreV1RunOwnedFixtureActorSource.Identity actor = + PreV1RunOwnedFixtureActorSource.identity(accountId, expectedTarget); + CanonicalInitialPlayerLocationRequest request = + worldRequest(target, accountId, actor, expectedTarget); + var lifecycleSelector = lifecycleRequest(target, launch.association(), request); + var startRoom = world.readRunOwnedFixtureStartRoom(lifecycleSelector); + requireCurrentLifecycle(target, launch, lifecycleSelector, startRoom.lifecycle()); + if (!launch.equals(readCurrentLaunch(target))) throw unavailable(); + + PreV1RunOwnedFixturePlacementSource placement = + standIns.fixturePlacement( + (worldRequest, operationDeadline) -> { + var lifecycle = + readCurrentFixtureLifecycle(target, launch, worldRequest, operationDeadline); + if (!startRoom.lifecycle().equals(lifecycle)) throw unavailable(); + return lifecycle; + }, + startRoom.roomKey()); + var resolved = placement.resolve(request, null); + var assignment = resolved.lifecycleAssignment(); + if (!assignment.runOwnedFixture() + || !assignment.request().equals(lifecycleRequest(target, launch.association(), request)) + || !assignment.lifecycleStatus().equals("ACTIVE") + || assignment.lifecycleEpoch() != target.activeWorldEpoch()) { + throw unavailable(); + } + + Source source = + new Source( + target.canonicalTenantId(), + target.canonicalGameInstanceId(), + assignment.canonicalRegionId(), + assignment.operationalRegionId(), + assignment.lifecycleEpoch(), + assignment.lifecycleRowVersion(), + assignment.request(), + assignment.captureId(), + assignment.graphSha256(), + assignment.preparationInputDigest()); + CanonicalGameplayRegionRuntimeStatusRepository statusRepository = + new CanonicalGameplayRegionRuntimeStatusRepository(dsl); + var existing = statusRepository.find(source).orElse(null); + if (existing != null && !existing.runOwnedFixture()) throw unavailable(); + long expectedRegionEpoch = existing == null ? 1L : existing.regionEpoch(); + if (expectedRegionEpoch <= 0L) throw unavailable(); + + CanonicalGameplayRegionBindingBridgeOwner bridge = + CanonicalGameplayRegionBindingBridgeOwnerFactory.compose( + dsl, + standIns.coordination(), + coordinationUri, + standIns.scripts(), + standIns.regionIncarnation(), + placement, + standIns.fixtureActor(), + runtimeIdentity, + REGION_LEASE_TTL, + clock); + return new Prepared( + actor.characterId(), + assignment.operationalRegionId(), + expectedRegionEpoch, + request, + startRoom.roomKey(), + bridge); + } + + private CanonicalInitialAdmissionLaunchTarget readCurrentLaunch(CanonicalPlayableTarget target) { + requireNoAmbientTransaction(); + CanonicalInitialAdmissionLaunchTarget launch = + launches + .readForInitialAdmission( + target.targetNamespace(), + target.canonicalTenantId(), + target.realmId(), + target.canonicalGameInstanceId()) + .orElseThrow(PreV1RunOwnedFixturePlayRegion::unavailable); + var association = launch.association(); + if (!target.targetNamespace().equals(association.targetNamespace()) + || !target.canonicalTenantId().equals(association.canonicalTenantId()) + || !target.realmId().equals(launch.realmId()) + || !target.worldSlug().equals(association.worldSlug()) + || !target.canonicalGameInstanceId().equals(association.gameInstanceUuid()) + || !target.playableStateNamespaceId().equals(association.playableStateNamespaceId()) + || !target.playableStateScope().equals(association.playableStateScope().name()) + || !association.publicProduction() + || association.currentGameInstanceStatus() + != CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus.RUNNING + || !target.canonicalVersionId().equals(launch.canonicalVersionId()) + || target.gameInstanceId() != launch.gameInstanceId() + || target.runtimeVersionId() != launch.runtimeVersionId() + || target.gameSessionTenantId() != association.gameSessionTenantId()) { + throw unavailable(); + } + return launch; + } + + private WorldRunOwnedFixtureLifecycleEvidence readCurrentFixtureLifecycle( + CanonicalPlayableTarget target, + CanonicalInitialAdmissionLaunchTarget expectedLaunch, + CanonicalInitialPlayerLocationRequest request, + Deadline operationDeadline) { + requireNoAmbientTransaction(); + CanonicalInitialAdmissionLaunchTarget before = readCurrentLaunch(target); + if (!expectedLaunch.equals(before) || !before.association().isRunOwnedFixture()) { + throw unavailable(); + } + WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest = + lifecycleRequest(target, before.association(), request); + WorldRunOwnedFixtureLifecycleEvidence lifecycle = + world.readRunOwnedFixture(lifecycleRequest, operationDeadline); + requireCurrentLifecycle(target, before, lifecycleRequest, lifecycle); + CanonicalInitialAdmissionLaunchTarget after = readCurrentLaunch(target); + if (!before.equals(after)) throw unavailable(); + return lifecycle; + } + + private static void requireCurrentLifecycle( + CanonicalPlayableTarget target, + CanonicalInitialAdmissionLaunchTarget launch, + WorldCanonicalInstanceLifecycleEvidence.Request request, + WorldRunOwnedFixtureLifecycleEvidence lifecycle) { + if (lifecycle == null + || !request.equals(lifecycle.request()) + || !"ACTIVE".equals(lifecycle.lifecycleStatus()) + || lifecycle.lifecycleEpoch() != target.activeWorldEpoch() + || !launch + .association() + .fixtureProvenanceDigest() + .equals(lifecycle.fixtureProvenanceDigest())) { + throw unavailable(); + } + } + + private static WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest( + CanonicalPlayableTarget target, + CanonicalGameInstanceLaunchAssociation association, + CanonicalInitialPlayerLocationRequest request) { + if (!association.isRunOwnedFixture()) throw unavailable(); + UUID placementOperationId; + try { + placementOperationId = UUID.fromString(request.getPlacementOperationUuid()); + } catch (IllegalArgumentException malformed) { + throw unavailable(); + } + if (!placementOperationId.toString().equals(request.getPlacementOperationUuid())) { + throw unavailable(); + } + var descriptor = association.descriptor(); + return new WorldCanonicalInstanceLifecycleEvidence.Request( + 1, + WorldCanonicalInstanceLifecycleEvidence.initialLocationReadRequestId(placementOperationId), + target.targetNamespace(), + target.canonicalTenantId(), + target.worldSlug(), + target.canonicalGameInstanceId(), + target.playableStateNamespaceId(), + target.playableStateScope(), + true, + association.controlPlaneRequestId(), + target.canonicalVersionId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + association.attestationDigest()); + } + + private static CanonicalInitialPlayerLocationRequest worldRequest( + CanonicalPlayableTarget target, + UUID accountId, + PreV1RunOwnedFixtureActorSource.Identity actor, + PreseededActorAssignmentExpectedTarget expectedTarget) { + return CanonicalInitialPlayerLocationRequest.newBuilder() + .setSchemaVersion(1) + .setPlacementOperationUuid(UUID.randomUUID().toString()) + .setExpectedTarget(expectedTarget) + .setCanonicalAccountUuid(accountId.toString()) + .setCharacterUuid(actor.characterId().toString()) + .setAssignmentUuid(actor.assignmentId().toString()) + .setAssignmentIntentDigest(actor.intentDigest()) + .setInitialAdmissionHoldUuid(target.holdId().toString()) + .setInitialAdmissionHoldFence(target.holdFence().toString()) + .setInitialAdmissionRequestId(target.initialAdmissionRequestId()) + .setInitialAdmissionRequestDigest(target.initialAdmissionRequestDigest()) + .setActiveLifecycleEpoch(target.activeWorldEpoch()) + .setTerminalProofDigest(target.ownerProofDigest()) + .setCommittedPointerVersion(target.pointerVersion()) + .setAuditEventId(target.auditEventId()) + .build(); + } + + private static PreseededActorAssignmentExpectedTarget expectedTarget( + CanonicalPlayableTarget target, + CanonicalGameInstanceLaunchAssociation association, + String frozenPolicyDigest) { + if (!"SHARED".equals(target.playableStateScope())) throw unavailable(); + var descriptor = association.descriptor(); + return PreseededActorAssignmentExpectedTarget.newBuilder() + .setCanonicalTenantUuid(target.canonicalTenantId().toString()) + .setRealmUuid(target.realmId().toString()) + .setWorldSlug(target.worldSlug()) + .setRealmSlug(target.realmSlug()) + .setGameInstanceId(target.canonicalGameInstanceId().toString()) + .setCatalogRevision(target.catalogRevision()) + .setCanonicalVersionUuid(target.canonicalVersionId().toString()) + .setFrozenPolicyDigest(frozenPolicyDigest) + .setPublishedReleaseBundleRef(descriptor.publishedReleaseBundleRef()) + .setPlayableStateNamespaceUuid(target.playableStateNamespaceId().toString()) + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .build(); + } + + private static String fixturePolicyDigest( + CanonicalPlayableTarget target, + CanonicalGameInstanceLaunchAssociation association, + CanonicalRealmCatalogSnapshot catalog) { + CanonicalRealmCatalogSnapshot.FixturePolicy policy = catalog.fixturePolicy(); + UUID operationId; + try { + operationId = UUID.fromString(association.controlPlaneRequestId()); + } catch (IllegalArgumentException malformed) { + throw unavailable(); + } + if (!catalog.isRunOwnedFixture() + || policy == null + || !target.targetNamespace().equals(catalog.targetNamespace()) + || !target.canonicalTenantId().equals(catalog.tenantId()) + || !target.worldSlug().equals(catalog.worldSlug()) + || !target.realmId().equals(catalog.realmId()) + || !target.realmSlug().equals(catalog.realmSlug()) + || !target.playableStateNamespaceId().equals(catalog.playableStateNamespaceId()) + || !target.playableStateScope().equals(catalog.stateScope()) + || !target.characterCreationPolicy().equals(catalog.characterCreationPolicy()) + || target.catalogRevision() != catalog.catalogRevision() + || !operationId.toString().equals(association.controlPlaneRequestId()) + || !operationId.equals(policy.sealOperationId()) + || !association.fixtureProvenanceDigest().equals(policy.sealEvidenceDigest()) + || !RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyEvidenceDigest( + policy.sealOperationId(), policy.sealRequestDigest()) + .equals(association.fixtureProvenanceDigest()) + || !policy.sealRequestDigest().matches("sha256:[0-9a-f]{64}")) { + throw unavailable(); + } + return policy.sealRequestDigest().substring("sha256:".length()); + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw unavailable(); + } + } + + private static void requireNonNil(UUID value, String field) { + if (value == null || value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(field + " must be a non-nil UUID"); + } + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Run-owned fixture region preparation is unavailable"); + } + + record Prepared( + UUID characterId, + UUID operationalRegionId, + long regionEpoch, + CanonicalInitialPlayerLocationRequest request, + String roomKey, + CanonicalGameplayRegionBindingBridgeOwner bridge) { + Prepared { + requireNonNil(characterId, "characterId"); + requireNonNil(operationalRegionId, "operationalRegionId"); + if (regionEpoch <= 0L) throw new IllegalArgumentException("regionEpoch must be positive"); + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(roomKey, "roomKey"); + Objects.requireNonNull(bridge, "bridge"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalInitialPlayerLocationRegionResolver.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalInitialPlayerLocationRegionResolver.java index 422059ca95..eeae1d2124 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalInitialPlayerLocationRegionResolver.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalInitialPlayerLocationRegionResolver.java @@ -68,6 +68,29 @@ public ResolvedRegion resolve( /** Immutable resolved observation; consumers must still revalidate at their binding gate. */ public static final class ResolvedRegion { + /** + * Pre-v1 gate waiver (ADR 0185) stand-in for the run-owned fixture: a Game Session-built + * observation over a fixture assignment. World places no fixture actor, so this is not a World + * placement read; the observation and assignment must name the same exact regions. + */ + public static ResolvedRegion preV1RunOwnedFixture( + CanonicalInitialPlayerLocationRegionResponse observation, + CanonicalRegionBootstrapAssignmentResolver.Assignment fixtureAssignment) { + Objects.requireNonNull(observation, "observation"); + Objects.requireNonNull(fixtureAssignment, "fixtureAssignment"); + if (!fixtureAssignment.runOwnedFixture() + || !observation + .getCanonicalRegionInstanceUuid() + .equals(fixtureAssignment.canonicalRegionId().toString()) + || !observation + .getOperationalRegionUuid() + .equals(fixtureAssignment.operationalRegionId().toString())) { + throw new IllegalArgumentException( + "Run-owned fixture observation must name its exact fixture assignment"); + } + return new ResolvedRegion(observation, fixtureAssignment); + } + private final CanonicalInitialPlayerLocationRegionResponse observation; private final CanonicalRegionBootstrapAssignmentResolver.Assignment lifecycleAssignment; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalRegionBootstrapAssignmentResolver.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalRegionBootstrapAssignmentResolver.java index add16f1fbc..5c40812ed0 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalRegionBootstrapAssignmentResolver.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalRegionBootstrapAssignmentResolver.java @@ -4,8 +4,10 @@ import java.util.Map; import java.util.Objects; import java.util.UUID; +import net.firedevops.firemud.common.prev1.PreV1GateWaivers; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleClient; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldRunOwnedFixtureLifecycleEvidence; /** Resolves a canonical region through the authenticated World lifecycle owner read. */ public final class CanonicalRegionBootstrapAssignmentResolver { @@ -67,7 +69,10 @@ private static void requireNonNil(UUID value, String fieldName) { } } - /** Immutable owner-read result. Construction is restricted to this authenticated resolver. */ + /** + * Immutable owner-read result. Construction is restricted to this authenticated resolver, or to + * the pre-v1 run-owned fixture stand-in below. A fixture assignment has no capture or graph. + */ public static final class Assignment { private final WorldCanonicalInstanceLifecycleEvidence.Request request; private final UUID canonicalRegionId; @@ -94,6 +99,48 @@ private Assignment( this.preparationInputDigest = evidence.preparationInputDigest(); } + private Assignment( + WorldRunOwnedFixtureLifecycleEvidence evidence, + UUID canonicalRegionId, + UUID operationalRegionId) { + this.request = evidence.request(); + this.canonicalRegionId = canonicalRegionId; + this.operationalRegionId = operationalRegionId; + this.lifecycleStatus = evidence.lifecycleStatus(); + this.lifecycleEpoch = evidence.lifecycleEpoch(); + this.lifecycleRowVersion = evidence.rowVersion(); + this.captureId = null; + this.graphSha256 = null; + this.preparationInputDigest = evidence.preparationInputDigest(); + } + + /** + * Pre-v1 gate waiver (ADR 0185) stand-in: the run-owned fixture world has no region graph or + * operational region assignment map, so the caller supplies its fixed region identities over + * World's ACTIVE fixture lifecycle. Refuses without the waivers (and so under prod). + */ + public static Assignment preV1RunOwnedFixture( + PreV1GateWaivers waivers, + WorldRunOwnedFixtureLifecycleEvidence evidence, + UUID canonicalRegionId, + UUID operationalRegionId) { + if (waivers == null || !waivers.enabled()) { + throw new IllegalStateException("Run-owned fixture region assignment requires waivers"); + } + Objects.requireNonNull(evidence, "evidence"); + if (!"ACTIVE".equals(evidence.lifecycleStatus())) { + throw new IllegalStateException("World fixture lifecycle evidence is not ACTIVE"); + } + requireNonNil(canonicalRegionId, "canonicalRegionId"); + requireNonNil(operationalRegionId, "operationalRegionId"); + return new Assignment(evidence, canonicalRegionId, operationalRegionId); + } + + /** True for the run-owned fixture stand-in, which has no capture or graph. */ + public boolean runOwnedFixture() { + return captureId == null; + } + public WorldCanonicalInstanceLifecycleEvidence.Request request() { return request; } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyOwner.java index 7ba5b8c1ff..3d9cda3bf7 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyOwner.java @@ -174,6 +174,30 @@ public Observation join( return observe(retained, original, verified, custody); } + /** Borrows the persisted current PLAY scope under the same exact LOGIN and transport custody. */ + public T withCurrentScope( + InitialGameplayLoginAttemptCoordinates original, + CanonicalGameplayLoginResult verified, + DirectTextAuthenticatedLobbyCustody custody, + DirectTextAuthenticatedLobbyScope expected, + Function action) { + requireNoTransaction(); + return current( + original, + verified, + custody, + transport -> { + var selected = + transaction.execute( + status -> repository.current(original, verified, transport, clock)); + if (selected == null || !selected.recordId().equals(expected.recordId())) { + throw unavailable(); + } + selected.requireCurrent(original, verified, transport, clock); + return action.apply(transport); + }); + } + private Observation observe( DirectTextAuthenticatedLobbyJoin originalJoin, InitialGameplayLoginAttemptCoordinates original, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayAdmissionDecisionReadGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayAdmissionDecisionReadGrpcService.java index 2aecd47179..6f476fcd8a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayAdmissionDecisionReadGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayAdmissionDecisionReadGrpcService.java @@ -782,42 +782,8 @@ private static Target toTarget(CanonicalGameplayAdmissionDecision decision) { return toTarget(decision.targetEvidence()); } - private static Target toTarget( - net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget target) { - return new Target( - target.targetNamespace(), - target.tenantSlug(), - target.canonicalTenantId(), - target.worldSlug(), - target.worldDisplayName(), - target.realmId(), - target.realmSlug(), - target.realmDisplayName(), - target.gameSessionTenantId(), - target.gameInstanceId(), - target.playableStateNamespaceId(), - target.playableStateScope(), - target.canonicalGameInstanceId(), - target.canonicalVersionId(), - target.runtimeVersionId(), - target.catalogRevision(), - target.pointerVersion(), - target.admissionPointerSnapshotDigest(), - target.activeWorldEpoch(), - target.initialAdmissionRequestId(), - target.initialAdmissionRequestDigest(), - CanonicalGameplayAdmissionDecisionReadGrpcCodec.OriginKind.valueOf( - target.initialAdmissionOriginKind().name()), - target.expectedPriorPointerVersion(), - target.holdId(), - target.holdFence(), - target.holdBindingDigest(), - target.auditEventId(), - target.ownerProofDigest(), - OwnerProofOutcome.valueOf(target.ownerProofOutcome().name()), - target.positiveDurableAbort(), - target.ownerProofTerminalAt(), - target.characterCreationPolicy()); + private static Target toTarget(CanonicalPlayableTarget target) { + return target.admissionDecisionTarget(); } private static boolean hasConnectionFailureSqlState(Throwable failure) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java index 60d5234f1d..7a8de891d0 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java @@ -11,6 +11,7 @@ import net.firedevops.firemud.gamesession.command.text.TextCommandInterpretationResult; import net.firedevops.firemud.gamesession.dto.CommandEnqueueResult; import net.firedevops.firemud.gamesession.presentation.PlayerOutput; +import net.firedevops.firemud.gamesession.repository.PreV1CanonicalPlayAdmissionOwner; import net.firedevops.firemud.gamesession.service.InitialGameplayLoginOwner; import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyOwner; import org.springframework.beans.factory.ObjectProvider; @@ -24,16 +25,19 @@ public final class AuthenticatedDirectTextCommandReceiver { private final ObjectProvider logins; private final ObjectProvider selections; private final ObjectProvider lobbies; + private final ObjectProvider admissions; public AuthenticatedDirectTextCommandReceiver( AuthenticatedDirectTextSessions sessions, ObjectProvider logins, ObjectProvider selections, - ObjectProvider lobbies) { + ObjectProvider lobbies, + ObjectProvider admissions) { this.sessions = sessions; this.logins = logins; this.selections = selections; this.lobbies = lobbies; + this.admissions = admissions; } public TextCommandInterpretationResult receive(WebSocketSession socket, TextCommand command) { @@ -107,14 +111,12 @@ public TextCommandInterpretationResult receive(WebSocketSession socket, TextComm return success("Joined public production realm"); }); } - // LOGIN and JOIN are not admission. Until the canonical binding owner is qualified, the - // retired numeric entitlement route must never be selected by this protected receiver. - case PLAY -> failure("ADMISSION_UNAVAILABLE", "Canonical gameplay admission unavailable"); + case PLAY -> play(connection, command); case LOGOUT -> success("Logged out"); default -> failure("FEATURE_UNAVAILABLE", "Command unavailable"); }; } catch (AuthenticatedDirectTextSessions.LoginRequiredException missingLogin) { - return failure("LOGIN_REQUIRED", "Use LOGIN before REALMS or JOIN"); + return failure("LOGIN_REQUIRED", "Use LOGIN before REALMS, JOIN, or PLAY"); } catch (ExpiredWorldSelectionException expiredSelection) { return failure( "INVALID_ARGUMENT", "World menu expired. Run WORLDS and choose a listed selector again."); @@ -139,6 +141,58 @@ public TextCommandInterpretationResult receive(WebSocketSession socket, TextComm } } + private TextCommandInterpretationResult play( + AuthenticatedDirectTextSessions.Connection connection, TextCommand command) { + var owner = admissions.getIfAvailable(); + if (owner == null || !owner.ready()) return admissionUnavailable(); + var request = command.playRequestPayload().orElse(null); + if (request == null + || request.worldSelector() == null + || request.worldSelector().isBlank() + || request.characterSelector() != null) { + return failure("INVALID_ARGUMENT", "Usage: PLAY [realm]"); + } + return connection.withLogin( + (original, login) -> { + var scope = connection.selectedScope; + if (connection.menu == null || scope == null) { + return failure("INVALID_ARGUMENT", "Run WORLDS and REALMS before PLAY "); + } + var selected = + required(selections).resolve(connection.menu, request.worldSelector()).orElseThrow(); + if (!selected.equals(scope.publicTarget()) + || request.realmSelector() != null + && !request.realmSelector().equalsIgnoreCase(selected.realmSlug())) { + return failure("INVALID_ARGUMENT", "Select the current world and realm before PLAY"); + } + return required(lobbies) + .withCurrentScope( + original, + login, + connection, + scope, + transport -> { + if (!connection.beginPlay()) return admissionUnavailable(); + try { + connection.admitted = + owner.play( + scope, + original, + login, + transport, + () -> connection.isCurrent() && connection.selectedScope == scope); + return success("Entered world: " + selected.worldSlug()); + } catch (IllegalStateException unavailable) { + return admissionUnavailable(); + } + }); + }); + } + + private static TextCommandInterpretationResult admissionUnavailable() { + return failure("ADMISSION_UNAVAILABLE", "Canonical gameplay admission unavailable"); + } + private static T required(ObjectProvider provider) { T value = provider.getIfAvailable(); if (value == null) throw new IllegalStateException("Protected owner unavailable"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessions.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessions.java index ea5812f051..bda9acb3cf 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessions.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessions.java @@ -14,6 +14,7 @@ import net.firedevops.firemud.gamesession.command.text.ObservedDirectTextTransport; import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; +import net.firedevops.firemud.gamesession.repository.PreV1CanonicalPlayAdmissionOwner; import net.firedevops.firemud.gamesession.service.InitialGameplayLoginCredentialPresentation; import net.firedevops.firemud.gamesession.service.InitialGameplayLoginOwner; import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyCustody; @@ -106,7 +107,13 @@ public final class Connection implements DirectTextAuthenticatedLobbyCustody { private volatile InitialGameplayLoginCredentialPresentation credentials; private volatile InitialGameplayLoginOwner.Outcome outcome; DirectTextWorldSelectionService.SelectionSnapshot menu; - DirectTextAuthenticatedLobbyScope selectedScope; + volatile DirectTextAuthenticatedLobbyScope selectedScope; + volatile PreV1CanonicalPlayAdmissionOwner.Admitted admitted; + private final AtomicBoolean playStarted = new AtomicBoolean(); + + boolean beginPlay() { + return playStarted.compareAndSet(false, true); + } private Connection( WebSocketSession socket, AuthenticatedDirectTextIngress ingress, Connection predecessor) { @@ -129,6 +136,8 @@ public void login(InitialGameplayLoginOwner owner, String email, char[] ownedSec } menu = null; selectedScope = null; + admitted = null; + playStarted.set(false); credentials = InitialGameplayLoginCredentialPresentation.fromAuthenticatedTcp( ingress, email, ownedSecret); @@ -234,6 +243,8 @@ private void close(CloseStatus status) { outcome = null; menu = null; selectedScope = null; + admitted = null; + playStarted.set(false); } finally { lifetime.writeLock().unlock(); } diff --git a/services/game-session-service/src/main/resources/application.yml b/services/game-session-service/src/main/resources/application.yml index 6ff7363775..c6048768c8 100644 --- a/services/game-session-service/src/main/resources/application.yml +++ b/services/game-session-service/src/main/resources/application.yml @@ -145,6 +145,10 @@ firemud: - game_session.v1.CanonicalGameplayAdmissionDecisionReadService/GetOriginalNewNeverAdmittedDecision - game_session.v1.CanonicalGameplayAdmissionDecisionReadService/GetCanonicalGameplayAdmissionDecision - game_session.v1.CanonicalGameplayAdmissionDecisionReadService/GetPublishedRealmAdmissionOwnerRead + # Bearer bypass only; the run-owned receivers still require the exact Account mTLS peer. + - game_session.v1.OriginalNewFinalAdmissionReadService/ReadOriginalNewFinalAdmission + - game_session.v1.OriginalNewCapacityExecutionReadService/ReadOriginalNewCapacityExecution + - game_session.v1.OriginalNewCapacityExecutionReadService/ReadHistoricalOriginalNewCapacityFinal grpc: cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} diff --git a/services/game-session-service/src/main/resources/db/migration/V1072__run_owned_fixture_region_world_source_kind.sql b/services/game-session-service/src/main/resources/db/migration/V1072__run_owned_fixture_region_world_source_kind.sql new file mode 100644 index 0000000000..3d30ee97ff --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1072__run_owned_fixture_region_world_source_kind.sql @@ -0,0 +1,217 @@ +-- Pre-v1 gate waiver (ADR 0185): the run-owned fixture world has no Human capture or region +-- graph, so its region runtime rows name an explicit RUN_OWNED_FIXTURE World source kind with no +-- capture id or graph digest instead of derived stand-in values. Its lifecycle request bytes still +-- carry the fixture provenance digest. Existing rows are HUMAN_CAPTURE and keep every Human check. +ALTER TABLE game_session_region_runtime_status + ADD COLUMN world_source_kind character varying(24) NOT NULL DEFAULT 'HUMAN_CAPTURE'; +ALTER TABLE game_session_region_runtime_status + ALTER COLUMN capture_id DROP NOT NULL; +ALTER TABLE game_session_region_runtime_status + ALTER COLUMN graph_sha256 DROP NOT NULL; +ALTER TABLE game_session_region_timeline_preparation + ADD COLUMN world_source_kind character varying(24) NOT NULL DEFAULT 'HUMAN_CAPTURE'; +ALTER TABLE game_session_region_timeline_preparation + ALTER COLUMN capture_id DROP NOT NULL; +ALTER TABLE game_session_region_timeline_preparation + ALTER COLUMN graph_sha256 DROP NOT NULL; +ALTER TABLE game_session_canonical_binding_region_bridge_obligation + ADD COLUMN world_source_kind character varying(24) NOT NULL DEFAULT 'HUMAN_CAPTURE'; + +-- [jooq ignore start] +ALTER TABLE game_session_region_runtime_status + ADD CONSTRAINT ck_game_session_region_runtime_world_source_kind CHECK ( + (world_source_kind = 'HUMAN_CAPTURE' + AND capture_id IS NOT NULL AND graph_sha256 IS NOT NULL) + OR (world_source_kind = 'RUN_OWNED_FIXTURE' + AND capture_id IS NULL AND graph_sha256 IS NULL)); +ALTER TABLE game_session_region_timeline_preparation + ADD CONSTRAINT ck_game_session_region_timeline_preparation_world_source_kind CHECK ( + (world_source_kind = 'HUMAN_CAPTURE' + AND capture_id IS NOT NULL AND graph_sha256 IS NOT NULL) + OR (world_source_kind = 'RUN_OWNED_FIXTURE' + AND capture_id IS NULL AND graph_sha256 IS NULL)); +ALTER TABLE game_session_canonical_binding_region_bridge_obligation + ADD CONSTRAINT ck_gs_region_bridge_obligation_world_source_kind CHECK ( + world_source_kind IN ('HUMAN_CAPTURE', 'RUN_OWNED_FIXTURE')); + +ALTER TABLE game_session_canonical_binding_region_bridge_obligation + DROP CONSTRAINT chk_gs_canonical_binding_region_bridge_obligation; + +ALTER TABLE game_session_canonical_binding_region_bridge_obligation + ADD CONSTRAINT chk_gs_canonical_binding_region_bridge_obligation CHECK ( + binding_generation > 0 + AND account_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND tenant_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND game_instance_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND runtime_game_instance_id > 0 + AND session_id <> '' + AND session_id ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + AND session_id <> '00000000-0000-0000-0000-000000000000' + AND session_id !~ '^[[:space:]]*$' + AND session_id !~ '[[:cntrl:]]' + AND region_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND region_epoch > 0 + AND status IN ('REQUIRED', 'ACKNOWLEDGED', 'NEVER_DISPATCHED') + AND inventory_revision > 0 + AND ( + (bridge_operation_id IS NULL + AND bridge_preimage_state IS NULL + AND runtime_entity_id IS NULL + AND entity_projection_generation IS NULL + AND entity_projection_fence IS NULL + AND entity_workload_namespace IS NULL + AND assignment_uuid IS NULL + AND assignment_intent_digest IS NULL + AND entity_created_origin IS NULL + AND entity_reference_digest IS NULL + AND world_source_digest IS NULL + AND canonical_region_id IS NULL + AND world_lifecycle_epoch IS NULL + AND world_lifecycle_row_version IS NULL + AND world_capture_id IS NULL + AND world_graph_sha256 IS NULL + AND world_preparation_input_digest IS NULL) + OR + (bridge_operation_id IS NOT NULL + AND bridge_preimage_state IS NOT NULL + AND bridge_preimage_state = 'ABSENT' + AND runtime_entity_id IS NOT NULL + AND runtime_entity_id > 0 + AND entity_projection_generation IS NOT NULL + AND entity_projection_generation > 0 + AND entity_projection_fence IS NOT NULL + AND entity_projection_fence > 0 + AND entity_workload_namespace IS NOT NULL + AND entity_workload_namespace <> '' + AND gs_original_actor_origin_valid( + assignment_uuid, assignment_intent_digest, entity_created_origin) + AND entity_reference_digest IS NOT NULL + AND entity_reference_digest ~ '^[0-9a-f]{64}$' + AND world_source_digest IS NOT NULL + AND world_source_digest ~ '^[0-9a-f]{64}$' + AND canonical_region_id IS NOT NULL + AND canonical_region_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND world_lifecycle_epoch IS NOT NULL + AND world_lifecycle_epoch > 0 + AND world_lifecycle_row_version IS NOT NULL + AND world_lifecycle_row_version >= 0 + AND ((world_source_kind = 'HUMAN_CAPTURE' + AND world_capture_id IS NOT NULL + AND world_capture_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND world_graph_sha256 IS NOT NULL + AND world_graph_sha256 ~ '^[0-9a-f]{64}$') + OR (world_source_kind = 'RUN_OWNED_FIXTURE' + AND world_capture_id IS NULL + AND world_graph_sha256 IS NULL)) + AND world_preparation_input_digest IS NOT NULL + AND world_preparation_input_digest ~ '^sha256:[0-9a-f]{64}$') + ) + AND ( + (status IN ('REQUIRED', 'NEVER_DISPATCHED') + AND redis_readback_digest IS NULL + AND acknowledged_at IS NULL) + OR + (status = 'ACKNOWLEDGED' + AND bridge_operation_id IS NOT NULL + AND executor_fence IS NOT NULL + AND executor_fence > 0 + AND lease_token_correlation IS NOT NULL + AND lease_token_correlation ~ '^[0-9a-f]{64}$' + AND redis_readback_digest IS NOT NULL + AND redis_readback_digest ~ '^[0-9a-f]{64}$' + AND acknowledged_at IS NOT NULL) + ) + AND ( + (bridge_operation_id IS NULL + AND executor_fence IS NULL + AND lease_token_correlation IS NULL) + OR + (bridge_operation_id IS NOT NULL + AND executor_fence IS NOT NULL + AND executor_fence > 0 + AND lease_token_correlation IS NOT NULL + AND lease_token_correlation ~ '^[0-9a-f]{64}$') + ) + ); + +-- Extend the exact latest live definitions, failing closed on absent or repeated anchors. +DO $migration$ +DECLARE + original TEXT; + anchor TEXT := $anchor$ AND preparation.capture_id = bridge.world_capture_id + AND preparation.graph_sha256 = bridge.world_graph_sha256$anchor$; + replacement TEXT := $replacement$ AND preparation.world_source_kind = bridge.world_source_kind + AND preparation.capture_id IS NOT DISTINCT FROM bridge.world_capture_id + AND preparation.graph_sha256 IS NOT DISTINCT FROM bridge.world_graph_sha256$replacement$; +BEGIN + SELECT pg_get_functiondef('"${flyway:defaultSchema}".gs_region_bridge_original_preparation_matches(game_session_canonical_binding_region_bridge_obligation)'::regprocedure) + INTO STRICT original; + IF (length(original) - length(replace(original, anchor, ''))) / length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exact V1051 region bridge preparation World source match'; + END IF; + EXECUTE replace(original, anchor, replacement); +END; +$migration$; + +DO $migration$ +DECLARE + original TEXT; + anchor TEXT := $anchor$ AND region_obligation.world_capture_id IS NOT NULL + AND region_obligation.world_capture_id <> + '00000000-0000-0000-0000-000000000000'::uuid + AND region_obligation.world_graph_sha256 ~ '^[0-9a-f]{64}$'$anchor$; + replacement TEXT := $replacement$ AND ((region_obligation.world_source_kind = 'HUMAN_CAPTURE' + AND region_obligation.world_capture_id IS NOT NULL + AND region_obligation.world_capture_id <> + '00000000-0000-0000-0000-000000000000'::uuid + AND region_obligation.world_graph_sha256 ~ '^[0-9a-f]{64}$') + OR (region_obligation.world_source_kind = 'RUN_OWNED_FIXTURE' + AND region_obligation.world_capture_id IS NULL + AND region_obligation.world_graph_sha256 IS NULL))$replacement$; +BEGIN + SELECT pg_get_functiondef('"${flyway:defaultSchema}".require_first_new_abort_source_complete()'::regprocedure) + INTO STRICT original; + IF (length(original) - length(replace(original, anchor, ''))) / length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exact V1044.1 retained region bridge abort World source guard'; + END IF; + EXECUTE replace(original, anchor, replacement); +END; +$migration$; + +DO $migration$ +DECLARE definition TEXT; original TEXT; replacement TEXT; +BEGIN + SELECT pg_get_functiondef((quote_ident(current_schema())||'.gs_runtime_family_catalog_installed()')::regprocedure) INTO STRICT definition; + original := $needle$WHERE version='1071' + ) AND ($needle$; + replacement := $replacement$WHERE version='1071' + ) AND ( + SELECT count(*)=1 AND coalesce(bool_and(type='SQL' + AND script='V1072__run_owned_fixture_region_world_source_kind.sql' AND success),false) + FROM "${flyway:table}" WHERE version='1072' + ) AND ($replacement$; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor catalog installation clause'; END IF; + EXECUTE replace(definition,original,replacement); + + SELECT pg_get_functiondef((quote_ident(current_schema())||'.gs_runtime_family_catalog_bytes(bigint)')::regprocedure) INTO STRICT definition; + original := $needle$AND version IS DISTINCT FROM '1071'$needle$; + replacement := original||E'\n AND version IS DISTINCT FROM ''1072'''; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor history exclusion'; END IF; + definition := replace(definition,original,replacement); + original := $needle$SELECT 'MIGRATION','catalog-installation:1071','V1071__run_owned_fixture_preseeded_only_catalog.sql'$needle$; + replacement := original||E'\n UNION ALL\n SELECT ''MIGRATION'',''catalog-installation:1072'',''V1072__run_owned_fixture_region_world_source_kind.sql'''; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor catalog marker'; END IF; + EXECUTE replace(definition,original,replacement); +END; +$migration$; + +INSERT INTO game_session_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest) +SELECT epoch,bytes,'sha256:'||encode(sha256(bytes),'hex') FROM ( + SELECT epoch,gs_runtime_family_catalog_bytes(epoch) AS bytes FROM ( + SELECT coalesce(max(catalog_epoch),0)+1 AS epoch FROM game_session_runtime_family_catalog_epoch + ) next_epoch +) seal; +-- [jooq ignore stop] diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java index ec9b3b29a0..8b68509f7f 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java @@ -97,7 +97,7 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB Map before = f.rows(f.tables()); var evidence = f.owner().capture(request()); var catalog = evidence.catalog(); - assertThat(catalog.catalogEpoch()).isEqualTo(25); + assertThat(catalog.catalogEpoch()).isEqualTo(26); assertThat( catalog.schemaFacts().stream() .filter(fact -> fact.kind() == FactKind.TABLE) @@ -226,7 +226,8 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB "catalog-installation:1066", "catalog-installation:1066.1", "catalog-installation:1070", - "catalog-installation:1071") + "catalog-installation:1071", + "catalog-installation:1072") .noneMatch( identity -> identity.contains(":1057:") @@ -253,7 +254,8 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB || identity.contains(":1066:") || identity.contains(":1066.1:") || identity.contains(":1070:") - || identity.contains(":1071:")); + || identity.contains(":1071:") + || identity.contains(":1072:")); assertThat( f.dsl .fetchSingle( @@ -796,7 +798,7 @@ void viewOptionsDriftRefusesReadsRetriesAndNewRequestsWithoutChangingRetainedRow "CREATE MATERIALIZED VIEW catalog_probe_materialized AS SELECT id,description FROM game_manifest WITH NO DATA"); migration(f.source, f.schema, f.history, null).migrate(); var original = f.owner().capture(request()); - assertThat(original.catalog().catalogEpoch()).isEqualTo(25); + assertThat(original.catalog().catalogEpoch()).isEqualTo(26); assertThat(original.catalog().schemaFacts()) .anyMatch( fact -> @@ -956,7 +958,8 @@ void priorAndLaterHistoryAndOwnSuccessfulScriptRemainSeparateInstallationChecks( "1066", "1066.1", "1070", - "1071")) { + "1071", + "1072")) { for (String change : List.of("success=false", "script='wrong_installation.sql'", "type='JDBC'")) { try (Fixture f = fixture(null)) { @@ -1009,7 +1012,8 @@ void priorAndLaterHistoryAndOwnSuccessfulScriptRemainSeparateInstallationChecks( "1066", "1066.1", "1070", - "1071")) { + "1071", + "1072")) { try (Fixture f = fixture(null)) { f.dsl.execute( "INSERT INTO " diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/PreV1RunOwnedFixtureStandInsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/PreV1RunOwnedFixtureStandInsTest.java new file mode 100644 index 0000000000..7e7c5b4ed4 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/PreV1RunOwnedFixtureStandInsTest.java @@ -0,0 +1,230 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.math.BigInteger; +import java.time.Instant; +import java.util.UUID; +import net.firedevops.firemud.common.prev1.PreV1GateWaivers; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldRunOwnedFixtureLifecycleEvidence; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.entitymanagement.v1.PreseededActorAssignmentExpectedTarget; +import net.firedevops.firemud.gamesession.client.CanonicalGameplayRuntimeActorReference; +import net.firedevops.firemud.gamesession.entity.CanonicalGameplayRegionRuntimeStatus; +import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest; +import org.junit.jupiter.api.Test; + +/** Controlled content only: the stand-ins grant no World placement or Entity provenance. */ +class PreV1RunOwnedFixtureStandInsTest { + private static final String NAMESPACE = "test"; + private static final UUID ACCOUNT = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID GAME = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID VERSION = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID STATE = UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final UUID REALM = UUID.fromString("66666666-6666-4666-8666-666666666666"); + private static final String PROVENANCE = "sha256:" + "b".repeat(64); + private static final String START_ROOM = "R-1021"; + + @Test + void actorIdentityIsDeterministicPerAccountAndRefusesAnyOtherRequest() { + var identity = PreV1RunOwnedFixtureActorSource.identity(ACCOUNT, target()); + assertThat(identity.characterId()) + .isEqualTo(PreV1RunOwnedFixtureActorSource.characterId(ACCOUNT)) + .isEqualTo( + PreV1RunOwnedFixtureActorSource.uuidV5( + PreV1RunOwnedFixtureActorSource.NAMESPACE, ACCOUNT.toString())); + assertThat(identity.characterId().version()).isEqualTo(5); + assertThat(PreV1RunOwnedFixtureActorSource.identity(ACCOUNT, target())).isEqualTo(identity); + assertThat(PreV1RunOwnedFixtureActorSource.characterId(UUID.randomUUID())) + .isNotEqualTo(identity.characterId()); + assertThat(identity.runtimeEntityId()).isPositive().isLessThanOrEqualTo((1L << 53) - 1L); + + var source = new PreV1RunOwnedFixtureActorSource(PreV1GateWaivers.enabledForTest(), NAMESPACE); + var request = request(1L); + CanonicalGameplayRuntimeActorReference first = source.read(request); + CanonicalGameplayRuntimeActorReference again = source.read(request); + assertThat(first.matchesWorldRequest(request)).isTrue(); + assertThat(first.characterUuid()).isEqualTo(identity.characterId()); + assertThat(first.canonicalAccountUuid()).isEqualTo(ACCOUNT); + assertThat(first.runtimeEntityId().value()).isEqualTo(identity.runtimeEntityId()); + assertThat(first.workloadNamespace()).isEqualTo(NAMESPACE); + assertThat(first.origin()) + .isEqualTo( + new CanonicalGameplayRuntimeActorReference.AssignmentOrigin( + identity.assignmentId(), identity.intentDigest())); + assertThat(CanonicalGameplayRegionBindingBridgeProofs.entityReferenceDigest(first)) + .isEqualTo(CanonicalGameplayRegionBindingBridgeProofs.entityReferenceDigest(again)); + + var otherCharacter = request.toBuilder().setCharacterUuid(UUID.randomUUID().toString()).build(); + var otherIntent = request.toBuilder().setAssignmentIntentDigest("c".repeat(64)).build(); + for (var invalid : java.util.List.of(otherCharacter, otherIntent)) { + assertThatThrownBy(() -> source.read(invalid)).isInstanceOf(IllegalStateException.class); + } + assertThatThrownBy( + () -> new PreV1RunOwnedFixtureActorSource(PreV1GateWaivers.disabled(), NAMESPACE)) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void placementJoinsTheActiveFixtureLifecycleToTheLegacyStartRoom() { + var lifecycle = lifecycle("ACTIVE", 1L); + var placement = + new PreV1RunOwnedFixturePlacementSource( + PreV1GateWaivers.enabledForTest(), (request, deadline) -> lifecycle, START_ROOM); + var resolved = placement.resolve(request(1L), null); + var assignment = resolved.lifecycleAssignment(); + + assertThat(assignment.runOwnedFixture()).isTrue(); + assertThat(assignment.captureId()).isNull(); + assertThat(assignment.graphSha256()).isNull(); + assertThat(assignment.request()).isEqualTo(lifecycle.request()); + assertThat(assignment.preparationInputDigest()).isEqualTo(lifecycle.preparationInputDigest()); + assertThat(resolved.operationalRegionId()) + .isEqualTo(placement.operationalRegionId(TENANT, GAME)); + assertThat(resolved.canonicalRegionInstanceId()).isEqualTo(placement.canonicalRegionId(GAME)); + assertThat(resolved.observation().getPlacementResult().getPrivateRuntimeRoomKey()) + .isEqualTo(START_ROOM); + assertThat(resolved.observation().getLifecycle().getCaptureUuid()).isEmpty(); + assertThat(CanonicalGameplayRegionBindingBridgeProofs.worldSourceDigest(request(1L), resolved)) + .matches("[0-9a-f]{64}"); + + for (var stale : java.util.List.of(lifecycle("TERMINATING", 1L), lifecycle("ACTIVE", 2L))) { + var refusing = + new PreV1RunOwnedFixturePlacementSource( + PreV1GateWaivers.enabledForTest(), (request, deadline) -> stale, START_ROOM); + assertThatThrownBy(() -> refusing.resolve(request(1L), null)) + .isInstanceOf(IllegalStateException.class); + } + assertThatThrownBy( + () -> + new PreV1RunOwnedFixturePlacementSource( + PreV1GateWaivers.disabled(), (request, deadline) -> lifecycle, START_ROOM)) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void fixtureRegionSourceAndStatusCarryNoCaptureOrGraph() { + var lifecycleRequest = lifecycle("ACTIVE", 1L).request(); + UUID region = UUID.randomUUID(); + var fixture = + new CanonicalGameplayRegionRuntimeStatusRepository.Source( + TENANT, + GAME, + UUID.randomUUID(), + region, + 1L, + 0L, + lifecycleRequest, + null, + null, + "sha256:" + "d".repeat(64)); + assertThat(fixture.runOwnedFixture()).isTrue(); + assertThat(fixture.worldSourceKind()).isEqualTo("RUN_OWNED_FIXTURE"); + assertThatThrownBy( + () -> + new CanonicalGameplayRegionRuntimeStatusRepository.Source( + TENANT, + GAME, + UUID.randomUUID(), + region, + 1L, + 0L, + lifecycleRequest, + UUID.randomUUID(), + null, + "sha256:" + "d".repeat(64))) + .isInstanceOf(IllegalStateException.class); + var human = + new CanonicalGameplayRegionRuntimeStatusRepository.Source( + TENANT, + GAME, + UUID.randomUUID(), + region, + 1L, + 0L, + lifecycleRequest, + UUID.randomUUID(), + "e".repeat(64), + "sha256:" + "d".repeat(64)); + assertThat(human.worldSourceKind()).isEqualTo("HUMAN_CAPTURE"); + + String tag = CanonicalGameplayRegionRedisKeys.tenantRegionTag(TENANT, GAME, region); + var status = + new CanonicalGameplayRegionRuntimeStatus( + TENANT, + GAME, + UUID.randomUUID(), + region, + tag, + 1L, + 0L, + lifecycleRequest, + null, + null, + "sha256:" + "d".repeat(64), + 1L, + BigInteger.ONE, + "f".repeat(64), + "game-session-service", + "instance-1", + false, + null, + -1L, + Instant.EPOCH); + assertThat(status.runOwnedFixture()).isTrue(); + } + + private static PreseededActorAssignmentExpectedTarget target() { + return PreseededActorAssignmentExpectedTarget.newBuilder() + .setCanonicalTenantUuid(TENANT.toString()) + .setRealmUuid(REALM.toString()) + .setWorldSlug("fixture-world") + .setRealmSlug("fixture-realm") + .setGameInstanceId(GAME.toString()) + .setCatalogRevision(1L) + .setCanonicalVersionUuid(VERSION.toString()) + .setFrozenPolicyDigest("a".repeat(64)) + .setPlayableStateNamespaceUuid(STATE.toString()) + .setPublishedReleaseBundleRef("fixture-bundle") + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .build(); + } + + private static CanonicalInitialPlayerLocationRequest request(long activeEpoch) { + var identity = PreV1RunOwnedFixtureActorSource.identity(ACCOUNT, target()); + return CanonicalInitialPlayerLocationRequest.newBuilder() + .setSchemaVersion(1) + .setPlacementOperationUuid(UUID.randomUUID().toString()) + .setExpectedTarget(target()) + .setCanonicalAccountUuid(ACCOUNT.toString()) + .setCharacterUuid(identity.characterId().toString()) + .setAssignmentUuid(identity.assignmentId().toString()) + .setAssignmentIntentDigest(identity.intentDigest()) + .setActiveLifecycleEpoch(activeEpoch) + .build(); + } + + private static WorldRunOwnedFixtureLifecycleEvidence lifecycle(String status, long epoch) { + var request = + new WorldCanonicalInstanceLifecycleEvidence.Request( + 1, + UUID.randomUUID(), + NAMESPACE, + TENANT, + "fixture-world", + GAME, + STATE, + "SHARED", + true, + "control-plane-request", + VERSION, + "sha256:" + "1".repeat(64), + "sha256:" + "2".repeat(64), + PROVENANCE); + return new WorldRunOwnedFixtureLifecycleEvidence( + request, PROVENANCE, "sha256:" + "3".repeat(64), status, epoch, 4L); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java index a07611335c..938a358e75 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java @@ -26,6 +26,7 @@ import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; import net.firedevops.firemud.gamesession.presentation.TextPlayerOutputRenderer; +import net.firedevops.firemud.gamesession.repository.PreV1CanonicalPlayAdmissionOwner; import net.firedevops.firemud.gamesession.service.InitialGameplayLoginOwner; import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyOwner; import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyScope; @@ -68,7 +69,13 @@ void emailNormalizationRejectionReturnsUsageBeforeProtectedOwnerLookup() { ObjectProvider selections = mock(ObjectProvider.class); ObjectProvider lobbies = mock(ObjectProvider.class); var receiver = - new AuthenticatedDirectTextCommandReceiver(sessions, logins, selections, lobbies); + new AuthenticatedDirectTextCommandReceiver( + sessions, + logins, + selections, + lobbies, + new StaticListableBeanFactory() + .getBeanProvider(PreV1CanonicalPlayAdmissionOwner.class)); var malformedEmail = " \u0000 "; var command = new TextCommand( @@ -371,7 +378,8 @@ private Fixture fixture() { sessions, beans.getBeanProvider(InitialGameplayLoginOwner.class), beans.getBeanProvider(DirectTextWorldSelectionService.class), - beans.getBeanProvider(DirectTextAuthenticatedLobbyOwner.class)); + beans.getBeanProvider(DirectTextAuthenticatedLobbyOwner.class), + beans.getBeanProvider(PreV1CanonicalPlayAdmissionOwner.class)); return new Fixture(socket, connection, selections, lobby, receiver); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessionsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessionsTest.java index f5601452a6..8b8a23eae4 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessionsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessionsTest.java @@ -24,6 +24,7 @@ import net.firedevops.firemud.gamesession.command.text.TextCommandType; import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; +import net.firedevops.firemud.gamesession.repository.PreV1CanonicalPlayAdmissionOwner; import net.firedevops.firemud.gamesession.service.InitialGameplayLoginCleanupOwner; import net.firedevops.firemud.gamesession.service.InitialGameplayLoginOwner; import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyOwner; @@ -70,7 +71,8 @@ void rejectedLoginPreservesOnlyBoundedDecisionsThroughTheReceiver( sessions, beans.getBeanProvider(InitialGameplayLoginOwner.class), beans.getBeanProvider(DirectTextWorldSelectionService.class), - beans.getBeanProvider(DirectTextAuthenticatedLobbyOwner.class)); + beans.getBeanProvider(DirectTextAuthenticatedLobbyOwner.class), + beans.getBeanProvider(PreV1CanonicalPlayAdmissionOwner.class)); var result = receiver.receive( @@ -111,7 +113,8 @@ void missingLoginIsActionableButClosedCustodyRemainsUnavailable(TextCommandType sessions, beans.getBeanProvider(InitialGameplayLoginOwner.class), beans.getBeanProvider(DirectTextWorldSelectionService.class), - beans.getBeanProvider(DirectTextAuthenticatedLobbyOwner.class)); + beans.getBeanProvider(DirectTextAuthenticatedLobbyOwner.class), + beans.getBeanProvider(PreV1CanonicalPlayAdmissionOwner.class)); var command = new TextCommand(type, List.of("demo"), type + " demo"); var missingLogin = receiver.receive(socket, command); diff --git a/services/tcp-proxy-service/telnet-login-look-smoke.sh b/services/tcp-proxy-service/telnet-login-look-smoke.sh index c443ec0767..d86570ae03 100755 --- a/services/tcp-proxy-service/telnet-login-look-smoke.sh +++ b/services/tcp-proxy-service/telnet-login-look-smoke.sh @@ -51,7 +51,7 @@ fi if [[ "$SMOKE_MUTATION_EXTENSION" == "true" ]]; then echo "Running Telnet baseline plus explicit item/container/equipment mutation extension against ${SMOKE_HOST}:${TCP_PORT}" else - echo "Running Telnet LOGIN + fail-closed PLAY baseline against ${SMOKE_HOST}:${TCP_PORT}" + echo "Running Telnet LOGIN + WORLDS + REALMS + JOIN + PLAY baseline against ${SMOKE_HOST}:${TCP_PORT}" fi echo "Using login credentials (email and password redacted)" echo "Using session='${SMOKE_SESSION_ID}' tenant='${SMOKE_TENANT_ID}'" @@ -68,7 +68,7 @@ repo_root = Path(os.environ["FIREMUD_REPO_ROOT"]) sys.path.insert(0, str(repo_root / "dev-tools" / "smoke")) from smoke_common import ( - authenticated_telnet_login_steps, + authenticated_telnet_play_steps, gameplay_item_container_equipment_steps, http_readiness_up, is_localhost_equivalent, @@ -172,8 +172,7 @@ if os.environ["SMOKE_MUTATION_EXTENSION"] == "true": discovery_selector = world login_wait_seconds = 0 else: - # Deferred: authenticated Telnet WORLDS/PLAY/LOOK needs the canonical admission chain. - steps = authenticated_telnet_login_steps(login_email, password, world, login_expect) + steps = authenticated_telnet_play_steps(login_email, password, world, worlds_expect, login_expect, play_expect) discovery_selector = None # Authenticated LOGIN answers UNAVAILABLE until the Account JWT signer is promoted, which the # pre-v1 stand-ins complete a few minutes after Account starts. @@ -192,5 +191,5 @@ run_telnet_smoke_session( if os.environ["SMOKE_MUTATION_EXTENSION"] == "true": print("Telnet WORLDS + LOGIN + PLAY + item/container/equipment mutation extension passed.") else: - print("Telnet LOGIN + fail-closed PLAY baseline smoke test passed.") + print("Telnet LOGIN + WORLDS + REALMS + JOIN + PLAY baseline smoke test passed.") PYTHON diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResources.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResources.java index 8fd648bf0b..646bd2fbaa 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResources.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResources.java @@ -85,6 +85,13 @@ public static Definition definition() { return new Definition(PRESET_ID, REGION, ZONE, List.of(STARTER_ROOM, SECONDARY_ROOM), EXITS); } + /** + * Returns the fixed preset's starter ROOM template identity, never a runtime or legacy row id. + */ + public static UUID starterRoomTemplateId() { + return STARTER_ROOM.templateId(); + } + /** * Builds a complete authorization plan before any World resource write is permitted. * diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadGrpcService.java index 2940ef60d4..1e9bbd3742 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadGrpcService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadGrpcService.java @@ -7,6 +7,8 @@ import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleGrpcCodec; +import net.firedevops.firemud.worldmanagement.v1.ReadRunOwnedFixtureStartRoomRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadRunOwnedFixtureStartRoomResponse; import net.firedevops.firemud.worldmanagement.v1.ReadWorldCanonicalInstanceLifecycleRequest; import net.firedevops.firemud.worldmanagement.v1.ReadWorldCanonicalInstanceLifecycleResponse; import net.firedevops.firemud.worldmanagement.v1.WorldCanonicalInstanceLifecycleReadServiceGrpc; @@ -133,6 +135,58 @@ public void readWorldCanonicalInstanceLifecycle( responseObserver.onCompleted(); } + @Override + public void readRunOwnedFixtureStartRoom( + ReadRunOwnedFixtureStartRoomRequest request, + StreamObserver observer) { + if (!requireAuthenticatedGameSessionPeer(observer)) return; + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + observer.onError(Status.FAILED_PRECONDITION.asRuntimeException()); + return; + } + WorldCanonicalInstanceLifecycleEvidence.Request selector; + try { + if (request == null + || !request.hasLifecycle() + || !request.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("A complete fixture lifecycle selector is required"); + } + selector = WorldCanonicalInstanceLifecycleGrpcCodec.fromRequest(request.getLifecycle()); + } catch (IllegalArgumentException invalid) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + if (!trustedNamespace.equals(selector.targetNamespace())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + final ReadRunOwnedFixtureStartRoomResponse response; + try { + var placement = repository.readRunOwnedFixtureStartRoom(selector); + if (placement.isEmpty()) { + observer.onError(Status.NOT_FOUND.asRuntimeException()); + return; + } + var startRoom = placement.orElseThrow(); + response = + ReadRunOwnedFixtureStartRoomResponse.newBuilder() + .setLifecycle( + WorldCanonicalInstanceLifecycleGrpcCodec.toFixtureResponse( + selector, startRoom.lifecycle())) + .setRoomInstanceKey(startRoom.roomKey()) + .build(); + } catch (RuntimeException unavailable) { + observer.onError( + Status.UNAVAILABLE + .withDescription("The run-owned fixture start room is unavailable") + .asRuntimeException()); + return; + } + observer.onNext(response); + observer.onCompleted(); + } + private boolean requireAuthenticatedGameSessionPeer(StreamObserver responseObserver) { GrpcPeerIdentity peer = GrpcPeerIdentity.current(); if (peer == null) { diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java index 28044ac41f..0c40409f34 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java @@ -22,6 +22,7 @@ import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.common.world.WorldRunOwnedFixtureLifecycleEvidence; +import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldFixedPresetResources; import net.firedevops.firemud.worldmanagement.v1.WorldInboundSourceFamily; import org.jooq.DSLContext; import org.jooq.Record; @@ -127,11 +128,40 @@ public Optional readRunOwnedFixture( transaction.execute( status -> { requireReadOnlyRepeatableReadOwnerTransaction(); - return readRunOwnedFixtureInCurrentOwnerTransaction(request); + var snapshot = readRunOwnedFixtureSnapshotInCurrentOwnerTransaction(request); + return snapshot == null ? null : snapshot.lifecycle(); })); } - private WorldRunOwnedFixtureLifecycleEvidence readRunOwnedFixtureInCurrentOwnerTransaction( + /** + * Reads the actual fixed-preset starter room and exact ACTIVE fixture lifecycle in one owner + * snapshot. This supplies neither placement nor admission authority and never adopts legacy + * rooms. + */ + public Optional readRunOwnedFixtureStartRoom( + WorldCanonicalInstanceLifecycleEvidence.Request request) { + Objects.requireNonNull(request, "request"); + requireNoActiveTransaction("World run-owned fixture start-room read"); + return Optional.ofNullable( + transaction.execute( + status -> { + requireReadOnlyRepeatableReadOwnerTransaction(); + var snapshot = readRunOwnedFixtureSnapshotInCurrentOwnerTransaction(request); + if (snapshot == null || !"ACTIVE".equals(snapshot.lifecycle().lifecycleStatus())) { + return null; + } + long roomId = requireRunOwnedFixtureStartRoom(snapshot.association()); + return new FixtureStartRoom(snapshot.lifecycle(), "R-" + roomId); + })); + } + + public record FixtureStartRoom(WorldRunOwnedFixtureLifecycleEvidence lifecycle, String roomKey) {} + + private record RunOwnedFixtureSnapshot( + WorldCanonicalInstanceAssociation association, + WorldRunOwnedFixtureLifecycleEvidence lifecycle) {} + + private RunOwnedFixtureSnapshot readRunOwnedFixtureSnapshotInCurrentOwnerTransaction( WorldCanonicalInstanceLifecycleEvidence.Request request) { try { Optional maybeAssociation = @@ -148,13 +178,15 @@ private WorldRunOwnedFixtureLifecycleEvidence readRunOwnedFixtureInCurrentOwnerT association.worldInstanceId()); if (row == null) return null; var fixture = association.runOwnedFixture(); - return new WorldRunOwnedFixtureLifecycleEvidence( - request, - fixture.fixtureProvenanceDigest(), - fixture.preparationInputDigest(), - required(row, "status", String.class), - required(row, "lifecycle_epoch", Long.class), - required(row, "row_version", Long.class)); + return new RunOwnedFixtureSnapshot( + association, + new WorldRunOwnedFixtureLifecycleEvidence( + request, + fixture.fixtureProvenanceDigest(), + fixture.preparationInputDigest(), + required(row, "status", String.class), + required(row, "lifecycle_epoch", Long.class), + required(row, "row_version", Long.class))); } catch (org.springframework.dao.DataAccessException | DataAccessException unavailable) { throw unavailable; } catch ( @@ -165,6 +197,51 @@ private WorldRunOwnedFixtureLifecycleEvidence readRunOwnedFixtureInCurrentOwnerT } } + private long requireRunOwnedFixtureStartRoom(WorldCanonicalInstanceAssociation association) { + var keys = association.runOwnedFixture().worldPrivateKeys(); + UUID templateId = RunOwnedWorldFixedPresetResources.starterRoomTemplateId(); + Record room = + dsl.fetchOne( + "SELECT m.runtime_room_instance_id,m.runtime_row_id,m.template_private_row_key," + + "r.id AS room_row_id,r.room_instance_row_id,r.template_room_id " + + "FROM world_canonical_instance_topology_identity m " + + "JOIN room_instance r ON r.id=m.runtime_row_id " + + "JOIN region_instance ri ON ri.id=r.region_instance_id " + + "JOIN zone_instance zi ON zi.id=r.zone_instance_id " + + "WHERE m.world_instance_id=? AND m.canonical_game_instance_id=? " + + "AND m.family='ROOM' AND m.template_id=? " + + "AND r.tenant_id=? AND r.game_instance_id=? " + + "AND ri.world_instance_id=? AND ri.tenant_id=? AND ri.game_instance_id=? " + + "AND zi.tenant_id=? AND zi.game_instance_id=? " + + "AND zi.region_instance_id=ri.id", + association.worldInstanceId(), + association.identity().canonicalGameInstanceId(), + templateId, + keys.tenantId(), + keys.gameInstanceId(), + association.worldInstanceId(), + keys.tenantId(), + keys.gameInstanceId(), + keys.tenantId(), + keys.gameInstanceId()); + if (room == null) { + throw invalid("Active run-owned fixture lacks its exact mapped scoped starter room"); + } + Long roomId = room.get("runtime_room_instance_id", Long.class); + Long templateRowId = room.get("template_private_row_key", Long.class); + if (roomId == null + || roomId <= 0 + || !roomId.equals(room.get("runtime_row_id", Long.class)) + || !roomId.equals(room.get("room_row_id", Long.class)) + || !roomId.equals(room.get("room_instance_row_id", Long.class)) + || templateRowId == null + || templateRowId <= 0 + || !templateRowId.equals(room.get("template_room_id", Long.class))) { + throw invalid("Run-owned fixture starter ROOM mapping differs from its actual runtime room"); + } + return roomId; + } + private boolean matchesFixtureRequest( WorldCanonicalInstanceLifecycleEvidence.Request request, WorldCanonicalInstanceAssociation association) { diff --git a/services/world-management-service/src/main/resources/application.yml b/services/world-management-service/src/main/resources/application.yml index b2b0839eeb..fb4069798e 100644 --- a/services/world-management-service/src/main/resources/application.yml +++ b/services/world-management-service/src/main/resources/application.yml @@ -93,6 +93,7 @@ firemud: - world_management.v1.WorldCanonicalInitialAdmissionHoldService/ReadCanonicalInitialAdmissionHoldIdentity - world_management.v1.WorldCanonicalInitialAdmissionHoldService/ReadCanonicalInitialAdmissionHoldState - world_management.v1.WorldCanonicalInstanceLifecycleReadService/ReadWorldCanonicalInstanceLifecycle + - world_management.v1.WorldCanonicalInstanceLifecycleReadService/ReadRunOwnedFixtureStartRoom grpc: cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResourcesPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResourcesPostgresIntegrationTest.java index 00ad23d7a2..c4533487c7 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResourcesPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResourcesPostgresIntegrationTest.java @@ -928,6 +928,21 @@ void activeFixtureAcquiresAndReadsTypedInitialAdmissionHoldWithFixtureLifecycle( new WorldCanonicalInitialAdmissionHoldRepository( dsl, transactionManager, associationRepository(), lifecycleRepository); + var room = lifecycleRepository.readRunOwnedFixtureStartRoom(lifecycleRequest).orElseThrow(); + var privateKeys = association.runOwnedFixture().worldPrivateKeys(); + long storedStartRoom = + dsl.fetchSingle( + "SELECT room_instance_row_id FROM room_instance " + + "WHERE tenant_id = ? AND game_instance_id = ? AND name = ?", + privateKeys.tenantId(), + privateKeys.gameInstanceId(), + "Candle-lit Antechamber") + .get(0, Long.class); + assertThat(room.roomKey()).isEqualTo("R-" + storedStartRoom); + assertThat(room.lifecycle()) + .isEqualTo(lifecycleRepository.readRunOwnedFixture(lifecycleRequest).orElseThrow()); + assertThat(room.lifecycle().lifecycleStatus()).isEqualTo("ACTIVE"); + var hold = holds.acquire(holdRequest, lifecycleRequest); assertThat(holds.acquire(holdRequest, lifecycleRequest)).isEqualTo(hold); var state = holds.readState(hold, lifecycleRequest).orElseThrow(); diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadGrpcServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadGrpcServiceTest.java index b1cf53af57..3a95485164 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadGrpcServiceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadGrpcServiceTest.java @@ -19,8 +19,11 @@ import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleGrpcCodec; +import net.firedevops.firemud.common.world.WorldRunOwnedFixtureLifecycleEvidence; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceLifecycleReadGrpcService; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceLifecycleReadRepository; +import net.firedevops.firemud.worldmanagement.v1.ReadRunOwnedFixtureStartRoomRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadRunOwnedFixtureStartRoomResponse; import net.firedevops.firemud.worldmanagement.v1.ReadWorldCanonicalInstanceLifecycleRequest; import net.firedevops.firemud.worldmanagement.v1.ReadWorldCanonicalInstanceLifecycleResponse; import org.junit.jupiter.api.Test; @@ -34,14 +37,14 @@ void rejectsActualOrSynchronizationTransactionBeforeParsingOrOwnerAccess() { var repository = mock(WorldCanonicalInstanceLifecycleReadRepository.class); var service = new WorldCanonicalInstanceLifecycleReadGrpcService(repository, "test"); var malformed = ReadWorldCanonicalInstanceLifecycleRequest.getDefaultInstance(); - Collector actual; + Collector actual; TransactionSynchronizationManager.setActualTransactionActive(true); try { actual = call(service, malformed, peer("game-session-service", "test")); } finally { TransactionSynchronizationManager.setActualTransactionActive(false); } - Collector synchronization; + Collector synchronization; TransactionSynchronizationManager.initSynchronization(); try { synchronization = call(service, malformed, peer("game-session-service", "test")); @@ -62,9 +65,9 @@ void rejectsWrongServiceOrNamespaceBeforeDecodingAndStorageAccess() { .setCanonicalRequestBytes(ByteString.copyFromUtf8("not-json")) .build(); - Collector wrongService = call(service, malformed, peer("account-service", "test")); - Collector wrongNamespace = call(service, malformed, peer("game-session-service", "other")); - Collector wrongRequestNamespace = + var wrongService = call(service, malformed, peer("account-service", "test")); + var wrongNamespace = call(service, malformed, peer("game-session-service", "other")); + var wrongRequestNamespace = call( service, WorldCanonicalInstanceLifecycleGrpcCodec.toRequest(request("other")), @@ -80,7 +83,7 @@ void rejectsMissingPeerIdentityAsUnauthenticatedBeforeStorageAccess() { var repository = mock(WorldCanonicalInstanceLifecycleReadRepository.class); var service = new WorldCanonicalInstanceLifecycleReadGrpcService(repository, "test"); - Collector result = + var result = call(service, ReadWorldCanonicalInstanceLifecycleRequest.getDefaultInstance(), null); assertThat(result.error).isEqualTo(Status.Code.UNAUTHENTICATED); @@ -92,7 +95,7 @@ void rejectsAuthenticatedEndUserContextBeforeDecodingOrStorageAccess() { var repository = mock(WorldCanonicalInstanceLifecycleReadRepository.class); var service = new WorldCanonicalInstanceLifecycleReadGrpcService(repository, "test"); SessionContext.setContext("11111111-1111-4111-8111-111111111111", List.of(), Map.of()); - Collector result; + Collector result; try { result = call( @@ -113,7 +116,7 @@ void exactSameNamespaceGameSessionPeerReachesOnlyExactLifecycleRequest() { var read = request("test"); when(repository.read(read)).thenReturn(Optional.empty()); - Collector result = + var result = call( service, WorldCanonicalInstanceLifecycleGrpcCodec.toRequest(read), @@ -131,7 +134,7 @@ void mapsSpringResourceFailureToUnavailableWithoutLeakingStorageDetails() { when(repository.read(read)) .thenThrow(new DataAccessResourceFailureException("private storage detail")); - Collector result = + var result = call( service, WorldCanonicalInstanceLifecycleGrpcCodec.toRequest(read), @@ -150,7 +153,7 @@ void mapsTransactionCreationFailureToUnavailableWithoutLeakingStorageDetails() { when(repository.read(read)) .thenThrow(new CannotCreateTransactionException("private transaction detail")); - Collector result = + var result = call( service, WorldCanonicalInstanceLifecycleGrpcCodec.toRequest(read), @@ -178,7 +181,7 @@ void classifiesJooqAndSpringStorageFailuresAtTheLifecycleRpcBoundary() { var read = request("test"); when(repository.read(read)).thenThrow(failure.failure); - Collector result = + var result = call( service, WorldCanonicalInstanceLifecycleGrpcCodec.toRequest(read), @@ -198,7 +201,7 @@ void mapsNonSqlTooManyRowsToFailedPreconditionWithoutLeakingDetails() { when(repository.read(read)) .thenThrow(new org.jooq.exception.TooManyRowsException("private duplicate evidence")); - Collector result = + var result = call( service, WorldCanonicalInstanceLifecycleGrpcCodec.toRequest(read), @@ -218,17 +221,62 @@ void authenticatedPeerWithMalformedRequestFailsBeforeStorageAccess() { .setCanonicalRequestBytes(ByteString.copyFromUtf8("not-json")) .build(); - Collector result = call(service, malformed, peer("game-session-service", "test")); + var result = call(service, malformed, peer("game-session-service", "test")); assertThat(result.error).isEqualTo(Status.Code.INVALID_ARGUMENT); verifyNoInteractions(repository); } - private static Collector call( + @Test + void fixtureStartRoomRequiresTheExactGameSessionPeerAndReturnsTheOwnerRoom() { + var repository = mock(WorldCanonicalInstanceLifecycleReadRepository.class); + var service = new WorldCanonicalInstanceLifecycleReadGrpcService(repository, "test"); + var read = request("test"); + var request = + ReadRunOwnedFixtureStartRoomRequest.newBuilder() + .setLifecycle(WorldCanonicalInstanceLifecycleGrpcCodec.toRequest(read)) + .build(); + + var rejected = new Collector(); + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer("game-logic-service", "test")) + .run(() -> service.readRunOwnedFixtureStartRoom(request, rejected)); + assertThat(rejected.error).isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(repository); + + var evidence = + new WorldRunOwnedFixtureLifecycleEvidence( + read, + read.expectedReleaseAttestationDigest(), + "sha256:" + "e".repeat(64), + "ACTIVE", + 3, + 4); + when(repository.readRunOwnedFixtureStartRoom(read)) + .thenReturn( + Optional.of( + new WorldCanonicalInstanceLifecycleReadRepository.FixtureStartRoom( + evidence, "R-37"))); + var admitted = new Collector(); + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer("game-session-service", "test")) + .run(() -> service.readRunOwnedFixtureStartRoom(request, admitted)); + + assertThat(admitted.error).isNull(); + assertThat(admitted.completed).isTrue(); + assertThat(admitted.value.getRoomInstanceKey()).isEqualTo("R-37"); + assertThat( + WorldCanonicalInstanceLifecycleGrpcCodec.fromFixtureResponse( + read, admitted.value.getLifecycle())) + .isEqualTo(evidence); + verify(repository).readRunOwnedFixtureStartRoom(read); + } + + private static Collector call( WorldCanonicalInstanceLifecycleReadGrpcService service, ReadWorldCanonicalInstanceLifecycleRequest request, GrpcPeerIdentity peer) { - Collector response = new Collector(); + var response = new Collector(); Context context = peer == null ? Context.ROOT @@ -277,15 +325,14 @@ private static org.springframework.dao.DataAccessException springFailure(String private record StorageFailureCase(Throwable failure, Status.Code expectedCode) {} - private static final class Collector - implements StreamObserver { - private ReadWorldCanonicalInstanceLifecycleResponse value; + private static final class Collector implements StreamObserver { + private T value; private Status.Code error; private String description; private boolean completed; @Override - public void onNext(ReadWorldCanonicalInstanceLifecycleResponse response) { + public void onNext(T response) { value = response; } From 934d9897ee56732405b9461d3a45162028698860 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 22 Nov 2026 23:46:30 +1300 Subject: [PATCH 06/28] Fence fixture admission against its retained OPEN completion --- .../game-session-service/runtime-and-data.md | 2 + ...layerAdmissionEntitlementEvidenceTest.java | 5 +- .../PreV1CanonicalPlayAdmissionOwner.java | 13 +- ...un_owned_fixture_binding_runtime_fence.sql | 147 ++++++++++++++++++ ...eFamilyCatalogPostgresIntegrationTest.java | 16 +- 5 files changed, 173 insertions(+), 10 deletions(-) create mode 100644 services/game-session-service/src/main/resources/db/migration/V1073__run_owned_fixture_binding_runtime_fence.sql 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 1c247aabfc..5890b9ec5b 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -165,6 +165,8 @@ The protected reservation retains the complete Account protection and original o The completed `RUNNING` row version is immutable provenance and a lower bound for later lease-bound decisions. An ordinary owner save may advance the current row version; each decision still requires the actual current `RUNNING` state, a version no earlier than completion, and every original launch, target, protection and terminal binding. A stopped runtime or changed source does not acquire authority through a later version number. +For the run-owned Compose fixture, the lease-bound decision uses the fixture policy seal and retained runtime completion. The runtime fence locks the exact current fixture row and checks its completion version, committed attempt, current OPEN pointer and matching audit identity. The same fence applies when the candidate becomes provisional and when its final receipt commits. + ### Persisted actor admission boundary Direct-text `CHARS` currently validates the Account identity and resolved realm target, then returns unavailable without invoking Entity's legacy roster adapter or accepting an `onCommand` event. Account bootstrap/HTTP character-roster discovery remains separate. The accepted contract remains in [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md), [Game Session protocols](./protocols.md), [Session Behavior](../../system-architecture-session-behavior.md), and [Authentication and authorization](../../system-architecture-authentication.md); implementation and proof status are tracked in [Realm Routing and Playable State](../../../project-management/implementation-tracking/realm-routing-and-playable-state.md) and [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidenceTest.java index 86bfd82222..39884b0510 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidenceTest.java @@ -125,8 +125,9 @@ void runOwnedFixtureSourceShapeRoundTripsAndStaysDistinctFromHuman() { assertThat(fixture.fields().get("target")).isEqualTo(human.fields().get("target")); var references = (Map) fixture.fields().get("sourceReferences"); assertThat(references.get("fixturePolicySealDigest")).isEqualTo("sha256:" + "c".repeat(64)); - assertThat(references.keySet()) - .doesNotContain("worldCaptureId", "publishedPolicySetDigest", "worldLifecycleDigest"); + assertThat(references.containsKey("worldCaptureId")).isFalse(); + assertThat(references.containsKey("publishedPolicySetDigest")).isFalse(); + assertThat(references.containsKey("worldLifecycleDigest")).isFalse(); assertThat(fixture.fields().get("snapshotIdentity")) .isNotEqualTo(human.fields().get("snapshotIdentity")); assertThat(RuntimePlayerAdmissionEntitlementEvidence.parseCanonical(fixture.canonicalBytes())) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayAdmissionOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayAdmissionOwner.java index 5a741149b4..6aad7f2e39 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayAdmissionOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayAdmissionOwner.java @@ -28,8 +28,10 @@ import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyScope; import org.jooq.DSLContext; +import org.postgresql.util.PSQLException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.core.NestedExceptionUtils; /** Composes ordinary NEW admission for the verified run-owned fixture. */ public final class PreV1CanonicalPlayAdmissionOwner { @@ -165,13 +167,15 @@ public Admitted play( new CanonicalGameplayAdmissionDecision( transitionId, lease, identity, generation, null, target); - phase = "candidate-and-indexes"; + phase = "candidate-install"; new CanonicalGameplayOriginalNewCandidateRedisOwner( standIns.coordination(), standIns.scripts(), inventory, standIns.tags()) .installOnce(decision); + phase = "account-index-repair"; new CanonicalGameplayAccountMemberRepairOwner( dsl, standIns.coordination(), standIns.scripts()) .repair(transitionId); + phase = "issuer-index-ack"; var projection = new CanonicalGameplayIssuerBindingLocalRedisOwner( standIns.coordination(), @@ -264,11 +268,16 @@ public Admitted play( } } catch (RuntimeException failure) { StackTraceElement[] trace = failure.getStackTrace(); + Throwable cause = NestedExceptionUtils.getMostSpecificCause(failure); + PSQLException postgres = cause instanceof PSQLException sql ? sql : null; + var databaseError = postgres == null ? null : postgres.getServerErrorMessage(); LOG.warn( - "Run-owned PLAY unavailable phase={} type={} grpcStatus={} source={}", + "Run-owned PLAY unavailable phase={} type={} grpcStatus={} sqlState={} constraint={} source={}", phase, failure.getClass().getSimpleName(), failure instanceof StatusRuntimeException rpc ? rpc.getStatus().getCode() : null, + postgres == null ? null : postgres.getSQLState(), + databaseError == null ? null : databaseError.getConstraint(), trace.length == 0 ? "unknown" : trace[0]); throw unavailable(); } diff --git a/services/game-session-service/src/main/resources/db/migration/V1073__run_owned_fixture_binding_runtime_fence.sql b/services/game-session-service/src/main/resources/db/migration/V1073__run_owned_fixture_binding_runtime_fence.sql new file mode 100644 index 0000000000..1da73bbb46 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1073__run_owned_fixture_binding_runtime_fence.sql @@ -0,0 +1,147 @@ +-- The retained completion and fixture policy seal identify this fixture's exact OPEN. +-- Keep the existing runtime lock, target checks and FINAL requirements for all sources. +-- [jooq ignore start] +CREATE FUNCTION gs_has_current_run_owned_fixture_binding_source( + decision game_session_canonical_binding_transition, + launch game_session_canonical_instance_launch, + runtime game_instances) +RETURNS BOOLEAN LANGUAGE SQL STABLE AS $$ + SELECT launch.fixture_policy_request_bytes IS NOT NULL + AND launch.original_start_session_tuple IS NULL + AND launch.fixture_policy_seal_evidence_digest IS NOT NULL + AND runtime.run_owned_start_request_id = launch.control_plane_request_id + AND decision.admission_target_owner_proof_outcome = 'COMMITTED' + AND decision.admission_target_positive_durable_abort IS FALSE + AND EXISTS ( + SELECT 1 + FROM game_session_run_owned_fixture_runtime_completion completion + JOIN game_session_canonical_initial_admission_attempt attempt + ON attempt.target_namespace = completion.target_namespace + AND attempt.initial_admission_request_id = completion.initial_admission_request_id + AND attempt.request_digest = completion.request_digest + AND attempt.fixture_provenance_digest = completion.fixture_provenance_digest + AND attempt.status = 'COMMITTED' + JOIN gameplay_admission_pointer pointer + ON pointer.id = attempt.pointer_id + AND pointer.representation_version = 3 + AND pointer.target_namespace = attempt.target_namespace + AND pointer.initial_admission_request_id = attempt.initial_admission_request_id + AND pointer.initial_admission_request_digest = attempt.request_digest + AND pointer.pointer_version = attempt.pointer_version + AND pointer.admission_state = 'OPEN' + JOIN gameplay_admission_pointer_event event + ON event.id = attempt.audit_event_id + AND event.representation_version = 3 + AND event.target_namespace = attempt.target_namespace + AND event.initial_admission_request_id = attempt.initial_admission_request_id + AND event.initial_admission_request_digest = attempt.request_digest + AND event.pointer_version = attempt.pointer_version + AND event.admission_state = 'OPEN' + WHERE completion.target_namespace = decision.admission_target_namespace + AND completion.initial_admission_request_id = decision.admission_target_initial_admission_request_id + AND completion.request_digest = decision.admission_target_initial_admission_request_digest + AND completion.canonical_tenant_id = decision.admission_target_tenant_id + AND completion.world_slug = decision.admission_target_world_slug + AND completion.realm_id = decision.admission_target_realm_id + AND completion.playable_state_namespace_id = decision.admission_target_playable_state_namespace_id + AND completion.playable_state_scope = decision.admission_target_playable_state_scope + AND completion.canonical_game_instance_id = decision.admission_target_canonical_game_instance_id + AND completion.canonical_version_id = decision.admission_target_canonical_version_id + AND completion.expected_catalog_revision = decision.admission_target_catalog_revision + AND completion.active_lifecycle_epoch = decision.admission_target_active_world_epoch + AND completion.origin_kind = decision.admission_target_origin_kind + AND completion.expected_prior_pointer_version IS NOT DISTINCT FROM + decision.admission_target_expected_prior_pointer_version + AND completion.hold_id = decision.admission_target_hold_id + AND completion.hold_fence = decision.admission_target_hold_fence + AND completion.hold_binding_digest = decision.admission_target_hold_binding_digest + AND completion.game_session_tenant_id = runtime.tenant_id + AND completion.game_instance_id = runtime.id + AND completion.control_plane_request_id = launch.control_plane_request_id + AND completion.captured_starting_row_version = launch.captured_starting_row_version + AND completion.completed_running_row_version = runtime.row_version + AND completion.fixture_provenance_digest = launch.fixture_policy_seal_evidence_digest + AND attempt.pointer_version = decision.admission_target_pointer_version + AND attempt.audit_event_id = decision.admission_target_audit_event_id + AND attempt.commit_proof_digest = decision.admission_target_owner_proof_digest + AND attempt.terminal_at = decision.admission_target_terminal_at + AND pointer.character_creation_policy = decision.admission_target_character_creation_policy + ) +$$; + +DO $migration$ +DECLARE definition TEXT; original TEXT; replacement TEXT; +BEGIN + SELECT pg_get_functiondef((quote_ident(current_schema()) + ||'.require_running_runtime_for_lease_bound_binding_decision()')::regprocedure) + INTO STRICT definition; + + original := $needle$ ( + -- Preserve the original run-owned source exactly for its owner route. + runtime.run_owned_start_active_epoch$needle$; + replacement := $replacement$ gs_has_current_run_owned_fixture_binding_source(NEW, launch, runtime) + OR ( + -- Preserve the original run-owned source exactly for its owner route. + launch.fixture_policy_request_bytes IS NULL + AND runtime.run_owned_start_active_epoch$replacement$; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact prior run-owned binding runtime clause'; END IF; + definition := replace(definition,original,replacement); + + original := $needle$ NEW.admission_target_owner_proof_outcome = 'COMMITTED' + AND NEW.admission_target_positive_durable_abort IS FALSE$needle$; + replacement := $replacement$ launch.fixture_policy_request_bytes IS NULL + AND NEW.admission_target_owner_proof_outcome = 'COMMITTED' + AND NEW.admission_target_positive_durable_abort IS FALSE$replacement$; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact Human binding runtime clause'; END IF; + definition := replace(definition,original,replacement); + + original := $needle$ AND launch.complete_launch_binding_evidence -> 'releaseAttestation' ->> 'canonicalVersionId' + = NEW.admission_target_canonical_version_id::text$needle$; + replacement := $replacement$ AND (launch.fixture_policy_request_bytes IS NOT NULL + OR launch.complete_launch_binding_evidence -> 'releaseAttestation' ->> 'canonicalVersionId' + = NEW.admission_target_canonical_version_id::text)$replacement$; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact binding runtime canonical version clause'; END IF; + EXECUTE replace(definition,original,replacement); +END; +$migration$; + +DO $migration$ +DECLARE definition TEXT; original TEXT; replacement TEXT; +BEGIN + SELECT pg_get_functiondef((quote_ident(current_schema())||'.gs_runtime_family_catalog_installed()')::regprocedure) INTO STRICT definition; + original := $needle$WHERE version='1072' + ) AND ($needle$; + replacement := $replacement$WHERE version='1072' + ) AND ( + SELECT count(*)=1 AND coalesce(bool_and(type='SQL' + AND script='V1073__run_owned_fixture_binding_runtime_fence.sql' AND success),false) + FROM "${flyway:table}" WHERE version='1073' + ) AND ($replacement$; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor catalog installation clause'; END IF; + EXECUTE replace(definition,original,replacement); + + SELECT pg_get_functiondef((quote_ident(current_schema())||'.gs_runtime_family_catalog_bytes(bigint)')::regprocedure) INTO STRICT definition; + original := $needle$AND version IS DISTINCT FROM '1072'$needle$; + replacement := original||E'\n AND version IS DISTINCT FROM ''1073'''; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor history exclusion'; END IF; + definition := replace(definition,original,replacement); + original := $needle$SELECT 'MIGRATION','catalog-installation:1072','V1072__run_owned_fixture_region_world_source_kind.sql'$needle$; + replacement := original||E'\n UNION ALL\n SELECT ''MIGRATION'',''catalog-installation:1073'',''V1073__run_owned_fixture_binding_runtime_fence.sql'''; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor catalog marker'; END IF; + EXECUTE replace(definition,original,replacement); +END; +$migration$; + +INSERT INTO game_session_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest) +SELECT epoch,bytes,'sha256:'||encode(sha256(bytes),'hex') FROM ( + SELECT epoch,gs_runtime_family_catalog_bytes(epoch) AS bytes FROM ( + SELECT coalesce(max(catalog_epoch),0)+1 AS epoch FROM game_session_runtime_family_catalog_epoch + ) next_epoch +) seal; +-- [jooq ignore stop] diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java index 8b68509f7f..dc29bb6572 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java @@ -97,7 +97,7 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB Map before = f.rows(f.tables()); var evidence = f.owner().capture(request()); var catalog = evidence.catalog(); - assertThat(catalog.catalogEpoch()).isEqualTo(26); + assertThat(catalog.catalogEpoch()).isEqualTo(27); assertThat( catalog.schemaFacts().stream() .filter(fact -> fact.kind() == FactKind.TABLE) @@ -227,7 +227,8 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB "catalog-installation:1066.1", "catalog-installation:1070", "catalog-installation:1071", - "catalog-installation:1072") + "catalog-installation:1072", + "catalog-installation:1073") .noneMatch( identity -> identity.contains(":1057:") @@ -255,7 +256,8 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB || identity.contains(":1066.1:") || identity.contains(":1070:") || identity.contains(":1071:") - || identity.contains(":1072:")); + || identity.contains(":1072:") + || identity.contains(":1073:")); assertThat( f.dsl .fetchSingle( @@ -959,7 +961,8 @@ void priorAndLaterHistoryAndOwnSuccessfulScriptRemainSeparateInstallationChecks( "1066.1", "1070", "1071", - "1072")) { + "1072", + "1073")) { for (String change : List.of("success=false", "script='wrong_installation.sql'", "type='JDBC'")) { try (Fixture f = fixture(null)) { @@ -982,7 +985,7 @@ void priorAndLaterHistoryAndOwnSuccessfulScriptRemainSeparateInstallationChecks( "INSERT INTO " + f.history + "(installed_rank,version,description,type,script,checksum,installed_by,execution_time,success)" - + " VALUES(10000,'1071','controlled later migration','SQL','V1071__probe.sql',1,current_user,0,true)"); + + " VALUES(10000,'1074','controlled later migration','SQL','V1074__probe.sql',1,current_user,0,true)"); assertThatThrownBy(() -> f.owner().readExact(original.request())) .isInstanceOf(GameSessionRuntimeFamilyCatalogRepository.CatalogConflictException.class); } @@ -1013,7 +1016,8 @@ void priorAndLaterHistoryAndOwnSuccessfulScriptRemainSeparateInstallationChecks( "1066.1", "1070", "1071", - "1072")) { + "1072", + "1073")) { try (Fixture f = fixture(null)) { f.dsl.execute( "INSERT INTO " From aab5b3ba44da7f7c139a0e5693aeea4a9f1ea222 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 23 Nov 2026 00:02:22 +1300 Subject: [PATCH 07/28] Preserve the run-owned fixture completion version floor --- .../game-session-service/runtime-and-data.md | 2 +- ...owned_fixture_completion_version_floor.sql | 49 +++++++ ...xtureFirstOpenPostgresIntegrationTest.java | 134 +++++++++++++++++- ...eFamilyCatalogPostgresIntegrationTest.java | 18 ++- 4 files changed, 194 insertions(+), 9 deletions(-) create mode 100644 services/game-session-service/src/main/resources/db/migration/V1074__run_owned_fixture_completion_version_floor.sql 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 5890b9ec5b..42a34df66c 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -165,7 +165,7 @@ The protected reservation retains the complete Account protection and original o The completed `RUNNING` row version is immutable provenance and a lower bound for later lease-bound decisions. An ordinary owner save may advance the current row version; each decision still requires the actual current `RUNNING` state, a version no earlier than completion, and every original launch, target, protection and terminal binding. A stopped runtime or changed source does not acquire authority through a later version number. -For the run-owned Compose fixture, the lease-bound decision uses the fixture policy seal and retained runtime completion. The runtime fence locks the exact current fixture row and checks its completion version, committed attempt, current OPEN pointer and matching audit identity. The same fence applies when the candidate becomes provisional and when its final receipt commits. +For the run-owned Compose fixture, the lease-bound decision uses the fixture policy seal and retained runtime completion. The runtime fence locks the exact current fixture row, checks that its version is at least the completion version, and verifies the committed attempt, current OPEN pointer and matching audit identity. The same fence applies when the candidate becomes provisional and when its final receipt commits. ### Persisted actor admission boundary diff --git a/services/game-session-service/src/main/resources/db/migration/V1074__run_owned_fixture_completion_version_floor.sql b/services/game-session-service/src/main/resources/db/migration/V1074__run_owned_fixture_completion_version_floor.sql new file mode 100644 index 0000000000..307ad400e8 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1074__run_owned_fixture_completion_version_floor.sql @@ -0,0 +1,49 @@ +-- Preserve the exact fixture completion as a floor for the current RUNNING row. +-- [jooq ignore start] +DO $migration$ +DECLARE definition TEXT; original TEXT; replacement TEXT; +BEGIN + SELECT pg_get_functiondef((quote_ident(current_schema()) + ||'.gs_has_current_run_owned_fixture_binding_source(game_session_canonical_binding_transition,game_session_canonical_instance_launch,game_instances)')::regprocedure) + INTO STRICT definition; + original := 'completion.completed_running_row_version = runtime.row_version'; + replacement := 'completion.completed_running_row_version <= runtime.row_version'; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact fixture completion version clause'; + END IF; + EXECUTE replace(definition,original,replacement); + + SELECT pg_get_functiondef((quote_ident(current_schema())||'.gs_runtime_family_catalog_installed()')::regprocedure) INTO STRICT definition; + original := $needle$WHERE version='1073' + ) AND ($needle$; + replacement := $replacement$WHERE version='1073' + ) AND ( + SELECT count(*)=1 AND coalesce(bool_and(type='SQL' + AND script='V1074__run_owned_fixture_completion_version_floor.sql' AND success),false) + FROM "${flyway:table}" WHERE version='1074' + ) AND ($replacement$; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor catalog installation clause'; END IF; + EXECUTE replace(definition,original,replacement); + + SELECT pg_get_functiondef((quote_ident(current_schema())||'.gs_runtime_family_catalog_bytes(bigint)')::regprocedure) INTO STRICT definition; + original := $needle$AND version IS DISTINCT FROM '1073'$needle$; + replacement := original||E'\n AND version IS DISTINCT FROM ''1074'''; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor history exclusion'; END IF; + definition := replace(definition,original,replacement); + original := $needle$SELECT 'MIGRATION','catalog-installation:1073','V1073__run_owned_fixture_binding_runtime_fence.sql'$needle$; + replacement := original||E'\n UNION ALL\n SELECT ''MIGRATION'',''catalog-installation:1074'',''V1074__run_owned_fixture_completion_version_floor.sql'''; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor catalog marker'; END IF; + EXECUTE replace(definition,original,replacement); +END; +$migration$; + +INSERT INTO game_session_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest) +SELECT epoch,bytes,'sha256:'||encode(sha256(bytes),'hex') FROM ( + SELECT epoch,gs_runtime_family_catalog_bytes(epoch) AS bytes FROM ( + SELECT coalesce(max(catalog_epoch),0)+1 AS epoch FROM game_session_runtime_family_catalog_epoch + ) next_epoch +) seal; +-- [jooq ignore stop] diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRunOwnedFixtureFirstOpenPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRunOwnedFixtureFirstOpenPostgresIntegrationTest.java index d065947caa..37eb423a95 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRunOwnedFixtureFirstOpenPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRunOwnedFixtureFirstOpenPostgresIntegrationTest.java @@ -259,6 +259,134 @@ void commitsFixtureFirstOpenThroughExactOwnersWithoutAccountProtection() { assertThat(targets.get(0).realmId()).isEqualTo(catalog.realmId()); assertThat(targets.get(0).initialAdmissionRequestId()).isEqualTo(requestId); assertThat(targets.get(0).activeWorldEpoch()).isEqualTo(ACTIVE_EPOCH); + + long completedVersion = completion.completedRunningRowVersion(); + String pointerSnapshotDigest = snapshot.admissionPointerSnapshotDigest(); + assertThat(hasFixtureBindingSource(f, requestId, pointerSnapshotDigest, completedVersion, 0L)) + .isTrue(); + // An older candidate runtime cannot use a completion from its future. Only the supplied + // composite changes here; retained runtime/completion/pointer evidence is not rewritten. + assertThat( + hasFixtureBindingSource(f, requestId, pointerSnapshotDigest, completedVersion - 1, 0L)) + .isFalse(); + assertThat(hasFixtureBindingSource(f, requestId, pointerSnapshotDigest, completedVersion, 1L)) + .isFalse(); + + // The runtime mutation guard permits a monotonic row-version advance without changing the + // RUNNING identity. Completion remains historical provenance, not an equality fence. + f.transactions.executeWithoutResult( + status -> + assertThat( + f.dsl.execute( + "UPDATE game_instances SET row_version = row_version + 1 " + + "WHERE tenant_id = ? AND id = ? AND status = 'RUNNING' " + + "AND row_version = ?", + association.gameSessionTenantId(), + launch.gameInstanceId(), + completedVersion)) + .isEqualTo(1)); + assertThat(runtimeStatus(f, association.gameSessionTenantId(), launch.gameInstanceId())) + .isEqualTo("RUNNING"); + assertThat( + f.dsl + .fetchSingle( + "SELECT row_version FROM game_instances WHERE tenant_id = ? AND id = ?", + association.gameSessionTenantId(), + launch.gameInstanceId()) + .get(0, Long.class)) + .isEqualTo(completedVersion + 1); + assertThat( + hasFixtureBindingSource(f, requestId, pointerSnapshotDigest, completedVersion + 1, 0L)) + .isFalse(); + CanonicalGameplayIssuerTestFixtures.migrateSchema( + f.dataSource, f.schema, MIGRATION_LOCATION, "1074"); + assertThat(replayCompletion(f, request, worldProof)).isEqualTo(completion); + assertThat( + f.admissions.readCurrentOpenSnapshotForRealm( + NAMESPACE, catalog.tenantId(), catalog.realmId())) + .isEqualTo(snapshot); + assertThat( + hasFixtureBindingSource(f, requestId, pointerSnapshotDigest, completedVersion + 1, 0L)) + .isTrue(); + assertThat( + hasFixtureBindingSource(f, requestId, pointerSnapshotDigest, completedVersion + 1, 1L)) + .isFalse(); + } + + /** + * Calls the installed predicate with a complete owner-derived target, without inserting a + * binding. + */ + private static boolean hasFixtureBindingSource( + Fixture f, + String requestId, + String pointerSnapshotDigest, + long runtimeRowVersion, + long pointerVersionOffset) { + return f.dsl + .fetchSingle( + """ + SELECT gs_has_current_run_owned_fixture_binding_source( + jsonb_populate_record(NULL::game_session_canonical_binding_transition, + jsonb_build_object( + 'admission_target_namespace', attempt.target_namespace, + 'admission_target_tenant_slug', catalog.tenant_slug, + 'admission_target_tenant_id', attempt.canonical_tenant_id, + 'admission_target_world_slug', attempt.world_slug, + 'admission_target_world_display_name', catalog.source_world_display_name, + 'admission_target_realm_id', attempt.realm_id, + 'admission_target_realm_slug', catalog.realm_slug, + 'admission_target_realm_display_name', catalog.realm_display_name, + 'admission_target_game_session_tenant_id', attempt.game_session_tenant_id, + 'admission_target_game_instance_id', attempt.game_instance_id, + 'admission_target_playable_state_namespace_id', attempt.playable_state_namespace_id, + 'admission_target_playable_state_scope', attempt.playable_state_scope, + 'admission_target_canonical_game_instance_id', attempt.canonical_game_instance_id, + 'admission_target_canonical_version_id', attempt.canonical_version_id, + 'admission_target_runtime_version_id', attempt.runtime_version_id, + 'admission_target_catalog_revision', attempt.expected_catalog_revision, + 'admission_target_pointer_version', attempt.pointer_version + CAST(? AS bigint), + 'admission_target_pointer_snapshot_digest', CAST(? AS text), + 'admission_target_active_world_epoch', attempt.active_lifecycle_epoch, + 'admission_target_initial_admission_request_id', attempt.initial_admission_request_id, + 'admission_target_initial_admission_request_digest', attempt.request_digest, + 'admission_target_origin_kind', attempt.origin_kind, + 'admission_target_expected_prior_pointer_version', attempt.expected_prior_pointer_version, + 'admission_target_hold_id', attempt.hold_id, + 'admission_target_hold_fence', attempt.hold_fence, + 'admission_target_hold_binding_digest', attempt.hold_binding_digest, + 'admission_target_audit_event_id', attempt.audit_event_id, + 'admission_target_owner_proof_digest', attempt.commit_proof_digest, + 'admission_target_owner_proof_outcome', attempt.status, + 'admission_target_positive_durable_abort', false, + 'admission_target_terminal_at', attempt.terminal_at, + 'admission_target_character_creation_policy', pointer.character_creation_policy)), + launch, + jsonb_populate_record(NULL::game_instances, + to_jsonb(runtime) || jsonb_build_object('row_version', CAST(? AS bigint)))) + FROM game_session_canonical_initial_admission_attempt attempt + JOIN game_session_run_owned_fixture_runtime_completion completion + ON completion.target_namespace = attempt.target_namespace + AND completion.initial_admission_request_id = attempt.initial_admission_request_id + JOIN gameplay_admission_pointer pointer ON pointer.id = attempt.pointer_id + JOIN game_session_canonical_instance_launch launch + ON launch.target_namespace = completion.target_namespace + AND launch.game_instance_uuid = completion.canonical_game_instance_id + JOIN game_instances runtime + ON runtime.tenant_id = completion.game_session_tenant_id + AND runtime.id = completion.game_instance_id + JOIN game_session_canonical_realm_catalog catalog + ON catalog.target_namespace = attempt.target_namespace + AND catalog.canonical_tenant_id = attempt.canonical_tenant_id + AND catalog.realm_id = attempt.realm_id + WHERE attempt.target_namespace = ? AND attempt.initial_admission_request_id = ? + """, + pointerVersionOffset, + pointerSnapshotDigest, + runtimeRowVersion, + NAMESPACE, + requestId) + .get(0, boolean.class); } private static boolean flag(Fixture f, java.util.function.Supplier owner) { @@ -404,7 +532,7 @@ private static Fixture fixture() { dataSource.setUsername(postgres.getUsername()); dataSource.setPassword(postgres.getPassword()); dataSource.setSchema(schema); - CanonicalGameplayIssuerTestFixtures.migrateSchema(dataSource, schema, MIGRATION_LOCATION, null); + CanonicalGameplayIssuerTestFixtures.migrateSchema(dataSource, schema, MIGRATION_LOCATION, "1073"); DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); TransactionTemplate transactions = new TransactionTemplate(transactionManager); @@ -418,6 +546,8 @@ private static Fixture fixture() { new GameSessionCanonicalAdmissionPointerRepository( dsl, catalogs, new GameplayAdmissionPointerEventRepository(dsl)); return new Fixture( + dataSource, + schema, dsl, transactions, new GameSessionAuthoredWorldSourceRepository(dsl), @@ -432,6 +562,8 @@ private static Fixture fixture() { } private record Fixture( + DriverManagerDataSource dataSource, + String schema, DSLContext dsl, TransactionTemplate transactions, GameSessionAuthoredWorldSourceRepository sources, diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java index dc29bb6572..37ddc6318f 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java @@ -97,7 +97,7 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB Map before = f.rows(f.tables()); var evidence = f.owner().capture(request()); var catalog = evidence.catalog(); - assertThat(catalog.catalogEpoch()).isEqualTo(27); + assertThat(catalog.catalogEpoch()).isEqualTo(28); assertThat( catalog.schemaFacts().stream() .filter(fact -> fact.kind() == FactKind.TABLE) @@ -228,7 +228,8 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB "catalog-installation:1070", "catalog-installation:1071", "catalog-installation:1072", - "catalog-installation:1073") + "catalog-installation:1073", + "catalog-installation:1074") .noneMatch( identity -> identity.contains(":1057:") @@ -257,7 +258,8 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB || identity.contains(":1070:") || identity.contains(":1071:") || identity.contains(":1072:") - || identity.contains(":1073:")); + || identity.contains(":1073:") + || identity.contains(":1074:")); assertThat( f.dsl .fetchSingle( @@ -800,7 +802,7 @@ void viewOptionsDriftRefusesReadsRetriesAndNewRequestsWithoutChangingRetainedRow "CREATE MATERIALIZED VIEW catalog_probe_materialized AS SELECT id,description FROM game_manifest WITH NO DATA"); migration(f.source, f.schema, f.history, null).migrate(); var original = f.owner().capture(request()); - assertThat(original.catalog().catalogEpoch()).isEqualTo(26); + assertThat(original.catalog().catalogEpoch()).isEqualTo(28); assertThat(original.catalog().schemaFacts()) .anyMatch( fact -> @@ -962,7 +964,8 @@ void priorAndLaterHistoryAndOwnSuccessfulScriptRemainSeparateInstallationChecks( "1070", "1071", "1072", - "1073")) { + "1073", + "1074")) { for (String change : List.of("success=false", "script='wrong_installation.sql'", "type='JDBC'")) { try (Fixture f = fixture(null)) { @@ -985,7 +988,7 @@ void priorAndLaterHistoryAndOwnSuccessfulScriptRemainSeparateInstallationChecks( "INSERT INTO " + f.history + "(installed_rank,version,description,type,script,checksum,installed_by,execution_time,success)" - + " VALUES(10000,'1074','controlled later migration','SQL','V1074__probe.sql',1,current_user,0,true)"); + + " VALUES(10000,'1075','controlled later migration','SQL','V1075__probe.sql',1,current_user,0,true)"); assertThatThrownBy(() -> f.owner().readExact(original.request())) .isInstanceOf(GameSessionRuntimeFamilyCatalogRepository.CatalogConflictException.class); } @@ -1017,7 +1020,8 @@ void priorAndLaterHistoryAndOwnSuccessfulScriptRemainSeparateInstallationChecks( "1070", "1071", "1072", - "1073")) { + "1073", + "1074")) { try (Fixture f = fixture(null)) { f.dsl.execute( "INSERT INTO " From 3ef0eb5d8b253495d689a80d5fdbfa9aaca6c1a1 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 23 Nov 2026 00:02:22 +1300 Subject: [PATCH 08/28] Reserve issuer capacity before fixture PLAY becomes provisional --- .../PreV1CanonicalPlayAdmissionOwner.java | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayAdmissionOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayAdmissionOwner.java index 6aad7f2e39..e4100b2e36 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayAdmissionOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayAdmissionOwner.java @@ -149,6 +149,15 @@ public Admitted play( throw unavailable(); } + phase = "issuer-capacity-reservation"; + var issuerProjection = + new CanonicalGameplayIssuerBindingLocalRedisOwner( + standIns.coordination(), + standIns.scripts(), + new CanonicalGameplayIssuerBindingLocalProjectionRepository(dsl, issuerSource), + issuerSource); + issuerProjection.projectAndRead(operation); + phase = "account-admission-lease"; byte[] compact = login.compactJwtBytes(); try { @@ -176,13 +185,7 @@ public Admitted play( dsl, standIns.coordination(), standIns.scripts()) .repair(transitionId); phase = "issuer-index-ack"; - var projection = - new CanonicalGameplayIssuerBindingLocalRedisOwner( - standIns.coordination(), - standIns.scripts(), - new CanonicalGameplayIssuerBindingLocalProjectionRepository(dsl, issuerSource), - issuerSource) - .projectAndRead(operation); + var projection = issuerProjection.projectAndRead(operation); new CanonicalGameplayIssuerBindingLocalAcknowledgementRepository(dsl, issuerSource) .acknowledge(projection); From af6077fbfb64781813f9b2852a316a8d227815f6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 23 Nov 2026 00:24:47 +1300 Subject: [PATCH 09/28] Authenticate tenant capacity on the shared Account service --- ...meplayAdmissionReceiversConfiguration.java | 15 ++++++++++++++ .../AccountTenantCapacityWorkloadGuard.java | 20 ++++++++++++++----- .../service/impl/AccountGrpcService.java | 8 +++++--- .../AccountTenantCapacityGrpcService.java | 7 ++++++- .../PreV1CanonicalPlayAdmissionOwner.java | 8 ++++---- ...xtureFirstOpenPostgresIntegrationTest.java | 3 ++- 6 files changed, 47 insertions(+), 14 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountGameplayAdmissionReceiversConfiguration.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountGameplayAdmissionReceiversConfiguration.java index 1b72ca6c1b..baee06d334 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountGameplayAdmissionReceiversConfiguration.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountGameplayAdmissionReceiversConfiguration.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.accountservice.config; import io.grpc.BindableService; +import io.grpc.ServerInterceptor; import io.grpc.ServerInterceptors; import java.time.Clock; import javax.sql.DataSource; @@ -21,6 +22,7 @@ import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.security.AccountTenantCapacityWorkloadGuard; import net.firedevops.firemud.accountservice.service.AccountPlayerAdmissionEntitlementOwner; import net.firedevops.firemud.accountservice.service.AccountTenantCapacityOwner; import net.firedevops.firemud.accountservice.service.impl.AccountPlayerAdmissionEntitlementGrpcService; @@ -42,6 +44,7 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.grpc.server.GlobalServerInterceptor; import org.springframework.transaction.PlatformTransactionManager; /** @@ -156,6 +159,18 @@ BindableService accountPlayerAdmissionEntitlementReceiver( return new AccountPlayerAdmissionEntitlementGrpcService(owner, namespace)::bindProtectedService; } + @Bean + AccountTenantCapacityWorkloadGuard accountTenantCapacityWorkloadGuard( + @Value("${firemud.grpc.workload-namespace:}") String namespace) { + return new AccountTenantCapacityWorkloadGuard(namespace); + } + + @Bean + @GlobalServerInterceptor + ServerInterceptor accountTenantCapacityInterceptor(AccountTenantCapacityWorkloadGuard guard) { + return guard::interceptSharedServiceCall; + } + @Bean AccountTenantCapacityOwner accountTenantCapacityOwner( DSLContext dsl, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuard.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuard.java index 88e1694a6f..7c63c8175f 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuard.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuard.java @@ -36,22 +36,32 @@ public String requireAuthenticatedCaller() { return value; } + public ServerCall.Listener interceptSharedServiceCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + if (isCapacityCommit(call)) { + return interceptCall(call, headers, next); + } + return next.startCall(call, headers); + } + @Override public ServerCall.Listener interceptCall( ServerCall call, Metadata headers, ServerCallHandler next) { var peer = GrpcPeerIdentity.fromSslSession(call.getAttributes().get(Grpc.TRANSPORT_ATTR_SSL_SESSION)); if (peer.isEmpty()) return deny(call, Status.UNAUTHENTICATED); - if (ambient() - || !allowed.contains(peer.orElseThrow().uri()) - || !AccountServiceGrpc.getCommitTenantCapacityAdmissionMethod() - .getFullMethodName() - .equals(call.getMethodDescriptor().getFullMethodName())) + if (ambient() || !allowed.contains(peer.orElseThrow().uri()) || !isCapacityCommit(call)) return deny(call, Status.PERMISSION_DENIED); return Contexts.interceptCall( Context.current().withValue(caller, peer.orElseThrow().uri()), call, headers, next); } + private static boolean isCapacityCommit(ServerCall call) { + return AccountServiceGrpc.getCommitTenantCapacityAdmissionMethod() + .getFullMethodName() + .equals(call.getMethodDescriptor().getFullMethodName()); + } + private static boolean ambient() { return SessionContext.hasAuthenticatedCallerContext() || SessionContext.isInternalService() diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java index e6ab7861a4..ce9b5f0d42 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java @@ -49,7 +49,9 @@ import net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest; import net.firedevops.firemud.accountservice.dto.PasswordResetRequest; import net.firedevops.firemud.accountservice.entity.ProfilePresenceVisibilityPolicy; +import net.firedevops.firemud.accountservice.security.AccountTenantCapacityWorkloadGuard; import net.firedevops.firemud.accountservice.service.AccountService; +import net.firedevops.firemud.accountservice.service.AccountTenantCapacityOwner; import net.firedevops.firemud.accountservice.service.PingService; import net.firedevops.firemud.accountservice.service.exception.AccountAlreadyExistsException; import net.firedevops.firemud.accountservice.service.exception.AccountLifecycleException; @@ -102,13 +104,13 @@ void canonicalGameplayReceiver(ObjectProvider - owner) { + ObjectProvider owner, + ObjectProvider guard) { var available = owner.getIfAvailable(); tenantCapacity = available == null ? null - : new AccountTenantCapacityGrpcService(available, workloadNamespace); + : new AccountTenantCapacityGrpcService(available, guard.getObject()); } @Override diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcService.java index 02b92e229b..250a1eeaf0 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcService.java @@ -29,8 +29,13 @@ public final class AccountTenantCapacityGrpcService private final AccountTenantCapacityWorkloadGuard guard; public AccountTenantCapacityGrpcService(AccountTenantCapacityOwner owner, String namespace) { + this(owner, new AccountTenantCapacityWorkloadGuard(namespace)); + } + + public AccountTenantCapacityGrpcService( + AccountTenantCapacityOwner owner, AccountTenantCapacityWorkloadGuard guard) { this.owner = Objects.requireNonNull(owner); - guard = new AccountTenantCapacityWorkloadGuard(namespace); + this.guard = Objects.requireNonNull(guard); } public Server createUnregisteredServer( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayAdmissionOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayAdmissionOwner.java index e4100b2e36..a8a288e7c3 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayAdmissionOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayAdmissionOwner.java @@ -1,6 +1,6 @@ package net.firedevops.firemud.gamesession.repository; -import io.grpc.StatusRuntimeException; +import io.grpc.Status; import io.lettuce.core.RedisURI; import java.math.BigInteger; import java.nio.charset.StandardCharsets; @@ -270,15 +270,15 @@ public Admitted play( Arrays.fill(compact, (byte) 0); } } catch (RuntimeException failure) { - StackTraceElement[] trace = failure.getStackTrace(); Throwable cause = NestedExceptionUtils.getMostSpecificCause(failure); + StackTraceElement[] trace = cause.getStackTrace(); PSQLException postgres = cause instanceof PSQLException sql ? sql : null; var databaseError = postgres == null ? null : postgres.getServerErrorMessage(); LOG.warn( "Run-owned PLAY unavailable phase={} type={} grpcStatus={} sqlState={} constraint={} source={}", phase, - failure.getClass().getSimpleName(), - failure instanceof StatusRuntimeException rpc ? rpc.getStatus().getCode() : null, + cause.getClass().getSimpleName(), + Status.fromThrowable(failure).getCode(), postgres == null ? null : postgres.getSQLState(), databaseError == null ? null : databaseError.getConstraint(), trace.length == 0 ? "unknown" : trace[0]); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRunOwnedFixtureFirstOpenPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRunOwnedFixtureFirstOpenPostgresIntegrationTest.java index 37eb423a95..8482823f5a 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRunOwnedFixtureFirstOpenPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRunOwnedFixtureFirstOpenPostgresIntegrationTest.java @@ -532,7 +532,8 @@ private static Fixture fixture() { dataSource.setUsername(postgres.getUsername()); dataSource.setPassword(postgres.getPassword()); dataSource.setSchema(schema); - CanonicalGameplayIssuerTestFixtures.migrateSchema(dataSource, schema, MIGRATION_LOCATION, "1073"); + CanonicalGameplayIssuerTestFixtures.migrateSchema( + dataSource, schema, MIGRATION_LOCATION, "1073"); DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); TransactionTemplate transactions = new TransactionTemplate(transactionManager); From e2eff6bf3e0ed88087eb97f8e169bc41ac863029 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 23 Nov 2026 00:34:11 +1300 Subject: [PATCH 10/28] Establish player capacity in the run-owned fixture birth transaction --- .../player-access-and-session.md | 2 +- ...unOwnedFixtureDemoTenantConfiguration.java | 1 - ...wnedFixtureDemoTenantEnrollmentDriver.java | 97 ++++++++---- .../FreshTenantIdentityEnrollmentService.java | 14 ++ ...un_owned_fixture_player_capacity_birth.sql | 138 ++++++++++++++++++ ...acityMigrationPostgresIntegrationTest.java | 101 ++++++++++++- 6 files changed, 320 insertions(+), 33 deletions(-) create mode 100644 services/account-service/src/main/resources/db/migration/V1048__run_owned_fixture_player_capacity_birth.sql 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 50ee5276f4..b1505779c6 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -28,7 +28,7 @@ Under ADR 0185 (no data carry-over before v1, proposed in #3459), Compose smoke | World runtime installation for the run-owned Compose fixture is read from a root-owned inventory file (`PreV1ComposeRuntimeInstallationSource`) | A deployed installation controller that holds the completed installation and its workload incarnations through each launch commit | | Account signer promotion uses self-attested validator readiness (`PreV1SelfAttestedReadinessDriver`) | A Pod-bound readiness receiver client and orchestrator that verifies each validator Pod's acceptance | | The run-owned Compose fixture tenant is enrolled into Account from the Game Design receipt as a locator plus the authenticated `ResolveFreshTenantCreation` readback, with a provisioned demo entitlement (`RunOwnedFixtureDemoTenantEnrollmentDriver`) | The Account tenant-creation coordinator and an operator-provisioned entitlement for real tenants | -| The authenticated direct-text PLAY composition uses the run-owned fixture's scoped issuer, Coordination, actor, placement and capacity-budget stand-ins | Deployed Account JWT signer and public-JWKS binding, protected Coordination Redis and qualification authority, production Entity actor and World placement owners, and owner-provisioned quota budgets | +| The authenticated direct-text PLAY composition uses the run-owned fixture's scoped issuer, Coordination, actor, placement and capacity-budget stand-ins and the same-transaction player usage baseline | Deployed Account JWT signer and public-JWKS binding, protected Coordination Redis and qualification authority, production Entity actor and World placement owners, owner-provisioned quota budgets, and Account creator completion for fresh production tenant capacity | ### Direct-text scope and JOIN identifier cutover diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/RunOwnedFixtureDemoTenantConfiguration.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/RunOwnedFixtureDemoTenantConfiguration.java index 45029dde00..b14f79aad8 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/RunOwnedFixtureDemoTenantConfiguration.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/RunOwnedFixtureDemoTenantConfiguration.java @@ -63,7 +63,6 @@ RunOwnedFixtureDemoTenantEnrollmentDriver runOwnedFixtureDemoTenantEnrollmentDri demos, dsl, PreV1GateWaivers.from(environment).enabled(), - transactions, Path.of(capabilityPath), Path.of(receiptPath), runId, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/RunOwnedFixtureDemoTenantEnrollmentDriver.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/RunOwnedFixtureDemoTenantEnrollmentDriver.java index 7a18127999..cc864f6518 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/RunOwnedFixtureDemoTenantEnrollmentDriver.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/RunOwnedFixtureDemoTenantEnrollmentDriver.java @@ -12,21 +12,19 @@ import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; import net.firedevops.firemud.accountservice.service.FreshTenantIdentityEnrollmentService; import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec; +import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec.SourceReceipt; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import org.jooq.DSLContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.TransactionDefinition; -import org.springframework.transaction.support.TransactionTemplate; /** * Enrolls the run-owned Compose fixture's fresh Game Design tenant into Account and provisions its * non-paid demo entitlement, so public REALMS and JOIN can admit players to it. The fixture receipt * only locates the creation; Account imports the authenticated Game Design readback. Retries until * Game Design has committed the fixture, and replays idempotently after a restart. Under the pre-v1 - * gate waivers it also provisions the tenant's capacity-origin refusal budget for canonical PLAY. + * gate waivers it also establishes the fresh fixture's player usage and refusal budget for PLAY. */ public final class RunOwnedFixtureDemoTenantEnrollmentDriver { private static final Logger LOG = @@ -40,8 +38,7 @@ public final class RunOwnedFixtureDemoTenantEnrollmentDriver { private final FreshTenantIdentityEnrollmentService enrollment; private final AccountDemoTenantEntitlementRepository demos; private final DSLContext dsl; - private final boolean preV1RefusalBudget; - private final TransactionTemplate transaction; + private final boolean preV1Waivers; private final Path capabilityPath; private final Path receiptPath; private final String runId; @@ -52,8 +49,7 @@ public RunOwnedFixtureDemoTenantEnrollmentDriver( FreshTenantIdentityEnrollmentService enrollment, AccountDemoTenantEntitlementRepository demos, DSLContext dsl, - boolean preV1RefusalBudget, - PlatformTransactionManager transactions, + boolean preV1Waivers, Path capabilityPath, Path receiptPath, String runId, @@ -61,14 +57,11 @@ public RunOwnedFixtureDemoTenantEnrollmentDriver( this.enrollment = Objects.requireNonNull(enrollment, "enrollment"); this.demos = Objects.requireNonNull(demos, "demos"); this.dsl = Objects.requireNonNull(dsl, "dsl"); - this.preV1RefusalBudget = preV1RefusalBudget; + this.preV1Waivers = preV1Waivers; this.capabilityPath = Objects.requireNonNull(capabilityPath, "capabilityPath"); this.receiptPath = Objects.requireNonNull(receiptPath, "receiptPath"); this.runId = requireText(runId, "runId"); this.composeProjectName = requireText(composeProjectName, "composeProjectName"); - transaction = new TransactionTemplate(Objects.requireNonNull(transactions, "transactions")); - transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); } @Scheduled(initialDelay = RETRY_INTERVAL_MS, fixedDelay = RETRY_INTERVAL_MS) @@ -101,9 +94,26 @@ FreshTenantCreationEvidence enroll() throws IOException { var receipt = RunOwnedInitialAdmissionFixtureWireCodec.parseSourceReceipt(read(receiptPath), capability); FreshTenantCreationEvidence located = Objects.requireNonNull(receipt.creationEvidence()); - // The receipt is an untrusted locator; the import uses Game Design's authenticated readback. - FreshTenantCreationEvidence creation = - enrollment.enroll(located.creationRequestId(), located.requestDigest()); + // The receipt locates the source. The owner readback must match it before initialization. + return enrollment.enrollAndInitialize( + located.creationRequestId(), + located.requestDigest(), + creation -> initialize(creation, receipt)); + } + + private void initialize(FreshTenantCreationEvidence creation, SourceReceipt receipt) { + if (!creation.equals(receipt.creationEvidence())) { + throw new IllegalStateException( + "Authenticated tenant creation differs from the fixture receipt"); + } + if (preV1Waivers) { + initializePlayerCapacity(creation, receipt); + dsl.execute( + "INSERT INTO account_capacity_origin_refusal_budget" + + " (tenant_uuid, maximum_refusals) VALUES (?, ?) ON CONFLICT DO NOTHING", + creation.canonicalTenantId(), + PRE_V1_CAPACITY_ORIGIN_REFUSALS); + } var request = new DemoTenantEntitlementRequest( UUID.nameUUIDFromBytes( @@ -120,19 +130,50 @@ FreshTenantCreationEvidence enroll() throws IOException { true, true, FIXTURE_QUOTAS); - transaction.executeWithoutResult( - status -> { - demos.provision(request, creation); - if (preV1RefusalBudget) { - // Pre-v1 gate waiver (ADR 0185): operational capacity refusal budgets are owed. - dsl.execute( - "INSERT INTO account_capacity_origin_refusal_budget" - + " (tenant_uuid, maximum_refusals) VALUES (?, ?) ON CONFLICT DO NOTHING", - creation.canonicalTenantId(), - PRE_V1_CAPACITY_ORIGIN_REFUSALS); - } - }); - return creation; + demos.provision(request, creation); + } + + private void initializePlayerCapacity( + FreshTenantCreationEvidence creation, SourceReceipt receipt) { + UUID tenantId = creation.canonicalTenantId(); + UUID operationId = UUID.fromString(receipt.fixtureOperationId()); + String policyDigest = receipt.fixturePolicySeal().evidenceDigest(); + if (!operationId.equals(creation.creationRequestId())) { + throw new IllegalStateException( + "Fixture capacity requires the original Game Design creation request"); + } + dsl.execute( + "INSERT INTO account_run_owned_fixture_capacity_birth" + + " (tenant_uuid, fixture_operation_id, run_id, compose_project, creation_evidence_digest," + + " fixture_policy_evidence_digest) VALUES (?, ?, ?, ?, ?, ?)" + + " ON CONFLICT (tenant_uuid) DO NOTHING", + tenantId, + operationId, + runId, + composeProjectName, + creation.evidenceDigest(), + policyDigest); + boolean matches = + Boolean.TRUE.equals( + dsl.fetchValue( + "SELECT EXISTS (SELECT 1 FROM account_run_owned_fixture_capacity_birth birth" + + " JOIN account_tenant_capacity_usage usage" + + " ON usage.fixture_birth_tenant_uuid = birth.tenant_uuid" + + " WHERE birth.tenant_uuid = ? AND birth.fixture_operation_id = ?" + + " AND birth.run_id = ? AND birth.compose_project = ?" + + " AND birth.creation_evidence_digest = ? AND birth.fixture_policy_evidence_digest = ?" + + " AND usage.tenant_uuid = birth.tenant_uuid" + + " AND usage.owner_service = 'game-session-service'" + + " AND usage.creation_evidence_digest = birth.creation_evidence_digest)", + tenantId, + operationId, + runId, + composeProjectName, + creation.evidenceDigest(), + policyDigest)); + if (!matches) { + throw new IllegalStateException("Run-owned fixture capacity birth did not read back exactly"); + } } private static byte[] read(Path path) throws IOException { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/FreshTenantIdentityEnrollmentService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/FreshTenantIdentityEnrollmentService.java index c711ac879a..3d0978955f 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/FreshTenantIdentityEnrollmentService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/FreshTenantIdentityEnrollmentService.java @@ -3,6 +3,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.Objects; import java.util.UUID; +import java.util.function.Consumer; import net.firedevops.firemud.accountservice.client.GameDesignFreshTenantIdentityClient; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; @@ -44,6 +45,18 @@ public FreshTenantIdentityEnrollmentService( * imports, reads back, and initializes the UUID tenant generation without resetting it. */ public FreshTenantCreationEvidence enroll(UUID creationRequestId, String expectedDigest) { + return enrollAndInitialize(creationRequestId, expectedDigest, ignored -> {}); + } + + /** + * Runs Account-owned initialization in the same transaction as the authenticated identity import. + * The initializer must verify any additional source and handle exact replays. + */ + public FreshTenantCreationEvidence enrollAndInitialize( + UUID creationRequestId, + String expectedDigest, + Consumer initializeAccount) { + Objects.requireNonNull(initializeAccount, "Account owner initialization is required"); if (creationRequestId == null || creationRequestId.equals(new UUID(0L, 0L)) || !GameTenantCreationDigest.isDigest(expectedDigest)) { @@ -81,6 +94,7 @@ public FreshTenantCreationEvidence enroll(UUID creationRequestId, String expecte "Fresh Account tenant association readback differs from owner evidence"); } generationRepository.initializeTenantIfAbsent(readback.canonicalTenantId()); + initializeAccount.accept(readback); return readback; }); return Objects.requireNonNull( diff --git a/services/account-service/src/main/resources/db/migration/V1048__run_owned_fixture_player_capacity_birth.sql b/services/account-service/src/main/resources/db/migration/V1048__run_owned_fixture_player_capacity_birth.sql new file mode 100644 index 0000000000..d727713d5c --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1048__run_owned_fixture_player_capacity_birth.sql @@ -0,0 +1,138 @@ +-- The run-owned smoke fixture is created by Game Design without a human creator Account. +-- Only the Account transaction importing that exact fresh fixture can establish player usage. +CREATE TABLE account_run_owned_fixture_capacity_birth ( + tenant_uuid UUID PRIMARY KEY + REFERENCES account_fresh_tenant_identity_associations(canonical_tenant_id), + fixture_operation_id UUID NOT NULL UNIQUE, + run_id VARCHAR(128) NOT NULL CHECK (run_id ~ '^[a-z0-9][a-z0-9-]*$'), + compose_project VARCHAR(128) NOT NULL UNIQUE, + creation_evidence_digest VARCHAR(71) NOT NULL + CHECK (creation_evidence_digest ~ '^sha256:[0-9a-f]{64}$'), + fixture_policy_evidence_digest VARCHAR(71) NOT NULL + CHECK (fixture_policy_evidence_digest ~ '^sha256:[0-9a-f]{64}$'), + CHECK (compose_project = 'firemud-smoke-' || run_id + OR (run_id ~ '^gha-[0-9a-f]{64}$' AND compose_project ~ '^smoke-full-[0-9]+-[0-9]+$')) +); + +ALTER TABLE account_tenant_capacity_usage + ALTER COLUMN bootstrap_request_id DROP NOT NULL; +ALTER TABLE account_tenant_capacity_usage + ADD COLUMN fixture_birth_tenant_uuid UUID + REFERENCES account_run_owned_fixture_capacity_birth(tenant_uuid); +ALTER TABLE account_tenant_capacity_usage + ADD CONSTRAINT account_tenant_capacity_has_one_birth_source CHECK ( + (bootstrap_request_id IS NOT NULL AND fixture_birth_tenant_uuid IS NULL) + OR (bootstrap_request_id IS NULL AND fixture_birth_tenant_uuid IS NOT NULL + AND fixture_birth_tenant_uuid = tenant_uuid AND owner_service = 'game-session-service') + ); + +-- [jooq ignore start] +CREATE FUNCTION account_tenant_capacity_has_current_birth(usage_row account_tenant_capacity_usage) +RETURNS BOOLEAN LANGUAGE SQL AS $$ + SELECT EXISTS ( + SELECT 1 FROM account_fresh_tenant_identity_associations birth + WHERE birth.canonical_tenant_id = usage_row.tenant_uuid + AND birth.evidence_digest = usage_row.creation_evidence_digest + AND birth.capacity_birth_transaction = pg_current_xact_id()::TEXT + AND ( + (usage_row.fixture_birth_tenant_uuid IS NULL AND EXISTS ( + SELECT 1 FROM account_tenant_creation_bootstrap_operations bootstrap + WHERE bootstrap.request_id = usage_row.bootstrap_request_id + AND bootstrap.tenant_uuid = usage_row.tenant_uuid + AND bootstrap.status = 'COMMITTED' + AND bootstrap.gameplay_admission_allowed IS FALSE + AND bootstrap.baseline_event_sequence = 0 + AND bootstrap.creation_operation_id = birth.operation_id + )) + OR (usage_row.bootstrap_request_id IS NULL + AND usage_row.fixture_birth_tenant_uuid = birth.canonical_tenant_id + AND usage_row.owner_service = 'game-session-service' + AND birth.target_namespace = 'dev' + AND EXISTS ( + SELECT 1 FROM account_run_owned_fixture_capacity_birth fixture + WHERE fixture.tenant_uuid = birth.canonical_tenant_id + AND fixture.fixture_operation_id = birth.creation_request_id + AND fixture.creation_evidence_digest = birth.evidence_digest + )) + ) + ); +$$; + +CREATE OR REPLACE FUNCTION account_tenant_capacity_usage_insert_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.held_units <> 0 OR NEW.used_units <> 0 OR NEW.usage_revision <> 1 + OR NOT account_tenant_capacity_has_current_birth(NEW) THEN + RAISE EXCEPTION 'Capacity usage initialization requires same-transaction new-tenant birth' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE OR REPLACE FUNCTION account_tenant_capacity_usage_update_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.tenant_uuid IS DISTINCT FROM OLD.tenant_uuid OR NEW.owner_service IS DISTINCT FROM OLD.owner_service + OR NEW.bootstrap_request_id IS DISTINCT FROM OLD.bootstrap_request_id + OR NEW.fixture_birth_tenant_uuid IS DISTINCT FROM OLD.fixture_birth_tenant_uuid + OR NEW.creation_evidence_digest IS DISTINCT FROM OLD.creation_evidence_digest + OR NEW.usage_revision <> OLD.usage_revision + 1 THEN + RAISE EXCEPTION 'Capacity usage identity is immutable and revision must advance once' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE OR REPLACE FUNCTION account_tenant_capacity_conservation_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP IN ('DELETE', 'TRUNCATE') OR pg_trigger_depth() < 2 THEN + RAISE EXCEPTION 'Capacity conservation is writable only by its nested owner triggers' + USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'INSERT' THEN + IF NEW.held_units <> 0 OR NEW.used_units <> 0 OR NOT EXISTS ( + SELECT 1 FROM account_tenant_capacity_usage usage + WHERE usage.tenant_uuid = NEW.tenant_uuid AND usage.owner_service = NEW.owner_service + AND usage.held_units = 0 AND usage.used_units = 0 AND usage.usage_revision = 1 + AND account_tenant_capacity_has_current_birth(usage)) THEN + RAISE EXCEPTION 'Capacity conservation birth requires exact same-transaction zero usage' + USING ERRCODE = '23514'; + END IF; + ELSIF NEW.tenant_uuid IS DISTINCT FROM OLD.tenant_uuid + OR NEW.owner_service IS DISTINCT FROM OLD.owner_service + OR NEW.used_units < OLD.used_units + OR (NEW.held_units > OLD.held_units AND NEW.used_units <> OLD.used_units) + OR (NEW.used_units > OLD.used_units + AND OLD.held_units::NUMERIC - NEW.held_units <> NEW.used_units::NUMERIC - OLD.used_units) THEN + RAISE EXCEPTION 'Capacity conservation permits only immutable-key reservation deltas' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_run_owned_fixture_capacity_birth_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Run-owned fixture capacity birth is immutable' USING ERRCODE = '23514'; + END IF; + IF EXISTS (SELECT 1 FROM account_tenant_membership + WHERE tenant_uuid = NEW.tenant_uuid AND gameplay_admission_allowed IS TRUE) THEN + RAISE EXCEPTION 'Run-owned fixture player usage is not demonstrably empty' USING ERRCODE = '23514'; + END IF; + + -- The existing usage and conservation triggers check the same-transaction owner source. + -- The fixture does not establish a World Management capacity baseline. + INSERT INTO account_tenant_capacity_usage + (tenant_uuid, owner_service, fixture_birth_tenant_uuid, creation_evidence_digest, + held_units, used_units, usage_revision) + VALUES (NEW.tenant_uuid, 'game-session-service', NEW.tenant_uuid, NEW.creation_evidence_digest, 0, 0, 1); + RETURN NULL; +END; +$$; +CREATE TRIGGER account_run_owned_fixture_capacity_birth_owner + AFTER INSERT OR UPDATE OR DELETE ON account_run_owned_fixture_capacity_birth + FOR EACH ROW EXECUTE FUNCTION account_run_owned_fixture_capacity_birth_guard(); +CREATE TRIGGER account_run_owned_fixture_capacity_birth_no_truncate + BEFORE TRUNCATE ON account_run_owned_fixture_capacity_birth + FOR EACH STATEMENT EXECUTE FUNCTION account_run_owned_fixture_capacity_birth_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java index 1b1b56c1c8..da0c637df0 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java @@ -135,6 +135,96 @@ void freshAndPopulated1040Through1041UpgradesPreserveRowsHistoryAndScopeReservat verify1040Upgrade(true); } + @Test + void onlyAnExactFreshFixtureBirthInitializesPlayerUsageAndConservation() { + String schema = "capacity_fixture_" + UUID.randomUUID().toString().replace("-", ""); + var admin = new JdbcTemplate(POSTGRES.dataSource()); + admin.execute("CREATE SCHEMA " + schema); + var data = POSTGRES.dataSource(schema); + try { + configureFlyway(data, schema, "1047").migrate(); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES); + var transaction = new TransactionTemplate(new DataSourceTransactionManager(data)); + var fixtures = new FreshTenantIdentityAssociationRepository(dsl, "dev"); + var retained = source("dev"); + transaction.executeWithoutResult(status -> fixtures.importVerified(retained)); + + configureFlyway(data, schema, "1048").migrate(); + var retainedReadback = + transaction.execute(status -> fixtures.read(retained.canonicalTenantId())); + assertThat(retainedReadback).contains(retained); + assertThatThrownBy( + () -> + transaction.executeWithoutResult( + status -> { + fixtures.importVerified(retained); + insertFixtureBirth(dsl, retained, retained.creationRequestId()); + })) + .hasRootCauseInstanceOf(SQLException.class); + assertThat(dsl.fetchCount(DSL.table("account_run_owned_fixture_capacity_birth"))).isZero(); + assertThat(dsl.fetchCount(DSL.table("account_tenant_capacity_usage"))).isZero(); + + var fresh = source("dev"); + assertThatThrownBy( + () -> + transaction.executeWithoutResult( + status -> { + fixtures.importVerified(fresh); + insertFixtureBirth(dsl, fresh, UUID.randomUUID()); + })) + .hasRootCauseInstanceOf(SQLException.class); + var rolledBack = transaction.execute(status -> fixtures.read(fresh.canonicalTenantId())); + assertThat(rolledBack).isEmpty(); + + for (int attempt = 0; attempt < 2; attempt++) { + transaction.executeWithoutResult( + status -> { + fixtures.importVerified(fresh); + insertFixtureBirth(dsl, fresh, fresh.creationRequestId()); + }); + } + assertThat( + dsl.fetch( + "SELECT owner_service, held_units, used_units, usage_revision" + + " FROM account_tenant_capacity_usage" + + " WHERE fixture_birth_tenant_uuid = ?", + fresh.canonicalTenantId()) + .map(Record::intoList)) + .containsExactly(List.of("game-session-service", 0L, 0L, 1L)); + assertThat( + dsl.fetch( + "SELECT owner_service, held_units, used_units" + + " FROM account_tenant_capacity_conservation WHERE tenant_uuid = ?", + fresh.canonicalTenantId()) + .map(Record::intoList)) + .containsExactly(List.of("game-session-service", 0L, 0L)); + assertThat(dsl.fetchCount(DSL.table("account_run_owned_fixture_capacity_birth"))).isOne(); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE account_run_owned_fixture_capacity_birth SET run_id = run_id")) + .hasRootCauseInstanceOf(SQLException.class); + } finally { + admin.execute("DROP SCHEMA " + schema + " CASCADE"); + } + } + + private static void insertFixtureBirth( + DSLContext dsl, FreshTenantCreationEvidence source, UUID fixtureOperationId) { + String run = source.canonicalTenantId().toString(); + dsl.execute( + "INSERT INTO account_run_owned_fixture_capacity_birth" + + " (tenant_uuid, fixture_operation_id, run_id, compose_project, creation_evidence_digest," + + " fixture_policy_evidence_digest) VALUES (?, ?, ?, ?, ?, ?)" + + " ON CONFLICT (tenant_uuid) DO NOTHING", + source.canonicalTenantId(), + fixtureOperationId, + run, + "firemud-smoke-" + run, + source.evidenceDigest(), + "sha256:" + "1".repeat(64)); + } + private static void verify1040Upgrade(boolean populated) { String schema = "capacity_trigger_" + UUID.randomUUID().toString().replace("-", ""); new JdbcTemplate(POSTGRES.dataSource()).execute("CREATE SCHEMA " + schema); @@ -734,13 +824,18 @@ private static Completion completion(StoredOperation operation) { } private static FreshTenantCreationEvidence source() { + return source("prod"); + } + + private static FreshTenantCreationEvidence source(String namespace) { UUID request = UUID.randomUUID(), operation = UUID.randomUUID(), tenant = UUID.randomUUID(); String slug = "capacity-" + UUID.randomUUID().toString().substring(0, 8); - String digest = GameTenantCreationDigest.requestDigest("prod", request, slug, "Capacity", null); + String digest = + GameTenantCreationDigest.requestDigest(namespace, request, slug, "Capacity", null); long row = Math.abs((long) tenant.hashCode()) + 1; return new FreshTenantCreationEvidence( 1, - "prod", + namespace, request, operation, digest, @@ -749,6 +844,6 @@ private static FreshTenantCreationEvidence source() { slug, "NEW_GAME_ROW", GameTenantCreationDigest.evidenceDigest( - "prod", request, operation, digest, tenant, row, slug, "NEW_GAME_ROW")); + namespace, request, operation, digest, tenant, row, slug, "NEW_GAME_ROW")); } } From 2ee775b3efaf07286cb9f793ae107832eab09916 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 23 Nov 2026 00:48:08 +1300 Subject: [PATCH 11/28] Use the original lease deadline for fixture final admission --- .../repository/PreV1CanonicalPlayAdmissionOwner.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayAdmissionOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayAdmissionOwner.java index a8a288e7c3..4055acb17d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayAdmissionOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayAdmissionOwner.java @@ -255,8 +255,7 @@ public Admitted play( jwt, installation, SESSION_DURATION.toMillis(), - Math.min( - clock.millis() + 5_000L, decision.leaseExpiresAtEpochMillis().longValueExact()), + decision.leaseExpiresAtEpochMillis().longValueExact(), capacityRequest); requireCurrent(scope, original, login, transport, current); return new Admitted( From 03f72cea0a090a4a33f1d53c43dff8ab8efb663c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 23 Nov 2026 01:52:21 +1300 Subject: [PATCH 12/28] Resolve LOOK from the admitted run-owned starter room --- .../api-contracts.md | 2 + .../game-logic-service/api-contracts.md | 2 + .../world-management-service/api-contracts.md | 2 + dev-tools/smoke/smoke_common.py | 7 +- dev-tools/tests/smoke-transport-contract.sh | 10 +- docker/docker-compose.grpc-mtls.override.yml | 19 ++ .../v1/entity_management_service.proto | 18 ++ protos/game-logic/v1/game_logic_service.proto | 15 ++ .../v1/world_management_service.proto | 17 ++ .../RunOwnedFixtureLookEntityGrpcService.java | 182 ++++++++++++++++++ .../src/main/resources/application.yml | 1 + .../config/GameLogicGrpcClientConfig.java | 30 +++ .../service/LookAggregationService.java | 58 +++--- .../impl/RunOwnedFixtureLookGrpcService.java | 133 +++++++++++++ .../src/main/resources/application.yml | 3 + .../gamesession/client/GameLogicClient.java | 22 +++ ...V1CanonicalPlayAdmissionConfiguration.java | 8 +- ...yOriginalNewFinalAdmissionCoordinator.java | 13 +- ...ayOriginalNewFinalAdmissionRedisOwner.java | 34 ++++ .../PreV1CanonicalPlayAdmissionOwner.java | 93 +++++++-- .../PreV1RunOwnedFixturePlayRegion.java | 3 + ...uthenticatedDirectTextCommandReceiver.java | 17 ++ .../telnet-login-look-smoke.sh | 4 +- ...tureInitialAdmissionHoldConfiguration.java | 17 ++ .../RunOwnedFixtureLookWorldGrpcService.java | 99 ++++++++++ .../impl/WorldManagementGrpcService.java | 28 ++- ...onicalInstanceLifecycleReadRepository.java | 53 +++++ .../src/main/resources/application.yml | 1 + ...resetResourcesPostgresIntegrationTest.java | 25 +++ 29 files changed, 853 insertions(+), 63 deletions(-) create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/RunOwnedFixtureLookEntityGrpcService.java create mode 100644 services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/impl/RunOwnedFixtureLookGrpcService.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/RunOwnedFixtureLookWorldGrpcService.java diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index 569acfa1af..6330e412ed 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -219,6 +219,8 @@ The target `ListRoomEntities` request carries the same `CausalReadFence` as Worl After that protocol exists, Entity Management serves the same region/scope/epoch and returns that proof, a scoped `servedThroughTickId`, and an opaque Entity component version. That returned version follows the [Identifier Glossary causal-read contract](../../system-architecture-identifier-glossary.md#cross-service-causal-read-fence-identity): Entity advances it atomically with relevant durable containment-owner commits and returns the stored version on matching replay/no-op. Game Logic accepts the participant when the returned region/scope/epoch matches and `servedThroughTickId >=` the requested `committedTickId`; a behind-floor or mixed tenant, game instance, region, room, or epoch response is rejected or retried. Opaque component versions are not directly compared. Game Logic validates the served-through proof, then composes only the requested floor plus the World and Entity component versions in the room-view identity and returns that identity with `LookResult` so Game Session can retain its transcript rendering/cache behavior; it does not claim an exact cross-database historical snapshot. +The protected `RunOwnedFixtureLookEntityService/ReadRunOwnedFixtureGround` read is restricted to the pre-v1 run-owned Compose fixture and the authenticated Game Logic workload. Entity correlates the exact active World proof with the mounted fixture receipt and verifies that the canonical game instance has no persisted ground-holder data in the current owner snapshot. Populated or unqualified scopes are held. Entity qualifies fixture room contents using the canonical game instance UUID. + Room-entity data is derived from runtime entity state plus authoritative world location. Ground items are discovered by querying items contained by the synthetic room-ground container for the target `RoomInstanceRef`. Characters and NPCs are included when their current location (owned by World Management) matches the target `RoomInstanceRef`: - Game Session obtains the complete causal floor, including `regionId`, from durable region commit authority before invoking `ResolveLook`; Game Logic propagates that floor unchanged to `ListRoomEntities`. The target request/response evolution must carry enough information for Entity Management to prove service of that region/scope/epoch floor; the current proto/request path does not yet carry the floor or served-through proof and does not claim this behavior complete. diff --git a/design/architecture/microservices/game-logic-service/api-contracts.md b/design/architecture/microservices/game-logic-service/api-contracts.md index 7d796d48a0..58ee718b98 100644 --- a/design/architecture/microservices/game-logic-service/api-contracts.md +++ b/design/architecture/microservices/game-logic-service/api-contracts.md @@ -129,6 +129,8 @@ grpcurl -plaintext -d '{"tenant_id":"demo","session_id":"demo","command":"look"} ## LOOK Aggregation and Formatting +The protected `RunOwnedFixtureLookService/ResolveRunOwnedFixtureLook` read serves the run-owned starter-room view for an already admitted Game Session caller. It combines the exact current World snapshot with Entity's qualified empty-ground read, checks the World response again, and returns the ordinary structured `LookResult`. The scope markers identify the fixture data. The target causal-floor contract below governs durable runtime reads. + - `ResolveLook` orchestrates World Management and Entity Management: World provides room topology, ambient state, and the authoritative occupant set for the target room or instance, while Entity enriches those caller-supplied occupant references with live entity and ground-item display data to build a deterministic `LookResult` that Game Session renders for clients. - In the target causal-read path, Game Session allocates the complete `CausalReadFence` from durable region commit authority before invoking `ResolveLook`. Its runtime fence identity is at least `{tenantId, gameInstanceId, regionId, roomInstanceId, regionEpoch, committedTickId}`. `playableStateNamespaceId` and `playableStateScope` may remain broader validated request/admission context, but they are not part of the runtime fence identity. Game Logic propagates the fence unchanged to World and Entity and forwards the validated preferred locale unchanged to World Management for localized room snapshot resolution. World Management owns stored-variant selection; fallback and provider rules remain owned by [Input, Output, and Presentation](../../system-architecture-input-output-and-presentation.md#localization-and-translation) and [ADR 0136](../../decisions/adr-0136-future-compatible-localization-boundary.md), not this service. Game Logic accepts only participant proofs matching the requested fence scope and epoch, with `servedThroughTickId >= requestedFloor` (the committed-tick floor), and requires each participant's own opaque component version. It rejects or retries behind-floor, missing-version, or mixed-region/scope/epoch responses. Component versions are not globally comparable numeric values: equality is not required, numeric skew is not evaluated, and the floor/epoch proof is the correctness fence. The floor and composite-identity details remain owned by the [Identifier Glossary](../../system-architecture-identifier-glossary.md#cross-service-causal-read-fence-identity) and [ADR 0059](../../decisions/adr-0059-causal-floor-cross-service-presentation-reads.md). The current `ResolveLook` request/proto path remains floor-free, so this propagation and proof are target behavior rather than current implementation. - The target-state `LookResult` should stay explicitly sectioned rather than collapsing everything into one mixed list. At minimum it should preserve distinct sections for room/world snapshot data, exits, visible occupants, visible room-ground items from the room-attached container, and later optional overlays such as combat, hazards, or ambient scripted notices. diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 256ef50af5..595eda2b9a 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -220,6 +220,8 @@ This is **as-of World-owner catalog evidence only**. It selects ADR 0137's permi ## LOOK Snapshot Contract +The run-owned Compose fixture can use the protected `RunOwnedFixtureLookWorldService/ReadRunOwnedFixtureLookRoom` read. World requires the authenticated same-namespace Game Logic workload and the exact ACTIVE fixture lifecycle selector. In one owner snapshot it resolves the retained physical starter-room mapping, checks the requested room key, verifies that no World-owned character location is present there, and reads the existing scoped room snapshot. The returned tenant and game instance are canonical UUIDs. The returned scope marker identifies the fixture snapshot. The target causal-floor contract below governs durable runtime reads. This fixture read is held for populated rooms and requires the pre-v1 waiver. + `GetRoomSnapshot` is the canonical endpoint feeding Game Logic's `ResolveLook`. The current and target fence contracts are intentionally separate. ### Current room-snapshot contract diff --git a/dev-tools/smoke/smoke_common.py b/dev-tools/smoke/smoke_common.py index 4cf9623e0a..b89f515c07 100644 --- a/dev-tools/smoke/smoke_common.py +++ b/dev-tools/smoke/smoke_common.py @@ -387,14 +387,17 @@ def login_play_look_steps( ] -def authenticated_telnet_play_steps(username, password, world, worlds_expect, login_expect, play_expect): - """Run the canonical Telnet lobby and PLAY on one live connection.""" +def authenticated_telnet_play_steps( + username, password, world, worlds_expect, login_expect, play_expect, look_expect +): + """Run the canonical Telnet lobby, PLAY, and LOOK on one live connection.""" return [ (f"LOGIN {username} {password}", [login_expect], "LOGIN"), ("WORLDS", [worlds_expect], "WORLDS"), (f"REALMS {world}", ["OK REALMS"], "REALMS"), (f"JOIN {world}", ["OK JOIN"], "JOIN"), (f"PLAY {world}", [play_expect], "PLAY"), + ("LOOK", [look_expect, "Candle-lit Antechamber"], "LOOK"), ] diff --git a/dev-tools/tests/smoke-transport-contract.sh b/dev-tools/tests/smoke-transport-contract.sh index e9444e9378..e41a40408c 100644 --- a/dev-tools/tests/smoke-transport-contract.sh +++ b/dev-tools/tests/smoke-transport-contract.sh @@ -2017,13 +2017,15 @@ with patch( telnet_steps = smoke_common.authenticated_telnet_play_steps( - "demo@example.com", "swordfish", "demo", "OK WORLDS", "OK LOGIN", "OK PLAY" + "demo@example.com", "swordfish", "demo", "OK WORLDS", "OK LOGIN", "OK PLAY", "OK LOOK" ) -assert [step[2] for step in telnet_steps] == ["LOGIN", "WORLDS", "REALMS", "JOIN", "PLAY"] +assert [step[2] for step in telnet_steps] == ["LOGIN", "WORLDS", "REALMS", "JOIN", "PLAY", "LOOK"] assert telnet_steps[2][:2] == ("REALMS demo", ["OK REALMS"]) assert telnet_steps[3][:2] == ("JOIN demo", ["OK JOIN"]) assert telnet_steps[4][:2] == ("PLAY demo", ["OK PLAY"]) +assert telnet_steps[5][:2] == ("LOOK", ["OK LOOK", "Candle-lit Antechamber"]) + item_steps = smoke_common.gameplay_item_container_equipment_steps( "demo@example.com", @@ -2079,8 +2081,8 @@ for script in \ if [[ "$script" == *"tcp-proxy-service/telnet-login-look-smoke.sh" ]]; then grep -Fq 'discovery_selector = world' "$script" || { echo "$script must gate the mutation extension on the configured WORLDS selector" >&2; exit 1; } - grep -Fq 'authenticated_telnet_play_steps(login_email, password, world, worlds_expect, login_expect, play_expect)' "$script" || - { echo "$script baseline must use the authenticated Telnet PLAY plan" >&2; exit 1; } + grep -Fq 'authenticated_telnet_play_steps(login_email, password, world, worlds_expect, login_expect, play_expect, look_expect)' "$script" || + { echo "$script baseline must use the authenticated Telnet PLAY and LOOK plan" >&2; exit 1; } else grep -Fq 'discovery_selector=world' "$script" || { echo "$script must gate LOGIN on the configured WORLDS selector" >&2; exit 1; } diff --git a/docker/docker-compose.grpc-mtls.override.yml b/docker/docker-compose.grpc-mtls.override.yml index ed1bf2db4c..ad8c475bf1 100644 --- a/docker/docker-compose.grpc-mtls.override.yml +++ b/docker/docker-compose.grpc-mtls.override.yml @@ -72,11 +72,28 @@ services: environment: <<: *grpc-mtls-environment FIREMUD_GRPC_WORKLOAD_NAMESPACE: dev + FIREMUD_SMOKE_RUN_ID: ${FIREMUD_SMOKE_RUN_ID:-} + FIREMUD_SMOKE_COMPOSE_PROJECT_NAME: ${FIREMUD_SMOKE_COMPOSE_PROJECT_NAME:-} + FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED: ${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:-false} + FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH: /app/run-owned-initial-admission-capability.json + FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_PATH: /app/run-owned-authored-world-source/source-receipt.json depends_on: account-service: condition: service_healthy volumes: - ${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:?canonical smoke must set a run-owned mTLS certificate root}/workloads/entity-management-service:/app/certs:ro + - type: bind + source: ${FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_HOST_PATH:-/dev/null} + target: /app/run-owned-initial-admission-capability.json + read_only: true + bind: + create_host_path: false + - type: bind + source: ${FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_DIR_HOST_PATH:?run-owned smoke must prepare a claimed authored-world receipt directory} + target: /app/run-owned-authored-world-source + read_only: true + bind: + create_host_path: false game-design-service: environment: @@ -119,6 +136,8 @@ services: game-logic-service: environment: <<: *grpc-mtls-environment + FIREMUD_GRPC_WORKLOAD_NAMESPACE: dev + FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED: ${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:-false} volumes: - ${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:?canonical smoke must set a run-owned mTLS certificate root}/workloads/game-logic-service:/app/certs:ro diff --git a/protos/entity-management/v1/entity_management_service.proto b/protos/entity-management/v1/entity_management_service.proto index 8fbc886777..15261fbdaa 100644 --- a/protos/entity-management/v1/entity_management_service.proto +++ b/protos/entity-management/v1/entity_management_service.proto @@ -10,6 +10,24 @@ import "entity-management/v1/entity_character_create_service.proto"; option java_package = "net.firedevops.firemud.entitymanagement.v1"; option java_multiple_files = true; +// Verifies physical room-ground absence within an exact run-owned fixture. +service RunOwnedFixtureLookEntityService { + rpc ReadRunOwnedFixtureGround(ReadRunOwnedFixtureGroundRequest) + returns (ReadRunOwnedFixtureGroundResponse); +} + +message ReadRunOwnedFixtureGroundRequest { + shared.v1.RoomInstanceRef room = 1; + // Complete WorldRunOwnedFixtureLifecycleEvidence from the authenticated World owner. + bytes world_fixture_lifecycle = 2; +} + +message ReadRunOwnedFixtureGroundResponse { + shared.v1.RoomInstanceRef room = 1; + string entity_snapshot_id = 2; + bool empty_ground_verified = 3; +} + service EntityManagementService { rpc Ping(PingRequest) returns (PingResponse); rpc CreateCharacter(CreateCharacterRequest) returns (CreateCharacterResponse); diff --git a/protos/game-logic/v1/game_logic_service.proto b/protos/game-logic/v1/game_logic_service.proto index 32f878da26..60c182e260 100644 --- a/protos/game-logic/v1/game_logic_service.proto +++ b/protos/game-logic/v1/game_logic_service.proto @@ -5,10 +5,25 @@ package game_logic.v1; import "entity-management/v1/entity_management_service.proto"; import "shared/v1/errors.proto"; import "shared/v1/instance_refs.proto"; +import "world-management/v1/world_management_service.proto"; option java_package = "net.firedevops.firemud.gamelogic.v1"; option java_multiple_files = true; +// Protected LOOK projection for an already admitted run-owned fixture session. +service RunOwnedFixtureLookService { + rpc ResolveRunOwnedFixtureLook(ResolveRunOwnedFixtureLookRequest) + returns (ResolveRunOwnedFixtureLookResponse); +} + +message ResolveRunOwnedFixtureLookRequest { + world_management.v1.ReadRunOwnedFixtureLookRoomRequest room = 1; +} + +message ResolveRunOwnedFixtureLookResponse { + LookResult look = 1; +} + service GameLogicService { rpc Ping(PingRequest) returns (PingResponse); rpc ExecuteCommand(ExecuteCommandRequest) returns (ExecuteCommandResponse); diff --git a/protos/world-management/v1/world_management_service.proto b/protos/world-management/v1/world_management_service.proto index 30468bf2f3..580e7fc9a1 100644 --- a/protos/world-management/v1/world_management_service.proto +++ b/protos/world-management/v1/world_management_service.proto @@ -10,6 +10,23 @@ import "world-management/v1/world_canonical_instance_lifecycle_read.proto"; option java_package = "net.firedevops.firemud.worldmanagement.v1"; option java_multiple_files = true; +// Protected World snapshot reads for the exact active run-owned fixture. +service RunOwnedFixtureLookWorldService { + rpc ReadRunOwnedFixtureLookRoom(ReadRunOwnedFixtureLookRoomRequest) + returns (ReadRunOwnedFixtureLookRoomResponse); +} + +message ReadRunOwnedFixtureLookRoomRequest { + ReadWorldCanonicalInstanceLifecycleRequest lifecycle = 1; + string expected_room_instance_key = 2; + string preferred_locale = 3; +} + +message ReadRunOwnedFixtureLookRoomResponse { + ReadWorldCanonicalInstanceLifecycleResponse lifecycle = 1; + RoomSnapshot snapshot = 2; +} + service WorldManagementService { rpc Ping(PingRequest) returns (PingResponse); rpc PrepareWorldInstance(PrepareWorldInstanceRequest) diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/RunOwnedFixtureLookEntityGrpcService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/RunOwnedFixtureLookEntityGrpcService.java new file mode 100644 index 0000000000..6b00d3043f --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/RunOwnedFixtureLookEntityGrpcService.java @@ -0,0 +1,182 @@ +package net.firedevops.firemud.entitymanagement.service.impl; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.prev1.PreV1GateWaivers; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec; +import net.firedevops.firemud.common.world.WorldRunOwnedFixtureLifecycleEvidence; +import net.firedevops.firemud.entitymanagement.v1.ReadRunOwnedFixtureGroundRequest; +import net.firedevops.firemud.entitymanagement.v1.ReadRunOwnedFixtureGroundResponse; +import net.firedevops.firemud.entitymanagement.v1.RunOwnedFixtureLookEntityServiceGrpc; +import org.jooq.DSLContext; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; +import org.springframework.core.env.Environment; +import org.springframework.grpc.server.service.GrpcService; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Entity-owned ground absence for the exact fresh fixture. Populated scopes require canonical + * Entity ownership and are held. The receipt and fixed run capability qualify the scope, and the + * actual holder tables establish absence. + */ +@GrpcService +@ConditionalOnExpression( + "${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:false}" + + " and ${firemud.pre-v1.gate-waivers.enabled:false}") +public final class RunOwnedFixtureLookEntityGrpcService + extends RunOwnedFixtureLookEntityServiceGrpc.RunOwnedFixtureLookEntityServiceImplBase { + private static final int MAX_FIXTURE_FILE_BYTES = 16 * 1024; + private static final String GROUND_SOURCE_EXISTS = + "SELECT EXISTS (SELECT 1 FROM room_ground_inventory WHERE game_instance_id = ?" + + " UNION ALL SELECT 1 FROM container_instances WHERE game_instance_id = ?" + + " UNION ALL SELECT 1 FROM item_instances WHERE game_instance_id = ?" + + " UNION ALL SELECT 1 FROM item_stacks WHERE game_instance_id = ?)"; + + private final DSLContext dsl; + private final TransactionTemplate transaction; + private final String namespace; + private final String runId; + private final String composeProject; + private final Path capabilityPath; + private final Path receiptPath; + + public RunOwnedFixtureLookEntityGrpcService( + DSLContext dsl, + @Qualifier("transactionManager") PlatformTransactionManager transactions, + Environment environment, + @Value("${firemud.grpc.workload-namespace:}") String namespace, + @Value("${FIREMUD_SMOKE_RUN_ID:}") String runId, + @Value("${FIREMUD_SMOKE_COMPOSE_PROJECT_NAME:}") String composeProject, + @Value("${FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH:}") String capabilityPath, + @Value("${FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_PATH:}") String receiptPath) { + if (!PreV1GateWaivers.from(environment).enabled() + || !GrpcPeerIdentity.isValidNamespace(namespace) + || runId.isBlank() + || composeProject.isBlank()) { + throw new IllegalArgumentException("A run-owned fixture Entity scope is required"); + } + this.dsl = dsl; + transaction = new TransactionTemplate(transactions); + transaction.setReadOnly(true); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + transaction.setTimeout(2); + this.namespace = namespace; + this.runId = runId; + this.composeProject = composeProject; + this.capabilityPath = Path.of(capabilityPath); + this.receiptPath = Path.of(receiptPath); + } + + @Override + public void readRunOwnedFixtureGround( + ReadRunOwnedFixtureGroundRequest request, + StreamObserver observer) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null) { + observer.onError(Status.UNAUTHENTICATED.asRuntimeException()); + return; + } + if (!peer.isService("game-logic-service") + || !peer.isInNamespace(namespace) + || SessionContext.hasAuthenticatedCallerContext() + || SessionContext.isInternalService()) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + final WorldRunOwnedFixtureLifecycleEvidence world; + var room = request.getRoom(); + try { + if (!request.hasRoom() + || !request.getUnknownFields().asMap().isEmpty() + || !room.getUnknownFields().asMap().isEmpty() + || !room.getRoomInstanceId().matches("R-[1-9][0-9]{0,18}")) { + throw new IllegalArgumentException("An exact fixture room is required"); + } + world = + WorldRunOwnedFixtureLifecycleEvidence.fromStored( + request.getWorldFixtureLifecycle().toByteArray()); + if (!world.request().canonicalTenantId().toString().equals(room.getTenantId()) + || !world.request().canonicalGameInstanceId().toString().equals(room.getGameInstanceId()) + || !world.request().targetNamespace().equals(namespace) + || !"ACTIVE".equals(world.lifecycleStatus())) { + throw new IllegalArgumentException("The fixture room differs from the current World scope"); + } + } catch (IllegalArgumentException invalid) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + try { + var verified = readFixture(); + if (!verified + .creationEvidence() + .canonicalTenantId() + .equals(world.request().canonicalTenantId()) + || !verified + .fixturePolicySeal() + .evidenceDigest() + .equals(world.fixtureProvenanceDigest())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + // The instance UUID is globally unique. Inspect every actual holder family at that UUID + // without adopting a numeric tenant or guessing the ownership of any populated row. + String game = room.getGameInstanceId(); + Boolean populated = + transaction.execute( + status -> { + dsl.execute("SET LOCAL statement_timeout = '1000ms'"); + return (Boolean) dsl.fetchValue(GROUND_SOURCE_EXISTS, game, game, game, game); + }); + if (!Boolean.FALSE.equals(populated) + || !verified.fixturePolicySeal().equals(readFixture().fixturePolicySeal())) { + observer.onError(Status.FAILED_PRECONDITION.asRuntimeException()); + return; + } + } catch (IOException | RuntimeException unavailable) { + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + return; + } + observer.onNext( + ReadRunOwnedFixtureGroundResponse.newBuilder() + .setRoom(room) + .setEntitySnapshotId( + room.getTenantId() + + ":" + + room.getGameInstanceId() + + ":" + + room.getRoomInstanceId()) + .setEmptyGroundVerified(true) + .build()); + observer.onCompleted(); + } + + private RunOwnedInitialAdmissionFixtureWireCodec.SourceReceipt readFixture() throws IOException { + var capability = RunOwnedInitialAdmissionFixtureWireCodec.parseCapability(read(capabilityPath)); + if (!runId.equals(capability.runId()) + || !composeProject.equals(capability.composeProjectName())) { + throw new IllegalStateException("Fixture capability does not belong to this run"); + } + return RunOwnedInitialAdmissionFixtureWireCodec.parseSourceReceipt( + read(receiptPath), capability); + } + + private static byte[] read(Path path) throws IOException { + try (var input = Files.newInputStream(path)) { + byte[] bytes = input.readNBytes(MAX_FIXTURE_FILE_BYTES + 1); + if (bytes.length > MAX_FIXTURE_FILE_BYTES) { + throw new IllegalStateException("Fixture source exceeds its wire bound"); + } + return bytes; + } + } +} diff --git a/services/entity-management-service/src/main/resources/application.yml b/services/entity-management-service/src/main/resources/application.yml index dc3d49415d..a037332dfe 100644 --- a/services/entity-management-service/src/main/resources/application.yml +++ b/services/entity-management-service/src/main/resources/application.yml @@ -74,6 +74,7 @@ firemud: path-pattern: /.well-known/** grpc: public-methods: + - entity_management.v1.RunOwnedFixtureLookEntityService/ReadRunOwnedFixtureGround - entity_management.v1.EntityManagementService/Ping grpc: workload-namespace: ${FIREMUD_GRPC_WORKLOAD_NAMESPACE:} diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/config/GameLogicGrpcClientConfig.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/config/GameLogicGrpcClientConfig.java index 4818baa611..fa643c1b3c 100644 --- a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/config/GameLogicGrpcClientConfig.java +++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/config/GameLogicGrpcClientConfig.java @@ -8,11 +8,17 @@ import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; import net.firedevops.firemud.entitymanagement.v1.EntityManagementServiceGrpc; import net.firedevops.firemud.entitymanagement.v1.EntityManagementServiceGrpc.EntityManagementServiceBlockingStub; +import net.firedevops.firemud.entitymanagement.v1.RunOwnedFixtureLookEntityServiceGrpc; import net.firedevops.firemud.socialgroups.v1.SocialGroupsServiceGrpc; +import net.firedevops.firemud.worldmanagement.v1.RunOwnedFixtureLookWorldServiceGrpc; import net.firedevops.firemud.worldmanagement.v1.WorldManagementServiceGrpc; import net.firedevops.firemud.worldmanagement.v1.WorldManagementServiceGrpc.WorldManagementServiceBlockingStub; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Lazy; @@ -76,6 +82,30 @@ public SocialGroupsServiceGrpc.SocialGroupsServiceBlockingStub socialGroupsStub( SocialGroupsServiceGrpc.newBlockingStub(socialChannel).withCompression("gzip")); } + @Bean + @ConditionalOnExpression( + "${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:false}" + + " and ${firemud.pre-v1.gate-waivers.enabled:false}") + RunOwnedFixtureLookWorldServiceGrpc.RunOwnedFixtureLookWorldServiceBlockingStub + fixtureLookWorldStub(@Value("${firemud.grpc.workload-namespace:}") String namespace) { + String peer = "spiffe://firemud/ns/" + namespace + "/sa/world-management-service"; + return RunOwnedFixtureLookWorldServiceGrpc.newBlockingStub(worldChannel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(peer)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(peer)); + } + + @Bean + @ConditionalOnExpression( + "${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:false}" + + " and ${firemud.pre-v1.gate-waivers.enabled:false}") + RunOwnedFixtureLookEntityServiceGrpc.RunOwnedFixtureLookEntityServiceBlockingStub + fixtureLookEntityStub(@Value("${firemud.grpc.workload-namespace:}") String namespace) { + String peer = "spiffe://firemud/ns/" + namespace + "/sa/entity-management-service"; + return RunOwnedFixtureLookEntityServiceGrpc.newBlockingStub(entityChannel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(peer)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(peer)); + } + private > T customize(T stub) { return stubCustomizer.customize(stub); } diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/LookAggregationService.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/LookAggregationService.java index 4c085b9042..845c46df4a 100644 --- a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/LookAggregationService.java +++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/LookAggregationService.java @@ -38,38 +38,38 @@ public class LookAggregationService { public LookResult resolve(LookRequest request) { try (GameplayLoggingContext ignored = GameplayLoggingContext.from(request)) { - RoomSnapshot snapshot = fetchSnapshot(request); - ListRoomEntitiesResponse entityResponse = fetchEntities(request); - requireSameReadFence(snapshot, entityResponse); - - LookResult.Builder builder = - LookResult.newBuilder() - .setRoomInstance( - RoomInstanceRef.newBuilder() - .setTenantId(snapshot.getTenantId()) - .setGameInstanceId(snapshot.getGameInstanceId()) - .setRoomInstanceId(snapshot.getRoomInstanceId()) - .build()) - .setRoomName(snapshot.getRoomName()) - .setShortDescription(snapshot.getShortDescription()) - .setLongDescription(snapshot.getLongDescription()) - .setWorldSnapshotId(snapshot.getWorldSnapshotId()) - .setEntitySnapshotId(entityResponse.getEntitySnapshotId()) - .setLookSnapshotId(snapshot.getWorldSnapshotId()) - .addAllRoomFlags(snapshot.getRoomFlagsList()) - .setAmbientState(toAmbientState(snapshot.getAmbientState())); - - snapshot.getExitsList().forEach(exit -> builder.addExits(toLookExit(exit))); - entityResponse.getEntitiesList().stream() - .map(this::toRoomEntity) - .forEach(builder::addEntities); - - LookResult result = builder.build(); - LOG.debug("Rendered LOOK text:\n{}", renderer.render(result)); - return result; + return project(fetchSnapshot(request), fetchEntities(request)); } } + public LookResult project(RoomSnapshot snapshot, ListRoomEntitiesResponse entityResponse) { + requireSameReadFence(snapshot, entityResponse); + + LookResult.Builder builder = + LookResult.newBuilder() + .setRoomInstance( + RoomInstanceRef.newBuilder() + .setTenantId(snapshot.getTenantId()) + .setGameInstanceId(snapshot.getGameInstanceId()) + .setRoomInstanceId(snapshot.getRoomInstanceId()) + .build()) + .setRoomName(snapshot.getRoomName()) + .setShortDescription(snapshot.getShortDescription()) + .setLongDescription(snapshot.getLongDescription()) + .setWorldSnapshotId(snapshot.getWorldSnapshotId()) + .setEntitySnapshotId(entityResponse.getEntitySnapshotId()) + .setLookSnapshotId(snapshot.getWorldSnapshotId()) + .addAllRoomFlags(snapshot.getRoomFlagsList()) + .setAmbientState(toAmbientState(snapshot.getAmbientState())); + + snapshot.getExitsList().forEach(exit -> builder.addExits(toLookExit(exit))); + entityResponse.getEntitiesList().stream().map(this::toRoomEntity).forEach(builder::addEntities); + + LookResult result = builder.build(); + LOG.debug("Rendered LOOK text:\n{}", renderer.render(result)); + return result; + } + private RoomSnapshot fetchSnapshot(LookRequest request) { try { GetRoomSnapshotResponse response = diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/impl/RunOwnedFixtureLookGrpcService.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/impl/RunOwnedFixtureLookGrpcService.java new file mode 100644 index 0000000000..1e26d2f482 --- /dev/null +++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/impl/RunOwnedFixtureLookGrpcService.java @@ -0,0 +1,133 @@ +package net.firedevops.firemud.gamelogic.service.impl; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.prev1.PreV1GateWaivers; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleGrpcCodec; +import net.firedevops.firemud.entitymanagement.v1.ListRoomEntitiesResponse; +import net.firedevops.firemud.entitymanagement.v1.ReadRunOwnedFixtureGroundRequest; +import net.firedevops.firemud.entitymanagement.v1.RunOwnedFixtureLookEntityServiceGrpc.RunOwnedFixtureLookEntityServiceBlockingStub; +import net.firedevops.firemud.gamelogic.service.LookAggregationService; +import net.firedevops.firemud.gamelogic.v1.LookResult; +import net.firedevops.firemud.gamelogic.v1.ResolveRunOwnedFixtureLookRequest; +import net.firedevops.firemud.gamelogic.v1.ResolveRunOwnedFixtureLookResponse; +import net.firedevops.firemud.gamelogic.v1.RunOwnedFixtureLookServiceGrpc; +import net.firedevops.firemud.shared.v1.RoomInstanceRef; +import net.firedevops.firemud.worldmanagement.v1.RunOwnedFixtureLookWorldServiceGrpc.RunOwnedFixtureLookWorldServiceBlockingStub; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; +import org.springframework.core.env.Environment; +import org.springframework.grpc.server.service.GrpcService; + +/** Game Logic owns the combined World and Entity view for an admitted fixture player. */ +@GrpcService +@ConditionalOnExpression( + "${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:false}" + + " and ${firemud.pre-v1.gate-waivers.enabled:false}") +public final class RunOwnedFixtureLookGrpcService + extends RunOwnedFixtureLookServiceGrpc.RunOwnedFixtureLookServiceImplBase { + private final RunOwnedFixtureLookWorldServiceBlockingStub world; + private final RunOwnedFixtureLookEntityServiceBlockingStub entity; + private final LookAggregationService look; + private final String namespace; + + public RunOwnedFixtureLookGrpcService( + RunOwnedFixtureLookWorldServiceBlockingStub world, + RunOwnedFixtureLookEntityServiceBlockingStub entity, + LookAggregationService look, + Environment environment, + @Value("${firemud.grpc.workload-namespace:}") String namespace) { + if (!PreV1GateWaivers.from(environment).enabled() + || !GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("An enabled run-owned LOOK scope is required"); + } + this.world = world; + this.entity = entity; + this.look = look; + this.namespace = namespace; + } + + @Override + public void resolveRunOwnedFixtureLook( + ResolveRunOwnedFixtureLookRequest wire, + StreamObserver observer) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null) { + observer.onError(Status.UNAUTHENTICATED.asRuntimeException()); + return; + } + if (!peer.isService("game-session-service") + || !peer.isInNamespace(namespace) + || SessionContext.hasAuthenticatedCallerContext() + || SessionContext.isInternalService()) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + LookResult view; + try { + if (!wire.hasRoom() || !wire.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("The exact fixture room request is required"); + } + var request = wire.getRoom(); + var selector = WorldCanonicalInstanceLifecycleGrpcCodec.fromRequest(request.getLifecycle()); + if (!request.getUnknownFields().asMap().isEmpty() + || !namespace.equals(selector.targetNamespace())) { + throw new IllegalArgumentException("The exact fixture World selector is required"); + } + var first = world.withDeadlineAfter(2, TimeUnit.SECONDS).readRunOwnedFixtureLookRoom(request); + var active = + WorldCanonicalInstanceLifecycleGrpcCodec.fromFixtureResponse( + selector, first.getLifecycle()); + var snapshot = first.getSnapshot(); + var room = + RoomInstanceRef.newBuilder() + .setTenantId(selector.canonicalTenantId().toString()) + .setGameInstanceId(selector.canonicalGameInstanceId().toString()) + .setRoomInstanceId(request.getExpectedRoomInstanceKey()) + .build(); + if (!"ACTIVE".equals(active.lifecycleStatus()) + || !first.hasSnapshot() + || !room.getTenantId().equals(snapshot.getTenantId()) + || !room.getGameInstanceId().equals(snapshot.getGameInstanceId()) + || !room.getRoomInstanceId().equals(snapshot.getRoomInstanceId())) { + throw Status.FAILED_PRECONDITION.asRuntimeException(); + } + var ground = + entity + .withDeadlineAfter(2, TimeUnit.SECONDS) + .readRunOwnedFixtureGround( + ReadRunOwnedFixtureGroundRequest.newBuilder() + .setRoom(room) + .setWorldFixtureLifecycle(first.getLifecycle().getCanonicalResponseBytes()) + .build()); + if (!ground.getEmptyGroundVerified() || !room.equals(ground.getRoom())) { + throw Status.FAILED_PRECONDITION.asRuntimeException(); + } + if (!first.equals( + world.withDeadlineAfter(2, TimeUnit.SECONDS).readRunOwnedFixtureLookRoom(request))) { + throw Status.FAILED_PRECONDITION.asRuntimeException(); + } + view = + look.project( + snapshot, + ListRoomEntitiesResponse.newBuilder() + .setEntitySnapshotId(ground.getEntitySnapshotId()) + .build()); + } catch (StatusRuntimeException sourceFailure) { + observer.onError(Status.fromCode(sourceFailure.getStatus().getCode()).asRuntimeException()); + return; + } catch (IllegalArgumentException invalid) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } catch (RuntimeException unavailable) { + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + return; + } + observer.onNext(ResolveRunOwnedFixtureLookResponse.newBuilder().setLook(view).build()); + observer.onCompleted(); + } +} diff --git a/services/game-logic-service/src/main/resources/application.yml b/services/game-logic-service/src/main/resources/application.yml index 972d39e002..ac710b032c 100644 --- a/services/game-logic-service/src/main/resources/application.yml +++ b/services/game-logic-service/src/main/resources/application.yml @@ -65,12 +65,15 @@ firemud: inventory-enabled: true command-history-enabled: true grpc: + workload-namespace: ${FIREMUD_GRPC_WORKLOAD_NAMESPACE:} cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} ca-cert: ${FIREMUD_GRPC_CA_CERT_PATH:certs/ca.crt} auth: grpc: force-internal-service-outbound: true + public-methods: + - game_logic.v1.RunOwnedFixtureLookService/ResolveRunOwnedFixtureLook server: compression: diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameLogicClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameLogicClient.java index 6aedf16b52..6d4c786af3 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameLogicClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameLogicClient.java @@ -8,8 +8,11 @@ import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; import net.firedevops.firemud.common.security.GameplaySessionAttestationService; import net.firedevops.firemud.common.security.JwtClaims; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleGrpcCodec; import net.firedevops.firemud.entitymanagement.v1.ApplyActorConditionRequest; import net.firedevops.firemud.entitymanagement.v1.ApplyActorConditionResponse; import net.firedevops.firemud.entitymanagement.v1.DropItemToRoomRequest; @@ -46,6 +49,8 @@ import net.firedevops.firemud.gamelogic.v1.PickupVisibleRoomItemRequest; import net.firedevops.firemud.gamelogic.v1.PingRequest; import net.firedevops.firemud.gamelogic.v1.PingResponse; +import net.firedevops.firemud.gamelogic.v1.ResolveRunOwnedFixtureLookRequest; +import net.firedevops.firemud.gamelogic.v1.RunOwnedFixtureLookServiceGrpc; import net.firedevops.firemud.gamelogic.v1.SendCommunicationRequest; import net.firedevops.firemud.gamelogic.v1.SendCommunicationResponse; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshots; @@ -53,6 +58,7 @@ import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.shared.v1.ErrorDetail; import net.firedevops.firemud.shared.v1.RoomInstanceRef; +import net.firedevops.firemud.worldmanagement.v1.ReadRunOwnedFixtureLookRoomRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; @@ -125,6 +131,22 @@ public LookResult resolveLook(SessionContext context, String roomId, String loca return callStub().resolveLook(request); } + public LookResult resolveRunOwnedFixtureLook(ReadRunOwnedFixtureLookRoomRequest request) { + var target = WorldCanonicalInstanceLifecycleGrpcCodec.fromRequest(request.getLifecycle()); + String peer = "spiffe://firemud/ns/" + target.targetNamespace() + "/sa/game-logic-service"; + var response = + RunOwnedFixtureLookServiceGrpc.newBlockingStub(stub().getChannel()) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(peer)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(peer)) + .withDeadlineAfter(8, TimeUnit.SECONDS) + .resolveRunOwnedFixtureLook( + ResolveRunOwnedFixtureLookRequest.newBuilder().setRoom(request).build()); + if (!response.hasLook() || !response.getUnknownFields().asMap().isEmpty()) { + throw new IllegalStateException("The fixture LOOK response is unavailable"); + } + return response.getLook(); + } + /** Authenticated connectivity conjunct; downstream readiness is checked separately. */ public PingResponse pingForReadiness() { return stub() diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/PreV1CanonicalPlayAdmissionConfiguration.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/PreV1CanonicalPlayAdmissionConfiguration.java index ef34a1ac87..30bb5badb0 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/PreV1CanonicalPlayAdmissionConfiguration.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/PreV1CanonicalPlayAdmissionConfiguration.java @@ -10,6 +10,8 @@ import net.firedevops.firemud.gamesession.client.AccountGameplayAdmissionLeaseClient; import net.firedevops.firemud.gamesession.client.AccountPlayerAdmissionEntitlementClient; import net.firedevops.firemud.gamesession.client.AccountTenantCapacityClient; +import net.firedevops.firemud.gamesession.client.GameLogicClient; +import net.firedevops.firemud.gamesession.command.text.LookTextRenderer; import net.firedevops.firemud.gamesession.data.PreV1CanonicalPlayBootstrapDriver; import net.firedevops.firemud.gamesession.data.RunOwnedCanonicalLaunchPreparationOwner; import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; @@ -77,7 +79,9 @@ PreV1CanonicalPlayAdmissionOwner preV1CanonicalPlayAdmissionOwner( AccountPlayerAdmissionEntitlementClient entitlements, AccountGameplayAdmissionLeaseClient leases, AccountTenantCapacityClient capacity, - AccountPublicJwksCache jwks) { + AccountPublicJwksCache jwks, + GameLogicClient gameLogic, + LookTextRenderer lookRenderer) { PreV1CanonicalPlayConfiguration.requireWaivers(environment); return new PreV1CanonicalPlayAdmissionOwner( dsl, @@ -93,6 +97,8 @@ PreV1CanonicalPlayAdmissionOwner preV1CanonicalPlayAdmissionOwner( leases, capacity, jwks, + gameLogic, + lookRenderer, Clock.systemUTC()); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCoordinator.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCoordinator.java index 6d3ad0d4ee..ea3528f63a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCoordinator.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCoordinator.java @@ -8,6 +8,7 @@ import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.OriginalFinalAdmissionConfirmation; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.OriginalNewCredential; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayOriginalNewFinalAdmissionReadGrpcCodec.Selector; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRegionBridgeObligation; @@ -298,7 +299,8 @@ FinalAdmissionResult completeOriginalNew( finalReadback.admissionAtMillis(), finalReadback.continuityExpiresAtMillis(), finalReadback.canonicalSessionDurationMillis(), - finalReadback.finalSessionSha256()); + finalReadback.finalSessionSha256(), + finalReadback.finalAdmissionReadSelector()); } } } @@ -685,18 +687,21 @@ static final class FinalAdmissionResult { private final long continuityExpiresAtMillis; private final long canonicalSessionDurationMillis; private final String finalSessionSha256; + private final Selector finalReadSelector; private FinalAdmissionResult( UUID transitionId, long admissionAtMillis, long continuityExpiresAtMillis, long canonicalSessionDurationMillis, - String finalSessionSha256) { + String finalSessionSha256, + Selector finalReadSelector) { this.transitionId = Objects.requireNonNull(transitionId, "transitionId"); this.admissionAtMillis = admissionAtMillis; this.continuityExpiresAtMillis = continuityExpiresAtMillis; this.canonicalSessionDurationMillis = canonicalSessionDurationMillis; this.finalSessionSha256 = Objects.requireNonNull(finalSessionSha256, "finalSessionSha256"); + this.finalReadSelector = Objects.requireNonNull(finalReadSelector, "finalReadSelector"); } UUID transitionId() { @@ -719,6 +724,10 @@ String finalSessionSha256() { return finalSessionSha256; } + Selector finalReadSelector() { + return finalReadSelector; + } + @Override public String toString() { return "CanonicalGameplayOriginalNewFinalAdmissionCoordinator.FinalAdmissionResult[confirmed,redacted]"; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.java index d4f847b744..add6011560 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.java @@ -23,6 +23,8 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import net.firedevops.firemud.common.account.capacity.OriginalNewCapacityExecution; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayOriginalNewFinalAdmissionReadGrpcCodec; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayOriginalNewFinalAdmissionReadGrpcCodec.Selector; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; @@ -1301,6 +1303,38 @@ String finalSessionSha256() { return finalSessionSha256; } + Selector finalAdmissionReadSelector() { + var finalized = session(); + var candidate = source.candidate(); + var lease = candidate.leaseEvidence(); + var carrier = lease.carrier(); + var identity = candidate.bindingIdentity(); + byte[] handle = finalized.opaqueRebindHandle(); + try { + return new Selector( + UUID.fromString((String) carrier.get("requestId")), + identity.accountId(), + identity.tenantId(), + UUID.fromString(identity.sessionId()), + candidate.bindingDecisionId(), + UUID.fromString((String) carrier.get("leaseId")), + lease.leaseFence().longValueExact(), + lease.sha256(), + finalized.authTokenHash(), + Long.parseLong(finalized.tokenGeneration()), + Long.parseLong(finalized.issuanceFence()), + CanonicalGameplayOriginalNewFinalAdmissionReadGrpcCodec.canonicalJsonSha256( + carrier.get("bindingScope")), + CanonicalGameplayOriginalNewFinalAdmissionReadGrpcCodec.canonicalJsonSha256( + carrier.get("membershipBaseline")), + CanonicalGameplayOriginalNewFinalAdmissionReadGrpcCodec.canonicalJsonSha256( + carrier.get("outboxCheckpoints")), + digest("SHA-256", handle)); + } finally { + wipe(handle); + } + } + long admissionAtMillis() { return session().admissionAtMillis(); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayAdmissionOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayAdmissionOwner.java index 4055acb17d..4c91b6c739 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayAdmissionOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayAdmissionOwner.java @@ -15,18 +15,24 @@ import net.firedevops.firemud.common.runtime.RuntimeIdentity; import net.firedevops.firemud.common.security.AccountPublicJwksCache; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleClient; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleGrpcCodec; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; import net.firedevops.firemud.gamesession.client.AccountGameplayAdmissionLeaseClient; import net.firedevops.firemud.gamesession.client.AccountPlayerAdmissionEntitlementClient; import net.firedevops.firemud.gamesession.client.AccountTenantCapacityClient; +import net.firedevops.firemud.gamesession.client.GameLogicClient; +import net.firedevops.firemud.gamesession.command.text.LookTextRenderer; import net.firedevops.firemud.gamesession.command.text.ObservedDirectTextTransport; import net.firedevops.firemud.gamesession.data.PreV1CanonicalPlayBootstrapDriver; import net.firedevops.firemud.gamesession.data.RunOwnedCanonicalLaunchPreparationOwner; import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; +import net.firedevops.firemud.gamesession.presentation.PlayerOutput; import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyScope; +import net.firedevops.firemud.worldmanagement.v1.ReadRunOwnedFixtureLookRoomRequest; import org.jooq.DSLContext; import org.postgresql.util.PSQLException; import org.slf4j.Logger; @@ -47,6 +53,8 @@ public final class PreV1CanonicalPlayAdmissionOwner { private final AccountGameplayAdmissionLeaseClient leases; private final AccountTenantCapacityClient capacity; private final AccountPublicJwksCache jwks; + private final GameLogicClient gameLogic; + private final LookTextRenderer lookRenderer; private final Clock clock; public PreV1CanonicalPlayAdmissionOwner( @@ -62,6 +70,8 @@ public PreV1CanonicalPlayAdmissionOwner( AccountGameplayAdmissionLeaseClient leases, AccountTenantCapacityClient capacity, AccountPublicJwksCache jwks, + GameLogicClient gameLogic, + LookTextRenderer lookRenderer, Clock clock) { this.dsl = dsl; this.standIns = standIns; @@ -74,6 +84,8 @@ public PreV1CanonicalPlayAdmissionOwner( this.leases = leases; this.capacity = capacity; this.jwks = jwks; + this.gameLogic = gameLogic; + this.lookRenderer = lookRenderer; this.clock = clock; } @@ -258,13 +270,7 @@ public Admitted play( decision.leaseExpiresAtEpochMillis().longValueExact(), capacityRequest); requireCurrent(scope, original, login, transport, current); - return new Admitted( - target, - identity, - transitionId, - generation, - region.roomKey(), - result.continuityExpiresAtMillis()); + return new Admitted(region.lifecycleSelector(), region.roomKey(), result); } finally { Arrays.fill(compact, (byte) 0); } @@ -318,11 +324,70 @@ private static IllegalStateException unavailable() { return new IllegalStateException("Run-owned canonical PLAY unavailable"); } - public record Admitted( - CanonicalPlayableTarget target, - CanonicalGameplayBindingIdentity binding, - UUID transitionId, - BigInteger bindingGeneration, - String roomKey, - long expiresAtMillis) {} + public PlayerOutput look(Admitted admitted) { + requireCurrentAdmission(admitted); + var view = + gameLogic.resolveRunOwnedFixtureLook( + ReadRunOwnedFixtureLookRoomRequest.newBuilder() + .setLifecycle( + WorldCanonicalInstanceLifecycleGrpcCodec.toRequest(admitted.lifecycle)) + .setExpectedRoomInstanceKey(admitted.roomKey) + .build()); + var room = view.getRoomInstance(); + if (view.hasError() + || !view.hasRoomInstance() + || !admitted.lifecycle.canonicalTenantId().toString().equals(room.getTenantId()) + || !admitted.lifecycle.canonicalGameInstanceId().toString().equals(room.getGameInstanceId()) + || !admitted.roomKey.equals(room.getRoomInstanceId())) { + throw unavailable(); + } + requireCurrentAdmission(admitted); + return lookRenderer.toPlayerOutput(view); + } + + private void requireCurrentAdmission(Admitted admitted) { + fixture.loadFixedVerifiedEvidence().requireVerifiedFixture(); + var result = admitted.finalAdmission; + var readOwner = + new CanonicalGameplayOriginalNewFinalAdmissionReadRepository( + dsl, + standIns.coordination(), + standIns.tags(), + admitted.lifecycle.targetNamespace(), + clock); + var current = + readOwner.readActualOriginalFinalAdmission( + result.finalReadSelector(), admitted.lifecycle.targetNamespace()); + if (!result.finalSessionSha256().equals(current.canonicalSessionSha256()) + || result.continuityExpiresAtMillis() != current.continuityExpiresAtMillis()) { + throw unavailable(); + } + // The fixture has no World placement for its stand-in actors. Only a lone viewer is known. + if (!Boolean.FALSE.equals( + dsl.fetchValue( + "SELECT EXISTS (SELECT 1 FROM game_session_canonical_gameplay_binding_inventory" + + " WHERE tenant_id = ? AND game_instance_id = ? AND transition_id <> ?" + + " AND lifecycle <> 'TERMINAL')", + admitted.lifecycle.canonicalTenantId(), + admitted.lifecycle.canonicalGameInstanceId(), + result.transitionId()))) { + throw unavailable(); + } + } + + public static final class Admitted { + private final WorldCanonicalInstanceLifecycleEvidence.Request lifecycle; + private final String roomKey; + private final CanonicalGameplayOriginalNewFinalAdmissionCoordinator.FinalAdmissionResult + finalAdmission; + + private Admitted( + WorldCanonicalInstanceLifecycleEvidence.Request lifecycle, + String roomKey, + CanonicalGameplayOriginalNewFinalAdmissionCoordinator.FinalAdmissionResult finalAdmission) { + this.lifecycle = lifecycle; + this.roomKey = roomKey; + this.finalAdmission = finalAdmission; + } + } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1RunOwnedFixturePlayRegion.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1RunOwnedFixturePlayRegion.java index 645c267485..8f53dae00e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1RunOwnedFixturePlayRegion.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1RunOwnedFixturePlayRegion.java @@ -129,6 +129,7 @@ Prepared prepare(CanonicalPlayableTarget target, UUID accountId) { assignment.operationalRegionId(), expectedRegionEpoch, request, + lifecycleSelector, startRoom.roomKey(), bridge); } @@ -333,6 +334,7 @@ record Prepared( UUID operationalRegionId, long regionEpoch, CanonicalInitialPlayerLocationRequest request, + WorldCanonicalInstanceLifecycleEvidence.Request lifecycleSelector, String roomKey, CanonicalGameplayRegionBindingBridgeOwner bridge) { Prepared { @@ -340,6 +342,7 @@ record Prepared( requireNonNil(operationalRegionId, "operationalRegionId"); if (regionEpoch <= 0L) throw new IllegalArgumentException("regionEpoch must be positive"); Objects.requireNonNull(request, "request"); + Objects.requireNonNull(lifecycleSelector, "lifecycleSelector"); Objects.requireNonNull(roomKey, "roomKey"); Objects.requireNonNull(bridge, "bridge"); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java index 7a8de891d0..7e70039e04 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java @@ -112,6 +112,7 @@ public TextCommandInterpretationResult receive(WebSocketSession socket, TextComm }); } case PLAY -> play(connection, command); + case LOOK -> look(connection, command); case LOGOUT -> success("Logged out"); default -> failure("FEATURE_UNAVAILABLE", "Command unavailable"); }; @@ -189,6 +190,22 @@ private TextCommandInterpretationResult play( }); } + private TextCommandInterpretationResult look( + AuthenticatedDirectTextSessions.Connection connection, TextCommand command) { + if (!command.args().isEmpty()) return failure("INVALID_ARGUMENT", "Usage: LOOK"); + var admitted = connection.admitted; + if (admitted == null || !connection.isCurrent()) return admissionUnavailable(); + try { + var result = required(admissions).look(admitted); + if (!connection.isCurrent() || connection.admitted != admitted) { + return admissionUnavailable(); + } + return new TextCommandInterpretationResult(CommandEnqueueResult.success(), List.of(result)); + } catch (RuntimeException unavailable) { + return failure("ROOM_UNAVAILABLE", "The current room is unavailable"); + } + } + private static TextCommandInterpretationResult admissionUnavailable() { return failure("ADMISSION_UNAVAILABLE", "Canonical gameplay admission unavailable"); } diff --git a/services/tcp-proxy-service/telnet-login-look-smoke.sh b/services/tcp-proxy-service/telnet-login-look-smoke.sh index d86570ae03..e29674ecc9 100755 --- a/services/tcp-proxy-service/telnet-login-look-smoke.sh +++ b/services/tcp-proxy-service/telnet-login-look-smoke.sh @@ -172,7 +172,7 @@ if os.environ["SMOKE_MUTATION_EXTENSION"] == "true": discovery_selector = world login_wait_seconds = 0 else: - steps = authenticated_telnet_play_steps(login_email, password, world, worlds_expect, login_expect, play_expect) + steps = authenticated_telnet_play_steps(login_email, password, world, worlds_expect, login_expect, play_expect, look_expect) discovery_selector = None # Authenticated LOGIN answers UNAVAILABLE until the Account JWT signer is promoted, which the # pre-v1 stand-ins complete a few minutes after Account starts. @@ -191,5 +191,5 @@ run_telnet_smoke_session( if os.environ["SMOKE_MUTATION_EXTENSION"] == "true": print("Telnet WORLDS + LOGIN + PLAY + item/container/equipment mutation extension passed.") else: - print("Telnet LOGIN + WORLDS + REALMS + JOIN + PLAY baseline smoke test passed.") + print("Telnet LOGIN + WORLDS + REALMS + JOIN + PLAY + LOOK baseline smoke test passed.") PYTHON diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/config/RunOwnedFixtureInitialAdmissionHoldConfiguration.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/config/RunOwnedFixtureInitialAdmissionHoldConfiguration.java index 9df0918cd4..71648a513a 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/config/RunOwnedFixtureInitialAdmissionHoldConfiguration.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/config/RunOwnedFixtureInitialAdmissionHoldConfiguration.java @@ -4,7 +4,10 @@ import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.prev1.PreV1GateWaivers; import net.firedevops.firemud.worldmanagement.client.GrpcGameSessionCanonicalInitialAdmissionOwnerClient; +import net.firedevops.firemud.worldmanagement.service.RoomService; +import net.firedevops.firemud.worldmanagement.service.impl.RunOwnedFixtureLookWorldGrpcService; import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeRepository; import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityRepository; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInitialAdmissionHoldGrpcService; @@ -19,6 +22,7 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; import org.springframework.transaction.PlatformTransactionManager; /** @@ -72,6 +76,19 @@ WorldCanonicalInstanceLifecycleReadGrpcService runOwnedFixtureInstanceLifecycleR return new WorldCanonicalInstanceLifecycleReadGrpcService(lifecycle, namespace); } + @Bean + @ConditionalOnProperty(name = PreV1GateWaivers.PROPERTY, havingValue = "true") + RunOwnedFixtureLookWorldGrpcService runOwnedFixtureLookWorldGrpcService( + WorldCanonicalInstanceLifecycleReadRepository lifecycle, + RoomService rooms, + Environment environment, + @Value("${firemud.grpc.workload-namespace:}") String namespace) { + if (!PreV1GateWaivers.from(environment).enabled()) { + throw new IllegalStateException("Run-owned fixture LOOK requires pre-v1 gate waivers"); + } + return new RunOwnedFixtureLookWorldGrpcService(lifecycle, rooms, namespace); + } + @Bean WorldCanonicalInitialAdmissionHoldGrpcService runOwnedFixtureInitialAdmissionHoldGrpcService( DSLContext dsl, diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/RunOwnedFixtureLookWorldGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/RunOwnedFixtureLookWorldGrpcService.java new file mode 100644 index 0000000000..8089dfe595 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/RunOwnedFixtureLookWorldGrpcService.java @@ -0,0 +1,99 @@ +package net.firedevops.firemud.worldmanagement.service.impl; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleGrpcCodec; +import net.firedevops.firemud.worldmanagement.service.RoomService; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceLifecycleReadRepository; +import net.firedevops.firemud.worldmanagement.v1.ReadRunOwnedFixtureLookRoomRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadRunOwnedFixtureLookRoomResponse; +import net.firedevops.firemud.worldmanagement.v1.RunOwnedFixtureLookWorldServiceGrpc; + +/** Reads actual World-owned topology and prose for the active run-owned fixture. */ +public final class RunOwnedFixtureLookWorldGrpcService + extends RunOwnedFixtureLookWorldServiceGrpc.RunOwnedFixtureLookWorldServiceImplBase { + private final WorldCanonicalInstanceLifecycleReadRepository lifecycle; + private final RoomService rooms; + private final String namespace; + + public RunOwnedFixtureLookWorldGrpcService( + WorldCanonicalInstanceLifecycleReadRepository lifecycle, + RoomService rooms, + String namespace) { + this.lifecycle = Objects.requireNonNull(lifecycle); + this.rooms = Objects.requireNonNull(rooms); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("A World workload namespace is required"); + } + this.namespace = namespace; + } + + @Override + public void readRunOwnedFixtureLookRoom( + ReadRunOwnedFixtureLookRoomRequest wire, + StreamObserver observer) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null) { + observer.onError(Status.UNAUTHENTICATED.asRuntimeException()); + return; + } + if (!peer.isService("game-logic-service") + || !peer.isInNamespace(namespace) + || SessionContext.hasAuthenticatedCallerContext() + || SessionContext.isInternalService()) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + + WorldCanonicalInstanceLifecycleEvidence.Request request; + try { + if (!wire.hasLifecycle() + || !wire.getUnknownFields().asMap().isEmpty() + || !wire.getExpectedRoomInstanceKey().matches("R-[1-9][0-9]{0,18}") + || wire.getPreferredLocale().length() > 128) { + throw new IllegalArgumentException("An exact fixture room selector is required"); + } + request = WorldCanonicalInstanceLifecycleGrpcCodec.fromRequest(wire.getLifecycle()); + } catch (IllegalArgumentException invalid) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + if (!namespace.equals(request.targetNamespace())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + + ReadRunOwnedFixtureLookRoomResponse response; + try { + var view = + lifecycle.readRunOwnedFixtureStartRoomView( + request, wire.getExpectedRoomInstanceKey(), wire.getPreferredLocale(), rooms); + if (view.isEmpty()) { + observer.onError(Status.NOT_FOUND.asRuntimeException()); + return; + } + var starter = view.orElseThrow(); + String tenant = request.canonicalTenantId().toString(); + String game = request.canonicalGameInstanceId().toString(); + String room = wire.getExpectedRoomInstanceKey(); + response = + ReadRunOwnedFixtureLookRoomResponse.newBuilder() + .setLifecycle( + WorldCanonicalInstanceLifecycleGrpcCodec.toFixtureResponse( + request, starter.lifecycle())) + .setSnapshot( + WorldManagementGrpcService.projectRoomSnapshot( + starter.snapshot(), tenant, game, tenant + ":" + game + ":" + room)) + .build(); + } catch (RuntimeException unavailable) { + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + return; + } + observer.onNext(response); + observer.onCompleted(); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcService.java index d66a911be9..4e1897248c 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcService.java @@ -671,18 +671,28 @@ public void getRoomSnapshot( } private RoomSnapshot toProto(RoomSnapshotDto snapshot) { + return projectRoomSnapshot( + snapshot, + snapshot.tenantId().toString(), + snapshot.gameInstanceId().toString(), + readFence( + snapshot.tenantId(), + snapshot.gameInstanceId(), + RuntimeRoomInstanceIds.canonical(snapshot.roomInstanceRowId()))); + } + + static RoomSnapshot projectRoomSnapshot( + RoomSnapshotDto snapshot, String tenantId, String gameInstanceId, String scopeMarker) { RoomSnapshot.Builder builder = RoomSnapshot.newBuilder(); - String runtimeRoomInstanceId = RuntimeRoomInstanceIds.canonical(snapshot.roomInstanceRowId()); builder - .setRoomInstanceId(runtimeRoomInstanceId) - .setTenantId(snapshot.tenantId().toString()) - .setGameInstanceId(snapshot.gameInstanceId().toString()) - .setWorldSnapshotId( - readFence(snapshot.tenantId(), snapshot.gameInstanceId(), runtimeRoomInstanceId)) + .setRoomInstanceId(RuntimeRoomInstanceIds.canonical(snapshot.roomInstanceRowId())) + .setTenantId(tenantId) + .setGameInstanceId(gameInstanceId) + .setWorldSnapshotId(scopeMarker) .setRoomName(snapshot.roomName()) .setShortDescription(snapshot.shortDescription()) .setLongDescription(snapshot.longDescription()); - snapshot.exits().forEach(exit -> builder.addExits(toProto(exit))); + snapshot.exits().forEach(exit -> builder.addExits(projectRoomExit(exit))); if (snapshot.ambientState() != null) { applyAmbientState(builder, snapshot); } @@ -779,7 +789,7 @@ private WorldInstanceLifecycleStatus toProtoStatus(String status) { }; } - private void applyAmbientState(RoomSnapshot.Builder builder, RoomSnapshotDto snapshot) { + private static void applyAmbientState(RoomSnapshot.Builder builder, RoomSnapshotDto snapshot) { String weather = snapshot.ambientState().get("weather"); if (weather == null || weather.isBlank()) { return; @@ -791,7 +801,7 @@ private void applyAmbientState(RoomSnapshot.Builder builder, RoomSnapshotDto sna .build()); } - private RoomExitSnapshot toProto(RoomExitSnapshotDto exit) { + private static RoomExitSnapshot projectRoomExit(RoomExitSnapshotDto exit) { RoomExitSnapshot.Builder builder = RoomExitSnapshot.newBuilder(); String targetRuntimeRoomInstanceId = RuntimeRoomInstanceIds.canonical(exit.targetRoomInstanceRowId()); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java index 0c40409f34..22eb7d1052 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java @@ -23,6 +23,8 @@ import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.common.world.WorldRunOwnedFixtureLifecycleEvidence; import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldFixedPresetResources; +import net.firedevops.firemud.worldmanagement.dto.RoomSnapshotDto; +import net.firedevops.firemud.worldmanagement.service.RoomService; import net.firedevops.firemud.worldmanagement.v1.WorldInboundSourceFamily; import org.jooq.DSLContext; import org.jooq.Record; @@ -157,6 +159,57 @@ public Optional readRunOwnedFixtureStartRoom( public record FixtureStartRoom(WorldRunOwnedFixtureLifecycleEvidence lifecycle, String roomKey) {} + /** + * Reads the existing room snapshot only after the exact ACTIVE fixture and its mapped starter + * room match the requested room key in the same owner snapshot. Private numeric selectors are + * resolved solely from retained World evidence; inconsistent room readback is refused. + */ + public Optional readRunOwnedFixtureStartRoomView( + WorldCanonicalInstanceLifecycleEvidence.Request request, + String expectedRoomKey, + String preferredLocale, + RoomService rooms) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(expectedRoomKey, "expectedRoomKey"); + Objects.requireNonNull(rooms, "rooms"); + requireNoActiveTransaction("World run-owned fixture start-room view read"); + return Optional.ofNullable( + transaction.execute( + status -> { + requireReadOnlyRepeatableReadOwnerTransaction(); + var fixture = readRunOwnedFixtureSnapshotInCurrentOwnerTransaction(request); + if (fixture == null || !"ACTIVE".equals(fixture.lifecycle().lifecycleStatus())) { + return null; + } + long roomId = requireRunOwnedFixtureStartRoom(fixture.association()); + if (!("R-" + roomId).equals(expectedRoomKey)) { + return null; + } + if (!Boolean.FALSE.equals( + dsl.fetchValue( + "SELECT EXISTS (SELECT 1 FROM character_location" + + " WHERE canonical_game_instance_id = ? AND runtime_room_instance_id = ?)", + request.canonicalGameInstanceId(), + roomId))) { + throw invalid("Run-owned starter LOOK does not support populated World occupancy"); + } + var keys = fixture.association().runOwnedFixture().worldPrivateKeys(); + RoomSnapshotDto snapshot = + rooms.getRoomSnapshot( + keys.tenantId(), keys.gameInstanceId(), roomId, preferredLocale); + if (snapshot == null + || !Long.valueOf(roomId).equals(snapshot.roomInstanceRowId()) + || !Long.valueOf(keys.tenantId()).equals(snapshot.tenantId()) + || !Long.valueOf(keys.gameInstanceId()).equals(snapshot.gameInstanceId())) { + throw invalid("Run-owned fixture room snapshot differs from its mapped room scope"); + } + return new FixtureStartRoomView(fixture.lifecycle(), snapshot); + })); + } + + public record FixtureStartRoomView( + WorldRunOwnedFixtureLifecycleEvidence lifecycle, RoomSnapshotDto snapshot) {} + private record RunOwnedFixtureSnapshot( WorldCanonicalInstanceAssociation association, WorldRunOwnedFixtureLifecycleEvidence lifecycle) {} diff --git a/services/world-management-service/src/main/resources/application.yml b/services/world-management-service/src/main/resources/application.yml index fb4069798e..dc81661608 100644 --- a/services/world-management-service/src/main/resources/application.yml +++ b/services/world-management-service/src/main/resources/application.yml @@ -94,6 +94,7 @@ firemud: - world_management.v1.WorldCanonicalInitialAdmissionHoldService/ReadCanonicalInitialAdmissionHoldState - world_management.v1.WorldCanonicalInstanceLifecycleReadService/ReadWorldCanonicalInstanceLifecycle - world_management.v1.WorldCanonicalInstanceLifecycleReadService/ReadRunOwnedFixtureStartRoom + - world_management.v1.RunOwnedFixtureLookWorldService/ReadRunOwnedFixtureLookRoom grpc: cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResourcesPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResourcesPostgresIntegrationTest.java index c4533487c7..37a4d30b01 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResourcesPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResourcesPostgresIntegrationTest.java @@ -49,8 +49,12 @@ import net.firedevops.firemud.worldmanagement.client.GameDesignClient; import net.firedevops.firemud.worldmanagement.client.GameSessionClient; import net.firedevops.firemud.worldmanagement.client.GrpcGameSessionInitialAdmissionBindProofClient; +import net.firedevops.firemud.worldmanagement.config.WorldProperties; import net.firedevops.firemud.worldmanagement.dto.PreparedWorldInstanceRequest; import net.firedevops.firemud.worldmanagement.dto.WorldInstanceLifecycleSnapshotDto; +import net.firedevops.firemud.worldmanagement.repository.RoomInstanceExitRepository; +import net.firedevops.firemud.worldmanagement.repository.RoomInstanceRepository; +import net.firedevops.firemud.worldmanagement.service.impl.RoomServiceImpl; import net.firedevops.firemud.worldmanagement.service.impl.RunOwnedWorldFixtureLifecycleTestFactory; import net.firedevops.firemud.worldmanagement.service.impl.WorldLifecycleCommandServiceImpl; import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeReceipt; @@ -943,6 +947,27 @@ void activeFixtureAcquiresAndReadsTypedInitialAdmissionHoldWithFixtureLifecycle( .isEqualTo(lifecycleRepository.readRunOwnedFixture(lifecycleRequest).orElseThrow()); assertThat(room.lifecycle().lifecycleStatus()).isEqualTo("ACTIVE"); + var rooms = + new RoomServiceImpl( + new RoomInstanceRepository(dsl), + null, + null, + new WorldProperties(), + new RoomInstanceExitRepository(dsl), + tools.jackson.databind.json.JsonMapper.builder().build()); + var view = + lifecycleRepository + .readRunOwnedFixtureStartRoomView(lifecycleRequest, room.roomKey(), "", rooms) + .orElseThrow(); + assertThat(view.lifecycle()).isEqualTo(room.lifecycle()); + assertThat(view.snapshot().roomInstanceRowId()).isEqualTo(storedStartRoom); + assertThat(view.snapshot().roomName()).isEqualTo("Candle-lit Antechamber"); + assertThat(view.snapshot().longDescription()).isNotBlank(); + assertThat( + lifecycleRepository.readRunOwnedFixtureStartRoomView( + lifecycleRequest, "R-0", "", rooms)) + .isEmpty(); + var hold = holds.acquire(holdRequest, lifecycleRequest); assertThat(holds.acquire(holdRequest, lifecycleRequest)).isEqualTo(hold); var state = holds.readState(hold, lifecycleRequest).orElseThrow(); From 473043bb63b749ff16e04a015a6b50df9189004e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:10:36 +1300 Subject: [PATCH 13/28] Exercise malformed discovery evidence and exact protected RPC registration --- ...anonicalGameplayAdmissionDecisionReadGrpcServiceTest.java | 3 +-- ...CanonicalGameplayRosterOwnerReadInterceptorChainTest.java | 5 ++++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java index f09b40e6dd..8232d907ad 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java @@ -137,8 +137,7 @@ void discoveryReturnsCompletePlayerCreatedAndMixedPolicyCollectionsOnBothReads() @Test void discoveryDoesNotHideMalformedPlayerCreatedAuthority() { var created = discoveryTarget("created", "World", "PLAYER_CREATED"); - var malformed = - mock(CanonicalPlayableTarget.class, org.mockito.AdditionalAnswers.delegatesTo(created)); + var malformed = org.mockito.Mockito.spy(created); org.mockito.Mockito.doReturn("not-a-proof-digest").when(malformed).ownerProofDigest(); var routes = mock(CanonicalPlayerRouteReadService.class); when(routes.readVisiblePublicProductionTargets()).thenReturn(List.of(malformed)); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/CanonicalGameplayRosterOwnerReadInterceptorChainTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/CanonicalGameplayRosterOwnerReadInterceptorChainTest.java index e61442cf4c..a8cd342187 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/CanonicalGameplayRosterOwnerReadInterceptorChainTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/CanonicalGameplayRosterOwnerReadInterceptorChainTest.java @@ -314,7 +314,10 @@ private static AuthTokenInterceptor configuredAuthInterceptor() { "game_session.v1.CanonicalGameplayAdmissionDecisionReadService/ResolvePublishedRealmAdmissionTarget", "game_session.v1.CanonicalGameplayAdmissionDecisionReadService/GetOriginalNewNeverAdmittedDecision", "game_session.v1.CanonicalGameplayAdmissionDecisionReadService/GetCanonicalGameplayAdmissionDecision", - "game_session.v1.CanonicalGameplayAdmissionDecisionReadService/GetPublishedRealmAdmissionOwnerRead") + "game_session.v1.CanonicalGameplayAdmissionDecisionReadService/GetPublishedRealmAdmissionOwnerRead", + "game_session.v1.OriginalNewFinalAdmissionReadService/ReadOriginalNewFinalAdmission", + "game_session.v1.OriginalNewCapacityExecutionReadService/ReadOriginalNewCapacityExecution", + "game_session.v1.OriginalNewCapacityExecutionReadService/ReadHistoricalOriginalNewCapacityFinal") .doesNotContain("game_session.v1.*"); Set publicMethods = Set.copyOf(configured); return new AuthTokenInterceptor( From d9eae8060294bbf49c9fbd61e045a1e10859cb86 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:10:36 +1300 Subject: [PATCH 14/28] Give the run-owned admission services one CPU each --- docker/docker-compose.pre-v1-login.override.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docker/docker-compose.pre-v1-login.override.yml b/docker/docker-compose.pre-v1-login.override.yml index 9dcc7ef99c..9737651680 100644 --- a/docker/docker-compose.pre-v1-login.override.yml +++ b/docker/docker-compose.pre-v1-login.override.yml @@ -101,6 +101,8 @@ services: start_period: 30s account-service: + # The first protected admission issues a credential and reserves capacity within a 15 s lease. + cpus: "1.0" # The pre-v1 signer, readiness and gameplay-login owners exceed the 512m default; a CI run # lost Account without an error on its first post-promotion LOGIN. mem_limit: 1g @@ -141,6 +143,8 @@ services: - ${FIREMUD_PRE_V1_SIGNER_FIXTURES:?run the pre-v1 signer fixtures first}/world-runtime-installation:/etc/firemud/world-runtime-installation:ro game-session-service: + # Candidate installation and final readback share the same admission lease. + cpus: "1.0" # Authenticated LOGIN needs a promoted Account signer; start only once it is live. depends_on: pre-v1-jwt-materializer: From 9c13b479197b8c4c0255feb83200d935ba5a1fec Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:16:03 +1300 Subject: [PATCH 15/28] Report LOOK admission and room failures at their owning stage --- .../PreV1CanonicalPlayAdmissionOwner.java | 17 ++++++++++ ...uthenticatedDirectTextCommandReceiver.java | 33 ++++++++++++------- ...nticatedDirectTextCommandReceiverTest.java | 11 +++++++ 3 files changed, 49 insertions(+), 12 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayAdmissionOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayAdmissionOwner.java index 4c91b6c739..686f8ce2f2 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayAdmissionOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayAdmissionOwner.java @@ -346,6 +346,17 @@ public PlayerOutput look(Admitted admitted) { } private void requireCurrentAdmission(Admitted admitted) { + try { + verifyCurrentLookAdmission(admitted); + } catch (RuntimeException failure) { + LOG.warn( + "Run-owned LOOK admission recheck unavailable type={}", + failure.getClass().getSimpleName()); + throw new LookAdmissionUnavailableException(); + } + } + + private void verifyCurrentLookAdmission(Admitted admitted) { fixture.loadFixedVerifiedEvidence().requireVerifiedFixture(); var result = admitted.finalAdmission; var readOwner = @@ -375,6 +386,12 @@ private void requireCurrentAdmission(Admitted admitted) { } } + public static final class LookAdmissionUnavailableException extends IllegalStateException { + private LookAdmissionUnavailableException() { + super("Run-owned LOOK admission unavailable"); + } + } + public static final class Admitted { private final WorldCanonicalInstanceLifecycleEvidence.Request lifecycle; private final String roomKey; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java index 7e70039e04..8017e82ad5 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java @@ -117,7 +117,7 @@ public TextCommandInterpretationResult receive(WebSocketSession socket, TextComm default -> failure("FEATURE_UNAVAILABLE", "Command unavailable"); }; } catch (AuthenticatedDirectTextSessions.LoginRequiredException missingLogin) { - return failure("LOGIN_REQUIRED", "Use LOGIN before REALMS, JOIN, or PLAY"); + return failure("LOGIN_REQUIRED", "Use LOGIN to authenticate"); } catch (ExpiredWorldSelectionException expiredSelection) { return failure( "INVALID_ARGUMENT", "World menu expired. Run WORLDS and choose a listed selector again."); @@ -193,17 +193,26 @@ private TextCommandInterpretationResult play( private TextCommandInterpretationResult look( AuthenticatedDirectTextSessions.Connection connection, TextCommand command) { if (!command.args().isEmpty()) return failure("INVALID_ARGUMENT", "Usage: LOOK"); - var admitted = connection.admitted; - if (admitted == null || !connection.isCurrent()) return admissionUnavailable(); - try { - var result = required(admissions).look(admitted); - if (!connection.isCurrent() || connection.admitted != admitted) { - return admissionUnavailable(); - } - return new TextCommandInterpretationResult(CommandEnqueueResult.success(), List.of(result)); - } catch (RuntimeException unavailable) { - return failure("ROOM_UNAVAILABLE", "The current room is unavailable"); - } + return connection.withLogin( + (original, login) -> { + var admitted = connection.admitted; + if (admitted == null) return failure("PLAY_REQUIRED", "Use PLAY to enter a world"); + if (!connection.isCurrent()) return admissionUnavailable(); + var owner = admissions.getIfAvailable(); + if (owner == null) return admissionUnavailable(); + try { + var result = owner.look(admitted); + if (!connection.isCurrent() || connection.admitted != admitted) { + return admissionUnavailable(); + } + return new TextCommandInterpretationResult( + CommandEnqueueResult.success(), List.of(result)); + } catch (PreV1CanonicalPlayAdmissionOwner.LookAdmissionUnavailableException unavailable) { + return admissionUnavailable(); + } catch (RuntimeException unavailable) { + return failure("ROOM_UNAVAILABLE", "The current room is unavailable"); + } + }); } private static TextCommandInterpretationResult admissionUnavailable() { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java index 938a358e75..876f1afbba 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java @@ -233,6 +233,17 @@ void loginAndLobbyObservationsNeverSubstituteForCanonicalPlayAdmission() { verifyNoInteractions(fixture.lobby, fixture.selections); } + @Test + void lookBeforePlayRequiresAdmissionOnTheSameConnection() { + var fixture = fixture(); + var command = new TextCommand(TextCommandType.LOOK, List.of(), "LOOK"); + + var result = fixture.receiver.receive(fixture.socket, command); + + assertThat(result.commandResult().errorCode()).isEqualTo("PLAY_REQUIRED"); + verifyNoInteractions(fixture.lobby, fixture.selections); + } + @ParameterizedTest @MethodSource("malformedCommands") void malformedCommandsReturnUsageBeforeOwnerOrLoginDispatch(TextCommand command) { From 098733479b52cd3e3b287eef72de3540542a2a5a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:35:35 +1300 Subject: [PATCH 16/28] Preserve the historical Human region cohort projection --- .../CanonicalGameplayIssuerCohortSql.java | 12 ++++--- ...berOperationRepositoryIntegrationTest.java | 32 +++++++++++++++++++ 2 files changed, 40 insertions(+), 4 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerCohortSql.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerCohortSql.java index 46916de314..d3c323a8bc 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerCohortSql.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerCohortSql.java @@ -65,7 +65,7 @@ final class CanonicalGameplayIssuerCohortSql { // V1042's untouched bridge extension is absence-equivalent to the old row shape. // Its CHECK makes every extension field NULL until a real bridge operation exists. // Once materialized, capture the entire bridge source, including all readback evidence. - + " CASE WHEN to_jsonb(g)->'bridge_operation_id' = 'null'::jsonb" + + " (CASE WHEN to_jsonb(g)->'bridge_operation_id' = 'null'::jsonb" + " AND (to_jsonb(g)->'entity_created_origin' IS NULL" + " OR to_jsonb(g)->'entity_created_origin' = 'null'::jsonb)" + " THEN (to_jsonb(g) - ARRAY['bridge_operation_id', 'bridge_preimage_state'," @@ -75,10 +75,14 @@ final class CanonicalGameplayIssuerCohortSql { + " 'world_lifecycle_epoch', 'world_lifecycle_row_version', 'world_capture_id'," + " 'world_graph_sha256', 'world_preparation_input_digest', 'executor_fence'," + " 'lease_token_correlation', 'redis_readback_digest', 'acknowledged_at'," - + " 'entity_created_origin'])::text" + + " 'entity_created_origin'])" + " WHEN to_jsonb(g)->'entity_created_origin' = 'null'::jsonb" - + " THEN (to_jsonb(g) - 'entity_created_origin')::text" - + " ELSE to_jsonb(g)::text END AS source_row_json" + + " THEN to_jsonb(g) - 'entity_created_origin'" + + " ELSE to_jsonb(g) END" + // Before V1072 every region obligation used Human capture. Keep that frozen shape + // and retain an explicit run-owned World source in every fixture cohort. + + " - CASE WHEN to_jsonb(g)->>'world_source_kind' = 'HUMAN_CAPTURE'" + + " THEN ARRAY['world_source_kind'] ELSE ARRAY[]::text[] END)::text AS source_row_json" + " FROM game_session_canonical_binding_region_bridge_obligation g" + " WHERE g.inventory_revision <= ?" + ") captured_cohort ORDER BY source_kind COLLATE \"C\", source_key COLLATE \"C\""; diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepositoryIntegrationTest.java index 76f3eeb7b8..65fe9cb60c 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepositoryIntegrationTest.java @@ -387,6 +387,38 @@ void groupedPartitionWorkIssuesAllExactOperationsConcurrentlyAndLeavesEmptyParti } } + @Test + void changedWorldSourceKindDoesNotMatchHistoricalHumanObligation() { + Fixture fixture = + pendingFixture( + "gs_bootstrap_member_world_kind_", PARTITION_CAPACITY, LAYOUT_VERSION, false, true); + try { + migrateRemaining(fixture.testSchema()); + var dsl = fixture.testSchema().dsl(); + assertThat( + dsl.execute( + "UPDATE game_session_canonical_binding_region_bridge_obligation" + + " SET world_source_kind = 'RUN_OWNED_FIXTURE' WHERE transition_id = ?", + fixture.preparedBinding().transitionId())) + .isEqualTo(1); + var owner = new CanonicalGameplayIssuerBootstrapMemberOperationRepository(dsl); + assertThatThrownBy( + () -> + owner.preparePartitionWork( + fixture.intent().operationId(), + fixture.requestId(), + fixture.partitionId(), + fixture.currentAccountCheckpoint(), + stableIncarnation("stable-a"))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Current source row differs from its exact original bootstrap cohort entry"); + assertThat(rowImages(dsl, "game_session_canonical_issuer_bootstrap_member_operation")) + .isEmpty(); + } finally { + dropSchema(fixture.testSchema().schema()); + } + } + @Test void wrongRequestCheckpointAndChangedFrozenSourceRefuseWithoutAllocatingCounters() { Fixture fixture = From ed6c3d72fdcc5037181ed661228285cf83dae04b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:35:35 +1300 Subject: [PATCH 17/28] Authenticate fixture LOOK with the exact Game Logic workload --- dev-tools/certs/ensure-dev-certs.sh | 4 +-- dev-tools/tests/compose-grpc-mtls-contract.sh | 35 ++++++++++++++++--- .../gamesession/client/GameLogicClient.java | 25 +++++++++---- 3 files changed, 50 insertions(+), 14 deletions(-) diff --git a/dev-tools/certs/ensure-dev-certs.sh b/dev-tools/certs/ensure-dev-certs.sh index 5faf6898a7..6faf5a389d 100644 --- a/dev-tools/certs/ensure-dev-certs.sh +++ b/dev-tools/certs/ensure-dev-certs.sh @@ -144,7 +144,7 @@ ensure_compose_mtls_certs() { for service in "${services[@]}"; do local service_dir="$COMPOSE_MTLS_STAGE_DIR/$service" mkdir -m 755 -- "$service_dir" - if [[ "$service" == account-service || "$service" == game-session-service || "$service" == entity-management-service || "$service" == world-management-service || "$service" == game-design-service || "$service" == tcp-proxy-service ]]; then + if [[ "$service" == account-service || "$service" == game-session-service || "$service" == entity-management-service || "$service" == world-management-service || "$service" == game-design-service || "$service" == game-logic-service || "$service" == tcp-proxy-service ]]; then "$GENERATOR" --workload \ "$authority_dir/ca.crt" "$authority_dir/ca.key" \ "$service_dir/client.crt" "$service_dir/client.key" dev "$service" @@ -217,7 +217,7 @@ ensure_compose_mtls_certs() { echo "Compose mTLS workload has the wrong SPIFFE identity: gateway" >&2 return 1 fi - for service in account-service game-session-service entity-management-service world-management-service game-design-service tcp-proxy-service; do + for service in account-service game-session-service entity-management-service world-management-service game-design-service game-logic-service tcp-proxy-service; do local san_output san_output="$(openssl x509 -in "$workloads_dir/$service/client.crt" -noout -ext subjectAltName)" if [[ "$service" == game-design-service ]]; then diff --git a/dev-tools/tests/compose-grpc-mtls-contract.sh b/dev-tools/tests/compose-grpc-mtls-contract.sh index 1531e559b4..f8300b2560 100644 --- a/dev-tools/tests/compose-grpc-mtls-contract.sh +++ b/dev-tools/tests/compose-grpc-mtls-contract.sh @@ -270,7 +270,8 @@ for service in "${services[@]}"; do done identity_services=( - account-service game-session-service entity-management-service world-management-service game-design-service + account-service game-session-service entity-management-service world-management-service + game-design-service game-logic-service ) declare -A identity_fingerprints=() for service in "${identity_services[@]}"; do @@ -301,6 +302,7 @@ for service in ( "world-management-service", "game-session-service", "game-design-service", + "game-logic-service", "logging-admin-service", ): headers = [index for index, line in enumerate(lines) if line == f" {service}:"] @@ -367,7 +369,10 @@ fixture_keys = ( "FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH", "FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_PATH", ) -fixture_services = ("game-design-service", "game-session-service", "world-management-service") +fixture_services = ( + "account-service", "entity-management-service", "game-design-service", + "game-session-service", "world-management-service", +) for service, block in service_blocks.items(): if service in fixture_services: for key in fixture_keys: @@ -408,7 +413,14 @@ for service, block in service_blocks.items(): assert any(line == f" target: {source_receipt_dir}" for line in block) assert any(line == " read_only: true" for line in block) else: - assert not any(any(key in line for key in fixture_keys) for line in block), service + activation = fixture_keys[2] + if service == "game-logic-service": + assert any(line.startswith(f" {activation}:") for line in block) + restricted_keys = ( + tuple(key for key in fixture_keys if key != activation) + if service == "game-logic-service" else fixture_keys + ) + assert not any(any(key in line for key in restricted_keys) for line in block), service assert not any(capability_path in line for line in block), service assert not any(source_receipt_dir in line for line in block), service assert not any(game_session_leaf_path in line for line in block), service @@ -514,7 +526,10 @@ app_names = { "game-session-service", "logging-admin-service", "social-groups-service", "tcp-proxy-service", "world-management-service", } -fixture_services = ("game-design-service", "game-session-service", "world-management-service") +fixture_services = ( + "account-service", "entity-management-service", "game-design-service", + "game-session-service", "world-management-service", +) for name in app_names: service = services[name] environment = service.get("environment", {}) @@ -530,7 +545,7 @@ for name in app_names: assert service.get("build") is None, f"image-only proof must not build {name}" for name in ( "account-service", "game-session-service", "entity-management-service", - "world-management-service", "game-design-service", "logging-admin-service", + "world-management-service", "game-design-service", "game-logic-service", "logging-admin-service", ): namespace = services[name]["environment"].get("FIREMUD_GRPC_WORKLOAD_NAMESPACE") assert namespace == "dev", (name, namespace) @@ -597,6 +612,16 @@ world_management_receipt_mounts = [mount for mount in world_management.get("volu assert len(world_management_receipt_mounts) == 1, world_management_receipt_mounts assert world_management_receipt_mounts[0]["source"] == source_receipt_source, world_management_receipt_mounts[0] assert world_management_receipt_mounts[0].get("read_only") is True +for name in ("account-service", "entity-management-service"): + service = services[name] + environment = service["environment"] + assert environment.get("FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED") == "false", name + assert environment.get("FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH") == capability_path, name + assert environment.get("FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_PATH") == source_receipt_path, name + for target, source in ((capability_path, capability_source), (source_receipt_dir, source_receipt_source)): + mounts = [mount for mount in service.get("volumes", []) if mount.get("target") == target] + assert len(mounts) == 1 and mounts[0]["source"] == source and mounts[0].get("read_only") is True, (name, target) +assert services["game-logic-service"]["environment"].get("FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED") == "false" for name, service in services.items(): if name not in fixture_services: assert not any(mount.get("target") == capability_path for mount in service.get("volumes", [])), name diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameLogicClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameLogicClient.java index 6d4c786af3..414cf78e97 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameLogicClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameLogicClient.java @@ -50,6 +50,7 @@ import net.firedevops.firemud.gamelogic.v1.PingRequest; import net.firedevops.firemud.gamelogic.v1.PingResponse; import net.firedevops.firemud.gamelogic.v1.ResolveRunOwnedFixtureLookRequest; +import net.firedevops.firemud.gamelogic.v1.ResolveRunOwnedFixtureLookResponse; import net.firedevops.firemud.gamelogic.v1.RunOwnedFixtureLookServiceGrpc; import net.firedevops.firemud.gamelogic.v1.SendCommunicationRequest; import net.firedevops.firemud.gamelogic.v1.SendCommunicationResponse; @@ -72,6 +73,7 @@ public class GameLogicClient private static final long READINESS_DEADLINE_SECONDS = 2L; private final GameplaySessionAttestationService gameplaySessionAttestationService; + private RunOwnedFixtureLookServiceGrpc.RunOwnedFixtureLookServiceBlockingStub fixtureLookStub; public GameLogicClient( ServiceEndpointsProperties endpoints, @@ -101,6 +103,8 @@ protected String defaultTarget() { @Override protected GameLogicServiceGrpc.GameLogicServiceBlockingStub buildStub( io.grpc.ManagedChannel channel) { + // The protected fixture receiver authenticates only the mTLS workload. + fixtureLookStub = RunOwnedFixtureLookServiceGrpc.newBlockingStub(channel); return applyStubCustomizer( GameLogicServiceGrpc.newBlockingStub(channel).withCompression("gzip")); } @@ -134,13 +138,20 @@ public LookResult resolveLook(SessionContext context, String roomId, String loca public LookResult resolveRunOwnedFixtureLook(ReadRunOwnedFixtureLookRoomRequest request) { var target = WorldCanonicalInstanceLifecycleGrpcCodec.fromRequest(request.getLifecycle()); String peer = "spiffe://firemud/ns/" + target.targetNamespace() + "/sa/game-logic-service"; - var response = - RunOwnedFixtureLookServiceGrpc.newBlockingStub(stub().getChannel()) - .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(peer)) - .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(peer)) - .withDeadlineAfter(8, TimeUnit.SECONDS) - .resolveRunOwnedFixtureLook( - ResolveRunOwnedFixtureLookRequest.newBuilder().setRoom(request).build()); + ResolveRunOwnedFixtureLookResponse response; + try { + response = + fixtureLookStub + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(peer)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(peer)) + .withDeadlineAfter(8, TimeUnit.SECONDS) + .resolveRunOwnedFixtureLook( + ResolveRunOwnedFixtureLookRequest.newBuilder().setRoom(request).build()); + } catch (io.grpc.StatusRuntimeException unavailable) { + LOG.warn( + "Protected fixture LOOK failed with gRPC status {}", unavailable.getStatus().getCode()); + throw unavailable; + } if (!response.hasLook() || !response.getUnknownFields().asMap().isEmpty()) { throw new IllegalStateException("The fixture LOOK response is unavailable"); } From f316a535eecb5b61e85d6ee514d6a33a38383c86 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:35:35 +1300 Subject: [PATCH 18/28] Keep published route and actor interceptor tests on the canonical projection --- ...nonicalGameplayAdmissionPublishedReadGrpcServiceTest.java | 1 + ...reseededActorAssignmentOwnerReadInterceptorChainTest.java | 5 ++++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionPublishedReadGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionPublishedReadGrpcServiceTest.java index b9c1987f4e..bfa4621429 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionPublishedReadGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionPublishedReadGrpcServiceTest.java @@ -623,6 +623,7 @@ private static CanonicalGameplayRosterOwnerReadEvidence.Request strictSelector( private static CanonicalPlayableTarget route() { var route = mock(CanonicalPlayableTarget.class); + when(route.admissionDecisionTarget()).thenCallRealMethod(); when(route.initialAdmissionOriginKind()) .thenReturn(CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER); when(route.ownerProofOutcome()) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/PreseededActorAssignmentOwnerReadInterceptorChainTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/PreseededActorAssignmentOwnerReadInterceptorChainTest.java index ab2fdc983e..775cd8efdc 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/PreseededActorAssignmentOwnerReadInterceptorChainTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/PreseededActorAssignmentOwnerReadInterceptorChainTest.java @@ -135,7 +135,10 @@ private static AuthTokenInterceptor configuredAuthInterceptor() { "game_session.v1.CanonicalGameplayAdmissionDecisionReadService/ResolvePublishedRealmAdmissionTarget", "game_session.v1.CanonicalGameplayAdmissionDecisionReadService/GetOriginalNewNeverAdmittedDecision", "game_session.v1.CanonicalGameplayAdmissionDecisionReadService/GetCanonicalGameplayAdmissionDecision", - "game_session.v1.CanonicalGameplayAdmissionDecisionReadService/GetPublishedRealmAdmissionOwnerRead") + "game_session.v1.CanonicalGameplayAdmissionDecisionReadService/GetPublishedRealmAdmissionOwnerRead", + "game_session.v1.OriginalNewFinalAdmissionReadService/ReadOriginalNewFinalAdmission", + "game_session.v1.OriginalNewCapacityExecutionReadService/ReadOriginalNewCapacityExecution", + "game_session.v1.OriginalNewCapacityExecutionReadService/ReadHistoricalOriginalNewCapacityFinal") .doesNotContain("game_session.v1.*"); Set publicMethods = Set.copyOf(configured); return new AuthTokenInterceptor( From 80778fc67534ac11a79db698fc055c40ecdac131 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:52:26 +1300 Subject: [PATCH 19/28] Prove canonical WebSocket and Telnet on independently fresh fixtures --- dev-tools/smoke/pre-v1-signer-fixtures.sh | 4 ++++ dev-tools/smoke/smoke_common.py | 14 -------------- dev-tools/tests/smoke-image-env-contract.sh | 11 ++++++++++- dev-tools/tests/smoke-transport-contract.sh | 10 ++++++++-- docker/docker-compose.pre-v1-login.override.yml | 3 +++ .../CanonicalGameplayRuntimeConfiguration.java | 17 ++++++++++++++++- .../telnet-login-look-smoke.sh | 6 +++--- 7 files changed, 44 insertions(+), 21 deletions(-) diff --git a/dev-tools/smoke/pre-v1-signer-fixtures.sh b/dev-tools/smoke/pre-v1-signer-fixtures.sh index 49933c1b5e..f629b8ea27 100644 --- a/dev-tools/smoke/pre-v1-signer-fixtures.sh +++ b/dev-tools/smoke/pre-v1-signer-fixtures.sh @@ -21,6 +21,10 @@ prepare_pre_v1_signer_fixtures() { export FIREMUD_PRE_V1_SIGNER_FIXTURES FIREMUD_PRE_V1_NAMESPACE_UID FIREMUD_PRE_V1_CLUSTER_UID \ FIREMUD_PRE_V1_CONFIG_MAP_UID unset FIREMUD_SMOKE_FIXTURE_WEBSOCKET_CERTIFICATE_SHA256 + if [[ "${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:-false}" == true \ + && "${FIREMUD_SMOKE_ADMISSION_QUALIFICATION:-baseline}" == baseline ]]; then + prepare_run_owned_websocket_client "$cert_root" || return 1 + fi } prepare_run_owned_websocket_client() { diff --git a/dev-tools/smoke/smoke_common.py b/dev-tools/smoke/smoke_common.py index e29513b96e..cb33aa5f43 100644 --- a/dev-tools/smoke/smoke_common.py +++ b/dev-tools/smoke/smoke_common.py @@ -387,20 +387,6 @@ def login_play_look_steps( ] -def authenticated_telnet_play_steps( - username, password, world, worlds_expect, login_expect, play_expect, look_expect -): - """Run the canonical Telnet lobby, PLAY, and LOOK on one live connection.""" - return [ - (f"LOGIN {username} {password}", [login_expect], "LOGIN"), - ("WORLDS", [worlds_expect], "WORLDS"), - (f"REALMS {world}", ["OK REALMS"], "REALMS"), - (f"JOIN {world}", ["OK JOIN"], "JOIN"), - (f"PLAY {world}", [play_expect], "PLAY"), - ("LOOK", [look_expect, "Candle-lit Antechamber"], "LOOK"), - ] - - def canonical_fixture_play_steps( username, password, world, worlds_expect, login_expect, play_expect, look_expect ): diff --git a/dev-tools/tests/smoke-image-env-contract.sh b/dev-tools/tests/smoke-image-env-contract.sh index fc5365e881..957010dfec 100644 --- a/dev-tools/tests/smoke-image-env-contract.sh +++ b/dev-tools/tests/smoke-image-env-contract.sh @@ -81,8 +81,11 @@ docker() { local arguments=" $* " if [[ "$arguments" == *" up "* ]]; then touch "$TEST_OWNERSHIP_DIR/$GITHUB_RUN_ID.resources" + printf 'up\n' >>"$TEST_OWNERSHIP_DIR/$GITHUB_RUN_ID.starts" + touch "$FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_DIR_HOST_PATH/source-receipt.json" elif [[ "$arguments" == *" down "* ]]; then - if [[ -e "$TEST_OWNERSHIP_DIR/$GITHUB_RUN_ID.resources" && "${SMOKE_TEST_CLEANUP_FAIL:-false}" == true ]]; then + if [[ -e "$TEST_OWNERSHIP_DIR/$GITHUB_RUN_ID.resources" && "${SMOKE_TEST_CLEANUP_FAIL:-false}" == true ]] \ + && [[ -e "$TEST_OWNERSHIP_DIR/$GITHUB_RUN_ID.telnet-probed" || "${SMOKE_TEST_PROBE_STATUS:-0}" != 0 ]]; then return 92 fi rm -f "$TEST_OWNERSHIP_DIR/$GITHUB_RUN_ID.resources" @@ -164,6 +167,10 @@ bash() { "$certificate_root/workloads/world-management-service/client.crt" cp "$certificate_root/workloads/game-session-service/ca.crt" \ "$certificate_root/workloads/world-management-service/ca.crt" + mkdir -m 700 -p "$certificate_root/websocket-client" + cp "$certificate_root/workloads/game-session-service/client.crt" \ + "$certificate_root/websocket-client/client.crt" + (umask 077; : >"$certificate_root/websocket-client/client.key") ;; verify-compose-health.sh) return 0 @@ -173,6 +180,7 @@ bash() { return "${SMOKE_TEST_PROBE_STATUS:-0}" ;; telnet-login-look-smoke.sh) + touch "$TEST_OWNERSHIP_DIR/$GITHUB_RUN_ID.telnet-probed" printf 'MOCK_TELNET_PROBE\n' ;; *) @@ -260,6 +268,7 @@ run_diagnostic_smoke_case() { run_failure_diagnostic_regressions() { run_diagnostic_smoke_case cleanup-success false 0 false 0 [[ ! -e "$TEST_OWNERSHIP_DIR/${TEST_RUN_ID}-cleanup-success.resources" ]] + [[ "$(wc -l <"$TEST_OWNERSHIP_DIR/${TEST_RUN_ID}-cleanup-success.starts")" -eq 2 ]] SMOKE_TEST_CLEANUP_FAIL=true run_diagnostic_smoke_case cleanup-failure false 0 false 1 [[ -e "$TEST_OWNERSHIP_DIR/${TEST_RUN_ID}-cleanup-failure.resources" ]] grep -Fq 'proof cleanup failed or remains unknown' "$ERR_FILE" diff --git a/dev-tools/tests/smoke-transport-contract.sh b/dev-tools/tests/smoke-transport-contract.sh index 21a4b9056c..00714f4899 100644 --- a/dev-tools/tests/smoke-transport-contract.sh +++ b/dev-tools/tests/smoke-transport-contract.sh @@ -2016,7 +2016,7 @@ with patch( raise AssertionError("unrelated HTTP exception was incorrectly classified") -telnet_steps = smoke_common.authenticated_telnet_play_steps( +telnet_steps = smoke_common.canonical_fixture_play_steps( "demo@example.com", "swordfish", "demo", "OK WORLDS", "OK LOGIN", "OK PLAY", "OK LOOK" ) assert [step[2] for step in telnet_steps] == ["LOGIN", "WORLDS", "REALMS", "JOIN", "PLAY", "LOOK"] @@ -2081,7 +2081,7 @@ for script in \ if [[ "$script" == *"tcp-proxy-service/telnet-login-look-smoke.sh" ]]; then grep -Fq 'discovery_selector = world' "$script" || { echo "$script must gate the mutation extension on the configured WORLDS selector" >&2; exit 1; } - grep -Fq 'authenticated_telnet_play_steps(login_email, password, world, worlds_expect, login_expect, play_expect, look_expect)' "$script" || + grep -Fq 'canonical_fixture_play_steps(login_email, password, world, worlds_expect, login_expect, play_expect, look_expect)' "$script" || { echo "$script baseline must use the authenticated Telnet PLAY and LOOK plan" >&2; exit 1; } else grep -Fq 'discovery_selector=world' "$script" || @@ -2553,6 +2553,12 @@ assert_command_rejects \ SMOKE_MUTATION_BOUNDARY=run-owned-compose \ SMOKE_GAME_SESSION_WS_URL=ws://localhost:8085/ws \ bash "$ROOT_DIR/services/game-session-service/websocket-login-look-smoke.sh" +assert_command_rejects \ + "run-owned loopback listener" \ + env FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED=true \ + FIREMUD_SMOKE_FIXTURE_WEBSOCKET_CERTIFICATE_SHA256=fixture-test \ + SMOKE_GAME_SESSION_WS_URL=wss://example.test/ws/game/run-owned-fixture \ + bash "$ROOT_DIR/services/game-session-service/websocket-login-look-smoke.sh" assert_command_rejects \ "canonical Telnet endpoint" \ env SMOKE_MUTATION_EXTENSION=true \ diff --git a/docker/docker-compose.pre-v1-login.override.yml b/docker/docker-compose.pre-v1-login.override.yml index 9737651680..80cc7c16f2 100644 --- a/docker/docker-compose.pre-v1-login.override.yml +++ b/docker/docker-compose.pre-v1-login.override.yml @@ -149,7 +149,10 @@ services: depends_on: pre-v1-jwt-materializer: condition: service_healthy + ports: + - "127.0.0.1:18444:8444" environment: + FIREMUD_SMOKE_FIXTURE_WEBSOCKET_CERTIFICATE_SHA256: ${FIREMUD_SMOKE_FIXTURE_WEBSOCKET_CERTIFICATE_SHA256:-} FIREMUD_GAME_SESSION_AUTHENTICATED_GAMEPLAY_ENABLED: "true" FIREMUD_GAME_SESSION_CANONICAL_PLAY_PRE_V1_ENABLED: ${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:-false} FIREMUD_GAME_SESSION_INITIAL_GAMEPLAY_LOGIN_PROTECTED_SOURCES_ENABLED: "true" diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/CanonicalGameplayRuntimeConfiguration.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/CanonicalGameplayRuntimeConfiguration.java index 36447ee6cd..eec49ebb6d 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/CanonicalGameplayRuntimeConfiguration.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/CanonicalGameplayRuntimeConfiguration.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.accountservice.config; import java.time.Clock; +import net.firedevops.firemud.accountservice.data.RunOwnedFixtureDemoTenantEnrollmentDriver; import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; import net.firedevops.firemud.accountservice.repository.AccountInitialGameplayLoginDisposalRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; @@ -13,12 +14,15 @@ import net.firedevops.firemud.accountservice.service.session.AccountGameplayPrimaryCredentialVerifier; import net.firedevops.firemud.accountservice.service.session.AccountInitialGameplayLoginDisposalOwner; import net.firedevops.firemud.accountservice.service.session.AccountMountedGameplayCredentialDigestKeySource; +import net.firedevops.firemud.common.prev1.PreV1GateWaivers; import org.jooq.DSLContext; +import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.annotation.Qualifier; 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; +import org.springframework.core.env.Environment; import org.springframework.transaction.PlatformTransactionManager; /** Receiving composition over the actual protected issuance, recovery and registry owners. */ @@ -37,6 +41,8 @@ AccountGameplayAuthenticateReceiver canonicalGameplayAuthenticateReceiver( AccountGameplayDelegationTokenRegistry registry, AccountServiceImpl primary, DSLContext dsl, + Environment environment, + ObjectProvider fixtureEnrollment, @Qualifier("transactionManager") PlatformTransactionManager transactions, @Value("${firemud.account.gameplay-login.request-digest-keyring-path:}") String digestKeyring, @Value("${firemud.grpc.workload-namespace:}") String namespace) { @@ -50,7 +56,16 @@ AccountGameplayAuthenticateReceiver canonicalGameplayAuthenticateReceiver( var disposal = new AccountInitialGameplayLoginDisposalOwner( new AccountInitialGameplayLoginDisposalRepository(dsl), registry, transactions); + boolean preV1 = PreV1GateWaivers.from(environment).enabled(); return new AccountGameplayAuthenticateReceiver( - owner, new AccountGameplayPrimaryCredentialVerifier(primary), namespace, disposal); + owner, + new AccountGameplayPrimaryCredentialVerifier(primary), + namespace, + disposal, + () -> { + if (!preV1) return false; + var fixture = fixtureEnrollment.getIfAvailable(); + return fixture != null && fixture.enrolled(); + }); } } diff --git a/services/tcp-proxy-service/telnet-login-look-smoke.sh b/services/tcp-proxy-service/telnet-login-look-smoke.sh index e29674ecc9..9b0717d26d 100755 --- a/services/tcp-proxy-service/telnet-login-look-smoke.sh +++ b/services/tcp-proxy-service/telnet-login-look-smoke.sh @@ -51,7 +51,7 @@ fi if [[ "$SMOKE_MUTATION_EXTENSION" == "true" ]]; then echo "Running Telnet baseline plus explicit item/container/equipment mutation extension against ${SMOKE_HOST}:${TCP_PORT}" else - echo "Running Telnet LOGIN + WORLDS + REALMS + JOIN + PLAY baseline against ${SMOKE_HOST}:${TCP_PORT}" + echo "Running Telnet LOGIN + WORLDS + REALMS + JOIN + PLAY + LOOK baseline against ${SMOKE_HOST}:${TCP_PORT}" fi echo "Using login credentials (email and password redacted)" echo "Using session='${SMOKE_SESSION_ID}' tenant='${SMOKE_TENANT_ID}'" @@ -68,7 +68,7 @@ repo_root = Path(os.environ["FIREMUD_REPO_ROOT"]) sys.path.insert(0, str(repo_root / "dev-tools" / "smoke")) from smoke_common import ( - authenticated_telnet_play_steps, + canonical_fixture_play_steps, gameplay_item_container_equipment_steps, http_readiness_up, is_localhost_equivalent, @@ -172,7 +172,7 @@ if os.environ["SMOKE_MUTATION_EXTENSION"] == "true": discovery_selector = world login_wait_seconds = 0 else: - steps = authenticated_telnet_play_steps(login_email, password, world, worlds_expect, login_expect, play_expect, look_expect) + steps = canonical_fixture_play_steps(login_email, password, world, worlds_expect, login_expect, play_expect, look_expect) discovery_selector = None # Authenticated LOGIN answers UNAVAILABLE until the Account JWT signer is promoted, which the # pre-v1 stand-ins complete a few minutes after Account starts. From 295d9a7a705c4917c0fa0533c86cc5266f6f5450 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 23 Nov 2026 03:05:18 +1300 Subject: [PATCH 20/28] Discover worlds before credential LOGIN on the WebSocket smoke --- dev-tools/smoke/smoke_common.py | 10 ++++++---- dev-tools/tests/smoke-transport-contract.sh | 7 +++++++ .../game-session-service/websocket-login-look-smoke.sh | 3 ++- 3 files changed, 15 insertions(+), 5 deletions(-) diff --git a/dev-tools/smoke/smoke_common.py b/dev-tools/smoke/smoke_common.py index cb33aa5f43..24aca3e46e 100644 --- a/dev-tools/smoke/smoke_common.py +++ b/dev-tools/smoke/smoke_common.py @@ -388,12 +388,14 @@ def login_play_look_steps( def canonical_fixture_play_steps( - username, password, world, worlds_expect, login_expect, play_expect, look_expect + username, password, world, worlds_expect, login_expect, play_expect, look_expect, *, + worlds_first=False, ): """Run the canonical fixture lobby, PLAY, and LOOK on one live connection.""" - return [ - (f"LOGIN {username} {password}", [login_expect], "LOGIN"), - ("WORLDS", [worlds_expect], "WORLDS"), + login = (f"LOGIN {username} {password}", [login_expect], "LOGIN") + discovery = ("WORLDS", [worlds_expect], "WORLDS") + steps = [discovery, login] if worlds_first else [login, discovery] + return steps + [ (f"REALMS {world}", ["OK REALMS"], "REALMS"), (f"JOIN {world}", ["OK JOIN"], "JOIN"), (f"PLAY {world}", [play_expect], "PLAY", 30), diff --git a/dev-tools/tests/smoke-transport-contract.sh b/dev-tools/tests/smoke-transport-contract.sh index 00714f4899..5ecd597f48 100644 --- a/dev-tools/tests/smoke-transport-contract.sh +++ b/dev-tools/tests/smoke-transport-contract.sh @@ -2026,6 +2026,13 @@ assert telnet_steps[4][:2] == ("PLAY demo", ["OK PLAY"]) assert telnet_steps[5][:2] == ("LOOK", ["OK LOOK", "Candle-lit Antechamber"]) +websocket_steps = smoke_common.canonical_fixture_play_steps( + "demo@example.com", "swordfish", "demo", "OK WORLDS", "OK LOGIN", "OK PLAY", "OK LOOK", + worlds_first=True, +) +assert [step[2] for step in websocket_steps] == ["WORLDS", "LOGIN", "REALMS", "JOIN", "PLAY", "LOOK"] +assert websocket_steps[2:] == telnet_steps[2:] + item_steps = smoke_common.gameplay_item_container_equipment_steps( "demo@example.com", diff --git a/services/game-session-service/websocket-login-look-smoke.sh b/services/game-session-service/websocket-login-look-smoke.sh index 3bc2a06672..a595e34d11 100644 --- a/services/game-session-service/websocket-login-look-smoke.sh +++ b/services/game-session-service/websocket-login-look-smoke.sh @@ -62,7 +62,7 @@ fi if [[ "$SMOKE_MUTATION_EXTENSION" == "true" ]]; then echo "Running direct WebSocket baseline plus explicit item/container/equipment mutation extension against ${SMOKE_GAME_SESSION_WS_URL}" elif [[ "$SMOKE_WS_FIXTURE_MODE" == true ]]; then - echo "Running canonical LOGIN, WORLDS, REALMS, JOIN, PLAY and LOOK over the claimed WebSocket fixture" + echo "Running canonical WORLDS, LOGIN, REALMS, JOIN, PLAY and LOOK over the claimed WebSocket fixture" else echo "Running direct WebSocket WORLDS + LOGIN + fail-closed PLAY baseline against ${SMOKE_GAME_SESSION_WS_URL}" fi @@ -144,6 +144,7 @@ if os.environ["SMOKE_MUTATION_EXTENSION"] == "true": elif fixture_mode: steps = canonical_fixture_play_steps( login_email, password, world, worlds_expect, login_expect, play_expect, look_expect, + worlds_first=True, ) fixture_root = Path(os.environ["FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT"]) connection_options["sslopt"] = { From b35ac3f851329c114a90d43b3d0b7be587ff75e9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 23 Nov 2026 03:07:22 +1300 Subject: [PATCH 21/28] Recognize canonical tenant and world selectors in smoke discovery --- dev-tools/smoke/smoke_common.py | 21 +++++++++++++++------ dev-tools/tests/smoke-transport-contract.sh | 15 +++++++++++++++ 2 files changed, 30 insertions(+), 6 deletions(-) diff --git a/dev-tools/smoke/smoke_common.py b/dev-tools/smoke/smoke_common.py index 24aca3e46e..5fcf297f0e 100644 --- a/dev-tools/smoke/smoke_common.py +++ b/dev-tools/smoke/smoke_common.py @@ -42,6 +42,9 @@ class TransientUpstreamSmokeFailure(ProbeOperationalFailure): WORLD_DISCOVERY_ROW = re.compile( r"^\s*\S(?:.*?\S)?\s+\(([^()\r\n]+)\)\s*$" ) +CANONICAL_WORLD_DISCOVERY_ROW = re.compile( + r"^\s*([a-z0-9]+(?:-[a-z0-9]+)*)/([a-z0-9]+(?:-[a-z0-9]+)*)\s*$" +) WORLD_DISCOVERY_POLL_INTERVAL_SECONDS = 0.5 RETRYABLE_UPSTREAM_FAILURE_PREFIXES = ("ERROR UPSTREAM_FAILURE", "ERROR UNAVAILABLE") DISCOVERY_RETRYABLE_UPSTREAM_PREFIXES = ( @@ -220,17 +223,23 @@ def worlds_response_contains_selector(response, selector): if not isinstance(selector, str) or not selector.strip(): raise ValueError("World discovery selector must be a non-empty string") normalized_selector = selector.strip().casefold() - slugs = [] + matches = 0 for line in response.splitlines(): match = WORLD_DISCOVERY_ROW.fullmatch(line) if match is not None: - slugs.append(match.group(1).strip().casefold()) - - matches = [slug for slug in slugs if slug == normalized_selector] + matches += match.group(1).strip().casefold() == normalized_selector + continue + canonical = CANONICAL_WORLD_DISCOVERY_ROW.fullmatch(line) + if canonical is not None: + tenant, world = canonical.groups() + # The canonical menu accepts the exact tenant/world or a unique tenant alias. + matches += normalized_selector == f"{tenant}/{world}" or ( + not normalized_selector.isdecimal() and normalized_selector == tenant + ) - if len(matches) > 1: + if matches > 1: raise ProbeOperationalFailure(f"Configured smoke world selector {selector!r} appears ambiguously in WORLDS") - return len(matches) == 1 + return matches == 1 def wait_for_world_discovery(selector, expected_substrings, timeout_seconds, execute_worlds): diff --git a/dev-tools/tests/smoke-transport-contract.sh b/dev-tools/tests/smoke-transport-contract.sh index 5ecd597f48..1470acdec6 100644 --- a/dev-tools/tests/smoke-transport-contract.sh +++ b/dev-tools/tests/smoke-transport-contract.sh @@ -1211,6 +1211,21 @@ assert smoke_common.worlds_response_contains_selector( assert not smoke_common.worlds_response_contains_selector( "OK WORLDS\nWelcome to the demo world\n", "demo" ) +assert smoke_common.worlds_response_contains_selector( + "OK WORLDS\ndemo/demo\n", "demo" +) +assert smoke_common.worlds_response_contains_selector( + "OK WORLDS\ndemo/other-world\n", "DEMO/other-world" +) +assert not smoke_common.worlds_response_contains_selector( + "OK WORLDS\ndemo/other-world\n", "other-world" +) +try: + smoke_common.worlds_response_contains_selector("OK WORLDS\ndemo/world\ndemo/other\n", "demo") +except smoke_common.ProbeOperationalFailure as exc: + assert "ambiguously" in str(exc) +else: + raise AssertionError("A canonical tenant alias must match exactly one world") for transient_error in ( From 8e016ecdf459577711568f516f8f4b653b872713 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 23 Nov 2026 03:12:30 +1300 Subject: [PATCH 22/28] Create mock smoke certificate directories with a private umask --- dev-tools/tests/smoke-image-env-contract.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dev-tools/tests/smoke-image-env-contract.sh b/dev-tools/tests/smoke-image-env-contract.sh index 957010dfec..270e033bac 100644 --- a/dev-tools/tests/smoke-image-env-contract.sh +++ b/dev-tools/tests/smoke-image-env-contract.sh @@ -167,7 +167,7 @@ bash() { "$certificate_root/workloads/world-management-service/client.crt" cp "$certificate_root/workloads/game-session-service/ca.crt" \ "$certificate_root/workloads/world-management-service/ca.crt" - mkdir -m 700 -p "$certificate_root/websocket-client" + (umask 077; mkdir -p "$certificate_root/websocket-client") cp "$certificate_root/workloads/game-session-service/client.crt" \ "$certificate_root/websocket-client/client.crt" (umask 077; : >"$certificate_root/websocket-client/client.key") From 4022ab4f6ad5571f4b008a3749628447b4de9d22 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 23 Nov 2026 03:13:59 +1300 Subject: [PATCH 23/28] Refresh the canonical WebSocket world menu after login --- dev-tools/smoke/smoke_common.py | 9 +++++---- dev-tools/tests/smoke-transport-contract.sh | 6 +++--- .../game-session-service/websocket-login-look-smoke.sh | 4 ++-- 3 files changed, 10 insertions(+), 9 deletions(-) diff --git a/dev-tools/smoke/smoke_common.py b/dev-tools/smoke/smoke_common.py index 5fcf297f0e..afd4e4a44e 100644 --- a/dev-tools/smoke/smoke_common.py +++ b/dev-tools/smoke/smoke_common.py @@ -398,13 +398,14 @@ def login_play_look_steps( def canonical_fixture_play_steps( username, password, world, worlds_expect, login_expect, play_expect, look_expect, *, - worlds_first=False, + discover_before_login=False, ): """Run the canonical fixture lobby, PLAY, and LOOK on one live connection.""" - login = (f"LOGIN {username} {password}", [login_expect], "LOGIN") discovery = ("WORLDS", [worlds_expect], "WORLDS") - steps = [discovery, login] if worlds_first else [login, discovery] - return steps + [ + # LOGIN starts a new custody and clears the pre-login world menu. + return ([discovery] if discover_before_login else []) + [ + (f"LOGIN {username} {password}", [login_expect], "LOGIN"), + discovery, (f"REALMS {world}", ["OK REALMS"], "REALMS"), (f"JOIN {world}", ["OK JOIN"], "JOIN"), (f"PLAY {world}", [play_expect], "PLAY", 30), diff --git a/dev-tools/tests/smoke-transport-contract.sh b/dev-tools/tests/smoke-transport-contract.sh index 1470acdec6..5fa81f319c 100644 --- a/dev-tools/tests/smoke-transport-contract.sh +++ b/dev-tools/tests/smoke-transport-contract.sh @@ -2043,10 +2043,10 @@ assert telnet_steps[5][:2] == ("LOOK", ["OK LOOK", "Candle-lit Antechamber"]) websocket_steps = smoke_common.canonical_fixture_play_steps( "demo@example.com", "swordfish", "demo", "OK WORLDS", "OK LOGIN", "OK PLAY", "OK LOOK", - worlds_first=True, + discover_before_login=True, ) -assert [step[2] for step in websocket_steps] == ["WORLDS", "LOGIN", "REALMS", "JOIN", "PLAY", "LOOK"] -assert websocket_steps[2:] == telnet_steps[2:] +assert websocket_steps[0] == ("WORLDS", ["OK WORLDS"], "WORLDS") +assert websocket_steps[1:] == telnet_steps item_steps = smoke_common.gameplay_item_container_equipment_steps( diff --git a/services/game-session-service/websocket-login-look-smoke.sh b/services/game-session-service/websocket-login-look-smoke.sh index a595e34d11..e207ba6cb6 100644 --- a/services/game-session-service/websocket-login-look-smoke.sh +++ b/services/game-session-service/websocket-login-look-smoke.sh @@ -62,7 +62,7 @@ fi if [[ "$SMOKE_MUTATION_EXTENSION" == "true" ]]; then echo "Running direct WebSocket baseline plus explicit item/container/equipment mutation extension against ${SMOKE_GAME_SESSION_WS_URL}" elif [[ "$SMOKE_WS_FIXTURE_MODE" == true ]]; then - echo "Running canonical WORLDS, LOGIN, REALMS, JOIN, PLAY and LOOK over the claimed WebSocket fixture" + echo "Running canonical WORLDS, LOGIN, authenticated WORLDS, REALMS, JOIN, PLAY and LOOK over the claimed WebSocket fixture" else echo "Running direct WebSocket WORLDS + LOGIN + fail-closed PLAY baseline against ${SMOKE_GAME_SESSION_WS_URL}" fi @@ -144,7 +144,7 @@ if os.environ["SMOKE_MUTATION_EXTENSION"] == "true": elif fixture_mode: steps = canonical_fixture_play_steps( login_email, password, world, worlds_expect, login_expect, play_expect, look_expect, - worlds_first=True, + discover_before_login=True, ) fixture_root = Path(os.environ["FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT"]) connection_options["sslopt"] = { From 96737c06461dd8f09eb6c7ab14ecc86d5d658e67 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 23 Nov 2026 03:22:56 +1300 Subject: [PATCH 24/28] Bound WebSocket fixture discovery by its startup deadline --- dev-tools/smoke/smoke_common.py | 13 ++++++++----- dev-tools/tests/smoke-transport-contract.sh | 4 ++-- .../websocket-login-look-smoke.sh | 2 +- 3 files changed, 11 insertions(+), 8 deletions(-) diff --git a/dev-tools/smoke/smoke_common.py b/dev-tools/smoke/smoke_common.py index afd4e4a44e..e5d99ebae9 100644 --- a/dev-tools/smoke/smoke_common.py +++ b/dev-tools/smoke/smoke_common.py @@ -398,12 +398,15 @@ def login_play_look_steps( def canonical_fixture_play_steps( username, password, world, worlds_expect, login_expect, play_expect, look_expect, *, - discover_before_login=False, + startup_discovery_timeout=None, ): """Run the canonical fixture lobby, PLAY, and LOOK on one live connection.""" discovery = ("WORLDS", [worlds_expect], "WORLDS") - # LOGIN starts a new custody and clears the pre-login world menu. - return ([discovery] if discover_before_login else []) + [ + # Check startup convergence before LOGIN, which starts new custody and clears that menu. + startup_steps = [] + if startup_discovery_timeout is not None: + startup_steps.append((*discovery, startup_discovery_timeout)) + return startup_steps + [ (f"LOGIN {username} {password}", [login_expect], "LOGIN"), discovery, (f"REALMS {world}", ["OK REALMS"], "REALMS"), @@ -987,11 +990,11 @@ def send_discovery_worlds(command, expected, label, remaining): retryable_upstream_prefixes=DISCOVERY_RETRYABLE_UPSTREAM_PREFIXES, ) - def precondition(_line, expected_substrings, _label, _timeout): + def precondition(_line, expected_substrings, _label, timeout): return wait_for_world_discovery( discovery_selector, expected_substrings, - timeout_seconds, + timeout_seconds if timeout is None else timeout, send_discovery_worlds, ) diff --git a/dev-tools/tests/smoke-transport-contract.sh b/dev-tools/tests/smoke-transport-contract.sh index 5fa81f319c..c4839f16d3 100644 --- a/dev-tools/tests/smoke-transport-contract.sh +++ b/dev-tools/tests/smoke-transport-contract.sh @@ -2043,9 +2043,9 @@ assert telnet_steps[5][:2] == ("LOOK", ["OK LOOK", "Candle-lit Antechamber"]) websocket_steps = smoke_common.canonical_fixture_play_steps( "demo@example.com", "swordfish", "demo", "OK WORLDS", "OK LOGIN", "OK PLAY", "OK LOOK", - discover_before_login=True, + startup_discovery_timeout=90, ) -assert websocket_steps[0] == ("WORLDS", ["OK WORLDS"], "WORLDS") +assert websocket_steps[0] == ("WORLDS", ["OK WORLDS"], "WORLDS", 90) assert websocket_steps[1:] == telnet_steps diff --git a/services/game-session-service/websocket-login-look-smoke.sh b/services/game-session-service/websocket-login-look-smoke.sh index e207ba6cb6..fb39738079 100644 --- a/services/game-session-service/websocket-login-look-smoke.sh +++ b/services/game-session-service/websocket-login-look-smoke.sh @@ -144,7 +144,7 @@ if os.environ["SMOKE_MUTATION_EXTENSION"] == "true": elif fixture_mode: steps = canonical_fixture_play_steps( login_email, password, world, worlds_expect, login_expect, play_expect, look_expect, - discover_before_login=True, + startup_discovery_timeout=startup_wait_seconds, ) fixture_root = Path(os.environ["FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT"]) connection_options["sslopt"] = { From 83148299283d152c42ad6c1446803d0bdbe1a513 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 23 Nov 2026 03:23:42 +1300 Subject: [PATCH 25/28] Check that fixture discovery uses its own startup deadline --- dev-tools/tests/smoke-transport-contract.sh | 3 +++ 1 file changed, 3 insertions(+) diff --git a/dev-tools/tests/smoke-transport-contract.sh b/dev-tools/tests/smoke-transport-contract.sh index c4839f16d3..f283c30b7e 100644 --- a/dev-tools/tests/smoke-transport-contract.sh +++ b/dev-tools/tests/smoke-transport-contract.sh @@ -2047,6 +2047,9 @@ websocket_steps = smoke_common.canonical_fixture_play_steps( ) assert websocket_steps[0] == ("WORLDS", ["OK WORLDS"], "WORLDS", 90) assert websocket_steps[1:] == telnet_steps +with patch("smoke_common.wait_for_world_discovery") as fixture_discovery: + smoke_common.run_websocket_command_plan(None, websocket_steps[:1], 10, discovery_selector="demo") +assert fixture_discovery.call_args.args[:3] == ("demo", ["OK WORLDS"], 90) item_steps = smoke_common.gameplay_item_container_equipment_steps( From 49567a5f7b54f392edc9cee951e226285fba29a9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 23 Nov 2026 03:34:29 +1300 Subject: [PATCH 26/28] Record canonical player admission on both fixture transports --- .../implementation-tracking/player-access-and-session.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index b1505779c6..5bd988b9d5 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,13 +6,13 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status -The canonical Account cutover currently authenticates LOGIN but direct backend PLAY fails exactly `ERROR ENTITLEMENT_UNAVAILABLE`; LOOK and successful public admission remain unproved. The [temporary CI exception](#temporary-canonical-play-transition-exception) accepts only that classified failure after held-admission qualification and authenticated cleanup for labeled nonproduction cutover PR merge gating. It does not establish runtime success or permit image publication. Remove it with successful fresh-image backend LOGIN/PLAY/LOOK proof after repairing the Account entitlement cutover. +The run-owned Compose demo completes canonical LOGIN, WORLDS, REALMS, JOIN, PLAY, and LOOK over Telnet and the dedicated mTLS WebSocket in #3481. The fixture confines the pre-v1 stand-ins to the claimed deployment. Public browser admission, paid hosting, and production qualification remain open. Account initial/current/final creation owners, explicit initial billing-owner consent, private Game Design create/close receivers, and original-bound dispatch/recovery are locally composed and unregistered. Focused receiving proof passes, while physical cross-owner qualification, protected Redis/source custody and public/default registration remain incomplete; proof limits are recorded below. ### Temporary canonical PLAY transition exception -The explicitly approved nonproduction canonical-cutover scope has a [bounded Smoke Gate diagnostic exception](../../architecture/system-architecture-cicd.md#pull-request-runtime-and-preview-chain), gated by the `canonical-play-transition` label and fresh evidence for the exact current PR tuple. The label does not authorize expanding that approved scope. The observed failure is successful backend LOGIN followed by exact direct-backend PLAY `ERROR ENTITLEMENT_UNAVAILABLE`, alone or with `Gameplay entitlement is temporarily unavailable. Retry PLAY shortly.` Held-admission denial qualification and authenticated cleanup pass, while LOOK and successful public admission remain unproved. The probe retains its failed Actions-native outcome and exact classified error. Runtime CI and Smoke Gate may pass under the bounded exception after successful authenticated cleanup; their summaries explicitly report that runtime qualification is absent. Image export, upload, typed publication handoff and trusted publication remain blocked for an exception attempt. Repair the canonical Account PLAYER_ADMISSION receiving chain and its Game Session PLAY consumer, then obtain successful fresh-image LOGIN → PLAY → LOOK before removing the exception and resuming trusted branch-image promotion. The integrated stack still leaves the canonical receiver unregistered and numeric PLAY entitlement reads denied; merely registering that receiver or restoring numeric subscription reads does not complete this obligation. This is nonproduction merge-gate accommodation, not activation authority. +The [bounded Smoke Gate diagnostic exception](../../architecture/system-architecture-cicd.md#pull-request-runtime-and-preview-chain) covered the earlier classified backend PLAY `ERROR ENTITLEMENT_UNAVAILABLE` after successful LOGIN, held-admission qualification, and authenticated cleanup. Its recorded outcome is diagnostic evidence for labeled exact PR comparisons. The #3461 → #3474 → #3481 stack leaves `canonical-play-transition` unset and uses normal Smoke Gate qualification. ### Pre-v1 gate waivers @@ -34,13 +34,13 @@ Under ADR 0185 (no data carry-over before v1, proposed in #3459), Compose smoke The canonical Account boundary requires non-nil UUID tenant and game-instance identifiers. The held Game Session scope target now takes those UUIDs from `CanonicalPlayableTarget`, and its Account client validates the same canonical shape. JOIN correlation retains exact tenant equality. The numeric transport session identifier remains an independent, bounded positive-long coordinate: its original bytes, including leading zeros, are preserved through scope issuance and JOIN rather than replaced by the proxy connection UUID. -Selected client-wire and Account receiver tests exercise malformed identifiers and mismatches. The registered receiving chain connects the authenticated Game Session lobby to Account's canonical realm-scope and JOIN owners, with the Account-only admission decision read supplying the selected target. Fresh run-owned Compose smoke for #3481 returned `OK LOGIN`, `OK WORLDS`, `OK REALMS`, and `OK JOIN` on one Telnet connection after the fixture's first `OPEN`. The same run reached the registered Account player-admission entitlement RPC during PLAY and returned `ADMISSION_UNAVAILABLE`. The live entitlement registration now uses its method-specific mTLS guard. Positive PLAY, LOOK, and WebSocket admission proof remain outstanding. Account's registered PLAY receivers serve the demo source. Paid hosting remains held pending its owning composition. +Selected client-wire and Account receiver tests exercise malformed identifiers and mismatches. Game Session's authenticated direct-text lobby uses Account's canonical realm-scope, JOIN, entitlement, lease, and capacity owners after the fixture's first `OPEN`. Fresh Telnet smoke and fresh mTLS WebSocket smoke in #3481 each returned `OK LOGIN`, `OK WORLDS`, `OK REALMS`, `OK JOIN`, `OK PLAY`, and `OK LOOK` on one connection, reading `Candle-lit Antechamber` (`R-1`). WebSocket polls for the first discoverable world at startup, then refreshes the world menu after LOGIN starts authenticated custody. Telnet terminal evidence records the committed physical binding readback, all three owner acknowledgements, and one reserved Account capacity unit. LOOK reads the mapped World room around the Entity empty-ground check. The Account registration serves the verified demo source with method-specific mTLS guards. Paid hosting remains held pending its owning composition. The preproduction format cutover requires canonical UUID scope and JOIN bytes. Existing SQL retention and exact-original identity guards continue to apply. Before activating an existing database populated by an earlier manual composition, establish whether numeric-era companion evidence exists. Preserve that evidence and resolve its retention and recovery requirements before invoking the canonical owner against it. Fresh Compose proof covers a newly initialized database. ### Canonical receiving capability boundaries -The Account source/transport foundation contains unregistered TENANT_OPERATION and PLAYER_ADMISSION owners, transports and controlled proof, Entity persisted-actor discovery, and policy-aware Game Session discovery. These do not replace live PLAY authority. The public receiving boundary contains canonical UUID schema retirement, the public facade/JOIN cutover, initial hosting provider-write source with its focused units, and dependent physical proof. Private FRESH/World preparation remains a separate receiving obligation. A functioning canonical PLAY replacement remains unqualified; no caller custody, runtime registration, admission or activation is established by these source boundaries. +The Account source/transport foundation prepares TENANT_OPERATION and PLAYER_ADMISSION owners, transports and controlled proof, Entity persisted-actor discovery, and policy-aware Game Session discovery. The public receiving boundary contains canonical UUID schema retirement, the public facade/JOIN cutover, initial hosting provider-write source with its focused units, and dependent physical proof. Private FRESH/World preparation remains a separate receiving obligation. The run-owned demo qualification above covers the registered direct-text path. These foundation proofs leave production caller custody, default runtime registration, and activation open. ### Strict tenant-capacity owner preparation From 4ffd9bc70bdfd65d0e00b7d0410f4cc590fa0cbe Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 23 Nov 2026 03:41:18 +1300 Subject: [PATCH 27/28] Wait for first OPEN before both canonical smoke transports log in --- .github/workflows/smoke.yml | 2 +- dev-tools/smoke/smoke_common.py | 19 +++++++----- dev-tools/tests/smoke-transport-contract.sh | 29 ++++++++----------- .../telnet-login-look-smoke.sh | 8 +++-- 4 files changed, 30 insertions(+), 28 deletions(-) diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index 28f6ea9931..25b0e5c379 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -616,7 +616,7 @@ jobs: // Include held-admission proof, authenticated cleanup, and their executed inputs. const canonicalPlayClassifierSha256 = { "dev-tools/verify-smoke-images.sh": "6597800feb9604921a55be989e70247ec4610f81ac8c203f038429c1be7d0bc7", - "dev-tools/smoke/smoke_common.py": "a71a6ad1ff439a78f66b010a05a715fc09f297e3735ada4db007fa5f664ef74d", + "dev-tools/smoke/smoke_common.py": "523a3986814fcbdf91531ccc98fa36f3901ed91d311436870ae1a958f9e8bd18", "services/game-session-service/websocket-login-look-smoke.sh": "7f10f11a36bc758ca5556e67c63cbcd5e3b67b893945a461d52f39958a4f15ad", "dev-tools/smoke/demo-smoke-defaults.sh": "8c9aae1abf005b47af3f313e0d635a666c74776733bcf5278a2e11ac9c8a18fb", "dev-tools/smoke/held-admission-qualification.sh": "b548a773f1786b72d40a3728052a336cb249257a3f40735f005b060812184ed3", diff --git a/dev-tools/smoke/smoke_common.py b/dev-tools/smoke/smoke_common.py index e5d99ebae9..b9625847a6 100644 --- a/dev-tools/smoke/smoke_common.py +++ b/dev-tools/smoke/smoke_common.py @@ -398,15 +398,13 @@ def login_play_look_steps( def canonical_fixture_play_steps( username, password, world, worlds_expect, login_expect, play_expect, look_expect, *, - startup_discovery_timeout=None, + startup_discovery_timeout, ): """Run the canonical fixture lobby, PLAY, and LOOK on one live connection.""" discovery = ("WORLDS", [worlds_expect], "WORLDS") # Check startup convergence before LOGIN, which starts new custody and clears that menu. - startup_steps = [] - if startup_discovery_timeout is not None: - startup_steps.append((*discovery, startup_discovery_timeout)) - return startup_steps + [ + return [ + (*discovery, startup_discovery_timeout), (f"LOGIN {username} {password}", [login_expect], "LOGIN"), discovery, (f"REALMS {world}", ["OK REALMS"], "REALMS"), @@ -734,6 +732,7 @@ def run_telnet_command_plan( default_drain_timeout=0.25, step_results=None, discovery_selector=None, + retry_login_unavailable=False, ): responses = [] @@ -747,7 +746,9 @@ def execute(line, expected_substrings, label, timeout): timeout_seconds if timeout is None else timeout, play_drain_timeout if label == "PLAY" else default_drain_timeout, step_results, - retry_upstream_failure=discovery_selector is None, + retry_upstream_failure=( + discovery_selector is None or (retry_login_unavailable and label == "LOGIN") + ), ) def send_discovery_worlds(command, expected, label, remaining): @@ -764,11 +765,11 @@ def send_discovery_worlds(command, expected, label, remaining): retryable_upstream_prefixes=DISCOVERY_RETRYABLE_UPSTREAM_PREFIXES, ) - def precondition(_line, expected_substrings, _label, _timeout): + def precondition(_line, expected_substrings, _label, timeout): return wait_for_world_discovery( discovery_selector, expected_substrings, - timeout_seconds, + timeout_seconds if timeout is None else timeout, send_discovery_worlds, ) @@ -835,6 +836,7 @@ def run_telnet_smoke_session( tls_server_hostname=None, tls_ca_file=None, discovery_selector=None, + retry_login_unavailable=False, ): return run_transport_session( open_session @@ -856,6 +858,7 @@ def run_telnet_smoke_session( default_drain_timeout=default_drain_timeout, step_results=step_results, discovery_selector=discovery_selector, + retry_login_unavailable=retry_login_unavailable, ), f"Telnet session {host}:{port}", retry_window_seconds=retry_window_seconds, diff --git a/dev-tools/tests/smoke-transport-contract.sh b/dev-tools/tests/smoke-transport-contract.sh index f283c30b7e..7f8056ca8c 100644 --- a/dev-tools/tests/smoke-transport-contract.sh +++ b/dev-tools/tests/smoke-transport-contract.sh @@ -2031,25 +2031,20 @@ with patch( raise AssertionError("unrelated HTTP exception was incorrectly classified") -telnet_steps = smoke_common.canonical_fixture_play_steps( - "demo@example.com", "swordfish", "demo", "OK WORLDS", "OK LOGIN", "OK PLAY", "OK LOOK" -) -assert [step[2] for step in telnet_steps] == ["LOGIN", "WORLDS", "REALMS", "JOIN", "PLAY", "LOOK"] -assert telnet_steps[2][:2] == ("REALMS demo", ["OK REALMS"]) -assert telnet_steps[3][:2] == ("JOIN demo", ["OK JOIN"]) -assert telnet_steps[4][:2] == ("PLAY demo", ["OK PLAY"]) - -assert telnet_steps[5][:2] == ("LOOK", ["OK LOOK", "Candle-lit Antechamber"]) - -websocket_steps = smoke_common.canonical_fixture_play_steps( +fixture_steps = smoke_common.canonical_fixture_play_steps( "demo@example.com", "swordfish", "demo", "OK WORLDS", "OK LOGIN", "OK PLAY", "OK LOOK", startup_discovery_timeout=90, ) -assert websocket_steps[0] == ("WORLDS", ["OK WORLDS"], "WORLDS", 90) -assert websocket_steps[1:] == telnet_steps -with patch("smoke_common.wait_for_world_discovery") as fixture_discovery: - smoke_common.run_websocket_command_plan(None, websocket_steps[:1], 10, discovery_selector="demo") -assert fixture_discovery.call_args.args[:3] == ("demo", ["OK WORLDS"], 90) +assert [step[2] for step in fixture_steps] == ["WORLDS", "LOGIN", "WORLDS", "REALMS", "JOIN", "PLAY", "LOOK"] +assert fixture_steps[0] == ("WORLDS", ["OK WORLDS"], "WORLDS", 90) +assert fixture_steps[3][:2] == ("REALMS demo", ["OK REALMS"]) +assert fixture_steps[4][:2] == ("JOIN demo", ["OK JOIN"]) +assert fixture_steps[5][:2] == ("PLAY demo", ["OK PLAY"]) +assert fixture_steps[6][:2] == ("LOOK", ["OK LOOK", "Candle-lit Antechamber"]) +for run_plan in (smoke_common.run_telnet_command_plan, smoke_common.run_websocket_command_plan): + with patch("smoke_common.wait_for_world_discovery") as fixture_discovery: + run_plan(None, fixture_steps[:1], 10, discovery_selector="demo") + assert fixture_discovery.call_args.args[:3] == ("demo", ["OK WORLDS"], 90) item_steps = smoke_common.gameplay_item_container_equipment_steps( @@ -2106,7 +2101,7 @@ for script in \ if [[ "$script" == *"tcp-proxy-service/telnet-login-look-smoke.sh" ]]; then grep -Fq 'discovery_selector = world' "$script" || { echo "$script must gate the mutation extension on the configured WORLDS selector" >&2; exit 1; } - grep -Fq 'canonical_fixture_play_steps(login_email, password, world, worlds_expect, login_expect, play_expect, look_expect)' "$script" || + grep -Fq 'steps = canonical_fixture_play_steps(' "$script" || { echo "$script baseline must use the authenticated Telnet PLAY and LOOK plan" >&2; exit 1; } else grep -Fq 'discovery_selector=world' "$script" || diff --git a/services/tcp-proxy-service/telnet-login-look-smoke.sh b/services/tcp-proxy-service/telnet-login-look-smoke.sh index 9b0717d26d..a820c7032a 100755 --- a/services/tcp-proxy-service/telnet-login-look-smoke.sh +++ b/services/tcp-proxy-service/telnet-login-look-smoke.sh @@ -172,8 +172,11 @@ if os.environ["SMOKE_MUTATION_EXTENSION"] == "true": discovery_selector = world login_wait_seconds = 0 else: - steps = canonical_fixture_play_steps(login_email, password, world, worlds_expect, login_expect, play_expect, look_expect) - discovery_selector = None + steps = canonical_fixture_play_steps( + login_email, password, world, worlds_expect, login_expect, play_expect, look_expect, + startup_discovery_timeout=startup_wait_seconds, + ) + discovery_selector = world # Authenticated LOGIN answers UNAVAILABLE until the Account JWT signer is promoted, which the # pre-v1 stand-ins complete a few minutes after Account starts. login_wait_seconds = int(os.environ.get("SMOKE_TELNET_LOGIN_WAIT_SECONDS", "480")) @@ -186,6 +189,7 @@ run_telnet_smoke_session( retry_interval_seconds=15, tls_enabled=False, discovery_selector=discovery_selector, + retry_login_unavailable=login_wait_seconds > 0, ) if os.environ["SMOKE_MUTATION_EXTENSION"] == "true": From afdb1e61b31cdcda199e92e1f82d4a107d34a7b7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:18:19 +1300 Subject: [PATCH 28/28] Match current and frozen region bridge test evidence --- .../PreV1CanonicalPlayAdmissionOwner.java | 4 + ...GameplayRegionOwnerCompositionFixture.java | 79 +++++++++++++++---- 2 files changed, 66 insertions(+), 17 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayAdmissionOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayAdmissionOwner.java index 686f8ce2f2..55b9a9ef92 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayAdmissionOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayAdmissionOwner.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.gamesession.repository; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.grpc.Status; import io.lettuce.core.RedisURI; import java.math.BigInteger; @@ -57,6 +58,9 @@ public final class PreV1CanonicalPlayAdmissionOwner { private final LookTextRenderer lookRenderer; private final Clock clock; + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "The owner shares injected jOOQ and Game Logic clients with their owners.") public PreV1CanonicalPlayAdmissionOwner( DSLContext dsl, PreV1CanonicalPlayStandIns standIns, diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java index ef0eba4cdb..2b0e7b9fbd 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java @@ -390,23 +390,14 @@ static UUID installHistoricalMaterializedRequiredBridge( metaDigest, java.sql.Timestamp.from(now), initializationId)); - var status = - new CanonicalGameplayRegionRuntimeStatusRepository(dsl) - .installOwner( - source, - 1L, - null, - grantCorrelation, - "game-session-service", - "historical-sql-fixture", - now); + long executorFence = installHistoricalRegionOwner(dsl, source, tag, grantCorrelation, now); historicalRequireOne( dsl.execute( "UPDATE game_session_region_timeline_preparation SET phase = ?, lease_token_correlation = ?," + " executor_fence = ?, redis_meta_digest = ?, updated_at = ? WHERE initialization_operation_id = ?", "INSTALLED", grantCorrelation, - status.executorFence().longValueExact(), + executorFence, metaDigest, java.sql.Timestamp.from(now), initializationId)); @@ -445,7 +436,7 @@ static UUID installHistoricalMaterializedRequiredBridge( source.captureId(), source.graphSha256(), source.preparationInputDigest(), - new BigDecimal(status.executorFence()), + BigDecimal.valueOf(executorFence), grantCorrelation, new BigDecimal(next), transitionId, @@ -548,6 +539,57 @@ private static void historicalWriteRegionRevisionRows( new BigDecimal(prior))); } + /** Installs the first owner using the V1050.6 table shape and exact predecessor sequence. */ + private static long installHistoricalRegionOwner( + DSLContext dsl, + CanonicalGameplayRegionRuntimeStatusRepository.Source source, + String tag, + String grantCorrelation, + Instant now) { + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + long executorFence = + transaction + .fetchSingle("SELECT nextval('game_session_region_executor_fence_seq')") + .get(0, Long.class); + Long installedFence = + transaction + .fetchSingle( + """ + INSERT INTO game_session_region_runtime_status + (tenant_id, game_instance_id, canonical_region_id, region_id, + tenant_region_tag, lifecycle_epoch, lifecycle_row_version, capture_id, + lifecycle_request_bytes, graph_sha256, preparation_input_digest, + region_epoch, executor_fence, lease_token_correlation, owner_service, + owner_instance_id, paused, last_committed_tick_id, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?, false, -1, ?) + RETURNING executor_fence + """, + source.tenantId(), + source.gameInstanceId(), + source.canonicalRegionId(), + source.regionId(), + tag, + source.lifecycleEpoch(), + source.lifecycleRowVersion(), + source.captureId(), + source.lifecycleRequest().canonicalBytes(), + source.graphSha256(), + source.preparationInputDigest(), + executorFence, + grantCorrelation, + "game-session-service", + "historical-sql-fixture", + java.time.LocalDateTime.ofInstant(now, java.time.ZoneOffset.UTC)) + .get(0, Long.class); + if (executorFence <= 0 || !Objects.equals(installedFence, executorFence)) { + throw new IllegalStateException("Historical region owner SQL changed the exact fence"); + } + return executorFence; + }); + } + private static void historicalRequireOne(int count) { if (count != 1) throw new IllegalStateException("Historical region owner SQL lost its exact row"); @@ -1662,11 +1704,14 @@ private static boolean sameAbortSource( private static void requireMaterializedBridgeCaptured(DSLContext dsl, UUID transitionId) { String exactRow = dsl.fetchSingle( - "SELECT CASE WHEN entity_created_origin IS NULL" - + " THEN (to_jsonb(g) - 'entity_created_origin')::text" - + " ELSE to_jsonb(g)::text END" - + " FROM game_session_canonical_binding_region_bridge_obligation g" - + " WHERE transition_id = ? AND bridge_operation_id IS NOT NULL", + """ + SELECT (to_jsonb(g) - array_remove(ARRAY[ + CASE WHEN entity_created_origin IS NULL THEN 'entity_created_origin' END, + CASE WHEN world_source_kind = 'HUMAN_CAPTURE' THEN 'world_source_kind' END + ], NULL))::text + FROM game_session_canonical_binding_region_bridge_obligation g + WHERE transition_id = ? AND bridge_operation_id IS NOT NULL + """, transitionId) .get(0, String.class); java.math.BigDecimal revision =