From fff09667c031b14aaa60002dd2c61f8ec99223ee Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 8 Oct 2026 12:04:56 +1300 Subject: [PATCH 1/8] Protect canonical World lifecycle with exact player admission holds --- .../world-management-service/api-contracts.md | 10 + .../world-runtime-and-movement.md | 2 + ...AccountGameplayAdmissionLeaseEvidence.java | 434 ++++++++++++++ .../AccountJwtProfileClaimSupport.java | 56 ++ .../GameSessionAccountDelegationProfile.java | 141 +++++ .../WorldCanonicalPlayerAdmissionHold.java | 114 ++++ ...anonicalPlayerAdmissionHoldRepository.java | 207 +++++++ ...ldCanonicalPlayerAdmissionHoldService.java | 81 +++ ..._world_canonical_player_admission_hold.sql | 241 ++++++++ ...rAdmissionHoldPostgresIntegrationTest.java | 563 ++++++++++++++++++ ...aphApplicationPostgresIntegrationTest.java | 23 + ...icalPlayerAdmissionHoldRepositoryTest.java | 110 ++++ ...nonicalPlayerAdmissionHoldServiceTest.java | 122 ++++ ...WorldCanonicalPlayerAdmissionHoldTest.java | 219 +++++++ 14 files changed, 2323 insertions(+) create mode 100644 services/common-security/src/main/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseEvidence.java create mode 100644 services/common-security/src/main/java/net/firedevops/firemud/common/security/GameSessionAccountDelegationProfile.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHold.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldRepository.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldService.java create mode 100644 services/world-management-service/src/main/resources/db/migration/V51__world_canonical_player_admission_hold.sql create mode 100644 services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldPostgresIntegrationTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldRepositoryTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldServiceTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldTest.java diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index f0546464ba..0fc01a4c69 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -338,6 +338,16 @@ World atomically commits the immutable operation result with the exact `PREPARIN The distinct `WorldCanonicalInstanceActivationService.ActivateCanonicalWorldInstance` transport carries the stable activation request UUID and complete original `PREPARING` evidence bytes, not merely the normalized request that omits its read-correlation UUID. Its standalone adapter authenticates the verified same-namespace Game Session workload without end-user context before decoding or owner access. Exact retry correlation compares the operation UUID, normalized complete request and digest while returning the original immutable result bytes; a later read-correlation UUID does not rewrite those bytes. Game Session separately uses the authenticated lifecycle-read RPC for current `ACTIVE` proof. This transport does not authorize activation without the operation-specific current-authority verifier or enable runtime registration; implementation and executed proof limits remain in the World tracker. +## Player Admission Serving Hold + +The Account lease and provisional/final binding sequence remains owned by [Session Behavior](../../system-architecture-session-behavior.md#session-types-and-lifetimes). World supplies a distinct player-admission serving hold over its actual current `ACTIVE` target; neither an initial-pointer hold nor an immutable historical activation result supplies this protection. Acquisition and readback authenticate the exact same-namespace Account workload without end-user context before parsing or owner access. Acquisition binds the original Account lease ID, request/attempt identity, unchanged full lease bytes and digest, complete canonical target scope, and expected World `ACTIVE` lifecycle epoch and Version. World resolves its private row through its persisted canonical association rather than caller-supplied numeric keys. + +World verifies and locks that actual lifecycle row in its own transaction before recording one immutable hold identity and fence. Identical retries return the original hold and acquisition evidence without extending the Account attempt's deadline; changed input conflicts. Concurrent and older-snapshot lifecycle mutations cannot pass through the acquisition fence, and every conflicting owner mutation remains blocked while the hold is unresolved. This must include database-level race and readback proof, not only an application preflight check. + +The cross-owner order is Account acquire, Game Session provisional binding, Account finalize, then Game Session admissible installation. The Game Session decision is bound only once it exists. Account must independently revalidate its current sources and exact lease before its commit; World lifecycle protection does not prove Game Session pointer/catalog currentness, and those owners must fence their own conflicting mutations through Account commit. A storage `COMMITTED` value, earlier source capture, caller-supplied decision or this hold by itself never grants admission. + +World releases only after exact authenticated Account terminal evidence and the matching Game Session installation or cleanup evidence jointly prove the approved outcome. Missing, contradictory, unavailable or ambiguous evidence retains the hold. Expiry is diagnostic, not proof of abort or permission to release; initial-pointer outcomes cannot be reused. The currently prepared owner has no enabled release or admission transport. Implementation and executed proof limits belong in the [World tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#current-status). + ## Initial Admission Hold Contract [Versioning and Runtime](../../system-architecture-versioning-runtime.md#first-open-from-never-opened-authority) owns the first-OPEN transition and its tagged prior-pointer preconditions. World owns the durable initial-admission hold and authoritative target lifecycle proof. The hold binds one stable initial-admission request/digest, the complete canonical namespace/tenant/realm/playable-namespace/scope, exact target instance/version/ACTIVE epoch, and the precondition tag with its applicable pointer/catalog versions. Private World storage selectors do not replace those identities: any association must come from exact persisted authenticated owner evidence, never numeric equality, slugs or Account's migration manifest. diff --git a/design/project-management/implementation-tracking/world-runtime-and-movement.md b/design/project-management/implementation-tracking/world-runtime-and-movement.md index 4fa38cd6ea..d1e60da68d 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for world runtime and movement. C ## Current Status +The distinct player-admission serving-hold candidate builds on the preserved #3044 source. It reuses the unchanged Account lease carrier and the actual canonical association/lifecycle reader; its unregistered Account-workload-only owner records immutable acquisition/readback and a V51 lifecycle tuple fence. The same-value tuple update changes PostgreSQL's physical row version without changing logical state, lifecycle epoch, owner row-version counter or history. Current definitions cover exact retry, substitution, retained diagnostic expiry, independent holds, V51-specific mutation denial and stale REPEATABLE_READ/SERIALIZABLE rejection. Consolidated local Common/World formatting, full checks, static analysis, jOOQ generation, integration-source compilation, World boot JAR and documentation validation pass: 161 Common and 525 World unit cases executed without failures/errors/skips, while all 206 World integration cases skipped without Docker. The definitions and reused ACTIVE fixture stipulate upstream authority; physical migration and race execution remain unproved. Release has no accepting path until exact authenticated Account terminal and Game Session installation/cleanup producers exist. Protected Account acquire/finalize, current source/physical-COMMIT proof and Game Session pointer/catalog/runtime fencing remain separate gates. No transport registration, canonical termination producer or live admission is enabled. The target owner is [Player Admission Serving Hold](../../architecture/microservices/world-management-service/api-contracts.md#player-admission-serving-hold). + Exact published #3044 `a36b152fdaf7f5bb5447094cd72718c66f7977de` [CI 37573659922](https://github.com/benhook1013/FireMUD/actions/runs/37573659922) executed all 196 World integration cases without skips, with three failures. The named PostgreSQL graph/application suite ran 51 cases with two failures; the operational-region suite ran three with one failure. The World checkout was synthetic merge `a9ada9077941141a1d3f8b315d1a0bb0cb1ae0f5`, with the exact #3041 base and published candidate as ordered parents and a head-identical tree. The `EXPECT_CLOSED` placement failure exposed V46's operation guard still accepting only `NO_PRIOR_POINTER` beneath V49's correctly typed location guard. Forward V50 preserves the earlier migrations and all other operation checks while permitting only the two explicit origins; new SQL negatives reject null and unknown origins. The actor/assignment reader correctly denied the changed full request before its later row check, so its fixture now expects that earlier stage and compares the unchanged journal and location rows. The operational-region trigger likewise correctly denied mutation, but its fixture expected jOOQ's exception instead of Spring's translated integrity exception; the corrected assertion retains all four tuple mutations. These corrections require fresh executed PostgreSQL proof and do not alter runtime activation gates. Game Session's unchanged retained-tenant suite and missing LOGIN capture, plus TCP's compiler heap exhaustion, remain separately owned aggregate failures. The #3044 continuation aligns canonical holds and placement with the complete shared Game Session terminal proof. V48 retains immutable proof bytes and their separate digest through an exact-row, one-use terminal manifest; V49 permits placement only against the matching typed commit and checked first-open pointer increment. Acquisition, lifecycle read and terminal transport composition require the explicit, default-disabled `firemud.world.canonical-first-admission.transport-enabled` gate. Terminalization additionally denies unless `owner-proof-client-enabled` explicitly composes the file-backed mTLS Game Session owner client; no caller-supplied proof or legacy numeric fallback substitutes for that read. Historical terminal readback is not fresh admission authority. The earlier consolidated local Common/World check, formatting, static analysis, jOOQ generation, boot JAR and documentation checks passed. World executed 511 unit methods with no failures or skips; 378 matching Common unit outcomes were reused. The physical transport cases include five actual Game Session owner-client methods and four protected World method-guard methods, with owner-store/result doubles. Its 196 World integration definitions compiled/discovered but skipped locally without Docker; the later executed runner result and corrections are recorded above. Component fixtures may stipulate upstream proof while executing the actual World owner transition, but they do not prove a Game Session pointer/audit commit or a playable flow. The runner executed V47–V49 and the passing owner cases, but corrected both-origin placement proof, genuine upstream owner evidence and complete activation/placement/region delivery remain open. diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseEvidence.java b/services/common-security/src/main/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseEvidence.java new file mode 100644 index 0000000000..eb42f2e370 --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseEvidence.java @@ -0,0 +1,434 @@ +package net.firedevops.firemud.common.account.admission; + +import java.io.IOException; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import tools.jackson.core.JacksonException; +import tools.jackson.core.JsonParser; +import tools.jackson.core.JsonToken; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Immutable, shape-only public-production lease carrier. This value authenticates no issuer, + * establishes no current source evidence, and never grants admission or proves COMMITTED state. + * + *

Tuple counters and membership versions inherit the public delegation validator's positive + * signed-long range. Values above that supported source range are rejected without substitution. + */ +public final class AccountGameplayAdmissionLeaseEvidence { + public static final String SCHEMA = "account-gameplay-admission-lease-evidence/v1"; + public static final long MAX_DURATION_MILLIS = 15_000L; + public static final int MAX_EVIDENCE_BYTES = 64 * 1024; + public static final int MAX_DEPTH = 8; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + private static final Set FIELDS = + Set.of( + "schema", + "schemaVersion", + "mode", + "targetNamespace", + "callerWorkload", + "requestId", + "leaseId", + "leaseFence", + "bindingScope", + "leaseKind", + "authorityTuple", + "issuanceFence", + "membershipBaseline", + "outboxCheckpoints", + "tokenIdentityEvidence", + "evaluatedAt", + "expiresAt"); + private final Map carrier; + private final String canonicalJson; + private final String digest; + + private AccountGameplayAdmissionLeaseEvidence(Map source) { + Map value = Map.copyOf(object(freeze(source, 1, new ByteBudget()))); + byte[] canonicalBytes = canonicalBytes(value); + Set expected = new java.util.HashSet<>(FIELDS); + LeaseKind kind = LeaseKind.valueOf(string(value, "leaseKind")); + if (kind == LeaseKind.RESUME) { + expected.add("resumeEpisodeId"); + expected.add("expectedOldBindingGeneration"); + } else if (value.containsKey("expectedOldBindingGeneration")) { + expected.add("expectedOldBindingGeneration"); + } + exact(value, expected); + if (!SCHEMA.equals(value.get("schema")) + || !"1".equals(value.get("schemaVersion")) + || !"PUBLIC_PRODUCTION".equals(value.get("mode"))) throw invalid(); + uuid(string(value, "requestId"), true); + uuid(string(value, "leaseId"), true); + if (kind == LeaseKind.RESUME) uuid(string(value, "resumeEpisodeId"), true); + if (value.containsKey("expectedOldBindingGeneration")) + positive(string(value, "expectedOldBindingGeneration")); + positive(string(value, "leaseFence")); + String namespace = string(value, "targetNamespace"); + String peerUri = string(value, "callerWorkload"); + GrpcPeerIdentity peer = + GrpcPeerIdentity.parseUri(peerUri) + .orElseThrow(AccountGameplayAdmissionLeaseEvidence::invalid); + if (!peer.uri().equals(peerUri) + || !namespace.equals(peer.namespace()) + || !peer.isService("game-session-service")) throw invalid(); + + Map scope = object(value.get("bindingScope")); + exact( + scope, + Set.of( + "accountId", + "tenantId", + "realmId", + "worldSlug", + "realmSlug", + "playableStateNamespaceId", + "playableStateScope", + "gameInstanceId", + "characterId", + "sessionId", + "bindingGeneration", + "catalogRevision", + "pointerVersion", + "regionId", + "regionEpoch")); + for (String field : + List.of( + "accountId", + "tenantId", + "realmId", + "playableStateNamespaceId", + "gameInstanceId", + "characterId", + "sessionId", + "regionId")) uuid(string(scope, field), false); + for (String field : + List.of("bindingGeneration", "catalogRevision", "pointerVersion", "regionEpoch")) + positive(string(scope, field)); + for (String field : List.of("worldSlug", "realmSlug")) text(string(scope, field)); + if (!Set.of("SHARED", "ISOLATED").contains(scope.get("playableStateScope"))) throw invalid(); + String tenant = string(scope, "tenantId"); + String account = string(scope, "accountId"); + + Map baseline = object(value.get("membershipBaseline")); + exact( + baseline, + Set.of("membershipLifecycleState", "membershipVersion", "membershipAuthorityGeneration")); + MembershipLifecycleState.valueOf(string(baseline, "membershipLifecycleState")); + Map versions = object(baseline.get("membershipVersion")); + exact(versions, Set.of(tenant)); + nonnegative(string(versions, tenant)); + String membershipGeneration = string(baseline, "membershipAuthorityGeneration"); + positive(membershipGeneration); + Map tuple = object(value.get("authorityTuple")); + // Reuse the profile's supported positive signed-long range, including exact values above 2^53. + try { + GameSessionAccountDelegationProfile.requirePublicTenantBoundAuthority( + tenant, tuple, versions); + } catch (RuntimeException failure) { + throw new IllegalArgumentException("Malformed public-tenant authority tuple", failure); + } + if (!membershipGeneration.equals( + object(tuple.get("membershipAuthorityGeneration")).get(tenant))) throw invalid(); + String fence = string(value, "issuanceFence"); + positive(fence); + + List checkpoints = list(value.get("outboxCheckpoints")); + Map coordinates = new LinkedHashMap<>(); + byte[] previous = null; + for (Object entry : checkpoints) { + Map checkpoint = object(entry); + exact(checkpoint, Set.of("outboxStreamKey", "outboxSequence")); + String key = string(checkpoint, "outboxStreamKey"); + text(key); + String sequence = string(checkpoint, "outboxSequence"); + nonnegative(sequence); + byte[] bytes = key.getBytes(StandardCharsets.UTF_8); + if (previous != null && Arrays.compareUnsigned(previous, bytes) >= 0) throw invalid(); + previous = bytes; + coordinates.put(key, sequence); + } + String prefix = "account:auth-authority:v1:"; + String issuerStream = prefix + "issuer/" + GameSessionAccountDelegationProfile.ISSUER; + String accountStream = prefix + "account/" + account; + String tenantStream = prefix + "tenant/" + tenant; + String membershipStream = prefix + "membership/" + account + "/" + tenant; + exact(coordinates, Set.of(issuerStream, accountStream, tenantStream, membershipStream)); + for (String stream : List.of(tenantStream, membershipStream)) positive(coordinates.get(stream)); + if (tuple.containsKey("accountSecurityCutoff")) { + cutoff(object(tuple.get("accountSecurityCutoff")), accountStream, coordinates); + } + if (tuple.containsKey("tenantBillingCutoff")) { + cutoff( + object(object(tuple.get("tenantBillingCutoff")).get(tenant)), tenantStream, coordinates); + } + + Map token = object(value.get("tokenIdentityEvidence")); + exact( + token, + Set.of( + "accountId", + "operationId", + "issuanceRequestId", + "tokenJti", + "tokenSHA256", + "tokenGeneration", + "issuanceFence", + "tokenIdentityFence", + "tokenProfile", + "issuedAt", + "notBefore", + "expiresAt")); + uuid(string(token, "accountId"), false); + for (String field : List.of("operationId", "issuanceRequestId", "tokenJti")) + uuid(string(token, field), true); + if (!account.equals(token.get("accountId")) + || !fence.equals(token.get("issuanceFence")) + || !string(token, "tokenSHA256").matches("[0-9a-f]{64}") + || !GameSessionAccountDelegationProfile.PROFILE.equals(token.get("tokenProfile"))) + throw invalid(); + for (String field : List.of("tokenGeneration", "issuanceFence", "tokenIdentityFence")) + positive(string(token, field)); + BigInteger issued = timestamp(token, "issuedAt").multiply(BigInteger.valueOf(1000L)); + BigInteger notBefore = timestamp(token, "notBefore").multiply(BigInteger.valueOf(1000L)); + BigInteger tokenExpiry = timestamp(token, "expiresAt").multiply(BigInteger.valueOf(1000L)); + BigInteger evaluated = timestamp(value, "evaluatedAt"); + BigInteger expiry = timestamp(value, "expiresAt"); + BigInteger duration = expiry.subtract(evaluated); + if (issued.compareTo(evaluated) > 0 + || notBefore.compareTo(issued) > 0 + || expiry.compareTo(tokenExpiry) > 0 + || duration.signum() <= 0 + || duration.compareTo(BigInteger.valueOf(MAX_DURATION_MILLIS)) > 0) throw invalid(); + carrier = value; + try { + canonicalJson = new String(canonicalBytes, StandardCharsets.UTF_8); + digest = + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(canonicalBytes)); + } catch (NoSuchAlgorithmException failure) { + throw new IllegalArgumentException("Cannot canonicalize lease evidence", failure); + } + } + + public enum LeaseKind { + NEW_BINDING, + RESUME + } + + public enum MembershipLifecycleState { + ACTIVE, + INACTIVE + } + + /** Validates and defensively freezes original carriers without establishing their provenance. */ + public static AccountGameplayAdmissionLeaseEvidence fromCarrier(Map carrier) { + if (carrier == null) throw invalid(); + return new AccountGameplayAdmissionLeaseEvidence(carrier); + } + + /** Accepts only the exact canonical serialization; duplicate and unknown fields fail closed. */ + public static AccountGameplayAdmissionLeaseEvidence parseCanonical(String json) { + requireByteBound(json); + try { + // Inspect depth before allocating a nested object tree; duplicate detection applies here too. + try (JsonParser parser = JSON.createParser(json)) { + int depth = 0; + JsonToken token; + while ((token = parser.nextToken()) != null) { + if ((token == JsonToken.START_OBJECT || token == JsonToken.START_ARRAY) + && ++depth > MAX_DEPTH) throw invalid(); + if (token == JsonToken.END_OBJECT || token == JsonToken.END_ARRAY) depth--; + } + } + AccountGameplayAdmissionLeaseEvidence result = + fromCarrier(object(JSON.readValue(json, Object.class))); + if (!result.canonicalJson.equals(json)) throw invalid(); + return result; + } catch (JacksonException failure) { + throw new IllegalArgumentException("Malformed lease evidence", failure); + } + } + + public Map carrier() { + return carrier; + } + + public String canonicalJson() { + return canonicalJson; + } + + public String sha256() { + return digest; + } + + public BigInteger leaseFence() { + return positive(string(carrier, "leaseFence")); + } + + public LeaseKind leaseKind() { + return LeaseKind.valueOf(string(carrier, "leaseKind")); + } + + /** Exact original immutable carriers and their canonical digest define retry identity. */ + public boolean hasSameIdentity(AccountGameplayAdmissionLeaseEvidence other) { + return other != null && carrier.equals(other.carrier) && digest.equals(other.digest); + } + + @Override + public boolean equals(Object other) { + return other instanceof AccountGameplayAdmissionLeaseEvidence evidence + && hasSameIdentity(evidence); + } + + @Override + public int hashCode() { + return carrier.hashCode(); + } + + @Override + public String toString() { + return "AccountGameplayAdmissionLeaseEvidence[redacted]"; + } + + private static void cutoff( + Map cutoff, String stream, Map checkpoints) { + if (!stream.equals(cutoff.get("outboxStreamKey")) + || nonnegative(checkpoints.get(stream)) + .compareTo(positive(string(cutoff, "outboxSequence"))) + < 0) throw invalid(); + } + + private static BigInteger timestamp(Map object, String field) { + BigInteger value = positive(string(object, field)); + if (value.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0) throw invalid(); + return value; + } + + private static BigInteger positive(String value) { + BigInteger integer = nonnegative(value); + if (integer.signum() <= 0) throw invalid(); + return integer; + } + + private static BigInteger nonnegative(String value) { + if (value == null || !value.matches("0|[1-9][0-9]*")) throw invalid(); + return new BigInteger(value); + } + + private static void uuid(String value, boolean highEntropy) { + UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (RuntimeException failure) { + throw invalid(); + } + if (!parsed.toString().equals(value) + || parsed.equals(new UUID(0, 0)) + || (highEntropy && (parsed.version() != 4 || parsed.variant() != 2))) throw invalid(); + } + + private static void text(String value) { + if (value.isBlank() + || value.length() > 2048 + || value.codePoints().anyMatch(Character::isISOControl)) throw invalid(); + } + + private static String string(Map object, String field) { + if (!(object.get(field) instanceof String value)) throw invalid(); + return value; + } + + private static void exact(Map object, Set fields) { + if (!object.keySet().equals(fields)) throw invalid(); + } + + private static Map object(Object value) { + if (!(value instanceof Map map)) throw invalid(); + Map result = new LinkedHashMap<>(); + map.forEach( + (key, child) -> { + if (!(key instanceof String text)) throw invalid(); + result.put(text, child); + }); + return result; + } + + private static List list(Object value) { + if (!(value instanceof List entries)) throw invalid(); + return entries; + } + + private static Object freeze(Object value, int depth, ByteBudget budget) { + if (depth > MAX_DEPTH) throw invalid(); + budget.consume(1); + if (value instanceof Map map) { + Map result = new LinkedHashMap<>(); + for (Map.Entry entry : map.entrySet()) { + if (!(entry.getKey() instanceof String key)) throw invalid(); + budget.consume(requireByteBound(key) + 4); + result.put(key, freeze(entry.getValue(), depth + 1, budget)); + } + return java.util.Collections.unmodifiableMap(result); + } + if (value instanceof List values) { + List frozen = new ArrayList<>(); + for (Object child : values) frozen.add(freeze(child, depth + 1, budget)); + return List.copyOf(frozen); + } + if (!(value instanceof String text)) throw invalid(); + budget.consume(requireByteBound(text) + 2); + return value; + } + + private static int requireByteBound(String value) { + if (value == null || value.length() > MAX_EVIDENCE_BYTES) throw invalid(); + int size = value.getBytes(StandardCharsets.UTF_8).length; + if (size > MAX_EVIDENCE_BYTES) throw invalid(); + return size; + } + + private static byte[] canonicalBytes(Map value) { + try { + String serialized = JSON.writeValueAsString(value); + requireByteBound(serialized); + byte[] bytes = Rfc8785CanonicalJson.canonicalizeUtf8(serialized); + if (bytes.length > MAX_EVIDENCE_BYTES) throw invalid(); + return bytes; + } catch (IOException | JacksonException failure) { + throw new IllegalArgumentException("Cannot canonicalize lease evidence", failure); + } + } + + private static final class ByteBudget { + private int remaining = MAX_EVIDENCE_BYTES; + + private void consume(int count) { + remaining -= count; + if (remaining < 0) throw invalid(); + } + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Malformed public-production admission lease evidence"); + } +} diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/AccountJwtProfileClaimSupport.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/AccountJwtProfileClaimSupport.java index 30f12d4270..eb38470cf9 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/AccountJwtProfileClaimSupport.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/AccountJwtProfileClaimSupport.java @@ -200,6 +200,62 @@ static Map requireVersionMap(Object value) { return result; } + /** Delegation-only signed-long bounds; generic Account counter semantics remain unchanged. */ + static Map requireDelegationAuthorityTuple( + Object value, + boolean allowTenantBillingCutoff, + boolean requireUnscoped, + boolean requireAccountCutoffForAdvancedGeneration) { + Map tuple = + requireAuthorityTuple( + value, + allowTenantBillingCutoff, + requireUnscoped, + requireAccountCutoffForAdvancedGeneration, + GameSessionAccountDelegationProfile.MAX_AUTHORITY_TUPLE_BYTES); + requireDelegationPositiveLong(tuple.get("issuerAuthGeneration")); + long accountGeneration = requireDelegationPositiveLong(tuple.get("accountAuthorityGeneration")); + requireDelegationVersionMap(tuple.get("tenantAuthorityGeneration")); + requireDelegationVersionMap(tuple.get("membershipAuthorityGeneration")); + if (tuple.containsKey("accountSecurityCutoff")) { + Map cutoff = requireObjectMap(tuple.get("accountSecurityCutoff")); + long generation = requireDelegationPositiveLong(cutoff.get("accountAuthorityGeneration")); + long sequence = requireDelegationPositiveLong(cutoff.get("outboxSequence")); + if (generation != accountGeneration || sequence != accountGeneration - 1L) throw invalid(); + } + if (tuple.containsKey("tenantBillingCutoff")) { + requireObjectMap(tuple.get("tenantBillingCutoff")) + .values() + .forEach( + entry -> { + var cutoff = requireObjectMap(entry); + requireDelegationPositiveLong(cutoff.get("tenantAuthorityGeneration")); + requireDelegationPositiveLong(cutoff.get("tenantBillingSequence")); + requireDelegationPositiveLong(cutoff.get("outboxSequence")); + }); + } + return tuple; + } + + static Map requireDelegationVersionMap(Object value) { + Map result = new LinkedHashMap<>(); + requireObjectMap(value) + .forEach( + (key, counter) -> { + requireUuid(key); + result.put(key, requireDelegationPositiveLong(counter)); + }); + return result; + } + + private static long requireDelegationPositiveLong(Object value) { + try { + return AccountJwtExactValues.positiveDecimalCounter(value).longValueExact(); + } catch (IllegalArgumentException | ArithmeticException failure) { + throw invalid(); + } + } + static void validateAccountSecurityCutoff(Object value, BigInteger accountGeneration) { Map cutoff = requireObjectMap(value); if (!cutoff diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameSessionAccountDelegationProfile.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameSessionAccountDelegationProfile.java new file mode 100644 index 0000000000..d77801189a --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameSessionAccountDelegationProfile.java @@ -0,0 +1,141 @@ +package net.firedevops.firemud.common.security; + +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.regex.Pattern; + +/** + * Bounded initial non-tenant and distinct public-production tenant-bound Account delegation forms. + * + *

This declares claim shape only. It does not authenticate Game Session, verify a signature, + * prove signer promotion, establish current Account evidence, or authorize a call. It is separate + * from Social & Friends delegations and from generic backend JWT conventions. + */ +public final class GameSessionAccountDelegationProfile { + public static final String PROFILE = "game-session-account-delegation"; + public static final String TYPE = "private_player_delegation"; + public static final String ISSUER = "firemud-account-service"; + public static final String AUDIENCE = "account-service"; + public static final String TOKEN_TYPE_CLAIM = "tokenType"; + public static final String TOKEN_PROFILE_CLAIM = "tokenProfile"; + public static final long MAX_TOKEN_LIFETIME_SECONDS = 300L; + public static final int MAX_COMPACT_JWT_BYTES = 16 * 1024; + public static final int MAX_AUTHORITY_TUPLE_BYTES = 4 * 1024; + public static final int MAX_REGISTRY_RECORD_BYTES = 16 * 1024; + private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]{0,18}"); + + private GameSessionAccountDelegationProfile() {} + + /** Checks the supported public-production tenant-bound form, never an initial LOGIN tuple. */ + public static void requirePublicTenantBoundAuthority( + String tenantId, Map tuple, Map membershipVersion) { + AccountJwtProfileClaimSupport.requireUuid(tenantId); + AccountJwtProfileClaimSupport.requireDelegationAuthorityTuple(tuple, true, false, true); + for (String field : + java.util.List.of("tenantAuthorityGeneration", "membershipAuthorityGeneration")) { + if (!AccountJwtProfileClaimSupport.requireDelegationVersionMap(tuple.get(field)) + .keySet() + .equals(java.util.Set.of(tenantId))) throw AccountJwtProfileClaimSupport.invalid(); + } + if (!AccountJwtProfileClaimSupport.requireDelegationVersionMap(membershipVersion) + .keySet() + .equals(java.util.Set.of(tenantId)) + || !java.util.List.of().equals(tuple.get("privateRealmGrantVersions"))) { + throw AccountJwtProfileClaimSupport.invalid(); + } + if (tuple.containsKey("tenantBillingCutoff")) { + Map cutoff = + AccountJwtProfileClaimSupport.requireObjectMap(tuple.get("tenantBillingCutoff")); + if (!cutoff.keySet().equals(java.util.Set.of(tenantId))) + throw AccountJwtProfileClaimSupport.invalid(); + var value = AccountJwtProfileClaimSupport.requireObjectMap(cutoff.get(tenantId)); + var generation = + AccountJwtProfileClaimSupport.requireObjectMap(tuple.get("tenantAuthorityGeneration")); + if (!java.util.Objects.equals( + generation.get(tenantId), value.get("tenantAuthorityGeneration"))) { + throw AccountJwtProfileClaimSupport.invalid(); + } + } + } + + /** Returns the exact required unscoped authority tuple for an initial credential login. */ + public static Map authorityTuple( + long issuerAuthGeneration, long accountAuthorityGeneration) { + if (accountAuthorityGeneration != 1L) { + throw new IllegalArgumentException( + "Advanced Account authority requires its exact current security cutoff"); + } + return authorityTuple(issuerAuthGeneration, accountAuthorityGeneration, Optional.empty()); + } + + /** Returns the exact tuple, carrying the Account cutoff only when source evidence proves it. */ + public static Map authorityTuple( + long issuerAuthGeneration, + long accountAuthorityGeneration, + Optional accountSecurityCutoff) { + if (issuerAuthGeneration <= 0L || accountAuthorityGeneration <= 0L) { + throw new IllegalArgumentException("Account delegation generations must be positive"); + } + Objects.requireNonNull(accountSecurityCutoff, "Account cutoff applicability is required"); + if ((accountAuthorityGeneration == 1L) != accountSecurityCutoff.isEmpty()) { + throw new IllegalArgumentException( + "Account security cutoff presence does not match the source generation"); + } + accountSecurityCutoff.ifPresent( + cutoff -> { + if (!Long.toString(accountAuthorityGeneration).equals(cutoff.accountAuthorityGeneration()) + || !Long.toString(accountAuthorityGeneration - 1L).equals(cutoff.outboxSequence())) { + throw new IllegalArgumentException( + "Account security cutoff generation or sequence is stale"); + } + }); + Map tuple = new LinkedHashMap<>(); + tuple.put("issuerAuthGeneration", Long.toString(issuerAuthGeneration)); + tuple.put("accountAuthorityGeneration", Long.toString(accountAuthorityGeneration)); + tuple.put("tenantAuthorityGeneration", Map.of()); + tuple.put("membershipAuthorityGeneration", Map.of()); + tuple.put("privateRealmGrantVersions", java.util.List.of()); + accountSecurityCutoff.ifPresent(cutoff -> tuple.put("accountSecurityCutoff", cutoff.toMap())); + return Map.copyOf(tuple); + } + + /** Exact optional Account cutoff value carried by this profile's authority tuple. */ + public record AccountSecurityCutoff( + String accountAuthorityGeneration, String outboxStreamKey, String outboxSequence) { + public AccountSecurityCutoff { + requirePositiveDecimal(accountAuthorityGeneration, "cutoff generation"); + requirePositiveDecimal(outboxSequence, "cutoff outbox sequence"); + if (outboxStreamKey == null + || outboxStreamKey.length() > 2048 + || !outboxStreamKey.startsWith("account:auth-authority:v1:account/")) { + throw new IllegalArgumentException("Account security cutoff stream is malformed"); + } + for (int index = 0; index < outboxStreamKey.length(); index++) { + if (Character.isISOControl(outboxStreamKey.charAt(index))) { + throw new IllegalArgumentException("Account security cutoff stream is malformed"); + } + } + } + + public Map toMap() { + return Map.of( + "accountAuthorityGeneration", accountAuthorityGeneration, + "outboxStreamKey", outboxStreamKey, + "outboxSequence", outboxSequence); + } + + private static void requirePositiveDecimal(String value, String field) { + if (value == null || !POSITIVE_DECIMAL.matcher(value).matches()) { + throw new IllegalArgumentException("Account security cutoff " + field + " is malformed"); + } + try { + Long.parseLong(value); + } catch (NumberFormatException ex) { + throw new IllegalArgumentException( + "Account security cutoff " + field + " exceeds the supported range"); + } + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHold.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHold.java new file mode 100644 index 0000000000..4da66a77ea --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHold.java @@ -0,0 +1,114 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; + +/** + * Distinct World-owned player-admission lifecycle hold. This is neither a first-pointer hold nor + * Account authorization, Game Session's binding decision, or gameplay admission permission. + * + *

The complete original lease and exact World owner evidence remain immutable. Its deadline is + * diagnostic only. Release requires independently authenticated exact Account terminal evidence AND + * Game Session installation/cleanup evidence; those producers do not exist in this slice. + */ +public record WorldCanonicalPlayerAdmissionHold( + UUID holdId, + UUID holdFence, + Request request, + WorldCanonicalInstanceLifecycleEvidence worldEvidence) { + public WorldCanonicalPlayerAdmissionHold { + requireOpaque(holdId); + requireOpaque(holdFence); + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(worldEvidence, "worldEvidence"); + request.requireExactActiveWorld(worldEvidence); + } + + /** Retained lease deadline triggers recovery diagnostics, never automatic release. */ + public long diagnosticExpiresAtMillis() { + return Long.parseLong((String) request.lease().carrier().get("expiresAt")); + } + + /** + * Complete original Account lease plus independently expected World lifecycle tuple. Account's + * regionEpoch is a separate domain and is never interpreted as this World lifecycle epoch. + */ + public record Request( + AccountGameplayAdmissionLeaseEvidence lease, + long expectedLifecycleEpoch, + long expectedRowVersion) { + public Request { + Objects.requireNonNull(lease, "lease"); + if (expectedLifecycleEpoch <= 0 || expectedRowVersion < 0) { + throw new IllegalArgumentException("Expected World lifecycle tuple is invalid"); + } + if (!(lease.carrier().get("bindingScope") instanceof Map scope) + || !"SHARED".equals(scope.get("playableStateScope")) + || !(lease.carrier().get("membershipBaseline") instanceof Map baseline) + || !"ACTIVE".equals(baseline.get("membershipLifecycleState"))) { + throw new IllegalArgumentException("Unsupported or non-admitting original lease scope"); + } + } + + public UUID leaseId() { + return UUID.fromString((String) lease.carrier().get("leaseId")); + } + + public UUID attemptId() { + return UUID.fromString((String) lease.carrier().get("requestId")); + } + + public UUID canonicalGameInstanceId() { + return UUID.fromString((String) scope().get("gameInstanceId")); + } + + public String targetNamespace() { + return (String) lease.carrier().get("targetNamespace"); + } + + public boolean sameBinding(Request other) { + return other != null + && lease.hasSameIdentity(other.lease) + && expectedLifecycleEpoch == other.expectedLifecycleEpoch + && expectedRowVersion == other.expectedRowVersion; + } + + public void requireExactActiveWorld(WorldCanonicalInstanceLifecycleEvidence evidence) { + Objects.requireNonNull(evidence, "evidence"); + requireExactWorldSelector(evidence.request()); + if (!"ACTIVE".equals(evidence.lifecycleStatus()) + || expectedLifecycleEpoch != evidence.lifecycleEpoch() + || expectedRowVersion != evidence.rowVersion()) { + throw new IllegalArgumentException("World target is not the exact expected ACTIVE tuple"); + } + } + + void requireExactWorldSelector(WorldCanonicalInstanceLifecycleEvidence.Request selector) { + if (!targetNamespace().equals(selector.targetNamespace()) + || !scope().get("tenantId").equals(selector.canonicalTenantId().toString()) + || !scope().get("worldSlug").equals(selector.worldSlug()) + || !scope().get("gameInstanceId").equals(selector.canonicalGameInstanceId().toString()) + || !scope() + .get("playableStateNamespaceId") + .equals(selector.playableStateNamespaceId().toString()) + || !scope().get("playableStateScope").equals(selector.playableStateScope()) + || !selector.publicProduction()) { + throw new IllegalArgumentException("Original lease differs from canonical World scope"); + } + } + + @SuppressWarnings("unchecked") + private Map scope() { + return (Map) lease.carrier().get("bindingScope"); + } + } + + private static void requireOpaque(UUID value) { + if (value == null || value.version() != 4 || value.variant() != 2) { + throw new IllegalArgumentException("Hold identity and fence must be opaque UUIDs"); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldRepository.java new file mode 100644 index 0000000000..d057e9b954 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldRepository.java @@ -0,0 +1,207 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.nio.charset.StandardCharsets; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered Account-to-World acquisition/readback component. V51 serializes insertion and every + * lifecycle mutation on the actual owner row, and versions that tuple without changing its state or + * counters so older MVCC snapshots cannot overlook the committed hold. + */ +public final class WorldCanonicalPlayerAdmissionHoldRepository { + private final DSLContext dsl; + private final String namespace; + private final TransactionTemplate writeTransaction; + private final TransactionTemplate readTransaction; + private final WorldCanonicalInstanceAssociationRepository associations; + private final WorldCanonicalInstanceLifecycleReadRepository lifecycles; + + public WorldCanonicalPlayerAdmissionHoldRepository( + DSLContext dsl, + PlatformTransactionManager transactionManager, + String namespace, + WorldCanonicalInstanceAssociationRepository associations, + WorldCanonicalInstanceLifecycleReadRepository lifecycles) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.namespace = WorldCanonicalPlayerAdmissionHoldService.requireNamespace(namespace); + this.associations = Objects.requireNonNull(associations, "associations"); + this.lifecycles = Objects.requireNonNull(lifecycles, "lifecycles"); + writeTransaction = new TransactionTemplate(Objects.requireNonNull(transactionManager)); + writeTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + writeTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + readTransaction = new TransactionTemplate(transactionManager); + readTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + readTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + readTransaction.setReadOnly(true); + } + + public WorldCanonicalPlayerAdmissionHold acquire( + WorldCanonicalPlayerAdmissionHold.Request request) { + requireBoundary(request); + return Objects.requireNonNull( + writeTransaction.execute( + status -> { + requireActualTransaction(false, "read committed"); + Record previous = findOriginal(request); + if (previous != null) return retained(previous, request); + + var association = + associations + .readOwnerAssociationInActivationTransaction( + request.canonicalGameInstanceId()) + .orElseThrow(() -> denied("Canonical World instance association is missing")); + var selector = selector(association, request.attemptId()); + request.requireExactWorldSelector(selector); + var current = + lifecycles + .readForActivationInOwnerTransaction(selector) + .orElseThrow(() -> denied("Canonical World lifecycle source is unavailable")); + request.requireExactActiveWorld(current); + + // Another exact retry may have inserted while this transaction waited on the row. + previous = findOriginal(request); + if (previous != null) return retained(previous, request); + UUID id = UUID.randomUUID(); + UUID fence = UUID.randomUUID(); + dsl.execute( + "INSERT INTO world_canonical_player_admission_hold " + + "(hold_id,hold_fence,lease_id,attempt_id,lease_sha256,lease_bytes," + + "canonical_game_instance_id,world_instance_id,active_lifecycle_epoch," + + "active_row_version,world_evidence_bytes,diagnostic_expires_at_millis) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?)", + id, + fence, + request.leaseId(), + request.attemptId(), + request.lease().sha256(), + request.lease().canonicalJson().getBytes(StandardCharsets.UTF_8), + request.canonicalGameInstanceId(), + association.worldInstanceId(), + current.lifecycleEpoch(), + current.rowVersion(), + current.canonicalBytes(), + Long.parseLong((String) request.lease().carrier().get("expiresAt"))); + var result = retained(Objects.requireNonNull(findOriginal(request)), request); + if (!id.equals(result.holdId()) || !fence.equals(result.holdFence())) { + throw denied("New hold readback differs from allocated identity"); + } + return result; + })); + } + + /** Exact durable retained identity; absence is UNKNOWN, never an abort or release result. */ + public Optional read( + WorldCanonicalPlayerAdmissionHold.Request request) { + requireBoundary(request); + return Optional.ofNullable( + readTransaction.execute( + status -> { + requireActualTransaction(true, "repeatable read"); + Record row = findOriginal(request); + return row == null ? null : retained(row, request); + })); + } + + private void requireBoundary(WorldCanonicalPlayerAdmissionHold.Request request) { + WorldCanonicalPlayerAdmissionHoldService.requireAccountPeer(namespace); + requireNoAmbientTransaction(); + Objects.requireNonNull(request, "request"); + if (!namespace.equals(request.targetNamespace())) + throw denied("Lease namespace differs from World"); + } + + private Record findOriginal(WorldCanonicalPlayerAdmissionHold.Request request) { + return dsl.fetchOne( + "SELECT * FROM world_canonical_player_admission_hold WHERE lease_id=? OR attempt_id=?", + request.leaseId(), + request.attemptId()); + } + + private static WorldCanonicalPlayerAdmissionHold retained( + Record row, WorldCanonicalPlayerAdmissionHold.Request expected) { + byte[] bytes = Objects.requireNonNull(row.get("lease_bytes", byte[].class)); + var lease = + AccountGameplayAdmissionLeaseEvidence.parseCanonical( + new String(bytes, StandardCharsets.UTF_8)); + var request = + new WorldCanonicalPlayerAdmissionHold.Request( + lease, + Objects.requireNonNull(row.get("active_lifecycle_epoch", Long.class)), + Objects.requireNonNull(row.get("active_row_version", Long.class))); + if (!expected.sameBinding(request) + || !lease.sha256().equals(row.get("lease_sha256", String.class)) + || !request.leaseId().equals(row.get("lease_id", UUID.class)) + || !request.attemptId().equals(row.get("attempt_id", UUID.class)) + || !request + .canonicalGameInstanceId() + .equals(row.get("canonical_game_instance_id", UUID.class)) + || Long.parseLong((String) lease.carrier().get("expiresAt")) + != Objects.requireNonNull(row.get("diagnostic_expires_at_millis", Long.class)) + || !"HELD".equals(row.get("hold_state", String.class)) + || row.get("account_terminal_evidence_bytes") != null + || row.get("game_session_completion_evidence_bytes") != null) { + throw denied("Retained hold conflicts with the complete original lease/attempt binding"); + } + return new WorldCanonicalPlayerAdmissionHold( + row.get("hold_id", UUID.class), + row.get("hold_fence", UUID.class), + request, + WorldCanonicalInstanceLifecycleEvidence.fromStored( + row.get("world_evidence_bytes", byte[].class))); + } + + private static WorldCanonicalInstanceLifecycleEvidence.Request selector( + WorldCanonicalInstanceAssociation association, UUID readId) { + var identity = association.identity(); + var binding = association.completeLaunchBinding(); + return new WorldCanonicalInstanceLifecycleEvidence.Request( + 1, + readId, + identity.targetNamespace(), + identity.canonicalTenantId(), + identity.worldSlug(), + identity.canonicalGameInstanceId(), + identity.playableStateNamespaceId(), + identity.playableStateScope(), + identity.publicProduction(), + identity.controlPlaneRequestId(), + association.canonicalVersionId(), + binding.descriptor().requestDigest(), + binding.descriptor().resultDigest(), + binding.evidence().releaseAttestation().evidenceDigest()); + } + + private void requireActualTransaction(boolean readOnly, String isolation) { + Record state = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS isolation, " + + "current_setting('transaction_read_only') AS read_only")); + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() != readOnly + || !isolation.equals(state.get("isolation", String.class)) + || !(readOnly ? "on" : "off").equals(state.get("read_only", String.class))) { + throw denied("World hold requires its owned transaction isolation and mutability"); + } + } + + static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw denied("World hold requires no ambient transaction"); + } + } + + private static IllegalStateException denied(String message) { + return new IllegalStateException(message); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldService.java new file mode 100644 index 0000000000..fb115dfa11 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldService.java @@ -0,0 +1,81 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; + +/** + * Unregistered internal boundary. Authenticating the exact Account workload establishes only the + * producer of the original lease; World never interprets the carrier as current Account authority. + */ +public final class WorldCanonicalPlayerAdmissionHoldService { + private final WorldCanonicalPlayerAdmissionHoldRepository repository; + private final String namespace; + + public WorldCanonicalPlayerAdmissionHoldService( + WorldCanonicalPlayerAdmissionHoldRepository repository, String namespace) { + this.repository = Objects.requireNonNull(repository, "repository"); + this.namespace = requireNamespace(namespace); + } + + public WorldCanonicalPlayerAdmissionHold acquire( + String originalLeaseJson, + String originalLeaseSha256, + long expectedEpoch, + long expectedVersion) { + return repository.acquire( + request(originalLeaseJson, originalLeaseSha256, expectedEpoch, expectedVersion)); + } + + public Optional read( + String originalLeaseJson, + String originalLeaseSha256, + long expectedEpoch, + long expectedVersion) { + return repository.read( + request(originalLeaseJson, originalLeaseSha256, expectedEpoch, expectedVersion)); + } + + /** No caller Boolean, COMMITTED label, expiry, or generic opaque proof can release this hold. */ + public void release() { + requireAccountPeer(namespace); + WorldCanonicalPlayerAdmissionHoldRepository.requireNoAmbientTransaction(); + throw new IllegalStateException( + "Hold release is unavailable without authenticated exact Account terminal AND Game Session installation/cleanup evidence"); + } + + private WorldCanonicalPlayerAdmissionHold.Request request( + String originalLeaseJson, + String originalLeaseSha256, + long expectedEpoch, + long expectedVersion) { + requireAccountPeer(namespace); + WorldCanonicalPlayerAdmissionHoldRepository.requireNoAmbientTransaction(); + var lease = AccountGameplayAdmissionLeaseEvidence.parseCanonical(originalLeaseJson); + if (!lease.sha256().equals(originalLeaseSha256) + || !namespace.equals(lease.carrier().get("targetNamespace"))) { + throw new IllegalArgumentException("Original lease digest or namespace differs"); + } + return new WorldCanonicalPlayerAdmissionHold.Request(lease, expectedEpoch, expectedVersion); + } + + static String requireNamespace(String namespace) { + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical World workload namespace is required"); + } + return namespace; + } + + static void requireAccountPeer(String namespace) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null + || !peer.isService("account-service") + || !peer.isInNamespace(namespace) + || SessionContext.hasAuthenticatedCallerContext()) { + throw new SecurityException( + "Exact authenticated same-namespace Account workload is required"); + } + } +} diff --git a/services/world-management-service/src/main/resources/db/migration/V51__world_canonical_player_admission_hold.sql b/services/world-management-service/src/main/resources/db/migration/V51__world_canonical_player_admission_hold.sql new file mode 100644 index 0000000000..515121ac2a --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V51__world_canonical_player_admission_hold.sql @@ -0,0 +1,241 @@ +-- Player admission is distinct from initial-pointer opening. No release producer exists yet: +-- every retained row stays HELD, even after its diagnostic lease deadline. +CREATE TABLE world_canonical_player_admission_hold ( + hold_id UUID PRIMARY KEY, + hold_fence UUID NOT NULL UNIQUE, + lease_id UUID NOT NULL UNIQUE, + attempt_id UUID NOT NULL UNIQUE, + lease_sha256 VARCHAR(64) NOT NULL CHECK (lease_sha256 ~ '^[0-9a-f]{64}$'), + lease_bytes BYTEA NOT NULL CHECK (octet_length(lease_bytes) BETWEEN 1 AND 65536), + canonical_game_instance_id UUID NOT NULL + REFERENCES world_canonical_instance_association(canonical_game_instance_id) ON DELETE RESTRICT, + world_instance_id BIGINT NOT NULL REFERENCES world_instance(id) ON DELETE RESTRICT, + active_lifecycle_epoch BIGINT NOT NULL CHECK (active_lifecycle_epoch > 0), + active_row_version BIGINT NOT NULL CHECK (active_row_version >= 0), + world_evidence_bytes BYTEA NOT NULL CHECK (octet_length(world_evidence_bytes) > 0), + diagnostic_expires_at_millis BIGINT NOT NULL CHECK (diagnostic_expires_at_millis > 0), + hold_state VARCHAR(16) NOT NULL DEFAULT 'HELD' CHECK (hold_state = 'HELD'), + -- Future terminalization must retain both exact independently authenticated owner results. + -- NULL means missing proof, never definitive absence. This migration authorizes neither. + account_terminal_evidence_bytes BYTEA CHECK (account_terminal_evidence_bytes IS NULL), + game_session_completion_evidence_bytes BYTEA CHECK (game_session_completion_evidence_bytes IS NULL), + acquisition_transaction_id BIGINT NOT NULL DEFAULT txid_current(), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP +); +CREATE INDEX idx_world_player_admission_hold_lifecycle + ON world_canonical_player_admission_hold(world_instance_id, hold_state); + +-- [jooq ignore start] +REVOKE ALL ON world_canonical_player_admission_hold FROM PUBLIC; + +CREATE FUNCTION world_validate_player_admission_hold() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + instance "${serviceSchema}".world_instance%ROWTYPE; + association "${serviceSchema}".world_canonical_instance_association%ROWTYPE; + preparation "${serviceSchema}".world_canonical_instance_preparation%ROWTYPE; + lease JSONB; + scope JSONB; + evidence JSONB; + selector JSONB; + evaluated BIGINT; + deadline BIGINT; + now_millis BIGINT; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'World player-admission hold is retained; authenticated dual-owner release is unavailable' + USING ERRCODE = '55000'; + END IF; + IF current_setting('transaction_isolation') <> 'read committed' + OR current_setting('transaction_read_only') <> 'off' + OR NEW.acquisition_transaction_id IS DISTINCT FROM txid_current() THEN + RAISE EXCEPTION 'World player-admission hold requires its writable READ COMMITTED owner transaction' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO instance FROM "${serviceSchema}".world_instance + WHERE id = NEW.world_instance_id FOR UPDATE; + IF NOT FOUND OR instance.status IS DISTINCT FROM 'ACTIVE' + OR instance.canonical_game_instance_id IS DISTINCT FROM NEW.canonical_game_instance_id + OR instance.lifecycle_epoch IS DISTINCT FROM NEW.active_lifecycle_epoch + OR instance.row_version IS DISTINCT FROM NEW.active_row_version THEN + RAISE EXCEPTION 'World player-admission hold requires the exact current ACTIVE lifecycle tuple' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO association FROM "${serviceSchema}".world_canonical_instance_association + WHERE canonical_game_instance_id = NEW.canonical_game_instance_id; + IF NOT FOUND OR association.world_instance_id IS DISTINCT FROM instance.id + OR association.local_tenant_key IS DISTINCT FROM instance.tenant_id + OR association.private_game_instance_key IS DISTINCT FROM instance.game_instance_id + OR association.canonical_tenant_id IS DISTINCT FROM instance.canonical_tenant_id + OR association.canonical_target_namespace IS DISTINCT FROM instance.canonical_target_namespace + OR association.canonical_world_slug IS DISTINCT FROM instance.canonical_world_slug + OR association.playable_state_namespace_id IS DISTINCT FROM instance.playable_state_namespace_id + OR association.playable_state_scope IS DISTINCT FROM instance.playable_state_scope + OR association.public_production IS DISTINCT FROM TRUE THEN + RAISE EXCEPTION 'World player-admission hold has no exact canonical owner association' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO preparation FROM "${serviceSchema}".world_canonical_instance_preparation + WHERE canonical_game_instance_id = NEW.canonical_game_instance_id; + IF NOT FOUND OR preparation.world_instance_id IS DISTINCT FROM instance.id + OR preparation.storage_status IS DISTINCT FROM 'MATERIALIZED_UNVERIFIED' + OR preparation.graph_sha256 IS DISTINCT FROM encode(sha256(preparation.graph_bytes), 'hex') + OR preparation.input_digest IS DISTINCT FROM + 'sha256:' || encode(sha256(convert_to(preparation.input_json,'UTF8')), 'hex') THEN + RAISE EXCEPTION 'World player-admission hold requires retained canonical materialization' + USING ERRCODE = '23514'; + END IF; + lease := convert_from(NEW.lease_bytes, 'UTF8')::JSONB; + scope := lease->'bindingScope'; + evidence := convert_from(NEW.world_evidence_bytes, 'UTF8')::JSONB; + selector := evidence->'request'; + evaluated := (lease->>'evaluatedAt')::BIGINT; + deadline := (lease->>'expiresAt')::BIGINT; + now_millis := floor(extract(epoch FROM clock_timestamp()) * 1000)::BIGINT; + IF lease->>'schema' IS DISTINCT FROM 'account-gameplay-admission-lease-evidence/v1' + OR lease->>'schemaVersion' IS DISTINCT FROM '1' + OR lease->>'mode' IS DISTINCT FROM 'PUBLIC_PRODUCTION' + OR lease->>'targetNamespace' IS DISTINCT FROM association.canonical_target_namespace + OR lease->>'callerWorkload' IS DISTINCT FROM + 'spiffe://firemud/ns/' || association.canonical_target_namespace || '/sa/game-session-service' + OR lease->>'leaseId' IS DISTINCT FROM NEW.lease_id::TEXT + OR lease->>'requestId' IS DISTINCT FROM NEW.attempt_id::TEXT + OR NEW.lease_sha256 IS DISTINCT FROM encode(sha256(NEW.lease_bytes), 'hex') + OR lease->'membershipBaseline'->>'membershipLifecycleState' IS DISTINCT FROM 'ACTIVE' + OR evaluated IS NULL OR deadline IS NULL OR evaluated <= 0 + OR evaluated > now_millis OR deadline <= now_millis + OR deadline <= evaluated OR deadline - evaluated > 15000 + OR NEW.diagnostic_expires_at_millis IS DISTINCT FROM deadline + OR scope->>'tenantId' IS DISTINCT FROM association.canonical_tenant_id::TEXT + OR scope->>'worldSlug' IS DISTINCT FROM association.canonical_world_slug + OR scope->>'gameInstanceId' IS DISTINCT FROM association.canonical_game_instance_id::TEXT + OR scope->>'playableStateNamespaceId' IS DISTINCT FROM association.playable_state_namespace_id::TEXT + OR scope->>'playableStateScope' IS DISTINCT FROM association.playable_state_scope + OR evidence->>'schema' IS DISTINCT FROM 'world-canonical-instance-lifecycle-evidence/v1' + OR evidence->>'lifecycleStatus' IS DISTINCT FROM 'ACTIVE' + OR evidence->>'lifecycleEpoch' IS DISTINCT FROM instance.lifecycle_epoch::TEXT + OR evidence->>'rowVersion' IS DISTINCT FROM instance.row_version::TEXT + OR evidence->>'captureId' IS DISTINCT FROM preparation.capture_id::TEXT + OR evidence->>'graphSha256' IS DISTINCT FROM preparation.graph_sha256 + OR evidence->>'preparationInputDigest' IS DISTINCT FROM preparation.input_digest + OR selector->>'schemaVersion' IS DISTINCT FROM '1' + OR selector->>'readRequestId' IS DISTINCT FROM NEW.attempt_id::TEXT + OR selector->>'targetNamespace' IS DISTINCT FROM association.canonical_target_namespace + OR selector->>'canonicalTenantId' IS DISTINCT FROM association.canonical_tenant_id::TEXT + OR selector->>'worldSlug' IS DISTINCT FROM association.canonical_world_slug + OR selector->>'canonicalGameInstanceId' IS DISTINCT FROM association.canonical_game_instance_id::TEXT + OR selector->>'playableStateNamespaceId' IS DISTINCT FROM association.playable_state_namespace_id::TEXT + OR selector->>'playableStateScope' IS DISTINCT FROM association.playable_state_scope + OR selector->'publicProduction' IS DISTINCT FROM 'true'::JSONB + OR selector->>'controlPlaneRequestId' IS DISTINCT FROM association.control_plane_request_id + OR selector->>'canonicalVersionId' IS DISTINCT FROM association.canonical_version_id::TEXT + OR selector->>'expectedDescriptorRequestDigest' IS DISTINCT FROM association.descriptor_request_digest + OR selector->>'expectedDescriptorResultDigest' IS DISTINCT FROM association.descriptor_result_digest + OR selector->>'expectedReleaseAttestationDigest' IS DISTINCT FROM association.release_attestation_digest THEN + RAISE EXCEPTION 'World player-admission hold differs from the original lease or exact owner evidence' + USING ERRCODE = '23514'; + END IF; + IF NEW.hold_id::TEXT !~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + OR NEW.hold_fence::TEXT !~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' THEN + RAISE EXCEPTION 'World player-admission hold requires opaque identities' USING ERRCODE='23514'; + END IF; + RETURN NEW; +END; +$$; +REVOKE ALL ON FUNCTION world_validate_player_admission_hold() FROM PUBLIC; +CREATE TRIGGER trg_world_player_admission_hold_retained + BEFORE INSERT OR UPDATE OR DELETE ON world_canonical_player_admission_hold + FOR EACH ROW EXECUTE FUNCTION world_validate_player_admission_hold(); + +CREATE FUNCTION world_reject_player_admission_hold_truncate() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +BEGIN + RAISE EXCEPTION 'World player-admission holds and original evidence are retained' USING ERRCODE='55000'; +END; +$$; +REVOKE ALL ON FUNCTION world_reject_player_admission_hold_truncate() FROM PUBLIC; +CREATE TRIGGER trg_world_player_admission_hold_no_truncate + BEFORE TRUNCATE ON world_canonical_player_admission_hold + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_player_admission_hold_truncate(); + +-- Preserve V35 and all subsequent exact execution-manifest extensions. The one exception is an +-- exact same-value World row UPDATE in the transaction that inserted this bound ACTIVE hold. +DO $migration$ +DECLARE + original TEXT; + anchor TEXT := $anchor$ RAISE EXCEPTION + 'World tenant key is reserved for a canonical authored source; no exact transaction execution manifest'$anchor$; +BEGIN + SELECT pg_get_functiondef('"${serviceSchema}".world_claim_legacy_numeric_tenant_key()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,anchor,'')))/length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one reserved-tenant execution denial guard'; + END IF; + original := replace(original,anchor,$replacement$ IF TG_TABLE_SCHEMA = '${serviceSchema}' AND TG_TABLE_NAME = 'world_instance' + AND TG_OP = 'UPDATE' AND old_row = new_row + AND old_row->>'status' = 'ACTIVE' + AND EXISTS (SELECT 1 FROM "${serviceSchema}".world_canonical_player_admission_hold h + WHERE h.world_instance_id = (old_row->>'id')::BIGINT + AND h.canonical_game_instance_id::TEXT = old_row->>'canonical_game_instance_id' + AND h.active_lifecycle_epoch = (old_row->>'lifecycle_epoch')::BIGINT + AND h.active_row_version = (old_row->>'row_version')::BIGINT + AND h.hold_state = 'HELD' AND h.acquisition_transaction_id = txid_current()) THEN + RETURN NEW; + END IF; +$replacement$ || anchor); + EXECUTE original; +END; +$migration$; + +CREATE FUNCTION world_version_player_admission_lifecycle_tuple() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +BEGIN + -- FOR UPDATE alone cannot refresh an older REPEATABLE READ/SERIALIZABLE snapshot. This exact + -- no-op UPDATE makes its later lifecycle UPDATE fail serialization rather than miss the hold. + UPDATE "${serviceSchema}".world_instance SET row_version = row_version + WHERE id = NEW.world_instance_id AND canonical_game_instance_id = NEW.canonical_game_instance_id + AND status = 'ACTIVE' AND lifecycle_epoch = NEW.active_lifecycle_epoch + AND row_version = NEW.active_row_version; + IF NOT FOUND THEN + RAISE EXCEPTION 'World player-admission hold lost its exact ACTIVE tuple' USING ERRCODE='23514'; + END IF; + RETURN NULL; +END; +$$; +REVOKE ALL ON FUNCTION world_version_player_admission_lifecycle_tuple() FROM PUBLIC; +CREATE TRIGGER trg_world_player_admission_hold_tuple_version + AFTER INSERT ON world_canonical_player_admission_hold + FOR EACH ROW EXECUTE FUNCTION world_version_player_admission_lifecycle_tuple(); + +CREATE FUNCTION world_guard_player_admission_lifecycle() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +BEGIN + -- UPDATE/DELETE owns the same tuple lock used by hold creation. For old MVCC snapshots the + -- hold's tuple UPDATE supplies PostgreSQL's serialization error before a stale change commits. + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_canonical_player_admission_hold h + WHERE h.world_instance_id = OLD.id AND h.hold_state = 'HELD') THEN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'World lifecycle is fenced by a retained player-admission hold' USING ERRCODE='23514'; + END IF; + IF to_jsonb(OLD) IS DISTINCT FROM to_jsonb(NEW) THEN + RAISE EXCEPTION 'World lifecycle is fenced by a retained player-admission hold' USING ERRCODE='23514'; + END IF; + END IF; + IF TG_OP = 'DELETE' THEN RETURN OLD; END IF; + RETURN NEW; +END; +$$; +REVOKE ALL ON FUNCTION world_guard_player_admission_lifecycle() FROM PUBLIC; +CREATE TRIGGER aaa_world_player_admission_lifecycle + BEFORE UPDATE OR DELETE ON world_instance + FOR EACH ROW EXECUTE FUNCTION world_guard_player_admission_lifecycle(); +-- Existing V34's unconditional World instance TRUNCATE guard remains in force. +-- [jooq ignore stop] diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldPostgresIntegrationTest.java new file mode 100644 index 0000000000..bcf61adb4b --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldPostgresIntegrationTest.java @@ -0,0 +1,563 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Context; +import java.sql.SQLException; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.worldmanagement.WorldManagementServiceApplication; +import net.firedevops.firemud.worldmanagement.client.EntityManagementClient; +import net.firedevops.firemud.worldmanagement.client.GameDesignClient; +import net.firedevops.firemud.worldmanagement.client.GameSessionClient; +import net.firedevops.firemud.worldmanagement.client.GrpcGameSessionInitialAdmissionBindProofClient; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.AutowireCapableBeanFactory; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Actual PostgreSQL owner fixture definitions. Account peer context and original lease are + * synthetic; the reused graph/release/preparation/activation path stipulates upstream authority. + * There is no accepting release or canonical termination producer, no real Account finalization, + * Game Session binding installation, protected transport composition, or live admission proof. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + classes = WorldManagementServiceApplication.class, + properties = "spring.grpc.server.port=0") +class WorldCanonicalPlayerAdmissionHoldPostgresIntegrationTest { + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Container + static GenericContainer redis = + new GenericContainer<>("redis:7.2-alpine").withExposedPorts(6379); + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.registerPostgresService( + registry, postgres, "world_management_service"); + PostgresBackedServiceTestSupport.registerRedisService(registry, redis); + } + + @Autowired private DSLContext dsl; + @Autowired private PlatformTransactionManager manager; + @Autowired private AutowireCapableBeanFactory beanFactory; + @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + + @MockitoBean(enforceOverride = true) + private GrpcGameSessionInitialAdmissionBindProofClient bindProofClient; + + @MockitoBean private GameDesignClient gameDesignClient; + @MockitoBean private GameSessionClient gameSessionClient; + @MockitoBean private EntityManagementClient entityManagementClient; + + @Test + void exactRetryAndReadbackRetainOriginalOpaqueIdentityEvidenceAndAllLogicalState() + throws Exception { + var f = fixture(); + var lease = lease(f, 15000L); + String before = logicalRow(f); + String previousTuple = tupleVersion(f); + var service = service(f); + var hold = account().call(() -> acquire(service, f, lease)); + var retry = account().call(() -> acquire(service, f, lease)); + assertThat(retry.holdId()).isEqualTo(hold.holdId()); + assertThat(retry.holdFence()).isEqualTo(hold.holdFence()); + assertThat(retry.worldEvidence().canonicalBytes()) + .isEqualTo(hold.worldEvidence().canonicalBytes()); + assertThat(retry.request().lease().canonicalJson()).isEqualTo(lease.canonicalJson()); + assertThat( + account() + .call( + () -> + service.read( + lease.canonicalJson(), + lease.sha256(), + f.activeEvidence().lifecycleEpoch(), + f.activeEvidence().rowVersion()))) + .contains(hold); + assertThat(logicalRow(f)).isEqualTo(before); + assertThat(tupleVersion(f)).isNotEqualTo(previousTuple); + assertThat(count(f)).isEqualTo(1L); + } + + @Test + void diagnosticExpiryRetainsHoldAndExactRetryWithoutDeadlineRenewal() throws Exception { + var f = fixture(); + var lease = lease(f, 5000L); + var service = service(f); + var hold = account().call(() -> acquire(service, f, lease)); + long deadline = hold.diagnosticExpiresAtMillis(); + long remaining = deadline - System.currentTimeMillis(); + if (remaining >= 0) TimeUnit.MILLISECONDS.sleep(remaining + 1L); + var retry = account().call(() -> acquire(service, f, lease)); + assertThat(retry).isEqualTo(hold); + assertThat(retry.diagnosticExpiresAtMillis()).isEqualTo(deadline); + assertV51Denied( + () -> + dsl.execute( + "UPDATE world_instance SET status='TERMINATING'," + + "lifecycle_epoch=lifecycle_epoch+1,row_version=row_version+1 WHERE id=?", + f.association().worldInstanceId())); + assertThat(count(f)).isEqualTo(1L); + } + + @Test + void expiredLeaseAndSubstitutedScopeOrExpectedTupleDenyWithoutStateOrHoldChanges() + throws Exception { + var f = fixture(); + var service = service(f); + String before = logicalRow(f); + String tuple = tupleVersion(f); + var valid = lease(f, 15000L); + account() + .run( + () -> { + assertThatThrownBy( + () -> + service.acquire( + valid.canonicalJson(), + valid.sha256(), + f.activeEvidence().lifecycleEpoch() + 1L, + f.activeEvidence().rowVersion())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + service.acquire( + valid.canonicalJson(), + valid.sha256(), + f.activeEvidence().lifecycleEpoch(), + f.activeEvidence().rowVersion() + 1L)) + .isInstanceOf(IllegalArgumentException.class); + }); + var changedScope = new LinkedHashMap<>(scope(valid.carrier())); + changedScope.put("worldSlug", "substituted-world"); + var changed = changed(valid, "bindingScope", changedScope); + account() + .run( + () -> + assertThatThrownBy(() -> acquire(service, f, changed)) + .isInstanceOf(IllegalArgumentException.class)); + changedScope.put("gameInstanceId", UUID.randomUUID().toString()); + var unmapped = changed(valid, "bindingScope", changedScope); + account() + .run( + () -> + assertThatThrownBy(() -> acquire(service, f, unmapped)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("association is missing")); + var expiredCarrier = new LinkedHashMap<>(valid.carrier()); + // Keep token valid and evaluated time unchanged, but expire this original lease. + long now = System.currentTimeMillis(); + expiredCarrier.put("evaluatedAt", Long.toString(now - 1000L)); + expiredCarrier.put("expiresAt", Long.toString(now - 1L)); + var expired = AccountGameplayAdmissionLeaseEvidence.fromCarrier(expiredCarrier); + account() + .run( + () -> + assertThatThrownBy(() -> acquire(service, f, expired)) + .hasMessageContaining("original lease or exact owner evidence")); + assertThat(count(f)).isZero(); + assertThat(logicalRow(f)).isEqualTo(before); + assertThat(tupleVersion(f)).isEqualTo(tuple); + } + + @Test + void retainedAttemptRejectsChangedLeaseDigestIdentityAndEpoch() throws Exception { + var f = fixture(); + var original = lease(f, 15000L); + var service = service(f); + var hold = account().call(() -> acquire(service, f, original)); + String before = logicalRow(f); + for (var changed : + List.of( + changed(original, "leaseFence", "2"), + changed(original, "leaseId", UUID.randomUUID().toString()), + changed(original, "requestId", UUID.randomUUID().toString()))) { + account() + .run( + () -> + assertThatThrownBy(() -> acquire(service, f, changed)) + .hasMessageContaining("original lease/attempt binding")); + } + account() + .run( + () -> + assertThatThrownBy( + () -> + service.acquire( + original.canonicalJson(), + original.sha256(), + f.activeEvidence().lifecycleEpoch() + 1L, + f.activeEvidence().rowVersion())) + .hasMessageContaining("original lease/attempt binding")); + assertThat(account().call(() -> acquire(service, f, original))).isEqualTo(hold); + assertThat(count(f)).isEqualTo(1L); + assertThat(logicalRow(f)).isEqualTo(before); + } + + @Test + void v51ItselfFencesRawLifecycleCounterMutationAndDeleteWhileReleaseStaysUnavailable() + throws Exception { + var f = fixture(); + var service = service(f); + account().call(() -> acquire(service, f, lease(f, 15000L))); + String before = logicalRow(f); + for (String sql : + List.of( + "UPDATE world_instance SET status='TERMINATING',lifecycle_epoch=lifecycle_epoch+1,row_version=row_version+1 WHERE id=?", + "UPDATE world_instance SET lifecycle_epoch=lifecycle_epoch+1 WHERE id=?", + "UPDATE world_instance SET row_version=row_version+1 WHERE id=?", + "DELETE FROM world_instance WHERE id=?")) { + assertV51Denied(() -> dsl.execute(sql, f.association().worldInstanceId())); + } + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE world_canonical_player_admission_hold SET hold_state='RELEASED' WHERE world_instance_id=?", + f.association().worldInstanceId())) + .hasMessageContaining("dual-owner release is unavailable"); + assertThatThrownBy( + () -> + dsl.execute( + "DELETE FROM world_canonical_player_admission_hold WHERE world_instance_id=?", + f.association().worldInstanceId())) + .hasMessageContaining("dual-owner release is unavailable"); + assertThatThrownBy(() -> dsl.execute("TRUNCATE world_canonical_player_admission_hold")) + .hasMessageContaining("original evidence are retained"); + account() + .run( + () -> + assertThatThrownBy(service::release) + .hasMessageContaining("release is unavailable")); + assertThat(count(f)).isEqualTo(1L); + assertThat(logicalRow(f)).isEqualTo(before); + } + + @Test + void twoConcurrentExactAcquisitionsRetainOneIdentity() throws Exception { + var f = fixture(); + var original = lease(f, 15000L); + var service = service(f); + var ready = new CountDownLatch(2); + var start = new CountDownLatch(1); + var executor = Executors.newFixedThreadPool(2); + try { + java.util.concurrent.Callable operation = + () -> { + ready.countDown(); + await(start); + return account().call(() -> acquire(service, f, original)); + }; + var first = executor.submit(operation); + var second = executor.submit(operation); + await(ready); + start.countDown(); + assertThat(first.get(15, TimeUnit.SECONDS)).isEqualTo(second.get(15, TimeUnit.SECONDS)); + assertThat(count(f)).isEqualTo(1L); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + + @Test + void independentPlayerAttemptsPreserveEveryExistingHoldAndDoNotOpenGenericNoOpBypass() + throws Exception { + var f = fixture(); + var service = service(f); + var firstLease = lease(f, 15000L); + var first = account().call(() -> acquire(service, f, firstLease)); + String before = logicalRow(f); + var second = account().call(() -> acquire(service, f, lease(f, 15000L))); + assertThat(second.holdId()).isNotEqualTo(first.holdId()); + assertThat(second.holdFence()).isNotEqualTo(first.holdFence()); + assertThat(account().call(() -> acquire(service, f, firstLease))).isEqualTo(first); + assertThat(count(f)).isEqualTo(2L); + assertThat(logicalRow(f)).isEqualTo(before); + // V51's exact no-op exception is restricted to the actual insertion transaction. An ordinary + // later caller still reaches the pre-existing V35 canonical-write denial. + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE world_instance SET row_version=row_version WHERE id=?", + f.association().worldInstanceId())) + .hasMessageContaining("no exact transaction execution manifest"); + } + + @Test + void staleRepeatableReadSnapshotCannotMissCommittedHoldTupleVersion() throws Exception { + assertStaleSnapshotFails(TransactionDefinition.ISOLATION_REPEATABLE_READ); + } + + @Test + void staleSerializableSnapshotCannotMissCommittedHoldTupleVersion() throws Exception { + assertStaleSnapshotFails(TransactionDefinition.ISOLATION_SERIALIZABLE); + } + + private void assertStaleSnapshotFails(int isolation) throws Exception { + var f = fixture(); + String before = logicalRow(f); + var snapshotRead = new CountDownLatch(1); + var holdCommitted = new CountDownLatch(1); + var executor = Executors.newSingleThreadExecutor(); + try { + var stale = + executor.submit( + () -> { + try { + transaction(isolation) + .execute( + status -> { + assertThat(logicalRow(f)).isEqualTo(before); + assertThat(count(f)).isZero(); + snapshotRead.countDown(); + await(holdCommitted); + dsl.execute( + "UPDATE world_instance SET status='TERMINATING',lifecycle_epoch=lifecycle_epoch+1," + + "row_version=row_version+1 WHERE id=?", + f.association().worldInstanceId()); + return null; + }); + throw new AssertionError( + "Stale snapshot lifecycle change unexpectedly committed"); + } catch (RuntimeException failure) { + return sqlState(failure); + } finally { + snapshotRead.countDown(); + } + }); + await(snapshotRead); + account().call(() -> acquire(service(f), f, lease(f, 15000L))); + holdCommitted.countDown(); + assertThat(stale.get(15, TimeUnit.SECONDS)).isEqualTo("40001"); + assertThat(logicalRow(f)).isEqualTo(before); + assertThat(count(f)).isEqualTo(1L); + } finally { + holdCommitted.countDown(); + executor.shutdownNow(); + } + } + + private WorldDraftGraphApplicationPostgresIntegrationTest.ActivePlayerAdmissionFixture fixture() { + var owner = new WorldDraftGraphApplicationPostgresIntegrationTest(); + beanFactory.autowireBean(owner); + return owner.activePlayerAdmissionFixture(); + } + + private WorldCanonicalPlayerAdmissionHoldService service( + WorldDraftGraphApplicationPostgresIntegrationTest.ActivePlayerAdmissionFixture f) { + var associations = + new WorldCanonicalInstanceAssociationRepository( + dsl, + new WorldCompleteLaunchBindingRepository(dsl), + new WorldAuthoredSourceIntakeRepository(dsl), + new WorldAuthoredVersionIdentityRepository(dsl)); + return new WorldCanonicalPlayerAdmissionHoldService( + new WorldCanonicalPlayerAdmissionHoldRepository( + dsl, manager, "firemud", associations, f.lifecycleRepository()), + "firemud"); + } + + private static WorldCanonicalPlayerAdmissionHold acquire( + WorldCanonicalPlayerAdmissionHoldService service, + WorldDraftGraphApplicationPostgresIntegrationTest.ActivePlayerAdmissionFixture f, + AccountGameplayAdmissionLeaseEvidence lease) { + return service.acquire( + lease.canonicalJson(), + lease.sha256(), + f.activeEvidence().lifecycleEpoch(), + f.activeEvidence().rowVersion()); + } + + /** Synthetic complete original Account carrier, with no current source or terminal authority. */ + private static AccountGameplayAdmissionLeaseEvidence lease( + WorldDraftGraphApplicationPostgresIntegrationTest.ActivePlayerAdmissionFixture f, + long duration) { + var identity = f.activeEvidence().request(); + String account = UUID.randomUUID().toString(); + String tenant = identity.canonicalTenantId().toString(); + Map scope = new LinkedHashMap<>(); + scope.put("accountId", account); + scope.put("tenantId", tenant); + scope.put("realmId", UUID.randomUUID().toString()); + scope.put("worldSlug", identity.worldSlug()); + scope.put("realmSlug", "synthetic-realm"); + scope.put("playableStateNamespaceId", identity.playableStateNamespaceId().toString()); + scope.put("playableStateScope", identity.playableStateScope()); + scope.put("gameInstanceId", identity.canonicalGameInstanceId().toString()); + for (String key : List.of("characterId", "sessionId", "regionId")) + scope.put(key, UUID.randomUUID().toString()); + for (String key : + List.of("bindingGeneration", "catalogRevision", "pointerVersion", "regionEpoch")) + scope.put(key, "9007199254740993"); + Map value = new LinkedHashMap<>(); + value.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); + value.put("schemaVersion", "1"); + value.put("mode", "PUBLIC_PRODUCTION"); + value.put("targetNamespace", "firemud"); + value.put("callerWorkload", "spiffe://firemud/ns/firemud/sa/game-session-service"); + value.put("requestId", UUID.randomUUID().toString()); + value.put("leaseId", UUID.randomUUID().toString()); + value.put("leaseFence", "1"); + value.put("leaseKind", "NEW_BINDING"); + value.put("bindingScope", scope); + value.put( + "authorityTuple", + Map.of( + "issuerAuthGeneration", + "1", + "accountAuthorityGeneration", + "1", + "tenantAuthorityGeneration", + Map.of(tenant, "1"), + "membershipAuthorityGeneration", + Map.of(tenant, "1"), + "privateRealmGrantVersions", + List.of())); + value.put("issuanceFence", "1"); + value.put( + "membershipBaseline", + Map.of( + "membershipLifecycleState", + "ACTIVE", + "membershipVersion", + Map.of(tenant, "1"), + "membershipAuthorityGeneration", + "1")); + value.put( + "outboxCheckpoints", + List.of( + checkpoint("account/" + account, "0"), + checkpoint("issuer/firemud-account-service", "0"), + checkpoint("membership/" + account + "/" + tenant, "1"), + checkpoint("tenant/" + tenant, "1"))); + long now = System.currentTimeMillis(); + value.put( + "tokenIdentityEvidence", + Map.ofEntries( + Map.entry("accountId", account), + Map.entry("operationId", UUID.randomUUID().toString()), + Map.entry("issuanceRequestId", UUID.randomUUID().toString()), + Map.entry("tokenJti", UUID.randomUUID().toString()), + Map.entry("tokenSHA256", "a".repeat(64)), + Map.entry("tokenGeneration", "1"), + Map.entry("issuanceFence", "1"), + Map.entry("tokenIdentityFence", "1"), + Map.entry("tokenProfile", "game-session-account-delegation"), + Map.entry("issuedAt", Long.toString(now / 1000 - 2)), + Map.entry("notBefore", Long.toString(now / 1000 - 2)), + Map.entry("expiresAt", Long.toString(now / 1000 + 300)))); + value.put("evaluatedAt", Long.toString(now)); + value.put("expiresAt", Long.toString(now + duration)); + return AccountGameplayAdmissionLeaseEvidence.fromCarrier(value); + } + + private static AccountGameplayAdmissionLeaseEvidence changed( + AccountGameplayAdmissionLeaseEvidence original, String field, Object value) { + var carrier = new LinkedHashMap<>(original.carrier()); + carrier.put(field, value); + return AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier); + } + + @SuppressWarnings("unchecked") + private static Map scope(Map carrier) { + return (Map) carrier.get("bindingScope"); + } + + private static Map checkpoint(String suffix, String sequence) { + return Map.of( + "outboxStreamKey", "account:auth-authority:v1:" + suffix, "outboxSequence", sequence); + } + + private long count( + WorldDraftGraphApplicationPostgresIntegrationTest.ActivePlayerAdmissionFixture f) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_canonical_player_admission_hold WHERE world_instance_id=?", + f.association().worldInstanceId())) + .get(0, Long.class); + } + + private String logicalRow( + WorldDraftGraphApplicationPostgresIntegrationTest.ActivePlayerAdmissionFixture f) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT to_jsonb(w)::text FROM world_instance w WHERE id=?", + f.association().worldInstanceId())) + .get(0, String.class); + } + + private String tupleVersion( + WorldDraftGraphApplicationPostgresIntegrationTest.ActivePlayerAdmissionFixture f) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT xmin::text FROM world_instance WHERE id=?", + f.association().worldInstanceId())) + .get(0, String.class); + } + + private TransactionTemplate transaction(int isolation) { + var transaction = new TransactionTemplate(manager); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(isolation); + return transaction; + } + + private static Context account() { + return Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/firemud/sa/account-service") + .orElseThrow()); + } + + private static void assertV51Denied( + org.assertj.core.api.ThrowableAssert.ThrowingCallable operation) { + assertThatThrownBy(operation) + .hasMessageContaining("fenced by a retained player-admission hold") + .satisfies(failure -> assertThat(sqlState(failure)).isEqualTo("23514")); + } + + private static String sqlState(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException sql) return sql.getSQLState(); + } + throw new AssertionError("Expected real PostgreSQL SQLSTATE", failure); + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) + throw new AssertionError("Owner fixture coordination timed out"); + } catch (InterruptedException failure) { + Thread.currentThread().interrupt(); + throw new AssertionError("Owner fixture interrupted", failure); + } + } +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java index 45e106bfaf..c3e25942fe 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java @@ -4201,6 +4201,29 @@ private AuthoredDraftPublishSelectionBinding publicationSelection( OffsetDateTime.parse("2026-01-01T00:00:00Z"))); } + /** Reuses genuine graph/release/materialization/activation; upstream authority is stipulated. */ + ActivePlayerAdmissionFixture activePlayerAdmissionFixture() { + var prepared = materializedLifecycleFixture(); + var activation = + canonicalActivationService(prepared, ignored -> stipulatedActivationAuthority()) + .activate( + new WorldCanonicalInstanceActivation.Request( + UUID.randomUUID(), prepared.preparing())); + assertThat(activation.outcome()).isEqualTo(WorldCanonicalInstanceActivation.Outcome.COMMITTED); + var current = + prepared + .lifecycleRepository() + .read(lifecycleRequestWithFreshReadId(activation.lifecycleEvidence().request())) + .orElseThrow(); + return new ActivePlayerAdmissionFixture( + prepared.materialized().association(), current, prepared.lifecycleRepository()); + } + + record ActivePlayerAdmissionFixture( + WorldCanonicalInstanceAssociation association, + WorldCanonicalInstanceLifecycleEvidence activeEvidence, + WorldCanonicalInstanceLifecycleReadRepository lifecycleRepository) {} + private PreparedLifecycleFixture materializedLifecycleFixture() { Fixture f = fixture(); var original = application(generationFreePlan(f)); diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldRepositoryTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldRepositoryTest.java new file mode 100644 index 0000000000..63dcae86b7 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldRepositoryTest.java @@ -0,0 +1,110 @@ +package unit.net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import io.grpc.Context; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceAssociationRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceLifecycleReadRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalPlayerAdmissionHold; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalPlayerAdmissionHoldRepository; +import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class WorldCanonicalPlayerAdmissionHoldRepositoryTest { + private final DSLContext dsl = mock(DSLContext.class); + private final PlatformTransactionManager manager = mock(PlatformTransactionManager.class); + private final WorldCanonicalInstanceAssociationRepository associations = + mock(WorldCanonicalInstanceAssociationRepository.class); + private final WorldCanonicalInstanceLifecycleReadRepository lifecycle = + mock(WorldCanonicalInstanceLifecycleReadRepository.class); + private final WorldCanonicalPlayerAdmissionHoldRepository repository = + new WorldCanonicalPlayerAdmissionHoldRepository( + dsl, manager, "firemud", associations, lifecycle); + + @AfterEach + void clearAmbientTransaction() { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + @Test + void directRepositoryAccessStillRequiresTheAuthenticatedAccountPeer() { + assertThatThrownBy(() -> repository.acquire(request())).isInstanceOf(SecurityException.class); + assertThatThrownBy(() -> repository.read(request())).isInstanceOf(SecurityException.class); + verifyNoInteractions(dsl, manager, associations, lifecycle); + } + + @Test + void accountWorkloadWithAuthenticatedEndUserContextCannotReachOwnerTransactionOrSql() { + SessionContext.setContext( + WorldCanonicalPlayerAdmissionHoldTest.ACCOUNT, java.util.List.of(), java.util.Map.of()); + try { + account() + .run( + () -> { + assertThatThrownBy(() -> repository.acquire(request())) + .isInstanceOf(SecurityException.class); + assertThatThrownBy(() -> repository.read(request())) + .isInstanceOf(SecurityException.class); + }); + verifyNoInteractions(dsl, manager, associations, lifecycle); + } finally { + SessionContext.clear(); + } + } + + @Test + void authenticatedCallerCannotJoinAnAmbientTransactionForAcquireOrRead() { + TransactionSynchronizationManager.setActualTransactionActive(true); + account() + .run( + () -> { + assertThatThrownBy(() -> repository.acquire(request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient"); + assertThatThrownBy(() -> repository.read(request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient"); + }); + verifyNoInteractions(dsl, manager, associations, lifecycle); + } + + @Test + void substitutedNamespaceDeniesBeforeOpeningSqlTransaction() { + var carrier = WorldCanonicalPlayerAdmissionHoldTest.carrier(); + carrier.put("targetNamespace", "other"); + carrier.put("callerWorkload", "spiffe://firemud/ns/other/sa/game-session-service"); + var changed = + new WorldCanonicalPlayerAdmissionHold.Request( + net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence + .fromCarrier(carrier), + 7L, + 8L); + account() + .run( + () -> + assertThatThrownBy(() -> repository.acquire(changed)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("namespace")); + verifyNoInteractions(dsl, manager, associations, lifecycle); + } + + private static WorldCanonicalPlayerAdmissionHold.Request request() { + return new WorldCanonicalPlayerAdmissionHold.Request( + WorldCanonicalPlayerAdmissionHoldTest.lease(), 7L, 8L); + } + + private static Context account() { + return Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/firemud/sa/account-service") + .orElseThrow()); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldServiceTest.java new file mode 100644 index 0000000000..8255f3f702 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldServiceTest.java @@ -0,0 +1,122 @@ +package unit.net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalPlayerAdmissionHold; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalPlayerAdmissionHoldRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalPlayerAdmissionHoldService; +import org.junit.jupiter.api.Test; + +class WorldCanonicalPlayerAdmissionHoldServiceTest { + private final WorldCanonicalPlayerAdmissionHoldRepository repository = + mock(WorldCanonicalPlayerAdmissionHoldRepository.class); + private final WorldCanonicalPlayerAdmissionHoldService service = + new WorldCanonicalPlayerAdmissionHoldService(repository, "firemud"); + + @Test + void unauthenticatedOrWrongPeerDeniesBeforeDecodeOrOwnerAccess() { + assertThatThrownBy(() -> service.acquire(null, null, 0, 0)) + .isInstanceOf(SecurityException.class); + for (String uri : + java.util.List.of( + "spiffe://firemud/ns/firemud/sa/game-session-service", + "spiffe://firemud/ns/other/sa/account-service")) { + peer(uri) + .run( + () -> + assertThatThrownBy(() -> service.read(null, null, 0, 0)) + .isInstanceOf(SecurityException.class)); + } + verifyNoInteractions(repository); + } + + @Test + void accountWorkloadWithAuthenticatedEndUserContextDeniesBeforeDecodeOrOwnerAccess() { + SessionContext.setContext( + WorldCanonicalPlayerAdmissionHoldTest.ACCOUNT, java.util.List.of(), java.util.Map.of()); + try { + account() + .run( + () -> { + assertThatThrownBy(() -> service.acquire(null, null, 0, 0)) + .isInstanceOf(SecurityException.class); + assertThatThrownBy(() -> service.read(null, null, 0, 0)) + .isInstanceOf(SecurityException.class); + assertThatThrownBy(service::release).isInstanceOf(SecurityException.class); + }); + verifyNoInteractions(repository); + } finally { + SessionContext.clear(); + } + } + + @Test + void exactAccountProducerPassesOriginalLeaseWithoutChangingIdentity() { + var lease = WorldCanonicalPlayerAdmissionHoldTest.lease(); + var request = new WorldCanonicalPlayerAdmissionHold.Request(lease, 7L, 8L); + var retained = + new WorldCanonicalPlayerAdmissionHold( + UUID.randomUUID(), + UUID.randomUUID(), + request, + WorldCanonicalPlayerAdmissionHoldTest.evidence()); + when(repository.acquire(request)).thenReturn(retained); + when(repository.read(request)).thenReturn(Optional.of(retained)); + account() + .run( + () -> { + assertThat(service.acquire(lease.canonicalJson(), lease.sha256(), 7L, 8L)) + .isSameAs(retained); + assertThat(service.read(lease.canonicalJson(), lease.sha256(), 7L, 8L)) + .contains(retained); + }); + verify(repository).acquire(request); + verify(repository).read(request); + } + + @Test + void changedDigestOrNonCanonicalBytesDenyWithoutSql() { + var lease = WorldCanonicalPlayerAdmissionHoldTest.lease(); + account() + .run( + () -> { + assertThatThrownBy( + () -> service.acquire(lease.canonicalJson(), "b".repeat(64), 7L, 8L)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> service.acquire(" " + lease.canonicalJson(), lease.sha256(), 7L, 8L)) + .isInstanceOf(IllegalArgumentException.class); + }); + verifyNoInteractions(repository); + } + + @Test + void releaseHasNoAcceptingPathEvenForAuthenticatedAccount() { + account() + .run( + () -> + assertThatThrownBy(service::release) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Account terminal AND Game Session")); + verifyNoInteractions(repository); + } + + private static Context account() { + return peer("spiffe://firemud/ns/firemud/sa/account-service"); + } + + private static Context peer(String uri) { + return Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(uri).orElseThrow()); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldTest.java new file mode 100644 index 0000000000..c8064eedec --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldTest.java @@ -0,0 +1,219 @@ +package unit.net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalPlayerAdmissionHold; +import org.junit.jupiter.api.Test; + +class WorldCanonicalPlayerAdmissionHoldTest { + static final String ID = "11111111-1111-4111-8111-111111111111"; + static final String ACCOUNT = "22222222-2222-4222-8222-222222222222"; + + @Test + void originalLeaseDefinesRetryIdentityWithoutRemintingOrRenewal() { + var lease = lease(); + var original = new WorldCanonicalPlayerAdmissionHold.Request(lease, 7L, 8L); + var exact = + new WorldCanonicalPlayerAdmissionHold.Request( + AccountGameplayAdmissionLeaseEvidence.parseCanonical(lease.canonicalJson()), 7L, 8L); + assertThat(original.sameBinding(exact)).isTrue(); + assertThat(original.sameBinding(new WorldCanonicalPlayerAdmissionHold.Request(lease, 8L, 8L))) + .isFalse(); + var changed = carrier(); + changed.put("leaseFence", "2"); + assertThat( + original.sameBinding( + new WorldCanonicalPlayerAdmissionHold.Request( + AccountGameplayAdmissionLeaseEvidence.fromCarrier(changed), 7L, 8L))) + .isFalse(); + } + + @Test + void donorDelegationBoundsRemainExactWithoutWideningTheOriginalCarrier() { + var carrier = carrier(); + var tuple = new LinkedHashMap<>((Map) carrier.get("authorityTuple")); + tuple.put("issuerAuthGeneration", "9007199254740993"); + carrier.put("authorityTuple", tuple); + var exact = AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier); + assertThat(exact.canonicalJson()).contains("9007199254740993"); + tuple.put("issuerAuthGeneration", "9223372036854775808"); + assertThatThrownBy(() -> AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void worldLifecycleEpochRemainsSeparateFromLeaseRegionEpoch() { + var request = new WorldCanonicalPlayerAdmissionHold.Request(lease(), 7L, 8L); + var evidence = evidence(); + var hold = + new WorldCanonicalPlayerAdmissionHold( + UUID.randomUUID(), UUID.randomUUID(), request, evidence); + assertThat(hold.worldEvidence().lifecycleEpoch()).isEqualTo(7L); + assertThat(hold.diagnosticExpiresAtMillis()) + .isEqualTo(Long.parseLong((String) request.lease().carrier().get("expiresAt"))); + when(evidence.lifecycleEpoch()).thenReturn(9L); + assertThatThrownBy(() -> request.requireExactActiveWorld(evidence)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact expected ACTIVE"); + } + + @Test + void inactiveMembershipAndIsolatedScopeAreNotRepairable() { + var changed = carrier(); + changed.put( + "membershipBaseline", + Map.of( + "membershipLifecycleState", + "INACTIVE", + "membershipVersion", + Map.of(ID, "1"), + "membershipAuthorityGeneration", + "1")); + var inactiveLease = AccountGameplayAdmissionLeaseEvidence.fromCarrier(changed); + assertThatThrownBy(() -> new WorldCanonicalPlayerAdmissionHold.Request(inactiveLease, 7L, 8L)) + .isInstanceOf(IllegalArgumentException.class); + changed = carrier(); + var scope = new LinkedHashMap<>(scope(changed)); + scope.put("playableStateScope", "ISOLATED"); + changed.put("bindingScope", scope); + var isolated = AccountGameplayAdmissionLeaseEvidence.fromCarrier(changed); + assertThatThrownBy(() -> new WorldCanonicalPlayerAdmissionHold.Request(isolated, 7L, 8L)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void substitutedWorldTenantOrNonActiveTupleIsDenied() { + var request = new WorldCanonicalPlayerAdmissionHold.Request(lease(), 7L, 8L); + var evidence = evidence(); + when(evidence.request().canonicalTenantId()).thenReturn(UUID.fromString(ACCOUNT)); + var substituted = evidence; + assertThatThrownBy(() -> request.requireExactActiveWorld(substituted)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical World scope"); + evidence = evidence(); + when(evidence.lifecycleStatus()).thenReturn("TERMINATING"); + var inactive = evidence; + assertThatThrownBy(() -> request.requireExactActiveWorld(inactive)) + .isInstanceOf(IllegalArgumentException.class); + } + + static WorldCanonicalInstanceLifecycleEvidence evidence() { + var selector = mock(WorldCanonicalInstanceLifecycleEvidence.Request.class); + when(selector.targetNamespace()).thenReturn("firemud"); + when(selector.canonicalTenantId()).thenReturn(UUID.fromString(ID)); + when(selector.worldSlug()).thenReturn("world"); + when(selector.canonicalGameInstanceId()).thenReturn(UUID.fromString(ID)); + when(selector.playableStateNamespaceId()).thenReturn(UUID.fromString(ID)); + when(selector.playableStateScope()).thenReturn("SHARED"); + when(selector.publicProduction()).thenReturn(true); + var evidence = mock(WorldCanonicalInstanceLifecycleEvidence.class); + when(evidence.request()).thenReturn(selector); + when(evidence.lifecycleStatus()).thenReturn("ACTIVE"); + when(evidence.lifecycleEpoch()).thenReturn(7L); + when(evidence.rowVersion()).thenReturn(8L); + return evidence; + } + + static AccountGameplayAdmissionLeaseEvidence lease() { + return AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier()); + } + + /** Synthetic lease shape only: no Account authentication, sources, or terminal proof. */ + static Map carrier() { + Map value = new LinkedHashMap<>(); + value.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); + value.put("schemaVersion", "1"); + value.put("mode", "PUBLIC_PRODUCTION"); + value.put("targetNamespace", "firemud"); + value.put("callerWorkload", "spiffe://firemud/ns/firemud/sa/game-session-service"); + value.put("requestId", ID); + value.put("leaseId", ACCOUNT); + value.put("leaseFence", "1"); + value.put("leaseKind", "NEW_BINDING"); + Map scope = new LinkedHashMap<>(); + for (String key : + List.of( + "tenantId", + "realmId", + "playableStateNamespaceId", + "gameInstanceId", + "characterId", + "sessionId", + "regionId")) scope.put(key, ID); + scope.put("accountId", ACCOUNT); + scope.put("worldSlug", "world"); + scope.put("realmSlug", "realm"); + scope.put("playableStateScope", "SHARED"); + for (String key : + List.of("bindingGeneration", "catalogRevision", "pointerVersion", "regionEpoch")) + scope.put(key, "9007199254740993"); + value.put("bindingScope", scope); + value.put( + "authorityTuple", + Map.of( + "issuerAuthGeneration", + "1", + "accountAuthorityGeneration", + "1", + "tenantAuthorityGeneration", + Map.of(ID, "1"), + "membershipAuthorityGeneration", + Map.of(ID, "1"), + "privateRealmGrantVersions", + List.of())); + value.put("issuanceFence", "1"); + value.put( + "membershipBaseline", + Map.of( + "membershipLifecycleState", + "ACTIVE", + "membershipVersion", + Map.of(ID, "1"), + "membershipAuthorityGeneration", + "1")); + value.put( + "outboxCheckpoints", + List.of( + checkpoint("account/" + ACCOUNT, "0"), + checkpoint("issuer/firemud-account-service", "0"), + checkpoint("membership/" + ACCOUNT + "/" + ID, "1"), checkpoint("tenant/" + ID, "1"))); + long now = System.currentTimeMillis(); + value.put( + "tokenIdentityEvidence", + Map.ofEntries( + Map.entry("accountId", ACCOUNT), + Map.entry("operationId", ID), + Map.entry("issuanceRequestId", ID), + Map.entry("tokenJti", ID), + Map.entry("tokenSHA256", "a".repeat(64)), + Map.entry("tokenGeneration", "1"), + Map.entry("issuanceFence", "1"), + Map.entry("tokenIdentityFence", "1"), + Map.entry("tokenProfile", "game-session-account-delegation"), + Map.entry("issuedAt", Long.toString(now / 1000)), + Map.entry("notBefore", Long.toString(now / 1000)), + Map.entry("expiresAt", Long.toString(now / 1000 + 300)))); + value.put("evaluatedAt", Long.toString(now)); + value.put("expiresAt", Long.toString(now + 15000)); + return value; + } + + @SuppressWarnings("unchecked") + static Map scope(Map carrier) { + return (Map) carrier.get("bindingScope"); + } + + private static Map checkpoint(String suffix, String sequence) { + return Map.of( + "outboxStreamKey", "account:auth-authority:v1:" + suffix, "outboxSequence", sequence); + } +} From 673aaaf6eff34c3263964db9581bb8924982d398 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 8 Oct 2026 12:34:20 +1300 Subject: [PATCH 2/8] Expose protected World player hold evidence and require named PostgreSQL proof --- .github/workflows/ci.yml | 26 + .../world-management-service/api-contracts.md | 4 +- .../world-runtime-and-movement.md | 2 + ...orld_canonical_player_admission_hold.proto | 45 + ...dCanonicalPlayerAdmissionHoldEvidence.java | 312 +++++++ ...onicalPlayerAdmissionHoldEvidenceTest.java | 804 ++++++++++++++++++ .../WorldCanonicalPlayerAdmissionHold.java | 114 --- ...nonicalPlayerAdmissionHoldGrpcService.java | 210 +++++ ...anonicalPlayerAdmissionHoldRepository.java | 21 +- ...ldCanonicalPlayerAdmissionHoldService.java | 10 +- ...rAdmissionHoldPostgresIntegrationTest.java | 5 +- ...calPlayerAdmissionHoldGrpcServiceTest.java | 308 +++++++ ...icalPlayerAdmissionHoldRepositoryTest.java | 8 +- ...nonicalPlayerAdmissionHoldServiceTest.java | 6 +- ...WorldCanonicalPlayerAdmissionHoldTest.java | 24 +- 15 files changed, 1751 insertions(+), 148 deletions(-) create mode 100644 protos/world-management/v1/world_canonical_player_admission_hold.proto create mode 100644 services/common-security/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalPlayerAdmissionHoldEvidence.java create mode 100644 services/common-security/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalPlayerAdmissionHoldEvidenceTest.java delete mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHold.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldGrpcService.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldGrpcServiceTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1a0494350f..f2944bc81a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2159,6 +2159,32 @@ jobs: fi echo "::endgroup::" + - name: Verify World player-admission hold PostgreSQL proof + if: ${{ !cancelled() && matrix.module == 'world-management-service' }} + run: | + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalPlayerAdmissionHoldPostgresIntegrationTest \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalPlayerAdmissionHoldPostgresIntegrationTest#exactRetryAndReadbackRetainOriginalOpaqueIdentityEvidenceAndAllLogicalState()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalPlayerAdmissionHoldPostgresIntegrationTest#diagnosticExpiryRetainsHoldAndExactRetryWithoutDeadlineRenewal()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalPlayerAdmissionHoldPostgresIntegrationTest#expiredLeaseAndSubstitutedScopeOrExpectedTupleDenyWithoutStateOrHoldChanges()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalPlayerAdmissionHoldPostgresIntegrationTest#retainedAttemptRejectsChangedLeaseDigestIdentityAndEpoch()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalPlayerAdmissionHoldPostgresIntegrationTest#v51ItselfFencesRawLifecycleCounterMutationAndDeleteWhileReleaseStaysUnavailable()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalPlayerAdmissionHoldPostgresIntegrationTest#twoConcurrentExactAcquisitionsRetainOneIdentity()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalPlayerAdmissionHoldPostgresIntegrationTest#independentPlayerAttemptsPreserveEveryExistingHoldAndDoNotOpenGenericNoOpBypass()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalPlayerAdmissionHoldPostgresIntegrationTest#staleRepeatableReadSnapshotCannotMissCommittedHoldTupleVersion()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalPlayerAdmissionHoldPostgresIntegrationTest#staleSerializableSnapshotCannotMissCommittedHoldTupleVersion()' \ + world-management-service + + - name: Capture World player-admission hold PostgreSQL raw XML + if: ${{ always() && matrix.module == 'world-management-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: world-player-admission-hold-postgresql-proof-${{ github.sha }}-${{ github.run_id }}-${{ github.run_attempt }} + path: services/world-management-service/build/test-results/integrationTest/TEST-*WorldCanonicalPlayerAdmissionHoldPostgresIntegrationTest.xml + if-no-files-found: error + retention-days: 7 + - name: Verify Game Design synchronized visibility PostgreSQL proof if: ${{ always() && matrix.module == 'game-design-service' }} run: | diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 0fc01a4c69..d16a60e95e 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -340,10 +340,12 @@ The distinct `WorldCanonicalInstanceActivationService.ActivateCanonicalWorldInst ## Player Admission Serving Hold -The Account lease and provisional/final binding sequence remains owned by [Session Behavior](../../system-architecture-session-behavior.md#session-types-and-lifetimes). World supplies a distinct player-admission serving hold over its actual current `ACTIVE` target; neither an initial-pointer hold nor an immutable historical activation result supplies this protection. Acquisition and readback authenticate the exact same-namespace Account workload without end-user context before parsing or owner access. Acquisition binds the original Account lease ID, request/attempt identity, unchanged full lease bytes and digest, complete canonical target scope, and expected World `ACTIVE` lifecycle epoch and Version. World resolves its private row through its persisted canonical association rather than caller-supplied numeric keys. +The Account lease and provisional/final binding sequence remains owned by [Session Behavior](../../system-architecture-session-behavior.md#session-types-and-lifetimes). World supplies a distinct player-admission serving hold over its actual current `ACTIVE` target; neither an initial-pointer hold nor an immutable historical activation result supplies this protection. Acquisition and readback authenticate the exact same-namespace Account workload without end-user context before parsing or owner access. Acquisition binds the original Account lease ID, request/attempt identity, unchanged full lease bytes and digest, complete canonical target scope, and expected World `ACTIVE` lifecycle epoch and row version. World resolves its private row through its persisted canonical association rather than caller-supplied numeric keys. World verifies and locks that actual lifecycle row in its own transaction before recording one immutable hold identity and fence. Identical retries return the original hold and acquisition evidence without extending the Account attempt's deadline; changed input conflicts. Concurrent and older-snapshot lifecycle mutations cannot pass through the acquisition fence, and every conflicting owner mutation remains blocked while the hold is unresolved. This must include database-level race and readback proof, not only an application preflight check. +The protected `AcquireCanonicalPlayerAdmissionHold` and `ReadCanonicalPlayerAdmissionHold` methods carry the original canonical Account lease bytes and SHA-256 digest plus the expected World lifecycle epoch and row version as canonical decimal strings. A separate request UUID correlates each transport response; it does not replace the retained lease/attempt identity or create a new hold. The closed `world-canonical-player-admission-hold-evidence/v1` readback contains string `schemaVersion = "1"`, opaque `holdId` and `holdFence`, the exact request object (`accountLeaseJson`, `accountLeaseSha256`, `expectedLifecycleEpoch`, `expectedRowVersion`), and canonical `worldLifecycleEvidenceBase64` retaining the complete original World lifecycle evidence. Its SHA-256 digest covers the canonical outer bytes and is carried separately. Receivers reject unknown or duplicate fields, malformed or noncanonical encoding, changed original bytes, substituted scope or digest, and mismatched request correlation. Missing readback is unresolved and never proves absence or permission to release. Codec validation does not authenticate an owner or establish current Account authorization. + The cross-owner order is Account acquire, Game Session provisional binding, Account finalize, then Game Session admissible installation. The Game Session decision is bound only once it exists. Account must independently revalidate its current sources and exact lease before its commit; World lifecycle protection does not prove Game Session pointer/catalog currentness, and those owners must fence their own conflicting mutations through Account commit. A storage `COMMITTED` value, earlier source capture, caller-supplied decision or this hold by itself never grants admission. World releases only after exact authenticated Account terminal evidence and the matching Game Session installation or cleanup evidence jointly prove the approved outcome. Missing, contradictory, unavailable or ambiguous evidence retains the hold. Expiry is diagnostic, not proof of abort or permission to release; initial-pointer outcomes cannot be reused. The currently prepared owner has no enabled release or admission transport. Implementation and executed proof limits belong in the [World tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#current-status). diff --git a/design/project-management/implementation-tracking/world-runtime-and-movement.md b/design/project-management/implementation-tracking/world-runtime-and-movement.md index d1e60da68d..62e6c9330d 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -8,6 +8,8 @@ This is a non-normative implementation tracker for world runtime and movement. C The distinct player-admission serving-hold candidate builds on the preserved #3044 source. It reuses the unchanged Account lease carrier and the actual canonical association/lifecycle reader; its unregistered Account-workload-only owner records immutable acquisition/readback and a V51 lifecycle tuple fence. The same-value tuple update changes PostgreSQL's physical row version without changing logical state, lifecycle epoch, owner row-version counter or history. Current definitions cover exact retry, substitution, retained diagnostic expiry, independent holds, V51-specific mutation denial and stale REPEATABLE_READ/SERIALIZABLE rejection. Consolidated local Common/World formatting, full checks, static analysis, jOOQ generation, integration-source compilation, World boot JAR and documentation validation pass: 161 Common and 525 World unit cases executed without failures/errors/skips, while all 206 World integration cases skipped without Docker. The definitions and reused ACTIVE fixture stipulate upstream authority; physical migration and race execution remain unproved. Release has no accepting path until exact authenticated Account terminal and Game Session installation/cleanup producers exist. Protected Account acquire/finalize, current source/physical-COMMIT proof and Game Session pointer/catalog/runtime fencing remain separate gates. No transport registration, canonical termination producer or live admission is enabled. The target owner is [Player Admission Serving Hold](../../architecture/microservices/world-management-service/api-contracts.md#player-admission-serving-hold). +The continuation moves the hold value into one closed Common Security carrier and adds an unregistered protected acquire/read adapter. It retains the original lease and complete World evidence, verifies exact workload identity before primitive parsing, and independently binds response correlation and original request scope. Five Common codec tests use real nested codecs over synthetic source fixtures; six adapter tests use explicitly mocked owner/lifecycle collaborators. The corrected full local gate passes after fixing two new SpotBugs issues without weakening guards: its reports contain 166 passing Common and 531 passing World unit cases, with all 206 integration cases skipped. The corrected gate reuses the unchanged Common test task and executes World tests; no duplicate fresh Common execution is claimed. Exact predecessor `fff09667c031b14aaa60002dd2c61f8ec99223ee` [World CI job](https://github.com/benhook1013/FireMUD/actions/runs/37700261172/job/113061857548) passed the full check and ran the integration task, but uploaded no JUnit report or strict result for the nine serving-hold methods. Their execution versus skips cannot be established from that run or JaCoCo coverage. The owning CI continuation therefore requires all nine cases through the existing strict JUnit verifier and captures their raw XML; its executed result is still pending. Authenticated Account consumption, actual owner composition, release and activation remain unproved. + Exact published #3044 `a36b152fdaf7f5bb5447094cd72718c66f7977de` [CI 37573659922](https://github.com/benhook1013/FireMUD/actions/runs/37573659922) executed all 196 World integration cases without skips, with three failures. The named PostgreSQL graph/application suite ran 51 cases with two failures; the operational-region suite ran three with one failure. The World checkout was synthetic merge `a9ada9077941141a1d3f8b315d1a0bb0cb1ae0f5`, with the exact #3041 base and published candidate as ordered parents and a head-identical tree. The `EXPECT_CLOSED` placement failure exposed V46's operation guard still accepting only `NO_PRIOR_POINTER` beneath V49's correctly typed location guard. Forward V50 preserves the earlier migrations and all other operation checks while permitting only the two explicit origins; new SQL negatives reject null and unknown origins. The actor/assignment reader correctly denied the changed full request before its later row check, so its fixture now expects that earlier stage and compares the unchanged journal and location rows. The operational-region trigger likewise correctly denied mutation, but its fixture expected jOOQ's exception instead of Spring's translated integrity exception; the corrected assertion retains all four tuple mutations. These corrections require fresh executed PostgreSQL proof and do not alter runtime activation gates. Game Session's unchanged retained-tenant suite and missing LOGIN capture, plus TCP's compiler heap exhaustion, remain separately owned aggregate failures. The #3044 continuation aligns canonical holds and placement with the complete shared Game Session terminal proof. V48 retains immutable proof bytes and their separate digest through an exact-row, one-use terminal manifest; V49 permits placement only against the matching typed commit and checked first-open pointer increment. Acquisition, lifecycle read and terminal transport composition require the explicit, default-disabled `firemud.world.canonical-first-admission.transport-enabled` gate. Terminalization additionally denies unless `owner-proof-client-enabled` explicitly composes the file-backed mTLS Game Session owner client; no caller-supplied proof or legacy numeric fallback substitutes for that read. Historical terminal readback is not fresh admission authority. The earlier consolidated local Common/World check, formatting, static analysis, jOOQ generation, boot JAR and documentation checks passed. World executed 511 unit methods with no failures or skips; 378 matching Common unit outcomes were reused. The physical transport cases include five actual Game Session owner-client methods and four protected World method-guard methods, with owner-store/result doubles. Its 196 World integration definitions compiled/discovered but skipped locally without Docker; the later executed runner result and corrections are recorded above. Component fixtures may stipulate upstream proof while executing the actual World owner transition, but they do not prove a Game Session pointer/audit commit or a playable flow. The runner executed V47–V49 and the passing owner cases, but corrected both-origin placement proof, genuine upstream owner evidence and complete activation/placement/region delivery remain open. diff --git a/protos/world-management/v1/world_canonical_player_admission_hold.proto b/protos/world-management/v1/world_canonical_player_admission_hold.proto new file mode 100644 index 0000000000..94b82b5b7b --- /dev/null +++ b/protos/world-management/v1/world_canonical_player_admission_hold.proto @@ -0,0 +1,45 @@ +syntax = "proto3"; + +package world_management.v1; + +option java_package = "net.firedevops.firemud.worldmanagement.v1"; +option java_multiple_files = true; + +// Distinct Account-to-World player-admission hold; neither binding admission nor hold release. +service WorldCanonicalPlayerAdmissionHoldService { + rpc AcquireCanonicalPlayerAdmissionHold(AcquireCanonicalPlayerAdmissionHoldRequest) + returns (AcquireCanonicalPlayerAdmissionHoldResponse); + rpc ReadCanonicalPlayerAdmissionHold(ReadCanonicalPlayerAdmissionHoldRequest) + returns (ReadCanonicalPlayerAdmissionHoldResponse); +} + +message AcquireCanonicalPlayerAdmissionHoldRequest { + // Fresh read correlation, echoed only; never the durable Account lease/attempt identity. + string request_id = 1; + bytes original_lease_json = 2; + string original_lease_sha256 = 3; + string expected_lifecycle_epoch = 4; + string expected_row_version = 5; +} + +message AcquireCanonicalPlayerAdmissionHoldResponse { + string request_id = 1; + string original_lease_sha256 = 2; + bytes hold_evidence_json = 3; + string hold_evidence_sha256 = 4; +} + +message ReadCanonicalPlayerAdmissionHoldRequest { + string request_id = 1; + bytes original_lease_json = 2; + string original_lease_sha256 = 3; + string expected_lifecycle_epoch = 4; + string expected_row_version = 5; +} + +message ReadCanonicalPlayerAdmissionHoldResponse { + string request_id = 1; + string original_lease_sha256 = 2; + bytes hold_evidence_json = 3; + string hold_evidence_sha256 = 4; +} diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalPlayerAdmissionHoldEvidence.java b/services/common-security/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalPlayerAdmissionHoldEvidence.java new file mode 100644 index 0000000000..ba635250e4 --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalPlayerAdmissionHoldEvidence.java @@ -0,0 +1,312 @@ +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.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.Base64; +import java.util.HexFormat; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.JsonParser; +import tools.jackson.core.JsonToken; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Distinct World-owned player-admission lifecycle hold. This is neither a first-pointer hold nor + * Account authorization, Game Session's binding decision, or gameplay admission permission. + * + *

The complete original lease and exact World owner evidence remain immutable. Its deadline is + * diagnostic only. Release requires independently authenticated exact Account terminal evidence AND + * Game Session installation/cleanup evidence; those producers do not exist in this slice. + */ +public record WorldCanonicalPlayerAdmissionHoldEvidence( + UUID holdId, + UUID holdFence, + Request request, + WorldCanonicalInstanceLifecycleEvidence worldEvidence) { + public static final String SCHEMA = "world-canonical-player-admission-hold-evidence/v1"; + public static final int MAX_EVIDENCE_BYTES = 1024 * 1024; + public static final int MAX_LIFECYCLE_BYTES = 512 * 1024; + private static final Set FIELDS = + Set.of( + "schema", + "schemaVersion", + "holdId", + "holdFence", + "request", + "worldLifecycleEvidenceBase64"); + private static final Set REQUEST_FIELDS = + Set.of( + "accountLeaseJson", "accountLeaseSha256", "expectedLifecycleEpoch", "expectedRowVersion"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + public WorldCanonicalPlayerAdmissionHoldEvidence { + requireOpaque(holdId); + requireOpaque(holdFence); + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(worldEvidence, "worldEvidence"); + request.requireExactActiveWorld(worldEvidence); + } + + /** Closed outer carrier; nested original Account and World bytes are preserved exactly. */ + public byte[] canonicalBytes() { + byte[] lifecycle = worldEvidence.canonicalBytes(); + requireBound(lifecycle, MAX_LIFECYCLE_BYTES); + Map value = + Map.of( + "schema", + SCHEMA, + "schemaVersion", + "1", + "holdId", + holdId.toString(), + "holdFence", + holdFence.toString(), + "request", + Map.of( + "accountLeaseJson", + request.lease().canonicalJson(), + "accountLeaseSha256", + request.lease().sha256(), + "expectedLifecycleEpoch", + Long.toString(request.expectedLifecycleEpoch()), + "expectedRowVersion", + Long.toString(request.expectedRowVersion())), + "worldLifecycleEvidenceBase64", + Base64.getEncoder().encodeToString(lifecycle)); + try { + byte[] result = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + requireBound(result, MAX_EVIDENCE_BYTES); + return result; + } catch (IOException failure) { + throw new IllegalStateException("Cannot encode canonical World player hold", failure); + } + } + + /** Separate digest of the complete canonical outer bytes; never a self-referential field. */ + public String sha256() { + return digest(canonicalBytes()); + } + + /** Shape and exact binding only: decoding does not authenticate World or authorize admission. */ + public static WorldCanonicalPlayerAdmissionHoldEvidence fromCanonical( + byte[] bytes, String sha256) { + requireBound(bytes, MAX_EVIDENCE_BYTES); + if (sha256 == null || !sha256.matches("[0-9a-f]{64}") || !digest(bytes).equals(sha256)) { + throw new IllegalArgumentException("World hold evidence SHA256 differs from original bytes"); + } + return parseCanonical(bytes); + } + + public static WorldCanonicalPlayerAdmissionHoldEvidence parseCanonical(byte[] bytes) { + requireBound(bytes, MAX_EVIDENCE_BYTES); + String json = strictUtf8(bytes); + try { + try (JsonParser parser = JSON.createParser(json)) { + int depth = 0; + JsonToken token; + while ((token = parser.nextToken()) != null) { + if ((token == JsonToken.START_OBJECT || token == JsonToken.START_ARRAY) && ++depth > 4) + throw new IllegalArgumentException("World hold evidence exceeds closed nesting bound"); + if (token == JsonToken.END_OBJECT || token == JsonToken.END_ARRAY) depth--; + } + } + JsonNode root = JSON.readTree(json); + exact(root, FIELDS); + if (!SCHEMA.equals(text(root, "schema")) || !"1".equals(text(root, "schemaVersion"))) { + throw new IllegalArgumentException("Unsupported World player hold evidence schema"); + } + JsonNode bound = root.get("request"); + exact(bound, REQUEST_FIELDS); + var lease = + AccountGameplayAdmissionLeaseEvidence.parseCanonical(text(bound, "accountLeaseJson")); + if (!lease.sha256().equals(text(bound, "accountLeaseSha256"))) { + throw new IllegalArgumentException( + "World hold request substituted its original Account lease digest"); + } + var request = + new Request( + lease, + decimal(text(bound, "expectedLifecycleEpoch"), true), + decimal(text(bound, "expectedRowVersion"), false)); + String encoded = text(root, "worldLifecycleEvidenceBase64"); + byte[] lifecycle = Base64.getDecoder().decode(encoded); + requireBound(lifecycle, MAX_LIFECYCLE_BYTES); + if (!Base64.getEncoder().encodeToString(lifecycle).equals(encoded)) { + throw new IllegalArgumentException("World lifecycle evidence base64 is not canonical"); + } + var result = + new WorldCanonicalPlayerAdmissionHoldEvidence( + UUID.fromString(text(root, "holdId")), + UUID.fromString(text(root, "holdFence")), + request, + WorldCanonicalInstanceLifecycleEvidence.fromStored(lifecycle)); + if (!Arrays.equals(bytes, result.canonicalBytes())) { + throw new IllegalArgumentException("World hold evidence bytes are not canonical"); + } + return result; + } catch (tools.jackson.core.JacksonException failure) { + throw new IllegalArgumentException("Malformed World player hold evidence", failure); + } + } + + private static String digest(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException failure) { + throw new IllegalStateException("SHA256 is unavailable", failure); + } + } + + 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 failure) { + throw new IllegalArgumentException("World hold evidence must be strict UTF-8", failure); + } + } + + private static void requireBound(byte[] bytes, int maximum) { + if (bytes == null || bytes.length == 0 || bytes.length > maximum) { + throw new IllegalArgumentException( + "World hold evidence exceeds its byte bound or is missing"); + } + } + + private static String text(JsonNode object, String field) { + JsonNode value = object.get(field); + if (value == null || !value.isTextual() || value.textValue().isEmpty()) { + throw new IllegalArgumentException("World hold evidence requires textual " + field); + } + return value.textValue(); + } + + private static void exact(JsonNode node, Set fields) { + if (node == null || !node.isObject()) { + throw new IllegalArgumentException("World hold evidence contains unknown or missing fields"); + } + Set actual = new java.util.HashSet<>(); + node.propertyNames().forEach(actual::add); + if (!actual.equals(fields)) + throw new IllegalArgumentException("World hold evidence contains unknown or missing fields"); + } + + public static long decimal(String value, boolean positive) { + if (value == null + || !value.matches(positive ? "[1-9][0-9]*" : "0|[1-9][0-9]*") + || value.length() > 19) { + throw new IllegalArgumentException("World hold counters require canonical decimal strings"); + } + try { + return Long.parseLong(value); + } catch (NumberFormatException failure) { + throw new IllegalArgumentException("World hold counter exceeds signed-long range", failure); + } + } + + /** Retained lease deadline triggers recovery diagnostics, never automatic release. */ + public long diagnosticExpiresAtMillis() { + return Long.parseLong((String) request.lease().carrier().get("expiresAt")); + } + + /** + * Complete original Account lease plus independently expected World lifecycle tuple. Account's + * regionEpoch is a separate domain and is never interpreted as this World lifecycle epoch. + */ + public record Request( + AccountGameplayAdmissionLeaseEvidence lease, + long expectedLifecycleEpoch, + long expectedRowVersion) { + public Request { + Objects.requireNonNull(lease, "lease"); + if (expectedLifecycleEpoch <= 0 || expectedRowVersion < 0) { + throw new IllegalArgumentException("Expected World lifecycle tuple is invalid"); + } + if (!(lease.carrier().get("bindingScope") instanceof Map scope) + || !"SHARED".equals(scope.get("playableStateScope")) + || !(lease.carrier().get("membershipBaseline") instanceof Map baseline) + || !"ACTIVE".equals(baseline.get("membershipLifecycleState"))) { + throw new IllegalArgumentException("Unsupported or non-admitting original lease scope"); + } + } + + public UUID leaseId() { + return UUID.fromString((String) lease.carrier().get("leaseId")); + } + + public UUID attemptId() { + return UUID.fromString((String) lease.carrier().get("requestId")); + } + + public UUID canonicalGameInstanceId() { + return UUID.fromString((String) scope().get("gameInstanceId")); + } + + public String targetNamespace() { + return (String) lease.carrier().get("targetNamespace"); + } + + public boolean sameBinding(Request other) { + return other != null + && lease.hasSameIdentity(other.lease) + && expectedLifecycleEpoch == other.expectedLifecycleEpoch + && expectedRowVersion == other.expectedRowVersion; + } + + public void requireExactActiveWorld(WorldCanonicalInstanceLifecycleEvidence evidence) { + Objects.requireNonNull(evidence, "evidence"); + requireExactWorldSelector(evidence.request()); + if (!"ACTIVE".equals(evidence.lifecycleStatus()) + || expectedLifecycleEpoch != evidence.lifecycleEpoch() + || expectedRowVersion != evidence.rowVersion()) { + throw new IllegalArgumentException("World target is not the exact expected ACTIVE tuple"); + } + } + + public void requireExactWorldSelector( + WorldCanonicalInstanceLifecycleEvidence.Request selector) { + if (!targetNamespace().equals(selector.targetNamespace()) + || !scope().get("tenantId").equals(selector.canonicalTenantId().toString()) + || !scope().get("worldSlug").equals(selector.worldSlug()) + || !scope().get("gameInstanceId").equals(selector.canonicalGameInstanceId().toString()) + || !scope() + .get("playableStateNamespaceId") + .equals(selector.playableStateNamespaceId().toString()) + || !scope().get("playableStateScope").equals(selector.playableStateScope()) + || !selector.publicProduction()) { + throw new IllegalArgumentException("Original lease differs from canonical World scope"); + } + } + + @SuppressWarnings("unchecked") + private Map scope() { + return (Map) lease.carrier().get("bindingScope"); + } + } + + private static void requireOpaque(UUID value) { + if (value == null || value.version() != 4 || value.variant() != 2) { + throw new IllegalArgumentException("Hold identity and fence must be opaque UUIDs"); + } + } +} diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalPlayerAdmissionHoldEvidenceTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalPlayerAdmissionHoldEvidenceTest.java new file mode 100644 index 0000000000..f3e1e396a2 --- /dev/null +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalPlayerAdmissionHoldEvidenceTest.java @@ -0,0 +1,804 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.OwnerReadback; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence.Request; +import org.junit.jupiter.api.Test; + +/** Real nested codecs over explicitly synthetic source/application/release and lease fixtures. */ +class WorldCanonicalPlayerAdmissionHoldEvidenceTest { + private static final String ID = "11111111-1111-4111-8111-111111111111"; + private static final String ACCOUNT = "22222222-2222-4222-8222-222222222222"; + + @Test + void closedCanonicalRoundtripPreservesEveryOriginalNestedByteAndDigest() throws Exception { + var original = hold(); + byte[] bytes = original.canonicalBytes(); + var decoded = WorldCanonicalPlayerAdmissionHoldEvidence.fromCanonical(bytes, original.sha256()); + assertThat(decoded).isEqualTo(original); + assertThat(decoded.canonicalBytes()).containsExactly(bytes); + assertThat(decoded.request().lease().canonicalJson()) + .isEqualTo(original.request().lease().canonicalJson()); + assertThat(decoded.request().lease().sha256()).isEqualTo(original.request().lease().sha256()); + assertThat(decoded.worldEvidence().canonicalBytes()) + .containsExactly(original.worldEvidence().canonicalBytes()); + assertThat(decoded.diagnosticExpiresAtMillis()).isEqualTo(original.diagnosticExpiresAtMillis()); + bytes[0] ^= 1; + assertThat(original.canonicalBytes()).isEqualTo(decoded.canonicalBytes()); + } + + @Test + void rejectsUnknownMissingDuplicateAndNoncanonicalOuterBytes() throws Exception { + var original = hold(); + var root = JSON.readTree(original.canonicalBytes()); + var unknown = root.deepCopy(); + ((tools.jackson.databind.node.ObjectNode) unknown).put("unknown", "value"); + assertRejected(canonical(unknown)); + var missing = root.deepCopy(); + ((tools.jackson.databind.node.ObjectNode) missing).remove("schemaVersion"); + assertRejected(canonical(missing)); + var nestedUnknown = root.deepCopy(); + ((tools.jackson.databind.node.ObjectNode) nestedUnknown.get("request")).put("unknown", "value"); + assertRejected(canonical(nestedUnknown)); + String text = new String(original.canonicalBytes(), StandardCharsets.UTF_8); + assertRejected( + text.replace("\"schemaVersion\":\"1\"", "\"schemaVersion\":\"1\",\"schemaVersion\":\"1\"") + .getBytes(StandardCharsets.UTF_8)); + assertRejected((" " + text).getBytes(StandardCharsets.UTF_8)); + assertRejected((text + "{}").getBytes(StandardCharsets.UTF_8)); + assertRejected( + text.replace("\"schemaVersion\":\"1\"", "\"schemaVersion\":1") + .getBytes(StandardCharsets.UTF_8)); + } + + @Test + void substitutedLeaseDigestOriginalScopeWorldEpochAndOpaqueIdentityFailClosed() throws Exception { + var original = hold(); + var root = JSON.readTree(original.canonicalBytes()); + var leaseDigest = root.deepCopy(); + ((tools.jackson.databind.node.ObjectNode) leaseDigest.get("request")) + .put("accountLeaseSha256", "b".repeat(64)); + assertRejected(canonical(leaseDigest)); + var changedCarrier = new LinkedHashMap<>(original.request().lease().carrier()); + var changedScope = new LinkedHashMap<>(scope(changedCarrier)); + changedScope.put("worldSlug", "another-world"); + changedCarrier.put("bindingScope", changedScope); + var changedLease = AccountGameplayAdmissionLeaseEvidence.fromCarrier(changedCarrier); + var changed = root.deepCopy(); + ((tools.jackson.databind.node.ObjectNode) changed.get("request")) + .put("accountLeaseJson", changedLease.canonicalJson()); + ((tools.jackson.databind.node.ObjectNode) changed.get("request")) + .put("accountLeaseSha256", changedLease.sha256()); + assertRejected(canonical(changed)); + var epoch = root.deepCopy(); + ((tools.jackson.databind.node.ObjectNode) epoch.get("request")) + .put("expectedLifecycleEpoch", "4"); + assertRejected(canonical(epoch)); + var uuid = root.deepCopy(); + ((tools.jackson.databind.node.ObjectNode) uuid) + .put("holdId", "00000000-0000-1000-8000-000000000001"); + assertRejected(canonical(uuid)); + assertThatThrownBy( + () -> + WorldCanonicalPlayerAdmissionHoldEvidence.fromCanonical( + original.canonicalBytes(), "c".repeat(64))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void exactDecimalStringsPreserveHighAndMaximumLongsAndRejectEveryOtherShape() throws Exception { + var original = hold(); + for (long value : List.of(9_007_199_254_740_993L, Long.MAX_VALUE)) { + var world = original.worldEvidence(); + var preciseWorld = + new WorldCanonicalInstanceLifecycleEvidence( + world.request(), + world.launchBinding(), + world.startLocation(), + world.runtimeRoomInstanceId(), + "ACTIVE", + value, + value, + world.captureId(), + world.graphSha256(), + world.preparationInputDigest()); + var precise = + new WorldCanonicalPlayerAdmissionHoldEvidence( + original.holdId(), + original.holdFence(), + new WorldCanonicalPlayerAdmissionHoldEvidence.Request( + original.request().lease(), value, value), + preciseWorld); + assertThat(WorldCanonicalPlayerAdmissionHoldEvidence.parseCanonical(precise.canonicalBytes())) + .isEqualTo(precise); + } + for (String invalid : List.of("01", "-1", "+1", "1.0", "1e0", " 1", "9223372036854775808")) { + var changed = JSON.readTree(original.canonicalBytes()); + ((tools.jackson.databind.node.ObjectNode) changed.get("request")) + .put("expectedRowVersion", invalid); + assertRejected(canonical(changed)); + } + var numeric = JSON.readTree(original.canonicalBytes()); + ((tools.jackson.databind.node.ObjectNode) numeric.get("request")) + .put("expectedLifecycleEpoch", 3); + assertRejected(canonical(numeric)); + var zeroEpoch = JSON.readTree(original.canonicalBytes()); + ((tools.jackson.databind.node.ObjectNode) zeroEpoch.get("request")) + .put("expectedLifecycleEpoch", "0"); + assertRejected(canonical(zeroEpoch)); + } + + @Test + void rejectsUtf8Base64ByteAndNestingBoundsWithoutMockedNestedDecoders() throws Exception { + assertRejected(new byte[] {(byte) 0xc3, 0x28}); + assertRejected(new byte[WorldCanonicalPlayerAdmissionHoldEvidence.MAX_EVIDENCE_BYTES + 1]); + assertRejected("{\"request\":{\"a\":{\"b\":{\"c\":{}}}}}".getBytes(StandardCharsets.UTF_8)); + var original = hold(); + var invalidBase64 = JSON.readTree(original.canonicalBytes()); + ((tools.jackson.databind.node.ObjectNode) invalidBase64) + .put("worldLifecycleEvidenceBase64", "%%%"); + assertRejected(canonical(invalidBase64)); + var oversizedLifecycle = JSON.readTree(original.canonicalBytes()); + ((tools.jackson.databind.node.ObjectNode) oversizedLifecycle) + .put( + "worldLifecycleEvidenceBase64", + Base64.getEncoder() + .encodeToString( + new byte[WorldCanonicalPlayerAdmissionHoldEvidence.MAX_LIFECYCLE_BYTES + 1])); + assertRejected(canonical(oversizedLifecycle)); + var corruptedWorld = JSON.readTree(original.canonicalBytes()); + ((tools.jackson.databind.node.ObjectNode) corruptedWorld) + .put( + "worldLifecycleEvidenceBase64", + Base64.getEncoder().encodeToString("{}".getBytes(StandardCharsets.UTF_8))); + assertRejected(canonical(corruptedWorld)); + } + + private static void assertRejected(byte[] bytes) throws Exception { + String digest = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + assertThatThrownBy(() -> WorldCanonicalPlayerAdmissionHoldEvidence.fromCanonical(bytes, digest)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static WorldCanonicalPlayerAdmissionHoldEvidence hold() throws Exception { + var world = lifecycleEvidence(); + var carrier = carrier(); + var boundScope = new LinkedHashMap<>(scope(carrier)); + boundScope.put("worldSlug", world.request().worldSlug()); + boundScope.put( + "playableStateNamespaceId", world.request().playableStateNamespaceId().toString()); + carrier.put("bindingScope", boundScope); + var lease = AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier); + return new WorldCanonicalPlayerAdmissionHoldEvidence( + UUID.randomUUID(), + UUID.randomUUID(), + new WorldCanonicalPlayerAdmissionHoldEvidence.Request( + lease, world.lifecycleEpoch(), world.rowVersion()), + world); + } + + // Only synthetic fixture construction is adapted from existing Common Core codec tests below. + + private static final UUID OPERATION_ID = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID REQUEST_ID = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID COMMIT_ID = uuid("55555555-5555-4555-8555-555555555555"); + private static final UUID FENCE_ID = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private static final UUID ACTOR_ID = uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); + private static final UUID TENANT_ID = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION_ID = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID REVISION_ID = uuid("66666666-6666-4666-8666-666666666666"); + private static final UUID REGION_TEMPLATE_ID = uuid("88888888-8888-4888-8888-888888888888"); + private static final UUID ZONE_TEMPLATE_ID = uuid("99999999-9999-4999-8999-999999999999"); + private static final UUID ROOM_TEMPLATE_ID = uuid("77777777-7777-4777-8777-777777777777"); + private static final UUID REGION_REVISION_ID = uuid("12345678-1234-4234-8234-123456789001"); + private static final UUID ZONE_REVISION_ID = uuid("12345678-1234-4234-8234-123456789002"); + private static final UUID ROOM_REVISION_ID = uuid("12345678-1234-4234-8234-123456789003"); + private static final tools.jackson.databind.ObjectMapper JSON = + new tools.jackson.databind.ObjectMapper(); + + private static WorldCanonicalInstanceLifecycleEvidence lifecycleEvidence() throws Exception { + WorldPublishedStartLocationEvidence selector = publishedSelector(); + var descriptorRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + selector.request().targetNamespace(), + "world-lifecycle-control-request", + selector.request().canonicalTenantId(), + "synthetic-world", + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + "sha256:" + "a".repeat(64), + 19L, + false, + null, + false, + null, + false, + null, + false, + null); + AuthoredWorldLaunchDescriptorEvidence descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + descriptorRequest, + "canonical-instance-launch-descriptor", + 42L, + false, + null, + "{}", + "generation-revision", + 9L, + 7L, + "release-bundle", + false, + null); + List participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptor.versionId()), + false, + null, + selector.request().appliedCommitId(), + selector.request().contentDigest(), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "c".repeat(64) : null)) + .toList(); + AuthoredWorldReleaseAttestationEvidence release = + AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + descriptor.canonicalTenantId(), + selector.request().canonicalVersionId(), + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + selector.request().publishWorkflowId(), + selector.request().appliedCommitId(), + participants, + "sha256:" + "d".repeat(64), + 1, + List.of(), + List.of(), + List.of(), + descriptor.generationConfigRevision(), + selector); + CompleteLaunchBindingEvidence binding = new CompleteLaunchBindingEvidence(descriptor, release); + WorldDraftStartLocationEvidence selectorReceipt = + WorldDraftStartLocationEvidence.fromStored(selector.selectorReceiptBytes()); + RoomTemplateRef startLocation = selectorReceipt.startLocation(); + Request request = + new Request( + Request.SCHEMA_VERSION, + uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + descriptor.targetNamespace(), + descriptor.canonicalTenantId(), + descriptor.worldSlug(), + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"), + "SHARED", + true, + descriptor.controlPlaneRequestId(), + release.canonicalVersionId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest()); + return new WorldCanonicalInstanceLifecycleEvidence( + request, + binding, + startLocation, + 1042L, + "ACTIVE", + 3L, + 0L, + uuid("33333333-3333-4333-8333-333333333333"), + selectorReceipt.graphDigest().substring("sha256:".length()), + "sha256:" + "e".repeat(64)); + } + + static WorldPublishedStartLocationEvidence publishedSelector() throws Exception { + WorldDraftTerminalReadEvidence.Request terminalRequest = freshGraphRequest(); + OwnerReadback committed = committedReadback(terminalRequest, true); + var account = terminalRequest.accountBinding(); + var draft = + DraftCommitBinding.fromStored( + new String(account.gameDesignBinding(), StandardCharsets.UTF_8), account.inputDigest()); + List tuples = + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .toList(); + var request = + new WorldPublishedStartLocationEvidence.Request( + "test", + account.tenantId(), + account.versionId(), + uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + "publication-request", + "a".repeat(64), + 5L, + "publish-workflow", + account.commitId().toString(), + "b".repeat(64), + 3, + tuples); + var applied = JSON.readTree(committed.result()); + byte[] receipt = + Base64.getDecoder().decode(applied.get("startLocationReceiptBase64").textValue()); + return new WorldPublishedStartLocationEvidence( + request, receipt, committed.fullBinding(), committed.result()); + } + + private static DraftAuthorizationFenceBinding.OwnerReadback committedReadback( + WorldDraftTerminalReadEvidence.Request request, boolean freshGraph) throws Exception { + var account = request.accountBinding(); + var draft = + DraftCommitBinding.fromStored( + new String(account.gameDesignBinding(), StandardCharsets.UTF_8), account.inputDigest()); + var operation = new ByteArrayOutputStream(); + var frames = new java.io.DataOutputStream(operation); + java.util.function.Consumer frame = + bytes -> { + try { + frames.writeInt(bytes.length); + frames.write(bytes); + } catch (java.io.IOException impossible) { + throw new AssertionError(impossible); + } + }; + java.util.function.Consumer text = + value -> frame.accept(value.getBytes(StandardCharsets.UTF_8)); + text.accept("world-draft-terminal-operation/v1"); + for (UUID id : + List.of( + account.operationId(), + account.requestId(), + account.commitId(), + account.fenceId(), + account.tenantId(), + account.versionId())) text.accept(id.toString()); + frame.accept(draft.canonicalBytes()); + for (String value : + List.of( + request.targetNamespace(), + account.tenantId().toString(), + account.versionId().toString(), + "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + Long.toString(draft.target().gameDesignVersionRowId()), + "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb", + "cccccccc-cccc-4ccc-8ccc-cccccccccccc", + "a".repeat(64), + "dddddddd-dddd-4ddd-8ddd-dddddddddddd", + "b".repeat(64), + "c".repeat(64))) text.accept(value); + text.accept(sha256(account.canonicalBytes())); + frame.accept(account.canonicalBytes()); + byte[] graph = freshGraph ? graphBytes(request, draft) : historicalGraphBytes(account); + String graphDigest = sha256(graph); + var result = new java.util.LinkedHashMap(); + result.put( + "schema", freshGraph ? "world-draft-graph-applied/v2" : "world-draft-graph-applied/v1"); + result.put("status", "APPLIED"); + result.put("operationBytesBase64", Base64.getEncoder().encodeToString(operation.toByteArray())); + result.put("graphBytesBase64", Base64.getEncoder().encodeToString(graph)); + result.put("graphDigest", graphDigest); + if (freshGraph) { + var receipt = receipt(request, draft, graphDigest); + byte[] receiptBytes = canonical(receipt); + result.put("startLocationReceiptBase64", Base64.getEncoder().encodeToString(receiptBytes)); + result.put("startLocationReceiptDigest", receipt.get("receiptDigest").textValue()); + } + result.put( + "appliedEpochs", + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + Map.of( + "aggregateType", + unit.aggregateType(), + "aggregateId", + unit.aggregateId(), + "scopeType", + unit.scopeType(), + "scopeId", + unit.scopeId(), + "expectedEpoch", + unit.expectedEpoch(), + "resultingEpoch", + new java.math.BigInteger(unit.expectedEpoch()) + .add(java.math.BigInteger.ONE) + .toString())) + .toList()); + return new DraftAuthorizationFenceBinding.OwnerReadback( + Owner.WORLD, + Outcome.COMMITTED, + account.operationId(), + account.commitId(), + account.fenceId(), + account.inputDigest(), + account.canonicalBytes(), + canonical(JSON.valueToTree(result))); + } + + private static WorldDraftTerminalReadEvidence.Request freshGraphRequest() throws Exception { + DraftCommitBinding draft = freshGraphBinding(); + return new WorldDraftTerminalReadEvidence.Request( + 1, "test", uuid("33333333-3333-4333-8333-333333333333"), accountBinding(draft)); + } + + private static DraftCommitBinding freshGraphBinding() throws Exception { + String declaration = + JSON.writeValueAsString( + Map.of( + "tenantId", TENANT_ID.toString(), + "versionId", VERSION_ID.toString(), + "startLocation", + Map.of( + "tenantId", TENANT_ID.toString(), + "versionId", VERSION_ID.toString(), + "roomTemplateId", ROOM_TEMPLATE_ID.toString()), + "familyCounts", + List.of( + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_REGION", "count", 1), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_ZONE", "count", 1), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_ROOM", "count", 1), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT", "count", 0), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE", "count", 0), + Map.of( + "family", + "WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING", + "count", + 0)))); + return DraftCommitBinding.create( + new TargetProof( + TENANT_ID, VERSION_ID, 19L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"), + REQUEST_ID, + COMMIT_ID, + "base-1", + List.of( + new RevisionPayload( + "0", + REGION_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + REGION_REVISION_ID, + "WORLD_DESIGN_AGGREGATE_TYPE_REGION", + REGION_TEMPLATE_ID, + declaration)), + new RevisionPayload( + "1", + ZONE_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + ZONE_REVISION_ID, "WORLD_DESIGN_AGGREGATE_TYPE_ZONE", ZONE_TEMPLATE_ID, null)), + new RevisionPayload( + "2", + ROOM_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + ROOM_REVISION_ID, "WORLD_DESIGN_AGGREGATE_TYPE_ROOM", ROOM_TEMPLATE_ID, null))), + List.of( + affected("REGION", REGION_TEMPLATE_ID, "REGION_SUBTREE", REGION_TEMPLATE_ID), + affected("ZONE", ZONE_TEMPLATE_ID, "REGION_SUBTREE", REGION_TEMPLATE_ID), + affected("ROOM", ROOM_TEMPLATE_ID, "ZONE_SUBTREE", ZONE_TEMPLATE_ID)) + .stream() + .flatMap(List::stream) + .toList()); + } + + private static String worldRevisionPayload( + UUID revisionId, String family, UUID templateId, String declaration) throws Exception { + var payload = new java.util.LinkedHashMap(); + payload.put("logicalRevisionId", revisionId.toString()); + payload.put("commitId", COMMIT_ID.toString()); + payload.put("aggregateType", family); + payload.put("aggregateId", templateId.toString()); + if (declaration != null) payload.put("freshGraphDeclaration", JSON.readTree(declaration)); + return JSON.writeValueAsString(payload); + } + + private static List affected( + String family, UUID templateId, String scopeType, UUID scopeId) { + return List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + family, + templateId.toString(), + "AGGREGATE", + templateId.toString(), + "0"), + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + family, + templateId.toString(), + scopeType, + scopeId.toString(), + "0")); + } + + private static byte[] accountBinding(DraftCommitBinding draft) { + byte[] draftBytes = draft.canonicalBytes(); + return new DraftAuthorizationFenceBinding( + OPERATION_ID, + REQUEST_ID, + COMMIT_ID, + FENCE_ID, + ACTOR_ID, + TENANT_ID, + VERSION_ID, + "base-1", + "0", + draftBytes, + draftBytes, + draft.digest(), + List.of( + new SourceEvidence( + SourceKind.GLOBAL_ROLES, + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd").toString(), + null, + "1", + null, + null, + new byte[] {4, 5}))) + .canonicalBytes(); + } + + private static byte[] historicalGraphBytes(DraftAuthorizationFenceBinding binding) { + return ("{\"schemaVersion\":\"2\",\"canonicalTenantId\":\"" + + binding.tenantId() + + "\",\"canonicalVersionId\":\"" + + binding.versionId() + + "\",\"rows\":[{}]}") + .getBytes(StandardCharsets.UTF_8); + } + + private static byte[] graphBytes( + WorldDraftTerminalReadEvidence.Request request, DraftCommitBinding draft) throws Exception { + var root = new java.util.LinkedHashMap(); + root.put("schemaVersion", "2"); + root.put("canonicalTenantId", draft.target().canonicalTenantId().toString()); + root.put("canonicalVersionId", draft.target().canonicalVersionId().toString()); + var rows = new java.util.ArrayList>(); + int mappingId = 1; + long privateRowKey = 101; + for (RevisionPayload revision : draft.revisions()) { + if (revision.owner() != DraftCommitBinding.Owner.WORLD_MANAGEMENT) continue; + var mutation = JSON.readTree(revision.payload()); + String family = + mutation.get("aggregateType").textValue().replace("WORLD_DESIGN_AGGREGATE_TYPE_", ""); + var mapping = new java.util.LinkedHashMap(); + mapping.put("id", mappingId++); + mapping.put("target_namespace", request.targetNamespace()); + mapping.put("canonical_tenant_id", draft.target().canonicalTenantId().toString()); + mapping.put("canonical_version_id", draft.target().canonicalVersionId().toString()); + mapping.put("family", family); + mapping.put("template_id", mutation.get("aggregateId").textValue()); + mapping.put("private_row_key", privateRowKey++); + mapping.put("tenant_id", 11); + mapping.put("version_id", 19); + mapping.put("version_identity_operation_id", OPERATION_ID.toString()); + mapping.put("request_id", draft.requestId().toString()); + mapping.put("commit_id", draft.commitId().toString()); + mapping.put("revision_id", revision.revisionId().toString()); + mapping.put("revision_order", revision.revisionOrder()); + rows.add(Map.of("mapping", mapping, "content", Map.of())); + } + root.put("rows", rows); + return JSON.writeValueAsBytes(root); + } + + private static tools.jackson.databind.node.ObjectNode receipt( + WorldDraftTerminalReadEvidence.Request request, DraftCommitBinding draft, String graphDigest) + throws Exception { + var account = request.accountBinding(); + var selector = + Map.of( + "tenantId", TENANT_ID.toString(), + "versionId", VERSION_ID.toString(), + "roomTemplateId", ROOM_TEMPLATE_ID.toString()); + String accountBindingDigest = sha256(request.originalAccountBinding()); + String receiptDigest = + startLocationReceiptDigest( + request.targetNamespace(), + account.operationId(), + account.requestId(), + account.commitId(), + account.fenceId(), + accountBindingDigest, + draft.digest(), + TENANT_ID, + VERSION_ID, + ROOM_TEMPLATE_ID, + graphDigest); + var value = new java.util.LinkedHashMap(); + value.put("schema", "world-draft-start-location-receipt/v1"); + value.put("targetNamespace", request.targetNamespace()); + value.put("operationId", account.operationId().toString()); + value.put("requestId", account.requestId().toString()); + value.put("commitId", account.commitId().toString()); + value.put("authorizationFenceId", account.fenceId().toString()); + value.put("accountBindingDigest", accountBindingDigest); + value.put("bindingDigest", draft.digest()); + value.put("startLocation", selector); + value.put("graphDigest", graphDigest); + value.put("receiptDigest", receiptDigest); + return (tools.jackson.databind.node.ObjectNode) JSON.valueToTree(value); + } + + private static String startLocationReceiptDigest( + String targetNamespace, + UUID operationId, + UUID requestId, + UUID commitId, + UUID fenceId, + String accountBindingDigest, + String bindingDigest, + UUID tenantId, + UUID versionId, + UUID roomTemplateId, + String graphDigest) + throws Exception { + var framed = new ByteArrayOutputStream(); + for (String value : + List.of( + "world-draft-start-location-receipt/v1", + targetNamespace, + operationId.toString(), + requestId.toString(), + commitId.toString(), + fenceId.toString(), + accountBindingDigest, + bindingDigest, + tenantId.toString(), + versionId.toString(), + roomTemplateId.toString(), + graphDigest)) { + byte[] bytes = value.getBytes(StandardCharsets.UTF_8); + framed.writeBytes(ByteBuffer.allocate(Integer.BYTES).putInt(bytes.length).array()); + framed.writeBytes(bytes); + } + return sha256(framed.toByteArray()); + } + + private static byte[] canonical(tools.jackson.databind.JsonNode value) throws Exception { + return net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + JSON.writeValueAsString(value)); + } + + private static String sha256(byte[] bytes) throws Exception { + return "sha256:" + + java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes)); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + static Map carrier() { + Map value = new LinkedHashMap<>(); + value.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); + value.put("schemaVersion", "1"); + value.put("mode", "PUBLIC_PRODUCTION"); + value.put("targetNamespace", "test"); + value.put("callerWorkload", "spiffe://firemud/ns/test/sa/game-session-service"); + value.put("requestId", ID); + value.put("leaseId", ACCOUNT); + value.put("leaseFence", "1"); + value.put("leaseKind", "NEW_BINDING"); + Map scope = new LinkedHashMap<>(); + for (String key : + List.of( + "tenantId", + "realmId", + "playableStateNamespaceId", + "gameInstanceId", + "characterId", + "sessionId", + "regionId")) scope.put(key, ID); + scope.put("accountId", ACCOUNT); + scope.put("worldSlug", "world"); + scope.put("realmSlug", "realm"); + scope.put("playableStateScope", "SHARED"); + for (String key : + List.of("bindingGeneration", "catalogRevision", "pointerVersion", "regionEpoch")) + scope.put(key, "9007199254740993"); + value.put("bindingScope", scope); + value.put( + "authorityTuple", + Map.of( + "issuerAuthGeneration", + "1", + "accountAuthorityGeneration", + "1", + "tenantAuthorityGeneration", + Map.of(ID, "1"), + "membershipAuthorityGeneration", + Map.of(ID, "1"), + "privateRealmGrantVersions", + List.of())); + value.put("issuanceFence", "1"); + value.put( + "membershipBaseline", + Map.of( + "membershipLifecycleState", + "ACTIVE", + "membershipVersion", + Map.of(ID, "1"), + "membershipAuthorityGeneration", + "1")); + value.put( + "outboxCheckpoints", + List.of( + checkpoint("account/" + ACCOUNT, "0"), + checkpoint("issuer/firemud-account-service", "0"), + checkpoint("membership/" + ACCOUNT + "/" + ID, "1"), checkpoint("tenant/" + ID, "1"))); + long now = System.currentTimeMillis(); + value.put( + "tokenIdentityEvidence", + Map.ofEntries( + Map.entry("accountId", ACCOUNT), + Map.entry("operationId", ID), + Map.entry("issuanceRequestId", ID), + Map.entry("tokenJti", ID), + Map.entry("tokenSHA256", "a".repeat(64)), + Map.entry("tokenGeneration", "1"), + Map.entry("issuanceFence", "1"), + Map.entry("tokenIdentityFence", "1"), + Map.entry("tokenProfile", "game-session-account-delegation"), + Map.entry("issuedAt", Long.toString(now / 1000)), + Map.entry("notBefore", Long.toString(now / 1000)), + Map.entry("expiresAt", Long.toString(now / 1000 + 300)))); + value.put("evaluatedAt", Long.toString(now)); + value.put("expiresAt", Long.toString(now + 15000)); + return value; + } + + @SuppressWarnings("unchecked") + static Map scope(Map carrier) { + return (Map) carrier.get("bindingScope"); + } + + private static Map checkpoint(String suffix, String sequence) { + return Map.of( + "outboxStreamKey", "account:auth-authority:v1:" + suffix, "outboxSequence", sequence); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHold.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHold.java deleted file mode 100644 index 4da66a77ea..0000000000 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHold.java +++ /dev/null @@ -1,114 +0,0 @@ -package net.firedevops.firemud.worldmanagement.tenant; - -import java.util.Map; -import java.util.Objects; -import java.util.UUID; -import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; -import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; - -/** - * Distinct World-owned player-admission lifecycle hold. This is neither a first-pointer hold nor - * Account authorization, Game Session's binding decision, or gameplay admission permission. - * - *

The complete original lease and exact World owner evidence remain immutable. Its deadline is - * diagnostic only. Release requires independently authenticated exact Account terminal evidence AND - * Game Session installation/cleanup evidence; those producers do not exist in this slice. - */ -public record WorldCanonicalPlayerAdmissionHold( - UUID holdId, - UUID holdFence, - Request request, - WorldCanonicalInstanceLifecycleEvidence worldEvidence) { - public WorldCanonicalPlayerAdmissionHold { - requireOpaque(holdId); - requireOpaque(holdFence); - Objects.requireNonNull(request, "request"); - Objects.requireNonNull(worldEvidence, "worldEvidence"); - request.requireExactActiveWorld(worldEvidence); - } - - /** Retained lease deadline triggers recovery diagnostics, never automatic release. */ - public long diagnosticExpiresAtMillis() { - return Long.parseLong((String) request.lease().carrier().get("expiresAt")); - } - - /** - * Complete original Account lease plus independently expected World lifecycle tuple. Account's - * regionEpoch is a separate domain and is never interpreted as this World lifecycle epoch. - */ - public record Request( - AccountGameplayAdmissionLeaseEvidence lease, - long expectedLifecycleEpoch, - long expectedRowVersion) { - public Request { - Objects.requireNonNull(lease, "lease"); - if (expectedLifecycleEpoch <= 0 || expectedRowVersion < 0) { - throw new IllegalArgumentException("Expected World lifecycle tuple is invalid"); - } - if (!(lease.carrier().get("bindingScope") instanceof Map scope) - || !"SHARED".equals(scope.get("playableStateScope")) - || !(lease.carrier().get("membershipBaseline") instanceof Map baseline) - || !"ACTIVE".equals(baseline.get("membershipLifecycleState"))) { - throw new IllegalArgumentException("Unsupported or non-admitting original lease scope"); - } - } - - public UUID leaseId() { - return UUID.fromString((String) lease.carrier().get("leaseId")); - } - - public UUID attemptId() { - return UUID.fromString((String) lease.carrier().get("requestId")); - } - - public UUID canonicalGameInstanceId() { - return UUID.fromString((String) scope().get("gameInstanceId")); - } - - public String targetNamespace() { - return (String) lease.carrier().get("targetNamespace"); - } - - public boolean sameBinding(Request other) { - return other != null - && lease.hasSameIdentity(other.lease) - && expectedLifecycleEpoch == other.expectedLifecycleEpoch - && expectedRowVersion == other.expectedRowVersion; - } - - public void requireExactActiveWorld(WorldCanonicalInstanceLifecycleEvidence evidence) { - Objects.requireNonNull(evidence, "evidence"); - requireExactWorldSelector(evidence.request()); - if (!"ACTIVE".equals(evidence.lifecycleStatus()) - || expectedLifecycleEpoch != evidence.lifecycleEpoch() - || expectedRowVersion != evidence.rowVersion()) { - throw new IllegalArgumentException("World target is not the exact expected ACTIVE tuple"); - } - } - - void requireExactWorldSelector(WorldCanonicalInstanceLifecycleEvidence.Request selector) { - if (!targetNamespace().equals(selector.targetNamespace()) - || !scope().get("tenantId").equals(selector.canonicalTenantId().toString()) - || !scope().get("worldSlug").equals(selector.worldSlug()) - || !scope().get("gameInstanceId").equals(selector.canonicalGameInstanceId().toString()) - || !scope() - .get("playableStateNamespaceId") - .equals(selector.playableStateNamespaceId().toString()) - || !scope().get("playableStateScope").equals(selector.playableStateScope()) - || !selector.publicProduction()) { - throw new IllegalArgumentException("Original lease differs from canonical World scope"); - } - } - - @SuppressWarnings("unchecked") - private Map scope() { - return (Map) lease.carrier().get("bindingScope"); - } - } - - private static void requireOpaque(UUID value) { - if (value == null || value.version() != 4 || value.variant() != 2) { - throw new IllegalArgumentException("Hold identity and fence must be opaque UUIDs"); - } - } -} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldGrpcService.java new file mode 100644 index 0000000000..2a220aa6b4 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldGrpcService.java @@ -0,0 +1,210 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import com.google.protobuf.ByteString; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalPlayerAdmissionHoldEvidence; +import net.firedevops.firemud.worldmanagement.v1.AcquireCanonicalPlayerAdmissionHoldRequest; +import net.firedevops.firemud.worldmanagement.v1.AcquireCanonicalPlayerAdmissionHoldResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadCanonicalPlayerAdmissionHoldRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadCanonicalPlayerAdmissionHoldResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldCanonicalPlayerAdmissionHoldServiceGrpc; +import org.jooq.exception.DataAccessException; +import org.springframework.dao.TransientDataAccessException; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Unregistered workload-only acquire/read adapter; no accepting release or runtime activation. */ +public final class WorldCanonicalPlayerAdmissionHoldGrpcService + extends WorldCanonicalPlayerAdmissionHoldServiceGrpc + .WorldCanonicalPlayerAdmissionHoldServiceImplBase { + private final WorldCanonicalPlayerAdmissionHoldService service; + private final String namespace; + + public WorldCanonicalPlayerAdmissionHoldGrpcService( + WorldCanonicalPlayerAdmissionHoldService service, String namespace) { + this.service = Objects.requireNonNull(service, "service"); + this.namespace = WorldCanonicalPlayerAdmissionHoldService.requireNamespace(namespace); + } + + @Override + public void acquireCanonicalPlayerAdmissionHold( + AcquireCanonicalPlayerAdmissionHoldRequest request, + StreamObserver observer) { + if (!requireBoundary(observer)) return; + try { + if (request == null || !request.getUnknownFields().asMap().isEmpty()) throw invalid(); + var parsed = + parse( + request.getRequestId(), + request.getOriginalLeaseJson(), + request.getOriginalLeaseSha256(), + request.getExpectedLifecycleEpoch(), + request.getExpectedRowVersion()); + var held = + service.acquire( + parsed.bound().lease().canonicalJson(), + parsed.bound().lease().sha256(), + parsed.bound().expectedLifecycleEpoch(), + parsed.bound().expectedRowVersion()); + var exact = requireResponse(parsed, held); + observer.onNext( + AcquireCanonicalPlayerAdmissionHoldResponse.newBuilder() + .setRequestId(parsed.correlationId()) + .setOriginalLeaseSha256(parsed.bound().lease().sha256()) + .setHoldEvidenceJson(ByteString.copyFrom(exact.canonicalBytes())) + .setHoldEvidenceSha256(exact.sha256()) + .build()); + observer.onCompleted(); + } catch (RuntimeException failure) { + report(observer, failure); + } + } + + @Override + public void readCanonicalPlayerAdmissionHold( + ReadCanonicalPlayerAdmissionHoldRequest request, + StreamObserver observer) { + if (!requireBoundary(observer)) return; + try { + if (request == null || !request.getUnknownFields().asMap().isEmpty()) throw invalid(); + var parsed = + parse( + request.getRequestId(), + request.getOriginalLeaseJson(), + request.getOriginalLeaseSha256(), + request.getExpectedLifecycleEpoch(), + request.getExpectedRowVersion()); + var held = + service + .read( + parsed.bound().lease().canonicalJson(), + parsed.bound().lease().sha256(), + parsed.bound().expectedLifecycleEpoch(), + parsed.bound().expectedRowVersion()) + .orElseThrow( + () -> + new IllegalStateException("Exact World player-admission hold is unresolved")); + var exact = requireResponse(parsed, held); + observer.onNext( + ReadCanonicalPlayerAdmissionHoldResponse.newBuilder() + .setRequestId(parsed.correlationId()) + .setOriginalLeaseSha256(parsed.bound().lease().sha256()) + .setHoldEvidenceJson(ByteString.copyFrom(exact.canonicalBytes())) + .setHoldEvidenceSha256(exact.sha256()) + .build()); + observer.onCompleted(); + } catch (RuntimeException failure) { + report(observer, failure); + } + } + + private boolean requireBoundary(StreamObserver observer) { + try { + WorldCanonicalPlayerAdmissionHoldService.requireAccountPeer(namespace); + } catch (SecurityException denied) { + observer.onError( + Status.PERMISSION_DENIED + .withDescription( + "Exact same-namespace Account workload without end-user context is required") + .asRuntimeException()); + return false; + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + observer.onError( + Status.FAILED_PRECONDITION + .withDescription("World player hold requires an independent owner operation") + .asRuntimeException()); + return false; + } + return true; + } + + private Parsed parse( + String correlation, + ByteString originalLease, + String leaseDigest, + String epoch, + String version) { + UUID requestId; + try { + requestId = UUID.fromString(correlation); + } catch (RuntimeException invalid) { + throw invalid(); + } + if (!requestId.toString().equals(correlation) + || requestId.version() != 4 + || requestId.variant() != 2 + || originalLease.isEmpty() + || originalLease.size() > AccountGameplayAdmissionLeaseEvidence.MAX_EVIDENCE_BYTES + || !originalLease.isValidUtf8()) throw invalid(); + var lease = AccountGameplayAdmissionLeaseEvidence.parseCanonical(originalLease.toStringUtf8()); + if (leaseDigest == null + || !lease.sha256().equals(leaseDigest) + || !namespace.equals(lease.carrier().get("targetNamespace"))) { + throw invalid(); + } + return new Parsed( + correlation, + new WorldCanonicalPlayerAdmissionHoldEvidence.Request( + lease, + WorldCanonicalPlayerAdmissionHoldEvidence.decimal(epoch, true), + WorldCanonicalPlayerAdmissionHoldEvidence.decimal(version, false))); + } + + private static WorldCanonicalPlayerAdmissionHoldEvidence requireResponse( + Parsed parsed, WorldCanonicalPlayerAdmissionHoldEvidence held) { + if (held == null || held.request() == null || !parsed.bound().sameBinding(held.request())) { + throw new IllegalStateException( + "World hold response changed the complete original lease binding"); + } + var world = held.worldEvidence(); + if (held.holdId() == null + || held.holdFence() == null + || world == null + || world.request() == null + || world.request().canonicalTenantId() == null + || world.request().canonicalGameInstanceId() == null + || world.request().playableStateNamespaceId() == null) { + throw new IllegalStateException("World hold response has missing owner evidence fields"); + } + try { + parsed.bound().requireExactActiveWorld(world); + // Rebuild the immutable carrier from the exact bound value rather than trusting supplied + // bytes. + var exact = + new WorldCanonicalPlayerAdmissionHoldEvidence( + held.holdId(), held.holdFence(), parsed.bound(), world); + exact.canonicalBytes(); + return exact; + } catch (IllegalArgumentException inconsistent) { + throw new IllegalStateException( + "World hold response has inconsistent owner evidence", inconsistent); + } + } + + private static void report(StreamObserver observer, RuntimeException failure) { + Status status; + if (failure instanceof IllegalArgumentException) status = Status.INVALID_ARGUMENT; + else if (failure instanceof SecurityException) status = Status.PERMISSION_DENIED; + else if (failure instanceof TransientDataAccessException + || failure instanceof DataAccessException) status = Status.UNAVAILABLE; + else if (failure instanceof IllegalStateException) status = Status.FAILED_PRECONDITION; + else status = Status.INTERNAL; + observer.onError( + status + .withDescription( + "World player hold request could not produce exact retained owner evidence") + .asRuntimeException()); + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Complete canonical World player hold request is required"); + } + + private record Parsed( + String correlationId, WorldCanonicalPlayerAdmissionHoldEvidence.Request bound) {} +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldRepository.java index d057e9b954..442527a3ce 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldRepository.java @@ -6,6 +6,7 @@ import java.util.UUID; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalPlayerAdmissionHoldEvidence; import org.jooq.DSLContext; import org.jooq.Record; import org.springframework.transaction.PlatformTransactionManager; @@ -45,8 +46,8 @@ public WorldCanonicalPlayerAdmissionHoldRepository( readTransaction.setReadOnly(true); } - public WorldCanonicalPlayerAdmissionHold acquire( - WorldCanonicalPlayerAdmissionHold.Request request) { + public WorldCanonicalPlayerAdmissionHoldEvidence acquire( + WorldCanonicalPlayerAdmissionHoldEvidence.Request request) { requireBoundary(request); return Objects.requireNonNull( writeTransaction.execute( @@ -100,8 +101,8 @@ public WorldCanonicalPlayerAdmissionHold acquire( } /** Exact durable retained identity; absence is UNKNOWN, never an abort or release result. */ - public Optional read( - WorldCanonicalPlayerAdmissionHold.Request request) { + public Optional read( + WorldCanonicalPlayerAdmissionHoldEvidence.Request request) { requireBoundary(request); return Optional.ofNullable( readTransaction.execute( @@ -112,7 +113,7 @@ public Optional read( })); } - private void requireBoundary(WorldCanonicalPlayerAdmissionHold.Request request) { + private void requireBoundary(WorldCanonicalPlayerAdmissionHoldEvidence.Request request) { WorldCanonicalPlayerAdmissionHoldService.requireAccountPeer(namespace); requireNoAmbientTransaction(); Objects.requireNonNull(request, "request"); @@ -120,21 +121,21 @@ private void requireBoundary(WorldCanonicalPlayerAdmissionHold.Request request) throw denied("Lease namespace differs from World"); } - private Record findOriginal(WorldCanonicalPlayerAdmissionHold.Request request) { + private Record findOriginal(WorldCanonicalPlayerAdmissionHoldEvidence.Request request) { return dsl.fetchOne( "SELECT * FROM world_canonical_player_admission_hold WHERE lease_id=? OR attempt_id=?", request.leaseId(), request.attemptId()); } - private static WorldCanonicalPlayerAdmissionHold retained( - Record row, WorldCanonicalPlayerAdmissionHold.Request expected) { + private static WorldCanonicalPlayerAdmissionHoldEvidence retained( + Record row, WorldCanonicalPlayerAdmissionHoldEvidence.Request expected) { byte[] bytes = Objects.requireNonNull(row.get("lease_bytes", byte[].class)); var lease = AccountGameplayAdmissionLeaseEvidence.parseCanonical( new String(bytes, StandardCharsets.UTF_8)); var request = - new WorldCanonicalPlayerAdmissionHold.Request( + new WorldCanonicalPlayerAdmissionHoldEvidence.Request( lease, Objects.requireNonNull(row.get("active_lifecycle_epoch", Long.class)), Objects.requireNonNull(row.get("active_row_version", Long.class))); @@ -152,7 +153,7 @@ private static WorldCanonicalPlayerAdmissionHold retained( || row.get("game_session_completion_evidence_bytes") != null) { throw denied("Retained hold conflicts with the complete original lease/attempt binding"); } - return new WorldCanonicalPlayerAdmissionHold( + return new WorldCanonicalPlayerAdmissionHoldEvidence( row.get("hold_id", UUID.class), row.get("hold_fence", UUID.class), request, diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldService.java index fb115dfa11..9787c34237 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldService.java @@ -5,6 +5,7 @@ import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldCanonicalPlayerAdmissionHoldEvidence; /** * Unregistered internal boundary. Authenticating the exact Account workload establishes only the @@ -20,7 +21,7 @@ public WorldCanonicalPlayerAdmissionHoldService( this.namespace = requireNamespace(namespace); } - public WorldCanonicalPlayerAdmissionHold acquire( + public WorldCanonicalPlayerAdmissionHoldEvidence acquire( String originalLeaseJson, String originalLeaseSha256, long expectedEpoch, @@ -29,7 +30,7 @@ public WorldCanonicalPlayerAdmissionHold acquire( request(originalLeaseJson, originalLeaseSha256, expectedEpoch, expectedVersion)); } - public Optional read( + public Optional read( String originalLeaseJson, String originalLeaseSha256, long expectedEpoch, @@ -46,7 +47,7 @@ public void release() { "Hold release is unavailable without authenticated exact Account terminal AND Game Session installation/cleanup evidence"); } - private WorldCanonicalPlayerAdmissionHold.Request request( + private WorldCanonicalPlayerAdmissionHoldEvidence.Request request( String originalLeaseJson, String originalLeaseSha256, long expectedEpoch, @@ -58,7 +59,8 @@ private WorldCanonicalPlayerAdmissionHold.Request request( || !namespace.equals(lease.carrier().get("targetNamespace"))) { throw new IllegalArgumentException("Original lease digest or namespace differs"); } - return new WorldCanonicalPlayerAdmissionHold.Request(lease, expectedEpoch, expectedVersion); + return new WorldCanonicalPlayerAdmissionHoldEvidence.Request( + lease, expectedEpoch, expectedVersion); } static String requireNamespace(String namespace) { diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldPostgresIntegrationTest.java index bcf61adb4b..36d0ed2e1e 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldPostgresIntegrationTest.java @@ -15,6 +15,7 @@ import java.util.concurrent.TimeUnit; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.world.WorldCanonicalPlayerAdmissionHoldEvidence; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.worldmanagement.WorldManagementServiceApplication; import net.firedevops.firemud.worldmanagement.client.EntityManagementClient; @@ -268,7 +269,7 @@ void twoConcurrentExactAcquisitionsRetainOneIdentity() throws Exception { var start = new CountDownLatch(1); var executor = Executors.newFixedThreadPool(2); try { - java.util.concurrent.Callable operation = + java.util.concurrent.Callable operation = () -> { ready.countDown(); await(start); @@ -384,7 +385,7 @@ private WorldCanonicalPlayerAdmissionHoldService service( "firemud"); } - private static WorldCanonicalPlayerAdmissionHold acquire( + private static WorldCanonicalPlayerAdmissionHoldEvidence acquire( WorldCanonicalPlayerAdmissionHoldService service, WorldDraftGraphApplicationPostgresIntegrationTest.ActivePlayerAdmissionFixture f, AccountGameplayAdmissionLeaseEvidence lease) { diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldGrpcServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldGrpcServiceTest.java new file mode 100644 index 0000000000..da49a4a55f --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldGrpcServiceTest.java @@ -0,0 +1,308 @@ +package unit.net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.nio.charset.StandardCharsets; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldCanonicalPlayerAdmissionHoldEvidence; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalPlayerAdmissionHoldGrpcService; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalPlayerAdmissionHoldService; +import net.firedevops.firemud.worldmanagement.v1.AcquireCanonicalPlayerAdmissionHoldRequest; +import net.firedevops.firemud.worldmanagement.v1.AcquireCanonicalPlayerAdmissionHoldResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadCanonicalPlayerAdmissionHoldRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadCanonicalPlayerAdmissionHoldResponse; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Adapter-only mocked service/lifecycle fixtures; not authenticated transport or database proof. + */ +class WorldCanonicalPlayerAdmissionHoldGrpcServiceTest { + private final WorldCanonicalPlayerAdmissionHoldService service = + mock(WorldCanonicalPlayerAdmissionHoldService.class); + private final WorldCanonicalPlayerAdmissionHoldGrpcService adapter = + new WorldCanonicalPlayerAdmissionHoldGrpcService(service, "firemud"); + + @AfterEach + void clearContext() { + SessionContext.clear(); + TransactionSynchronizationManager.setActualTransactionActive(false); + if (TransactionSynchronizationManager.isSynchronizationActive()) + TransactionSynchronizationManager.clearSynchronization(); + } + + @Test + void wrongPeerAndEndUserContextDenyBeforeAnyPrimitiveParsingOrOwnerAccess() { + for (String peer : + java.util.List.of( + "spiffe://firemud/ns/firemud/sa/game-session-service", + "spiffe://firemud/ns/other/sa/account-service")) { + peer(peer) + .run( + () -> { + var acquire = new Collector(); + adapter.acquireCanonicalPlayerAdmissionHold(null, acquire); + assertThat(acquire.code()).isEqualTo(Status.Code.PERMISSION_DENIED); + var read = new Collector(); + adapter.readCanonicalPlayerAdmissionHold(null, read); + assertThat(read.code()).isEqualTo(Status.Code.PERMISSION_DENIED); + }); + } + SessionContext.setContext( + WorldCanonicalPlayerAdmissionHoldTest.ACCOUNT, java.util.List.of(), java.util.Map.of()); + account() + .run( + () -> { + var acquire = new Collector(); + adapter.acquireCanonicalPlayerAdmissionHold(null, acquire); + assertThat(acquire.code()).isEqualTo(Status.Code.PERMISSION_DENIED); + var read = new Collector(); + adapter.readCanonicalPlayerAdmissionHold(null, read); + assertThat(read.code()).isEqualTo(Status.Code.PERMISSION_DENIED); + }); + verifyNoInteractions(service); + } + + @Test + void ambientTransactionAndSynchronizationDenyBeforeDecode() { + account() + .run( + () -> { + TransactionSynchronizationManager.setActualTransactionActive(true); + var acquire = new Collector(); + adapter.acquireCanonicalPlayerAdmissionHold(null, acquire); + assertThat(acquire.code()).isEqualTo(Status.Code.FAILED_PRECONDITION); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + var read = new Collector(); + adapter.readCanonicalPlayerAdmissionHold(null, read); + assertThat(read.code()).isEqualTo(Status.Code.FAILED_PRECONDITION); + }); + verifyNoInteractions(service); + } + + @Test + void acquireAndReadEchoFreshCorrelationAndExactOriginalBindingWithSeparateOuterDigest() { + var request = request(); + var held = mockedLifecycleHold(request); + when(service.acquire( + request.getOriginalLeaseJson().toStringUtf8(), + request.getOriginalLeaseSha256(), + 7L, + 8L)) + .thenReturn(held); + when(service.read( + request.getOriginalLeaseJson().toStringUtf8(), + request.getOriginalLeaseSha256(), + 7L, + 8L)) + .thenReturn(Optional.of(held)); + account() + .run( + () -> { + var acquire = new Collector(); + adapter.acquireCanonicalPlayerAdmissionHold(request, acquire); + assertThat(acquire.error).isNull(); + assertThat(acquire.completed).isTrue(); + assertThat(acquire.value.getRequestId()).isEqualTo(request.getRequestId()); + assertThat(acquire.value.getOriginalLeaseSha256()) + .isEqualTo(request.getOriginalLeaseSha256()); + assertThat(acquire.value.getHoldEvidenceJson().toByteArray()) + .containsExactly(held.canonicalBytes()); + assertThat(acquire.value.getHoldEvidenceSha256()).isEqualTo(held.sha256()); + String readCorrelation = UUID.randomUUID().toString(); + var readRequest = + readRequest(request).toBuilder().setRequestId(readCorrelation).build(); + var read = new Collector(); + adapter.readCanonicalPlayerAdmissionHold(readRequest, read); + assertThat(read.error).isNull(); + assertThat(read.completed).isTrue(); + assertThat(read.value.getRequestId()).isEqualTo(readCorrelation); + assertThat(read.value.getOriginalLeaseSha256()) + .isEqualTo(request.getOriginalLeaseSha256()); + assertThat(read.value.getHoldEvidenceJson()) + .isEqualTo(acquire.value.getHoldEvidenceJson()); + assertThat(read.value.getHoldEvidenceSha256()) + .isEqualTo(acquire.value.getHoldEvidenceSha256()); + }); + } + + @Test + void missingReadIsUnresolvedAndNeverAnAbsenceOrReleaseProof() { + when(service.read(anyString(), anyString(), anyLong(), anyLong())).thenReturn(Optional.empty()); + account() + .run( + () -> { + var read = new Collector(); + adapter.readCanonicalPlayerAdmissionHold(readRequest(request()), read); + assertThat(read.code()).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(read.value).isNull(); + assertThat(read.completed).isFalse(); + }); + } + + @Test + void malformedUnknownAndNoncanonicalPrimitivesDenyWithoutOwnerCalls() { + var original = request(); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + for (var changed : + java.util.List.of( + original.toBuilder().setRequestId("invalid").build(), + original.toBuilder().setExpectedLifecycleEpoch("07").build(), + original.toBuilder().setExpectedRowVersion("9223372036854775808").build(), + original.toBuilder().setOriginalLeaseSha256("b".repeat(64)).build(), + original.toBuilder() + .setOriginalLeaseJson(ByteString.copyFrom(new byte[] {(byte) 0xc3, 0x28})) + .build(), + original.toBuilder() + .setOriginalLeaseJson( + ByteString.copyFrom( + new byte + [net.firedevops.firemud.common.account.admission + .AccountGameplayAdmissionLeaseEvidence.MAX_EVIDENCE_BYTES + + 1])) + .build(), + original.toBuilder().setUnknownFields(unknown).build())) { + account() + .run( + () -> { + var acquire = new Collector(); + adapter.acquireCanonicalPlayerAdmissionHold(changed, acquire); + assertThat(acquire.code()).isEqualTo(Status.Code.INVALID_ARGUMENT); + }); + } + var unknownRead = readRequest(original).toBuilder().setUnknownFields(unknown).build(); + account() + .run( + () -> { + var read = new Collector(); + adapter.readCanonicalPlayerAdmissionHold(unknownRead, read); + assertThat(read.code()).isEqualTo(Status.Code.INVALID_ARGUMENT); + }); + verifyNoInteractions(service); + } + + @Test + void changedOwnerBindingOrWorldScopeCannotProduceResponse() { + var request = request(); + var held = mockedLifecycleHold(request); + var lease = WorldCanonicalPlayerAdmissionHoldTest.lease(); + var changedCarrier = new java.util.LinkedHashMap<>(lease.carrier()); + changedCarrier.put("leaseFence", "2"); + var changedLease = + net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence + .fromCarrier(changedCarrier); + var changed = + new WorldCanonicalPlayerAdmissionHoldEvidence( + held.holdId(), + held.holdFence(), + new WorldCanonicalPlayerAdmissionHoldEvidence.Request(changedLease, 7L, 8L), + held.worldEvidence()); + when(service.acquire(anyString(), anyString(), anyLong(), anyLong())).thenReturn(changed); + account() + .run( + () -> { + var acquire = new Collector(); + adapter.acquireCanonicalPlayerAdmissionHold(request, acquire); + assertThat(acquire.code()).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(acquire.value).isNull(); + }); + when(service.acquire(anyString(), anyString(), anyLong(), anyLong())).thenReturn(held); + when(held.worldEvidence().request().worldSlug()).thenReturn("substituted-world"); + account() + .run( + () -> { + var acquire = new Collector(); + adapter.acquireCanonicalPlayerAdmissionHold(request, acquire); + assertThat(acquire.code()).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(acquire.value).isNull(); + }); + } + + private static AcquireCanonicalPlayerAdmissionHoldRequest request() { + var lease = WorldCanonicalPlayerAdmissionHoldTest.lease(); + return AcquireCanonicalPlayerAdmissionHoldRequest.newBuilder() + .setRequestId(UUID.randomUUID().toString()) + .setOriginalLeaseJson(ByteString.copyFromUtf8(lease.canonicalJson())) + .setOriginalLeaseSha256(lease.sha256()) + .setExpectedLifecycleEpoch("7") + .setExpectedRowVersion("8") + .build(); + } + + private static ReadCanonicalPlayerAdmissionHoldRequest readRequest( + AcquireCanonicalPlayerAdmissionHoldRequest request) { + return ReadCanonicalPlayerAdmissionHoldRequest.newBuilder() + .setRequestId(request.getRequestId()) + .setOriginalLeaseJson(request.getOriginalLeaseJson()) + .setOriginalLeaseSha256(request.getOriginalLeaseSha256()) + .setExpectedLifecycleEpoch(request.getExpectedLifecycleEpoch()) + .setExpectedRowVersion(request.getExpectedRowVersion()) + .build(); + } + + private static WorldCanonicalPlayerAdmissionHoldEvidence mockedLifecycleHold( + AcquireCanonicalPlayerAdmissionHoldRequest request) { + var lease = + net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence + .parseCanonical(request.getOriginalLeaseJson().toStringUtf8()); + var world = WorldCanonicalPlayerAdmissionHoldTest.evidence(); + // Opaque mocked lifecycle bytes test adapter serialization only. The Common test uses real + // complete nested codecs and independently verifies their canonical roundtrip. + when(world.canonicalBytes()) + .thenReturn("mocked lifecycle bytes".getBytes(StandardCharsets.UTF_8)); + return new WorldCanonicalPlayerAdmissionHoldEvidence( + UUID.randomUUID(), + UUID.randomUUID(), + new WorldCanonicalPlayerAdmissionHoldEvidence.Request(lease, 7L, 8L), + world); + } + + private static Context peer(String uri) { + return Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(uri).orElseThrow()); + } + + private static Context account() { + return peer("spiffe://firemud/ns/firemud/sa/account-service"); + } + + private static final class Collector implements StreamObserver { + private T value; + private Status error; + private boolean completed; + + public void onNext(T response) { + value = response; + } + + public void onError(Throwable failure) { + error = Status.fromThrowable(failure); + } + + public void onCompleted() { + completed = true; + } + + private Status.Code code() { + return error.getCode(); + } + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldRepositoryTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldRepositoryTest.java index 63dcae86b7..b2590d6eb5 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldRepositoryTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldRepositoryTest.java @@ -7,9 +7,9 @@ import io.grpc.Context; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldCanonicalPlayerAdmissionHoldEvidence; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceAssociationRepository; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceLifecycleReadRepository; -import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalPlayerAdmissionHold; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalPlayerAdmissionHoldRepository; import org.jooq.DSLContext; import org.junit.jupiter.api.AfterEach; @@ -81,7 +81,7 @@ void substitutedNamespaceDeniesBeforeOpeningSqlTransaction() { carrier.put("targetNamespace", "other"); carrier.put("callerWorkload", "spiffe://firemud/ns/other/sa/game-session-service"); var changed = - new WorldCanonicalPlayerAdmissionHold.Request( + new WorldCanonicalPlayerAdmissionHoldEvidence.Request( net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence .fromCarrier(carrier), 7L, @@ -95,8 +95,8 @@ void substitutedNamespaceDeniesBeforeOpeningSqlTransaction() { verifyNoInteractions(dsl, manager, associations, lifecycle); } - private static WorldCanonicalPlayerAdmissionHold.Request request() { - return new WorldCanonicalPlayerAdmissionHold.Request( + private static WorldCanonicalPlayerAdmissionHoldEvidence.Request request() { + return new WorldCanonicalPlayerAdmissionHoldEvidence.Request( WorldCanonicalPlayerAdmissionHoldTest.lease(), 7L, 8L); } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldServiceTest.java index 8255f3f702..f436211d11 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldServiceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldServiceTest.java @@ -12,7 +12,7 @@ import java.util.UUID; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.SessionContext; -import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalPlayerAdmissionHold; +import net.firedevops.firemud.common.world.WorldCanonicalPlayerAdmissionHoldEvidence; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalPlayerAdmissionHoldRepository; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalPlayerAdmissionHoldService; import org.junit.jupiter.api.Test; @@ -63,9 +63,9 @@ void accountWorkloadWithAuthenticatedEndUserContextDeniesBeforeDecodeOrOwnerAcce @Test void exactAccountProducerPassesOriginalLeaseWithoutChangingIdentity() { var lease = WorldCanonicalPlayerAdmissionHoldTest.lease(); - var request = new WorldCanonicalPlayerAdmissionHold.Request(lease, 7L, 8L); + var request = new WorldCanonicalPlayerAdmissionHoldEvidence.Request(lease, 7L, 8L); var retained = - new WorldCanonicalPlayerAdmissionHold( + new WorldCanonicalPlayerAdmissionHoldEvidence( UUID.randomUUID(), UUID.randomUUID(), request, diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldTest.java index c8064eedec..b067211b6c 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldTest.java @@ -11,7 +11,7 @@ import java.util.UUID; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; -import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalPlayerAdmissionHold; +import net.firedevops.firemud.common.world.WorldCanonicalPlayerAdmissionHoldEvidence; import org.junit.jupiter.api.Test; class WorldCanonicalPlayerAdmissionHoldTest { @@ -21,18 +21,20 @@ class WorldCanonicalPlayerAdmissionHoldTest { @Test void originalLeaseDefinesRetryIdentityWithoutRemintingOrRenewal() { var lease = lease(); - var original = new WorldCanonicalPlayerAdmissionHold.Request(lease, 7L, 8L); + var original = new WorldCanonicalPlayerAdmissionHoldEvidence.Request(lease, 7L, 8L); var exact = - new WorldCanonicalPlayerAdmissionHold.Request( + new WorldCanonicalPlayerAdmissionHoldEvidence.Request( AccountGameplayAdmissionLeaseEvidence.parseCanonical(lease.canonicalJson()), 7L, 8L); assertThat(original.sameBinding(exact)).isTrue(); - assertThat(original.sameBinding(new WorldCanonicalPlayerAdmissionHold.Request(lease, 8L, 8L))) + assertThat( + original.sameBinding( + new WorldCanonicalPlayerAdmissionHoldEvidence.Request(lease, 8L, 8L))) .isFalse(); var changed = carrier(); changed.put("leaseFence", "2"); assertThat( original.sameBinding( - new WorldCanonicalPlayerAdmissionHold.Request( + new WorldCanonicalPlayerAdmissionHoldEvidence.Request( AccountGameplayAdmissionLeaseEvidence.fromCarrier(changed), 7L, 8L))) .isFalse(); } @@ -52,10 +54,10 @@ void donorDelegationBoundsRemainExactWithoutWideningTheOriginalCarrier() { @Test void worldLifecycleEpochRemainsSeparateFromLeaseRegionEpoch() { - var request = new WorldCanonicalPlayerAdmissionHold.Request(lease(), 7L, 8L); + var request = new WorldCanonicalPlayerAdmissionHoldEvidence.Request(lease(), 7L, 8L); var evidence = evidence(); var hold = - new WorldCanonicalPlayerAdmissionHold( + new WorldCanonicalPlayerAdmissionHoldEvidence( UUID.randomUUID(), UUID.randomUUID(), request, evidence); assertThat(hold.worldEvidence().lifecycleEpoch()).isEqualTo(7L); assertThat(hold.diagnosticExpiresAtMillis()) @@ -79,20 +81,22 @@ void inactiveMembershipAndIsolatedScopeAreNotRepairable() { "membershipAuthorityGeneration", "1")); var inactiveLease = AccountGameplayAdmissionLeaseEvidence.fromCarrier(changed); - assertThatThrownBy(() -> new WorldCanonicalPlayerAdmissionHold.Request(inactiveLease, 7L, 8L)) + assertThatThrownBy( + () -> new WorldCanonicalPlayerAdmissionHoldEvidence.Request(inactiveLease, 7L, 8L)) .isInstanceOf(IllegalArgumentException.class); changed = carrier(); var scope = new LinkedHashMap<>(scope(changed)); scope.put("playableStateScope", "ISOLATED"); changed.put("bindingScope", scope); var isolated = AccountGameplayAdmissionLeaseEvidence.fromCarrier(changed); - assertThatThrownBy(() -> new WorldCanonicalPlayerAdmissionHold.Request(isolated, 7L, 8L)) + assertThatThrownBy( + () -> new WorldCanonicalPlayerAdmissionHoldEvidence.Request(isolated, 7L, 8L)) .isInstanceOf(IllegalArgumentException.class); } @Test void substitutedWorldTenantOrNonActiveTupleIsDenied() { - var request = new WorldCanonicalPlayerAdmissionHold.Request(lease(), 7L, 8L); + var request = new WorldCanonicalPlayerAdmissionHoldEvidence.Request(lease(), 7L, 8L); var evidence = evidence(); when(evidence.request().canonicalTenantId()).thenReturn(UUID.fromString(ACCOUNT)); var substituted = evidence; From a006f44ec3ad92eadf944c72ccd81c7c444bbe10 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 8 Oct 2026 13:22:30 +1300 Subject: [PATCH 3/8] Record executed World player hold PostgreSQL proof --- .../implementation-tracking/world-runtime-and-movement.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/design/project-management/implementation-tracking/world-runtime-and-movement.md b/design/project-management/implementation-tracking/world-runtime-and-movement.md index 62e6c9330d..e3da727120 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -6,9 +6,11 @@ This is a non-normative implementation tracker for world runtime and movement. C ## Current Status -The distinct player-admission serving-hold candidate builds on the preserved #3044 source. It reuses the unchanged Account lease carrier and the actual canonical association/lifecycle reader; its unregistered Account-workload-only owner records immutable acquisition/readback and a V51 lifecycle tuple fence. The same-value tuple update changes PostgreSQL's physical row version without changing logical state, lifecycle epoch, owner row-version counter or history. Current definitions cover exact retry, substitution, retained diagnostic expiry, independent holds, V51-specific mutation denial and stale REPEATABLE_READ/SERIALIZABLE rejection. Consolidated local Common/World formatting, full checks, static analysis, jOOQ generation, integration-source compilation, World boot JAR and documentation validation pass: 161 Common and 525 World unit cases executed without failures/errors/skips, while all 206 World integration cases skipped without Docker. The definitions and reused ACTIVE fixture stipulate upstream authority; physical migration and race execution remain unproved. Release has no accepting path until exact authenticated Account terminal and Game Session installation/cleanup producers exist. Protected Account acquire/finalize, current source/physical-COMMIT proof and Game Session pointer/catalog/runtime fencing remain separate gates. No transport registration, canonical termination producer or live admission is enabled. The target owner is [Player Admission Serving Hold](../../architecture/microservices/world-management-service/api-contracts.md#player-admission-serving-hold). +The distinct player-admission serving-hold candidate builds on the preserved #3044 source. It reuses the unchanged Account lease carrier and the actual canonical association/lifecycle reader; its unregistered Account-workload-only owner records immutable acquisition/readback and a V51 lifecycle tuple fence. The same-value tuple update changes PostgreSQL's physical row version without changing logical state, lifecycle epoch, owner row-version counter or history. Current definitions cover exact retry, substitution, retained diagnostic expiry, independent holds, V51-specific mutation denial and stale REPEATABLE_READ/SERIALIZABLE rejection. Consolidated local Common/World formatting, full checks, static analysis, jOOQ generation, integration-source compilation, World boot JAR and documentation validation pass: 161 Common and 525 World unit cases executed without failures/errors/skips, while all 206 World integration cases skipped without Docker. The definitions and reused ACTIVE fixture stipulate upstream authority; those local checks do not establish physical migration or race execution, whose separate CI evidence follows below. Release has no accepting path until exact authenticated Account terminal and Game Session installation/cleanup producers exist. Protected Account acquire/finalize, current source/physical-COMMIT proof and Game Session pointer/catalog/runtime fencing remain separate gates. No transport registration, canonical termination producer or live admission is enabled. The target owner is [Player Admission Serving Hold](../../architecture/microservices/world-management-service/api-contracts.md#player-admission-serving-hold). -The continuation moves the hold value into one closed Common Security carrier and adds an unregistered protected acquire/read adapter. It retains the original lease and complete World evidence, verifies exact workload identity before primitive parsing, and independently binds response correlation and original request scope. Five Common codec tests use real nested codecs over synthetic source fixtures; six adapter tests use explicitly mocked owner/lifecycle collaborators. The corrected full local gate passes after fixing two new SpotBugs issues without weakening guards: its reports contain 166 passing Common and 531 passing World unit cases, with all 206 integration cases skipped. The corrected gate reuses the unchanged Common test task and executes World tests; no duplicate fresh Common execution is claimed. Exact predecessor `fff09667c031b14aaa60002dd2c61f8ec99223ee` [World CI job](https://github.com/benhook1013/FireMUD/actions/runs/37700261172/job/113061857548) passed the full check and ran the integration task, but uploaded no JUnit report or strict result for the nine serving-hold methods. Their execution versus skips cannot be established from that run or JaCoCo coverage. The owning CI continuation therefore requires all nine cases through the existing strict JUnit verifier and captures their raw XML; its executed result is still pending. Authenticated Account consumption, actual owner composition, release and activation remain unproved. +The continuation moves the hold value into one closed Common Security carrier and adds an unregistered protected acquire/read adapter. It retains the original lease and complete World evidence, verifies exact workload identity before primitive parsing, and independently binds response correlation and original request scope. Five Common codec tests use real nested codecs over synthetic source fixtures; six adapter tests use explicitly mocked owner/lifecycle collaborators. The corrected full local gate passes after fixing two new SpotBugs issues without weakening guards: its reports contain 166 passing Common and 531 passing World unit cases, with all 206 integration cases skipped. The corrected gate reuses the unchanged Common test task and executes World tests; no duplicate fresh Common execution is claimed. Exact predecessor `fff09667c031b14aaa60002dd2c61f8ec99223ee` [World CI job](https://github.com/benhook1013/FireMUD/actions/runs/37700261172/job/113061857548) passed the full check and ran the integration task, but uploaded no JUnit report or strict result for the nine serving-hold methods. Their execution versus skips cannot be established from that run or JaCoCo coverage. The owning CI continuation therefore requires all nine cases through the existing strict JUnit verifier and captures their raw XML. Authenticated Account consumption, actual owner composition, release and activation remain unproved. + +Exact `673aaaf6eff34c3263964db9581bb8924982d398` [World CI job](https://github.com/benhook1013/FireMUD/actions/runs/37703041844/job/113071330638), against unchanged #3044 `59eb1d22ac3ec906a64d2db378c79f3353e263d3`, passed the full check and both named-case verification and raw XML capture steps. Artifact `11518603960` proves all nine `WorldCanonicalPlayerAdmissionHoldPostgresIntegrationTest` cases executed with zero skips, failures or errors, including concurrent acquisition, independent hold preservation, exact immutable readback, diagnostic expiry retention, V51 mutation/delete denial and stale REPEATABLE_READ/SERIALIZABLE rejection. This closes the physical PostgreSQL migration/race execution gap for this hold owner over explicitly synthetic upstream evidence; it does not prove live mTLS/database composition, current Account authority or admission. Other service jobs failed, so aggregate validation is not claimed green. Exact published #3044 `a36b152fdaf7f5bb5447094cd72718c66f7977de` [CI 37573659922](https://github.com/benhook1013/FireMUD/actions/runs/37573659922) executed all 196 World integration cases without skips, with three failures. The named PostgreSQL graph/application suite ran 51 cases with two failures; the operational-region suite ran three with one failure. The World checkout was synthetic merge `a9ada9077941141a1d3f8b315d1a0bb0cb1ae0f5`, with the exact #3041 base and published candidate as ordered parents and a head-identical tree. The `EXPECT_CLOSED` placement failure exposed V46's operation guard still accepting only `NO_PRIOR_POINTER` beneath V49's correctly typed location guard. Forward V50 preserves the earlier migrations and all other operation checks while permitting only the two explicit origins; new SQL negatives reject null and unknown origins. The actor/assignment reader correctly denied the changed full request before its later row check, so its fixture now expects that earlier stage and compares the unchanged journal and location rows. The operational-region trigger likewise correctly denied mutation, but its fixture expected jOOQ's exception instead of Spring's translated integrity exception; the corrected assertion retains all four tuple mutations. These corrections require fresh executed PostgreSQL proof and do not alter runtime activation gates. Game Session's unchanged retained-tenant suite and missing LOGIN capture, plus TCP's compiler heap exhaustion, remain separately owned aggregate failures. From 1335cc68790714dd903ebd0501bd2bad5d55e2f8 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 8 Oct 2026 14:50:35 +1300 Subject: [PATCH 4/8] Bind complete operational region assignments to World lifecycle evidence --- .../world-management-service/api-contracts.md | 2 + .../world-runtime-and-movement.md | 2 + ...rldCanonicalInstanceLifecycleEvidence.java | 86 +++++++- ...onicalInstanceLifecycleClientMtlsTest.java | 8 +- ...orldInstancePreparationClientMtlsTest.java | 8 +- ...WorldInstancePreparationGrpcCodecTest.java | 8 +- ...rldCanonicalInitialPlayerLocationTest.java | 8 +- ...anonicalInstanceLifecycleEvidenceTest.java | 141 +++++++++++- ...onicalPlayerAdmissionHoldEvidenceTest.java | 8 +- ...onWorldCanonicalLifecycleVerifierTest.java | 10 +- ...CanonicalInstanceActivationRepository.java | 3 +- ...onicalInstanceLifecycleReadRepository.java | 191 ++++++++++++++++- ...aphApplicationPostgresIntegrationTest.java | 200 +++++++++++++++++- ...anonicalPlayerLocationGrpcServiceTest.java | 5 +- 14 files changed, 649 insertions(+), 31 deletions(-) diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index d16a60e95e..e3b4584e7a 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -328,6 +328,8 @@ Fresh materialization requires actual Game Session `STARTING` evidence. An exact World assigns a separate opaque operational-region label when it first materializes a fresh runtime region, retaining it with the exact tenant/instance/World-row association. It is neither the private region row ID nor `canonical_region_instance_id`; exact retry retains the original label and an update cannot reassign its scope. Retained rows without proved assignment remain unassigned, not backfilled from numeric keys or templates. Game Session must authenticate and durably register the exact scoped World assignment before using it as its operational `regionId`; Game Session's durable region-status authority, not the World label, supplies the operational epoch and fence defined by the [Identifier Glossary](../../system-architecture-identifier-glossary.md#core-identifiers). Actor-specific placement still requires the separate authenticated World location read after genuine actor assignment. Neither region allocation nor lifecycle evidence establishes actor placement, initializes Redis, grants a lease or admits gameplay. +The source-qualified lifecycle carrier includes `operationalRegionAssignments`, the complete immutable map from canonical runtime region UUID to its separately allocated operational region UUID for that exact World materialization. World derives it from the actual scoped region rows and their retained topology identities in the same owner snapshot as the complete lifecycle evidence, checking the frozen graph/preparation identity and complete region count; a caller's partial list is not completeness evidence. Missing, duplicate, substituted, extra or unassigned rows deny the handoff. Canonical encoding and exact readback bind the complete assignment set to the existing canonical tenant/world/instance, playable namespace, capture, graph digest and preparation-input digest. The set remains unchanged across a valid `PREPARING` to initial `ACTIVE` transition and matching retry. It contains no operational epoch: Game Session must supply its separately authenticated durable initialization/readback before World can bind an initial causal component checkpoint; lifecycle epoch, queue claims and a requested causal floor cannot supply that proof. + `ReadWorldCanonicalInstanceLifecycle` is a separate read-only World-to-Game Session owner handoff. World authenticates the exact same-namespace Game Session workload, without end-user context, before decoding or accessing owner storage. The closed versioned request binds its distinct read UUID, workload namespace, canonical tenant/world/instance/Version, playable namespace and scope, public-production qualification, control-plane request, and expected descriptor request/result and full release-attestation digests. One World read-only snapshot resolves the instance through its persisted canonical association and joins the complete original launch binding, preparation and typed start-room materialization with the actual current lifecycle row. The response echoes the complete request and retains the full descriptor/release pair, authored `RoomTemplateRef`, separately scoped runtime room identity, capture and graph/input digests, lifecycle state, World lifecycle epoch and owner row version. Its runtime room identity, lifecycle epoch and row version use canonical decimal strings on the wire to preserve exact signed-64-bit values. Private World storage selectors are not exposed as request or lifecycle identities; retained provenance in the unchanged complete Game Design evidence cannot substitute for the World association. Missing, mismatched, receipt-less or ambiguous evidence is denied; a read never repairs history, chooses a room or authorizes admission. Game Session must compare the complete returned binding with its original launch evidence. A transition from a durably proved `PREPARING` result to the initial `ACTIVE` result requires the same association, source/release, capture, graph/input and selector/runtime-room evidence, exactly the next World lifecycle epoch and an advanced owner row version; Game Design's version-state epoch is a separate token. An exact same-state replay may retain its row version, but a later current read cannot regress it. A historical materialization result cannot be used as a current lifecycle result, and an authenticated lifecycle read does not replace current Account authority or the initial-admission hold and pointer commit below. This handoff does not itself enable an activation writer. diff --git a/design/project-management/implementation-tracking/world-runtime-and-movement.md b/design/project-management/implementation-tracking/world-runtime-and-movement.md index e3da727120..f13ee924e2 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for world runtime and movement. C ## Current Status +The #3084 continuation extends the existing closed lifecycle carrier with the complete canonical-runtime-region to operational-region assignment map, derived from the actual scoped materialization and frozen graph in the same World snapshot. Activation copies the unchanged map; shared codec tests cover immutable canonical encoding and incomplete/duplicate/substituted evidence. The new PostgreSQL definition covers corrupt retained assignment denial and exact recovery, and the existing preparation proof now forces real BIGINT region keys above the Java boxed-cache range. Local consolidated R13 passes full Common/World checks, generation, formatting, static analysis, World boot packaging and documentation checks in 2m7s. Reports contain 379 Common Platform Core, 166 Common Security and 531 World passing unit results, reused unchanged from preceding runs; four Game Session lifecycle-verifier fixture tests execute cleanly in R13. All 207 World integration definitions compile/discover but skip without Docker, including all 53 graph/application cases. The new assignment proof has not executed against PostgreSQL. Gameplay owns the actual receiver's full-map comparison and separately authenticated operational-region epoch/readback; no epoch or initial component checkpoint is inferred from this map. This does not enable preparation, activation, serving-hold release or admission. The [lifecycle owner contract](../../architecture/microservices/world-management-service/api-contracts.md#canonical-instance-activation-and-lifecycle-readback) remains authoritative. + The distinct player-admission serving-hold candidate builds on the preserved #3044 source. It reuses the unchanged Account lease carrier and the actual canonical association/lifecycle reader; its unregistered Account-workload-only owner records immutable acquisition/readback and a V51 lifecycle tuple fence. The same-value tuple update changes PostgreSQL's physical row version without changing logical state, lifecycle epoch, owner row-version counter or history. Current definitions cover exact retry, substitution, retained diagnostic expiry, independent holds, V51-specific mutation denial and stale REPEATABLE_READ/SERIALIZABLE rejection. Consolidated local Common/World formatting, full checks, static analysis, jOOQ generation, integration-source compilation, World boot JAR and documentation validation pass: 161 Common and 525 World unit cases executed without failures/errors/skips, while all 206 World integration cases skipped without Docker. The definitions and reused ACTIVE fixture stipulate upstream authority; those local checks do not establish physical migration or race execution, whose separate CI evidence follows below. Release has no accepting path until exact authenticated Account terminal and Game Session installation/cleanup producers exist. Protected Account acquire/finalize, current source/physical-COMMIT proof and Game Session pointer/catalog/runtime fencing remain separate gates. No transport registration, canonical termination producer or live admission is enabled. The target owner is [Player Admission Serving Hold](../../architecture/microservices/world-management-service/api-contracts.md#player-admission-serving-hold). The continuation moves the hold value into one closed Common Security carrier and adds an unregistered protected acquire/read adapter. It retains the original lease and complete World evidence, verifies exact workload identity before primitive parsing, and independently binds response correlation and original request scope. Five Common codec tests use real nested codecs over synthetic source fixtures; six adapter tests use explicitly mocked owner/lifecycle collaborators. The corrected full local gate passes after fixing two new SpotBugs issues without weakening guards: its reports contain 166 passing Common and 531 passing World unit cases, with all 206 integration cases skipped. The corrected gate reuses the unchanged Common test task and executes World tests; no duplicate fresh Common execution is claimed. Exact predecessor `fff09667c031b14aaa60002dd2c61f8ec99223ee` [World CI job](https://github.com/benhook1013/FireMUD/actions/runs/37700261172/job/113061857548) passed the full check and ran the integration task, but uploaded no JUnit report or strict result for the nine serving-hold methods. Their execution versus skips cannot be established from that run or JaCoCo coverage. The owning CI continuation therefore requires all nine cases through the existing strict JUnit verifier and captures their raw XML. Authenticated Account consumption, actual owner composition, release and activation remain unproved. diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidence.java index 62750d0aa0..6ad7be6478 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidence.java @@ -6,6 +6,8 @@ import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Base64; +import java.util.Collections; +import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; @@ -41,7 +43,8 @@ public record WorldCanonicalInstanceLifecycleEvidence( long rowVersion, UUID captureId, String graphSha256, - String preparationInputDigest) { + String preparationInputDigest, + Map operationalRegionAssignments) { public static final String SCHEMA = "world-canonical-instance-lifecycle-evidence/v1"; public static final String REQUEST_SCHEMA = "world-canonical-instance-lifecycle-read-request/v1"; @@ -60,7 +63,8 @@ public record WorldCanonicalInstanceLifecycleEvidence( "rowVersion", "captureId", "graphSha256", - "preparationInputDigest"); + "preparationInputDigest", + "operationalRegionAssignments"); private static final Set REQUEST_FIELDS = Set.of( "schemaVersion", @@ -108,9 +112,17 @@ public record WorldCanonicalInstanceLifecycleEvidence( requireNonNil(captureId, "captureId"); requireDigest(graphSha256, BARE_SHA256, "graphSha256"); requireDigest(preparationInputDigest, PREFIXED_SHA256, "preparationInputDigest"); + operationalRegionAssignments = + immutableOperationalRegionAssignments(operationalRegionAssignments); requireExactBinding(request, launchBinding, startLocation, graphSha256); } + /** Returns an immutable ordered copy without exposing the retained map representation. */ + @Override + public Map operationalRegionAssignments() { + return Collections.unmodifiableMap(new LinkedHashMap<>(operationalRegionAssignments)); + } + /** Closed canonical representation with the complete descriptor and separate attestation. */ public byte[] canonicalBytes() { Map value = new LinkedHashMap<>(); @@ -127,6 +139,9 @@ public byte[] canonicalBytes() { value.put("captureId", captureId.toString()); value.put("graphSha256", graphSha256); value.put("preparationInputDigest", preparationInputDigest); + value.put( + "operationalRegionAssignments", + operationalRegionAssignmentsJson(operationalRegionAssignments)); try { return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); } catch (IOException impossible) { @@ -158,7 +173,8 @@ public static WorldCanonicalInstanceLifecycleEvidence fromStored(byte[] stored) nonNegativeLong(text(root, "rowVersion"), "rowVersion"), parseUuid(text(root, "captureId"), "captureId"), text(root, "graphSha256"), - text(root, "preparationInputDigest")); + text(root, "preparationInputDigest"), + parseOperationalRegionAssignments(root.get("operationalRegionAssignments"))); if (!Arrays.equals(stored, evidence.canonicalBytes())) { throw new IllegalArgumentException("World canonical lifecycle evidence is not canonical"); } @@ -290,6 +306,70 @@ private static Map roomTemplateRefJson(RoomTemplateRef reference return value; } + private static Map operationalRegionAssignmentsJson(Map assignments) { + Map value = new LinkedHashMap<>(); + assignments.entrySet().stream() + .sorted((left, right) -> left.getKey().toString().compareTo(right.getKey().toString())) + .forEach(entry -> value.put(entry.getKey().toString(), entry.getValue().toString())); + return value; + } + + private static Map parseOperationalRegionAssignments(JsonNode node) { + if (node == null || !node.isObject() || node.size() == 0) { + throw new IllegalArgumentException("operationalRegionAssignments must be a nonempty object"); + } + Map assignments = new LinkedHashMap<>(); + node.propertyNames() + .forEach( + canonicalRegionId -> { + JsonNode operationalRegion = node.get(canonicalRegionId); + if (operationalRegion == null || !operationalRegion.isTextual()) { + throw new IllegalArgumentException( + "operationalRegionAssignments values must be canonical UUID strings"); + } + UUID canonical = parseUuid(canonicalRegionId, "operationalRegionAssignments key"); + UUID operational = + parseUuid(operationalRegion.textValue(), "operationalRegionAssignments value"); + if (assignments.putIfAbsent(canonical, operational) != null) { + throw new IllegalArgumentException( + "operationalRegionAssignments contains duplicate canonical region identities"); + } + }); + return immutableOperationalRegionAssignments(assignments); + } + + private static Map immutableOperationalRegionAssignments( + Map assignments) { + Objects.requireNonNull(assignments, "operationalRegionAssignments"); + if (assignments.isEmpty()) { + throw new IllegalArgumentException("operationalRegionAssignments must be nonempty"); + } + assignments.forEach( + (canonical, operational) -> { + requireNonNil(canonical, "operationalRegionAssignments canonical region ID"); + requireNonNil(operational, "operationalRegionAssignments operational region ID"); + }); + Map ordered = new LinkedHashMap<>(); + Set operationalIdentities = new HashSet<>(); + assignments.entrySet().stream() + .sorted((left, right) -> left.getKey().toString().compareTo(right.getKey().toString())) + .forEach( + entry -> { + UUID canonical = entry.getKey(); + UUID operational = entry.getValue(); + if (canonical.equals(operational)) { + throw new IllegalArgumentException( + "Canonical and operational region identities must be distinct"); + } + if (!operationalIdentities.add(operational)) { + throw new IllegalArgumentException( + "operationalRegionAssignments contains duplicate operational region identities"); + } + ordered.put(canonical, operational); + }); + return Collections.unmodifiableMap(ordered); + } + private static byte[] base64(JsonNode node, String field) { try { return Base64.getDecoder().decode(text(node, field)); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/WorldCanonicalInstanceLifecycleClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/WorldCanonicalInstanceLifecycleClientMtlsTest.java index 785ae148d6..682315cc0f 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/WorldCanonicalInstanceLifecycleClientMtlsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/WorldCanonicalInstanceLifecycleClientMtlsTest.java @@ -306,7 +306,10 @@ private static WorldCanonicalInstanceLifecycleEvidence evidence( WorldDraftStartLocationEvidence.fromStored(selector.selectorReceiptBytes()) .graphDigest() .substring("sha256:".length()), - "sha256:" + "e".repeat(64)); + "sha256:" + "e".repeat(64), + java.util.Map.of( + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"))); } private static WorldCanonicalInstanceLifecycleEvidence withRequest( @@ -322,7 +325,8 @@ private static WorldCanonicalInstanceLifecycleEvidence withRequest( evidence.rowVersion(), evidence.captureId(), evidence.graphSha256(), - evidence.preparationInputDigest()); + evidence.preparationInputDigest(), + evidence.operationalRegionAssignments()); } private static WorldCanonicalInstanceLifecycleEvidence.Request withReadRequestId( diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationClientMtlsTest.java index 335ae02d25..8d2326aea5 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationClientMtlsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationClientMtlsTest.java @@ -363,7 +363,8 @@ private static WorldCanonicalInstanceLifecycleEvidence withRequest( source.rowVersion(), source.captureId(), source.graphSha256(), - source.preparationInputDigest()); + source.preparationInputDigest(), + source.operationalRegionAssignments()); } private static WorldCanonicalInstanceLifecycleEvidence evidence() throws Exception { @@ -467,7 +468,10 @@ private static WorldCanonicalInstanceLifecycleEvidence evidence() throws Excepti ABOVE_JAVASCRIPT_INTEGER + 2, uuid("33333333-3333-4333-8333-333333333333"), selectorReceipt.graphDigest().substring("sha256:".length()), - "sha256:" + "e".repeat(64)); + "sha256:" + "e".repeat(64), + java.util.Map.of( + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"))); } private static UUID uuid(String value) { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationGrpcCodecTest.java index 0fef5a7497..19c79b3c44 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationGrpcCodecTest.java @@ -245,7 +245,8 @@ private static WorldCanonicalInstanceLifecycleEvidence withRequest( source.rowVersion(), source.captureId(), source.graphSha256(), - source.preparationInputDigest()); + source.preparationInputDigest(), + source.operationalRegionAssignments()); } private static WorldCanonicalInstanceLifecycleEvidence evidence() throws Exception { @@ -349,7 +350,10 @@ private static WorldCanonicalInstanceLifecycleEvidence evidence() throws Excepti ABOVE_JAVASCRIPT_INTEGER + 2, uuid("33333333-3333-4333-8333-333333333333"), selectorReceipt.graphDigest().substring("sha256:".length()), - "sha256:" + "e".repeat(64)); + "sha256:" + "e".repeat(64), + java.util.Map.of( + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"))); } private static UUID uuid(String value) { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInitialPlayerLocationTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInitialPlayerLocationTest.java index 52834eca69..a51415438a 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInitialPlayerLocationTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInitialPlayerLocationTest.java @@ -435,7 +435,10 @@ private static WorldCanonicalInstanceLifecycleEvidence genuineLifecycleEvidence( 0L, uuid("33333333-3333-4333-8333-333333333333"), selectorReceipt.graphDigest().substring("sha256:".length()), - "sha256:" + "e".repeat(64)); + "sha256:" + "e".repeat(64), + java.util.Map.of( + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"))); } private static WorldCanonicalInstanceLifecycleEvidence.Request copyLifecycleRequest( @@ -472,7 +475,8 @@ private static WorldCanonicalInstanceLifecycleEvidence copyLifecycle( source.rowVersion(), source.captureId(), source.graphSha256(), - source.preparationInputDigest()); + source.preparationInputDigest(), + source.operationalRegionAssignments()); } private static UUID uuid(String value) { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidenceTest.java index 62af4d0284..50f80d4687 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidenceTest.java @@ -7,6 +7,7 @@ import com.google.protobuf.UnknownFieldSet; import java.nio.charset.StandardCharsets; import java.util.List; +import java.util.Map; import java.util.UUID; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; @@ -37,6 +38,110 @@ void completeOwnerCaptureAndExactRequestEchoRoundTrip() throws Exception { assertThat(decoded.canonicalBytes()).containsExactly(expected.canonicalBytes()); assertThat(reread).isEqualTo(expected); assertThat(reread.hashCode()).isEqualTo(expected.hashCode()); + assertThat(reread.operationalRegionAssignments()) + .containsExactlyEntriesOf(expected.operationalRegionAssignments()); + } + + @Test + void rejectsMalformedOperationalRegionAssignmentMapsAndFreezesCallerInput() throws Exception { + WorldCanonicalInstanceLifecycleEvidence evidence = evidence(); + UUID canonicalRegionId = uuid("abcdefab-cdef-4abc-8def-abcdefabcdef"); + UUID operationalRegionId = uuid("22222222-2222-4222-8222-222222222222"); + Map mutableAssignments = new java.util.LinkedHashMap<>(); + mutableAssignments.put(canonicalRegionId, operationalRegionId); + var frozen = + new WorldCanonicalInstanceLifecycleEvidence( + evidence.request(), + evidence.launchBinding(), + evidence.startLocation(), + evidence.runtimeRoomInstanceId(), + evidence.lifecycleStatus(), + evidence.lifecycleEpoch(), + evidence.rowVersion(), + evidence.captureId(), + evidence.graphSha256(), + evidence.preparationInputDigest(), + mutableAssignments); + mutableAssignments.clear(); + assertThat(frozen.operationalRegionAssignments()) + .containsExactlyEntriesOf(Map.of(canonicalRegionId, operationalRegionId)); + assertThatThrownBy( + () -> frozen.operationalRegionAssignments().put(canonicalRegionId, operationalRegionId)) + .isInstanceOf(UnsupportedOperationException.class); + + UUID secondCanonicalRegionId = uuid("44444444-4444-4444-8444-444444444444"); + UUID secondOperationalRegionId = uuid("55555555-5555-4555-8555-555555555555"); + Map forward = new java.util.LinkedHashMap<>(); + forward.put(canonicalRegionId, operationalRegionId); + forward.put(secondCanonicalRegionId, secondOperationalRegionId); + Map reverse = new java.util.LinkedHashMap<>(); + reverse.put(secondCanonicalRegionId, secondOperationalRegionId); + reverse.put(canonicalRegionId, operationalRegionId); + assertThat(withAssignments(evidence, forward).canonicalBytes()) + .containsExactly(withAssignments(evidence, reverse).canonicalBytes()); + + String stored = new String(frozen.canonicalBytes(), StandardCharsets.UTF_8); + String assignmentField = + "\"operationalRegionAssignments\":{\"" + + canonicalRegionId + + "\":\"" + + operationalRegionId + + "\"}"; + assertThat(stored).contains(assignmentField); + String legacyShape = stored.replace("," + assignmentField, ""); + assertThatThrownBy( + () -> + WorldCanonicalInstanceLifecycleEvidence.fromStored( + legacyShape.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("missing or unsupported fields"); + assertInvalidStoredAssignments(stored, assignmentField, "{}", "nonempty"); + assertInvalidStoredAssignments( + stored, + assignmentField, + "{\"00000000-0000-0000-0000-000000000000\":\"" + operationalRegionId + "\"}", + "non-nil UUID"); + assertInvalidStoredAssignments( + stored, + assignmentField, + "{\"" + canonicalRegionId + "\":\"00000000-0000-0000-0000-000000000000\"}", + "non-nil UUID"); + assertInvalidStoredAssignments( + stored, + assignmentField, + "{\"" + canonicalRegionId + "\":\"" + canonicalRegionId + "\"}", + "must be distinct"); + assertInvalidStoredAssignments( + stored, + assignmentField, + "{\"" + canonicalRegionId.toString().toUpperCase() + "\":\"" + operationalRegionId + "\"}", + "canonical non-nil UUID"); + assertInvalidStoredAssignments( + stored, + assignmentField, + "{\"" + + canonicalRegionId + + "\":\"" + + operationalRegionId + + "\",\"" + + canonicalRegionId + + "\":\"" + + uuid("33333333-3333-4333-8333-333333333333") + + "\"}", + "invalid"); + assertInvalidStoredAssignments( + stored, + assignmentField, + "{\"" + + canonicalRegionId + + "\":\"" + + operationalRegionId + + "\",\"" + + uuid("44444444-4444-4444-8444-444444444444") + + "\":\"" + + operationalRegionId + + "\"}", + "duplicate operational region identities"); } @Test @@ -568,7 +673,8 @@ private static WorldCanonicalInstanceLifecycleEvidence with( rowVersion, captureId, graphSha256, - preparationInputDigest); + preparationInputDigest, + source.operationalRegionAssignments()); } private static Request copyRequest( @@ -713,7 +819,38 @@ private static WorldCanonicalInstanceLifecycleEvidence evidence() throws Excepti 0L, uuid("33333333-3333-4333-8333-333333333333"), selectorReceipt.graphDigest().substring("sha256:".length()), - "sha256:" + "e".repeat(64)); + "sha256:" + "e".repeat(64), + Map.of( + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"))); + } + + private static void assertInvalidStoredAssignments( + String stored, String assignmentField, String replacement, String message) { + String malformed = + stored.replace(assignmentField, "\"operationalRegionAssignments\":" + replacement); + assertThatThrownBy( + () -> + WorldCanonicalInstanceLifecycleEvidence.fromStored( + malformed.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(message); + } + + private static WorldCanonicalInstanceLifecycleEvidence withAssignments( + WorldCanonicalInstanceLifecycleEvidence source, Map assignments) { + return new WorldCanonicalInstanceLifecycleEvidence( + source.request(), + source.launchBinding(), + source.startLocation(), + source.runtimeRoomInstanceId(), + source.lifecycleStatus(), + source.lifecycleEpoch(), + source.rowVersion(), + source.captureId(), + source.graphSha256(), + source.preparationInputDigest(), + assignments); } private static UUID uuid(String value) { diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalPlayerAdmissionHoldEvidenceTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalPlayerAdmissionHoldEvidenceTest.java index f3e1e396a2..4970705c72 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalPlayerAdmissionHoldEvidenceTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalPlayerAdmissionHoldEvidenceTest.java @@ -127,7 +127,8 @@ void exactDecimalStringsPreserveHighAndMaximumLongsAndRejectEveryOtherShape() th value, world.captureId(), world.graphSha256(), - world.preparationInputDigest()); + world.preparationInputDigest(), + world.operationalRegionAssignments()); var precise = new WorldCanonicalPlayerAdmissionHoldEvidence( original.holdId(), @@ -323,7 +324,10 @@ private static WorldCanonicalInstanceLifecycleEvidence lifecycleEvidence() throw 0L, uuid("33333333-3333-4333-8333-333333333333"), selectorReceipt.graphDigest().substring("sha256:".length()), - "sha256:" + "e".repeat(64)); + "sha256:" + "e".repeat(64), + java.util.Map.of( + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"))); } static WorldPublishedStartLocationEvidence publishedSelector() throws Exception { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionWorldCanonicalLifecycleVerifierTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionWorldCanonicalLifecycleVerifierTest.java index 7ca97825e2..7aa748b824 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionWorldCanonicalLifecycleVerifierTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionWorldCanonicalLifecycleVerifierTest.java @@ -709,7 +709,10 @@ private static Fixture fixture(String status, long epoch, long rowVersion, UUID WorldDraftStartLocationEvidence.fromStored(selector.selectorReceiptBytes()) .graphDigest() .substring("sha256:".length()), - "sha256:" + "e".repeat(64)); + "sha256:" + "e".repeat(64), + java.util.Map.of( + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"))); return new Fixture( new GameSessionWorldCanonicalLifecycleVerifier.Expected(request, binding), evidence); } @@ -816,9 +819,8 @@ private static WorldCanonicalInstanceLifecycleEvidence withEvidence( rowVersion, captureId == null ? original.captureId() : captureId, graphSha256 == null ? original.graphSha256() : graphSha256, - preparationInputDigest == null - ? original.preparationInputDigest() - : preparationInputDigest); + preparationInputDigest == null ? original.preparationInputDigest() : preparationInputDigest, + original.operationalRegionAssignments()); } private static WorldCanonicalInstanceLifecycleEvidence.Request withReadRequestId( diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationRepository.java index 061af36d89..74d5c02b8a 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationRepository.java @@ -214,7 +214,8 @@ private static WorldCanonicalInstanceLifecycleEvidence nextActiveEvidence( Math.addExact(request.expectedRowVersion(), 1L), current.captureId(), current.graphSha256(), - current.preparationInputDigest()); + current.preparationInputDigest(), + current.operationalRegionAssignments()); } private void requireReadOnlyRepeatableReadTransaction() { 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 3a1bfddf66..07560e5121 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 @@ -5,7 +5,10 @@ import java.security.NoSuchAlgorithmException; import java.sql.Connection; import java.util.Arrays; +import java.util.HashSet; import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; @@ -169,6 +172,10 @@ private WorldCanonicalInstanceLifecycleEvidence readMaterialized( JsonNode input = parseInput(inputJson); requireInputIdentity(input, request, association, captureId); requirePreparationCounts(input, preparation); + Set expectedRegionTemplates = + requireFrozenGraphIdentity(input, preparation, graphBytes, graphSha256); + Map operationalRegionAssignments = + readOperationalRegionAssignments(association, preparation, expectedRegionTemplates); var release = association.completeLaunchBinding().evidence().releaseAttestation(); if (release.schemaVersion() @@ -207,7 +214,8 @@ private WorldCanonicalInstanceLifecycleEvidence readMaterialized( required(lifecycle, "row_version", Long.class), captureId, graphSha256, - inputDigest); + inputDigest, + operationalRegionAssignments); } catch (InvalidLifecycleEvidenceException invalid) { throw invalid; } catch (TransientDataAccessException | DataAccessException unavailable) { @@ -349,6 +357,167 @@ private void requirePreparationCounts(JsonNode input, Record preparation) { } } + /** Proves the preparation graph is the immutable graph retained by the exact frozen capture. */ + private Set requireFrozenGraphIdentity( + JsonNode input, Record preparation, byte[] graphBytes, String graphSha256) { + JsonNode topology = requiredObject(input, "topology"); + UUID captureId = required(preparation, "capture_id", UUID.class); + Record frozen = + dsl.fetchOne( + "SELECT capture_id,request_id,commit_id,version_identity_operation_id,publication_fence," + + "graph_bytes,graph_sha256,capture_status FROM world_canonical_frozen_topology " + + "WHERE capture_id=?", + captureId); + if (frozen == null + || !captureId.equals(required(frozen, "capture_id", UUID.class)) + || !"CAPTURED_UNVERIFIED".equals(required(frozen, "capture_status", String.class)) + || !Arrays.equals(graphBytes, required(frozen, "graph_bytes", byte[].class)) + || !graphSha256.equals(required(frozen, "graph_sha256", String.class)) + || !HexFormat.of().formatHex(sha256(graphBytes)).equals(graphSha256)) { + throw invalid("Canonical preparation graph differs from its exact frozen capture"); + } + requireText(topology, "requestId", required(frozen, "request_id", UUID.class).toString()); + requireText(topology, "commitId", required(frozen, "commit_id", UUID.class).toString()); + requireText( + topology, + "versionIdentityOperationId", + required(frozen, "version_identity_operation_id", UUID.class).toString()); + requireText( + topology, "publicationFence", required(frozen, "publication_fence", UUID.class).toString()); + + try { + JsonNode graph = CLOSED_JSON.readTree(graphBytes); + requireFields( + graph, + Set.of("schemaVersion", "canonicalTenantId", "canonicalVersionId", "rows"), + "Frozen canonical graph"); + requireText(graph, "schemaVersion", "2"); + requireText( + graph, "canonicalTenantId", text(requiredObject(input, "identity"), "canonicalTenantId")); + requireText(graph, "canonicalVersionId", text(topology, "canonicalVersionId")); + JsonNode rows = graph.get("rows"); + if (rows == null || !rows.isArray()) { + throw invalid("Frozen canonical graph rows must be an array"); + } + Map expectedCounts = + Map.of( + "REGION", intValue(topology, "regionCount"), + "ZONE", intValue(topology, "zoneCount"), + "ROOM", intValue(topology, "roomCount"), + "ROOM_EXIT", intValue(topology, "exitCount"), + "GENERATION_RULE", intValue(topology, "generationRuleCount"), + "WORLD_ENTITY_SPAWN_BINDING", intValue(topology, "spawnBindingCount")); + Map actualCounts = new java.util.HashMap<>(); + Set graphIdentities = new HashSet<>(); + Set expectedRegionTemplates = new HashSet<>(); + for (JsonNode row : rows) { + JsonNode mapping = requiredObject(row, "mapping"); + String family = text(mapping, "family"); + String templateText = text(mapping, "template_id"); + UUID templateId = parseCanonicalUuid(templateText, "Frozen graph template_id"); + if (!expectedCounts.containsKey(family) + || !graphIdentities.add(family + ":" + templateId)) { + throw invalid("Frozen canonical graph has an unsupported or duplicate identity"); + } + actualCounts.merge(family, 1, Integer::sum); + if ("REGION".equals(family) && !expectedRegionTemplates.add(templateId)) { + throw invalid("Frozen canonical graph repeats a REGION template identity"); + } + } + if (expectedCounts.entrySet().stream() + .anyMatch( + entry -> + actualCounts.getOrDefault(entry.getKey(), 0).intValue() + != entry.getValue().intValue()) + || rows.size() != expectedCounts.values().stream().mapToInt(Integer::intValue).sum() + || expectedRegionTemplates.size() + != required(preparation, "region_count", Integer.class)) { + throw invalid("Frozen canonical graph family counts differ from exact preparation input"); + } + return Set.copyOf(expectedRegionTemplates); + } catch (tools.jackson.core.JacksonException malformed) { + throw new InvalidLifecycleEvidenceException("Frozen canonical graph is invalid", malformed); + } + } + + /** + * Reads every scoped region row together with its REGION topology identity in this same owner + * snapshot. The immutable graph's template set and persisted materialization count must match + * exactly before World exposes the canonical-runtime UUID to operational-label assignments. + */ + private Map readOperationalRegionAssignments( + WorldCanonicalInstanceAssociation association, + Record preparation, + Set expectedRegionTemplates) { + long worldInstanceId = association.worldInstanceId(); + long tenantKey = association.worldPrepareFields().privateTenantKey(); + long gameInstanceKey = association.worldPrepareFields().privateGameInstanceKey(); + int expectedCount = required(preparation, "region_count", Integer.class); + if (expectedCount <= 0 || expectedRegionTemplates.size() != expectedCount) { + throw invalid("Canonical World region count differs from its frozen graph"); + } + var rows = + dsl.fetch( + "SELECT m.id AS mapping_id,m.world_instance_id AS mapping_world_instance_id," + + "m.canonical_game_instance_id AS mapping_game_instance_id,m.family AS mapping_family," + + "m.template_id AS mapping_template_id,m.runtime_row_id AS mapping_runtime_row_id," + + "m.runtime_identity AS mapping_runtime_identity,ri.id AS region_row_id," + + "ri.world_instance_id AS region_world_instance_id,ri.tenant_id AS region_tenant_key," + + "ri.game_instance_id AS region_game_instance_key," + + "ri.canonical_region_instance_id,ri.operational_region_id " + + "FROM world_canonical_instance_topology_identity m FULL OUTER JOIN region_instance ri " + + "ON m.family='REGION' AND m.runtime_row_id=ri.id " + + "WHERE (m.world_instance_id=? AND m.family='REGION') OR ri.world_instance_id=? " + + "OR (ri.tenant_id=? AND ri.game_instance_id=?)", + worldInstanceId, + worldInstanceId, + tenantKey, + gameInstanceKey); + if (rows.size() != expectedCount) { + throw invalid("Canonical World REGION materialization has missing or extra retained rows"); + } + Map assignments = new LinkedHashMap<>(); + Set seenTemplates = new HashSet<>(); + Set seenOperationalIds = new HashSet<>(); + for (Record row : rows) { + Long mappingId = row.get("mapping_id", Long.class); + Long regionRowId = row.get("region_row_id", Long.class); + if (mappingId == null || regionRowId == null) { + throw invalid( + "Canonical World REGION row lacks its exact topology identity or runtime row"); + } + if (!"REGION".equals(required(row, "mapping_family", String.class)) + || required(row, "mapping_world_instance_id", Long.class) != worldInstanceId + || !association + .identity() + .canonicalGameInstanceId() + .equals(required(row, "mapping_game_instance_id", UUID.class)) + || required(row, "mapping_runtime_row_id", Long.class).longValue() + != regionRowId.longValue() + || required(row, "region_world_instance_id", Long.class) != worldInstanceId + || required(row, "region_tenant_key", Long.class) != tenantKey + || required(row, "region_game_instance_key", Long.class) != gameInstanceKey) { + throw invalid("Canonical World REGION row differs from its exact instance scope"); + } + UUID templateId = required(row, "mapping_template_id", UUID.class); + UUID canonicalRegionId = required(row, "canonical_region_instance_id", UUID.class); + UUID mappedCanonicalRegionId = required(row, "mapping_runtime_identity", UUID.class); + UUID operationalRegionId = required(row, "operational_region_id", UUID.class); + if (!expectedRegionTemplates.contains(templateId) + || !seenTemplates.add(templateId) + || !canonicalRegionId.equals(mappedCanonicalRegionId) + || canonicalRegionId.equals(operationalRegionId) + || !seenOperationalIds.add(operationalRegionId) + || assignments.putIfAbsent(canonicalRegionId, operationalRegionId) != null) { + throw invalid("Canonical World REGION assignment is duplicate or differs from its graph"); + } + } + if (!seenTemplates.equals(expectedRegionTemplates) || assignments.size() != expectedCount) { + throw invalid("Canonical World REGION assignments do not completely cover the frozen graph"); + } + return assignments; + } + private void requireOriginalSelector( WorldPublishedStartLocationEvidence selector, WorldDraftStartLocationEvidence receipt, @@ -575,6 +744,26 @@ private static JsonNode requiredObject(JsonNode parent, String field) { return value; } + private static String text(JsonNode parent, String field) { + JsonNode value = parent == null ? null : parent.get(field); + if (value == null || !value.isTextual() || value.textValue().isBlank()) { + throw invalid("Retained World preparation " + field + " is missing"); + } + return value.textValue(); + } + + private static UUID parseCanonicalUuid(String value, String label) { + try { + UUID parsed = UUID.fromString(value); + if (parsed.equals(new UUID(0L, 0L)) || !parsed.toString().equals(value)) { + throw invalid(label + " must be a canonical non-nil UUID"); + } + return parsed; + } catch (IllegalArgumentException malformed) { + throw invalid(label + " must be a canonical non-nil UUID"); + } + } + private static void requireText(JsonNode parent, String field, String expected) { JsonNode value = parent.get(field); if (value == null || !value.isTextual() || !expected.equals(value.textValue())) { diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java index c3e25942fe..4ab452099f 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java @@ -343,6 +343,11 @@ void releaseSelectorMaterializesItsOriginalRoomAndExactlyRetriesWithSeparateRunt @Test void authenticatedPreparationAdapterBindsFreshLaunchAndReadsActualPreparingLifecycle() throws Exception { + // Advance only this isolated fixture's allocator; do not rely on test order to escape Java's + // boxed-Long cache or fabricate a topology mapping for the regression below. + dsl.fetchValue( + "SELECT setval('region_instance_id_seq', GREATEST(last_value, 128), true) " + + "FROM region_instance_id_seq"); Fixture f = fixture(); var original = application(generationFreePlan(f)); var selectedRoom = @@ -470,6 +475,9 @@ void authenticatedPreparationAdapterBindsFreshLaunchAndReadsActualPreparingLifec assertThat(firstLifecycleRequest).isEqualTo(expectedFirstLifecycleRequest); var firstActualLifecycle = lifecycleRepository.read(firstLifecycleRequest).orElseThrow(); assertThat(firstLifecycle).isEqualTo(firstActualLifecycle); + assertThat(firstLifecycle.operationalRegionAssignments()) + .containsExactlyEntriesOf( + materializedOperationalRegionAssignments(ownerRequest.gameInstanceUuid())); assertThat(firstLifecycle.lifecycleStatus()).isEqualTo("PREPARING"); assertThat(firstLifecycle.lifecycleEpoch()).isEqualTo(1L); assertThat(firstLifecycle.launchBinding()).isEqualTo(evidence); @@ -511,6 +519,9 @@ void authenticatedPreparationAdapterBindsFreshLaunchAndReadsActualPreparingLifec .isEqualTo(materializedRegion.get("room_region_instance_id", Long.class)); assertThat(materializedRegion.get("region_row_id", Long.class)) .isEqualTo(materializedRegion.get("zone_region_instance_id", Long.class)); + // Exercise the lifecycle reader against PostgreSQL's actual BIGINT key outside the + // boxed-Long cache range; the read above must match this persisted topology mapping. + assertThat(materializedRegion.get("region_row_id", Long.class)).isGreaterThan(127L); assertThat(materializedRegion.get("zone_row_id", Long.class)) .isEqualTo(materializedRegion.get("room_zone_instance_id", Long.class)); String retainedOperationalRegionRow = @@ -1193,6 +1204,118 @@ private void insertPublicationTerminal(WorldPublicationTerminal.Request request) request.releaseContentBytes()); } + @Test + void canonicalLifecycleReadRejectsIncompleteOrSubstitutedRegionAssignments() { + PreparedLifecycleFixture fixture = materializedLifecycleFixture(); + var firstRegion = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT ri.id AS region_row_id,ri.tenant_id,ri.game_instance_id,ri.world_instance_id," + + "ri.shard_id,ri.name,ri.weather,ri.generation_seed,ri.generator_type," + + "ri.generator_params,ri.spacing_multiplier,ri.version," + + "ri.canonical_region_instance_id,ri.operational_region_id," + + "m.id AS mapping_id,m.canonical_game_instance_id,m.family,m.template_id," + + "m.template_private_row_key,m.runtime_row_id,m.runtime_identity," + + "m.runtime_room_instance_id " + + "FROM region_instance ri JOIN world_canonical_instance_topology_identity m " + + "ON m.runtime_row_id=ri.id AND m.family='REGION' " + + "WHERE m.canonical_game_instance_id=? ORDER BY m.template_id LIMIT 1", + fixture.input().canonicalGameInstanceId())); + long regionRowId = required(firstRegion, "region_row_id", Long.class); + long mappingId = required(firstRegion, "mapping_id", Long.class); + UUID originalOperationalId = required(firstRegion, "operational_region_id", UUID.class); + UUID originalRuntimeIdentity = required(firstRegion, "runtime_identity", UUID.class); + + mutateWithUserTriggersDisabled( + "region_instance", + () -> + dsl.execute( + "UPDATE region_instance SET operational_region_id=NULL WHERE id=?", regionRowId)); + assertThatThrownBy(() -> fixture.lifecycleRepository().read(fixture.readRequest())) + .isInstanceOf( + WorldCanonicalInstanceLifecycleReadRepository.InvalidLifecycleEvidenceException.class); + mutateWithUserTriggersDisabled( + "region_instance", + () -> + dsl.execute( + "UPDATE region_instance SET operational_region_id=? WHERE id=?", + originalOperationalId, + regionRowId)); + + UUID substitutedRuntimeIdentity = UUID.randomUUID(); + mutateWithUserTriggersDisabled( + "world_canonical_instance_topology_identity", + () -> + dsl.execute( + "UPDATE world_canonical_instance_topology_identity SET runtime_identity=? WHERE id=?", + substitutedRuntimeIdentity, + mappingId)); + assertThatThrownBy(() -> fixture.lifecycleRepository().read(fixture.readRequest())) + .isInstanceOf( + WorldCanonicalInstanceLifecycleReadRepository.InvalidLifecycleEvidenceException.class); + mutateWithUserTriggersDisabled( + "world_canonical_instance_topology_identity", + () -> + dsl.execute( + "UPDATE world_canonical_instance_topology_identity SET runtime_identity=? WHERE id=?", + originalRuntimeIdentity, + mappingId)); + + mutateWithUserTriggersDisabled( + "world_canonical_instance_topology_identity", + () -> + dsl.execute( + "DELETE FROM world_canonical_instance_topology_identity WHERE id=?", mappingId)); + assertThatThrownBy(() -> fixture.lifecycleRepository().read(fixture.readRequest())) + .isInstanceOf( + WorldCanonicalInstanceLifecycleReadRepository.InvalidLifecycleEvidenceException.class); + mutateWithUserTriggersDisabled( + "world_canonical_instance_topology_identity", + () -> + dsl.execute( + "INSERT INTO world_canonical_instance_topology_identity " + + "(world_instance_id,canonical_game_instance_id,family,template_id," + + "template_private_row_key,runtime_row_id,runtime_identity,runtime_room_instance_id) " + + "VALUES (?,?, 'REGION', ?,?,?,?,NULL)", + required(firstRegion, "world_instance_id", Long.class), + required(firstRegion, "canonical_game_instance_id", UUID.class), + required(firstRegion, "template_id", UUID.class), + required(firstRegion, "template_private_row_key", Long.class), + required(firstRegion, "runtime_row_id", Long.class), + originalRuntimeIdentity)); + + UUID extraCanonicalId = UUID.randomUUID(); + UUID extraOperationalId = UUID.randomUUID(); + while (extraCanonicalId.equals(extraOperationalId)) { + extraOperationalId = UUID.randomUUID(); + } + final UUID finalExtraOperationalId = extraOperationalId; + Record extraRegion = + queryWithUserTriggersDisabled( + "region_instance", + () -> + dsl.fetchOne( + "INSERT INTO region_instance " + + "(tenant_id,game_instance_id,world_instance_id,shard_id,name,weather," + + "generation_seed,generator_type,generator_params,spacing_multiplier,version," + + "canonical_region_instance_id,operational_region_id) " + + "SELECT tenant_id,game_instance_id,world_instance_id,shard_id,name,weather," + + "generation_seed,generator_type,generator_params,spacing_multiplier,version,?,? " + + "FROM region_instance WHERE id=? RETURNING id", + extraCanonicalId, + finalExtraOperationalId, + regionRowId)); + long extraRegionRowId = required(extraRegion, "id", Long.class); + assertThatThrownBy(() -> fixture.lifecycleRepository().read(fixture.readRequest())) + .isInstanceOf( + WorldCanonicalInstanceLifecycleReadRepository.InvalidLifecycleEvidenceException.class); + mutateWithUserTriggersDisabled( + "region_instance", + () -> dsl.execute("DELETE FROM region_instance WHERE id=?", extraRegionRowId)); + assertThat(fixture.lifecycleRepository().read(fixture.readRequest()).orElseThrow()) + .isEqualTo(fixture.preparing()); + } + @Test void lifecycleReadPreservesPreparingStateAndDeniesLegacyNumericFailureWithExactCanonicalServiceEcho() { @@ -1229,6 +1352,9 @@ private void insertPublicationTerminal(WorldPublicationTerminal.Request request) .startLocation()); assertThat(preparing.startLocation().roomTemplateId()).isEqualTo(roomTemplateId); assertThat(preparing.runtimeRoomInstanceId()).isEqualTo(materialized.runtimeRoomInstanceId()); + assertThat(preparing.operationalRegionAssignments()) + .containsExactlyEntriesOf( + materializedOperationalRegionAssignments(input.canonicalGameInstanceId())); var mappedRoomOwnership = Objects.requireNonNull( dsl.fetchOne( @@ -1503,6 +1629,10 @@ void canonicalActivationCommitsOneOwnerCasAndReplaysWhileLegacyTerminationIsDeni assertThat(active.lifecycleStatus()).isEqualTo("ACTIVE"); assertThat(active.lifecycleEpoch()).isEqualTo(committed.lifecycleEvidence().lifecycleEpoch()); assertThat(active.rowVersion()).isEqualTo(committed.lifecycleEvidence().rowVersion()); + assertThat(active.operationalRegionAssignments()) + .containsExactlyEntriesOf(fixture.preparing().operationalRegionAssignments()); + assertThat(committed.lifecycleEvidence().operationalRegionAssignments()) + .containsExactlyEntriesOf(fixture.preparing().operationalRegionAssignments()); assertThat(activationManifestCount(fixture.input().canonicalGameInstanceId())).isZero(); var repository = @@ -1524,7 +1654,8 @@ void canonicalActivationCommitsOneOwnerCasAndReplaysWhileLegacyTerminationIsDeni fixture.preparing().rowVersion() + 1L, fixture.preparing().captureId(), fixture.preparing().graphSha256(), - fixture.preparing().preparationInputDigest()); + fixture.preparing().preparationInputDigest(), + fixture.preparing().operationalRegionAssignments()); var changedRetry = new WorldCanonicalInstanceActivation.Request( committed.request().activationRequestId(), changedExpectedVersion); @@ -1694,7 +1825,8 @@ void canonicalActivationTransportRequiresGameSessionAndReplaysImmutableOwnerResu fixture.preparing().rowVersion() + 1L, fixture.preparing().captureId(), fixture.preparing().graphSha256(), - fixture.preparing().preparationInputDigest()); + fixture.preparing().preparationInputDigest(), + fixture.preparing().operationalRegionAssignments()); // Reusing the same operation ID with a changed normalized expected version is a conflict // probe, not evidence that the persisted PREPARING row had that version. var changedRequest = @@ -2450,7 +2582,8 @@ void currentInitialPlayerLocationReadDeniesChangedActorScopeOrAssignment() { fixture.activeEvidence().rowVersion(), fixture.activeEvidence().captureId(), fixture.activeEvidence().graphSha256(), - fixture.activeEvidence().preparationInputDigest()); + fixture.activeEvidence().preparationInputDigest(), + fixture.activeEvidence().operationalRegionAssignments()); var changedScope = initialLocationRequest( fixture, @@ -2492,7 +2625,8 @@ void currentInitialPlayerLocationReadDeniesStaleLifecycleOrSubstitutedRoomMappin active.rowVersion(), active.captureId(), active.graphSha256(), - active.preparationInputDigest()); + active.preparationInputDigest(), + active.operationalRegionAssignments()); var staleRequest = initialLocationRequest( fixture, @@ -2516,7 +2650,8 @@ void currentInitialPlayerLocationReadDeniesStaleLifecycleOrSubstitutedRoomMappin active.rowVersion(), active.captureId(), active.graphSha256(), - active.preparationInputDigest()); + active.preparationInputDigest(), + active.operationalRegionAssignments()); var changedRoomRequest = initialLocationRequest( fixture, @@ -2892,7 +3027,8 @@ void changedCanonicalScopeOrRuntimeRoomEvidenceDeniesBeforePlacementWrites() { active.rowVersion(), active.captureId(), active.graphSha256(), - active.preparationInputDigest())) + active.preparationInputDigest(), + active.operationalRegionAssignments())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("ROOM selector or graph digest differs"); var original = active.request(); @@ -2923,7 +3059,8 @@ void changedCanonicalScopeOrRuntimeRoomEvidenceDeniesBeforePlacementWrites() { active.rowVersion(), active.captureId(), active.graphSha256(), - active.preparationInputDigest()); + active.preparationInputDigest(), + active.operationalRegionAssignments()); var wrongScopeRequest = initialLocationRequest( fixture, @@ -2947,7 +3084,8 @@ void changedCanonicalScopeOrRuntimeRoomEvidenceDeniesBeforePlacementWrites() { active.rowVersion(), active.captureId(), active.graphSha256(), - active.preparationInputDigest()); + active.preparationInputDigest(), + active.operationalRegionAssignments()); var wrongRuntimeRequest = initialLocationRequest( fixture, @@ -4613,7 +4751,8 @@ private ActivationProof rawCommittedActivationProof(PreparedLifecycleFixture fix fixture.preparing().rowVersion() + 1L, fixture.preparing().captureId(), fixture.preparing().graphSha256(), - fixture.preparing().preparationInputDigest()); + fixture.preparing().preparationInputDigest(), + fixture.preparing().operationalRegionAssignments()); return new ActivationProof( request, new WorldCanonicalInstanceActivation.Result( @@ -4756,6 +4895,49 @@ private org.jooq.Record materializedOperationalRegionRow( regionTemplateId)); } + private Map materializedOperationalRegionAssignments(UUID canonicalGameInstanceId) { + var rows = + dsl.fetch( + "SELECT ri.canonical_region_instance_id,ri.operational_region_id " + + "FROM world_canonical_instance_preparation p " + + "JOIN region_instance ri ON ri.world_instance_id=p.world_instance_id " + + "WHERE p.canonical_game_instance_id=? " + + "ORDER BY ri.canonical_region_instance_id", + canonicalGameInstanceId); + Map assignments = new LinkedHashMap<>(); + for (Record row : rows) { + UUID canonical = row.get("canonical_region_instance_id", UUID.class); + UUID operational = row.get("operational_region_id", UUID.class); + assertThat(canonical).isNotNull(); + assertThat(operational).isNotNull().isNotEqualTo(canonical); + assertThat(assignments.putIfAbsent(canonical, operational)).isNull(); + } + return assignments; + } + + private void mutateWithUserTriggersDisabled(String table, Runnable mutation) { + dsl.execute("ALTER TABLE " + table + " DISABLE TRIGGER USER"); + try { + mutation.run(); + } finally { + dsl.execute("ALTER TABLE " + table + " ENABLE TRIGGER USER"); + } + } + + private Record queryWithUserTriggersDisabled( + String table, java.util.function.Supplier mutation) { + dsl.execute("ALTER TABLE " + table + " DISABLE TRIGGER USER"); + try { + return mutation.get(); + } finally { + dsl.execute("ALTER TABLE " + table + " ENABLE TRIGGER USER"); + } + } + + private static T required(Record row, String field, Class type) { + return Objects.requireNonNull(row.get(field, type), "Persisted " + field + " is null"); + } + private PrepareCanonicalWorldInstanceResponse invokePreparationAsGameSession( WorldCanonicalInstancePreparationGrpcService adapter, net.firedevops.firemud.worldmanagement.v1.PrepareCanonicalWorldInstanceRequest request) { diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerLocationGrpcServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerLocationGrpcServiceTest.java index 913c52a58c..18cf8d7f90 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerLocationGrpcServiceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerLocationGrpcServiceTest.java @@ -871,7 +871,10 @@ private static WorldCanonicalInstanceLifecycleEvidence lifecycleEvidence( 0L, uuid("33333333-3333-4333-8333-333333333333"), selectorReceipt.graphDigest().substring("sha256:".length()), - "sha256:" + "e".repeat(64)); + "sha256:" + "e".repeat(64), + java.util.Map.of( + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"))); } private static WorldPublishedStartLocationEvidence publishedSelector(String namespace) From d723a4a91f688a11e380de6884cf273e19bd9cf5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 8 Oct 2026 15:24:39 +1300 Subject: [PATCH 5/8] Align World activation SQL with complete region lifecycle evidence --- .../world-management-service/api-contracts.md | 2 +- .../world-runtime-and-movement.md | 4 +- ...al_activation_complete_region_evidence.sql | 108 ++++++++++++++++++ ...aphApplicationPostgresIntegrationTest.java | 96 ++++++++++++++++ 4 files changed, 208 insertions(+), 2 deletions(-) create mode 100644 services/world-management-service/src/main/resources/db/migration/V52__canonical_activation_complete_region_evidence.sql diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index e3b4584e7a..4568ab43b0 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -328,7 +328,7 @@ Fresh materialization requires actual Game Session `STARTING` evidence. An exact World assigns a separate opaque operational-region label when it first materializes a fresh runtime region, retaining it with the exact tenant/instance/World-row association. It is neither the private region row ID nor `canonical_region_instance_id`; exact retry retains the original label and an update cannot reassign its scope. Retained rows without proved assignment remain unassigned, not backfilled from numeric keys or templates. Game Session must authenticate and durably register the exact scoped World assignment before using it as its operational `regionId`; Game Session's durable region-status authority, not the World label, supplies the operational epoch and fence defined by the [Identifier Glossary](../../system-architecture-identifier-glossary.md#core-identifiers). Actor-specific placement still requires the separate authenticated World location read after genuine actor assignment. Neither region allocation nor lifecycle evidence establishes actor placement, initializes Redis, grants a lease or admits gameplay. -The source-qualified lifecycle carrier includes `operationalRegionAssignments`, the complete immutable map from canonical runtime region UUID to its separately allocated operational region UUID for that exact World materialization. World derives it from the actual scoped region rows and their retained topology identities in the same owner snapshot as the complete lifecycle evidence, checking the frozen graph/preparation identity and complete region count; a caller's partial list is not completeness evidence. Missing, duplicate, substituted, extra or unassigned rows deny the handoff. Canonical encoding and exact readback bind the complete assignment set to the existing canonical tenant/world/instance, playable namespace, capture, graph digest and preparation-input digest. The set remains unchanged across a valid `PREPARING` to initial `ACTIVE` transition and matching retry. It contains no operational epoch: Game Session must supply its separately authenticated durable initialization/readback before World can bind an initial causal component checkpoint; lifecycle epoch, queue claims and a requested causal floor cannot supply that proof. +The source-qualified lifecycle carrier includes `operationalRegionAssignments`, the complete immutable map from canonical runtime region UUID to its separately allocated operational region UUID for that exact World materialization. World derives it from the actual scoped region rows and their retained topology identities in the same owner snapshot as the complete lifecycle evidence, checking the frozen graph/preparation identity and complete region count; a caller's partial list is not completeness evidence. Missing, duplicate, substituted, extra or unassigned rows deny the handoff. Canonical encoding and exact readback bind the complete assignment set to the existing canonical tenant/world/instance, playable namespace, capture, graph digest and preparation-input digest. The set remains unchanged across a valid `PREPARING` to initial `ACTIVE` transition and matching retry. The activation SQL guard also verifies the complete assignment map against the exact persisted scoped REGION materialization before retaining the operation; accepting the expanded carrier must not relax the existing lifecycle CAS, authenticated owner proof or serving-hold predicates. It contains no operational epoch: Game Session must supply its separately authenticated durable initialization/readback before World can bind an initial causal component checkpoint; lifecycle epoch, queue claims and a requested causal floor cannot supply that proof. `ReadWorldCanonicalInstanceLifecycle` is a separate read-only World-to-Game Session owner handoff. World authenticates the exact same-namespace Game Session workload, without end-user context, before decoding or accessing owner storage. The closed versioned request binds its distinct read UUID, workload namespace, canonical tenant/world/instance/Version, playable namespace and scope, public-production qualification, control-plane request, and expected descriptor request/result and full release-attestation digests. One World read-only snapshot resolves the instance through its persisted canonical association and joins the complete original launch binding, preparation and typed start-room materialization with the actual current lifecycle row. The response echoes the complete request and retains the full descriptor/release pair, authored `RoomTemplateRef`, separately scoped runtime room identity, capture and graph/input digests, lifecycle state, World lifecycle epoch and owner row version. Its runtime room identity, lifecycle epoch and row version use canonical decimal strings on the wire to preserve exact signed-64-bit values. Private World storage selectors are not exposed as request or lifecycle identities; retained provenance in the unchanged complete Game Design evidence cannot substitute for the World association. Missing, mismatched, receipt-less or ambiguous evidence is denied; a read never repairs history, chooses a room or authorizes admission. diff --git a/design/project-management/implementation-tracking/world-runtime-and-movement.md b/design/project-management/implementation-tracking/world-runtime-and-movement.md index f13ee924e2..1092677ba4 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -6,7 +6,9 @@ This is a non-normative implementation tracker for world runtime and movement. C ## Current Status -The #3084 continuation extends the existing closed lifecycle carrier with the complete canonical-runtime-region to operational-region assignment map, derived from the actual scoped materialization and frozen graph in the same World snapshot. Activation copies the unchanged map; shared codec tests cover immutable canonical encoding and incomplete/duplicate/substituted evidence. The new PostgreSQL definition covers corrupt retained assignment denial and exact recovery, and the existing preparation proof now forces real BIGINT region keys above the Java boxed-cache range. Local consolidated R13 passes full Common/World checks, generation, formatting, static analysis, World boot packaging and documentation checks in 2m7s. Reports contain 379 Common Platform Core, 166 Common Security and 531 World passing unit results, reused unchanged from preceding runs; four Game Session lifecycle-verifier fixture tests execute cleanly in R13. All 207 World integration definitions compile/discover but skip without Docker, including all 53 graph/application cases. The new assignment proof has not executed against PostgreSQL. Gameplay owns the actual receiver's full-map comparison and separately authenticated operational-region epoch/readback; no epoch or initial component checkpoint is inferred from this map. This does not enable preparation, activation, serving-hold release or admission. The [lifecycle owner contract](../../architecture/microservices/world-management-service/api-contracts.md#canonical-instance-activation-and-lifecycle-readback) remains authoritative. +Exact `1335cc68790714dd903ebd0501bd2bad5d55e2f8` [World CI job](https://github.com/benhook1013/FireMUD/actions/runs/37714931038/job/113109207975) fails: all 53 graph/application cases execute with 22 failures and no skips/errors; all nine serving-hold cases execute with nine failures and no skips/errors. The runner merge `50ea680602c98e695621bb62f229fe165d7917d7` has the exact base/head parents and the source head's tree. V43's three closed lifecycle-object checks still expect eleven fields, while the complete assignment carrier has twelve; all nine hold cases fail in the shared activation fixture before their hold assertions. The forward V52 correction preserves historical migration checksums, all inherited activation/hold predicates and function grants, accepts the complete twelve-field shape, and verifies its entire assignment map against the exact persisted REGION materialization and preparation count. A new raw-SQL PostgreSQL definition rejects missing, extra and substituted assignments without changing lifecycle or recording an activation result. Corrected local R15 passes full World checks, generation, formatting, static analysis, integration compilation, boot packaging and documentation checks in 1m20s: 531 unit cases execute cleanly, while all 208 integration cases skip without Docker. The 54 graph definitions and nine hold definitions are compiled, not physical success. New exact-head PostgreSQL proof is required; executed predecessor failures are not successful serving-hold proof. + +The #3084 continuation extends the existing closed lifecycle carrier with the complete canonical-runtime-region to operational-region assignment map, derived from the actual scoped materialization and frozen graph in the same World snapshot. Activation copies the unchanged map; shared codec tests cover immutable canonical encoding and incomplete/duplicate/substituted evidence. The new PostgreSQL definition covers corrupt retained assignment denial and exact recovery, and the existing preparation proof now forces real BIGINT region keys above the Java boxed-cache range. Local consolidated R13 passes full Common/World checks, generation, formatting, static analysis, World boot packaging and documentation checks in 2m7s. Reports contain 379 Common Platform Core, 166 Common Security and 531 World passing unit results, reused unchanged from preceding runs; four Game Session lifecycle-verifier fixture tests execute cleanly in R13. All 207 World integration definitions compile/discover but skip without Docker, including all 53 graph/application cases. The first exact-head execution and its activation guard failures are recorded above; this earlier local gate supplied no PostgreSQL proof. Gameplay owns the actual receiver's full-map comparison and separately authenticated operational-region epoch/readback; no epoch or initial component checkpoint is inferred from this map. This does not enable preparation, activation, serving-hold release or admission. The [lifecycle owner contract](../../architecture/microservices/world-management-service/api-contracts.md#canonical-instance-activation-and-lifecycle-readback) remains authoritative. The distinct player-admission serving-hold candidate builds on the preserved #3044 source. It reuses the unchanged Account lease carrier and the actual canonical association/lifecycle reader; its unregistered Account-workload-only owner records immutable acquisition/readback and a V51 lifecycle tuple fence. The same-value tuple update changes PostgreSQL's physical row version without changing logical state, lifecycle epoch, owner row-version counter or history. Current definitions cover exact retry, substitution, retained diagnostic expiry, independent holds, V51-specific mutation denial and stale REPEATABLE_READ/SERIALIZABLE rejection. Consolidated local Common/World formatting, full checks, static analysis, jOOQ generation, integration-source compilation, World boot JAR and documentation validation pass: 161 Common and 525 World unit cases executed without failures/errors/skips, while all 206 World integration cases skipped without Docker. The definitions and reused ACTIVE fixture stipulate upstream authority; those local checks do not establish physical migration or race execution, whose separate CI evidence follows below. Release has no accepting path until exact authenticated Account terminal and Game Session installation/cleanup producers exist. Protected Account acquire/finalize, current source/physical-COMMIT proof and Game Session pointer/catalog/runtime fencing remain separate gates. No transport registration, canonical termination producer or live admission is enabled. The target owner is [Player Admission Serving Hold](../../architecture/microservices/world-management-service/api-contracts.md#player-admission-serving-hold). diff --git a/services/world-management-service/src/main/resources/db/migration/V52__canonical_activation_complete_region_evidence.sql b/services/world-management-service/src/main/resources/db/migration/V52__canonical_activation_complete_region_evidence.sql new file mode 100644 index 0000000000..1b93267ce6 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V52__canonical_activation_complete_region_evidence.sql @@ -0,0 +1,108 @@ +-- Extend V43's canonical activation proof to retain and validate the complete operational REGION +-- assignment map added to WorldCanonicalInstanceLifecycleEvidence. +-- [jooq ignore start] +DO $migration$ +DECLARE + definition TEXT; + original_oid OID; + original_acl ACLITEM[]; + old_fragment TEXT; + new_fragment TEXT; + anchor TEXT; + replacement TEXT; +BEGIN + SELECT p.oid, p.proacl + INTO STRICT original_oid, original_acl + FROM pg_proc p + WHERE p.oid = '"${serviceSchema}".world_validate_canonical_activation_operation()'::REGPROCEDURE; + SELECT pg_get_functiondef( + '"${serviceSchema}".world_validate_canonical_activation_operation()'::REGPROCEDURE) + INTO STRICT definition; + + old_fragment := '(SELECT count(*) FROM jsonb_object_keys(preparing)) <> 11'; + new_fragment := '(SELECT count(*) FROM jsonb_object_keys(preparing)) <> 12'; + IF (length(definition)-length(replace(definition, old_fragment, '')))/length(old_fragment) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one closed PREPARING lifecycle object count in V43 activation guard'; + END IF; + definition := replace(definition, old_fragment, new_fragment); + + old_fragment := '(SELECT count(*) FROM jsonb_object_keys(normalized_request->''preparingEvidence'')) <> 11'; + new_fragment := '(SELECT count(*) FROM jsonb_object_keys(normalized_request->''preparingEvidence'')) <> 12'; + IF (length(definition)-length(replace(definition, old_fragment, '')))/length(old_fragment) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one closed normalized PREPARING lifecycle object count in V43 activation guard'; + END IF; + definition := replace(definition, old_fragment, new_fragment); + + old_fragment := '(SELECT count(*) FROM jsonb_object_keys(lifecycle)) <> 11'; + new_fragment := '(SELECT count(*) FROM jsonb_object_keys(lifecycle)) <> 12'; + IF (length(definition)-length(replace(definition, old_fragment, '')))/length(old_fragment) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one closed result lifecycle object count in V43 activation guard'; + END IF; + definition := replace(definition, old_fragment, new_fragment); + + anchor := $$ IF jsonb_typeof(result) IS DISTINCT FROM 'object'$$; + IF (length(definition)-length(replace(definition, anchor, '')))/length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one result-evidence validation anchor in V43 activation guard'; + END IF; + replacement := $replacement$ IF NOT EXISTS ( + SELECT 1 + FROM "${serviceSchema}".world_canonical_instance_association a + JOIN "${serviceSchema}".world_canonical_instance_preparation p + ON p.canonical_game_instance_id=a.canonical_game_instance_id + CROSS JOIN LATERAL ( + SELECT count(*) AS row_count, + count(*) FILTER (WHERE m.id IS NULL OR ri.id IS NULL + OR m.world_instance_id IS DISTINCT FROM a.world_instance_id + OR m.canonical_game_instance_id IS DISTINCT FROM a.canonical_game_instance_id + OR m.family IS DISTINCT FROM 'REGION' + OR m.runtime_row_id IS DISTINCT FROM ri.id + OR ri.world_instance_id IS DISTINCT FROM a.world_instance_id + OR ri.tenant_id IS DISTINCT FROM a.local_tenant_key + OR ri.game_instance_id IS DISTINCT FROM a.private_game_instance_key + OR m.runtime_identity IS NULL + OR m.runtime_identity = '00000000-0000-0000-0000-000000000000'::UUID + OR ri.canonical_region_instance_id IS DISTINCT FROM m.runtime_identity + OR ri.operational_region_id IS NULL + OR ri.operational_region_id = '00000000-0000-0000-0000-000000000000'::UUID + OR ri.operational_region_id = m.runtime_identity) AS invalid_count, + count(DISTINCT m.runtime_identity) AS canonical_identity_count, + count(DISTINCT ri.operational_region_id) AS operational_identity_count, + jsonb_object_agg(m.runtime_identity::TEXT, ri.operational_region_id::TEXT) + FILTER (WHERE m.runtime_identity IS NOT NULL AND ri.operational_region_id IS NOT NULL) + AS assignment_map + FROM "${serviceSchema}".world_canonical_instance_topology_identity m + FULL OUTER JOIN "${serviceSchema}".region_instance ri + ON m.family='REGION' AND m.runtime_row_id=ri.id + WHERE (m.world_instance_id=a.world_instance_id AND m.family='REGION') + OR ri.world_instance_id=a.world_instance_id + OR (ri.tenant_id=a.local_tenant_key AND ri.game_instance_id=a.private_game_instance_key) + ) scoped_regions + WHERE a.canonical_game_instance_id=NEW.canonical_game_instance_id + AND a.world_instance_id=NEW.world_instance_id + AND p.region_count > 0 + AND p.region_count=scoped_regions.row_count + AND scoped_regions.row_count=scoped_regions.canonical_identity_count + AND scoped_regions.row_count=scoped_regions.operational_identity_count + AND scoped_regions.invalid_count=0 + AND jsonb_typeof(preparing->'operationalRegionAssignments')='object' + AND CASE WHEN jsonb_typeof(preparing->'operationalRegionAssignments')='object' + THEN (SELECT count(*) FROM jsonb_object_keys(preparing->'operationalRegionAssignments')) + ELSE -1 END = p.region_count + AND scoped_regions.assignment_map=preparing->'operationalRegionAssignments' + ) THEN + RAISE EXCEPTION 'Canonical activation lifecycle evidence lacks the exact complete operational REGION assignment map' + USING ERRCODE = '23514'; + END IF; + IF jsonb_typeof(result) IS DISTINCT FROM 'object'$replacement$; + definition := replace(definition, anchor, replacement); + + EXECUTE definition; + IF '"${serviceSchema}".world_validate_canonical_activation_operation()'::REGPROCEDURE + IS DISTINCT FROM original_oid + OR (SELECT p.proacl FROM pg_proc p WHERE p.oid = original_oid) + IS DISTINCT FROM original_acl THEN + RAISE EXCEPTION 'Canonical activation guard replacement changed function identity or grants'; + END IF; +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java index 4ab452099f..5ece4edd87 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java @@ -1695,6 +1695,67 @@ void canonicalActivationCommitsOneOwnerCasAndReplaysWhileLegacyTerminationIsDeni assertOrigin(); } + @Test + void canonicalActivationRawSqlRejectsIncompleteOrSubstitutedOperationalRegionAssignments() { + PreparedLifecycleFixture fixture = materializedLifecycleFixture(); + var assignments = fixture.preparing().operationalRegionAssignments(); + assertThat(assignments).hasSizeGreaterThan(1); + var first = assignments.entrySet().iterator().next(); + + Map missing = new LinkedHashMap<>(assignments); + missing.remove(first.getKey()); + Map extra = new LinkedHashMap<>(assignments); + UUID extraCanonicalId = UUID.randomUUID(); + while (assignments.containsKey(extraCanonicalId) + || assignments.containsValue(extraCanonicalId)) { + extraCanonicalId = UUID.randomUUID(); + } + UUID extraOperationalId = UUID.randomUUID(); + while (assignments.containsKey(extraOperationalId) + || assignments.containsValue(extraOperationalId) + || extraCanonicalId.equals(extraOperationalId)) { + extraOperationalId = UUID.randomUUID(); + } + extra.put(extraCanonicalId, extraOperationalId); + Map substituted = new LinkedHashMap<>(assignments); + UUID substitutedOperationalId = UUID.randomUUID(); + while (assignments.containsKey(substitutedOperationalId) + || assignments.containsValue(substitutedOperationalId) + || first.getKey().equals(substitutedOperationalId)) { + substitutedOperationalId = UUID.randomUUID(); + } + substituted.put(first.getKey(), substitutedOperationalId); + + ownerTransaction() + .execute( + status -> { + int index = 0; + for (Map invalidAssignments : List.of(missing, extra, substituted)) { + var proof = rawCommittedActivationProofWithAssignments(fixture, invalidAssignments); + String savepoint = "invalid_activation_region_map_" + index++; + dsl.execute("SAVEPOINT " + savepoint); + assertThatThrownBy( + () -> + insertRawActivationOperation( + proof, fixture.materialized().association().worldInstanceId())) + .hasMessageContaining("exact complete operational REGION assignment map"); + dsl.execute("ROLLBACK TO SAVEPOINT " + savepoint); + assertThat( + activationOperationCountForRequest(proof.request().activationRequestId())) + .isZero(); + assertThat(activationManifestCountForRequest(proof.request().activationRequestId())) + .isZero(); + } + return null; + }); + + var retained = fixture.lifecycleRepository().read(fixture.readRequest()).orElseThrow(); + assertThat(retained.lifecycleStatus()).isEqualTo("PREPARING"); + assertThat(retained.operationalRegionAssignments()).containsExactlyEntriesOf(assignments); + assertThat(activationManifestCount(fixture.input().canonicalGameInstanceId())).isZero(); + assertOrigin(); + } + @Test void canonicalActivationTransportRequiresGameSessionAndReplaysImmutableOwnerResult() throws Exception { @@ -4759,6 +4820,41 @@ private ActivationProof rawCommittedActivationProof(PreparedLifecycleFixture fix request, WorldCanonicalInstanceActivation.Outcome.COMMITTED, null, predictedActive)); } + private ActivationProof rawCommittedActivationProofWithAssignments( + PreparedLifecycleFixture fixture, Map assignments) { + var preparing = + new WorldCanonicalInstanceLifecycleEvidence( + fixture.preparing().request(), + fixture.preparing().launchBinding(), + fixture.preparing().startLocation(), + fixture.preparing().runtimeRoomInstanceId(), + "PREPARING", + fixture.preparing().lifecycleEpoch(), + fixture.preparing().rowVersion(), + fixture.preparing().captureId(), + fixture.preparing().graphSha256(), + fixture.preparing().preparationInputDigest(), + assignments); + var request = new WorldCanonicalInstanceActivation.Request(UUID.randomUUID(), preparing); + var active = + new WorldCanonicalInstanceLifecycleEvidence( + preparing.request(), + preparing.launchBinding(), + preparing.startLocation(), + preparing.runtimeRoomInstanceId(), + "ACTIVE", + preparing.lifecycleEpoch() + 1L, + preparing.rowVersion() + 1L, + preparing.captureId(), + preparing.graphSha256(), + preparing.preparationInputDigest(), + assignments); + return new ActivationProof( + request, + new WorldCanonicalInstanceActivation.Result( + request, WorldCanonicalInstanceActivation.Outcome.COMMITTED, null, active)); + } + private void insertRawActivationOperation(ActivationProof proof, long worldInstanceId) { var request = proof.request(); var result = proof.result(); From 09d6c163df96ef64afa6ae2585e68e4ec5ae7bd6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 8 Oct 2026 15:53:30 +1300 Subject: [PATCH 6/8] World: prove region map denial with genuine single-region fixture --- .../implementation-tracking/world-runtime-and-movement.md | 2 ++ ...WorldDraftGraphApplicationPostgresIntegrationTest.java | 8 +++++++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/design/project-management/implementation-tracking/world-runtime-and-movement.md b/design/project-management/implementation-tracking/world-runtime-and-movement.md index 1092677ba4..dfbd3a70c4 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for world runtime and movement. C ## Current Status +Exact `d723a4a91f688a11e380de6884cf273e19bd9cf5` [World CI job](https://github.com/benhook1013/FireMUD/actions/runs/37717741597/job/113118122004) physically executes all nine serving-hold cases cleanly and all 54 graph/application cases with one failure, no skips or errors. Checkout `e43db7aa88fe3ada4656ac25ff82a49520035352` has exact base/head parents; its tree equals the source head. Forward V52 removes the prior eleven-versus-twelve-field activation rejection without weakening the persisted-map predicate. The sole failure is the newly added raw-SQL negative fixture's assumption that materialization has more than one region; its genuine fixture has one. The bounded correction keeps that actual one-region source and all three guard/no-mutation assertions: the missing canonical assignment is replaced by an unknown canonical key while retaining its original operational value, so a valid nonempty closed carrier reaches the SQL predicate. Extra and substituted operational assignments remain separate cases. Corrected local R17 full World check, formatting, integration compilation, packaging and documentation checks pass in 45s; unchanged 531-unit results are reused and all 208 integration cases skip without Docker. New exact-head PostgreSQL execution of this fixture correction remains required. This physical component proof stipulates upstream owner authority; it is not admission, authenticated end-to-end composition or an initial causal component checkpoint. + Exact `1335cc68790714dd903ebd0501bd2bad5d55e2f8` [World CI job](https://github.com/benhook1013/FireMUD/actions/runs/37714931038/job/113109207975) fails: all 53 graph/application cases execute with 22 failures and no skips/errors; all nine serving-hold cases execute with nine failures and no skips/errors. The runner merge `50ea680602c98e695621bb62f229fe165d7917d7` has the exact base/head parents and the source head's tree. V43's three closed lifecycle-object checks still expect eleven fields, while the complete assignment carrier has twelve; all nine hold cases fail in the shared activation fixture before their hold assertions. The forward V52 correction preserves historical migration checksums, all inherited activation/hold predicates and function grants, accepts the complete twelve-field shape, and verifies its entire assignment map against the exact persisted REGION materialization and preparation count. A new raw-SQL PostgreSQL definition rejects missing, extra and substituted assignments without changing lifecycle or recording an activation result. Corrected local R15 passes full World checks, generation, formatting, static analysis, integration compilation, boot packaging and documentation checks in 1m20s: 531 unit cases execute cleanly, while all 208 integration cases skip without Docker. The 54 graph definitions and nine hold definitions are compiled, not physical success. New exact-head PostgreSQL proof is required; executed predecessor failures are not successful serving-hold proof. The #3084 continuation extends the existing closed lifecycle carrier with the complete canonical-runtime-region to operational-region assignment map, derived from the actual scoped materialization and frozen graph in the same World snapshot. Activation copies the unchanged map; shared codec tests cover immutable canonical encoding and incomplete/duplicate/substituted evidence. The new PostgreSQL definition covers corrupt retained assignment denial and exact recovery, and the existing preparation proof now forces real BIGINT region keys above the Java boxed-cache range. Local consolidated R13 passes full Common/World checks, generation, formatting, static analysis, World boot packaging and documentation checks in 2m7s. Reports contain 379 Common Platform Core, 166 Common Security and 531 World passing unit results, reused unchanged from preceding runs; four Game Session lifecycle-verifier fixture tests execute cleanly in R13. All 207 World integration definitions compile/discover but skip without Docker, including all 53 graph/application cases. The first exact-head execution and its activation guard failures are recorded above; this earlier local gate supplied no PostgreSQL proof. Gameplay owns the actual receiver's full-map comparison and separately authenticated operational-region epoch/readback; no epoch or initial component checkpoint is inferred from this map. This does not enable preparation, activation, serving-hold release or admission. The [lifecycle owner contract](../../architecture/microservices/world-management-service/api-contracts.md#canonical-instance-activation-and-lifecycle-readback) remains authoritative. diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java index 5ece4edd87..85aa460b6e 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java @@ -1699,11 +1699,17 @@ void canonicalActivationCommitsOneOwnerCasAndReplaysWhileLegacyTerminationIsDeni void canonicalActivationRawSqlRejectsIncompleteOrSubstitutedOperationalRegionAssignments() { PreparedLifecycleFixture fixture = materializedLifecycleFixture(); var assignments = fixture.preparing().operationalRegionAssignments(); - assertThat(assignments).hasSizeGreaterThan(1); + assertThat(assignments).isNotEmpty().hasSize(1); var first = assignments.entrySet().iterator().next(); Map missing = new LinkedHashMap<>(assignments); missing.remove(first.getKey()); + UUID missingCanonicalId = UUID.randomUUID(); + while (assignments.containsKey(missingCanonicalId) + || assignments.containsValue(missingCanonicalId)) { + missingCanonicalId = UUID.randomUUID(); + } + missing.put(missingCanonicalId, first.getValue()); Map extra = new LinkedHashMap<>(assignments); UUID extraCanonicalId = UUID.randomUUID(); while (assignments.containsKey(extraCanonicalId) From 4db094cc2ed418b595475122abe56fd6f7dbdd09 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 8 Oct 2026 16:44:28 +1300 Subject: [PATCH 7/8] Expose immutable published World spawn requirements to Entity --- .github/workflows/ci.yml | 3 + .../world-management-service/api-contracts.md | 10 + .../world-runtime-and-movement.md | 4 + .../world_published_spawn_requirements.proto | 67 +++ ...WorldPublishedSpawnRequirementsClient.java | 182 +++++++ ...rldPublishedSpawnRequirementsEvidence.java | 341 ++++++++++++ ...ldPublishedSpawnRequirementsGrpcCodec.java | 322 ++++++++++++ ...lishedSpawnRequirementsClientMtlsTest.java | 493 ++++++++++++++++++ ...dPublishedSpawnRequirementsClientTest.java | 38 ++ ...ublishedSpawnRequirementsEvidenceTest.java | 90 ++++ ...blishedSpawnRequirementsGrpcCodecTest.java | 443 ++++++++++++++++ ...orldCanonicalFrozenTopologyRepository.java | 31 +- .../WorldDraftGraphApplicationRepository.java | 27 + ...ishedSpawnRequirementsReadGrpcService.java | 61 +++ ...ldPublishedSpawnRequirementsReadOwner.java | 334 ++++++++++++ ...WorldPublishedStartLocationRepository.java | 40 +- ...aphApplicationPostgresIntegrationTest.java | 225 ++++++++ .../WorldPublishedSourceSnapshotReadTest.java | 88 ++++ ...dSpawnRequirementsReadGrpcServiceTest.java | 74 +++ ...blishedSpawnRequirementsReadOwnerTest.java | 476 +++++++++++++++++ 20 files changed, 3341 insertions(+), 8 deletions(-) create mode 100644 protos/world-management/v1/world_published_spawn_requirements.proto create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsGrpcCodec.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsClientMtlsTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsClientTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsEvidenceTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsGrpcCodecTest.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadGrpcService.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadOwner.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSourceSnapshotReadTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadGrpcServiceTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadOwnerTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f2944bc81a..c3af25ef2b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2344,6 +2344,9 @@ jobs: --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#selectorPreparationLateFenceLossRollsBackSelectorRuntimeAndAssociationTogether()' \ --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#v41MaterializedV1HistoryRemainsByteExactAndRetryableAfterV42WithoutSelectorPromotion()' \ --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#publishedSelectorJoinsExactFrozenCheckpointToOriginalAppliedWithoutWrites()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#publishedSelectorOwnedReadUsesOneActualReadOnlyRepeatableReadSnapshot()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#publishedSpawnRequirementsOwnerProjectsOnlyRealFrozenAndAppliedSource()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#publishedSpawnRequirementsOwnerPreservesExplicitZeroOptionalFamilies()' \ --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#permissionUnverifiedGraphAndFrozenHistoryCannotSupplyPublishedSelector()' \ --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#freshApplicationRetainsCompleteExactGraphAndOriginalAccountReadbackAndRetriesAfterFreeze()' \ --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#explicitEmptyOptionalFamiliesProduceAppliedGraphAndExactTypedStartSelector()' \ diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 4568ab43b0..d8e71b66a4 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -318,6 +318,16 @@ The retained graph/2 payload preserves World's original UTF-8 owner serializatio The initial generation-free path may use explicitly authored empty optional families only when that complete World owner input and committed readback prove them; missing rows alone do not prove emptiness. Present generation or spawn intent retains its existing preparation gates. This selector neither manufactures an actor nor changes `PRESEEDED_ONLY`: Entity's genuine owner-assigned actor and namespace-qualified ownership proof remain separate. Implementation, executed owner proof and activation limits belong to the [World tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#current-status). +## Published Spawn-Requirement Source Read + +`WorldPublishedSpawnRequirementsReadService.ReadWorldPublishedSpawnRequirements` is a distinct immutable content read for the verified same-namespace Entity workload, without end-user context. It does not reuse the Game Design-only published-selector method's permission. The closed versioned request binds the target namespace, a distinct non-nil read UUID, the complete immutable Game Design launch-binding read selector and expected release-attestation digest. World independently authenticates Game Design and verifies its exact complete descriptor/release pair; caller-supplied release bytes are not producer authority. + +World derives the publication selection from that verified pair, then reads its exact frozen topology and original Account-authorized APPLIED application in one owned read-only REPEATABLE_READ snapshot. It compares the complete retained World selection, selector receipt and graph against the release binding before projecting content. This source exists before runtime instance materialization: requiring PREPARING or ACTIVE would create a circular dependency for the Entity materializer. Missing or conflicting frozen, APPLIED or release evidence denies the read; it never repairs history or treats absent rows as an empty family. + +The response echoes the complete request and binds the verified immutable launch/release pair, capture UUID and exact graph digest to the explicit ordered six-family declaration, including zero counts. It carries every original spawn binding in original order with its canonical authored binding/revision identity, `RoomTemplateRef`, complete typed Entity tenant/version/template reference, exact spawn count and respawn delay. It also preserves every generation-rule intent with its canonical scope and unchanged authored name/value. Counts must agree with the complete original source. Private numeric storage keys, actor assignments, runtime room IDs, region epochs and causal floors are not derived or exported as canonical identities. + +Entity separately proves its published definition payloads, version association and applied-commit/digest evidence; a World reference is not that proof. This read grants no generation execution, materialization, region registration, initial causal checkpoint, activation or admission authority. The adapter remains unregistered until its authenticated producer, consumer, same-snapshot and negative proofs pass. Executed versus unrun proof belongs in the [World tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#current-status). + ## Canonical Instance Activation and Lifecycle Readback Canonical preparation verifies Game Design's exact [authored-source-bound launch descriptor and its separately authenticated full release attestation](../game-design-service/api-contracts.md#authored-source-bound-launch-descriptor-and-exact-readback), then retains and reads back both together with the World lifecycle result before reporting `PREPARING`. World rejects either missing item and any swapped or mismatched pair, including disagreement in descriptor/source identity, canonical tenant/world scope, canonical UUID version, resolved release, or required release evidence. An exact retry returns the originally retained pair and lifecycle result; it cannot replace either item with newer owner state. The existing currentness and authorization checks still apply, and the pair and `PREPARING` result commit through the existing atomic workflow. A source selector receipt does not replace release attestation, and a private source key does not establish a World tenant association. Game Design's version-state epoch remains distinct from this owner's lifecycle epoch; descriptor recovery alone does not prove current ACTIVE eligibility. The separate closed evidence and exact authenticated read are owned by [Game Design's release-attestation contract](../game-design-service/api-contracts.md#separate-complete-release-attestation-evidence); World must retain both components rather than extending descriptor v1 or accepting descriptor-only fallback. Producer, consumer, local retention and negative runtime proof remain activation gates. diff --git a/design/project-management/implementation-tracking/world-runtime-and-movement.md b/design/project-management/implementation-tracking/world-runtime-and-movement.md index dfbd3a70c4..1a9ee910ef 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -6,6 +6,10 @@ This is a non-normative implementation tracker for world runtime and movement. C ## Current Status +Exact `09d6c163df96ef64afa6ae2585e68e4ec5ae7bd6` [World CI job](https://github.com/benhook1013/FireMUD/actions/runs/37720089984/job/113125620495) succeeds. Raw JUnit results prove all 54 graph/application and nine serving-hold PostgreSQL cases executed with zero skips, failures or errors, including the corrected missing/extra/substituted operational-assignment negative. Checkout `f5c40a3ce9fb5674ee8d3832e748614efd29e24a` has the exact base/head parents and tree `6eef2a659acd8fa308d9d5637fdf05a369f7e278`, identical to the source head. This supersedes the fixture failure below, but the upstream authority remains explicit component evidence rather than genuine authenticated multi-owner composition or admission. + +The continuation implements the separate [published spawn-requirement source read](../../architecture/microservices/world-management-service/api-contracts.md#published-spawn-requirement-source-read): a closed shared carrier, same-namespace Entity-only unregistered adapter, independent Game Design complete-release read, and an owned read-only REPEATABLE_READ join of the original frozen topology and Account-authorized APPLIED journals. It projects the original ordered family declaration, typed spawn references and generation intent before PREPARING, without allocating runtime or Entity identities. An explicitly constructed file-backed Entity client verifies the exact World peer before releasing request metadata or body. Corrected consolidated R24 passes full Core/World checks, formatting, static analysis, integration compilation, World boot packaging and documentation checks in 1m36s. World executes 545 unit cases cleanly; 391 Core outcomes, including four physical client socket cases, are retained from the preceding corrected Core execution. The socket owner is an explicit transport double, not the database source. All 211 World integration cases skip locally without Docker, including three new actual-journal snapshot/projection definitions required by CI. Fixture import and narrowly scoped generated-protobuf immutability annotation corrections preserve all guards and assertions. Entity's definition payload/applied-commit producer, physical execution of this new boundary, complete authenticated consumer proof, initial causal checkpoints and activation remain separate open obligations. + Exact `d723a4a91f688a11e380de6884cf273e19bd9cf5` [World CI job](https://github.com/benhook1013/FireMUD/actions/runs/37717741597/job/113118122004) physically executes all nine serving-hold cases cleanly and all 54 graph/application cases with one failure, no skips or errors. Checkout `e43db7aa88fe3ada4656ac25ff82a49520035352` has exact base/head parents; its tree equals the source head. Forward V52 removes the prior eleven-versus-twelve-field activation rejection without weakening the persisted-map predicate. The sole failure is the newly added raw-SQL negative fixture's assumption that materialization has more than one region; its genuine fixture has one. The bounded correction keeps that actual one-region source and all three guard/no-mutation assertions: the missing canonical assignment is replaced by an unknown canonical key while retaining its original operational value, so a valid nonempty closed carrier reaches the SQL predicate. Extra and substituted operational assignments remain separate cases. Corrected local R17 full World check, formatting, integration compilation, packaging and documentation checks pass in 45s; unchanged 531-unit results are reused and all 208 integration cases skip without Docker. New exact-head PostgreSQL execution of this fixture correction remains required. This physical component proof stipulates upstream owner authority; it is not admission, authenticated end-to-end composition or an initial causal component checkpoint. Exact `1335cc68790714dd903ebd0501bd2bad5d55e2f8` [World CI job](https://github.com/benhook1013/FireMUD/actions/runs/37714931038/job/113109207975) fails: all 53 graph/application cases execute with 22 failures and no skips/errors; all nine serving-hold cases execute with nine failures and no skips/errors. The runner merge `50ea680602c98e695621bb62f229fe165d7917d7` has the exact base/head parents and the source head's tree. V43's three closed lifecycle-object checks still expect eleven fields, while the complete assignment carrier has twelve; all nine hold cases fail in the shared activation fixture before their hold assertions. The forward V52 correction preserves historical migration checksums, all inherited activation/hold predicates and function grants, accepts the complete twelve-field shape, and verifies its entire assignment map against the exact persisted REGION materialization and preparation count. A new raw-SQL PostgreSQL definition rejects missing, extra and substituted assignments without changing lifecycle or recording an activation result. Corrected local R15 passes full World checks, generation, formatting, static analysis, integration compilation, boot packaging and documentation checks in 1m20s: 531 unit cases execute cleanly, while all 208 integration cases skip without Docker. The 54 graph definitions and nine hold definitions are compiled, not physical success. New exact-head PostgreSQL proof is required; executed predecessor failures are not successful serving-hold proof. diff --git a/protos/world-management/v1/world_published_spawn_requirements.proto b/protos/world-management/v1/world_published_spawn_requirements.proto new file mode 100644 index 0000000000..382f8c06bc --- /dev/null +++ b/protos/world-management/v1/world_published_spawn_requirements.proto @@ -0,0 +1,67 @@ +syntax = "proto3"; + +package world_management.v1; + +import "game-design/v1/game_design_service.proto"; +import "shared/v1/errors.proto"; +import "world-management/v1/world_management_service.proto"; + +option java_package = "net.firedevops.firemud.worldmanagement.v1"; +option java_multiple_files = true; + +// Exact immutable source read for the verified same-namespace Entity workload. +service WorldPublishedSpawnRequirementsReadService { + rpc ReadWorldPublishedSpawnRequirements(ReadWorldPublishedSpawnRequirementsRequest) + returns (ReadWorldPublishedSpawnRequirementsResponse); +} + +message ReadWorldPublishedSpawnRequirementsRequest { + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + gamedesign.v1.GetLaunchDescriptorRequest launch_binding_request = 4; + string expected_release_attestation_digest = 5; +} + +message WorldPublishedSpawnRequirementsFamilyCount { + WorldDesignAggregateType family = 1; + optional int32 count = 2; +} + +message WorldPublishedSpawnRequirementsEntityTemplateReference { + EntityTemplateReferenceType kind = 1; + string tenant_id = 2; + string version_id = 3; + string template_id = 4; +} + +message WorldPublishedSpawnRequirement { + string revision_order = 1; + string revision_id = 2; + string spawn_binding_id = 3; + RoomTemplateRef room_template = 4; + WorldPublishedSpawnRequirementsEntityTemplateReference entity_template = 5; + int32 spawn_count = 6; + int32 respawn_delay_seconds = 7; +} + +message WorldPublishedGenerationRequirement { + string revision_order = 1; + string revision_id = 2; + string rule_template_id = 3; + WorldDesignAggregateType scope_family = 4; + string scope_id = 5; + string name = 6; + string value = 7; +} + +message ReadWorldPublishedSpawnRequirementsResponse { + ReadWorldPublishedSpawnRequirementsRequest request = 1; + gamedesign.v1.GetCompleteLaunchBindingResponse complete_launch_binding = 2; + string capture_id = 3; + string graph_digest = 4; + repeated WorldPublishedSpawnRequirementsFamilyCount family_counts = 5; + repeated WorldPublishedSpawnRequirement spawn_requirements = 6; + repeated WorldPublishedGenerationRequirement generation_requirements = 7; + shared.v1.ErrorDetail error = 8; +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsClient.java new file mode 100644 index 0000000000..5b59a148f1 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsClient.java @@ -0,0 +1,182 @@ +package net.firedevops.firemud.common.world; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.worldmanagement.v1.WorldPublishedSpawnRequirementsReadServiceGrpc; + +/** + * Explicit file-backed mTLS client for immutable World published spawn-requirement source reads. + */ +public final class WorldPublishedSpawnRequirementsClient + extends AbstractReloadingBlockingGrpcClient< + WorldPublishedSpawnRequirementsReadServiceGrpc + .WorldPublishedSpawnRequirementsReadServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + private static final String ENTITY_SERVICE = "entity-management-service"; + private static final String WORLD_SERVICE = "world-management-service"; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public WorldPublishedSpawnRequirementsClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireEntityMtls(tlsProperties, workloadNamespace), + channelFactory, + WorldPublishedSpawnRequirementsClient.class); + this.workloadNamespace = workloadNamespace; + } + + /** Initializes only when the owning Entity service explicitly starts this opt-in client. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("World spawn-requirements client is closed"); + } + if (initialized) { + return; + } + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("World spawn-requirements client has no gRPC stub"); + } + initialized = true; + } + + /** Reads and validates the complete immutable source evidence for one exact selector. */ + public WorldPublishedSpawnRequirementsEvidence read( + WorldPublishedSpawnRequirementsEvidence.Request request) { + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "World spawn-requirements request must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readWorldPublishedSpawnRequirements( + WorldPublishedSpawnRequirementsGrpcCodec.toRequest(request)); + try { + return WorldPublishedSpawnRequirementsGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "World returned invalid published spawn-requirements evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getWorldManagementService(); + } + + @Override + protected String defaultTarget() { + return "world-management-service:6565"; + } + + @Override + protected WorldPublishedSpawnRequirementsReadServiceGrpc + .WorldPublishedSpawnRequirementsReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/" + WORLD_SERVICE; + return WorldPublishedSpawnRequirementsReadServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private WorldPublishedSpawnRequirementsReadServiceGrpc + .WorldPublishedSpawnRequirementsReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "World spawn-requirements client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireEntityMtls( + CommonGrpcClientProperties tlsProperties, String workloadNamespace) { + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("World spawn-requirements reads require workload mTLS"); + } + Path certificatePath = requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + requireExactEntityCertificate(certificatePath, workloadNamespace); + return tlsProperties; + } + + private static Path requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "World spawn-requirements reads require file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "World spawn-requirements reads require file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "World spawn-requirements " + label + " must be a readable file-backed path", invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "World spawn-requirements " + label + " must be an existing readable file"); + } + return path; + } + + private static void requireExactEntityCertificate(Path certificatePath, String namespace) { + try (InputStream input = Files.newInputStream(certificatePath)) { + X509Certificate certificate = + (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + String expectedUri = "spiffe://firemud/ns/" + namespace + "/sa/" + ENTITY_SERVICE; + if (GrpcPeerIdentity.fromCertificate(certificate) + .filter(identity -> identity.uri().equals(expectedUri)) + .isEmpty()) { + throw new IllegalArgumentException( + "World spawn-requirements client certificate must be the exact same-namespace Entity workload identity"); + } + } catch (IOException | CertificateException invalid) { + throw new IllegalArgumentException( + "World spawn-requirements client certificate must contain an exact Entity workload identity", + invalid); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsEvidence.java new file mode 100644 index 0000000000..4cfb655ea6 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsEvidence.java @@ -0,0 +1,341 @@ +package net.firedevops.firemud.common.world; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.math.BigInteger; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; +import net.firedevops.firemud.worldmanagement.v1.EntityTemplateReferenceType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; + +/** Exact immutable published spawn and generation inputs retained from one World source read. */ +public record WorldPublishedSpawnRequirementsEvidence( + Request request, + CompleteLaunchBindingEvidence launchBinding, + UUID captureId, + String graphDigest, + List familyCounts, + List spawnRequirements, + List generationRequirements) { + public static final int SCHEMA_VERSION = 1; + + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Pattern CANONICAL_DECIMAL = Pattern.compile("0|[1-9][0-9]*"); + private static final List FAMILY_ORDER = + List.of( + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING); + + /** Exact source-read selector. The nested Game Design request remains unchanged. */ + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "Generated protobuf request messages are immutable value messages.") + public record Request( + String targetNamespace, + UUID readRequestId, + GetLaunchDescriptorRequest launchBindingRequest, + String expectedReleaseAttestationDigest) { + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Generated protobuf request messages are immutable value messages.") + public Request { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be a canonical DNS label"); + } + requireNonNil(readRequestId, "readRequestId"); + Objects.requireNonNull(launchBindingRequest, "launchBindingRequest"); + requireNoUnknownFields(launchBindingRequest, "launch binding request"); + UUID nestedReadRequestId = + parseCanonicalUuid(launchBindingRequest.getRequestId(), "launch binding request ID"); + if (!readRequestId.equals(nestedReadRequestId)) { + throw new IllegalArgumentException( + "Launch binding request ID must equal the published spawn read request ID"); + } + if (readRequestId.toString().equals(launchBindingRequest.getControlPlaneRequestId())) { + throw new IllegalArgumentException( + "Published spawn read request ID must be distinct from the original control-plane request"); + } + parseCanonicalUuid(launchBindingRequest.getCanonicalTenantId(), "canonical tenant ID"); + requireText(launchBindingRequest.getWorldSlug(), "worldSlug"); + requireText(launchBindingRequest.getControlPlaneRequestId(), "controlPlaneRequestId"); + requireSha256(launchBindingRequest.getExpectedRequestDigest(), "expectedRequestDigest"); + requireSha256(launchBindingRequest.getExpectedResultDigest(), "expectedResultDigest"); + requireSha256(expectedReleaseAttestationDigest, "expectedReleaseAttestationDigest"); + } + } + + /** One explicit count from the original ordered six-family declaration. */ + public record FamilyCount(WorldDesignAggregateType family, int count) { + public FamilyCount { + Objects.requireNonNull(family, "family"); + if (count < 0) { + throw new IllegalArgumentException("Published World family count must be nonnegative"); + } + } + } + + /** Exact authored Entity template reference; the owner payload is intentionally absent. */ + public record EntityTemplateReference( + EntityTemplateReferenceType kind, UUID tenantId, UUID versionId, UUID templateId) { + public EntityTemplateReference { + Objects.requireNonNull(kind, "kind"); + if (kind != EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_ITEM + && kind != EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_NPC) { + throw new IllegalArgumentException("Published spawn Entity kind must be ITEM or NPC"); + } + requireNonNil(tenantId, "entity tenantId"); + requireNonNil(versionId, "entity versionId"); + requireNonNil(templateId, "entity templateId"); + } + } + + /** One unchanged authored spawn binding at its original revision position. */ + public record SpawnRequirement( + String revisionOrder, + UUID revisionId, + UUID spawnBindingId, + RoomTemplateRef roomTemplate, + EntityTemplateReference entityTemplate, + int spawnCount, + int respawnDelaySeconds) { + public SpawnRequirement { + requireCanonicalDecimal(revisionOrder, "revisionOrder"); + requireNonNil(revisionId, "revisionId"); + requireNonNil(spawnBindingId, "spawnBindingId"); + Objects.requireNonNull(roomTemplate, "roomTemplate"); + Objects.requireNonNull(entityTemplate, "entityTemplate"); + if (spawnCount < 0 || respawnDelaySeconds < 0) { + throw new IllegalArgumentException( + "Published spawn count and respawn delay must be nonnegative"); + } + } + } + + /** One unchanged authored generation-rule intent at its original revision position. */ + public record GenerationRequirement( + String revisionOrder, + UUID revisionId, + UUID ruleTemplateId, + WorldDesignAggregateType scopeFamily, + UUID scopeId, + String name, + String value) { + public GenerationRequirement { + requireCanonicalDecimal(revisionOrder, "revisionOrder"); + requireNonNil(revisionId, "revisionId"); + requireNonNil(ruleTemplateId, "ruleTemplateId"); + Objects.requireNonNull(scopeFamily, "scopeFamily"); + if (scopeFamily != WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION + && scopeFamily != WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE) { + throw new IllegalArgumentException("Generation requirement scope must be REGION or ZONE"); + } + requireNonNil(scopeId, "scopeId"); + Objects.requireNonNull(name, "name"); + Objects.requireNonNull(value, "value"); + } + } + + public WorldPublishedSpawnRequirementsEvidence { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(launchBinding, "launchBinding"); + requireNonNil(captureId, "captureId"); + requireSha256(graphDigest, "graphDigest"); + familyCounts = List.copyOf(Objects.requireNonNull(familyCounts, "familyCounts")); + spawnRequirements = List.copyOf(Objects.requireNonNull(spawnRequirements, "spawnRequirements")); + generationRequirements = + List.copyOf(Objects.requireNonNull(generationRequirements, "generationRequirements")); + + var descriptor = launchBinding.descriptor(); + var release = launchBinding.releaseAttestation(); + if (!request.targetNamespace().equals(descriptor.targetNamespace()) + || !request.targetNamespace().equals(release.targetNamespace()) + || !descriptor + .canonicalTenantId() + .toString() + .equals(request.launchBindingRequest().getCanonicalTenantId()) + || !descriptor.worldSlug().equals(request.launchBindingRequest().getWorldSlug()) + || !descriptor + .controlPlaneRequestId() + .equals(request.launchBindingRequest().getControlPlaneRequestId()) + || !descriptor + .requestDigest() + .equals(request.launchBindingRequest().getExpectedRequestDigest()) + || !descriptor + .resultDigest() + .equals(request.launchBindingRequest().getExpectedResultDigest())) { + throw new IllegalArgumentException( + "Complete launch binding differs from the exact source-read selector and namespace"); + } + if (request.readRequestId().equals(descriptor.authoredWorldSourceOperationId())) { + throw new IllegalArgumentException( + "Published spawn read request ID must be distinct from the original source operation"); + } + if (!request.expectedReleaseAttestationDigest().equals(release.evidenceDigest())) { + throw new IllegalArgumentException( + "Release attestation digest differs from the exact source-read selector"); + } + if (release.schemaVersion() != AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION + || release.worldStartLocationEvidence() == null) { + throw new IllegalArgumentException( + "Published spawn requirements require the schema-2 release World selector"); + } + String boundGraphDigest = + WorldDraftStartLocationEvidence.fromStored( + release.worldStartLocationEvidence().selectorReceiptBytes()) + .graphDigest(); + if (!boundGraphDigest.equals(graphDigest)) { + throw new IllegalArgumentException( + "Published spawn graph digest differs from the exact release World selector receipt"); + } + + if (familyCounts.size() != FAMILY_ORDER.size()) { + throw new IllegalArgumentException("Exactly six ordered World family counts are required"); + } + for (int index = 0; index < FAMILY_ORDER.size(); index++) { + if (familyCounts.get(index).family() != FAMILY_ORDER.get(index)) { + throw new IllegalArgumentException( + "World family counts must use the canonical ordered six-family declaration"); + } + } + requireCount( + familyCounts, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE, + generationRequirements.size()); + requireCount( + familyCounts, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING, + spawnRequirements.size()); + + UUID tenantId = release.canonicalTenantId(); + UUID versionId = release.canonicalVersionId(); + Set revisionIds = new HashSet<>(); + Set spawnBindingIds = new HashSet<>(); + Set> spawnIdentities = new HashSet<>(); + Set ruleTemplateIds = new HashSet<>(); + requireIncreasingOrders( + spawnRequirements.stream().map(SpawnRequirement::revisionOrder).toList()); + for (SpawnRequirement spawn : spawnRequirements) { + if (!revisionIds.add(spawn.revisionId())) { + throw new IllegalArgumentException("Published requirements repeat a revision identity"); + } + if (!spawnBindingIds.add(spawn.spawnBindingId())) { + throw new IllegalArgumentException( + "Published spawn requirements repeat a binding identity"); + } + if (!tenantId.equals(spawn.roomTemplate().tenantId()) + || !versionId.equals(spawn.roomTemplate().versionId()) + || !tenantId.equals(spawn.entityTemplate().tenantId()) + || !versionId.equals(spawn.entityTemplate().versionId())) { + throw new IllegalArgumentException( + "Published spawn references differ from the exact canonical tenant/version context"); + } + List identity = + List.of( + spawn.roomTemplate().roomTemplateId(), + spawn.entityTemplate().kind(), + spawn.entityTemplate().templateId()); + if (!spawnIdentities.add(identity)) { + throw new IllegalArgumentException( + "Published spawn requirements repeat an authored identity"); + } + } + + Set> generationIdentities = new HashSet<>(); + requireIncreasingOrders( + generationRequirements.stream().map(GenerationRequirement::revisionOrder).toList()); + for (GenerationRequirement generation : generationRequirements) { + if (!revisionIds.add(generation.revisionId())) { + throw new IllegalArgumentException("Published requirements repeat a revision identity"); + } + if (!ruleTemplateIds.add(generation.ruleTemplateId())) { + throw new IllegalArgumentException( + "Published generation requirements repeat a rule template identity"); + } + List identity = + List.of(generation.scopeFamily(), generation.scopeId(), generation.name()); + if (!generationIdentities.add(identity)) { + throw new IllegalArgumentException( + "Published generation requirements repeat an authored identity"); + } + } + } + + private static void requireCount( + List familyCounts, WorldDesignAggregateType family, int expectedCount) { + FamilyCount count = + familyCounts.stream().filter(entry -> entry.family() == family).findFirst().orElseThrow(); + if (count.count() != expectedCount) { + throw new IllegalArgumentException( + "Published World family count differs from its complete source list"); + } + } + + private static void requireIncreasingOrders(List orders) { + BigInteger previous = null; + for (String order : orders) { + BigInteger current = new BigInteger(order); + if (previous != null && current.compareTo(previous) <= 0) { + throw new IllegalArgumentException( + "Published requirements must preserve strictly increasing revision order"); + } + previous = current; + } + } + + static UUID parseCanonicalUuid(String value, String label) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || NIL_UUID.equals(parsed)) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + return parsed; + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID", invalid); + } + } + + static void requireCanonicalDecimal(String value, String label) { + Objects.requireNonNull(value, label); + if (!CANONICAL_DECIMAL.matcher(value).matches()) { + throw new IllegalArgumentException(label + " must be a canonical nonnegative decimal string"); + } + } + + static void requireNoUnknownFields(com.google.protobuf.Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(label + " contains unsupported fields"); + } + } + + private static void requireNonNil(UUID value, String label) { + Objects.requireNonNull(value, label); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + } + + private static void requireSha256(String value, String label) { + if (value == null || !SHA256.matcher(value).matches()) { + throw new IllegalArgumentException(label + " must be canonical tagged SHA-256 text"); + } + } + + private static void requireText(String value, String label) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException(label + " must not be blank"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsGrpcCodec.java new file mode 100644 index 0000000000..9e3962ca09 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsGrpcCodec.java @@ -0,0 +1,322 @@ +package net.firedevops.firemud.common.world; + +import com.google.protobuf.Descriptors.FieldDescriptor; +import com.google.protobuf.Message; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.gamedesign.v1.GetCompleteLaunchBindingResponse; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; +import net.firedevops.firemud.gamedesign.v1.LaunchDescriptor; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedSpawnRequirementsRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedSpawnRequirementsResponse; +import net.firedevops.firemud.worldmanagement.v1.RoomTemplateRef; +import net.firedevops.firemud.worldmanagement.v1.WorldPublishedGenerationRequirement; +import net.firedevops.firemud.worldmanagement.v1.WorldPublishedSpawnRequirement; +import net.firedevops.firemud.worldmanagement.v1.WorldPublishedSpawnRequirementsEntityTemplateReference; +import net.firedevops.firemud.worldmanagement.v1.WorldPublishedSpawnRequirementsFamilyCount; + +/** Closed mapping and exact request-echo validation for published spawn-requirement reads. */ +public final class WorldPublishedSpawnRequirementsGrpcCodec { + private WorldPublishedSpawnRequirementsGrpcCodec() {} + + public static ReadWorldPublishedSpawnRequirementsRequest toRequest( + WorldPublishedSpawnRequirementsEvidence.Request request) { + Objects.requireNonNull(request, "request"); + return ReadWorldPublishedSpawnRequirementsRequest.newBuilder() + .setSchemaVersion(WorldPublishedSpawnRequirementsEvidence.SCHEMA_VERSION) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setLaunchBindingRequest(request.launchBindingRequest()) + .setExpectedReleaseAttestationDigest(request.expectedReleaseAttestationDigest()) + .build(); + } + + /** Parses the closed owner request only after transport authentication by its caller. */ + public static WorldPublishedSpawnRequirementsEvidence.Request fromRequest( + ReadWorldPublishedSpawnRequirementsRequest request) { + Objects.requireNonNull(request, "request"); + requireNoUnknownFieldsRecursively(request, "ReadWorldPublishedSpawnRequirementsRequest"); + if (request.getSchemaVersion() != WorldPublishedSpawnRequirementsEvidence.SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported published spawn-requirements schema version"); + } + if (!request.hasLaunchBindingRequest()) { + throw new IllegalArgumentException( + "Published spawn request lacks its complete binding selector"); + } + return new WorldPublishedSpawnRequirementsEvidence.Request( + request.getTargetNamespace(), + WorldPublishedSpawnRequirementsEvidence.parseCanonicalUuid( + request.getReadRequestId(), "readRequestId"), + request.getLaunchBindingRequest(), + request.getExpectedReleaseAttestationDigest()); + } + + /** + * Encodes complete immutable evidence without changing its request selector or authored values. + */ + public static ReadWorldPublishedSpawnRequirementsResponse toResponse( + WorldPublishedSpawnRequirementsEvidence.Request request, + WorldPublishedSpawnRequirementsEvidence evidence) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(evidence, "evidence"); + if (!request.equals(evidence.request())) { + throw new IllegalArgumentException( + "Published spawn evidence differs from the exact source-read request"); + } + var builder = + ReadWorldPublishedSpawnRequirementsResponse.newBuilder() + .setRequest(toRequest(request)) + .setCompleteLaunchBinding( + toCompleteLaunchBindingResponse( + request.launchBindingRequest(), evidence.launchBinding())) + .setCaptureId(evidence.captureId().toString()) + .setGraphDigest(evidence.graphDigest()); + for (WorldPublishedSpawnRequirementsEvidence.FamilyCount familyCount : + evidence.familyCounts()) { + builder.addFamilyCounts( + WorldPublishedSpawnRequirementsFamilyCount.newBuilder() + .setFamily(familyCount.family()) + .setCount(familyCount.count())); + } + for (WorldPublishedSpawnRequirementsEvidence.SpawnRequirement spawn : + evidence.spawnRequirements()) { + builder.addSpawnRequirements( + WorldPublishedSpawnRequirement.newBuilder() + .setRevisionOrder(spawn.revisionOrder()) + .setRevisionId(spawn.revisionId().toString()) + .setSpawnBindingId(spawn.spawnBindingId().toString()) + .setRoomTemplate( + RoomTemplateRef.newBuilder() + .setTenantId(spawn.roomTemplate().tenantId().toString()) + .setVersionId(spawn.roomTemplate().versionId().toString()) + .setRoomTemplateId(spawn.roomTemplate().roomTemplateId().toString())) + .setEntityTemplate( + WorldPublishedSpawnRequirementsEntityTemplateReference.newBuilder() + .setKind(spawn.entityTemplate().kind()) + .setTenantId(spawn.entityTemplate().tenantId().toString()) + .setVersionId(spawn.entityTemplate().versionId().toString()) + .setTemplateId(spawn.entityTemplate().templateId().toString())) + .setSpawnCount(spawn.spawnCount()) + .setRespawnDelaySeconds(spawn.respawnDelaySeconds())); + } + for (WorldPublishedSpawnRequirementsEvidence.GenerationRequirement generation : + evidence.generationRequirements()) { + builder.addGenerationRequirements( + WorldPublishedGenerationRequirement.newBuilder() + .setRevisionOrder(generation.revisionOrder()) + .setRevisionId(generation.revisionId().toString()) + .setRuleTemplateId(generation.ruleTemplateId().toString()) + .setScopeFamily(generation.scopeFamily()) + .setScopeId(generation.scopeId().toString()) + .setName(generation.name()) + .setValue(generation.value())); + } + return builder.build(); + } + + /** Validates the complete source response, exact request echo and complete Game Design pair. */ + public static WorldPublishedSpawnRequirementsEvidence fromResponse( + WorldPublishedSpawnRequirementsEvidence.Request request, + ReadWorldPublishedSpawnRequirementsResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFieldsRecursively(response, "ReadWorldPublishedSpawnRequirementsResponse"); + if (response.hasError()) { + throw new IllegalArgumentException("World rejected the published spawn-requirements read"); + } + if (!response.hasRequest() || !response.hasCompleteLaunchBinding()) { + throw new IllegalArgumentException( + "Published spawn response lacks its exact request or complete launch binding"); + } + WorldPublishedSpawnRequirementsEvidence.Request echoed = fromRequest(response.getRequest()); + if (!request.equals(echoed)) { + throw new IllegalArgumentException( + "Published spawn response changed the exact source-read request"); + } + CompleteLaunchBindingEvidence launchBinding = + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + request.launchBindingRequest(), response.getCompleteLaunchBinding()); + + List familyCounts = + new ArrayList<>(response.getFamilyCountsCount()); + for (WorldPublishedSpawnRequirementsFamilyCount count : response.getFamilyCountsList()) { + requireNoUnknownFieldsRecursively(count, "WorldPublishedSpawnRequirementsFamilyCount"); + if (!count.hasCount()) { + throw new IllegalArgumentException( + "Published World family count is not explicitly present"); + } + familyCounts.add( + new WorldPublishedSpawnRequirementsEvidence.FamilyCount( + count.getFamily(), count.getCount())); + } + + List spawns = + new ArrayList<>(response.getSpawnRequirementsCount()); + for (WorldPublishedSpawnRequirement spawn : response.getSpawnRequirementsList()) { + requireNoUnknownFieldsRecursively(spawn, "WorldPublishedSpawnRequirement"); + if (!spawn.hasRoomTemplate() || !spawn.hasEntityTemplate()) { + throw new IllegalArgumentException("Published spawn requirement lacks typed references"); + } + var room = spawn.getRoomTemplate(); + var entity = spawn.getEntityTemplate(); + spawns.add( + new WorldPublishedSpawnRequirementsEvidence.SpawnRequirement( + spawn.getRevisionOrder(), + WorldPublishedSpawnRequirementsEvidence.parseCanonicalUuid( + spawn.getRevisionId(), "revisionId"), + WorldPublishedSpawnRequirementsEvidence.parseCanonicalUuid( + spawn.getSpawnBindingId(), "spawnBindingId"), + new net.firedevops.firemud.common.world.RoomTemplateRef( + WorldPublishedSpawnRequirementsEvidence.parseCanonicalUuid( + room.getTenantId(), "room tenantId"), + WorldPublishedSpawnRequirementsEvidence.parseCanonicalUuid( + room.getVersionId(), "room versionId"), + WorldPublishedSpawnRequirementsEvidence.parseCanonicalUuid( + room.getRoomTemplateId(), "roomTemplateId")), + new WorldPublishedSpawnRequirementsEvidence.EntityTemplateReference( + entity.getKind(), + WorldPublishedSpawnRequirementsEvidence.parseCanonicalUuid( + entity.getTenantId(), "entity tenantId"), + WorldPublishedSpawnRequirementsEvidence.parseCanonicalUuid( + entity.getVersionId(), "entity versionId"), + WorldPublishedSpawnRequirementsEvidence.parseCanonicalUuid( + entity.getTemplateId(), "entity templateId")), + spawn.getSpawnCount(), + spawn.getRespawnDelaySeconds())); + } + + List generations = + new ArrayList<>(response.getGenerationRequirementsCount()); + for (WorldPublishedGenerationRequirement generation : + response.getGenerationRequirementsList()) { + requireNoUnknownFieldsRecursively(generation, "WorldPublishedGenerationRequirement"); + generations.add( + new WorldPublishedSpawnRequirementsEvidence.GenerationRequirement( + generation.getRevisionOrder(), + WorldPublishedSpawnRequirementsEvidence.parseCanonicalUuid( + generation.getRevisionId(), "revisionId"), + WorldPublishedSpawnRequirementsEvidence.parseCanonicalUuid( + generation.getRuleTemplateId(), "ruleTemplateId"), + generation.getScopeFamily(), + WorldPublishedSpawnRequirementsEvidence.parseCanonicalUuid( + generation.getScopeId(), "scopeId"), + generation.getName(), + generation.getValue())); + } + return new WorldPublishedSpawnRequirementsEvidence( + request, + launchBinding, + WorldPublishedSpawnRequirementsEvidence.parseCanonicalUuid( + response.getCaptureId(), "captureId"), + response.getGraphDigest(), + familyCounts, + spawns, + generations); + } + + /** Encodes a parsed launch pair for the outer response while validating its exact selector. */ + public static GetCompleteLaunchBindingResponse toCompleteLaunchBindingResponse( + GetLaunchDescriptorRequest request, CompleteLaunchBindingEvidence evidence) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(evidence, "evidence"); + AuthoredWorldLaunchDescriptorEvidence descriptor = evidence.descriptor(); + var bindingBuilder = + net.firedevops.firemud.gamedesign.v1.AuthoredWorldLaunchDescriptorEvidence.newBuilder() + .setSchemaVersion(descriptor.schemaVersion()) + .setTargetNamespace(descriptor.targetNamespace()) + .setControlPlaneRequestId(descriptor.controlPlaneRequestId()) + .setCanonicalTenantId(descriptor.canonicalTenantId().toString()) + .setWorldSlug(descriptor.worldSlug()) + .setAuthoredWorldSourceOperationId( + descriptor.authoredWorldSourceOperationId().toString()) + .setAuthoredWorldSourceEvidenceDigest(descriptor.authoredWorldSourceEvidenceDigest()) + .setGameTemplateId(descriptor.gameTemplateId()) + .setRequestDigest(descriptor.requestDigest()) + .setLaunchDescriptorId(descriptor.launchDescriptorId()) + .setVersionId(descriptor.versionId()) + .setRuntimeFlagsJson(descriptor.runtimeFlagsJson()) + .setGenerationConfigRevision(descriptor.generationConfigRevision()) + .setVersionStateEpoch(descriptor.versionStateEpoch()) + .setReleaseBundleId(descriptor.releaseBundleId()) + .setPublishedReleaseBundleRef(descriptor.publishedReleaseBundleRef()) + .setResultDigest(descriptor.resultDigest()); + if (descriptor.requestedScriptPatchVersionPresent()) { + bindingBuilder.setRequestedScriptPatchVersion(descriptor.requestedScriptPatchVersion()); + } + if (descriptor.sourceVersionIdPresent()) { + bindingBuilder.setSourceVersionId(descriptor.sourceVersionId()); + } + if (descriptor.targetVersionIdPresent()) { + bindingBuilder.setTargetVersionId(descriptor.targetVersionId()); + } + if (descriptor.requestedRuntimeFlagsJsonPresent()) { + bindingBuilder.setRequestedRuntimeFlagsJson(descriptor.requestedRuntimeFlagsJson()); + } + if (descriptor.scriptPatchVersionPresent()) { + bindingBuilder.setScriptPatchVersion(descriptor.scriptPatchVersion()); + } + if (descriptor.remapSetIdPresent()) { + bindingBuilder.setRemapSetId(descriptor.remapSetId()); + } + + var descriptorBuilder = + LaunchDescriptor.newBuilder() + .setLaunchDescriptorId(descriptor.launchDescriptorId()) + .setCanonicalTenantId(descriptor.canonicalTenantId().toString()) + .setGameTemplateId(descriptor.gameTemplateId()) + .setControlPlaneRequestId(descriptor.controlPlaneRequestId()) + .setVersionId(descriptor.versionId()) + .setRuntimeFlagsJson(descriptor.runtimeFlagsJson()) + .setGenerationConfigRevision(descriptor.generationConfigRevision()) + .setVersionStateEpoch(descriptor.versionStateEpoch()) + .setReleaseBundleId(descriptor.releaseBundleId()) + .setPublishedReleaseBundleRef(descriptor.publishedReleaseBundleRef()) + .setAuthoredWorldBinding(bindingBuilder.build()); + if (descriptor.scriptPatchVersionPresent()) { + descriptorBuilder.setScriptPatchVersion(descriptor.scriptPatchVersion()); + } + if (descriptor.remapSetIdPresent()) { + descriptorBuilder.setRemapSetId(descriptor.remapSetId()); + } + + GetCompleteLaunchBindingResponse response = + GetCompleteLaunchBindingResponse.newBuilder() + .setRequestId(request.getRequestId()) + .setLaunchDescriptor(descriptorBuilder) + .setReleaseAttestation( + AuthoredWorldLaunchDescriptorGrpcCodec.toReleaseAttestation( + evidence.releaseAttestation())) + .build(); + CompleteLaunchBindingEvidence decoded = + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse(request, response); + if (!decoded.equals(evidence)) { + throw new IllegalArgumentException( + "Encoded complete launch binding differs from its immutable evidence pair"); + } + return response; + } + + private static void requireNoUnknownFieldsRecursively(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(label + " contains unsupported fields"); + } + for (var entry : message.getAllFields().entrySet()) { + FieldDescriptor field = entry.getKey(); + if (field.getJavaType() != FieldDescriptor.JavaType.MESSAGE) { + continue; + } + Object value = entry.getValue(); + if (field.isRepeated()) { + for (Object element : (List) value) { + requireNoUnknownFieldsRecursively((Message) element, field.getName()); + } + } else { + requireNoUnknownFieldsRecursively((Message) value, field.getName()); + } + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsClientMtlsTest.java new file mode 100644 index 0000000000..207da9778e --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsClientMtlsTest.java @@ -0,0 +1,493 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.Base64; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedSpawnRequirementsRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedSpawnRequirementsResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldPublishedSpawnRequirementsReadServiceGrpc; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** Physical mTLS proof against a labeled transport-only World source double. */ +class WorldPublishedSpawnRequirementsClientMtlsTest { + private static final String NAMESPACE = "test"; + private static final String WORLD_URI = "spiffe://firemud/ns/test/sa/world-management-service"; + private static final String OTHER_WORLD_URI = + "spiffe://firemud/ns/other-test/sa/world-management-service"; + private static final String WRONG_WORKLOAD_URI = + "spiffe://firemud/ns/test/sa/game-design-service"; + private static final String ENTITY_URI = "spiffe://firemud/ns/test/sa/entity-management-service"; + private static final String WRONG_CLIENT_URI = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String STORE_PASSWORD = "test-only-store-password"; + + @TempDir static Path tempDirectory; + private static TestPki pki; + private Server server; + private WorldPublishedSpawnRequirementsClient client; + private AtomicInteger headers; + private AtomicInteger bodies; + + @BeforeAll + static void createTrustedCertificates() throws Exception { + pki = TestPki.create(tempDirectory); + } + + @AfterEach + void stopTransport() throws Exception { + if (client != null) { + client.close(); + client = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } + + @Test + void exactWorldPeerReturnsUnchangedSourceCarrierAndExactRequestId() throws Exception { + var expected = WorldPublishedSpawnRequirementsGrpcCodecTest.evidence(); + startServer(pki.worldServer(), Mode.EXACT); + client = newClient(server, pki.entityClient()); + client.init(); + + var actual = client.read(expected.request()); + + assertThat(actual).isEqualTo(expected); + assertThat(actual.request().readRequestId()).isEqualTo(expected.request().readRequestId()); + assertThat(actual.familyCounts()).isEqualTo(expected.familyCounts()); + assertThat(actual.spawnRequirements()).isEqualTo(expected.spawnRequirements()); + assertThat(actual.generationRequirements()).isEqualTo(expected.generationRequirements()); + assertThat(headers).hasValue(1); + assertThat(bodies).hasValue(1); + } + + @Test + void trustedWrongWorldWorkloadAndNamespaceReleaseNoRequestMetadataOrBody() throws Exception { + var request = WorldPublishedSpawnRequirementsGrpcCodecTest.evidence().request(); + for (TestIdentity identity : List.of(pki.wrongWorkloadServer(), pki.otherNamespaceServer())) { + startServer(identity, Mode.EXACT); + client = newClient(server, pki.entityClient()); + client.init(); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + exception -> + assertThat(Status.fromThrowable(exception).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(headers).hasValue(0); + assertThat(bodies).hasValue(0); + stopTransport(); + } + } + + @Test + void rejectsChangedRequestReleaseGraphAndFamilyEvidenceAfterAuthenticatedRead() throws Exception { + var request = WorldPublishedSpawnRequirementsGrpcCodecTest.evidence().request(); + for (Mode mode : + List.of( + Mode.CHANGED_REQUEST, Mode.CHANGED_RELEASE, Mode.CHANGED_GRAPH, Mode.CHANGED_FAMILY)) { + startServer(pki.worldServer(), mode); + client = newClient(server, pki.entityClient()); + client.init(); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid published spawn-requirements evidence"); + assertThat(headers).hasValue(1); + assertThat(bodies).hasValue(1); + stopTransport(); + } + } + + @Test + void rejectsWrongLocalWorkloadPlaintextAndNonFileBackedTls() throws Exception { + var request = WorldPublishedSpawnRequirementsGrpcCodecTest.evidence().request(); + startServer(pki.worldServer(), Mode.EXACT); + + assertThatThrownBy(() -> newClient(server, pki.wrongClient())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact same-namespace Entity workload identity"); + + var plaintext = pki.clientProperties(tempDirectory, pki.entityClient()); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new WorldPublishedSpawnRequirementsClient( + endpoints(server), plaintext, new GrpcChannelFactory(), NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("workload mTLS"); + + var classpath = pki.clientProperties(tempDirectory, pki.entityClient()); + classpath.setCaCert("classpath:ca.crt"); + assertThatThrownBy( + () -> + new WorldPublishedSpawnRequirementsClient( + endpoints(server), classpath, new GrpcChannelFactory(), NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + + client = newClient(server, pki.entityClient()); + assertThatThrownBy(() -> client.read(request)).isInstanceOf(IllegalStateException.class); + client.init(); + client.close(); + assertThatThrownBy(() -> client.read(request)).isInstanceOf(IllegalStateException.class); + assertThat(headers).hasValue(0); + } + + private enum Mode { + EXACT, + CHANGED_REQUEST, + CHANGED_RELEASE, + CHANGED_GRAPH, + CHANGED_FAMILY + } + + private void startServer(TestIdentity identity, Mode mode) throws Exception { + headers = new AtomicInteger(); + bodies = new AtomicInteger(); + var service = + new WorldPublishedSpawnRequirementsReadServiceGrpc + .WorldPublishedSpawnRequirementsReadServiceImplBase() { + @Override + public void readWorldPublishedSpawnRequirements( + ReadWorldPublishedSpawnRequirementsRequest wire, + StreamObserver observer) { + bodies.incrementAndGet(); + assertThat(GrpcPeerIdentity.current().uri()).isEqualTo(ENTITY_URI); + var request = WorldPublishedSpawnRequirementsGrpcCodec.fromRequest(wire); + var evidence = WorldPublishedSpawnRequirementsGrpcCodecTest.evidence(); + var response = WorldPublishedSpawnRequirementsGrpcCodec.toResponse(request, evidence); + if (mode == Mode.CHANGED_REQUEST) { + response = + response.toBuilder() + .setRequest( + response.getRequest().toBuilder() + .setReadRequestId("ffffffff-ffff-4fff-8fff-ffffffffffff")) + .build(); + } else if (mode == Mode.CHANGED_RELEASE) { + response = + response.toBuilder() + .setRequest( + response.getRequest().toBuilder() + .setExpectedReleaseAttestationDigest("sha256:" + "f".repeat(64))) + .build(); + } else if (mode == Mode.CHANGED_GRAPH) { + response = response.toBuilder().setGraphDigest("sha256:" + "f".repeat(64)).build(); + } else if (mode == Mode.CHANGED_FAMILY) { + response = + response.toBuilder() + .setFamilyCounts( + 0, + response.getFamilyCounts(0).toBuilder() + .setFamily( + net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType + .WORLD_DESIGN_AGGREGATE_TYPE_UNSPECIFIED)) + .build(); + } + observer.onNext(response); + observer.onCompleted(); + } + }; + ServerInterceptor countHeaders = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata metadata, + ServerCallHandler next) { + headers.incrementAndGet(); + return next.startCall(call, metadata); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + service, countHeaders, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private WorldPublishedSpawnRequirementsClient newClient(Server target, TestIdentity local) + throws Exception { + return new WorldPublishedSpawnRequirementsClient( + endpoints(target), + pki.clientProperties(tempDirectory, local), + new GrpcChannelFactory(), + NAMESPACE); + } + + private static ServiceEndpointsProperties endpoints(Server target) { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setWorldManagementService("localhost:" + target.getPort()); + return endpoints; + } + + private record TestIdentity(PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestIdentity worldServer, + TestIdentity wrongWorkloadServer, + TestIdentity otherNamespaceServer, + TestIdentity entityClient, + TestIdentity wrongClient) { + private static TestPki create(Path directory) throws Exception { + Path caStore = directory.resolve("test-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD spawn-requirements test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path caFile = directory.resolve("test-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-rfc"); + X509Certificate caCertificate = readCertificate(caFile); + return new TestPki( + caCertificate, + issueIdentity(directory, caStore, caFile, "world-server", WORLD_URI, true), + issueIdentity( + directory, caStore, caFile, "wrong-workload-server", WRONG_WORKLOAD_URI, true), + issueIdentity( + directory, caStore, caFile, "wrong-namespace-server", OTHER_WORLD_URI, true), + issueIdentity(directory, caStore, caFile, "entity-client", ENTITY_URI, false), + issueIdentity(directory, caStore, caFile, "wrong-client", WRONG_CLIENT_URI, false)); + } + + private CommonGrpcClientProperties clientProperties(Path directory, TestIdentity identity) + throws Exception { + Path certificate = + writePem( + directory.resolve("entity-client.crt"), + "CERTIFICATE", + identity.certificate().getEncoded()); + Path privateKey = + writePem( + directory.resolve("entity-client.key"), + "PRIVATE KEY", + identity.privateKey().getEncoded()); + Path caFile = + writePem( + directory.resolve("client-trust-ca.crt"), "CERTIFICATE", caCertificate.getEncoded()); + var properties = new CommonGrpcClientProperties(); + properties.setCertChain(certificate.toString()); + properties.setPrivateKey(privateKey.toString()); + properties.setCaCert(caFile.toString()); + return properties; + } + + private static TestIdentity issueIdentity( + Path directory, Path caStore, Path caFile, String alias, String workloadUri, boolean server) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san); + runKeytool( + "-importcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-noprompt"); + runKeytool( + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-noprompt"); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, STORE_PASSWORD.toCharArray()); + } + return new TestIdentity( + (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), + (X509Certificate) keyStore.getCertificate(alias)); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + var command = new java.util.ArrayList(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + String output; + try (var stream = process.getInputStream()) { + output = new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + if (!process.waitFor(30, TimeUnit.SECONDS) || process.exitValue() != 0) { + process.destroyForcibly(); + throw new IllegalStateException("keytool failed: " + output); + } + } + + private static X509Certificate readCertificate(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsClientTest.java new file mode 100644 index 0000000000..1e73376529 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsClientTest.java @@ -0,0 +1,38 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; + +import java.nio.file.Path; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import org.junit.jupiter.api.Test; + +class WorldPublishedSpawnRequirementsClientTest { + @Test + void rejectsPlaintextAndInvalidNamespaceBeforeCreatingTransport() { + var plaintext = new CommonGrpcClientProperties(); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new WorldPublishedSpawnRequirementsClient( + new ServiceEndpointsProperties(), + plaintext, + mock(GrpcChannelFactory.class), + "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("workload mTLS"); + + var tls = new CommonGrpcClientProperties(); + tls.setCertChain(Path.of("missing.crt").toString()); + tls.setPrivateKey(Path.of("missing.key").toString()); + tls.setCaCert(Path.of("missing-ca.crt").toString()); + assertThatThrownBy( + () -> + new WorldPublishedSpawnRequirementsClient( + new ServiceEndpointsProperties(), tls, mock(GrpcChannelFactory.class), "Test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical DNS label"); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsEvidenceTest.java new file mode 100644 index 0000000000..b2a8dcec71 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsEvidenceTest.java @@ -0,0 +1,90 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.List; +import org.junit.jupiter.api.Test; + +class WorldPublishedSpawnRequirementsEvidenceTest { + @Test + void retainsImmutableOriginalRequirementsAndArbitraryPrecisionRevisionOrder() { + var evidence = WorldPublishedSpawnRequirementsGrpcCodecTest.evidence(); + + assertThat(evidence.spawnRequirements()).hasSize(2); + assertThat(evidence.spawnRequirements().get(0).revisionOrder()).isEqualTo("9007199254740993"); + assertThat(evidence.spawnRequirements().get(0).spawnCount()).isEqualTo(7); + assertThat(evidence.spawnRequirements().get(0).respawnDelaySeconds()).isEqualTo(2700); + assertThat(evidence.spawnRequirements().get(0).roomTemplate().tenantId()) + .isEqualTo(evidence.launchBinding().releaseAttestation().canonicalTenantId()); + assertThat(evidence.spawnRequirements().get(0).entityTemplate().kind().name()) + .isEqualTo("ENTITY_TEMPLATE_REFERENCE_TYPE_ITEM"); + assertThat(evidence.generationRequirements().get(0).revisionOrder()) + .isEqualTo("9007199254740992"); + assertThat(evidence.generationRequirements().get(0).value()).isEqualTo(" authored value "); + assertThatThrownBy(evidence.spawnRequirements()::clear) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(evidence.generationRequirements()::clear) + .isInstanceOf(UnsupportedOperationException.class); + } + + @Test + void deniesDuplicateIdentityAndNonIncreasingRevisionOrder() { + var evidence = WorldPublishedSpawnRequirementsGrpcCodecTest.evidence(); + var first = evidence.spawnRequirements().get(0); + var second = evidence.spawnRequirements().get(1); + + assertThatThrownBy( + () -> + new WorldPublishedSpawnRequirementsEvidence( + evidence.request(), + evidence.launchBinding(), + evidence.captureId(), + evidence.graphDigest(), + evidence.familyCounts(), + List.of( + first, + new WorldPublishedSpawnRequirementsEvidence.SpawnRequirement( + "9007199254740994", + second.revisionId(), + first.spawnBindingId(), + second.roomTemplate(), + second.entityTemplate(), + second.spawnCount(), + second.respawnDelaySeconds())), + evidence.generationRequirements())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("binding identity"); + + assertThatThrownBy( + () -> + new WorldPublishedSpawnRequirementsEvidence( + evidence.request(), + evidence.launchBinding(), + evidence.captureId(), + evidence.graphDigest(), + evidence.familyCounts(), + List.of(second, first), + evidence.generationRequirements())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("strictly increasing revision order"); + } + + @Test + void bindsGraphDigestToTheReleaseSelectorReceipt() { + var evidence = WorldPublishedSpawnRequirementsGrpcCodecTest.evidence(); + + assertThatThrownBy( + () -> + new WorldPublishedSpawnRequirementsEvidence( + evidence.request(), + evidence.launchBinding(), + evidence.captureId(), + "sha256:" + "f".repeat(64), + evidence.familyCounts(), + evidence.spawnRequirements(), + evidence.generationRequirements())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("graph digest"); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsGrpcCodecTest.java new file mode 100644 index 0000000000..fd3e886c9e --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsGrpcCodecTest.java @@ -0,0 +1,443 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.UnknownFieldSet; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; +import net.firedevops.firemud.worldmanagement.v1.WorldPublishedSpawnRequirementsFamilyCount; +import org.junit.jupiter.api.Test; + +class WorldPublishedSpawnRequirementsGrpcCodecTest { + private static final UUID READ_ID = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID OTHER_ID = uuid("44444444-4444-4444-8444-444444444444"); + + @Test + void roundTripsExactRequestCompletePairAndOriginalRequirementValues() { + var expected = evidence(); + var request = WorldPublishedSpawnRequirementsGrpcCodec.toRequest(expected.request()); + assertThat(WorldPublishedSpawnRequirementsGrpcCodec.fromRequest(request)) + .isEqualTo(expected.request()); + + var response = + WorldPublishedSpawnRequirementsGrpcCodec.toResponse(expected.request(), expected); + var actual = + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse(expected.request(), response); + + assertThat(actual).isEqualTo(expected); + assertThat(actual.spawnRequirements()).hasSize(2); + assertThat(actual.spawnRequirements().getFirst().revisionOrder()).isEqualTo("9007199254740993"); + assertThat(actual.spawnRequirements().getFirst().spawnCount()).isEqualTo(7); + assertThat(actual.spawnRequirements().getFirst().respawnDelaySeconds()).isEqualTo(2700); + assertThat(actual.spawnRequirements().getFirst().entityTemplate()) + .isEqualTo(expected.spawnRequirements().getFirst().entityTemplate()); + assertThat(actual.generationRequirements().getFirst().revisionOrder()) + .isEqualTo("9007199254740992"); + assertThat(actual.generationRequirements().getFirst().value()).isEqualTo(" authored value "); + } + + @Test + void rejectsChangedRequestScopeReleaseAndMalformedCapture() { + var expected = evidence(); + var response = + WorldPublishedSpawnRequirementsGrpcCodec.toResponse(expected.request(), expected); + + assertThatThrownBy( + () -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + expected.request(), + response.toBuilder() + .setRequest( + response.getRequest().toBuilder().setReadRequestId(OTHER_ID.toString())) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + expected.request(), + response.toBuilder().setGraphDigest("sha256:" + "f".repeat(64)).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("graph digest"); + assertThatThrownBy( + () -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + expected.request(), + response.toBuilder() + .setRequest( + response.getRequest().toBuilder() + .setExpectedReleaseAttestationDigest("sha256:" + "f".repeat(64))) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("changed the exact source-read request"); + assertThatThrownBy( + () -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + expected.request(), + response.toBuilder() + .setCompleteLaunchBinding( + response.getCompleteLaunchBinding().toBuilder() + .setReleaseAttestation( + response + .getCompleteLaunchBinding() + .getReleaseAttestation() + .toBuilder() + .setCanonicalTenantId(OTHER_ID.toString()))) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + expected.request(), + response.toBuilder() + .setCaptureId("00000000-0000-0000-0000-000000000000") + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("captureId"); + } + + @Test + void rejectsMissingNestedEvidenceUnknownFieldsAndChangedAuthoredScope() { + var expected = evidence(); + var response = + WorldPublishedSpawnRequirementsGrpcCodec.toResponse(expected.request(), expected); + assertThatThrownBy( + () -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + expected.request(), response.toBuilder().clearRequest().build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + expected.request(), response.toBuilder().clearCompleteLaunchBinding().build())) + .isInstanceOf(IllegalArgumentException.class); + + UnknownFieldSet unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + assertThatThrownBy( + () -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + expected.request(), response.toBuilder().setUnknownFields(unknown).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + assertThatThrownBy( + () -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + expected.request(), + response.toBuilder() + .setRequest(response.getRequest().toBuilder().setUnknownFields(unknown)) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + assertThatThrownBy( + () -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + expected.request(), + response.toBuilder() + .setRequest( + response.getRequest().toBuilder() + .setLaunchBindingRequest( + response.getRequest().getLaunchBindingRequest().toBuilder() + .setUnknownFields(unknown))) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + assertThatThrownBy( + () -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + expected.request(), + response.toBuilder() + .setSpawnRequirements( + 0, + response.getSpawnRequirements(0).toBuilder() + .setRoomTemplate( + response.getSpawnRequirements(0).getRoomTemplate().toBuilder() + .setTenantId(OTHER_ID.toString()))) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical tenant/version context"); + assertThatThrownBy( + () -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + expected.request(), + response.toBuilder() + .setSpawnRequirements( + 0, + response.getSpawnRequirements(0).toBuilder() + .setRoomTemplate( + response.getSpawnRequirements(0).getRoomTemplate().toBuilder() + .setUnknownFields(unknown))) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + } + + @Test + void requiresAllSixExplicitCountsAndRejectsCountListMismatch() { + var empty = emptyEvidence(); + var emptyResponse = WorldPublishedSpawnRequirementsGrpcCodec.toResponse(empty.request(), empty); + assertThat(emptyResponse.getFamilyCountsCount()).isEqualTo(6); + for (var count : emptyResponse.getFamilyCountsList()) { + assertThat(count.hasCount()).isTrue(); + assertThat(count.getCount()).isZero(); + } + assertThat( + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse(empty.request(), emptyResponse)) + .isEqualTo(empty); + + var populated = evidence(); + var response = + WorldPublishedSpawnRequirementsGrpcCodec.toResponse(populated.request(), populated); + var badCount = + WorldPublishedSpawnRequirementsFamilyCount.newBuilder() + .setFamily(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE) + .setCount(1) + .build(); + assertThatThrownBy( + () -> + new WorldPublishedSpawnRequirementsEvidence( + populated.request(), + populated.launchBinding(), + populated.captureId(), + populated.graphDigest(), + List.of( + populated.familyCounts().get(0), + populated.familyCounts().get(1), + populated.familyCounts().get(2), + populated.familyCounts().get(3), + new WorldPublishedSpawnRequirementsEvidence.FamilyCount( + badCount.getFamily(), badCount.getCount()), + populated.familyCounts().get(5)), + populated.spawnRequirements(), + populated.generationRequirements())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("count differs"); + assertThatThrownBy( + () -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + populated.request(), + response.toBuilder() + .setFamilyCounts(4, response.getFamilyCounts(4).toBuilder().setCount(1)) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("count differs"); + + assertThatThrownBy( + () -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + empty.request(), + emptyResponse.toBuilder() + .setFamilyCounts( + 0, emptyResponse.getFamilyCounts(0).toBuilder().clearCount()) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("not explicitly present"); + } + + static WorldPublishedSpawnRequirementsEvidence evidence() { + CompleteLaunchBindingEvidence binding = completeBinding(); + var request = request(binding); + UUID tenant = binding.releaseAttestation().canonicalTenantId(); + UUID version = binding.releaseAttestation().canonicalVersionId(); + var item = + new WorldPublishedSpawnRequirementsEvidence.EntityTemplateReference( + net.firedevops.firemud.worldmanagement.v1.EntityTemplateReferenceType + .ENTITY_TEMPLATE_REFERENCE_TYPE_ITEM, + tenant, + version, + uuid("66666666-6666-4666-8666-666666666666")); + var npc = + new WorldPublishedSpawnRequirementsEvidence.EntityTemplateReference( + net.firedevops.firemud.worldmanagement.v1.EntityTemplateReferenceType + .ENTITY_TEMPLATE_REFERENCE_TYPE_NPC, + tenant, + version, + uuid("77777777-7777-4777-8777-777777777777")); + return new WorldPublishedSpawnRequirementsEvidence( + request, + binding, + uuid("88888888-8888-4888-8888-888888888888"), + graphDigest(binding), + counts(1, 2, 3, 4, 2, 2), + List.of( + new WorldPublishedSpawnRequirementsEvidence.SpawnRequirement( + "9007199254740993", + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + new RoomTemplateRef(tenant, version, uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc")), + item, + 7, + 2700), + new WorldPublishedSpawnRequirementsEvidence.SpawnRequirement( + "9007199254740994", + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + new RoomTemplateRef(tenant, version, uuid("ffffffff-ffff-4fff-8fff-ffffffffffff")), + npc, + 0, + 0)), + List.of( + new WorldPublishedSpawnRequirementsEvidence.GenerationRequirement( + "9007199254740992", + uuid("12345678-1234-4234-8234-123456789001"), + uuid("12345678-1234-4234-8234-123456789101"), + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION, + uuid("12345678-1234-4234-8234-123456789201"), + "difficulty.mode", + " authored value "), + new WorldPublishedSpawnRequirementsEvidence.GenerationRequirement( + "9007199254740995", + uuid("12345678-1234-4234-8234-123456789002"), + uuid("12345678-1234-4234-8234-123456789102"), + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE, + uuid("12345678-1234-4234-8234-123456789202"), + "population.mode", + "sparse"))); + } + + static WorldPublishedSpawnRequirementsEvidence emptyEvidence() { + CompleteLaunchBindingEvidence binding = completeBinding(); + return new WorldPublishedSpawnRequirementsEvidence( + request(binding), + binding, + uuid("88888888-8888-4888-8888-888888888888"), + graphDigest(binding), + counts(0, 0, 0, 0, 0, 0), + List.of(), + List.of()); + } + + private static List counts( + int region, int zone, int room, int exit, int generation, int spawn) { + return List.of( + new WorldPublishedSpawnRequirementsEvidence.FamilyCount( + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION, region), + new WorldPublishedSpawnRequirementsEvidence.FamilyCount( + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE, zone), + new WorldPublishedSpawnRequirementsEvidence.FamilyCount( + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM, room), + new WorldPublishedSpawnRequirementsEvidence.FamilyCount( + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT, exit), + new WorldPublishedSpawnRequirementsEvidence.FamilyCount( + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE, generation), + new WorldPublishedSpawnRequirementsEvidence.FamilyCount( + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING, + spawn)); + } + + private static WorldPublishedSpawnRequirementsEvidence.Request request( + CompleteLaunchBindingEvidence binding) { + var descriptor = binding.descriptor(); + GetLaunchDescriptorRequest selector = + GetLaunchDescriptorRequest.newBuilder() + .setRequestId(READ_ID.toString()) + .setCanonicalTenantId(descriptor.canonicalTenantId().toString()) + .setWorldSlug(descriptor.worldSlug()) + .setControlPlaneRequestId(descriptor.controlPlaneRequestId()) + .setExpectedRequestDigest(descriptor.requestDigest()) + .setExpectedResultDigest(descriptor.resultDigest()) + .build(); + return new WorldPublishedSpawnRequirementsEvidence.Request( + descriptor.targetNamespace(), + READ_ID, + selector, + binding.releaseAttestation().evidenceDigest()); + } + + private static String graphDigest(CompleteLaunchBindingEvidence binding) { + return WorldDraftStartLocationEvidence.fromStored( + binding.releaseAttestation().worldStartLocationEvidence().selectorReceiptBytes()) + .graphDigest(); + } + + private static CompleteLaunchBindingEvidence completeBinding() { + WorldPublishedStartLocationEvidence worldStart; + try { + worldStart = WorldPublishedStartLocationGrpcCodecTest.evidence(); + } catch (Exception impossible) { + throw new AssertionError(impossible); + } + var selection = worldStart.request(); + var descriptorRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + selection.targetNamespace(), + "launch-control-request", + selection.canonicalTenantId(), + "synthetic-world", + uuid("99999999-9999-4999-8999-999999999999"), + "sha256:" + "a".repeat(64), + 19L, + false, + null, + false, + null, + false, + null, + false, + null); + AuthoredWorldLaunchDescriptorEvidence descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + descriptorRequest, + "descriptor", + Long.MAX_VALUE, + false, + null, + "{}", + "generation-config", + 9L, + 7L, + "published-release", + false, + null); + var participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptor.versionId()), + false, + null, + selection.appliedCommitId(), + "b".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "c".repeat(64) : null)) + .toList(); + AuthoredWorldReleaseAttestationEvidence release = + AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + descriptor.canonicalTenantId(), + selection.canonicalVersionId(), + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + selection.publishWorkflowId(), + selection.appliedCommitId(), + participants, + "sha256:" + "d".repeat(64), + 1, + List.of(), + List.of(), + List.of("LOOK"), + descriptor.generationConfigRevision(), + worldStart); + return new CompleteLaunchBindingEvidence(descriptor, release); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyRepository.java index 9932ad43be..3055518042 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyRepository.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.worldmanagement.tenant; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.Connection; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.Map; @@ -59,7 +60,16 @@ public Optional readCommitted(CaptureRequest reque if (TransactionSynchronizationManager.isActualTransactionActive()) { throw new ConflictException("Frozen topology readback requires no caller transaction"); } - Objects.requireNonNull(request, "request"); + return readFrozen(Objects.requireNonNull(request, "request")); + } + + /** Reads this immutable selector only inside the caller-owned read-only RR snapshot. */ + Optional readInOwnedSnapshot(CaptureRequest request) { + requireOwnedReadOnlyRepeatableReadSnapshot(); + return readFrozen(Objects.requireNonNull(request, "request")); + } + + private Optional readFrozen(CaptureRequest request) { Record row = dsl.resultQuery( "SELECT binding_json,binding_digest,owner_binding_json FROM world_canonical_frozen_topology WHERE publication_fence=?", @@ -72,8 +82,23 @@ public Optional readCommitted(CaptureRequest reque required(row, "binding_digest", String.class)); var ownerBinding = JSON.readValue(required(row, "owner_binding_json", String.class), OwnerBinding.class); - return readCommitted( - new Request(WorldDraftTopologyCommitPlan.create(binding, ownerBinding), request)); + return Optional.ofNullable( + find(new Request(WorldDraftTopologyCommitPlan.create(binding, ownerBinding), request))); + } + + private void requireOwnedReadOnlyRepeatableReadSnapshot() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_REPEATABLE_READ) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new ConflictException( + "Frozen topology snapshot read requires an active read-only REPEATABLE READ owner transaction"); + } + Integer jdbcIsolation = dsl.connectionResult(Connection::getTransactionIsolation); + if (!Integer.valueOf(Connection.TRANSACTION_REPEATABLE_READ).equals(jdbcIsolation)) { + throw new ConflictException( + "Frozen topology snapshot read requires actual JDBC REPEATABLE READ isolation"); + } } WorldCanonicalFrozenTopology capture(Request request) { diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationRepository.java index b88d867616..ad1f185430 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationRepository.java @@ -50,6 +50,18 @@ public Optional readCommitted( public Optional readCommitted( String targetNamespace, byte[] originalAccountBinding) { requireCommittedRead(); + return readByOriginalAccountBinding(targetNamespace, originalAccountBinding); + } + + /** Reads the original namespace and Account selection inside the caller-owned RR snapshot. */ + Optional readInOwnedSnapshot( + String targetNamespace, byte[] originalAccountBinding) { + requireOwnedReadOnlyRepeatableReadSnapshot(); + return readByOriginalAccountBinding(targetNamespace, originalAccountBinding); + } + + private Optional readByOriginalAccountBinding( + String targetNamespace, byte[] originalAccountBinding) { if (!net.firedevops.firemud.common.grpc.GrpcPeerIdentity.isValidNamespace(targetNamespace)) { throw new IllegalArgumentException("Canonical World workload namespace is required"); } @@ -75,6 +87,21 @@ public Optional readCommitted( return Optional.of(readExact(application, rows.getFirst())); } + private void requireOwnedReadOnlyRepeatableReadSnapshot() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(java.sql.Connection.TRANSACTION_REPEATABLE_READ) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new ConflictException( + "World application snapshot read requires an active read-only REPEATABLE READ owner transaction"); + } + Integer jdbcIsolation = dsl.connectionResult(java.sql.Connection::getTransactionIsolation); + if (!Integer.valueOf(java.sql.Connection.TRANSACTION_REPEATABLE_READ).equals(jdbcIsolation)) { + throw new ConflictException( + "World application snapshot read requires actual JDBC REPEATABLE READ isolation"); + } + } + WorldDraftGraphAppliedResult apply( WorldDraftGraphApplication application, CommitOrderProof proof) { requireTransaction(); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadGrpcService.java new file mode 100644 index 0000000000..f6d37dbd49 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadGrpcService.java @@ -0,0 +1,61 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.Map; +import java.util.Objects; +import net.firedevops.firemud.common.world.WorldPublishedSpawnRequirementsGrpcCodec; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedSpawnRequirementsRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedSpawnRequirementsResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldPublishedSpawnRequirementsReadServiceGrpc; + +/** Standalone transport adapter; intentionally not registered in production composition. */ +final class WorldPublishedSpawnRequirementsReadGrpcService + extends WorldPublishedSpawnRequirementsReadServiceGrpc + .WorldPublishedSpawnRequirementsReadServiceImplBase { + private static final Map DESCRIPTIONS = + Map.of( + Status.Code.PERMISSION_DENIED, + "Published World source read is not authorized", + Status.Code.INVALID_ARGUMENT, + "Published World source selector is invalid", + Status.Code.NOT_FOUND, + "No exact published World source matches the selector", + Status.Code.FAILED_PRECONDITION, + "Published World source evidence is incomplete or inconsistent", + Status.Code.UNAVAILABLE, + "Published World source is temporarily unavailable", + Status.Code.INTERNAL, + "Published World source read failed"); + + private final WorldPublishedSpawnRequirementsReadOwner owner; + + WorldPublishedSpawnRequirementsReadGrpcService(WorldPublishedSpawnRequirementsReadOwner owner) { + this.owner = Objects.requireNonNull(owner, "owner"); + } + + @Override + public void readWorldPublishedSpawnRequirements( + ReadWorldPublishedSpawnRequirementsRequest request, + StreamObserver responseObserver) { + final ReadWorldPublishedSpawnRequirementsResponse response; + try { + var evidence = owner.read(request); + response = WorldPublishedSpawnRequirementsGrpcCodec.toResponse(evidence.request(), evidence); + } catch (WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException rejected) { + responseObserver.onError(status(rejected.code())); + return; + } catch (RuntimeException failure) { + responseObserver.onError(status(Status.Code.INTERNAL)); + return; + } + responseObserver.onNext(response); + responseObserver.onCompleted(); + } + + private static io.grpc.StatusRuntimeException status(Status.Code code) { + return Status.fromCode(code) + .withDescription(DESCRIPTIONS.getOrDefault(code, "Published World source read failed")) + .asRuntimeException(); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadOwner.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadOwner.java new file mode 100644 index 0000000000..545ef3f6ab --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadOwner.java @@ -0,0 +1,334 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import io.grpc.Status; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.RoomTemplateRef; +import net.firedevops.firemud.common.world.WorldPublishedSpawnRequirementsEvidence; +import net.firedevops.firemud.common.world.WorldPublishedSpawnRequirementsEvidence.EntityTemplateReference; +import net.firedevops.firemud.common.world.WorldPublishedSpawnRequirementsEvidence.FamilyCount; +import net.firedevops.firemud.common.world.WorldPublishedSpawnRequirementsEvidence.GenerationRequirement; +import net.firedevops.firemud.common.world.WorldPublishedSpawnRequirementsEvidence.Request; +import net.firedevops.firemud.common.world.WorldPublishedSpawnRequirementsEvidence.SpawnRequirement; +import net.firedevops.firemud.common.world.WorldPublishedSpawnRequirementsGrpcCodec; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.CaptureRequest; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceTopologyPlan.GenerationRuleIntent; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceTopologyPlan.SpawnBindingIntent; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedSpawnRequirementsRequest; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; +import org.springframework.dao.DataAccessException; +import org.springframework.dao.TransientDataAccessException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Standalone authenticated read owner for immutable published World spawn requirements. */ +final class WorldPublishedSpawnRequirementsReadOwner { + private final String workloadNamespace; + private final AuthoredWorldLaunchDescriptorClient gameDesignClient; + private final WorldPublishedStartLocationRepository publishedSources; + private final PlatformTransactionManager transactionManager; + + WorldPublishedSpawnRequirementsReadOwner( + String workloadNamespace, + AuthoredWorldLaunchDescriptorClient gameDesignClient, + WorldPublishedStartLocationRepository publishedSources, + PlatformTransactionManager transactionManager) { + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("World workload namespace is invalid"); + } + this.workloadNamespace = workloadNamespace; + this.gameDesignClient = Objects.requireNonNull(gameDesignClient, "gameDesignClient"); + this.publishedSources = Objects.requireNonNull(publishedSources, "publishedSources"); + this.transactionManager = Objects.requireNonNull(transactionManager, "transactionManager"); + } + + WorldPublishedSpawnRequirementsEvidence read( + ReadWorldPublishedSpawnRequirementsRequest wireRequest) { + requireAuthenticatedEntityPeer(); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw rejected( + Status.Code.FAILED_PRECONDITION, + "Published spawn-requirement read requires no ambient World transaction"); + } + + final Request request; + try { + request = WorldPublishedSpawnRequirementsGrpcCodec.fromRequest(wireRequest); + } catch (IllegalArgumentException invalid) { + throw rejected(Status.Code.INVALID_ARGUMENT, "Published spawn selector is invalid"); + } + if (!workloadNamespace.equals(request.targetNamespace())) { + throw rejected(Status.Code.PERMISSION_DENIED, "Published spawn namespace is not authorized"); + } + + CompleteLaunchBindingEvidence launchBinding = readLaunchBinding(request); + AuthoredWorldReleaseAttestationEvidence release = launchBinding.releaseAttestation(); + if (!workloadNamespace.equals(launchBinding.descriptor().targetNamespace()) + || !workloadNamespace.equals(release.targetNamespace()) + || !request.expectedReleaseAttestationDigest().equals(release.evidenceDigest()) + || release.schemaVersion() + != AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION + || release.worldStartLocationEvidence() == null) { + throw rejected( + Status.Code.FAILED_PRECONDITION, + "Authenticated Game Design release differs from the exact published selector"); + } + + CaptureRequest captureRequest = captureRequest(release.worldStartLocationEvidence()); + Optional stored = readInOwnedSnapshot(captureRequest); + if (stored.isEmpty()) { + throw rejected(Status.Code.NOT_FOUND, "No exact frozen World source matches the release"); + } + + WorldPublishedStartLocationSource source = stored.orElseThrow(); + WorldCanonicalInstanceTopologyPlan topology; + try { + topology = WorldCanonicalInstanceTopologyPlan.create(source.frozenTopology()); + WorldCanonicalInstancePreparation.requireExactReleaseGraph(release, topology); + WorldPublishedStartLocationEvidence actualSelector = + actualSelectorEvidence(source, release.worldStartLocationEvidence().request()); + if (!actualSelector.equals(release.worldStartLocationEvidence())) { + throw new IllegalArgumentException( + "Frozen selector, Account binding, or APPLIED result differs from Game Design release"); + } + var projection = projectRequirements(frozenGraph(source.frozenTopology()), topology); + return new WorldPublishedSpawnRequirementsEvidence( + request, + launchBinding, + source.frozenTopology().captureId(), + WorldDraftGraphAppliedResult.digest(source.frozenTopology().graphBytes()), + projection.familyCounts(), + projection.spawnRequirements(), + projection.generationRequirements()); + } catch (RuntimeException invalid) { + throw rejected( + Status.Code.FAILED_PRECONDITION, + "Frozen World source differs from authenticated release evidence"); + } + } + + private CompleteLaunchBindingEvidence readLaunchBinding(Request request) { + try { + return gameDesignClient.getComplete(request.launchBindingRequest()); + } catch (RuntimeException unavailable) { + throw rejected( + Status.Code.UNAVAILABLE, "Authenticated Game Design release read did not complete"); + } + } + + private Optional readInOwnedSnapshot( + CaptureRequest captureRequest) { + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + transaction.setReadOnly(true); + try { + return Objects.requireNonNull( + transaction.execute(status -> publishedSources.readInOwnedSnapshot(captureRequest)), + "World published source transaction result"); + } catch (WorldDesignPublicationFenceRepository.ConflictException conflict) { + throw rejected( + Status.Code.FAILED_PRECONDITION, + "Frozen World source conflicts with the exact publication selection"); + } catch (TransientDataAccessException unavailable) { + throw rejected(Status.Code.UNAVAILABLE, "World published source is temporarily unavailable"); + } catch (DataAccessException unavailable) { + throw rejected(Status.Code.UNAVAILABLE, "World published source is temporarily unavailable"); + } catch (RuntimeException failure) { + throw rejected(Status.Code.INTERNAL, "World published source read failed"); + } + } + + static RequirementProjection projectRequirements( + WorldDraftTopologyInputGraph authoredGraph, WorldCanonicalInstanceTopologyPlan topology) { + var declaration = + authoredGraph + .freshGraphDeclaration() + .orElseThrow( + () -> + new IllegalArgumentException( + "Published World source lacks its original complete family declaration")); + + Map spawnsByRevision = new HashMap<>(); + for (SpawnBindingIntent spawn : topology.spawnBindings()) { + UUID revisionId = UUID.fromString(spawn.source().authoredRevision().getLogicalRevisionId()); + if (spawnsByRevision.putIfAbsent(revisionId, spawn) != null) { + throw new IllegalArgumentException("Frozen World source repeats a spawn revision"); + } + } + Map generationsByRevision = new HashMap<>(); + for (GenerationRuleIntent generation : topology.generationRules()) { + UUID revisionId = + UUID.fromString(generation.source().authoredRevision().getLogicalRevisionId()); + if (generationsByRevision.putIfAbsent(revisionId, generation) != null) { + throw new IllegalArgumentException("Frozen World source repeats a generation revision"); + } + } + + List spawns = new ArrayList<>(); + List generations = new ArrayList<>(); + for (var node : authoredGraph.nodes()) { + if (node.mutation().getAggregateType() + == WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING) { + SpawnBindingIntent intent = spawnsByRevision.remove(node.revisionId()); + if (intent == null || !node.templateId().equals(intent.identity().templateId())) { + throw new IllegalArgumentException("Spawn projection differs from its original revision"); + } + var entity = intent.entityReference(); + spawns.add( + new SpawnRequirement( + node.revisionOrder(), + node.revisionId(), + intent.identity().templateId(), + new RoomTemplateRef( + topology.tenantId(), topology.versionId(), intent.room().templateId()), + new EntityTemplateReference( + entity.kind(), entity.tenantId(), entity.versionId(), entity.templateId()), + intent.requiredIntent().getSpawnCount(), + intent.requiredIntent().getRespawnDelaySeconds())); + } else if (node.mutation().getAggregateType() + == WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE) { + GenerationRuleIntent intent = generationsByRevision.remove(node.revisionId()); + if (intent == null || !node.templateId().equals(intent.identity().templateId())) { + throw new IllegalArgumentException( + "Generation projection differs from its original revision"); + } + WorldDesignAggregateType scopeFamily = + switch (intent.scope().family()) { + case REGION -> WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION; + case ZONE -> WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE; + default -> + throw new IllegalArgumentException( + "Generation scope is not an authored REGION or ZONE"); + }; + generations.add( + new GenerationRequirement( + node.revisionOrder(), + node.revisionId(), + intent.identity().templateId(), + scopeFamily, + intent.scope().templateId(), + intent.requiredIntent().getName(), + intent.requiredIntent().getValue())); + } + } + if (!spawnsByRevision.isEmpty() || !generationsByRevision.isEmpty()) { + throw new IllegalArgumentException("Frozen source projections omit original intent rows"); + } + + List familyCounts = + declaration.familyCounts().stream() + .map(count -> new FamilyCount(count.family(), count.count())) + .toList(); + return new RequirementProjection(familyCounts, spawns, generations); + } + + private static WorldDraftTopologyInputGraph frozenGraph(WorldCanonicalFrozenTopology frozen) { + return frozen.request().plan().graph(); + } + + private static CaptureRequest captureRequest(WorldPublishedStartLocationEvidence selector) { + var request = selector.request(); + return new CaptureRequest( + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalVersionId(), + request.intakeRequestId(), + request.publicationFence(), + request.publicationRequestId(), + request.requestDigest(), + request.versionStateEpoch(), + request.publishWorkflowId(), + request.appliedCommitId(), + request.contentDigest(), + request.digestSchemaVersion(), + request.worldAffectedTuples().stream() + .map( + tuple -> + new WorldAuthoredGraphSnapshot.OwnedAffectedTuple( + tuple.owner(), + tuple.aggregateType(), + tuple.aggregateId(), + tuple.scopeType(), + tuple.scopeId(), + tuple.expectedEpoch())) + .toList()); + } + + private static WorldPublishedStartLocationEvidence actualSelectorEvidence( + WorldPublishedStartLocationSource source, + WorldPublishedStartLocationEvidence.Request selectorRequest) { + var receipt = source.selectorReceipt(); + var receiptEvidence = + new net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence( + receipt.targetNamespace(), + receipt.operationId(), + receipt.requestId(), + receipt.commitId(), + receipt.authorizationFenceId(), + receipt.accountBindingDigest(), + receipt.bindingDigest(), + receipt.startLocation(), + receipt.graphDigest(), + receipt.receiptDigest()); + return new WorldPublishedStartLocationEvidence( + selectorRequest, + receiptEvidence.canonicalBytes(), + source.appliedResult().application().operation().accountBindingBytes(), + source.appliedResult().canonicalBytes()); + } + + private void requireAuthenticatedEntityPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null + || !peer.isService("entity-management-service") + || !peer.isInNamespace(workloadNamespace) + || SessionContext.hasAuthenticatedCallerContext()) { + throw rejected( + Status.Code.PERMISSION_DENIED, + "Only the verified same-namespace Entity workload without end-user context is allowed"); + } + } + + private static ReadRejectedException rejected(Status.Code code, String message) { + return new ReadRejectedException(code, message); + } + + static final class ReadRejectedException extends IllegalStateException { + private final Status.Code code; + + ReadRejectedException(Status.Code code, String message) { + super(message); + this.code = code; + } + + Status.Code code() { + return code; + } + } + + record RequirementProjection( + List familyCounts, + List spawnRequirements, + List generationRequirements) { + RequirementProjection { + familyCounts = List.copyOf(familyCounts); + spawnRequirements = List.copyOf(spawnRequirements); + generationRequirements = List.copyOf(generationRequirements); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedStartLocationRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedStartLocationRepository.java index c0ab0e5b8a..02557eb327 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedStartLocationRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedStartLocationRepository.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.worldmanagement.tenant; +import java.sql.Connection; import java.util.Arrays; import java.util.Objects; import java.util.Optional; @@ -29,7 +30,19 @@ public Optional readCommitted(CaptureRequest if (TransactionSynchronizationManager.isActualTransactionActive()) { throw new ConflictException("World published selector read requires no caller transaction"); } - var selected = frozen.readCommitted(Objects.requireNonNull(request, "request")); + return readSource(Objects.requireNonNull(request, "request"), false); + } + + /** Joins both immutable journals within one caller-owned read-only RR snapshot. */ + Optional readInOwnedSnapshot(CaptureRequest request) { + requireOwnedReadOnlyRepeatableReadSnapshot(); + return readSource(Objects.requireNonNull(request, "request"), true); + } + + private Optional readSource( + CaptureRequest request, boolean ownedSnapshot) { + var selected = + ownedSnapshot ? frozen.readInOwnedSnapshot(request) : frozen.readCommitted(request); if (selected.isEmpty()) return Optional.empty(); var capture = selected.orElseThrow(); var plan = capture.request().plan(); @@ -50,11 +63,13 @@ public Optional readCommitted(CaptureRequest var account = DraftAuthorizationFenceBinding.fromStored( rows.getFirst().get("account_binding_bytes", byte[].class)); + var appliedRead = + ownedSnapshot + ? applications.readInOwnedSnapshot(request.targetNamespace(), account.canonicalBytes()) + : applications.readCommitted(request.targetNamespace(), account.canonicalBytes()); var applied = - applications - .readCommitted(request.targetNamespace(), account.canonicalBytes()) - .orElseThrow( - () -> new ConflictException("World published selector lacks committed APPLIED")); + appliedRead.orElseThrow( + () -> new ConflictException("World published selector lacks committed APPLIED")); var application = applied.application(); var receipt = applied @@ -76,4 +91,19 @@ public Optional readCommitted(CaptureRequest } return Optional.of(new WorldPublishedStartLocationSource(capture, applied, receipt)); } + + private void requireOwnedReadOnlyRepeatableReadSnapshot() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_REPEATABLE_READ) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new ConflictException( + "World published selector snapshot read requires an active read-only REPEATABLE READ owner transaction"); + } + Integer jdbcIsolation = dsl.connectionResult(Connection::getTransactionIsolation); + if (!Integer.valueOf(Connection.TRANSACTION_REPEATABLE_READ).equals(jdbcIsolation)) { + throw new ConflictException( + "World published selector snapshot read requires actual JDBC REPEATABLE READ isolation"); + } + } } diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java index 85aa460b6e..c19783415d 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java @@ -90,7 +90,10 @@ import net.firedevops.firemud.common.world.WorldPublicationTerminalCompletionGrpcCodec; import net.firedevops.firemud.common.world.WorldPublicationTerminalReadEvidence; import net.firedevops.firemud.common.world.WorldPublicationTerminalReadGrpcCodec; +import net.firedevops.firemud.common.world.WorldPublishedSpawnRequirementsEvidence; +import net.firedevops.firemud.common.world.WorldPublishedSpawnRequirementsGrpcCodec; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; @@ -5141,6 +5144,219 @@ dsl, frozenRepository(), substitutedApplications) assertOrigin(); } + @Test + void publishedSelectorOwnedReadUsesOneActualReadOnlyRepeatableReadSnapshot() { + Fixture f = fixture(); + var application = application(f); + var applied = appliedComponent().apply(application); + var capture = capture(application.plan()); + var request = capture.request().freeze(); + byte[] originalApplication = retainedApplicationBytes(application); + long applicationCount = count(f, "world_draft_graph_application"); + long receiptCount = count(f, "world_draft_start_location_receipt"); + long frozenCount = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_canonical_frozen_topology WHERE publication_fence=?", + request.publicationFence())) + .get(0, Long.class); + Map preparationRowsBeforeRead = preparationHistoryRows(); + + TransactionTemplate ownedSnapshot = new TransactionTemplate(manager); + ownedSnapshot.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ownedSnapshot.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + ownedSnapshot.setReadOnly(true); + var source = + Objects.requireNonNull( + ownedSnapshot.execute( + status -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()) + .isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) + .isTrue(); + assertThat( + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) + .isEqualTo(java.sql.Connection.TRANSACTION_REPEATABLE_READ); + assertThat(dsl.fetchOne("SELECT current_setting('transaction_isolation')").get(0)) + .isEqualTo("repeatable read"); + assertThat(dsl.fetchOne("SELECT current_setting('transaction_read_only')").get(0)) + .isEqualTo("on"); + return publishedSelectors().readInOwnedSnapshot(request).orElseThrow(); + })); + + assertThat(source.selectorReceipt()).isEqualTo(applied.startLocationReceipt().orElseThrow()); + assertThat(source.frozenTopology().captureId()).isEqualTo(capture.captureId()); + assertThat(source.frozenTopology().resultBytes()).containsExactly(capture.resultBytes()); + assertThat(source.appliedResult().canonicalBytes()).containsExactly(applied.canonicalBytes()); + assertThat(source.appliedResult().application().operation().accountBindingBytes()) + .containsExactly(application.operation().accountBindingBytes()); + + TransactionTemplate wrongIsolation = new TransactionTemplate(manager); + wrongIsolation.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + wrongIsolation.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + wrongIsolation.setReadOnly(true); + assertThatThrownBy( + () -> + wrongIsolation.execute(status -> publishedSelectors().readInOwnedSnapshot(request))) + .hasMessageContaining("read-only REPEATABLE READ owner transaction"); + + assertThat(retainedApplicationBytes(application)).containsExactly(originalApplication); + assertThat(count(f, "world_draft_graph_application")).isEqualTo(applicationCount); + assertThat(count(f, "world_draft_start_location_receipt")).isEqualTo(receiptCount); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_canonical_frozen_topology WHERE publication_fence=?", + request.publicationFence())) + .get(0, Long.class)) + .isEqualTo(frozenCount); + // The source reader is pre-PREPARING: it does not allocate any runtime world row. + assertThat(preparationHistoryRows()).isEqualTo(preparationRowsBeforeRead); + assertOrigin(); + } + + @Test + void publishedSpawnRequirementsOwnerProjectsOnlyRealFrozenAndAppliedSource() { + Fixture f = fixture(); + var application = application(f); + appliedComponent().apply(application); + var capture = capture(application.plan()); + var frozen = capture.request().freeze(); + var source = publishedSelectors().readCommitted(frozen).orElseThrow(); + var selector = publishedEvidence(source); + var launchBinding = + preparationLaunchFixture(f, source.frozenTopology(), selector, 2L, List.of("LOOK")) + .evidence(); + var descriptor = launchBinding.descriptor(); + UUID readId = UUID.randomUUID(); + var launchRequest = + GetLaunchDescriptorRequest.newBuilder() + .setRequestId(readId.toString()) + .setCanonicalTenantId(descriptor.canonicalTenantId().toString()) + .setWorldSlug(descriptor.worldSlug()) + .setControlPlaneRequestId(descriptor.controlPlaneRequestId()) + .setExpectedRequestDigest(descriptor.requestDigest()) + .setExpectedResultDigest(descriptor.resultDigest()) + .build(); + var request = + new WorldPublishedSpawnRequirementsEvidence.Request( + NAMESPACE, readId, launchRequest, launchBinding.releaseAttestation().evidenceDigest()); + var wireRequest = WorldPublishedSpawnRequirementsGrpcCodec.toRequest(request); + + // The authenticated Game Design pair is a labeled upstream double; the World rows below are + // the actual migrated PostgreSQL application, original APPLIED receipt, and frozen capture. + var gameDesign = Mockito.mock(AuthoredWorldLaunchDescriptorClient.class); + Mockito.when(gameDesign.getComplete(launchRequest)).thenReturn(launchBinding); + var owner = + new WorldPublishedSpawnRequirementsReadOwner( + NAMESPACE, gameDesign, publishedSelectors(), manager); + Map before = preparationHistoryRows(); + var entityContext = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + new GrpcPeerIdentity( + "spiffe://firemud/ns/" + NAMESPACE + "/sa/entity-management-service", + NAMESPACE, + "entity-management-service")); + Context previous = entityContext.attach(); + WorldPublishedSpawnRequirementsEvidence evidence; + try { + SessionContext.clear(); + evidence = owner.read(wireRequest); + } finally { + Context.current().detach(previous); + SessionContext.clear(); + } + + assertThat(evidence.captureId()).isEqualTo(capture.captureId()); + assertThat(evidence.graphDigest()) + .isEqualTo(WorldDraftGraphAppliedResult.digest(capture.graphBytes())); + assertThat(evidence.familyCounts()).hasSize(6); + assertThat(evidence.familyCounts()).extracting("count").contains(1); + assertThat(evidence.spawnRequirements()).hasSize(1); + assertThat(evidence.spawnRequirements().getFirst().respawnDelaySeconds()).isEqualTo(17); + assertThat(evidence.spawnRequirements().getFirst().entityTemplate().kind()) + .isEqualTo(EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_NPC); + assertThat(evidence.generationRequirements()).hasSize(1); + assertThat(evidence.generationRequirements().getFirst().name()).isEqualTo("rule"); + assertThat(evidence.generationRequirements().getFirst().value()).isEqualTo("seeded"); + assertThat(preparationHistoryRows()).isEqualTo(before); + Mockito.verify(gameDesign).getComplete(launchRequest); + assertOrigin(); + } + + @Test + void publishedSpawnRequirementsOwnerPreservesExplicitZeroOptionalFamilies() { + Fixture f = fixture(); + var application = application(plan(f, true)); + appliedComponent().apply(application); + var capture = capture(application.plan()); + var source = publishedSelectors().readCommitted(capture.request().freeze()).orElseThrow(); + var launchBinding = + preparationLaunchFixture( + f, source.frozenTopology(), publishedEvidence(source), 2L, List.of("LOOK")) + .evidence(); + var descriptor = launchBinding.descriptor(); + UUID readId = UUID.randomUUID(); + var launchRequest = + GetLaunchDescriptorRequest.newBuilder() + .setRequestId(readId.toString()) + .setCanonicalTenantId(descriptor.canonicalTenantId().toString()) + .setWorldSlug(descriptor.worldSlug()) + .setControlPlaneRequestId(descriptor.controlPlaneRequestId()) + .setExpectedRequestDigest(descriptor.requestDigest()) + .setExpectedResultDigest(descriptor.resultDigest()) + .build(); + var request = + new WorldPublishedSpawnRequirementsEvidence.Request( + NAMESPACE, readId, launchRequest, launchBinding.releaseAttestation().evidenceDigest()); + var gameDesign = Mockito.mock(AuthoredWorldLaunchDescriptorClient.class); + Mockito.when(gameDesign.getComplete(launchRequest)).thenReturn(launchBinding); + var owner = + new WorldPublishedSpawnRequirementsReadOwner( + NAMESPACE, gameDesign, publishedSelectors(), manager); + var context = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + new GrpcPeerIdentity( + "spiffe://firemud/ns/" + NAMESPACE + "/sa/entity-management-service", + NAMESPACE, + "entity-management-service")); + Context previous = context.attach(); + WorldPublishedSpawnRequirementsEvidence evidence; + try { + SessionContext.clear(); + evidence = owner.read(WorldPublishedSpawnRequirementsGrpcCodec.toRequest(request)); + } finally { + Context.current().detach(previous); + SessionContext.clear(); + } + + assertThat(evidence.familyCounts()).hasSize(6); + assertThat(evidence.familyCounts()) + .filteredOn( + count -> + count.family() + == WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE) + .singleElement() + .extracting("count") + .isEqualTo(0); + assertThat(evidence.familyCounts()) + .filteredOn( + count -> + count.family() + == WorldDesignAggregateType + .WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING) + .singleElement() + .extracting("count") + .isEqualTo(0); + assertThat(evidence.spawnRequirements()).isEmpty(); + assertThat(evidence.generationRequirements()).isEmpty(); + assertOrigin(); + } + @Test void permissionUnverifiedGraphAndFrozenHistoryCannotSupplyPublishedSelector() { var plan = plan(fixture()); @@ -5149,6 +5365,15 @@ void permissionUnverifiedGraphAndFrozenHistoryCannotSupplyPublishedSelector() { assertThat(frozenRepository().readCommitted(capture.request().freeze())).isPresent(); assertThatThrownBy(() -> publishedSelectors().readCommitted(capture.request().freeze())) .hasMessageContaining("lacks original APPLIED application"); + TransactionTemplate ownedSnapshot = new TransactionTemplate(manager); + ownedSnapshot.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ownedSnapshot.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + ownedSnapshot.setReadOnly(true); + assertThatThrownBy( + () -> + ownedSnapshot.execute( + status -> publishedSelectors().readInOwnedSnapshot(capture.request().freeze()))) + .hasMessageContaining("lacks original APPLIED application"); assertOrigin(); } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSourceSnapshotReadTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSourceSnapshotReadTest.java new file mode 100644 index 0000000000..27e7414f2a --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSourceSnapshotReadTest.java @@ -0,0 +1,88 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.sql.Connection; +import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.ObjectMapper; + +class WorldPublishedSourceSnapshotReadTest { + private final DSLContext dsl = mock(DSLContext.class); + private final WorldCanonicalFrozenTopologyRepository frozen = + new WorldCanonicalFrozenTopologyRepository( + dsl, + mock(WorldAuthoredGraphSnapshotRepository.class), + mock(WorldDraftTopologyCommitRepository.class), + mock(net.firedevops.firemud.worldmanagement.service.WorldDraftDesignDigestService.class)); + private final WorldDraftGraphApplicationRepository applications = + new WorldDraftGraphApplicationRepository( + dsl, mock(WorldDesignPublicationFenceRepository.class), mock(ObjectMapper.class)); + private final WorldPublishedStartLocationRepository published = + new WorldPublishedStartLocationRepository(dsl, frozen, applications); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void allOwnedSnapshotSeamsRejectMissingTransaction() { + assertThatThrownBy(() -> frozen.readInOwnedSnapshot(null)) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class); + assertThatThrownBy(() -> applications.readInOwnedSnapshot("test", new byte[0])) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class); + assertThatThrownBy(() -> published.readInOwnedSnapshot(null)) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class); + } + + @Test + void allOwnedSnapshotSeamsRejectWritableTransactions() { + setTransaction(false, Connection.TRANSACTION_REPEATABLE_READ); + assertSnapshotSeamsReject(); + } + + @Test + void allOwnedSnapshotSeamsRejectWrongTransactionIsolation() { + setTransaction(true, Connection.TRANSACTION_READ_COMMITTED); + assertSnapshotSeamsReject(); + } + + @Test + void allOwnedSnapshotSeamsRejectWrongActualJdbcIsolation() { + setTransaction(true, Connection.TRANSACTION_REPEATABLE_READ); + when(dsl.connectionResult(any())).thenReturn(Connection.TRANSACTION_READ_COMMITTED); + assertSnapshotSeamsReject(); + } + + @Test + void existingCommittedApisContinueRejectingAmbientTransactions() { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> frozen.readCommitted((WorldAuthoredGraphSnapshot.CaptureRequest) null)) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class); + assertThatThrownBy(() -> applications.readCommitted("test", new byte[0])) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class); + assertThatThrownBy(() -> published.readCommitted(null)) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class); + } + + private void assertSnapshotSeamsReject() { + assertThatThrownBy(() -> frozen.readInOwnedSnapshot(null)) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class); + assertThatThrownBy(() -> applications.readInOwnedSnapshot("test", new byte[0])) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class); + assertThatThrownBy(() -> published.readInOwnedSnapshot(null)) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class); + } + + private static void setTransaction(boolean readOnly, int isolation) { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(readOnly); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel(isolation); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadGrpcServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadGrpcServiceTest.java new file mode 100644 index 0000000000..31dd458ef4 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadGrpcServiceTest.java @@ -0,0 +1,74 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedSpawnRequirementsRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedSpawnRequirementsResponse; +import org.junit.jupiter.api.Test; + +class WorldPublishedSpawnRequirementsReadGrpcServiceTest { + @Test + void mapsOwnerFailureToBoundedStatusWithoutReturningInternalDetails() { + var owner = mock(WorldPublishedSpawnRequirementsReadOwner.class); + when(owner.read(any())) + .thenThrow( + new WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException( + Status.Code.FAILED_PRECONDITION, "secret database row detail")); + var service = new WorldPublishedSpawnRequirementsReadGrpcService(owner); + var observer = new Collector(); + + service.readWorldPublishedSpawnRequirements( + ReadWorldPublishedSpawnRequirementsRequest.newBuilder().build(), observer); + + assertThat(observer.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(observer.description) + .isEqualTo("Published World source evidence is incomplete or inconsistent"); + assertThat(observer.description).doesNotContain("secret database row detail"); + assertThat(observer.value).isNull(); + assertThat(observer.completed).isFalse(); + } + + @Test + void unexpectedOwnerFailureReturnsRedactedInternalAndNeverMasksObserverDelivery() { + var owner = mock(WorldPublishedSpawnRequirementsReadOwner.class); + when(owner.read(any())).thenThrow(new IllegalStateException("private exception detail")); + var service = new WorldPublishedSpawnRequirementsReadGrpcService(owner); + var observer = new Collector(); + + service.readWorldPublishedSpawnRequirements( + ReadWorldPublishedSpawnRequirementsRequest.newBuilder().build(), observer); + + assertThat(observer.error).isEqualTo(Status.Code.INTERNAL); + assertThat(observer.description).isEqualTo("Published World source read failed"); + assertThat(observer.description).doesNotContain("private exception detail"); + } + + private static final class Collector + implements StreamObserver { + private ReadWorldPublishedSpawnRequirementsResponse value; + private Status.Code error; + private String description; + private boolean completed; + + @Override + public void onNext(ReadWorldPublishedSpawnRequirementsResponse next) { + value = next; + } + + @Override + public void onError(Throwable failure) { + error = Status.fromThrowable(failure).getCode(); + description = Status.fromThrowable(failure).getDescription(); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadOwnerTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadOwnerTest.java new file mode 100644 index 0000000000..9accb19a81 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadOwnerTest.java @@ -0,0 +1,476 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.RoomTemplateRef; +import net.firedevops.firemud.common.world.WorldPublishedSpawnRequirementsEvidence.EntityTemplateReference; +import net.firedevops.firemud.common.world.WorldPublishedSpawnRequirementsEvidence.FamilyCount; +import net.firedevops.firemud.common.world.WorldPublishedSpawnRequirementsEvidence.GenerationRequirement; +import net.firedevops.firemud.common.world.WorldPublishedSpawnRequirementsEvidence.SpawnRequirement; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalAuthoredGraph.Family; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalAuthoredGraph.Template; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceTopologyPlan.GenerationRuleIntent; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceTopologyPlan.SourceRow; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceTopologyPlan.SpawnBindingIntent; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyInputGraph.FreshGraphDeclaration; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyInputGraph.Node; +import net.firedevops.firemud.worldmanagement.v1.EntityTemplateReferenceType; +import net.firedevops.firemud.worldmanagement.v1.GenerationRuleDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedSpawnRequirementsRequest; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; +import net.firedevops.firemud.worldmanagement.v1.WorldEntitySpawnBindingDesignMutation; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class WorldPublishedSpawnRequirementsReadOwnerTest { + private static final String NAMESPACE = "test"; + private static final UUID READ_ID = uuid(1); + private static final UUID TENANT = uuid(2); + private static final UUID VERSION = uuid(3); + private final AuthoredWorldLaunchDescriptorClient gameDesign = + mock(AuthoredWorldLaunchDescriptorClient.class); + private final WorldPublishedStartLocationRepository published = + mock(WorldPublishedStartLocationRepository.class); + private final PlatformTransactionManager transactions = mock(PlatformTransactionManager.class); + + @AfterEach + void clearThreadState() { + TransactionSynchronizationManager.clear(); + SessionContext.clear(); + } + + @Test + void rejectsWrongPeerAndEndUserBeforeRequestDecodingOrOwnerAccess() { + var malformed = + ReadWorldPublishedSpawnRequirementsRequest.newBuilder().setSchemaVersion(-1).build(); + for (GrpcPeerIdentity identity : + List.of( + peer("game-design-service", NAMESPACE), peer("entity-management-service", "other"))) { + try (var ignored = attach(identity)) { + assertThatThrownBy(() -> owner().read(malformed)) + .isInstanceOf(WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException.class) + .satisfies( + failure -> + assertThat( + ((WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) + failure) + .code()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + } + } + SessionContext.setContext(TENANT.toString(), List.of(), java.util.Map.of()); + try (var ignored = attach(peer("entity-management-service", NAMESPACE))) { + assertThatThrownBy(() -> owner().read(malformed)) + .isInstanceOf(WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException.class) + .satisfies( + failure -> + assertThat( + ((WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) failure) + .code()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + } + verifyNoInteractions(gameDesign, published, transactions); + } + + @Test + void ambientTransactionIsRejectedBeforeDecodingOrGameDesignRead() { + TransactionSynchronizationManager.setActualTransactionActive(true); + try (var ignored = attach(peer("entity-management-service", NAMESPACE))) { + assertThatThrownBy( + () -> + owner() + .read( + ReadWorldPublishedSpawnRequirementsRequest.newBuilder() + .setSchemaVersion(-1) + .build())) + .isInstanceOf(WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException.class) + .satisfies( + failure -> + assertThat( + ((WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) failure) + .code()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + } + verifyNoInteractions(gameDesign, published, transactions); + } + + @Test + void requestNamespaceMustMatchConfiguredOwnerBeforeGameDesignRead() { + try (var ignored = attach(peer("entity-management-service", NAMESPACE))) { + assertThatThrownBy(() -> owner().read(wireRequest("other"))) + .isInstanceOf(WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException.class) + .satisfies( + failure -> + assertThat( + ((WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) failure) + .code()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + } + verifyNoInteractions(gameDesign, published, transactions); + } + + @Test + void unavailableGameDesignReadNeverOpensWorldSnapshot() { + var wire = wireRequest(NAMESPACE); + when(gameDesign.getComplete(any(GetLaunchDescriptorRequest.class))) + .thenThrow(Status.UNAVAILABLE.asRuntimeException()); + var owner = owner(); + try (var ignored = attach(peer("entity-management-service", NAMESPACE))) { + assertThatThrownBy(() -> owner.read(wire)) + .isInstanceOf(WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException.class) + .satisfies( + failure -> + assertThat( + ((WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) failure) + .code()) + .isEqualTo(Status.Code.UNAVAILABLE)); + } + verify(gameDesign).getComplete(any(GetLaunchDescriptorRequest.class)); + verifyNoInteractions(published, transactions); + } + + @Test + void changedReleaseAttestationDigestFailsBeforeWorldRead() { + var wire = wireRequest(NAMESPACE); + var pair = mock(CompleteLaunchBindingEvidence.class); + var descriptor = mock(AuthoredWorldLaunchDescriptorEvidence.class); + var release = mock(AuthoredWorldReleaseAttestationEvidence.class); + when(gameDesign.getComplete(any(GetLaunchDescriptorRequest.class))).thenReturn(pair); + when(pair.descriptor()).thenReturn(descriptor); + when(pair.releaseAttestation()).thenReturn(release); + when(descriptor.targetNamespace()).thenReturn(NAMESPACE); + when(release.targetNamespace()).thenReturn(NAMESPACE); + when(release.evidenceDigest()).thenReturn("sha256:" + "f".repeat(64)); + when(release.schemaVersion()) + .thenReturn(AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION); + when(release.worldStartLocationEvidence()) + .thenReturn(mock(WorldPublishedStartLocationEvidence.class)); + try (var ignored = attach(peer("entity-management-service", NAMESPACE))) { + assertThatThrownBy(() -> owner().read(wire)) + .isInstanceOf(WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException.class) + .satisfies( + failure -> + assertThat( + ((WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) failure) + .code()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + } + verifyNoInteractions(published, transactions); + } + + @Test + void malformedFrozenSourceFailsClosedAfterTheOwnedRead() { + var wire = wireRequest(NAMESPACE); + var selector = mock(WorldPublishedStartLocationEvidence.class); + when(selector.request()).thenReturn(selectorRequest()); + var pair = mock(CompleteLaunchBindingEvidence.class); + var descriptor = mock(AuthoredWorldLaunchDescriptorEvidence.class); + var release = mock(AuthoredWorldReleaseAttestationEvidence.class); + when(gameDesign.getComplete(any(GetLaunchDescriptorRequest.class))).thenReturn(pair); + when(pair.descriptor()).thenReturn(descriptor); + when(pair.releaseAttestation()).thenReturn(release); + when(descriptor.targetNamespace()).thenReturn(NAMESPACE); + when(release.targetNamespace()).thenReturn(NAMESPACE); + when(release.evidenceDigest()).thenReturn(wire.getExpectedReleaseAttestationDigest()); + when(release.schemaVersion()) + .thenReturn(AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION); + when(release.worldStartLocationEvidence()).thenReturn(selector); + + var source = mock(WorldPublishedStartLocationSource.class); + var frozen = mock(WorldCanonicalFrozenTopology.class); + when(source.frozenTopology()).thenReturn(frozen); + when(frozen.status()).thenReturn("CHANGED"); + when(published.readInOwnedSnapshot(any())).thenReturn(Optional.of(source)); + try (var ignored = attach(peer("entity-management-service", NAMESPACE))) { + assertThatThrownBy(() -> owner().read(wire)) + .isInstanceOf(WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException.class) + .satisfies( + failure -> + assertThat( + ((WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) failure) + .code()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + } + verify(published).readInOwnedSnapshot(any()); + } + + @Test + void projectsOriginalIntentFieldsAndExplicitFamilyCountsInRevisionOrder() { + UUID spawnRevision = uuid(20); + UUID generationRevision = uuid(21); + UUID secondSpawnRevision = uuid(22); + UUID spawnId = uuid(30); + UUID ruleId = uuid(31); + UUID secondSpawnId = uuid(32); + UUID roomId = uuid(40); + UUID entityId = uuid(41); + UUID secondRoomId = uuid(42); + UUID secondEntityId = uuid(43); + var spawnMutation = + base( + spawnRevision, + spawnId, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING, + WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE, + uuid(50)) + .setWorldEntitySpawnBinding( + WorldEntitySpawnBindingDesignMutation.newBuilder() + .setRoomId(roomId.toString()) + .setEntityTemplateType( + EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_NPC) + .setEntityTemplateId(entityId.toString()) + .setSpawnCount(0) + .setRespawnDelaySeconds(77)) + .build(); + var generationMutation = + base( + generationRevision, + ruleId, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE, + WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_ZONE_SUBTREE, + uuid(51)) + .setGenerationRule( + GenerationRuleDesignMutation.newBuilder() + .setName("authored-name") + .setValue("unchanged-value")) + .build(); + var secondSpawnMutation = + base( + secondSpawnRevision, + secondSpawnId, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING, + WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_ZONE_SUBTREE, + uuid(52)) + .setWorldEntitySpawnBinding( + WorldEntitySpawnBindingDesignMutation.newBuilder() + .setRoomId(secondRoomId.toString()) + .setEntityTemplateType( + EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_ITEM) + .setEntityTemplateId(secondEntityId.toString()) + .setSpawnCount(4) + .setRespawnDelaySeconds(9)) + .build(); + var entityRef = + new WorldDraftTopologyInputGraph.EntityTemplateReference( + EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_NPC, + TENANT, + VERSION, + entityId); + var spawn = + new SpawnBindingIntent( + source(Family.WORLD_ENTITY_SPAWN_BINDING, spawnId, spawnMutation), + new Template(Family.ROOM, roomId), + new WorldDraftTopologyInputGraph.EntityTemplateReference( + entityRef.kind(), + entityRef.tenantId(), + entityRef.versionId(), + entityRef.templateId()), + spawnMutation.getWorldEntitySpawnBinding()); + var generation = + new GenerationRuleIntent( + source(Family.GENERATION_RULE, ruleId, generationMutation), + new Template(Family.ZONE, uuid(51)), + generationMutation.getGenerationRule()); + var secondSpawn = + new SpawnBindingIntent( + source(Family.WORLD_ENTITY_SPAWN_BINDING, secondSpawnId, secondSpawnMutation), + new Template(Family.ROOM, secondRoomId), + new WorldDraftTopologyInputGraph.EntityTemplateReference( + EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_ITEM, + TENANT, + VERSION, + secondEntityId), + secondSpawnMutation.getWorldEntitySpawnBinding()); + var topology = mock(WorldCanonicalInstanceTopologyPlan.class); + when(topology.spawnBindings()).thenReturn(List.of(spawn, secondSpawn)); + when(topology.generationRules()).thenReturn(List.of(generation)); + when(topology.tenantId()).thenReturn(TENANT); + when(topology.versionId()).thenReturn(VERSION); + var declaration = + new FreshGraphDeclaration( + TENANT, + VERSION, + new RoomTemplateRef(TENANT, VERSION, roomId), + List.of( + new WorldDraftTopologyInputGraph.FamilyCount( + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION, 0), + new WorldDraftTopologyInputGraph.FamilyCount( + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE, 0), + new WorldDraftTopologyInputGraph.FamilyCount( + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM, 0), + new WorldDraftTopologyInputGraph.FamilyCount( + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT, 0), + new WorldDraftTopologyInputGraph.FamilyCount( + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE, 1), + new WorldDraftTopologyInputGraph.FamilyCount( + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING, + 2))); + var graph = + new WorldDraftTopologyInputGraph( + TENANT, + VERSION, + List.of( + new Node("0", spawnRevision, spawnId, uuid(50), spawnMutation, entityRef), + new Node("1", generationRevision, ruleId, uuid(51), generationMutation, null), + new Node( + "2", + secondSpawnRevision, + secondSpawnId, + uuid(52), + secondSpawnMutation, + new WorldDraftTopologyInputGraph.EntityTemplateReference( + EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_ITEM, + TENANT, + VERSION, + secondEntityId))), + declaration); + + var projection = WorldPublishedSpawnRequirementsReadOwner.projectRequirements(graph, topology); + + assertThat(projection.familyCounts()) + .extracting(FamilyCount::count) + .containsExactly(0, 0, 0, 0, 1, 2); + assertThat(projection.spawnRequirements()) + .containsExactly( + new SpawnRequirement( + "0", + spawnRevision, + spawnId, + new RoomTemplateRef(TENANT, VERSION, roomId), + new EntityTemplateReference( + EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_NPC, + TENANT, + VERSION, + entityId), + 0, + 77), + new SpawnRequirement( + "2", + secondSpawnRevision, + secondSpawnId, + new RoomTemplateRef(TENANT, VERSION, secondRoomId), + new EntityTemplateReference( + EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_ITEM, + TENANT, + VERSION, + secondEntityId), + 4, + 9)); + assertThat(projection.generationRequirements()) + .containsExactly( + new GenerationRequirement( + "1", + generationRevision, + ruleId, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE, + uuid(51), + "authored-name", + "unchanged-value")); + } + + private WorldPublishedSpawnRequirementsReadOwner owner() { + return new WorldPublishedSpawnRequirementsReadOwner( + NAMESPACE, gameDesign, published, transactions); + } + + private static ReadWorldPublishedSpawnRequirementsRequest wireRequest(String namespace) { + var binding = + GetLaunchDescriptorRequest.newBuilder() + .setRequestId(READ_ID.toString()) + .setCanonicalTenantId(TENANT.toString()) + .setWorldSlug("world") + .setControlPlaneRequestId("control-plane-request") + .setExpectedRequestDigest("sha256:" + "a".repeat(64)) + .setExpectedResultDigest("sha256:" + "b".repeat(64)) + .build(); + return ReadWorldPublishedSpawnRequirementsRequest.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(namespace) + .setReadRequestId(READ_ID.toString()) + .setLaunchBindingRequest(binding) + .setExpectedReleaseAttestationDigest("sha256:" + "c".repeat(64)) + .build(); + } + + private static WorldPublishedStartLocationEvidence.Request selectorRequest() { + return new WorldPublishedStartLocationEvidence.Request( + NAMESPACE, + TENANT, + VERSION, + uuid(4), + uuid(5), + "publication", + "d".repeat(64), + 6, + "workflow", + uuid(6).toString(), + "e".repeat(64), + 3, + List.of()); + } + + private static WorldDesignMutationRevision.Builder base( + UUID revision, + UUID aggregateId, + WorldDesignAggregateType aggregate, + WorldDesignScopeType scopeType, + UUID scopeId) { + return WorldDesignMutationRevision.newBuilder() + .setLogicalRevisionId(revision.toString()) + .setCommitId(uuid(7).toString()) + .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) + .setAggregateType(aggregate) + .setAggregateId(aggregateId.toString()) + .setScopeType(scopeType) + .setScopeId(scopeId.toString()); + } + + private static SourceRow source(Family family, UUID id, WorldDesignMutationRevision revision) { + return new SourceRow(new Template(family, id), revision, revision, "original-payload"); + } + + private static UUID uuid(int value) { + return UUID.fromString("00000000-0000-4000-8000-%012d".formatted(value)); + } + + private static GrpcPeerIdentity peer(String service, String namespace) { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + } + + private static ContextScope attach(GrpcPeerIdentity peer) { + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + return new ContextScope(context.attach()); + } + + private record ContextScope(Context previous) implements AutoCloseable { + @Override + public void close() { + Context.current().detach(previous); + } + } +} From f7a31ab5b6bc5ca35a824f256591bdbf67292b70 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 8 Oct 2026 17:56:22 +1300 Subject: [PATCH 8/8] Preserve World proof time through post-job cleanup Consume only the World timeout allowance from reviewed #3099 (d780aa061), preserving the existing Account and Game Session 30-minute allowances. --- .github/workflows/ci.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c3af25ef2b..2864918280 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -909,7 +909,8 @@ jobs: # Game Session and Account run composed owner proofs before full checks and runtime JARs. # CI37121026340 exhausted 20m at Game Session packaging; CI37425364000 # reached Account PostgreSQL cases but exhausted 20m before raw XML finalized. - timeout-minutes: ${{ (matrix.module == 'game-session-service' || matrix.module == 'account-service') && 30 || 20 }} + # World PostgreSQL proof can also reach 20 minutes before Gradle post-job cleanup (#3099). + timeout-minutes: ${{ (matrix.module == 'game-session-service' || matrix.module == 'account-service' || matrix.module == 'world-management-service') && 30 || 20 }} strategy: fail-fast: false matrix: